l10n: ko: fix typos found by git-po-helper
[alt-git.git] / midx.c
blob8433086ac13c91a5c00fd4c97ef72341b2c06e3a
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;
464 struct string_list *to_include;
467 static void add_pack_to_midx(const char *full_path, size_t full_path_len,
468 const char *file_name, void *data)
470 struct write_midx_context *ctx = data;
472 if (ends_with(file_name, ".idx")) {
473 display_progress(ctx->progress, ++ctx->pack_paths_checked);
475 * Note that at most one of ctx->m and ctx->to_include are set,
476 * so we are testing midx_contains_pack() and
477 * string_list_has_string() independently (guarded by the
478 * appropriate NULL checks).
480 * We could support passing to_include while reusing an existing
481 * MIDX, but don't currently since the reuse process drags
482 * forward all packs from an existing MIDX (without checking
483 * whether or not they appear in the to_include list).
485 * If we added support for that, these next two conditional
486 * should be performed independently (likely checking
487 * to_include before the existing MIDX).
489 if (ctx->m && midx_contains_pack(ctx->m, file_name))
490 return;
491 else if (ctx->to_include &&
492 !string_list_has_string(ctx->to_include, file_name))
493 return;
495 ALLOC_GROW(ctx->info, ctx->nr + 1, ctx->alloc);
497 ctx->info[ctx->nr].p = add_packed_git(full_path,
498 full_path_len,
501 if (!ctx->info[ctx->nr].p) {
502 warning(_("failed to add packfile '%s'"),
503 full_path);
504 return;
507 if (open_pack_index(ctx->info[ctx->nr].p)) {
508 warning(_("failed to open pack-index '%s'"),
509 full_path);
510 close_pack(ctx->info[ctx->nr].p);
511 FREE_AND_NULL(ctx->info[ctx->nr].p);
512 return;
515 ctx->info[ctx->nr].pack_name = xstrdup(file_name);
516 ctx->info[ctx->nr].orig_pack_int_id = ctx->nr;
517 ctx->info[ctx->nr].expired = 0;
518 ctx->nr++;
522 struct pack_midx_entry {
523 struct object_id oid;
524 uint32_t pack_int_id;
525 time_t pack_mtime;
526 uint64_t offset;
527 unsigned preferred : 1;
530 static int midx_oid_compare(const void *_a, const void *_b)
532 const struct pack_midx_entry *a = (const struct pack_midx_entry *)_a;
533 const struct pack_midx_entry *b = (const struct pack_midx_entry *)_b;
534 int cmp = oidcmp(&a->oid, &b->oid);
536 if (cmp)
537 return cmp;
539 /* Sort objects in a preferred pack first when multiple copies exist. */
540 if (a->preferred > b->preferred)
541 return -1;
542 if (a->preferred < b->preferred)
543 return 1;
545 if (a->pack_mtime > b->pack_mtime)
546 return -1;
547 else if (a->pack_mtime < b->pack_mtime)
548 return 1;
550 return a->pack_int_id - b->pack_int_id;
553 static int nth_midxed_pack_midx_entry(struct multi_pack_index *m,
554 struct pack_midx_entry *e,
555 uint32_t pos)
557 if (pos >= m->num_objects)
558 return 1;
560 nth_midxed_object_oid(&e->oid, m, pos);
561 e->pack_int_id = nth_midxed_pack_int_id(m, pos);
562 e->offset = nth_midxed_offset(m, pos);
564 /* consider objects in midx to be from "old" packs */
565 e->pack_mtime = 0;
566 return 0;
569 static void fill_pack_entry(uint32_t pack_int_id,
570 struct packed_git *p,
571 uint32_t cur_object,
572 struct pack_midx_entry *entry,
573 int preferred)
575 if (nth_packed_object_id(&entry->oid, p, cur_object) < 0)
576 die(_("failed to locate object %d in packfile"), cur_object);
578 entry->pack_int_id = pack_int_id;
579 entry->pack_mtime = p->mtime;
581 entry->offset = nth_packed_object_offset(p, cur_object);
582 entry->preferred = !!preferred;
586 * It is possible to artificially get into a state where there are many
587 * duplicate copies of objects. That can create high memory pressure if
588 * we are to create a list of all objects before de-duplication. To reduce
589 * this memory pressure without a significant performance drop, automatically
590 * group objects by the first byte of their object id. Use the IDX fanout
591 * tables to group the data, copy to a local array, then sort.
593 * Copy only the de-duplicated entries (selected by most-recent modified time
594 * of a packfile containing the object).
596 static struct pack_midx_entry *get_sorted_entries(struct multi_pack_index *m,
597 struct pack_info *info,
598 uint32_t nr_packs,
599 uint32_t *nr_objects,
600 int preferred_pack)
602 uint32_t cur_fanout, cur_pack, cur_object;
603 uint32_t alloc_fanout, alloc_objects, total_objects = 0;
604 struct pack_midx_entry *entries_by_fanout = NULL;
605 struct pack_midx_entry *deduplicated_entries = NULL;
606 uint32_t start_pack = m ? m->num_packs : 0;
608 for (cur_pack = start_pack; cur_pack < nr_packs; cur_pack++)
609 total_objects += info[cur_pack].p->num_objects;
612 * As we de-duplicate by fanout value, we expect the fanout
613 * slices to be evenly distributed, with some noise. Hence,
614 * allocate slightly more than one 256th.
616 alloc_objects = alloc_fanout = total_objects > 3200 ? total_objects / 200 : 16;
618 ALLOC_ARRAY(entries_by_fanout, alloc_fanout);
619 ALLOC_ARRAY(deduplicated_entries, alloc_objects);
620 *nr_objects = 0;
622 for (cur_fanout = 0; cur_fanout < 256; cur_fanout++) {
623 uint32_t nr_fanout = 0;
625 if (m) {
626 uint32_t start = 0, end;
628 if (cur_fanout)
629 start = ntohl(m->chunk_oid_fanout[cur_fanout - 1]);
630 end = ntohl(m->chunk_oid_fanout[cur_fanout]);
632 for (cur_object = start; cur_object < end; cur_object++) {
633 ALLOC_GROW(entries_by_fanout, nr_fanout + 1, alloc_fanout);
634 nth_midxed_pack_midx_entry(m,
635 &entries_by_fanout[nr_fanout],
636 cur_object);
637 if (nth_midxed_pack_int_id(m, cur_object) == preferred_pack)
638 entries_by_fanout[nr_fanout].preferred = 1;
639 else
640 entries_by_fanout[nr_fanout].preferred = 0;
641 nr_fanout++;
645 for (cur_pack = start_pack; cur_pack < nr_packs; cur_pack++) {
646 uint32_t start = 0, end;
647 int preferred = cur_pack == preferred_pack;
649 if (cur_fanout)
650 start = get_pack_fanout(info[cur_pack].p, cur_fanout - 1);
651 end = get_pack_fanout(info[cur_pack].p, cur_fanout);
653 for (cur_object = start; cur_object < end; cur_object++) {
654 ALLOC_GROW(entries_by_fanout, nr_fanout + 1, alloc_fanout);
655 fill_pack_entry(cur_pack,
656 info[cur_pack].p,
657 cur_object,
658 &entries_by_fanout[nr_fanout],
659 preferred);
660 nr_fanout++;
664 QSORT(entries_by_fanout, nr_fanout, midx_oid_compare);
667 * The batch is now sorted by OID and then mtime (descending).
668 * Take only the first duplicate.
670 for (cur_object = 0; cur_object < nr_fanout; cur_object++) {
671 if (cur_object && oideq(&entries_by_fanout[cur_object - 1].oid,
672 &entries_by_fanout[cur_object].oid))
673 continue;
675 ALLOC_GROW(deduplicated_entries, *nr_objects + 1, alloc_objects);
676 memcpy(&deduplicated_entries[*nr_objects],
677 &entries_by_fanout[cur_object],
678 sizeof(struct pack_midx_entry));
679 (*nr_objects)++;
683 free(entries_by_fanout);
684 return deduplicated_entries;
687 static int write_midx_pack_names(struct hashfile *f, void *data)
689 struct write_midx_context *ctx = data;
690 uint32_t i;
691 unsigned char padding[MIDX_CHUNK_ALIGNMENT];
692 size_t written = 0;
694 for (i = 0; i < ctx->nr; i++) {
695 size_t writelen;
697 if (ctx->info[i].expired)
698 continue;
700 if (i && strcmp(ctx->info[i].pack_name, ctx->info[i - 1].pack_name) <= 0)
701 BUG("incorrect pack-file order: %s before %s",
702 ctx->info[i - 1].pack_name,
703 ctx->info[i].pack_name);
705 writelen = strlen(ctx->info[i].pack_name) + 1;
706 hashwrite(f, ctx->info[i].pack_name, writelen);
707 written += writelen;
710 /* add padding to be aligned */
711 i = MIDX_CHUNK_ALIGNMENT - (written % MIDX_CHUNK_ALIGNMENT);
712 if (i < MIDX_CHUNK_ALIGNMENT) {
713 memset(padding, 0, sizeof(padding));
714 hashwrite(f, padding, i);
717 return 0;
720 static int write_midx_oid_fanout(struct hashfile *f,
721 void *data)
723 struct write_midx_context *ctx = data;
724 struct pack_midx_entry *list = ctx->entries;
725 struct pack_midx_entry *last = ctx->entries + ctx->entries_nr;
726 uint32_t count = 0;
727 uint32_t i;
730 * Write the first-level table (the list is sorted,
731 * but we use a 256-entry lookup to be able to avoid
732 * having to do eight extra binary search iterations).
734 for (i = 0; i < 256; i++) {
735 struct pack_midx_entry *next = list;
737 while (next < last && next->oid.hash[0] == i) {
738 count++;
739 next++;
742 hashwrite_be32(f, count);
743 list = next;
746 return 0;
749 static int write_midx_oid_lookup(struct hashfile *f,
750 void *data)
752 struct write_midx_context *ctx = data;
753 unsigned char hash_len = the_hash_algo->rawsz;
754 struct pack_midx_entry *list = ctx->entries;
755 uint32_t i;
757 for (i = 0; i < ctx->entries_nr; i++) {
758 struct pack_midx_entry *obj = list++;
760 if (i < ctx->entries_nr - 1) {
761 struct pack_midx_entry *next = list;
762 if (oidcmp(&obj->oid, &next->oid) >= 0)
763 BUG("OIDs not in order: %s >= %s",
764 oid_to_hex(&obj->oid),
765 oid_to_hex(&next->oid));
768 hashwrite(f, obj->oid.hash, (int)hash_len);
771 return 0;
774 static int write_midx_object_offsets(struct hashfile *f,
775 void *data)
777 struct write_midx_context *ctx = data;
778 struct pack_midx_entry *list = ctx->entries;
779 uint32_t i, nr_large_offset = 0;
781 for (i = 0; i < ctx->entries_nr; i++) {
782 struct pack_midx_entry *obj = list++;
784 if (ctx->pack_perm[obj->pack_int_id] == PACK_EXPIRED)
785 BUG("object %s is in an expired pack with int-id %d",
786 oid_to_hex(&obj->oid),
787 obj->pack_int_id);
789 hashwrite_be32(f, ctx->pack_perm[obj->pack_int_id]);
791 if (ctx->large_offsets_needed && obj->offset >> 31)
792 hashwrite_be32(f, MIDX_LARGE_OFFSET_NEEDED | nr_large_offset++);
793 else if (!ctx->large_offsets_needed && obj->offset >> 32)
794 BUG("object %s requires a large offset (%"PRIx64") but the MIDX is not writing large offsets!",
795 oid_to_hex(&obj->oid),
796 obj->offset);
797 else
798 hashwrite_be32(f, (uint32_t)obj->offset);
801 return 0;
804 static int write_midx_large_offsets(struct hashfile *f,
805 void *data)
807 struct write_midx_context *ctx = data;
808 struct pack_midx_entry *list = ctx->entries;
809 struct pack_midx_entry *end = ctx->entries + ctx->entries_nr;
810 uint32_t nr_large_offset = ctx->num_large_offsets;
812 while (nr_large_offset) {
813 struct pack_midx_entry *obj;
814 uint64_t offset;
816 if (list >= end)
817 BUG("too many large-offset objects");
819 obj = list++;
820 offset = obj->offset;
822 if (!(offset >> 31))
823 continue;
825 hashwrite_be64(f, offset);
827 nr_large_offset--;
830 return 0;
833 struct midx_pack_order_data {
834 uint32_t nr;
835 uint32_t pack;
836 off_t offset;
839 static int midx_pack_order_cmp(const void *va, const void *vb)
841 const struct midx_pack_order_data *a = va, *b = vb;
842 if (a->pack < b->pack)
843 return -1;
844 else if (a->pack > b->pack)
845 return 1;
846 else if (a->offset < b->offset)
847 return -1;
848 else if (a->offset > b->offset)
849 return 1;
850 else
851 return 0;
854 static uint32_t *midx_pack_order(struct write_midx_context *ctx)
856 struct midx_pack_order_data *data;
857 uint32_t *pack_order;
858 uint32_t i;
860 ALLOC_ARRAY(data, ctx->entries_nr);
861 for (i = 0; i < ctx->entries_nr; i++) {
862 struct pack_midx_entry *e = &ctx->entries[i];
863 data[i].nr = i;
864 data[i].pack = ctx->pack_perm[e->pack_int_id];
865 if (!e->preferred)
866 data[i].pack |= (1U << 31);
867 data[i].offset = e->offset;
870 QSORT(data, ctx->entries_nr, midx_pack_order_cmp);
872 ALLOC_ARRAY(pack_order, ctx->entries_nr);
873 for (i = 0; i < ctx->entries_nr; i++)
874 pack_order[i] = data[i].nr;
875 free(data);
877 return pack_order;
880 static void write_midx_reverse_index(char *midx_name, unsigned char *midx_hash,
881 struct write_midx_context *ctx)
883 struct strbuf buf = STRBUF_INIT;
884 const char *tmp_file;
886 strbuf_addf(&buf, "%s-%s.rev", midx_name, hash_to_hex(midx_hash));
888 tmp_file = write_rev_file_order(NULL, ctx->pack_order, ctx->entries_nr,
889 midx_hash, WRITE_REV);
891 if (finalize_object_file(tmp_file, buf.buf))
892 die(_("cannot store reverse index file"));
894 strbuf_release(&buf);
897 static void clear_midx_files_ext(const char *object_dir, const char *ext,
898 unsigned char *keep_hash);
900 static int midx_checksum_valid(struct multi_pack_index *m)
902 return hashfile_checksum_valid(m->data, m->data_len);
905 static void prepare_midx_packing_data(struct packing_data *pdata,
906 struct write_midx_context *ctx)
908 uint32_t i;
910 memset(pdata, 0, sizeof(struct packing_data));
911 prepare_packing_data(the_repository, pdata);
913 for (i = 0; i < ctx->entries_nr; i++) {
914 struct pack_midx_entry *from = &ctx->entries[ctx->pack_order[i]];
915 struct object_entry *to = packlist_alloc(pdata, &from->oid);
917 oe_set_in_pack(pdata, to,
918 ctx->info[ctx->pack_perm[from->pack_int_id]].p);
922 static int add_ref_to_pending(const char *refname,
923 const struct object_id *oid,
924 int flag, void *cb_data)
926 struct rev_info *revs = (struct rev_info*)cb_data;
927 struct object *object;
929 if ((flag & REF_ISSYMREF) && (flag & REF_ISBROKEN)) {
930 warning("symbolic ref is dangling: %s", refname);
931 return 0;
934 object = parse_object_or_die(oid, refname);
935 if (object->type != OBJ_COMMIT)
936 return 0;
938 add_pending_object(revs, object, "");
939 if (bitmap_is_preferred_refname(revs->repo, refname))
940 object->flags |= NEEDS_BITMAP;
941 return 0;
944 struct bitmap_commit_cb {
945 struct commit **commits;
946 size_t commits_nr, commits_alloc;
948 struct write_midx_context *ctx;
951 static const struct object_id *bitmap_oid_access(size_t index,
952 const void *_entries)
954 const struct pack_midx_entry *entries = _entries;
955 return &entries[index].oid;
958 static void bitmap_show_commit(struct commit *commit, void *_data)
960 struct bitmap_commit_cb *data = _data;
961 int pos = oid_pos(&commit->object.oid, data->ctx->entries,
962 data->ctx->entries_nr,
963 bitmap_oid_access);
964 if (pos < 0)
965 return;
967 ALLOC_GROW(data->commits, data->commits_nr + 1, data->commits_alloc);
968 data->commits[data->commits_nr++] = commit;
971 static int read_refs_snapshot(const char *refs_snapshot,
972 struct rev_info *revs)
974 struct strbuf buf = STRBUF_INIT;
975 struct object_id oid;
976 FILE *f = xfopen(refs_snapshot, "r");
978 while (strbuf_getline(&buf, f) != EOF) {
979 struct object *object;
980 int preferred = 0;
981 char *hex = buf.buf;
982 const char *end = NULL;
984 if (buf.len && *buf.buf == '+') {
985 preferred = 1;
986 hex = &buf.buf[1];
989 if (parse_oid_hex(hex, &oid, &end) < 0)
990 die(_("could not parse line: %s"), buf.buf);
991 if (*end)
992 die(_("malformed line: %s"), buf.buf);
994 object = parse_object_or_die(&oid, NULL);
995 if (preferred)
996 object->flags |= NEEDS_BITMAP;
998 add_pending_object(revs, object, "");
1001 fclose(f);
1002 strbuf_release(&buf);
1003 return 0;
1006 static struct commit **find_commits_for_midx_bitmap(uint32_t *indexed_commits_nr_p,
1007 const char *refs_snapshot,
1008 struct write_midx_context *ctx)
1010 struct rev_info revs;
1011 struct bitmap_commit_cb cb = {0};
1013 cb.ctx = ctx;
1015 repo_init_revisions(the_repository, &revs, NULL);
1016 if (refs_snapshot) {
1017 read_refs_snapshot(refs_snapshot, &revs);
1018 } else {
1019 setup_revisions(0, NULL, &revs, NULL);
1020 for_each_ref(add_ref_to_pending, &revs);
1024 * Skipping promisor objects here is intentional, since it only excludes
1025 * them from the list of reachable commits that we want to select from
1026 * when computing the selection of MIDX'd commits to receive bitmaps.
1028 * Reachability bitmaps do require that their objects be closed under
1029 * reachability, but fetching any objects missing from promisors at this
1030 * point is too late. But, if one of those objects can be reached from
1031 * an another object that is included in the bitmap, then we will
1032 * complain later that we don't have reachability closure (and fail
1033 * appropriately).
1035 fetch_if_missing = 0;
1036 revs.exclude_promisor_objects = 1;
1038 if (prepare_revision_walk(&revs))
1039 die(_("revision walk setup failed"));
1041 traverse_commit_list(&revs, bitmap_show_commit, NULL, &cb);
1042 if (indexed_commits_nr_p)
1043 *indexed_commits_nr_p = cb.commits_nr;
1045 return cb.commits;
1048 static int write_midx_bitmap(char *midx_name, unsigned char *midx_hash,
1049 struct write_midx_context *ctx,
1050 const char *refs_snapshot,
1051 unsigned flags)
1053 struct packing_data pdata;
1054 struct pack_idx_entry **index;
1055 struct commit **commits = NULL;
1056 uint32_t i, commits_nr;
1057 uint16_t options = 0;
1058 char *bitmap_name = xstrfmt("%s-%s.bitmap", midx_name, hash_to_hex(midx_hash));
1059 int ret;
1061 if (flags & MIDX_WRITE_BITMAP_HASH_CACHE)
1062 options |= BITMAP_OPT_HASH_CACHE;
1064 prepare_midx_packing_data(&pdata, ctx);
1066 commits = find_commits_for_midx_bitmap(&commits_nr, refs_snapshot, ctx);
1069 * Build the MIDX-order index based on pdata.objects (which is already
1070 * in MIDX order; c.f., 'midx_pack_order_cmp()' for the definition of
1071 * this order).
1073 ALLOC_ARRAY(index, pdata.nr_objects);
1074 for (i = 0; i < pdata.nr_objects; i++)
1075 index[i] = &pdata.objects[i].idx;
1077 bitmap_writer_show_progress(flags & MIDX_PROGRESS);
1078 bitmap_writer_build_type_index(&pdata, index, pdata.nr_objects);
1081 * bitmap_writer_finish expects objects in lex order, but pack_order
1082 * gives us exactly that. use it directly instead of re-sorting the
1083 * array.
1085 * This changes the order of objects in 'index' between
1086 * bitmap_writer_build_type_index and bitmap_writer_finish.
1088 * The same re-ordering takes place in the single-pack bitmap code via
1089 * write_idx_file(), which is called by finish_tmp_packfile(), which
1090 * happens between bitmap_writer_build_type_index() and
1091 * bitmap_writer_finish().
1093 for (i = 0; i < pdata.nr_objects; i++)
1094 index[ctx->pack_order[i]] = &pdata.objects[i].idx;
1096 bitmap_writer_select_commits(commits, commits_nr, -1);
1097 ret = bitmap_writer_build(&pdata);
1098 if (ret < 0)
1099 goto cleanup;
1101 bitmap_writer_set_checksum(midx_hash);
1102 bitmap_writer_finish(index, pdata.nr_objects, bitmap_name, options);
1104 cleanup:
1105 free(index);
1106 free(bitmap_name);
1107 return ret;
1110 static struct multi_pack_index *lookup_multi_pack_index(struct repository *r,
1111 const char *object_dir)
1113 struct multi_pack_index *cur;
1115 /* Ensure the given object_dir is local, or a known alternate. */
1116 find_odb(r, object_dir);
1118 for (cur = get_multi_pack_index(r); cur; cur = cur->next) {
1119 if (!strcmp(object_dir, cur->object_dir))
1120 return cur;
1123 return NULL;
1126 static int write_midx_internal(const char *object_dir,
1127 struct string_list *packs_to_include,
1128 struct string_list *packs_to_drop,
1129 const char *preferred_pack_name,
1130 const char *refs_snapshot,
1131 unsigned flags)
1133 char *midx_name;
1134 unsigned char midx_hash[GIT_MAX_RAWSZ];
1135 uint32_t i;
1136 struct hashfile *f = NULL;
1137 struct lock_file lk;
1138 struct write_midx_context ctx = { 0 };
1139 int pack_name_concat_len = 0;
1140 int dropped_packs = 0;
1141 int result = 0;
1142 struct chunkfile *cf;
1144 midx_name = get_midx_filename(object_dir);
1145 if (safe_create_leading_directories(midx_name))
1146 die_errno(_("unable to create leading directories of %s"),
1147 midx_name);
1149 if (!packs_to_include) {
1151 * Only reference an existing MIDX when not filtering which
1152 * packs to include, since all packs and objects are copied
1153 * blindly from an existing MIDX if one is present.
1155 ctx.m = lookup_multi_pack_index(the_repository, object_dir);
1158 if (ctx.m && !midx_checksum_valid(ctx.m)) {
1159 warning(_("ignoring existing multi-pack-index; checksum mismatch"));
1160 ctx.m = NULL;
1163 ctx.nr = 0;
1164 ctx.alloc = ctx.m ? ctx.m->num_packs : 16;
1165 ctx.info = NULL;
1166 ALLOC_ARRAY(ctx.info, ctx.alloc);
1168 if (ctx.m) {
1169 for (i = 0; i < ctx.m->num_packs; i++) {
1170 ALLOC_GROW(ctx.info, ctx.nr + 1, ctx.alloc);
1172 ctx.info[ctx.nr].orig_pack_int_id = i;
1173 ctx.info[ctx.nr].pack_name = xstrdup(ctx.m->pack_names[i]);
1174 ctx.info[ctx.nr].p = ctx.m->packs[i];
1175 ctx.info[ctx.nr].expired = 0;
1177 if (flags & MIDX_WRITE_REV_INDEX) {
1179 * If generating a reverse index, need to have
1180 * packed_git's loaded to compare their
1181 * mtimes and object count.
1183 if (prepare_midx_pack(the_repository, ctx.m, i)) {
1184 error(_("could not load pack"));
1185 result = 1;
1186 goto cleanup;
1189 if (open_pack_index(ctx.m->packs[i]))
1190 die(_("could not open index for %s"),
1191 ctx.m->packs[i]->pack_name);
1192 ctx.info[ctx.nr].p = ctx.m->packs[i];
1195 ctx.nr++;
1199 ctx.pack_paths_checked = 0;
1200 if (flags & MIDX_PROGRESS)
1201 ctx.progress = start_delayed_progress(_("Adding packfiles to multi-pack-index"), 0);
1202 else
1203 ctx.progress = NULL;
1205 ctx.to_include = packs_to_include;
1207 for_each_file_in_pack_dir(object_dir, add_pack_to_midx, &ctx);
1208 stop_progress(&ctx.progress);
1210 if ((ctx.m && ctx.nr == ctx.m->num_packs) &&
1211 !(packs_to_include || packs_to_drop)) {
1212 struct bitmap_index *bitmap_git;
1213 int bitmap_exists;
1214 int want_bitmap = flags & MIDX_WRITE_BITMAP;
1216 bitmap_git = prepare_midx_bitmap_git(ctx.m);
1217 bitmap_exists = bitmap_git && bitmap_is_midx(bitmap_git);
1218 free_bitmap_index(bitmap_git);
1220 if (bitmap_exists || !want_bitmap) {
1222 * The correct MIDX already exists, and so does a
1223 * corresponding bitmap (or one wasn't requested).
1225 if (!want_bitmap)
1226 clear_midx_files_ext(object_dir, ".bitmap",
1227 NULL);
1228 goto cleanup;
1232 if (preferred_pack_name) {
1233 int found = 0;
1234 for (i = 0; i < ctx.nr; i++) {
1235 if (!cmp_idx_or_pack_name(preferred_pack_name,
1236 ctx.info[i].pack_name)) {
1237 ctx.preferred_pack_idx = i;
1238 found = 1;
1239 break;
1243 if (!found)
1244 warning(_("unknown preferred pack: '%s'"),
1245 preferred_pack_name);
1246 } else if (ctx.nr &&
1247 (flags & (MIDX_WRITE_REV_INDEX | MIDX_WRITE_BITMAP))) {
1248 struct packed_git *oldest = ctx.info[ctx.preferred_pack_idx].p;
1249 ctx.preferred_pack_idx = 0;
1251 if (packs_to_drop && packs_to_drop->nr)
1252 BUG("cannot write a MIDX bitmap during expiration");
1255 * set a preferred pack when writing a bitmap to ensure that
1256 * the pack from which the first object is selected in pseudo
1257 * pack-order has all of its objects selected from that pack
1258 * (and not another pack containing a duplicate)
1260 for (i = 1; i < ctx.nr; i++) {
1261 struct packed_git *p = ctx.info[i].p;
1263 if (!oldest->num_objects || p->mtime < oldest->mtime) {
1264 oldest = p;
1265 ctx.preferred_pack_idx = i;
1269 if (!oldest->num_objects) {
1271 * If all packs are empty; unset the preferred index.
1272 * This is acceptable since there will be no duplicate
1273 * objects to resolve, so the preferred value doesn't
1274 * matter.
1276 ctx.preferred_pack_idx = -1;
1278 } else {
1280 * otherwise don't mark any pack as preferred to avoid
1281 * interfering with expiration logic below
1283 ctx.preferred_pack_idx = -1;
1286 if (ctx.preferred_pack_idx > -1) {
1287 struct packed_git *preferred = ctx.info[ctx.preferred_pack_idx].p;
1288 if (!preferred->num_objects) {
1289 error(_("cannot select preferred pack %s with no objects"),
1290 preferred->pack_name);
1291 result = 1;
1292 goto cleanup;
1296 ctx.entries = get_sorted_entries(ctx.m, ctx.info, ctx.nr, &ctx.entries_nr,
1297 ctx.preferred_pack_idx);
1299 ctx.large_offsets_needed = 0;
1300 for (i = 0; i < ctx.entries_nr; i++) {
1301 if (ctx.entries[i].offset > 0x7fffffff)
1302 ctx.num_large_offsets++;
1303 if (ctx.entries[i].offset > 0xffffffff)
1304 ctx.large_offsets_needed = 1;
1307 QSORT(ctx.info, ctx.nr, pack_info_compare);
1309 if (packs_to_drop && packs_to_drop->nr) {
1310 int drop_index = 0;
1311 int missing_drops = 0;
1313 for (i = 0; i < ctx.nr && drop_index < packs_to_drop->nr; i++) {
1314 int cmp = strcmp(ctx.info[i].pack_name,
1315 packs_to_drop->items[drop_index].string);
1317 if (!cmp) {
1318 drop_index++;
1319 ctx.info[i].expired = 1;
1320 } else if (cmp > 0) {
1321 error(_("did not see pack-file %s to drop"),
1322 packs_to_drop->items[drop_index].string);
1323 drop_index++;
1324 missing_drops++;
1325 i--;
1326 } else {
1327 ctx.info[i].expired = 0;
1331 if (missing_drops) {
1332 result = 1;
1333 goto cleanup;
1338 * pack_perm stores a permutation between pack-int-ids from the
1339 * previous multi-pack-index to the new one we are writing:
1341 * pack_perm[old_id] = new_id
1343 ALLOC_ARRAY(ctx.pack_perm, ctx.nr);
1344 for (i = 0; i < ctx.nr; i++) {
1345 if (ctx.info[i].expired) {
1346 dropped_packs++;
1347 ctx.pack_perm[ctx.info[i].orig_pack_int_id] = PACK_EXPIRED;
1348 } else {
1349 ctx.pack_perm[ctx.info[i].orig_pack_int_id] = i - dropped_packs;
1353 for (i = 0; i < ctx.nr; i++) {
1354 if (!ctx.info[i].expired)
1355 pack_name_concat_len += strlen(ctx.info[i].pack_name) + 1;
1358 /* Check that the preferred pack wasn't expired (if given). */
1359 if (preferred_pack_name) {
1360 struct pack_info *preferred = bsearch(preferred_pack_name,
1361 ctx.info, ctx.nr,
1362 sizeof(*ctx.info),
1363 idx_or_pack_name_cmp);
1364 if (preferred) {
1365 uint32_t perm = ctx.pack_perm[preferred->orig_pack_int_id];
1366 if (perm == PACK_EXPIRED)
1367 warning(_("preferred pack '%s' is expired"),
1368 preferred_pack_name);
1372 if (pack_name_concat_len % MIDX_CHUNK_ALIGNMENT)
1373 pack_name_concat_len += MIDX_CHUNK_ALIGNMENT -
1374 (pack_name_concat_len % MIDX_CHUNK_ALIGNMENT);
1376 hold_lock_file_for_update(&lk, midx_name, LOCK_DIE_ON_ERROR);
1377 f = hashfd(get_lock_file_fd(&lk), get_lock_file_path(&lk));
1379 if (ctx.nr - dropped_packs == 0) {
1380 error(_("no pack files to index."));
1381 result = 1;
1382 goto cleanup;
1385 cf = init_chunkfile(f);
1387 add_chunk(cf, MIDX_CHUNKID_PACKNAMES, pack_name_concat_len,
1388 write_midx_pack_names);
1389 add_chunk(cf, MIDX_CHUNKID_OIDFANOUT, MIDX_CHUNK_FANOUT_SIZE,
1390 write_midx_oid_fanout);
1391 add_chunk(cf, MIDX_CHUNKID_OIDLOOKUP,
1392 (size_t)ctx.entries_nr * the_hash_algo->rawsz,
1393 write_midx_oid_lookup);
1394 add_chunk(cf, MIDX_CHUNKID_OBJECTOFFSETS,
1395 (size_t)ctx.entries_nr * MIDX_CHUNK_OFFSET_WIDTH,
1396 write_midx_object_offsets);
1398 if (ctx.large_offsets_needed)
1399 add_chunk(cf, MIDX_CHUNKID_LARGEOFFSETS,
1400 (size_t)ctx.num_large_offsets * MIDX_CHUNK_LARGE_OFFSET_WIDTH,
1401 write_midx_large_offsets);
1403 write_midx_header(f, get_num_chunks(cf), ctx.nr - dropped_packs);
1404 write_chunkfile(cf, &ctx);
1406 finalize_hashfile(f, midx_hash, CSUM_FSYNC | CSUM_HASH_IN_STREAM);
1407 free_chunkfile(cf);
1409 if (flags & (MIDX_WRITE_REV_INDEX | MIDX_WRITE_BITMAP))
1410 ctx.pack_order = midx_pack_order(&ctx);
1412 if (flags & MIDX_WRITE_REV_INDEX)
1413 write_midx_reverse_index(midx_name, midx_hash, &ctx);
1414 if (flags & MIDX_WRITE_BITMAP) {
1415 if (write_midx_bitmap(midx_name, midx_hash, &ctx,
1416 refs_snapshot, flags) < 0) {
1417 error(_("could not write multi-pack bitmap"));
1418 result = 1;
1419 goto cleanup;
1423 if (ctx.m)
1424 close_object_store(the_repository->objects);
1426 if (commit_lock_file(&lk) < 0)
1427 die_errno(_("could not write multi-pack-index"));
1429 clear_midx_files_ext(object_dir, ".bitmap", midx_hash);
1430 clear_midx_files_ext(object_dir, ".rev", midx_hash);
1432 cleanup:
1433 for (i = 0; i < ctx.nr; i++) {
1434 if (ctx.info[i].p) {
1435 close_pack(ctx.info[i].p);
1436 free(ctx.info[i].p);
1438 free(ctx.info[i].pack_name);
1441 free(ctx.info);
1442 free(ctx.entries);
1443 free(ctx.pack_perm);
1444 free(ctx.pack_order);
1445 free(midx_name);
1447 return result;
1450 int write_midx_file(const char *object_dir,
1451 const char *preferred_pack_name,
1452 const char *refs_snapshot,
1453 unsigned flags)
1455 return write_midx_internal(object_dir, NULL, NULL, preferred_pack_name,
1456 refs_snapshot, flags);
1459 int write_midx_file_only(const char *object_dir,
1460 struct string_list *packs_to_include,
1461 const char *preferred_pack_name,
1462 const char *refs_snapshot,
1463 unsigned flags)
1465 return write_midx_internal(object_dir, packs_to_include, NULL,
1466 preferred_pack_name, refs_snapshot, flags);
1469 struct clear_midx_data {
1470 char *keep;
1471 const char *ext;
1474 static void clear_midx_file_ext(const char *full_path, size_t full_path_len,
1475 const char *file_name, void *_data)
1477 struct clear_midx_data *data = _data;
1479 if (!(starts_with(file_name, "multi-pack-index-") &&
1480 ends_with(file_name, data->ext)))
1481 return;
1482 if (data->keep && !strcmp(data->keep, file_name))
1483 return;
1485 if (unlink(full_path))
1486 die_errno(_("failed to remove %s"), full_path);
1489 static void clear_midx_files_ext(const char *object_dir, const char *ext,
1490 unsigned char *keep_hash)
1492 struct clear_midx_data data;
1493 memset(&data, 0, sizeof(struct clear_midx_data));
1495 if (keep_hash)
1496 data.keep = xstrfmt("multi-pack-index-%s%s",
1497 hash_to_hex(keep_hash), ext);
1498 data.ext = ext;
1500 for_each_file_in_pack_dir(object_dir,
1501 clear_midx_file_ext,
1502 &data);
1504 free(data.keep);
1507 void clear_midx_file(struct repository *r)
1509 char *midx = get_midx_filename(r->objects->odb->path);
1511 if (r->objects && r->objects->multi_pack_index) {
1512 close_midx(r->objects->multi_pack_index);
1513 r->objects->multi_pack_index = NULL;
1516 if (remove_path(midx))
1517 die(_("failed to clear multi-pack-index at %s"), midx);
1519 clear_midx_files_ext(r->objects->odb->path, ".bitmap", NULL);
1520 clear_midx_files_ext(r->objects->odb->path, ".rev", NULL);
1522 free(midx);
1525 static int verify_midx_error;
1527 __attribute__((format (printf, 1, 2)))
1528 static void midx_report(const char *fmt, ...)
1530 va_list ap;
1531 verify_midx_error = 1;
1532 va_start(ap, fmt);
1533 vfprintf(stderr, fmt, ap);
1534 fprintf(stderr, "\n");
1535 va_end(ap);
1538 struct pair_pos_vs_id
1540 uint32_t pos;
1541 uint32_t pack_int_id;
1544 static int compare_pair_pos_vs_id(const void *_a, const void *_b)
1546 struct pair_pos_vs_id *a = (struct pair_pos_vs_id *)_a;
1547 struct pair_pos_vs_id *b = (struct pair_pos_vs_id *)_b;
1549 return b->pack_int_id - a->pack_int_id;
1553 * Limit calls to display_progress() for performance reasons.
1554 * The interval here was arbitrarily chosen.
1556 #define SPARSE_PROGRESS_INTERVAL (1 << 12)
1557 #define midx_display_sparse_progress(progress, n) \
1558 do { \
1559 uint64_t _n = (n); \
1560 if ((_n & (SPARSE_PROGRESS_INTERVAL - 1)) == 0) \
1561 display_progress(progress, _n); \
1562 } while (0)
1564 int verify_midx_file(struct repository *r, const char *object_dir, unsigned flags)
1566 struct pair_pos_vs_id *pairs = NULL;
1567 uint32_t i;
1568 struct progress *progress = NULL;
1569 struct multi_pack_index *m = load_multi_pack_index(object_dir, 1);
1570 verify_midx_error = 0;
1572 if (!m) {
1573 int result = 0;
1574 struct stat sb;
1575 char *filename = get_midx_filename(object_dir);
1576 if (!stat(filename, &sb)) {
1577 error(_("multi-pack-index file exists, but failed to parse"));
1578 result = 1;
1580 free(filename);
1581 return result;
1584 if (!midx_checksum_valid(m))
1585 midx_report(_("incorrect checksum"));
1587 if (flags & MIDX_PROGRESS)
1588 progress = start_delayed_progress(_("Looking for referenced packfiles"),
1589 m->num_packs);
1590 for (i = 0; i < m->num_packs; i++) {
1591 if (prepare_midx_pack(r, m, i))
1592 midx_report("failed to load pack in position %d", i);
1594 display_progress(progress, i + 1);
1596 stop_progress(&progress);
1598 for (i = 0; i < 255; i++) {
1599 uint32_t oid_fanout1 = ntohl(m->chunk_oid_fanout[i]);
1600 uint32_t oid_fanout2 = ntohl(m->chunk_oid_fanout[i + 1]);
1602 if (oid_fanout1 > oid_fanout2)
1603 midx_report(_("oid fanout out of order: fanout[%d] = %"PRIx32" > %"PRIx32" = fanout[%d]"),
1604 i, oid_fanout1, oid_fanout2, i + 1);
1607 if (m->num_objects == 0) {
1608 midx_report(_("the midx contains no oid"));
1610 * Remaining tests assume that we have objects, so we can
1611 * return here.
1613 return verify_midx_error;
1616 if (flags & MIDX_PROGRESS)
1617 progress = start_sparse_progress(_("Verifying OID order in multi-pack-index"),
1618 m->num_objects - 1);
1619 for (i = 0; i < m->num_objects - 1; i++) {
1620 struct object_id oid1, oid2;
1622 nth_midxed_object_oid(&oid1, m, i);
1623 nth_midxed_object_oid(&oid2, m, i + 1);
1625 if (oidcmp(&oid1, &oid2) >= 0)
1626 midx_report(_("oid lookup out of order: oid[%d] = %s >= %s = oid[%d]"),
1627 i, oid_to_hex(&oid1), oid_to_hex(&oid2), i + 1);
1629 midx_display_sparse_progress(progress, i + 1);
1631 stop_progress(&progress);
1634 * Create an array mapping each object to its packfile id. Sort it
1635 * to group the objects by packfile. Use this permutation to visit
1636 * each of the objects and only require 1 packfile to be open at a
1637 * time.
1639 ALLOC_ARRAY(pairs, m->num_objects);
1640 for (i = 0; i < m->num_objects; i++) {
1641 pairs[i].pos = i;
1642 pairs[i].pack_int_id = nth_midxed_pack_int_id(m, i);
1645 if (flags & MIDX_PROGRESS)
1646 progress = start_sparse_progress(_("Sorting objects by packfile"),
1647 m->num_objects);
1648 display_progress(progress, 0); /* TODO: Measure QSORT() progress */
1649 QSORT(pairs, m->num_objects, compare_pair_pos_vs_id);
1650 stop_progress(&progress);
1652 if (flags & MIDX_PROGRESS)
1653 progress = start_sparse_progress(_("Verifying object offsets"), m->num_objects);
1654 for (i = 0; i < m->num_objects; i++) {
1655 struct object_id oid;
1656 struct pack_entry e;
1657 off_t m_offset, p_offset;
1659 if (i > 0 && pairs[i-1].pack_int_id != pairs[i].pack_int_id &&
1660 m->packs[pairs[i-1].pack_int_id])
1662 close_pack_fd(m->packs[pairs[i-1].pack_int_id]);
1663 close_pack_index(m->packs[pairs[i-1].pack_int_id]);
1666 nth_midxed_object_oid(&oid, m, pairs[i].pos);
1668 if (!fill_midx_entry(r, &oid, &e, m)) {
1669 midx_report(_("failed to load pack entry for oid[%d] = %s"),
1670 pairs[i].pos, oid_to_hex(&oid));
1671 continue;
1674 if (open_pack_index(e.p)) {
1675 midx_report(_("failed to load pack-index for packfile %s"),
1676 e.p->pack_name);
1677 break;
1680 m_offset = e.offset;
1681 p_offset = find_pack_entry_one(oid.hash, e.p);
1683 if (m_offset != p_offset)
1684 midx_report(_("incorrect object offset for oid[%d] = %s: %"PRIx64" != %"PRIx64),
1685 pairs[i].pos, oid_to_hex(&oid), m_offset, p_offset);
1687 midx_display_sparse_progress(progress, i + 1);
1689 stop_progress(&progress);
1691 free(pairs);
1693 return verify_midx_error;
1696 int expire_midx_packs(struct repository *r, const char *object_dir, unsigned flags)
1698 uint32_t i, *count, result = 0;
1699 struct string_list packs_to_drop = STRING_LIST_INIT_DUP;
1700 struct multi_pack_index *m = lookup_multi_pack_index(r, object_dir);
1701 struct progress *progress = NULL;
1703 if (!m)
1704 return 0;
1706 CALLOC_ARRAY(count, m->num_packs);
1708 if (flags & MIDX_PROGRESS)
1709 progress = start_delayed_progress(_("Counting referenced objects"),
1710 m->num_objects);
1711 for (i = 0; i < m->num_objects; i++) {
1712 int pack_int_id = nth_midxed_pack_int_id(m, i);
1713 count[pack_int_id]++;
1714 display_progress(progress, i + 1);
1716 stop_progress(&progress);
1718 if (flags & MIDX_PROGRESS)
1719 progress = start_delayed_progress(_("Finding and deleting unreferenced packfiles"),
1720 m->num_packs);
1721 for (i = 0; i < m->num_packs; i++) {
1722 char *pack_name;
1723 display_progress(progress, i + 1);
1725 if (count[i])
1726 continue;
1728 if (prepare_midx_pack(r, m, i))
1729 continue;
1731 if (m->packs[i]->pack_keep)
1732 continue;
1734 pack_name = xstrdup(m->packs[i]->pack_name);
1735 close_pack(m->packs[i]);
1737 string_list_insert(&packs_to_drop, m->pack_names[i]);
1738 unlink_pack_path(pack_name, 0);
1739 free(pack_name);
1741 stop_progress(&progress);
1743 free(count);
1745 if (packs_to_drop.nr)
1746 result = write_midx_internal(object_dir, NULL, &packs_to_drop, NULL, NULL, flags);
1748 string_list_clear(&packs_to_drop, 0);
1750 return result;
1753 struct repack_info {
1754 timestamp_t mtime;
1755 uint32_t referenced_objects;
1756 uint32_t pack_int_id;
1759 static int compare_by_mtime(const void *a_, const void *b_)
1761 const struct repack_info *a, *b;
1763 a = (const struct repack_info *)a_;
1764 b = (const struct repack_info *)b_;
1766 if (a->mtime < b->mtime)
1767 return -1;
1768 if (a->mtime > b->mtime)
1769 return 1;
1770 return 0;
1773 static int fill_included_packs_all(struct repository *r,
1774 struct multi_pack_index *m,
1775 unsigned char *include_pack)
1777 uint32_t i, count = 0;
1778 int pack_kept_objects = 0;
1780 repo_config_get_bool(r, "repack.packkeptobjects", &pack_kept_objects);
1782 for (i = 0; i < m->num_packs; i++) {
1783 if (prepare_midx_pack(r, m, i))
1784 continue;
1785 if (!pack_kept_objects && m->packs[i]->pack_keep)
1786 continue;
1788 include_pack[i] = 1;
1789 count++;
1792 return count < 2;
1795 static int fill_included_packs_batch(struct repository *r,
1796 struct multi_pack_index *m,
1797 unsigned char *include_pack,
1798 size_t batch_size)
1800 uint32_t i, packs_to_repack;
1801 size_t total_size;
1802 struct repack_info *pack_info = xcalloc(m->num_packs, sizeof(struct repack_info));
1803 int pack_kept_objects = 0;
1805 repo_config_get_bool(r, "repack.packkeptobjects", &pack_kept_objects);
1807 for (i = 0; i < m->num_packs; i++) {
1808 pack_info[i].pack_int_id = i;
1810 if (prepare_midx_pack(r, m, i))
1811 continue;
1813 pack_info[i].mtime = m->packs[i]->mtime;
1816 for (i = 0; batch_size && i < m->num_objects; i++) {
1817 uint32_t pack_int_id = nth_midxed_pack_int_id(m, i);
1818 pack_info[pack_int_id].referenced_objects++;
1821 QSORT(pack_info, m->num_packs, compare_by_mtime);
1823 total_size = 0;
1824 packs_to_repack = 0;
1825 for (i = 0; total_size < batch_size && i < m->num_packs; i++) {
1826 int pack_int_id = pack_info[i].pack_int_id;
1827 struct packed_git *p = m->packs[pack_int_id];
1828 size_t expected_size;
1830 if (!p)
1831 continue;
1832 if (!pack_kept_objects && p->pack_keep)
1833 continue;
1834 if (open_pack_index(p) || !p->num_objects)
1835 continue;
1837 expected_size = (size_t)(p->pack_size
1838 * pack_info[i].referenced_objects);
1839 expected_size /= p->num_objects;
1841 if (expected_size >= batch_size)
1842 continue;
1844 packs_to_repack++;
1845 total_size += expected_size;
1846 include_pack[pack_int_id] = 1;
1849 free(pack_info);
1851 if (packs_to_repack < 2)
1852 return 1;
1854 return 0;
1857 int midx_repack(struct repository *r, const char *object_dir, size_t batch_size, unsigned flags)
1859 int result = 0;
1860 uint32_t i;
1861 unsigned char *include_pack;
1862 struct child_process cmd = CHILD_PROCESS_INIT;
1863 FILE *cmd_in;
1864 struct strbuf base_name = STRBUF_INIT;
1865 struct multi_pack_index *m = lookup_multi_pack_index(r, object_dir);
1868 * When updating the default for these configuration
1869 * variables in builtin/repack.c, these must be adjusted
1870 * to match.
1872 int delta_base_offset = 1;
1873 int use_delta_islands = 0;
1875 if (!m)
1876 return 0;
1878 CALLOC_ARRAY(include_pack, m->num_packs);
1880 if (batch_size) {
1881 if (fill_included_packs_batch(r, m, include_pack, batch_size))
1882 goto cleanup;
1883 } else if (fill_included_packs_all(r, m, include_pack))
1884 goto cleanup;
1886 repo_config_get_bool(r, "repack.usedeltabaseoffset", &delta_base_offset);
1887 repo_config_get_bool(r, "repack.usedeltaislands", &use_delta_islands);
1889 strvec_push(&cmd.args, "pack-objects");
1891 strbuf_addstr(&base_name, object_dir);
1892 strbuf_addstr(&base_name, "/pack/pack");
1893 strvec_push(&cmd.args, base_name.buf);
1895 if (delta_base_offset)
1896 strvec_push(&cmd.args, "--delta-base-offset");
1897 if (use_delta_islands)
1898 strvec_push(&cmd.args, "--delta-islands");
1900 if (flags & MIDX_PROGRESS)
1901 strvec_push(&cmd.args, "--progress");
1902 else
1903 strvec_push(&cmd.args, "-q");
1905 strbuf_release(&base_name);
1907 cmd.git_cmd = 1;
1908 cmd.in = cmd.out = -1;
1910 if (start_command(&cmd)) {
1911 error(_("could not start pack-objects"));
1912 result = 1;
1913 goto cleanup;
1916 cmd_in = xfdopen(cmd.in, "w");
1918 for (i = 0; i < m->num_objects; i++) {
1919 struct object_id oid;
1920 uint32_t pack_int_id = nth_midxed_pack_int_id(m, i);
1922 if (!include_pack[pack_int_id])
1923 continue;
1925 nth_midxed_object_oid(&oid, m, i);
1926 fprintf(cmd_in, "%s\n", oid_to_hex(&oid));
1928 fclose(cmd_in);
1930 if (finish_command(&cmd)) {
1931 error(_("could not finish pack-objects"));
1932 result = 1;
1933 goto cleanup;
1936 result = write_midx_internal(object_dir, NULL, NULL, NULL, NULL, flags);
1938 cleanup:
1939 free(include_pack);
1940 return result;