gc: fix a memory leak
[git/debian.git] / midx.c
blob5f0dd386b0266b6549c85499ab50e964ed868f1d
1 #include "cache.h"
2 #include "config.h"
3 #include "csum-file.h"
4 #include "dir.h"
5 #include "lockfile.h"
6 #include "packfile.h"
7 #include "object-store.h"
8 #include "hash-lookup.h"
9 #include "midx.h"
10 #include "progress.h"
11 #include "trace2.h"
12 #include "run-command.h"
13 #include "repository.h"
14 #include "chunk-format.h"
15 #include "pack.h"
16 #include "pack-bitmap.h"
17 #include "refs.h"
18 #include "revision.h"
19 #include "list-objects.h"
21 #define MIDX_SIGNATURE 0x4d494458 /* "MIDX" */
22 #define MIDX_VERSION 1
23 #define MIDX_BYTE_FILE_VERSION 4
24 #define MIDX_BYTE_HASH_VERSION 5
25 #define MIDX_BYTE_NUM_CHUNKS 6
26 #define MIDX_BYTE_NUM_PACKS 8
27 #define MIDX_HEADER_SIZE 12
28 #define MIDX_MIN_SIZE (MIDX_HEADER_SIZE + the_hash_algo->rawsz)
30 #define MIDX_CHUNK_ALIGNMENT 4
31 #define MIDX_CHUNKID_PACKNAMES 0x504e414d /* "PNAM" */
32 #define MIDX_CHUNKID_OIDFANOUT 0x4f494446 /* "OIDF" */
33 #define MIDX_CHUNKID_OIDLOOKUP 0x4f49444c /* "OIDL" */
34 #define MIDX_CHUNKID_OBJECTOFFSETS 0x4f4f4646 /* "OOFF" */
35 #define MIDX_CHUNKID_LARGEOFFSETS 0x4c4f4646 /* "LOFF" */
36 #define MIDX_CHUNKID_REVINDEX 0x52494458 /* "RIDX" */
37 #define MIDX_CHUNK_FANOUT_SIZE (sizeof(uint32_t) * 256)
38 #define MIDX_CHUNK_OFFSET_WIDTH (2 * sizeof(uint32_t))
39 #define MIDX_CHUNK_LARGE_OFFSET_WIDTH (sizeof(uint64_t))
40 #define MIDX_LARGE_OFFSET_NEEDED 0x80000000
42 #define PACK_EXPIRED UINT_MAX
44 const unsigned char *get_midx_checksum(struct multi_pack_index *m)
46 return m->data + m->data_len - the_hash_algo->rawsz;
49 void get_midx_filename(struct strbuf *out, const char *object_dir)
51 strbuf_addf(out, "%s/pack/multi-pack-index", object_dir);
54 void get_midx_rev_filename(struct strbuf *out, struct multi_pack_index *m)
56 get_midx_filename(out, m->object_dir);
57 strbuf_addf(out, "-%s.rev", hash_to_hex(get_midx_checksum(m)));
60 static int midx_read_oid_fanout(const unsigned char *chunk_start,
61 size_t chunk_size, void *data)
63 struct multi_pack_index *m = data;
64 m->chunk_oid_fanout = (uint32_t *)chunk_start;
66 if (chunk_size != 4 * 256) {
67 error(_("multi-pack-index OID fanout is of the wrong size"));
68 return 1;
70 return 0;
73 struct multi_pack_index *load_multi_pack_index(const char *object_dir, int local)
75 struct multi_pack_index *m = NULL;
76 int fd;
77 struct stat st;
78 size_t midx_size;
79 void *midx_map = NULL;
80 uint32_t hash_version;
81 struct strbuf midx_name = STRBUF_INIT;
82 uint32_t i;
83 const char *cur_pack_name;
84 struct chunkfile *cf = NULL;
86 get_midx_filename(&midx_name, object_dir);
88 fd = git_open(midx_name.buf);
90 if (fd < 0)
91 goto cleanup_fail;
92 if (fstat(fd, &st)) {
93 error_errno(_("failed to read %s"), midx_name.buf);
94 goto cleanup_fail;
97 midx_size = xsize_t(st.st_size);
99 if (midx_size < MIDX_MIN_SIZE) {
100 error(_("multi-pack-index file %s is too small"), midx_name.buf);
101 goto cleanup_fail;
104 strbuf_release(&midx_name);
106 midx_map = xmmap(NULL, midx_size, PROT_READ, MAP_PRIVATE, fd, 0);
107 close(fd);
109 FLEX_ALLOC_STR(m, object_dir, object_dir);
110 m->data = midx_map;
111 m->data_len = midx_size;
112 m->local = local;
114 m->signature = get_be32(m->data);
115 if (m->signature != MIDX_SIGNATURE)
116 die(_("multi-pack-index signature 0x%08x does not match signature 0x%08x"),
117 m->signature, MIDX_SIGNATURE);
119 m->version = m->data[MIDX_BYTE_FILE_VERSION];
120 if (m->version != MIDX_VERSION)
121 die(_("multi-pack-index version %d not recognized"),
122 m->version);
124 hash_version = m->data[MIDX_BYTE_HASH_VERSION];
125 if (hash_version != oid_version(the_hash_algo)) {
126 error(_("multi-pack-index hash version %u does not match version %u"),
127 hash_version, oid_version(the_hash_algo));
128 goto cleanup_fail;
130 m->hash_len = the_hash_algo->rawsz;
132 m->num_chunks = m->data[MIDX_BYTE_NUM_CHUNKS];
134 m->num_packs = get_be32(m->data + MIDX_BYTE_NUM_PACKS);
136 cf = init_chunkfile(NULL);
138 if (read_table_of_contents(cf, m->data, midx_size,
139 MIDX_HEADER_SIZE, m->num_chunks))
140 goto cleanup_fail;
142 if (pair_chunk(cf, MIDX_CHUNKID_PACKNAMES, &m->chunk_pack_names) == CHUNK_NOT_FOUND)
143 die(_("multi-pack-index missing required pack-name chunk"));
144 if (read_chunk(cf, MIDX_CHUNKID_OIDFANOUT, midx_read_oid_fanout, m) == CHUNK_NOT_FOUND)
145 die(_("multi-pack-index missing required OID fanout chunk"));
146 if (pair_chunk(cf, MIDX_CHUNKID_OIDLOOKUP, &m->chunk_oid_lookup) == CHUNK_NOT_FOUND)
147 die(_("multi-pack-index missing required OID lookup chunk"));
148 if (pair_chunk(cf, MIDX_CHUNKID_OBJECTOFFSETS, &m->chunk_object_offsets) == CHUNK_NOT_FOUND)
149 die(_("multi-pack-index missing required object offsets chunk"));
151 pair_chunk(cf, MIDX_CHUNKID_LARGEOFFSETS, &m->chunk_large_offsets);
153 if (git_env_bool("GIT_TEST_MIDX_READ_RIDX", 1))
154 pair_chunk(cf, MIDX_CHUNKID_REVINDEX, &m->chunk_revindex);
156 m->num_objects = ntohl(m->chunk_oid_fanout[255]);
158 CALLOC_ARRAY(m->pack_names, m->num_packs);
159 CALLOC_ARRAY(m->packs, m->num_packs);
161 cur_pack_name = (const char *)m->chunk_pack_names;
162 for (i = 0; i < m->num_packs; i++) {
163 m->pack_names[i] = cur_pack_name;
165 cur_pack_name += strlen(cur_pack_name) + 1;
167 if (i && strcmp(m->pack_names[i], m->pack_names[i - 1]) <= 0)
168 die(_("multi-pack-index pack names out of order: '%s' before '%s'"),
169 m->pack_names[i - 1],
170 m->pack_names[i]);
173 trace2_data_intmax("midx", the_repository, "load/num_packs", m->num_packs);
174 trace2_data_intmax("midx", the_repository, "load/num_objects", m->num_objects);
176 free_chunkfile(cf);
177 return m;
179 cleanup_fail:
180 free(m);
181 strbuf_release(&midx_name);
182 free_chunkfile(cf);
183 if (midx_map)
184 munmap(midx_map, midx_size);
185 if (0 <= fd)
186 close(fd);
187 return NULL;
190 void close_midx(struct multi_pack_index *m)
192 uint32_t i;
194 if (!m)
195 return;
197 close_midx(m->next);
199 munmap((unsigned char *)m->data, m->data_len);
201 for (i = 0; i < m->num_packs; i++) {
202 if (m->packs[i])
203 m->packs[i]->multi_pack_index = 0;
205 FREE_AND_NULL(m->packs);
206 FREE_AND_NULL(m->pack_names);
207 free(m);
210 int prepare_midx_pack(struct repository *r, struct multi_pack_index *m, uint32_t pack_int_id)
212 struct strbuf pack_name = STRBUF_INIT;
213 struct packed_git *p;
215 if (pack_int_id >= m->num_packs)
216 die(_("bad pack-int-id: %u (%u total packs)"),
217 pack_int_id, m->num_packs);
219 if (m->packs[pack_int_id])
220 return 0;
222 strbuf_addf(&pack_name, "%s/pack/%s", m->object_dir,
223 m->pack_names[pack_int_id]);
225 p = add_packed_git(pack_name.buf, pack_name.len, m->local);
226 strbuf_release(&pack_name);
228 if (!p)
229 return 1;
231 p->multi_pack_index = 1;
232 m->packs[pack_int_id] = p;
233 install_packed_git(r, p);
234 list_add_tail(&p->mru, &r->objects->packed_git_mru);
236 return 0;
239 int bsearch_midx(const struct object_id *oid, struct multi_pack_index *m, uint32_t *result)
241 return bsearch_hash(oid->hash, m->chunk_oid_fanout, m->chunk_oid_lookup,
242 the_hash_algo->rawsz, result);
245 struct object_id *nth_midxed_object_oid(struct object_id *oid,
246 struct multi_pack_index *m,
247 uint32_t n)
249 if (n >= m->num_objects)
250 return NULL;
252 oidread(oid, m->chunk_oid_lookup + m->hash_len * n);
253 return oid;
256 off_t nth_midxed_offset(struct multi_pack_index *m, uint32_t pos)
258 const unsigned char *offset_data;
259 uint32_t offset32;
261 offset_data = m->chunk_object_offsets + (off_t)pos * MIDX_CHUNK_OFFSET_WIDTH;
262 offset32 = get_be32(offset_data + sizeof(uint32_t));
264 if (m->chunk_large_offsets && offset32 & MIDX_LARGE_OFFSET_NEEDED) {
265 if (sizeof(off_t) < sizeof(uint64_t))
266 die(_("multi-pack-index stores a 64-bit offset, but off_t is too small"));
268 offset32 ^= MIDX_LARGE_OFFSET_NEEDED;
269 return get_be64(m->chunk_large_offsets + sizeof(uint64_t) * offset32);
272 return offset32;
275 uint32_t nth_midxed_pack_int_id(struct multi_pack_index *m, uint32_t pos)
277 return get_be32(m->chunk_object_offsets +
278 (off_t)pos * MIDX_CHUNK_OFFSET_WIDTH);
281 int fill_midx_entry(struct repository * r,
282 const struct object_id *oid,
283 struct pack_entry *e,
284 struct multi_pack_index *m)
286 uint32_t pos;
287 uint32_t pack_int_id;
288 struct packed_git *p;
290 if (!bsearch_midx(oid, m, &pos))
291 return 0;
293 if (pos >= m->num_objects)
294 return 0;
296 pack_int_id = nth_midxed_pack_int_id(m, pos);
298 if (prepare_midx_pack(r, m, pack_int_id))
299 return 0;
300 p = m->packs[pack_int_id];
303 * We are about to tell the caller where they can locate the
304 * requested object. We better make sure the packfile is
305 * still here and can be accessed before supplying that
306 * answer, as it may have been deleted since the MIDX was
307 * loaded!
309 if (!is_pack_valid(p))
310 return 0;
312 if (oidset_size(&p->bad_objects) &&
313 oidset_contains(&p->bad_objects, oid))
314 return 0;
316 e->offset = nth_midxed_offset(m, pos);
317 e->p = p;
319 return 1;
322 /* Match "foo.idx" against either "foo.pack" _or_ "foo.idx". */
323 static int cmp_idx_or_pack_name(const char *idx_or_pack_name,
324 const char *idx_name)
326 /* Skip past any initial matching prefix. */
327 while (*idx_name && *idx_name == *idx_or_pack_name) {
328 idx_name++;
329 idx_or_pack_name++;
333 * If we didn't match completely, we may have matched "pack-1234." and
334 * be left with "idx" and "pack" respectively, which is also OK. We do
335 * not have to check for "idx" and "idx", because that would have been
336 * a complete match (and in that case these strcmps will be false, but
337 * we'll correctly return 0 from the final strcmp() below.
339 * Technically this matches "fooidx" and "foopack", but we'd never have
340 * such names in the first place.
342 if (!strcmp(idx_name, "idx") && !strcmp(idx_or_pack_name, "pack"))
343 return 0;
346 * This not only checks for a complete match, but also orders based on
347 * the first non-identical character, which means our ordering will
348 * match a raw strcmp(). That makes it OK to use this to binary search
349 * a naively-sorted list.
351 return strcmp(idx_or_pack_name, idx_name);
354 int midx_contains_pack(struct multi_pack_index *m, const char *idx_or_pack_name)
356 uint32_t first = 0, last = m->num_packs;
358 while (first < last) {
359 uint32_t mid = first + (last - first) / 2;
360 const char *current;
361 int cmp;
363 current = m->pack_names[mid];
364 cmp = cmp_idx_or_pack_name(idx_or_pack_name, current);
365 if (!cmp)
366 return 1;
367 if (cmp > 0) {
368 first = mid + 1;
369 continue;
371 last = mid;
374 return 0;
377 int prepare_multi_pack_index_one(struct repository *r, const char *object_dir, int local)
379 struct multi_pack_index *m;
380 struct multi_pack_index *m_search;
382 prepare_repo_settings(r);
383 if (!r->settings.core_multi_pack_index)
384 return 0;
386 for (m_search = r->objects->multi_pack_index; m_search; m_search = m_search->next)
387 if (!strcmp(object_dir, m_search->object_dir))
388 return 1;
390 m = load_multi_pack_index(object_dir, local);
392 if (m) {
393 struct multi_pack_index *mp = r->objects->multi_pack_index;
394 if (mp) {
395 m->next = mp->next;
396 mp->next = m;
397 } else
398 r->objects->multi_pack_index = m;
399 return 1;
402 return 0;
405 static size_t write_midx_header(struct hashfile *f,
406 unsigned char num_chunks,
407 uint32_t num_packs)
409 hashwrite_be32(f, MIDX_SIGNATURE);
410 hashwrite_u8(f, MIDX_VERSION);
411 hashwrite_u8(f, oid_version(the_hash_algo));
412 hashwrite_u8(f, num_chunks);
413 hashwrite_u8(f, 0); /* unused */
414 hashwrite_be32(f, num_packs);
416 return MIDX_HEADER_SIZE;
419 struct pack_info {
420 uint32_t orig_pack_int_id;
421 char *pack_name;
422 struct packed_git *p;
423 unsigned expired : 1;
426 static int pack_info_compare(const void *_a, const void *_b)
428 struct pack_info *a = (struct pack_info *)_a;
429 struct pack_info *b = (struct pack_info *)_b;
430 return strcmp(a->pack_name, b->pack_name);
433 static int idx_or_pack_name_cmp(const void *_va, const void *_vb)
435 const char *pack_name = _va;
436 const struct pack_info *compar = _vb;
438 return cmp_idx_or_pack_name(pack_name, compar->pack_name);
441 struct write_midx_context {
442 struct pack_info *info;
443 uint32_t nr;
444 uint32_t alloc;
445 struct multi_pack_index *m;
446 struct progress *progress;
447 unsigned pack_paths_checked;
449 struct pack_midx_entry *entries;
450 uint32_t entries_nr;
452 uint32_t *pack_perm;
453 uint32_t *pack_order;
454 unsigned large_offsets_needed:1;
455 uint32_t num_large_offsets;
457 int preferred_pack_idx;
459 struct string_list *to_include;
462 static void add_pack_to_midx(const char *full_path, size_t full_path_len,
463 const char *file_name, void *data)
465 struct write_midx_context *ctx = data;
467 if (ends_with(file_name, ".idx")) {
468 display_progress(ctx->progress, ++ctx->pack_paths_checked);
470 * Note that at most one of ctx->m and ctx->to_include are set,
471 * so we are testing midx_contains_pack() and
472 * string_list_has_string() independently (guarded by the
473 * appropriate NULL checks).
475 * We could support passing to_include while reusing an existing
476 * MIDX, but don't currently since the reuse process drags
477 * forward all packs from an existing MIDX (without checking
478 * whether or not they appear in the to_include list).
480 * If we added support for that, these next two conditional
481 * should be performed independently (likely checking
482 * to_include before the existing MIDX).
484 if (ctx->m && midx_contains_pack(ctx->m, file_name))
485 return;
486 else if (ctx->to_include &&
487 !string_list_has_string(ctx->to_include, file_name))
488 return;
490 ALLOC_GROW(ctx->info, ctx->nr + 1, ctx->alloc);
492 ctx->info[ctx->nr].p = add_packed_git(full_path,
493 full_path_len,
496 if (!ctx->info[ctx->nr].p) {
497 warning(_("failed to add packfile '%s'"),
498 full_path);
499 return;
502 if (open_pack_index(ctx->info[ctx->nr].p)) {
503 warning(_("failed to open pack-index '%s'"),
504 full_path);
505 close_pack(ctx->info[ctx->nr].p);
506 FREE_AND_NULL(ctx->info[ctx->nr].p);
507 return;
510 ctx->info[ctx->nr].pack_name = xstrdup(file_name);
511 ctx->info[ctx->nr].orig_pack_int_id = ctx->nr;
512 ctx->info[ctx->nr].expired = 0;
513 ctx->nr++;
517 struct pack_midx_entry {
518 struct object_id oid;
519 uint32_t pack_int_id;
520 time_t pack_mtime;
521 uint64_t offset;
522 unsigned preferred : 1;
525 static int midx_oid_compare(const void *_a, const void *_b)
527 const struct pack_midx_entry *a = (const struct pack_midx_entry *)_a;
528 const struct pack_midx_entry *b = (const struct pack_midx_entry *)_b;
529 int cmp = oidcmp(&a->oid, &b->oid);
531 if (cmp)
532 return cmp;
534 /* Sort objects in a preferred pack first when multiple copies exist. */
535 if (a->preferred > b->preferred)
536 return -1;
537 if (a->preferred < b->preferred)
538 return 1;
540 if (a->pack_mtime > b->pack_mtime)
541 return -1;
542 else if (a->pack_mtime < b->pack_mtime)
543 return 1;
545 return a->pack_int_id - b->pack_int_id;
548 static int nth_midxed_pack_midx_entry(struct multi_pack_index *m,
549 struct pack_midx_entry *e,
550 uint32_t pos)
552 if (pos >= m->num_objects)
553 return 1;
555 nth_midxed_object_oid(&e->oid, m, pos);
556 e->pack_int_id = nth_midxed_pack_int_id(m, pos);
557 e->offset = nth_midxed_offset(m, pos);
559 /* consider objects in midx to be from "old" packs */
560 e->pack_mtime = 0;
561 return 0;
564 static void fill_pack_entry(uint32_t pack_int_id,
565 struct packed_git *p,
566 uint32_t cur_object,
567 struct pack_midx_entry *entry,
568 int preferred)
570 if (nth_packed_object_id(&entry->oid, p, cur_object) < 0)
571 die(_("failed to locate object %d in packfile"), cur_object);
573 entry->pack_int_id = pack_int_id;
574 entry->pack_mtime = p->mtime;
576 entry->offset = nth_packed_object_offset(p, cur_object);
577 entry->preferred = !!preferred;
581 * It is possible to artificially get into a state where there are many
582 * duplicate copies of objects. That can create high memory pressure if
583 * we are to create a list of all objects before de-duplication. To reduce
584 * this memory pressure without a significant performance drop, automatically
585 * group objects by the first byte of their object id. Use the IDX fanout
586 * tables to group the data, copy to a local array, then sort.
588 * Copy only the de-duplicated entries (selected by most-recent modified time
589 * of a packfile containing the object).
591 static struct pack_midx_entry *get_sorted_entries(struct multi_pack_index *m,
592 struct pack_info *info,
593 uint32_t nr_packs,
594 uint32_t *nr_objects,
595 int preferred_pack)
597 uint32_t cur_fanout, cur_pack, cur_object;
598 uint32_t alloc_fanout, alloc_objects, total_objects = 0;
599 struct pack_midx_entry *entries_by_fanout = NULL;
600 struct pack_midx_entry *deduplicated_entries = NULL;
601 uint32_t start_pack = m ? m->num_packs : 0;
603 for (cur_pack = start_pack; cur_pack < nr_packs; cur_pack++)
604 total_objects += info[cur_pack].p->num_objects;
607 * As we de-duplicate by fanout value, we expect the fanout
608 * slices to be evenly distributed, with some noise. Hence,
609 * allocate slightly more than one 256th.
611 alloc_objects = alloc_fanout = total_objects > 3200 ? total_objects / 200 : 16;
613 ALLOC_ARRAY(entries_by_fanout, alloc_fanout);
614 ALLOC_ARRAY(deduplicated_entries, alloc_objects);
615 *nr_objects = 0;
617 for (cur_fanout = 0; cur_fanout < 256; cur_fanout++) {
618 uint32_t nr_fanout = 0;
620 if (m) {
621 uint32_t start = 0, end;
623 if (cur_fanout)
624 start = ntohl(m->chunk_oid_fanout[cur_fanout - 1]);
625 end = ntohl(m->chunk_oid_fanout[cur_fanout]);
627 for (cur_object = start; cur_object < end; cur_object++) {
628 ALLOC_GROW(entries_by_fanout, nr_fanout + 1, alloc_fanout);
629 nth_midxed_pack_midx_entry(m,
630 &entries_by_fanout[nr_fanout],
631 cur_object);
632 if (nth_midxed_pack_int_id(m, cur_object) == preferred_pack)
633 entries_by_fanout[nr_fanout].preferred = 1;
634 else
635 entries_by_fanout[nr_fanout].preferred = 0;
636 nr_fanout++;
640 for (cur_pack = start_pack; cur_pack < nr_packs; cur_pack++) {
641 uint32_t start = 0, end;
642 int preferred = cur_pack == preferred_pack;
644 if (cur_fanout)
645 start = get_pack_fanout(info[cur_pack].p, cur_fanout - 1);
646 end = get_pack_fanout(info[cur_pack].p, cur_fanout);
648 for (cur_object = start; cur_object < end; cur_object++) {
649 ALLOC_GROW(entries_by_fanout, nr_fanout + 1, alloc_fanout);
650 fill_pack_entry(cur_pack,
651 info[cur_pack].p,
652 cur_object,
653 &entries_by_fanout[nr_fanout],
654 preferred);
655 nr_fanout++;
659 QSORT(entries_by_fanout, nr_fanout, midx_oid_compare);
662 * The batch is now sorted by OID and then mtime (descending).
663 * Take only the first duplicate.
665 for (cur_object = 0; cur_object < nr_fanout; cur_object++) {
666 if (cur_object && oideq(&entries_by_fanout[cur_object - 1].oid,
667 &entries_by_fanout[cur_object].oid))
668 continue;
670 ALLOC_GROW(deduplicated_entries, *nr_objects + 1, alloc_objects);
671 memcpy(&deduplicated_entries[*nr_objects],
672 &entries_by_fanout[cur_object],
673 sizeof(struct pack_midx_entry));
674 (*nr_objects)++;
678 free(entries_by_fanout);
679 return deduplicated_entries;
682 static int write_midx_pack_names(struct hashfile *f, void *data)
684 struct write_midx_context *ctx = data;
685 uint32_t i;
686 unsigned char padding[MIDX_CHUNK_ALIGNMENT];
687 size_t written = 0;
689 for (i = 0; i < ctx->nr; i++) {
690 size_t writelen;
692 if (ctx->info[i].expired)
693 continue;
695 if (i && strcmp(ctx->info[i].pack_name, ctx->info[i - 1].pack_name) <= 0)
696 BUG("incorrect pack-file order: %s before %s",
697 ctx->info[i - 1].pack_name,
698 ctx->info[i].pack_name);
700 writelen = strlen(ctx->info[i].pack_name) + 1;
701 hashwrite(f, ctx->info[i].pack_name, writelen);
702 written += writelen;
705 /* add padding to be aligned */
706 i = MIDX_CHUNK_ALIGNMENT - (written % MIDX_CHUNK_ALIGNMENT);
707 if (i < MIDX_CHUNK_ALIGNMENT) {
708 memset(padding, 0, sizeof(padding));
709 hashwrite(f, padding, i);
712 return 0;
715 static int write_midx_oid_fanout(struct hashfile *f,
716 void *data)
718 struct write_midx_context *ctx = data;
719 struct pack_midx_entry *list = ctx->entries;
720 struct pack_midx_entry *last = ctx->entries + ctx->entries_nr;
721 uint32_t count = 0;
722 uint32_t i;
725 * Write the first-level table (the list is sorted,
726 * but we use a 256-entry lookup to be able to avoid
727 * having to do eight extra binary search iterations).
729 for (i = 0; i < 256; i++) {
730 struct pack_midx_entry *next = list;
732 while (next < last && next->oid.hash[0] == i) {
733 count++;
734 next++;
737 hashwrite_be32(f, count);
738 list = next;
741 return 0;
744 static int write_midx_oid_lookup(struct hashfile *f,
745 void *data)
747 struct write_midx_context *ctx = data;
748 unsigned char hash_len = the_hash_algo->rawsz;
749 struct pack_midx_entry *list = ctx->entries;
750 uint32_t i;
752 for (i = 0; i < ctx->entries_nr; i++) {
753 struct pack_midx_entry *obj = list++;
755 if (i < ctx->entries_nr - 1) {
756 struct pack_midx_entry *next = list;
757 if (oidcmp(&obj->oid, &next->oid) >= 0)
758 BUG("OIDs not in order: %s >= %s",
759 oid_to_hex(&obj->oid),
760 oid_to_hex(&next->oid));
763 hashwrite(f, obj->oid.hash, (int)hash_len);
766 return 0;
769 static int write_midx_object_offsets(struct hashfile *f,
770 void *data)
772 struct write_midx_context *ctx = data;
773 struct pack_midx_entry *list = ctx->entries;
774 uint32_t i, nr_large_offset = 0;
776 for (i = 0; i < ctx->entries_nr; i++) {
777 struct pack_midx_entry *obj = list++;
779 if (ctx->pack_perm[obj->pack_int_id] == PACK_EXPIRED)
780 BUG("object %s is in an expired pack with int-id %d",
781 oid_to_hex(&obj->oid),
782 obj->pack_int_id);
784 hashwrite_be32(f, ctx->pack_perm[obj->pack_int_id]);
786 if (ctx->large_offsets_needed && obj->offset >> 31)
787 hashwrite_be32(f, MIDX_LARGE_OFFSET_NEEDED | nr_large_offset++);
788 else if (!ctx->large_offsets_needed && obj->offset >> 32)
789 BUG("object %s requires a large offset (%"PRIx64") but the MIDX is not writing large offsets!",
790 oid_to_hex(&obj->oid),
791 obj->offset);
792 else
793 hashwrite_be32(f, (uint32_t)obj->offset);
796 return 0;
799 static int write_midx_large_offsets(struct hashfile *f,
800 void *data)
802 struct write_midx_context *ctx = data;
803 struct pack_midx_entry *list = ctx->entries;
804 struct pack_midx_entry *end = ctx->entries + ctx->entries_nr;
805 uint32_t nr_large_offset = ctx->num_large_offsets;
807 while (nr_large_offset) {
808 struct pack_midx_entry *obj;
809 uint64_t offset;
811 if (list >= end)
812 BUG("too many large-offset objects");
814 obj = list++;
815 offset = obj->offset;
817 if (!(offset >> 31))
818 continue;
820 hashwrite_be64(f, offset);
822 nr_large_offset--;
825 return 0;
828 static int write_midx_revindex(struct hashfile *f,
829 void *data)
831 struct write_midx_context *ctx = data;
832 uint32_t i;
834 for (i = 0; i < ctx->entries_nr; i++)
835 hashwrite_be32(f, ctx->pack_order[i]);
837 return 0;
840 struct midx_pack_order_data {
841 uint32_t nr;
842 uint32_t pack;
843 off_t offset;
846 static int midx_pack_order_cmp(const void *va, const void *vb)
848 const struct midx_pack_order_data *a = va, *b = vb;
849 if (a->pack < b->pack)
850 return -1;
851 else if (a->pack > b->pack)
852 return 1;
853 else if (a->offset < b->offset)
854 return -1;
855 else if (a->offset > b->offset)
856 return 1;
857 else
858 return 0;
861 static uint32_t *midx_pack_order(struct write_midx_context *ctx)
863 struct midx_pack_order_data *data;
864 uint32_t *pack_order;
865 uint32_t i;
867 ALLOC_ARRAY(data, ctx->entries_nr);
868 for (i = 0; i < ctx->entries_nr; i++) {
869 struct pack_midx_entry *e = &ctx->entries[i];
870 data[i].nr = i;
871 data[i].pack = ctx->pack_perm[e->pack_int_id];
872 if (!e->preferred)
873 data[i].pack |= (1U << 31);
874 data[i].offset = e->offset;
877 QSORT(data, ctx->entries_nr, midx_pack_order_cmp);
879 ALLOC_ARRAY(pack_order, ctx->entries_nr);
880 for (i = 0; i < ctx->entries_nr; i++)
881 pack_order[i] = data[i].nr;
882 free(data);
884 return pack_order;
887 static void write_midx_reverse_index(char *midx_name, unsigned char *midx_hash,
888 struct write_midx_context *ctx)
890 struct strbuf buf = STRBUF_INIT;
891 const char *tmp_file;
893 strbuf_addf(&buf, "%s-%s.rev", midx_name, hash_to_hex(midx_hash));
895 tmp_file = write_rev_file_order(NULL, ctx->pack_order, ctx->entries_nr,
896 midx_hash, WRITE_REV);
898 if (finalize_object_file(tmp_file, buf.buf))
899 die(_("cannot store reverse index file"));
901 strbuf_release(&buf);
904 static void clear_midx_files_ext(const char *object_dir, const char *ext,
905 unsigned char *keep_hash);
907 static int midx_checksum_valid(struct multi_pack_index *m)
909 return hashfile_checksum_valid(m->data, m->data_len);
912 static void prepare_midx_packing_data(struct packing_data *pdata,
913 struct write_midx_context *ctx)
915 uint32_t i;
917 memset(pdata, 0, sizeof(struct packing_data));
918 prepare_packing_data(the_repository, pdata);
920 for (i = 0; i < ctx->entries_nr; i++) {
921 struct pack_midx_entry *from = &ctx->entries[ctx->pack_order[i]];
922 struct object_entry *to = packlist_alloc(pdata, &from->oid);
924 oe_set_in_pack(pdata, to,
925 ctx->info[ctx->pack_perm[from->pack_int_id]].p);
929 static int add_ref_to_pending(const char *refname,
930 const struct object_id *oid,
931 int flag, void *cb_data)
933 struct rev_info *revs = (struct rev_info*)cb_data;
934 struct object *object;
936 if ((flag & REF_ISSYMREF) && (flag & REF_ISBROKEN)) {
937 warning("symbolic ref is dangling: %s", refname);
938 return 0;
941 object = parse_object_or_die(oid, refname);
942 if (object->type != OBJ_COMMIT)
943 return 0;
945 add_pending_object(revs, object, "");
946 if (bitmap_is_preferred_refname(revs->repo, refname))
947 object->flags |= NEEDS_BITMAP;
948 return 0;
951 struct bitmap_commit_cb {
952 struct commit **commits;
953 size_t commits_nr, commits_alloc;
955 struct write_midx_context *ctx;
958 static const struct object_id *bitmap_oid_access(size_t index,
959 const void *_entries)
961 const struct pack_midx_entry *entries = _entries;
962 return &entries[index].oid;
965 static void bitmap_show_commit(struct commit *commit, void *_data)
967 struct bitmap_commit_cb *data = _data;
968 int pos = oid_pos(&commit->object.oid, data->ctx->entries,
969 data->ctx->entries_nr,
970 bitmap_oid_access);
971 if (pos < 0)
972 return;
974 ALLOC_GROW(data->commits, data->commits_nr + 1, data->commits_alloc);
975 data->commits[data->commits_nr++] = commit;
978 static int read_refs_snapshot(const char *refs_snapshot,
979 struct rev_info *revs)
981 struct strbuf buf = STRBUF_INIT;
982 struct object_id oid;
983 FILE *f = xfopen(refs_snapshot, "r");
985 while (strbuf_getline(&buf, f) != EOF) {
986 struct object *object;
987 int preferred = 0;
988 char *hex = buf.buf;
989 const char *end = NULL;
991 if (buf.len && *buf.buf == '+') {
992 preferred = 1;
993 hex = &buf.buf[1];
996 if (parse_oid_hex(hex, &oid, &end) < 0)
997 die(_("could not parse line: %s"), buf.buf);
998 if (*end)
999 die(_("malformed line: %s"), buf.buf);
1001 object = parse_object_or_die(&oid, NULL);
1002 if (preferred)
1003 object->flags |= NEEDS_BITMAP;
1005 add_pending_object(revs, object, "");
1008 fclose(f);
1009 strbuf_release(&buf);
1010 return 0;
1013 static struct commit **find_commits_for_midx_bitmap(uint32_t *indexed_commits_nr_p,
1014 const char *refs_snapshot,
1015 struct write_midx_context *ctx)
1017 struct rev_info revs;
1018 struct bitmap_commit_cb cb = {0};
1020 cb.ctx = ctx;
1022 repo_init_revisions(the_repository, &revs, NULL);
1023 if (refs_snapshot) {
1024 read_refs_snapshot(refs_snapshot, &revs);
1025 } else {
1026 setup_revisions(0, NULL, &revs, NULL);
1027 for_each_ref(add_ref_to_pending, &revs);
1031 * Skipping promisor objects here is intentional, since it only excludes
1032 * them from the list of reachable commits that we want to select from
1033 * when computing the selection of MIDX'd commits to receive bitmaps.
1035 * Reachability bitmaps do require that their objects be closed under
1036 * reachability, but fetching any objects missing from promisors at this
1037 * point is too late. But, if one of those objects can be reached from
1038 * an another object that is included in the bitmap, then we will
1039 * complain later that we don't have reachability closure (and fail
1040 * appropriately).
1042 fetch_if_missing = 0;
1043 revs.exclude_promisor_objects = 1;
1045 if (prepare_revision_walk(&revs))
1046 die(_("revision walk setup failed"));
1048 traverse_commit_list(&revs, bitmap_show_commit, NULL, &cb);
1049 if (indexed_commits_nr_p)
1050 *indexed_commits_nr_p = cb.commits_nr;
1052 release_revisions(&revs);
1053 return cb.commits;
1056 static int write_midx_bitmap(char *midx_name, unsigned char *midx_hash,
1057 struct write_midx_context *ctx,
1058 const char *refs_snapshot,
1059 unsigned flags)
1061 struct packing_data pdata;
1062 struct pack_idx_entry **index;
1063 struct commit **commits = NULL;
1064 uint32_t i, commits_nr;
1065 uint16_t options = 0;
1066 char *bitmap_name = xstrfmt("%s-%s.bitmap", midx_name, hash_to_hex(midx_hash));
1067 int ret;
1069 if (!ctx->entries_nr)
1070 BUG("cannot write a bitmap without any objects");
1072 if (flags & MIDX_WRITE_BITMAP_HASH_CACHE)
1073 options |= BITMAP_OPT_HASH_CACHE;
1075 prepare_midx_packing_data(&pdata, ctx);
1077 commits = find_commits_for_midx_bitmap(&commits_nr, refs_snapshot, ctx);
1080 * Build the MIDX-order index based on pdata.objects (which is already
1081 * in MIDX order; c.f., 'midx_pack_order_cmp()' for the definition of
1082 * this order).
1084 ALLOC_ARRAY(index, pdata.nr_objects);
1085 for (i = 0; i < pdata.nr_objects; i++)
1086 index[i] = &pdata.objects[i].idx;
1088 bitmap_writer_show_progress(flags & MIDX_PROGRESS);
1089 bitmap_writer_build_type_index(&pdata, index, pdata.nr_objects);
1092 * bitmap_writer_finish expects objects in lex order, but pack_order
1093 * gives us exactly that. use it directly instead of re-sorting the
1094 * array.
1096 * This changes the order of objects in 'index' between
1097 * bitmap_writer_build_type_index and bitmap_writer_finish.
1099 * The same re-ordering takes place in the single-pack bitmap code via
1100 * write_idx_file(), which is called by finish_tmp_packfile(), which
1101 * happens between bitmap_writer_build_type_index() and
1102 * bitmap_writer_finish().
1104 for (i = 0; i < pdata.nr_objects; i++)
1105 index[ctx->pack_order[i]] = &pdata.objects[i].idx;
1107 bitmap_writer_select_commits(commits, commits_nr, -1);
1108 ret = bitmap_writer_build(&pdata);
1109 if (ret < 0)
1110 goto cleanup;
1112 bitmap_writer_set_checksum(midx_hash);
1113 bitmap_writer_finish(index, pdata.nr_objects, bitmap_name, options);
1115 cleanup:
1116 free(index);
1117 free(bitmap_name);
1118 return ret;
1121 static struct multi_pack_index *lookup_multi_pack_index(struct repository *r,
1122 const char *object_dir)
1124 struct multi_pack_index *result = NULL;
1125 struct multi_pack_index *cur;
1126 char *obj_dir_real = real_pathdup(object_dir, 1);
1127 struct strbuf cur_path_real = STRBUF_INIT;
1129 /* Ensure the given object_dir is local, or a known alternate. */
1130 find_odb(r, obj_dir_real);
1132 for (cur = get_multi_pack_index(r); cur; cur = cur->next) {
1133 strbuf_realpath(&cur_path_real, cur->object_dir, 1);
1134 if (!strcmp(obj_dir_real, cur_path_real.buf)) {
1135 result = cur;
1136 goto cleanup;
1140 cleanup:
1141 free(obj_dir_real);
1142 strbuf_release(&cur_path_real);
1143 return result;
1146 static int write_midx_internal(const char *object_dir,
1147 struct string_list *packs_to_include,
1148 struct string_list *packs_to_drop,
1149 const char *preferred_pack_name,
1150 const char *refs_snapshot,
1151 unsigned flags)
1153 struct strbuf midx_name = STRBUF_INIT;
1154 unsigned char midx_hash[GIT_MAX_RAWSZ];
1155 uint32_t i;
1156 struct hashfile *f = NULL;
1157 struct lock_file lk;
1158 struct write_midx_context ctx = { 0 };
1159 int pack_name_concat_len = 0;
1160 int dropped_packs = 0;
1161 int result = 0;
1162 struct chunkfile *cf;
1164 get_midx_filename(&midx_name, object_dir);
1165 if (safe_create_leading_directories(midx_name.buf))
1166 die_errno(_("unable to create leading directories of %s"),
1167 midx_name.buf);
1169 if (!packs_to_include) {
1171 * Only reference an existing MIDX when not filtering which
1172 * packs to include, since all packs and objects are copied
1173 * blindly from an existing MIDX if one is present.
1175 ctx.m = lookup_multi_pack_index(the_repository, object_dir);
1178 if (ctx.m && !midx_checksum_valid(ctx.m)) {
1179 warning(_("ignoring existing multi-pack-index; checksum mismatch"));
1180 ctx.m = NULL;
1183 ctx.nr = 0;
1184 ctx.alloc = ctx.m ? ctx.m->num_packs : 16;
1185 ctx.info = NULL;
1186 ALLOC_ARRAY(ctx.info, ctx.alloc);
1188 if (ctx.m) {
1189 for (i = 0; i < ctx.m->num_packs; i++) {
1190 ALLOC_GROW(ctx.info, ctx.nr + 1, ctx.alloc);
1192 ctx.info[ctx.nr].orig_pack_int_id = i;
1193 ctx.info[ctx.nr].pack_name = xstrdup(ctx.m->pack_names[i]);
1194 ctx.info[ctx.nr].p = ctx.m->packs[i];
1195 ctx.info[ctx.nr].expired = 0;
1197 if (flags & MIDX_WRITE_REV_INDEX) {
1199 * If generating a reverse index, need to have
1200 * packed_git's loaded to compare their
1201 * mtimes and object count.
1203 if (prepare_midx_pack(the_repository, ctx.m, i)) {
1204 error(_("could not load pack"));
1205 result = 1;
1206 goto cleanup;
1209 if (open_pack_index(ctx.m->packs[i]))
1210 die(_("could not open index for %s"),
1211 ctx.m->packs[i]->pack_name);
1212 ctx.info[ctx.nr].p = ctx.m->packs[i];
1215 ctx.nr++;
1219 ctx.pack_paths_checked = 0;
1220 if (flags & MIDX_PROGRESS)
1221 ctx.progress = start_delayed_progress(_("Adding packfiles to multi-pack-index"), 0);
1222 else
1223 ctx.progress = NULL;
1225 ctx.to_include = packs_to_include;
1227 for_each_file_in_pack_dir(object_dir, add_pack_to_midx, &ctx);
1228 stop_progress(&ctx.progress);
1230 if ((ctx.m && ctx.nr == ctx.m->num_packs) &&
1231 !(packs_to_include || packs_to_drop)) {
1232 struct bitmap_index *bitmap_git;
1233 int bitmap_exists;
1234 int want_bitmap = flags & MIDX_WRITE_BITMAP;
1236 bitmap_git = prepare_midx_bitmap_git(ctx.m);
1237 bitmap_exists = bitmap_git && bitmap_is_midx(bitmap_git);
1238 free_bitmap_index(bitmap_git);
1240 if (bitmap_exists || !want_bitmap) {
1242 * The correct MIDX already exists, and so does a
1243 * corresponding bitmap (or one wasn't requested).
1245 if (!want_bitmap)
1246 clear_midx_files_ext(object_dir, ".bitmap",
1247 NULL);
1248 goto cleanup;
1252 if (preferred_pack_name) {
1253 int found = 0;
1254 for (i = 0; i < ctx.nr; i++) {
1255 if (!cmp_idx_or_pack_name(preferred_pack_name,
1256 ctx.info[i].pack_name)) {
1257 ctx.preferred_pack_idx = i;
1258 found = 1;
1259 break;
1263 if (!found)
1264 warning(_("unknown preferred pack: '%s'"),
1265 preferred_pack_name);
1266 } else if (ctx.nr &&
1267 (flags & (MIDX_WRITE_REV_INDEX | MIDX_WRITE_BITMAP))) {
1268 struct packed_git *oldest = ctx.info[ctx.preferred_pack_idx].p;
1269 ctx.preferred_pack_idx = 0;
1271 if (packs_to_drop && packs_to_drop->nr)
1272 BUG("cannot write a MIDX bitmap during expiration");
1275 * set a preferred pack when writing a bitmap to ensure that
1276 * the pack from which the first object is selected in pseudo
1277 * pack-order has all of its objects selected from that pack
1278 * (and not another pack containing a duplicate)
1280 for (i = 1; i < ctx.nr; i++) {
1281 struct packed_git *p = ctx.info[i].p;
1283 if (!oldest->num_objects || p->mtime < oldest->mtime) {
1284 oldest = p;
1285 ctx.preferred_pack_idx = i;
1289 if (!oldest->num_objects) {
1291 * If all packs are empty; unset the preferred index.
1292 * This is acceptable since there will be no duplicate
1293 * objects to resolve, so the preferred value doesn't
1294 * matter.
1296 ctx.preferred_pack_idx = -1;
1298 } else {
1300 * otherwise don't mark any pack as preferred to avoid
1301 * interfering with expiration logic below
1303 ctx.preferred_pack_idx = -1;
1306 if (ctx.preferred_pack_idx > -1) {
1307 struct packed_git *preferred = ctx.info[ctx.preferred_pack_idx].p;
1308 if (!preferred->num_objects) {
1309 error(_("cannot select preferred pack %s with no objects"),
1310 preferred->pack_name);
1311 result = 1;
1312 goto cleanup;
1316 ctx.entries = get_sorted_entries(ctx.m, ctx.info, ctx.nr, &ctx.entries_nr,
1317 ctx.preferred_pack_idx);
1319 ctx.large_offsets_needed = 0;
1320 for (i = 0; i < ctx.entries_nr; i++) {
1321 if (ctx.entries[i].offset > 0x7fffffff)
1322 ctx.num_large_offsets++;
1323 if (ctx.entries[i].offset > 0xffffffff)
1324 ctx.large_offsets_needed = 1;
1327 QSORT(ctx.info, ctx.nr, pack_info_compare);
1329 if (packs_to_drop && packs_to_drop->nr) {
1330 int drop_index = 0;
1331 int missing_drops = 0;
1333 for (i = 0; i < ctx.nr && drop_index < packs_to_drop->nr; i++) {
1334 int cmp = strcmp(ctx.info[i].pack_name,
1335 packs_to_drop->items[drop_index].string);
1337 if (!cmp) {
1338 drop_index++;
1339 ctx.info[i].expired = 1;
1340 } else if (cmp > 0) {
1341 error(_("did not see pack-file %s to drop"),
1342 packs_to_drop->items[drop_index].string);
1343 drop_index++;
1344 missing_drops++;
1345 i--;
1346 } else {
1347 ctx.info[i].expired = 0;
1351 if (missing_drops) {
1352 result = 1;
1353 goto cleanup;
1358 * pack_perm stores a permutation between pack-int-ids from the
1359 * previous multi-pack-index to the new one we are writing:
1361 * pack_perm[old_id] = new_id
1363 ALLOC_ARRAY(ctx.pack_perm, ctx.nr);
1364 for (i = 0; i < ctx.nr; i++) {
1365 if (ctx.info[i].expired) {
1366 dropped_packs++;
1367 ctx.pack_perm[ctx.info[i].orig_pack_int_id] = PACK_EXPIRED;
1368 } else {
1369 ctx.pack_perm[ctx.info[i].orig_pack_int_id] = i - dropped_packs;
1373 for (i = 0; i < ctx.nr; i++) {
1374 if (!ctx.info[i].expired)
1375 pack_name_concat_len += strlen(ctx.info[i].pack_name) + 1;
1378 /* Check that the preferred pack wasn't expired (if given). */
1379 if (preferred_pack_name) {
1380 struct pack_info *preferred = bsearch(preferred_pack_name,
1381 ctx.info, ctx.nr,
1382 sizeof(*ctx.info),
1383 idx_or_pack_name_cmp);
1384 if (preferred) {
1385 uint32_t perm = ctx.pack_perm[preferred->orig_pack_int_id];
1386 if (perm == PACK_EXPIRED)
1387 warning(_("preferred pack '%s' is expired"),
1388 preferred_pack_name);
1392 if (pack_name_concat_len % MIDX_CHUNK_ALIGNMENT)
1393 pack_name_concat_len += MIDX_CHUNK_ALIGNMENT -
1394 (pack_name_concat_len % MIDX_CHUNK_ALIGNMENT);
1396 hold_lock_file_for_update(&lk, midx_name.buf, LOCK_DIE_ON_ERROR);
1397 f = hashfd(get_lock_file_fd(&lk), get_lock_file_path(&lk));
1399 if (ctx.nr - dropped_packs == 0) {
1400 error(_("no pack files to index."));
1401 result = 1;
1402 goto cleanup;
1405 if (!ctx.entries_nr) {
1406 if (flags & MIDX_WRITE_BITMAP)
1407 warning(_("refusing to write multi-pack .bitmap without any objects"));
1408 flags &= ~(MIDX_WRITE_REV_INDEX | MIDX_WRITE_BITMAP);
1411 cf = init_chunkfile(f);
1413 add_chunk(cf, MIDX_CHUNKID_PACKNAMES, pack_name_concat_len,
1414 write_midx_pack_names);
1415 add_chunk(cf, MIDX_CHUNKID_OIDFANOUT, MIDX_CHUNK_FANOUT_SIZE,
1416 write_midx_oid_fanout);
1417 add_chunk(cf, MIDX_CHUNKID_OIDLOOKUP,
1418 (size_t)ctx.entries_nr * the_hash_algo->rawsz,
1419 write_midx_oid_lookup);
1420 add_chunk(cf, MIDX_CHUNKID_OBJECTOFFSETS,
1421 (size_t)ctx.entries_nr * MIDX_CHUNK_OFFSET_WIDTH,
1422 write_midx_object_offsets);
1424 if (ctx.large_offsets_needed)
1425 add_chunk(cf, MIDX_CHUNKID_LARGEOFFSETS,
1426 (size_t)ctx.num_large_offsets * MIDX_CHUNK_LARGE_OFFSET_WIDTH,
1427 write_midx_large_offsets);
1429 if (flags & (MIDX_WRITE_REV_INDEX | MIDX_WRITE_BITMAP)) {
1430 ctx.pack_order = midx_pack_order(&ctx);
1431 add_chunk(cf, MIDX_CHUNKID_REVINDEX,
1432 ctx.entries_nr * sizeof(uint32_t),
1433 write_midx_revindex);
1436 write_midx_header(f, get_num_chunks(cf), ctx.nr - dropped_packs);
1437 write_chunkfile(cf, &ctx);
1439 finalize_hashfile(f, midx_hash, FSYNC_COMPONENT_PACK_METADATA,
1440 CSUM_FSYNC | CSUM_HASH_IN_STREAM);
1441 free_chunkfile(cf);
1443 if (flags & MIDX_WRITE_REV_INDEX &&
1444 git_env_bool("GIT_TEST_MIDX_WRITE_REV", 0))
1445 write_midx_reverse_index(midx_name.buf, midx_hash, &ctx);
1446 if (flags & MIDX_WRITE_BITMAP) {
1447 if (write_midx_bitmap(midx_name.buf, midx_hash, &ctx,
1448 refs_snapshot, flags) < 0) {
1449 error(_("could not write multi-pack bitmap"));
1450 result = 1;
1451 goto cleanup;
1455 if (ctx.m)
1456 close_object_store(the_repository->objects);
1458 if (commit_lock_file(&lk) < 0)
1459 die_errno(_("could not write multi-pack-index"));
1461 clear_midx_files_ext(object_dir, ".bitmap", midx_hash);
1462 clear_midx_files_ext(object_dir, ".rev", midx_hash);
1464 cleanup:
1465 for (i = 0; i < ctx.nr; i++) {
1466 if (ctx.info[i].p) {
1467 close_pack(ctx.info[i].p);
1468 free(ctx.info[i].p);
1470 free(ctx.info[i].pack_name);
1473 free(ctx.info);
1474 free(ctx.entries);
1475 free(ctx.pack_perm);
1476 free(ctx.pack_order);
1477 strbuf_release(&midx_name);
1479 return result;
1482 int write_midx_file(const char *object_dir,
1483 const char *preferred_pack_name,
1484 const char *refs_snapshot,
1485 unsigned flags)
1487 return write_midx_internal(object_dir, NULL, NULL, preferred_pack_name,
1488 refs_snapshot, flags);
1491 int write_midx_file_only(const char *object_dir,
1492 struct string_list *packs_to_include,
1493 const char *preferred_pack_name,
1494 const char *refs_snapshot,
1495 unsigned flags)
1497 return write_midx_internal(object_dir, packs_to_include, NULL,
1498 preferred_pack_name, refs_snapshot, flags);
1501 struct clear_midx_data {
1502 char *keep;
1503 const char *ext;
1506 static void clear_midx_file_ext(const char *full_path, size_t full_path_len,
1507 const char *file_name, void *_data)
1509 struct clear_midx_data *data = _data;
1511 if (!(starts_with(file_name, "multi-pack-index-") &&
1512 ends_with(file_name, data->ext)))
1513 return;
1514 if (data->keep && !strcmp(data->keep, file_name))
1515 return;
1517 if (unlink(full_path))
1518 die_errno(_("failed to remove %s"), full_path);
1521 static void clear_midx_files_ext(const char *object_dir, const char *ext,
1522 unsigned char *keep_hash)
1524 struct clear_midx_data data;
1525 memset(&data, 0, sizeof(struct clear_midx_data));
1527 if (keep_hash)
1528 data.keep = xstrfmt("multi-pack-index-%s%s",
1529 hash_to_hex(keep_hash), ext);
1530 data.ext = ext;
1532 for_each_file_in_pack_dir(object_dir,
1533 clear_midx_file_ext,
1534 &data);
1536 free(data.keep);
1539 void clear_midx_file(struct repository *r)
1541 struct strbuf midx = STRBUF_INIT;
1543 get_midx_filename(&midx, r->objects->odb->path);
1545 if (r->objects && r->objects->multi_pack_index) {
1546 close_midx(r->objects->multi_pack_index);
1547 r->objects->multi_pack_index = NULL;
1550 if (remove_path(midx.buf))
1551 die(_("failed to clear multi-pack-index at %s"), midx.buf);
1553 clear_midx_files_ext(r->objects->odb->path, ".bitmap", NULL);
1554 clear_midx_files_ext(r->objects->odb->path, ".rev", NULL);
1556 strbuf_release(&midx);
1559 static int verify_midx_error;
1561 __attribute__((format (printf, 1, 2)))
1562 static void midx_report(const char *fmt, ...)
1564 va_list ap;
1565 verify_midx_error = 1;
1566 va_start(ap, fmt);
1567 vfprintf(stderr, fmt, ap);
1568 fprintf(stderr, "\n");
1569 va_end(ap);
1572 struct pair_pos_vs_id
1574 uint32_t pos;
1575 uint32_t pack_int_id;
1578 static int compare_pair_pos_vs_id(const void *_a, const void *_b)
1580 struct pair_pos_vs_id *a = (struct pair_pos_vs_id *)_a;
1581 struct pair_pos_vs_id *b = (struct pair_pos_vs_id *)_b;
1583 return b->pack_int_id - a->pack_int_id;
1587 * Limit calls to display_progress() for performance reasons.
1588 * The interval here was arbitrarily chosen.
1590 #define SPARSE_PROGRESS_INTERVAL (1 << 12)
1591 #define midx_display_sparse_progress(progress, n) \
1592 do { \
1593 uint64_t _n = (n); \
1594 if ((_n & (SPARSE_PROGRESS_INTERVAL - 1)) == 0) \
1595 display_progress(progress, _n); \
1596 } while (0)
1598 int verify_midx_file(struct repository *r, const char *object_dir, unsigned flags)
1600 struct pair_pos_vs_id *pairs = NULL;
1601 uint32_t i;
1602 struct progress *progress = NULL;
1603 struct multi_pack_index *m = load_multi_pack_index(object_dir, 1);
1604 verify_midx_error = 0;
1606 if (!m) {
1607 int result = 0;
1608 struct stat sb;
1609 struct strbuf filename = STRBUF_INIT;
1611 get_midx_filename(&filename, object_dir);
1613 if (!stat(filename.buf, &sb)) {
1614 error(_("multi-pack-index file exists, but failed to parse"));
1615 result = 1;
1617 strbuf_release(&filename);
1618 return result;
1621 if (!midx_checksum_valid(m))
1622 midx_report(_("incorrect checksum"));
1624 if (flags & MIDX_PROGRESS)
1625 progress = start_delayed_progress(_("Looking for referenced packfiles"),
1626 m->num_packs);
1627 for (i = 0; i < m->num_packs; i++) {
1628 if (prepare_midx_pack(r, m, i))
1629 midx_report("failed to load pack in position %d", i);
1631 display_progress(progress, i + 1);
1633 stop_progress(&progress);
1635 for (i = 0; i < 255; i++) {
1636 uint32_t oid_fanout1 = ntohl(m->chunk_oid_fanout[i]);
1637 uint32_t oid_fanout2 = ntohl(m->chunk_oid_fanout[i + 1]);
1639 if (oid_fanout1 > oid_fanout2)
1640 midx_report(_("oid fanout out of order: fanout[%d] = %"PRIx32" > %"PRIx32" = fanout[%d]"),
1641 i, oid_fanout1, oid_fanout2, i + 1);
1644 if (m->num_objects == 0) {
1645 midx_report(_("the midx contains no oid"));
1647 * Remaining tests assume that we have objects, so we can
1648 * return here.
1650 goto cleanup;
1653 if (flags & MIDX_PROGRESS)
1654 progress = start_sparse_progress(_("Verifying OID order in multi-pack-index"),
1655 m->num_objects - 1);
1656 for (i = 0; i < m->num_objects - 1; i++) {
1657 struct object_id oid1, oid2;
1659 nth_midxed_object_oid(&oid1, m, i);
1660 nth_midxed_object_oid(&oid2, m, i + 1);
1662 if (oidcmp(&oid1, &oid2) >= 0)
1663 midx_report(_("oid lookup out of order: oid[%d] = %s >= %s = oid[%d]"),
1664 i, oid_to_hex(&oid1), oid_to_hex(&oid2), i + 1);
1666 midx_display_sparse_progress(progress, i + 1);
1668 stop_progress(&progress);
1671 * Create an array mapping each object to its packfile id. Sort it
1672 * to group the objects by packfile. Use this permutation to visit
1673 * each of the objects and only require 1 packfile to be open at a
1674 * time.
1676 ALLOC_ARRAY(pairs, m->num_objects);
1677 for (i = 0; i < m->num_objects; i++) {
1678 pairs[i].pos = i;
1679 pairs[i].pack_int_id = nth_midxed_pack_int_id(m, i);
1682 if (flags & MIDX_PROGRESS)
1683 progress = start_sparse_progress(_("Sorting objects by packfile"),
1684 m->num_objects);
1685 display_progress(progress, 0); /* TODO: Measure QSORT() progress */
1686 QSORT(pairs, m->num_objects, compare_pair_pos_vs_id);
1687 stop_progress(&progress);
1689 if (flags & MIDX_PROGRESS)
1690 progress = start_sparse_progress(_("Verifying object offsets"), m->num_objects);
1691 for (i = 0; i < m->num_objects; i++) {
1692 struct object_id oid;
1693 struct pack_entry e;
1694 off_t m_offset, p_offset;
1696 if (i > 0 && pairs[i-1].pack_int_id != pairs[i].pack_int_id &&
1697 m->packs[pairs[i-1].pack_int_id])
1699 close_pack_fd(m->packs[pairs[i-1].pack_int_id]);
1700 close_pack_index(m->packs[pairs[i-1].pack_int_id]);
1703 nth_midxed_object_oid(&oid, m, pairs[i].pos);
1705 if (!fill_midx_entry(r, &oid, &e, m)) {
1706 midx_report(_("failed to load pack entry for oid[%d] = %s"),
1707 pairs[i].pos, oid_to_hex(&oid));
1708 continue;
1711 if (open_pack_index(e.p)) {
1712 midx_report(_("failed to load pack-index for packfile %s"),
1713 e.p->pack_name);
1714 break;
1717 m_offset = e.offset;
1718 p_offset = find_pack_entry_one(oid.hash, e.p);
1720 if (m_offset != p_offset)
1721 midx_report(_("incorrect object offset for oid[%d] = %s: %"PRIx64" != %"PRIx64),
1722 pairs[i].pos, oid_to_hex(&oid), m_offset, p_offset);
1724 midx_display_sparse_progress(progress, i + 1);
1726 stop_progress(&progress);
1728 cleanup:
1729 free(pairs);
1730 close_midx(m);
1732 return verify_midx_error;
1735 int expire_midx_packs(struct repository *r, const char *object_dir, unsigned flags)
1737 uint32_t i, *count, result = 0;
1738 struct string_list packs_to_drop = STRING_LIST_INIT_DUP;
1739 struct multi_pack_index *m = lookup_multi_pack_index(r, object_dir);
1740 struct progress *progress = NULL;
1742 if (!m)
1743 return 0;
1745 CALLOC_ARRAY(count, m->num_packs);
1747 if (flags & MIDX_PROGRESS)
1748 progress = start_delayed_progress(_("Counting referenced objects"),
1749 m->num_objects);
1750 for (i = 0; i < m->num_objects; i++) {
1751 int pack_int_id = nth_midxed_pack_int_id(m, i);
1752 count[pack_int_id]++;
1753 display_progress(progress, i + 1);
1755 stop_progress(&progress);
1757 if (flags & MIDX_PROGRESS)
1758 progress = start_delayed_progress(_("Finding and deleting unreferenced packfiles"),
1759 m->num_packs);
1760 for (i = 0; i < m->num_packs; i++) {
1761 char *pack_name;
1762 display_progress(progress, i + 1);
1764 if (count[i])
1765 continue;
1767 if (prepare_midx_pack(r, m, i))
1768 continue;
1770 if (m->packs[i]->pack_keep)
1771 continue;
1773 pack_name = xstrdup(m->packs[i]->pack_name);
1774 close_pack(m->packs[i]);
1776 string_list_insert(&packs_to_drop, m->pack_names[i]);
1777 unlink_pack_path(pack_name, 0);
1778 free(pack_name);
1780 stop_progress(&progress);
1782 free(count);
1784 if (packs_to_drop.nr)
1785 result = write_midx_internal(object_dir, NULL, &packs_to_drop, NULL, NULL, flags);
1787 string_list_clear(&packs_to_drop, 0);
1789 return result;
1792 struct repack_info {
1793 timestamp_t mtime;
1794 uint32_t referenced_objects;
1795 uint32_t pack_int_id;
1798 static int compare_by_mtime(const void *a_, const void *b_)
1800 const struct repack_info *a, *b;
1802 a = (const struct repack_info *)a_;
1803 b = (const struct repack_info *)b_;
1805 if (a->mtime < b->mtime)
1806 return -1;
1807 if (a->mtime > b->mtime)
1808 return 1;
1809 return 0;
1812 static int fill_included_packs_all(struct repository *r,
1813 struct multi_pack_index *m,
1814 unsigned char *include_pack)
1816 uint32_t i, count = 0;
1817 int pack_kept_objects = 0;
1819 repo_config_get_bool(r, "repack.packkeptobjects", &pack_kept_objects);
1821 for (i = 0; i < m->num_packs; i++) {
1822 if (prepare_midx_pack(r, m, i))
1823 continue;
1824 if (!pack_kept_objects && m->packs[i]->pack_keep)
1825 continue;
1827 include_pack[i] = 1;
1828 count++;
1831 return count < 2;
1834 static int fill_included_packs_batch(struct repository *r,
1835 struct multi_pack_index *m,
1836 unsigned char *include_pack,
1837 size_t batch_size)
1839 uint32_t i, packs_to_repack;
1840 size_t total_size;
1841 struct repack_info *pack_info = xcalloc(m->num_packs, sizeof(struct repack_info));
1842 int pack_kept_objects = 0;
1844 repo_config_get_bool(r, "repack.packkeptobjects", &pack_kept_objects);
1846 for (i = 0; i < m->num_packs; i++) {
1847 pack_info[i].pack_int_id = i;
1849 if (prepare_midx_pack(r, m, i))
1850 continue;
1852 pack_info[i].mtime = m->packs[i]->mtime;
1855 for (i = 0; batch_size && i < m->num_objects; i++) {
1856 uint32_t pack_int_id = nth_midxed_pack_int_id(m, i);
1857 pack_info[pack_int_id].referenced_objects++;
1860 QSORT(pack_info, m->num_packs, compare_by_mtime);
1862 total_size = 0;
1863 packs_to_repack = 0;
1864 for (i = 0; total_size < batch_size && i < m->num_packs; i++) {
1865 int pack_int_id = pack_info[i].pack_int_id;
1866 struct packed_git *p = m->packs[pack_int_id];
1867 size_t expected_size;
1869 if (!p)
1870 continue;
1871 if (!pack_kept_objects && p->pack_keep)
1872 continue;
1873 if (open_pack_index(p) || !p->num_objects)
1874 continue;
1876 expected_size = (size_t)(p->pack_size
1877 * pack_info[i].referenced_objects);
1878 expected_size /= p->num_objects;
1880 if (expected_size >= batch_size)
1881 continue;
1883 packs_to_repack++;
1884 total_size += expected_size;
1885 include_pack[pack_int_id] = 1;
1888 free(pack_info);
1890 if (packs_to_repack < 2)
1891 return 1;
1893 return 0;
1896 int midx_repack(struct repository *r, const char *object_dir, size_t batch_size, unsigned flags)
1898 int result = 0;
1899 uint32_t i;
1900 unsigned char *include_pack;
1901 struct child_process cmd = CHILD_PROCESS_INIT;
1902 FILE *cmd_in;
1903 struct strbuf base_name = STRBUF_INIT;
1904 struct multi_pack_index *m = lookup_multi_pack_index(r, object_dir);
1907 * When updating the default for these configuration
1908 * variables in builtin/repack.c, these must be adjusted
1909 * to match.
1911 int delta_base_offset = 1;
1912 int use_delta_islands = 0;
1914 if (!m)
1915 return 0;
1917 CALLOC_ARRAY(include_pack, m->num_packs);
1919 if (batch_size) {
1920 if (fill_included_packs_batch(r, m, include_pack, batch_size))
1921 goto cleanup;
1922 } else if (fill_included_packs_all(r, m, include_pack))
1923 goto cleanup;
1925 repo_config_get_bool(r, "repack.usedeltabaseoffset", &delta_base_offset);
1926 repo_config_get_bool(r, "repack.usedeltaislands", &use_delta_islands);
1928 strvec_push(&cmd.args, "pack-objects");
1930 strbuf_addstr(&base_name, object_dir);
1931 strbuf_addstr(&base_name, "/pack/pack");
1932 strvec_push(&cmd.args, base_name.buf);
1934 if (delta_base_offset)
1935 strvec_push(&cmd.args, "--delta-base-offset");
1936 if (use_delta_islands)
1937 strvec_push(&cmd.args, "--delta-islands");
1939 if (flags & MIDX_PROGRESS)
1940 strvec_push(&cmd.args, "--progress");
1941 else
1942 strvec_push(&cmd.args, "-q");
1944 strbuf_release(&base_name);
1946 cmd.git_cmd = 1;
1947 cmd.in = cmd.out = -1;
1949 if (start_command(&cmd)) {
1950 error(_("could not start pack-objects"));
1951 result = 1;
1952 goto cleanup;
1955 cmd_in = xfdopen(cmd.in, "w");
1957 for (i = 0; i < m->num_objects; i++) {
1958 struct object_id oid;
1959 uint32_t pack_int_id = nth_midxed_pack_int_id(m, i);
1961 if (!include_pack[pack_int_id])
1962 continue;
1964 nth_midxed_object_oid(&oid, m, i);
1965 fprintf(cmd_in, "%s\n", oid_to_hex(&oid));
1967 fclose(cmd_in);
1969 if (finish_command(&cmd)) {
1970 error(_("could not finish pack-objects"));
1971 result = 1;
1972 goto cleanup;
1975 result = write_midx_internal(object_dir, NULL, NULL, NULL, NULL, flags);
1977 cleanup:
1978 free(include_pack);
1979 return result;