Merge branch 'kz/revindex-comment-fix'
[git/debian.git] / midx.c
blobf96fb2efeeb16bb2eb9b9177eaa213b157609cd2
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_CHUNK_FANOUT_SIZE (sizeof(uint32_t) * 256)
37 #define MIDX_CHUNK_OFFSET_WIDTH (2 * sizeof(uint32_t))
38 #define MIDX_CHUNK_LARGE_OFFSET_WIDTH (sizeof(uint64_t))
39 #define MIDX_LARGE_OFFSET_NEEDED 0x80000000
41 #define PACK_EXPIRED UINT_MAX
43 static uint8_t oid_version(void)
45 switch (hash_algo_by_ptr(the_hash_algo)) {
46 case GIT_HASH_SHA1:
47 return 1;
48 case GIT_HASH_SHA256:
49 return 2;
50 default:
51 die(_("invalid hash version"));
55 const unsigned char *get_midx_checksum(struct multi_pack_index *m)
57 return m->data + m->data_len - the_hash_algo->rawsz;
60 char *get_midx_filename(const char *object_dir)
62 return xstrfmt("%s/pack/multi-pack-index", object_dir);
65 char *get_midx_rev_filename(struct multi_pack_index *m)
67 return xstrfmt("%s/pack/multi-pack-index-%s.rev",
68 m->object_dir, hash_to_hex(get_midx_checksum(m)));
71 static int midx_read_oid_fanout(const unsigned char *chunk_start,
72 size_t chunk_size, void *data)
74 struct multi_pack_index *m = data;
75 m->chunk_oid_fanout = (uint32_t *)chunk_start;
77 if (chunk_size != 4 * 256) {
78 error(_("multi-pack-index OID fanout is of the wrong size"));
79 return 1;
81 return 0;
84 struct multi_pack_index *load_multi_pack_index(const char *object_dir, int local)
86 struct multi_pack_index *m = NULL;
87 int fd;
88 struct stat st;
89 size_t midx_size;
90 void *midx_map = NULL;
91 uint32_t hash_version;
92 char *midx_name = get_midx_filename(object_dir);
93 uint32_t i;
94 const char *cur_pack_name;
95 struct chunkfile *cf = NULL;
97 fd = git_open(midx_name);
99 if (fd < 0)
100 goto cleanup_fail;
101 if (fstat(fd, &st)) {
102 error_errno(_("failed to read %s"), midx_name);
103 goto cleanup_fail;
106 midx_size = xsize_t(st.st_size);
108 if (midx_size < MIDX_MIN_SIZE) {
109 error(_("multi-pack-index file %s is too small"), midx_name);
110 goto cleanup_fail;
113 FREE_AND_NULL(midx_name);
115 midx_map = xmmap(NULL, midx_size, PROT_READ, MAP_PRIVATE, fd, 0);
116 close(fd);
118 FLEX_ALLOC_STR(m, object_dir, object_dir);
119 m->data = midx_map;
120 m->data_len = midx_size;
121 m->local = local;
123 m->signature = get_be32(m->data);
124 if (m->signature != MIDX_SIGNATURE)
125 die(_("multi-pack-index signature 0x%08x does not match signature 0x%08x"),
126 m->signature, MIDX_SIGNATURE);
128 m->version = m->data[MIDX_BYTE_FILE_VERSION];
129 if (m->version != MIDX_VERSION)
130 die(_("multi-pack-index version %d not recognized"),
131 m->version);
133 hash_version = m->data[MIDX_BYTE_HASH_VERSION];
134 if (hash_version != oid_version()) {
135 error(_("multi-pack-index hash version %u does not match version %u"),
136 hash_version, oid_version());
137 goto cleanup_fail;
139 m->hash_len = the_hash_algo->rawsz;
141 m->num_chunks = m->data[MIDX_BYTE_NUM_CHUNKS];
143 m->num_packs = get_be32(m->data + MIDX_BYTE_NUM_PACKS);
145 cf = init_chunkfile(NULL);
147 if (read_table_of_contents(cf, m->data, midx_size,
148 MIDX_HEADER_SIZE, m->num_chunks))
149 goto cleanup_fail;
151 if (pair_chunk(cf, MIDX_CHUNKID_PACKNAMES, &m->chunk_pack_names) == CHUNK_NOT_FOUND)
152 die(_("multi-pack-index missing required pack-name chunk"));
153 if (read_chunk(cf, MIDX_CHUNKID_OIDFANOUT, midx_read_oid_fanout, m) == CHUNK_NOT_FOUND)
154 die(_("multi-pack-index missing required OID fanout chunk"));
155 if (pair_chunk(cf, MIDX_CHUNKID_OIDLOOKUP, &m->chunk_oid_lookup) == CHUNK_NOT_FOUND)
156 die(_("multi-pack-index missing required OID lookup chunk"));
157 if (pair_chunk(cf, MIDX_CHUNKID_OBJECTOFFSETS, &m->chunk_object_offsets) == CHUNK_NOT_FOUND)
158 die(_("multi-pack-index missing required object offsets chunk"));
160 pair_chunk(cf, MIDX_CHUNKID_LARGEOFFSETS, &m->chunk_large_offsets);
162 m->num_objects = ntohl(m->chunk_oid_fanout[255]);
164 CALLOC_ARRAY(m->pack_names, m->num_packs);
165 CALLOC_ARRAY(m->packs, m->num_packs);
167 cur_pack_name = (const char *)m->chunk_pack_names;
168 for (i = 0; i < m->num_packs; i++) {
169 m->pack_names[i] = cur_pack_name;
171 cur_pack_name += strlen(cur_pack_name) + 1;
173 if (i && strcmp(m->pack_names[i], m->pack_names[i - 1]) <= 0)
174 die(_("multi-pack-index pack names out of order: '%s' before '%s'"),
175 m->pack_names[i - 1],
176 m->pack_names[i]);
179 trace2_data_intmax("midx", the_repository, "load/num_packs", m->num_packs);
180 trace2_data_intmax("midx", the_repository, "load/num_objects", m->num_objects);
182 return m;
184 cleanup_fail:
185 free(m);
186 free(midx_name);
187 free(cf);
188 if (midx_map)
189 munmap(midx_map, midx_size);
190 if (0 <= fd)
191 close(fd);
192 return NULL;
195 void close_midx(struct multi_pack_index *m)
197 uint32_t i;
199 if (!m)
200 return;
202 close_midx(m->next);
204 munmap((unsigned char *)m->data, m->data_len);
206 for (i = 0; i < m->num_packs; i++) {
207 if (m->packs[i])
208 m->packs[i]->multi_pack_index = 0;
210 FREE_AND_NULL(m->packs);
211 FREE_AND_NULL(m->pack_names);
212 free(m);
215 int prepare_midx_pack(struct repository *r, struct multi_pack_index *m, uint32_t pack_int_id)
217 struct strbuf pack_name = STRBUF_INIT;
218 struct packed_git *p;
220 if (pack_int_id >= m->num_packs)
221 die(_("bad pack-int-id: %u (%u total packs)"),
222 pack_int_id, m->num_packs);
224 if (m->packs[pack_int_id])
225 return 0;
227 strbuf_addf(&pack_name, "%s/pack/%s", m->object_dir,
228 m->pack_names[pack_int_id]);
230 p = add_packed_git(pack_name.buf, pack_name.len, m->local);
231 strbuf_release(&pack_name);
233 if (!p)
234 return 1;
236 p->multi_pack_index = 1;
237 m->packs[pack_int_id] = p;
238 install_packed_git(r, p);
239 list_add_tail(&p->mru, &r->objects->packed_git_mru);
241 return 0;
244 int bsearch_midx(const struct object_id *oid, struct multi_pack_index *m, uint32_t *result)
246 return bsearch_hash(oid->hash, m->chunk_oid_fanout, m->chunk_oid_lookup,
247 the_hash_algo->rawsz, result);
250 struct object_id *nth_midxed_object_oid(struct object_id *oid,
251 struct multi_pack_index *m,
252 uint32_t n)
254 if (n >= m->num_objects)
255 return NULL;
257 oidread(oid, m->chunk_oid_lookup + m->hash_len * n);
258 return oid;
261 off_t nth_midxed_offset(struct multi_pack_index *m, uint32_t pos)
263 const unsigned char *offset_data;
264 uint32_t offset32;
266 offset_data = m->chunk_object_offsets + (off_t)pos * MIDX_CHUNK_OFFSET_WIDTH;
267 offset32 = get_be32(offset_data + sizeof(uint32_t));
269 if (m->chunk_large_offsets && offset32 & MIDX_LARGE_OFFSET_NEEDED) {
270 if (sizeof(off_t) < sizeof(uint64_t))
271 die(_("multi-pack-index stores a 64-bit offset, but off_t is too small"));
273 offset32 ^= MIDX_LARGE_OFFSET_NEEDED;
274 return get_be64(m->chunk_large_offsets + sizeof(uint64_t) * offset32);
277 return offset32;
280 uint32_t nth_midxed_pack_int_id(struct multi_pack_index *m, uint32_t pos)
282 return get_be32(m->chunk_object_offsets +
283 (off_t)pos * MIDX_CHUNK_OFFSET_WIDTH);
286 int fill_midx_entry(struct repository * r,
287 const struct object_id *oid,
288 struct pack_entry *e,
289 struct multi_pack_index *m)
291 uint32_t pos;
292 uint32_t pack_int_id;
293 struct packed_git *p;
295 if (!bsearch_midx(oid, m, &pos))
296 return 0;
298 if (pos >= m->num_objects)
299 return 0;
301 pack_int_id = nth_midxed_pack_int_id(m, pos);
303 if (prepare_midx_pack(r, m, pack_int_id))
304 return 0;
305 p = m->packs[pack_int_id];
308 * We are about to tell the caller where they can locate the
309 * requested object. We better make sure the packfile is
310 * still here and can be accessed before supplying that
311 * answer, as it may have been deleted since the MIDX was
312 * loaded!
314 if (!is_pack_valid(p))
315 return 0;
317 if (oidset_size(&p->bad_objects) &&
318 oidset_contains(&p->bad_objects, oid))
319 return 0;
321 e->offset = nth_midxed_offset(m, pos);
322 e->p = p;
324 return 1;
327 /* Match "foo.idx" against either "foo.pack" _or_ "foo.idx". */
328 static int cmp_idx_or_pack_name(const char *idx_or_pack_name,
329 const char *idx_name)
331 /* Skip past any initial matching prefix. */
332 while (*idx_name && *idx_name == *idx_or_pack_name) {
333 idx_name++;
334 idx_or_pack_name++;
338 * If we didn't match completely, we may have matched "pack-1234." and
339 * be left with "idx" and "pack" respectively, which is also OK. We do
340 * not have to check for "idx" and "idx", because that would have been
341 * a complete match (and in that case these strcmps will be false, but
342 * we'll correctly return 0 from the final strcmp() below.
344 * Technically this matches "fooidx" and "foopack", but we'd never have
345 * such names in the first place.
347 if (!strcmp(idx_name, "idx") && !strcmp(idx_or_pack_name, "pack"))
348 return 0;
351 * This not only checks for a complete match, but also orders based on
352 * the first non-identical character, which means our ordering will
353 * match a raw strcmp(). That makes it OK to use this to binary search
354 * a naively-sorted list.
356 return strcmp(idx_or_pack_name, idx_name);
359 int midx_contains_pack(struct multi_pack_index *m, const char *idx_or_pack_name)
361 uint32_t first = 0, last = m->num_packs;
363 while (first < last) {
364 uint32_t mid = first + (last - first) / 2;
365 const char *current;
366 int cmp;
368 current = m->pack_names[mid];
369 cmp = cmp_idx_or_pack_name(idx_or_pack_name, current);
370 if (!cmp)
371 return 1;
372 if (cmp > 0) {
373 first = mid + 1;
374 continue;
376 last = mid;
379 return 0;
382 int prepare_multi_pack_index_one(struct repository *r, const char *object_dir, int local)
384 struct multi_pack_index *m;
385 struct multi_pack_index *m_search;
387 prepare_repo_settings(r);
388 if (!r->settings.core_multi_pack_index)
389 return 0;
391 for (m_search = r->objects->multi_pack_index; m_search; m_search = m_search->next)
392 if (!strcmp(object_dir, m_search->object_dir))
393 return 1;
395 m = load_multi_pack_index(object_dir, local);
397 if (m) {
398 struct multi_pack_index *mp = r->objects->multi_pack_index;
399 if (mp) {
400 m->next = mp->next;
401 mp->next = m;
402 } else
403 r->objects->multi_pack_index = m;
404 return 1;
407 return 0;
410 static size_t write_midx_header(struct hashfile *f,
411 unsigned char num_chunks,
412 uint32_t num_packs)
414 hashwrite_be32(f, MIDX_SIGNATURE);
415 hashwrite_u8(f, MIDX_VERSION);
416 hashwrite_u8(f, oid_version());
417 hashwrite_u8(f, num_chunks);
418 hashwrite_u8(f, 0); /* unused */
419 hashwrite_be32(f, num_packs);
421 return MIDX_HEADER_SIZE;
424 struct pack_info {
425 uint32_t orig_pack_int_id;
426 char *pack_name;
427 struct packed_git *p;
428 unsigned expired : 1;
431 static int pack_info_compare(const void *_a, const void *_b)
433 struct pack_info *a = (struct pack_info *)_a;
434 struct pack_info *b = (struct pack_info *)_b;
435 return strcmp(a->pack_name, b->pack_name);
438 static int idx_or_pack_name_cmp(const void *_va, const void *_vb)
440 const char *pack_name = _va;
441 const struct pack_info *compar = _vb;
443 return cmp_idx_or_pack_name(pack_name, compar->pack_name);
446 struct write_midx_context {
447 struct pack_info *info;
448 uint32_t nr;
449 uint32_t alloc;
450 struct multi_pack_index *m;
451 struct progress *progress;
452 unsigned pack_paths_checked;
454 struct pack_midx_entry *entries;
455 uint32_t entries_nr;
457 uint32_t *pack_perm;
458 uint32_t *pack_order;
459 unsigned large_offsets_needed:1;
460 uint32_t num_large_offsets;
462 int preferred_pack_idx;
465 static void add_pack_to_midx(const char *full_path, size_t full_path_len,
466 const char *file_name, void *data)
468 struct write_midx_context *ctx = data;
470 if (ends_with(file_name, ".idx")) {
471 display_progress(ctx->progress, ++ctx->pack_paths_checked);
472 if (ctx->m && midx_contains_pack(ctx->m, file_name))
473 return;
475 ALLOC_GROW(ctx->info, ctx->nr + 1, ctx->alloc);
477 ctx->info[ctx->nr].p = add_packed_git(full_path,
478 full_path_len,
481 if (!ctx->info[ctx->nr].p) {
482 warning(_("failed to add packfile '%s'"),
483 full_path);
484 return;
487 if (open_pack_index(ctx->info[ctx->nr].p)) {
488 warning(_("failed to open pack-index '%s'"),
489 full_path);
490 close_pack(ctx->info[ctx->nr].p);
491 FREE_AND_NULL(ctx->info[ctx->nr].p);
492 return;
495 ctx->info[ctx->nr].pack_name = xstrdup(file_name);
496 ctx->info[ctx->nr].orig_pack_int_id = ctx->nr;
497 ctx->info[ctx->nr].expired = 0;
498 ctx->nr++;
502 struct pack_midx_entry {
503 struct object_id oid;
504 uint32_t pack_int_id;
505 time_t pack_mtime;
506 uint64_t offset;
507 unsigned preferred : 1;
510 static int midx_oid_compare(const void *_a, const void *_b)
512 const struct pack_midx_entry *a = (const struct pack_midx_entry *)_a;
513 const struct pack_midx_entry *b = (const struct pack_midx_entry *)_b;
514 int cmp = oidcmp(&a->oid, &b->oid);
516 if (cmp)
517 return cmp;
519 /* Sort objects in a preferred pack first when multiple copies exist. */
520 if (a->preferred > b->preferred)
521 return -1;
522 if (a->preferred < b->preferred)
523 return 1;
525 if (a->pack_mtime > b->pack_mtime)
526 return -1;
527 else if (a->pack_mtime < b->pack_mtime)
528 return 1;
530 return a->pack_int_id - b->pack_int_id;
533 static int nth_midxed_pack_midx_entry(struct multi_pack_index *m,
534 struct pack_midx_entry *e,
535 uint32_t pos)
537 if (pos >= m->num_objects)
538 return 1;
540 nth_midxed_object_oid(&e->oid, m, pos);
541 e->pack_int_id = nth_midxed_pack_int_id(m, pos);
542 e->offset = nth_midxed_offset(m, pos);
544 /* consider objects in midx to be from "old" packs */
545 e->pack_mtime = 0;
546 return 0;
549 static void fill_pack_entry(uint32_t pack_int_id,
550 struct packed_git *p,
551 uint32_t cur_object,
552 struct pack_midx_entry *entry,
553 int preferred)
555 if (nth_packed_object_id(&entry->oid, p, cur_object) < 0)
556 die(_("failed to locate object %d in packfile"), cur_object);
558 entry->pack_int_id = pack_int_id;
559 entry->pack_mtime = p->mtime;
561 entry->offset = nth_packed_object_offset(p, cur_object);
562 entry->preferred = !!preferred;
566 * It is possible to artificially get into a state where there are many
567 * duplicate copies of objects. That can create high memory pressure if
568 * we are to create a list of all objects before de-duplication. To reduce
569 * this memory pressure without a significant performance drop, automatically
570 * group objects by the first byte of their object id. Use the IDX fanout
571 * tables to group the data, copy to a local array, then sort.
573 * Copy only the de-duplicated entries (selected by most-recent modified time
574 * of a packfile containing the object).
576 static struct pack_midx_entry *get_sorted_entries(struct multi_pack_index *m,
577 struct pack_info *info,
578 uint32_t nr_packs,
579 uint32_t *nr_objects,
580 int preferred_pack)
582 uint32_t cur_fanout, cur_pack, cur_object;
583 uint32_t alloc_fanout, alloc_objects, total_objects = 0;
584 struct pack_midx_entry *entries_by_fanout = NULL;
585 struct pack_midx_entry *deduplicated_entries = NULL;
586 uint32_t start_pack = m ? m->num_packs : 0;
588 for (cur_pack = start_pack; cur_pack < nr_packs; cur_pack++)
589 total_objects += info[cur_pack].p->num_objects;
592 * As we de-duplicate by fanout value, we expect the fanout
593 * slices to be evenly distributed, with some noise. Hence,
594 * allocate slightly more than one 256th.
596 alloc_objects = alloc_fanout = total_objects > 3200 ? total_objects / 200 : 16;
598 ALLOC_ARRAY(entries_by_fanout, alloc_fanout);
599 ALLOC_ARRAY(deduplicated_entries, alloc_objects);
600 *nr_objects = 0;
602 for (cur_fanout = 0; cur_fanout < 256; cur_fanout++) {
603 uint32_t nr_fanout = 0;
605 if (m) {
606 uint32_t start = 0, end;
608 if (cur_fanout)
609 start = ntohl(m->chunk_oid_fanout[cur_fanout - 1]);
610 end = ntohl(m->chunk_oid_fanout[cur_fanout]);
612 for (cur_object = start; cur_object < end; cur_object++) {
613 ALLOC_GROW(entries_by_fanout, nr_fanout + 1, alloc_fanout);
614 nth_midxed_pack_midx_entry(m,
615 &entries_by_fanout[nr_fanout],
616 cur_object);
617 if (nth_midxed_pack_int_id(m, cur_object) == preferred_pack)
618 entries_by_fanout[nr_fanout].preferred = 1;
619 else
620 entries_by_fanout[nr_fanout].preferred = 0;
621 nr_fanout++;
625 for (cur_pack = start_pack; cur_pack < nr_packs; cur_pack++) {
626 uint32_t start = 0, end;
627 int preferred = cur_pack == preferred_pack;
629 if (cur_fanout)
630 start = get_pack_fanout(info[cur_pack].p, cur_fanout - 1);
631 end = get_pack_fanout(info[cur_pack].p, cur_fanout);
633 for (cur_object = start; cur_object < end; cur_object++) {
634 ALLOC_GROW(entries_by_fanout, nr_fanout + 1, alloc_fanout);
635 fill_pack_entry(cur_pack,
636 info[cur_pack].p,
637 cur_object,
638 &entries_by_fanout[nr_fanout],
639 preferred);
640 nr_fanout++;
644 QSORT(entries_by_fanout, nr_fanout, midx_oid_compare);
647 * The batch is now sorted by OID and then mtime (descending).
648 * Take only the first duplicate.
650 for (cur_object = 0; cur_object < nr_fanout; cur_object++) {
651 if (cur_object && oideq(&entries_by_fanout[cur_object - 1].oid,
652 &entries_by_fanout[cur_object].oid))
653 continue;
655 ALLOC_GROW(deduplicated_entries, *nr_objects + 1, alloc_objects);
656 memcpy(&deduplicated_entries[*nr_objects],
657 &entries_by_fanout[cur_object],
658 sizeof(struct pack_midx_entry));
659 (*nr_objects)++;
663 free(entries_by_fanout);
664 return deduplicated_entries;
667 static int write_midx_pack_names(struct hashfile *f, void *data)
669 struct write_midx_context *ctx = data;
670 uint32_t i;
671 unsigned char padding[MIDX_CHUNK_ALIGNMENT];
672 size_t written = 0;
674 for (i = 0; i < ctx->nr; i++) {
675 size_t writelen;
677 if (ctx->info[i].expired)
678 continue;
680 if (i && strcmp(ctx->info[i].pack_name, ctx->info[i - 1].pack_name) <= 0)
681 BUG("incorrect pack-file order: %s before %s",
682 ctx->info[i - 1].pack_name,
683 ctx->info[i].pack_name);
685 writelen = strlen(ctx->info[i].pack_name) + 1;
686 hashwrite(f, ctx->info[i].pack_name, writelen);
687 written += writelen;
690 /* add padding to be aligned */
691 i = MIDX_CHUNK_ALIGNMENT - (written % MIDX_CHUNK_ALIGNMENT);
692 if (i < MIDX_CHUNK_ALIGNMENT) {
693 memset(padding, 0, sizeof(padding));
694 hashwrite(f, padding, i);
697 return 0;
700 static int write_midx_oid_fanout(struct hashfile *f,
701 void *data)
703 struct write_midx_context *ctx = data;
704 struct pack_midx_entry *list = ctx->entries;
705 struct pack_midx_entry *last = ctx->entries + ctx->entries_nr;
706 uint32_t count = 0;
707 uint32_t i;
710 * Write the first-level table (the list is sorted,
711 * but we use a 256-entry lookup to be able to avoid
712 * having to do eight extra binary search iterations).
714 for (i = 0; i < 256; i++) {
715 struct pack_midx_entry *next = list;
717 while (next < last && next->oid.hash[0] == i) {
718 count++;
719 next++;
722 hashwrite_be32(f, count);
723 list = next;
726 return 0;
729 static int write_midx_oid_lookup(struct hashfile *f,
730 void *data)
732 struct write_midx_context *ctx = data;
733 unsigned char hash_len = the_hash_algo->rawsz;
734 struct pack_midx_entry *list = ctx->entries;
735 uint32_t i;
737 for (i = 0; i < ctx->entries_nr; i++) {
738 struct pack_midx_entry *obj = list++;
740 if (i < ctx->entries_nr - 1) {
741 struct pack_midx_entry *next = list;
742 if (oidcmp(&obj->oid, &next->oid) >= 0)
743 BUG("OIDs not in order: %s >= %s",
744 oid_to_hex(&obj->oid),
745 oid_to_hex(&next->oid));
748 hashwrite(f, obj->oid.hash, (int)hash_len);
751 return 0;
754 static int write_midx_object_offsets(struct hashfile *f,
755 void *data)
757 struct write_midx_context *ctx = data;
758 struct pack_midx_entry *list = ctx->entries;
759 uint32_t i, nr_large_offset = 0;
761 for (i = 0; i < ctx->entries_nr; i++) {
762 struct pack_midx_entry *obj = list++;
764 if (ctx->pack_perm[obj->pack_int_id] == PACK_EXPIRED)
765 BUG("object %s is in an expired pack with int-id %d",
766 oid_to_hex(&obj->oid),
767 obj->pack_int_id);
769 hashwrite_be32(f, ctx->pack_perm[obj->pack_int_id]);
771 if (ctx->large_offsets_needed && obj->offset >> 31)
772 hashwrite_be32(f, MIDX_LARGE_OFFSET_NEEDED | nr_large_offset++);
773 else if (!ctx->large_offsets_needed && obj->offset >> 32)
774 BUG("object %s requires a large offset (%"PRIx64") but the MIDX is not writing large offsets!",
775 oid_to_hex(&obj->oid),
776 obj->offset);
777 else
778 hashwrite_be32(f, (uint32_t)obj->offset);
781 return 0;
784 static int write_midx_large_offsets(struct hashfile *f,
785 void *data)
787 struct write_midx_context *ctx = data;
788 struct pack_midx_entry *list = ctx->entries;
789 struct pack_midx_entry *end = ctx->entries + ctx->entries_nr;
790 uint32_t nr_large_offset = ctx->num_large_offsets;
792 while (nr_large_offset) {
793 struct pack_midx_entry *obj;
794 uint64_t offset;
796 if (list >= end)
797 BUG("too many large-offset objects");
799 obj = list++;
800 offset = obj->offset;
802 if (!(offset >> 31))
803 continue;
805 hashwrite_be64(f, offset);
807 nr_large_offset--;
810 return 0;
813 struct midx_pack_order_data {
814 uint32_t nr;
815 uint32_t pack;
816 off_t offset;
819 static int midx_pack_order_cmp(const void *va, const void *vb)
821 const struct midx_pack_order_data *a = va, *b = vb;
822 if (a->pack < b->pack)
823 return -1;
824 else if (a->pack > b->pack)
825 return 1;
826 else if (a->offset < b->offset)
827 return -1;
828 else if (a->offset > b->offset)
829 return 1;
830 else
831 return 0;
834 static uint32_t *midx_pack_order(struct write_midx_context *ctx)
836 struct midx_pack_order_data *data;
837 uint32_t *pack_order;
838 uint32_t i;
840 ALLOC_ARRAY(data, ctx->entries_nr);
841 for (i = 0; i < ctx->entries_nr; i++) {
842 struct pack_midx_entry *e = &ctx->entries[i];
843 data[i].nr = i;
844 data[i].pack = ctx->pack_perm[e->pack_int_id];
845 if (!e->preferred)
846 data[i].pack |= (1U << 31);
847 data[i].offset = e->offset;
850 QSORT(data, ctx->entries_nr, midx_pack_order_cmp);
852 ALLOC_ARRAY(pack_order, ctx->entries_nr);
853 for (i = 0; i < ctx->entries_nr; i++)
854 pack_order[i] = data[i].nr;
855 free(data);
857 return pack_order;
860 static void write_midx_reverse_index(char *midx_name, unsigned char *midx_hash,
861 struct write_midx_context *ctx)
863 struct strbuf buf = STRBUF_INIT;
864 const char *tmp_file;
866 strbuf_addf(&buf, "%s-%s.rev", midx_name, hash_to_hex(midx_hash));
868 tmp_file = write_rev_file_order(NULL, ctx->pack_order, ctx->entries_nr,
869 midx_hash, WRITE_REV);
871 if (finalize_object_file(tmp_file, buf.buf))
872 die(_("cannot store reverse index file"));
874 strbuf_release(&buf);
877 static void clear_midx_files_ext(const char *object_dir, const char *ext,
878 unsigned char *keep_hash);
880 static int midx_checksum_valid(struct multi_pack_index *m)
882 return hashfile_checksum_valid(m->data, m->data_len);
885 static void prepare_midx_packing_data(struct packing_data *pdata,
886 struct write_midx_context *ctx)
888 uint32_t i;
890 memset(pdata, 0, sizeof(struct packing_data));
891 prepare_packing_data(the_repository, pdata);
893 for (i = 0; i < ctx->entries_nr; i++) {
894 struct pack_midx_entry *from = &ctx->entries[ctx->pack_order[i]];
895 struct object_entry *to = packlist_alloc(pdata, &from->oid);
897 oe_set_in_pack(pdata, to,
898 ctx->info[ctx->pack_perm[from->pack_int_id]].p);
902 static int add_ref_to_pending(const char *refname,
903 const struct object_id *oid,
904 int flag, void *cb_data)
906 struct rev_info *revs = (struct rev_info*)cb_data;
907 struct object *object;
909 if ((flag & REF_ISSYMREF) && (flag & REF_ISBROKEN)) {
910 warning("symbolic ref is dangling: %s", refname);
911 return 0;
914 object = parse_object_or_die(oid, refname);
915 if (object->type != OBJ_COMMIT)
916 return 0;
918 add_pending_object(revs, object, "");
919 if (bitmap_is_preferred_refname(revs->repo, refname))
920 object->flags |= NEEDS_BITMAP;
921 return 0;
924 struct bitmap_commit_cb {
925 struct commit **commits;
926 size_t commits_nr, commits_alloc;
928 struct write_midx_context *ctx;
931 static const struct object_id *bitmap_oid_access(size_t index,
932 const void *_entries)
934 const struct pack_midx_entry *entries = _entries;
935 return &entries[index].oid;
938 static void bitmap_show_commit(struct commit *commit, void *_data)
940 struct bitmap_commit_cb *data = _data;
941 int pos = oid_pos(&commit->object.oid, data->ctx->entries,
942 data->ctx->entries_nr,
943 bitmap_oid_access);
944 if (pos < 0)
945 return;
947 ALLOC_GROW(data->commits, data->commits_nr + 1, data->commits_alloc);
948 data->commits[data->commits_nr++] = commit;
951 static struct commit **find_commits_for_midx_bitmap(uint32_t *indexed_commits_nr_p,
952 struct write_midx_context *ctx)
954 struct rev_info revs;
955 struct bitmap_commit_cb cb = {0};
957 cb.ctx = ctx;
959 repo_init_revisions(the_repository, &revs, NULL);
960 setup_revisions(0, NULL, &revs, NULL);
961 for_each_ref(add_ref_to_pending, &revs);
964 * Skipping promisor objects here is intentional, since it only excludes
965 * them from the list of reachable commits that we want to select from
966 * when computing the selection of MIDX'd commits to receive bitmaps.
968 * Reachability bitmaps do require that their objects be closed under
969 * reachability, but fetching any objects missing from promisors at this
970 * point is too late. But, if one of those objects can be reached from
971 * an another object that is included in the bitmap, then we will
972 * complain later that we don't have reachability closure (and fail
973 * appropriately).
975 fetch_if_missing = 0;
976 revs.exclude_promisor_objects = 1;
978 if (prepare_revision_walk(&revs))
979 die(_("revision walk setup failed"));
981 traverse_commit_list(&revs, bitmap_show_commit, NULL, &cb);
982 if (indexed_commits_nr_p)
983 *indexed_commits_nr_p = cb.commits_nr;
985 return cb.commits;
988 static int write_midx_bitmap(char *midx_name, unsigned char *midx_hash,
989 struct write_midx_context *ctx,
990 unsigned flags)
992 struct packing_data pdata;
993 struct pack_idx_entry **index;
994 struct commit **commits = NULL;
995 uint32_t i, commits_nr;
996 char *bitmap_name = xstrfmt("%s-%s.bitmap", midx_name, hash_to_hex(midx_hash));
997 int ret;
999 prepare_midx_packing_data(&pdata, ctx);
1001 commits = find_commits_for_midx_bitmap(&commits_nr, ctx);
1004 * Build the MIDX-order index based on pdata.objects (which is already
1005 * in MIDX order; c.f., 'midx_pack_order_cmp()' for the definition of
1006 * this order).
1008 ALLOC_ARRAY(index, pdata.nr_objects);
1009 for (i = 0; i < pdata.nr_objects; i++)
1010 index[i] = &pdata.objects[i].idx;
1012 bitmap_writer_show_progress(flags & MIDX_PROGRESS);
1013 bitmap_writer_build_type_index(&pdata, index, pdata.nr_objects);
1016 * bitmap_writer_finish expects objects in lex order, but pack_order
1017 * gives us exactly that. use it directly instead of re-sorting the
1018 * array.
1020 * This changes the order of objects in 'index' between
1021 * bitmap_writer_build_type_index and bitmap_writer_finish.
1023 * The same re-ordering takes place in the single-pack bitmap code via
1024 * write_idx_file(), which is called by finish_tmp_packfile(), which
1025 * happens between bitmap_writer_build_type_index() and
1026 * bitmap_writer_finish().
1028 for (i = 0; i < pdata.nr_objects; i++)
1029 index[ctx->pack_order[i]] = &pdata.objects[i].idx;
1031 bitmap_writer_select_commits(commits, commits_nr, -1);
1032 ret = bitmap_writer_build(&pdata);
1033 if (ret < 0)
1034 goto cleanup;
1036 bitmap_writer_set_checksum(midx_hash);
1037 bitmap_writer_finish(index, pdata.nr_objects, bitmap_name, 0);
1039 cleanup:
1040 free(index);
1041 free(bitmap_name);
1042 return ret;
1045 static int write_midx_internal(const char *object_dir,
1046 struct string_list *packs_to_drop,
1047 const char *preferred_pack_name,
1048 unsigned flags)
1050 char *midx_name;
1051 unsigned char midx_hash[GIT_MAX_RAWSZ];
1052 uint32_t i;
1053 struct hashfile *f = NULL;
1054 struct lock_file lk;
1055 struct write_midx_context ctx = { 0 };
1056 struct multi_pack_index *cur;
1057 int pack_name_concat_len = 0;
1058 int dropped_packs = 0;
1059 int result = 0;
1060 struct chunkfile *cf;
1062 /* Ensure the given object_dir is local, or a known alternate. */
1063 find_odb(the_repository, object_dir);
1065 midx_name = get_midx_filename(object_dir);
1066 if (safe_create_leading_directories(midx_name))
1067 die_errno(_("unable to create leading directories of %s"),
1068 midx_name);
1070 for (cur = get_multi_pack_index(the_repository); cur; cur = cur->next) {
1071 if (!strcmp(object_dir, cur->object_dir)) {
1072 ctx.m = cur;
1073 break;
1077 if (ctx.m && !midx_checksum_valid(ctx.m)) {
1078 warning(_("ignoring existing multi-pack-index; checksum mismatch"));
1079 ctx.m = NULL;
1082 ctx.nr = 0;
1083 ctx.alloc = ctx.m ? ctx.m->num_packs : 16;
1084 ctx.info = NULL;
1085 ALLOC_ARRAY(ctx.info, ctx.alloc);
1087 if (ctx.m) {
1088 for (i = 0; i < ctx.m->num_packs; i++) {
1089 ALLOC_GROW(ctx.info, ctx.nr + 1, ctx.alloc);
1091 ctx.info[ctx.nr].orig_pack_int_id = i;
1092 ctx.info[ctx.nr].pack_name = xstrdup(ctx.m->pack_names[i]);
1093 ctx.info[ctx.nr].p = ctx.m->packs[i];
1094 ctx.info[ctx.nr].expired = 0;
1096 if (flags & MIDX_WRITE_REV_INDEX) {
1098 * If generating a reverse index, need to have
1099 * packed_git's loaded to compare their
1100 * mtimes and object count.
1102 if (prepare_midx_pack(the_repository, ctx.m, i)) {
1103 error(_("could not load pack"));
1104 result = 1;
1105 goto cleanup;
1108 if (open_pack_index(ctx.m->packs[i]))
1109 die(_("could not open index for %s"),
1110 ctx.m->packs[i]->pack_name);
1111 ctx.info[ctx.nr].p = ctx.m->packs[i];
1114 ctx.nr++;
1118 ctx.pack_paths_checked = 0;
1119 if (flags & MIDX_PROGRESS)
1120 ctx.progress = start_delayed_progress(_("Adding packfiles to multi-pack-index"), 0);
1121 else
1122 ctx.progress = NULL;
1124 for_each_file_in_pack_dir(object_dir, add_pack_to_midx, &ctx);
1125 stop_progress(&ctx.progress);
1127 if (ctx.m && ctx.nr == ctx.m->num_packs && !packs_to_drop) {
1128 struct bitmap_index *bitmap_git;
1129 int bitmap_exists;
1130 int want_bitmap = flags & MIDX_WRITE_BITMAP;
1132 bitmap_git = prepare_midx_bitmap_git(ctx.m);
1133 bitmap_exists = bitmap_git && bitmap_is_midx(bitmap_git);
1134 free_bitmap_index(bitmap_git);
1136 if (bitmap_exists || !want_bitmap) {
1138 * The correct MIDX already exists, and so does a
1139 * corresponding bitmap (or one wasn't requested).
1141 if (!want_bitmap)
1142 clear_midx_files_ext(object_dir, ".bitmap",
1143 NULL);
1144 goto cleanup;
1148 if (preferred_pack_name) {
1149 int found = 0;
1150 for (i = 0; i < ctx.nr; i++) {
1151 if (!cmp_idx_or_pack_name(preferred_pack_name,
1152 ctx.info[i].pack_name)) {
1153 ctx.preferred_pack_idx = i;
1154 found = 1;
1155 break;
1159 if (!found)
1160 warning(_("unknown preferred pack: '%s'"),
1161 preferred_pack_name);
1162 } else if (ctx.nr &&
1163 (flags & (MIDX_WRITE_REV_INDEX | MIDX_WRITE_BITMAP))) {
1164 struct packed_git *oldest = ctx.info[ctx.preferred_pack_idx].p;
1165 ctx.preferred_pack_idx = 0;
1167 if (packs_to_drop && packs_to_drop->nr)
1168 BUG("cannot write a MIDX bitmap during expiration");
1171 * set a preferred pack when writing a bitmap to ensure that
1172 * the pack from which the first object is selected in pseudo
1173 * pack-order has all of its objects selected from that pack
1174 * (and not another pack containing a duplicate)
1176 for (i = 1; i < ctx.nr; i++) {
1177 struct packed_git *p = ctx.info[i].p;
1179 if (!oldest->num_objects || p->mtime < oldest->mtime) {
1180 oldest = p;
1181 ctx.preferred_pack_idx = i;
1185 if (!oldest->num_objects) {
1187 * If all packs are empty; unset the preferred index.
1188 * This is acceptable since there will be no duplicate
1189 * objects to resolve, so the preferred value doesn't
1190 * matter.
1192 ctx.preferred_pack_idx = -1;
1194 } else {
1196 * otherwise don't mark any pack as preferred to avoid
1197 * interfering with expiration logic below
1199 ctx.preferred_pack_idx = -1;
1202 if (ctx.preferred_pack_idx > -1) {
1203 struct packed_git *preferred = ctx.info[ctx.preferred_pack_idx].p;
1204 if (!preferred->num_objects) {
1205 error(_("cannot select preferred pack %s with no objects"),
1206 preferred->pack_name);
1207 result = 1;
1208 goto cleanup;
1212 ctx.entries = get_sorted_entries(ctx.m, ctx.info, ctx.nr, &ctx.entries_nr,
1213 ctx.preferred_pack_idx);
1215 ctx.large_offsets_needed = 0;
1216 for (i = 0; i < ctx.entries_nr; i++) {
1217 if (ctx.entries[i].offset > 0x7fffffff)
1218 ctx.num_large_offsets++;
1219 if (ctx.entries[i].offset > 0xffffffff)
1220 ctx.large_offsets_needed = 1;
1223 QSORT(ctx.info, ctx.nr, pack_info_compare);
1225 if (packs_to_drop && packs_to_drop->nr) {
1226 int drop_index = 0;
1227 int missing_drops = 0;
1229 for (i = 0; i < ctx.nr && drop_index < packs_to_drop->nr; i++) {
1230 int cmp = strcmp(ctx.info[i].pack_name,
1231 packs_to_drop->items[drop_index].string);
1233 if (!cmp) {
1234 drop_index++;
1235 ctx.info[i].expired = 1;
1236 } else if (cmp > 0) {
1237 error(_("did not see pack-file %s to drop"),
1238 packs_to_drop->items[drop_index].string);
1239 drop_index++;
1240 missing_drops++;
1241 i--;
1242 } else {
1243 ctx.info[i].expired = 0;
1247 if (missing_drops) {
1248 result = 1;
1249 goto cleanup;
1254 * pack_perm stores a permutation between pack-int-ids from the
1255 * previous multi-pack-index to the new one we are writing:
1257 * pack_perm[old_id] = new_id
1259 ALLOC_ARRAY(ctx.pack_perm, ctx.nr);
1260 for (i = 0; i < ctx.nr; i++) {
1261 if (ctx.info[i].expired) {
1262 dropped_packs++;
1263 ctx.pack_perm[ctx.info[i].orig_pack_int_id] = PACK_EXPIRED;
1264 } else {
1265 ctx.pack_perm[ctx.info[i].orig_pack_int_id] = i - dropped_packs;
1269 for (i = 0; i < ctx.nr; i++) {
1270 if (!ctx.info[i].expired)
1271 pack_name_concat_len += strlen(ctx.info[i].pack_name) + 1;
1274 /* Check that the preferred pack wasn't expired (if given). */
1275 if (preferred_pack_name) {
1276 struct pack_info *preferred = bsearch(preferred_pack_name,
1277 ctx.info, ctx.nr,
1278 sizeof(*ctx.info),
1279 idx_or_pack_name_cmp);
1280 if (preferred) {
1281 uint32_t perm = ctx.pack_perm[preferred->orig_pack_int_id];
1282 if (perm == PACK_EXPIRED)
1283 warning(_("preferred pack '%s' is expired"),
1284 preferred_pack_name);
1288 if (pack_name_concat_len % MIDX_CHUNK_ALIGNMENT)
1289 pack_name_concat_len += MIDX_CHUNK_ALIGNMENT -
1290 (pack_name_concat_len % MIDX_CHUNK_ALIGNMENT);
1292 hold_lock_file_for_update(&lk, midx_name, LOCK_DIE_ON_ERROR);
1293 f = hashfd(get_lock_file_fd(&lk), get_lock_file_path(&lk));
1295 if (ctx.nr - dropped_packs == 0) {
1296 error(_("no pack files to index."));
1297 result = 1;
1298 goto cleanup;
1301 cf = init_chunkfile(f);
1303 add_chunk(cf, MIDX_CHUNKID_PACKNAMES, pack_name_concat_len,
1304 write_midx_pack_names);
1305 add_chunk(cf, MIDX_CHUNKID_OIDFANOUT, MIDX_CHUNK_FANOUT_SIZE,
1306 write_midx_oid_fanout);
1307 add_chunk(cf, MIDX_CHUNKID_OIDLOOKUP,
1308 (size_t)ctx.entries_nr * the_hash_algo->rawsz,
1309 write_midx_oid_lookup);
1310 add_chunk(cf, MIDX_CHUNKID_OBJECTOFFSETS,
1311 (size_t)ctx.entries_nr * MIDX_CHUNK_OFFSET_WIDTH,
1312 write_midx_object_offsets);
1314 if (ctx.large_offsets_needed)
1315 add_chunk(cf, MIDX_CHUNKID_LARGEOFFSETS,
1316 (size_t)ctx.num_large_offsets * MIDX_CHUNK_LARGE_OFFSET_WIDTH,
1317 write_midx_large_offsets);
1319 write_midx_header(f, get_num_chunks(cf), ctx.nr - dropped_packs);
1320 write_chunkfile(cf, &ctx);
1322 finalize_hashfile(f, midx_hash, CSUM_FSYNC | CSUM_HASH_IN_STREAM);
1323 free_chunkfile(cf);
1325 if (flags & (MIDX_WRITE_REV_INDEX | MIDX_WRITE_BITMAP))
1326 ctx.pack_order = midx_pack_order(&ctx);
1328 if (flags & MIDX_WRITE_REV_INDEX)
1329 write_midx_reverse_index(midx_name, midx_hash, &ctx);
1330 if (flags & MIDX_WRITE_BITMAP) {
1331 if (write_midx_bitmap(midx_name, midx_hash, &ctx, flags) < 0) {
1332 error(_("could not write multi-pack bitmap"));
1333 result = 1;
1334 goto cleanup;
1338 if (ctx.m)
1339 close_object_store(the_repository->objects);
1341 commit_lock_file(&lk);
1343 clear_midx_files_ext(object_dir, ".bitmap", midx_hash);
1344 clear_midx_files_ext(object_dir, ".rev", midx_hash);
1346 cleanup:
1347 for (i = 0; i < ctx.nr; i++) {
1348 if (ctx.info[i].p) {
1349 close_pack(ctx.info[i].p);
1350 free(ctx.info[i].p);
1352 free(ctx.info[i].pack_name);
1355 free(ctx.info);
1356 free(ctx.entries);
1357 free(ctx.pack_perm);
1358 free(ctx.pack_order);
1359 free(midx_name);
1361 return result;
1364 int write_midx_file(const char *object_dir,
1365 const char *preferred_pack_name,
1366 unsigned flags)
1368 return write_midx_internal(object_dir, NULL, preferred_pack_name, flags);
1371 struct clear_midx_data {
1372 char *keep;
1373 const char *ext;
1376 static void clear_midx_file_ext(const char *full_path, size_t full_path_len,
1377 const char *file_name, void *_data)
1379 struct clear_midx_data *data = _data;
1381 if (!(starts_with(file_name, "multi-pack-index-") &&
1382 ends_with(file_name, data->ext)))
1383 return;
1384 if (data->keep && !strcmp(data->keep, file_name))
1385 return;
1387 if (unlink(full_path))
1388 die_errno(_("failed to remove %s"), full_path);
1391 static void clear_midx_files_ext(const char *object_dir, const char *ext,
1392 unsigned char *keep_hash)
1394 struct clear_midx_data data;
1395 memset(&data, 0, sizeof(struct clear_midx_data));
1397 if (keep_hash)
1398 data.keep = xstrfmt("multi-pack-index-%s%s",
1399 hash_to_hex(keep_hash), ext);
1400 data.ext = ext;
1402 for_each_file_in_pack_dir(object_dir,
1403 clear_midx_file_ext,
1404 &data);
1406 free(data.keep);
1409 void clear_midx_file(struct repository *r)
1411 char *midx = get_midx_filename(r->objects->odb->path);
1413 if (r->objects && r->objects->multi_pack_index) {
1414 close_midx(r->objects->multi_pack_index);
1415 r->objects->multi_pack_index = NULL;
1418 if (remove_path(midx))
1419 die(_("failed to clear multi-pack-index at %s"), midx);
1421 clear_midx_files_ext(r->objects->odb->path, ".bitmap", NULL);
1422 clear_midx_files_ext(r->objects->odb->path, ".rev", NULL);
1424 free(midx);
1427 static int verify_midx_error;
1429 __attribute__((format (printf, 1, 2)))
1430 static void midx_report(const char *fmt, ...)
1432 va_list ap;
1433 verify_midx_error = 1;
1434 va_start(ap, fmt);
1435 vfprintf(stderr, fmt, ap);
1436 fprintf(stderr, "\n");
1437 va_end(ap);
1440 struct pair_pos_vs_id
1442 uint32_t pos;
1443 uint32_t pack_int_id;
1446 static int compare_pair_pos_vs_id(const void *_a, const void *_b)
1448 struct pair_pos_vs_id *a = (struct pair_pos_vs_id *)_a;
1449 struct pair_pos_vs_id *b = (struct pair_pos_vs_id *)_b;
1451 return b->pack_int_id - a->pack_int_id;
1455 * Limit calls to display_progress() for performance reasons.
1456 * The interval here was arbitrarily chosen.
1458 #define SPARSE_PROGRESS_INTERVAL (1 << 12)
1459 #define midx_display_sparse_progress(progress, n) \
1460 do { \
1461 uint64_t _n = (n); \
1462 if ((_n & (SPARSE_PROGRESS_INTERVAL - 1)) == 0) \
1463 display_progress(progress, _n); \
1464 } while (0)
1466 int verify_midx_file(struct repository *r, const char *object_dir, unsigned flags)
1468 struct pair_pos_vs_id *pairs = NULL;
1469 uint32_t i;
1470 struct progress *progress = NULL;
1471 struct multi_pack_index *m = load_multi_pack_index(object_dir, 1);
1472 verify_midx_error = 0;
1474 if (!m) {
1475 int result = 0;
1476 struct stat sb;
1477 char *filename = get_midx_filename(object_dir);
1478 if (!stat(filename, &sb)) {
1479 error(_("multi-pack-index file exists, but failed to parse"));
1480 result = 1;
1482 free(filename);
1483 return result;
1486 if (!midx_checksum_valid(m))
1487 midx_report(_("incorrect checksum"));
1489 if (flags & MIDX_PROGRESS)
1490 progress = start_delayed_progress(_("Looking for referenced packfiles"),
1491 m->num_packs);
1492 for (i = 0; i < m->num_packs; i++) {
1493 if (prepare_midx_pack(r, m, i))
1494 midx_report("failed to load pack in position %d", i);
1496 display_progress(progress, i + 1);
1498 stop_progress(&progress);
1500 for (i = 0; i < 255; i++) {
1501 uint32_t oid_fanout1 = ntohl(m->chunk_oid_fanout[i]);
1502 uint32_t oid_fanout2 = ntohl(m->chunk_oid_fanout[i + 1]);
1504 if (oid_fanout1 > oid_fanout2)
1505 midx_report(_("oid fanout out of order: fanout[%d] = %"PRIx32" > %"PRIx32" = fanout[%d]"),
1506 i, oid_fanout1, oid_fanout2, i + 1);
1509 if (m->num_objects == 0) {
1510 midx_report(_("the midx contains no oid"));
1512 * Remaining tests assume that we have objects, so we can
1513 * return here.
1515 return verify_midx_error;
1518 if (flags & MIDX_PROGRESS)
1519 progress = start_sparse_progress(_("Verifying OID order in multi-pack-index"),
1520 m->num_objects - 1);
1521 for (i = 0; i < m->num_objects - 1; i++) {
1522 struct object_id oid1, oid2;
1524 nth_midxed_object_oid(&oid1, m, i);
1525 nth_midxed_object_oid(&oid2, m, i + 1);
1527 if (oidcmp(&oid1, &oid2) >= 0)
1528 midx_report(_("oid lookup out of order: oid[%d] = %s >= %s = oid[%d]"),
1529 i, oid_to_hex(&oid1), oid_to_hex(&oid2), i + 1);
1531 midx_display_sparse_progress(progress, i + 1);
1533 stop_progress(&progress);
1536 * Create an array mapping each object to its packfile id. Sort it
1537 * to group the objects by packfile. Use this permutation to visit
1538 * each of the objects and only require 1 packfile to be open at a
1539 * time.
1541 ALLOC_ARRAY(pairs, m->num_objects);
1542 for (i = 0; i < m->num_objects; i++) {
1543 pairs[i].pos = i;
1544 pairs[i].pack_int_id = nth_midxed_pack_int_id(m, i);
1547 if (flags & MIDX_PROGRESS)
1548 progress = start_sparse_progress(_("Sorting objects by packfile"),
1549 m->num_objects);
1550 display_progress(progress, 0); /* TODO: Measure QSORT() progress */
1551 QSORT(pairs, m->num_objects, compare_pair_pos_vs_id);
1552 stop_progress(&progress);
1554 if (flags & MIDX_PROGRESS)
1555 progress = start_sparse_progress(_("Verifying object offsets"), m->num_objects);
1556 for (i = 0; i < m->num_objects; i++) {
1557 struct object_id oid;
1558 struct pack_entry e;
1559 off_t m_offset, p_offset;
1561 if (i > 0 && pairs[i-1].pack_int_id != pairs[i].pack_int_id &&
1562 m->packs[pairs[i-1].pack_int_id])
1564 close_pack_fd(m->packs[pairs[i-1].pack_int_id]);
1565 close_pack_index(m->packs[pairs[i-1].pack_int_id]);
1568 nth_midxed_object_oid(&oid, m, pairs[i].pos);
1570 if (!fill_midx_entry(r, &oid, &e, m)) {
1571 midx_report(_("failed to load pack entry for oid[%d] = %s"),
1572 pairs[i].pos, oid_to_hex(&oid));
1573 continue;
1576 if (open_pack_index(e.p)) {
1577 midx_report(_("failed to load pack-index for packfile %s"),
1578 e.p->pack_name);
1579 break;
1582 m_offset = e.offset;
1583 p_offset = find_pack_entry_one(oid.hash, e.p);
1585 if (m_offset != p_offset)
1586 midx_report(_("incorrect object offset for oid[%d] = %s: %"PRIx64" != %"PRIx64),
1587 pairs[i].pos, oid_to_hex(&oid), m_offset, p_offset);
1589 midx_display_sparse_progress(progress, i + 1);
1591 stop_progress(&progress);
1593 free(pairs);
1595 return verify_midx_error;
1598 int expire_midx_packs(struct repository *r, const char *object_dir, unsigned flags)
1600 uint32_t i, *count, result = 0;
1601 struct string_list packs_to_drop = STRING_LIST_INIT_DUP;
1602 struct multi_pack_index *m = load_multi_pack_index(object_dir, 1);
1603 struct progress *progress = NULL;
1605 if (!m)
1606 return 0;
1608 CALLOC_ARRAY(count, m->num_packs);
1610 if (flags & MIDX_PROGRESS)
1611 progress = start_delayed_progress(_("Counting referenced objects"),
1612 m->num_objects);
1613 for (i = 0; i < m->num_objects; i++) {
1614 int pack_int_id = nth_midxed_pack_int_id(m, i);
1615 count[pack_int_id]++;
1616 display_progress(progress, i + 1);
1618 stop_progress(&progress);
1620 if (flags & MIDX_PROGRESS)
1621 progress = start_delayed_progress(_("Finding and deleting unreferenced packfiles"),
1622 m->num_packs);
1623 for (i = 0; i < m->num_packs; i++) {
1624 char *pack_name;
1625 display_progress(progress, i + 1);
1627 if (count[i])
1628 continue;
1630 if (prepare_midx_pack(r, m, i))
1631 continue;
1633 if (m->packs[i]->pack_keep)
1634 continue;
1636 pack_name = xstrdup(m->packs[i]->pack_name);
1637 close_pack(m->packs[i]);
1639 string_list_insert(&packs_to_drop, m->pack_names[i]);
1640 unlink_pack_path(pack_name, 0);
1641 free(pack_name);
1643 stop_progress(&progress);
1645 free(count);
1647 if (packs_to_drop.nr) {
1648 result = write_midx_internal(object_dir, &packs_to_drop, NULL, flags);
1649 m = NULL;
1652 string_list_clear(&packs_to_drop, 0);
1653 return result;
1656 struct repack_info {
1657 timestamp_t mtime;
1658 uint32_t referenced_objects;
1659 uint32_t pack_int_id;
1662 static int compare_by_mtime(const void *a_, const void *b_)
1664 const struct repack_info *a, *b;
1666 a = (const struct repack_info *)a_;
1667 b = (const struct repack_info *)b_;
1669 if (a->mtime < b->mtime)
1670 return -1;
1671 if (a->mtime > b->mtime)
1672 return 1;
1673 return 0;
1676 static int fill_included_packs_all(struct repository *r,
1677 struct multi_pack_index *m,
1678 unsigned char *include_pack)
1680 uint32_t i, count = 0;
1681 int pack_kept_objects = 0;
1683 repo_config_get_bool(r, "repack.packkeptobjects", &pack_kept_objects);
1685 for (i = 0; i < m->num_packs; i++) {
1686 if (prepare_midx_pack(r, m, i))
1687 continue;
1688 if (!pack_kept_objects && m->packs[i]->pack_keep)
1689 continue;
1691 include_pack[i] = 1;
1692 count++;
1695 return count < 2;
1698 static int fill_included_packs_batch(struct repository *r,
1699 struct multi_pack_index *m,
1700 unsigned char *include_pack,
1701 size_t batch_size)
1703 uint32_t i, packs_to_repack;
1704 size_t total_size;
1705 struct repack_info *pack_info = xcalloc(m->num_packs, sizeof(struct repack_info));
1706 int pack_kept_objects = 0;
1708 repo_config_get_bool(r, "repack.packkeptobjects", &pack_kept_objects);
1710 for (i = 0; i < m->num_packs; i++) {
1711 pack_info[i].pack_int_id = i;
1713 if (prepare_midx_pack(r, m, i))
1714 continue;
1716 pack_info[i].mtime = m->packs[i]->mtime;
1719 for (i = 0; batch_size && i < m->num_objects; i++) {
1720 uint32_t pack_int_id = nth_midxed_pack_int_id(m, i);
1721 pack_info[pack_int_id].referenced_objects++;
1724 QSORT(pack_info, m->num_packs, compare_by_mtime);
1726 total_size = 0;
1727 packs_to_repack = 0;
1728 for (i = 0; total_size < batch_size && i < m->num_packs; i++) {
1729 int pack_int_id = pack_info[i].pack_int_id;
1730 struct packed_git *p = m->packs[pack_int_id];
1731 size_t expected_size;
1733 if (!p)
1734 continue;
1735 if (!pack_kept_objects && p->pack_keep)
1736 continue;
1737 if (open_pack_index(p) || !p->num_objects)
1738 continue;
1740 expected_size = (size_t)(p->pack_size
1741 * pack_info[i].referenced_objects);
1742 expected_size /= p->num_objects;
1744 if (expected_size >= batch_size)
1745 continue;
1747 packs_to_repack++;
1748 total_size += expected_size;
1749 include_pack[pack_int_id] = 1;
1752 free(pack_info);
1754 if (packs_to_repack < 2)
1755 return 1;
1757 return 0;
1760 int midx_repack(struct repository *r, const char *object_dir, size_t batch_size, unsigned flags)
1762 int result = 0;
1763 uint32_t i;
1764 unsigned char *include_pack;
1765 struct child_process cmd = CHILD_PROCESS_INIT;
1766 FILE *cmd_in;
1767 struct strbuf base_name = STRBUF_INIT;
1768 struct multi_pack_index *m = load_multi_pack_index(object_dir, 1);
1771 * When updating the default for these configuration
1772 * variables in builtin/repack.c, these must be adjusted
1773 * to match.
1775 int delta_base_offset = 1;
1776 int use_delta_islands = 0;
1778 if (!m)
1779 return 0;
1781 CALLOC_ARRAY(include_pack, m->num_packs);
1783 if (batch_size) {
1784 if (fill_included_packs_batch(r, m, include_pack, batch_size))
1785 goto cleanup;
1786 } else if (fill_included_packs_all(r, m, include_pack))
1787 goto cleanup;
1789 repo_config_get_bool(r, "repack.usedeltabaseoffset", &delta_base_offset);
1790 repo_config_get_bool(r, "repack.usedeltaislands", &use_delta_islands);
1792 strvec_push(&cmd.args, "pack-objects");
1794 strbuf_addstr(&base_name, object_dir);
1795 strbuf_addstr(&base_name, "/pack/pack");
1796 strvec_push(&cmd.args, base_name.buf);
1798 if (delta_base_offset)
1799 strvec_push(&cmd.args, "--delta-base-offset");
1800 if (use_delta_islands)
1801 strvec_push(&cmd.args, "--delta-islands");
1803 if (flags & MIDX_PROGRESS)
1804 strvec_push(&cmd.args, "--progress");
1805 else
1806 strvec_push(&cmd.args, "-q");
1808 strbuf_release(&base_name);
1810 cmd.git_cmd = 1;
1811 cmd.in = cmd.out = -1;
1813 if (start_command(&cmd)) {
1814 error(_("could not start pack-objects"));
1815 result = 1;
1816 goto cleanup;
1819 cmd_in = xfdopen(cmd.in, "w");
1821 for (i = 0; i < m->num_objects; i++) {
1822 struct object_id oid;
1823 uint32_t pack_int_id = nth_midxed_pack_int_id(m, i);
1825 if (!include_pack[pack_int_id])
1826 continue;
1828 nth_midxed_object_oid(&oid, m, i);
1829 fprintf(cmd_in, "%s\n", oid_to_hex(&oid));
1831 fclose(cmd_in);
1833 if (finish_command(&cmd)) {
1834 error(_("could not finish pack-objects"));
1835 result = 1;
1836 goto cleanup;
1839 result = write_midx_internal(object_dir, NULL, NULL, flags);
1840 m = NULL;
1842 cleanup:
1843 if (m)
1844 close_midx(m);
1845 free(include_pack);
1846 return result;