Merge branch 'jt/fetch-peek-optional-section'
[alt-git.git] / midx.c
blob3db0e47735f600c936ec8a9566d5587228534481
1 #include "cache.h"
2 #include "config.h"
3 #include "csum-file.h"
4 #include "dir.h"
5 #include "lockfile.h"
6 #include "packfile.h"
7 #include "object-store.h"
8 #include "hash-lookup.h"
9 #include "midx.h"
10 #include "progress.h"
11 #include "trace2.h"
12 #include "run-command.h"
13 #include "repository.h"
14 #include "chunk-format.h"
15 #include "pack.h"
16 #include "pack-bitmap.h"
17 #include "refs.h"
18 #include "revision.h"
19 #include "list-objects.h"
21 #define MIDX_SIGNATURE 0x4d494458 /* "MIDX" */
22 #define MIDX_VERSION 1
23 #define MIDX_BYTE_FILE_VERSION 4
24 #define MIDX_BYTE_HASH_VERSION 5
25 #define MIDX_BYTE_NUM_CHUNKS 6
26 #define MIDX_BYTE_NUM_PACKS 8
27 #define MIDX_HEADER_SIZE 12
28 #define MIDX_MIN_SIZE (MIDX_HEADER_SIZE + the_hash_algo->rawsz)
30 #define MIDX_CHUNK_ALIGNMENT 4
31 #define MIDX_CHUNKID_PACKNAMES 0x504e414d /* "PNAM" */
32 #define MIDX_CHUNKID_OIDFANOUT 0x4f494446 /* "OIDF" */
33 #define MIDX_CHUNKID_OIDLOOKUP 0x4f49444c /* "OIDL" */
34 #define MIDX_CHUNKID_OBJECTOFFSETS 0x4f4f4646 /* "OOFF" */
35 #define MIDX_CHUNKID_LARGEOFFSETS 0x4c4f4646 /* "LOFF" */
36 #define MIDX_CHUNKID_REVINDEX 0x52494458 /* "RIDX" */
37 #define MIDX_CHUNK_FANOUT_SIZE (sizeof(uint32_t) * 256)
38 #define MIDX_CHUNK_OFFSET_WIDTH (2 * sizeof(uint32_t))
39 #define MIDX_CHUNK_LARGE_OFFSET_WIDTH (sizeof(uint64_t))
40 #define MIDX_LARGE_OFFSET_NEEDED 0x80000000
42 #define PACK_EXPIRED UINT_MAX
44 static uint8_t oid_version(void)
46 switch (hash_algo_by_ptr(the_hash_algo)) {
47 case GIT_HASH_SHA1:
48 return 1;
49 case GIT_HASH_SHA256:
50 return 2;
51 default:
52 die(_("invalid hash version"));
56 const unsigned char *get_midx_checksum(struct multi_pack_index *m)
58 return m->data + m->data_len - the_hash_algo->rawsz;
61 void get_midx_filename(struct strbuf *out, const char *object_dir)
63 strbuf_addf(out, "%s/pack/multi-pack-index", object_dir);
66 void get_midx_rev_filename(struct strbuf *out, struct multi_pack_index *m)
68 get_midx_filename(out, m->object_dir);
69 strbuf_addf(out, "-%s.rev", hash_to_hex(get_midx_checksum(m)));
72 static int midx_read_oid_fanout(const unsigned char *chunk_start,
73 size_t chunk_size, void *data)
75 struct multi_pack_index *m = data;
76 m->chunk_oid_fanout = (uint32_t *)chunk_start;
78 if (chunk_size != 4 * 256) {
79 error(_("multi-pack-index OID fanout is of the wrong size"));
80 return 1;
82 return 0;
85 struct multi_pack_index *load_multi_pack_index(const char *object_dir, int local)
87 struct multi_pack_index *m = NULL;
88 int fd;
89 struct stat st;
90 size_t midx_size;
91 void *midx_map = NULL;
92 uint32_t hash_version;
93 struct strbuf midx_name = STRBUF_INIT;
94 uint32_t i;
95 const char *cur_pack_name;
96 struct chunkfile *cf = NULL;
98 get_midx_filename(&midx_name, object_dir);
100 fd = git_open(midx_name.buf);
102 if (fd < 0)
103 goto cleanup_fail;
104 if (fstat(fd, &st)) {
105 error_errno(_("failed to read %s"), midx_name.buf);
106 goto cleanup_fail;
109 midx_size = xsize_t(st.st_size);
111 if (midx_size < MIDX_MIN_SIZE) {
112 error(_("multi-pack-index file %s is too small"), midx_name.buf);
113 goto cleanup_fail;
116 strbuf_release(&midx_name);
118 midx_map = xmmap(NULL, midx_size, PROT_READ, MAP_PRIVATE, fd, 0);
119 close(fd);
121 FLEX_ALLOC_STR(m, object_dir, object_dir);
122 m->data = midx_map;
123 m->data_len = midx_size;
124 m->local = local;
126 m->signature = get_be32(m->data);
127 if (m->signature != MIDX_SIGNATURE)
128 die(_("multi-pack-index signature 0x%08x does not match signature 0x%08x"),
129 m->signature, MIDX_SIGNATURE);
131 m->version = m->data[MIDX_BYTE_FILE_VERSION];
132 if (m->version != MIDX_VERSION)
133 die(_("multi-pack-index version %d not recognized"),
134 m->version);
136 hash_version = m->data[MIDX_BYTE_HASH_VERSION];
137 if (hash_version != oid_version()) {
138 error(_("multi-pack-index hash version %u does not match version %u"),
139 hash_version, oid_version());
140 goto cleanup_fail;
142 m->hash_len = the_hash_algo->rawsz;
144 m->num_chunks = m->data[MIDX_BYTE_NUM_CHUNKS];
146 m->num_packs = get_be32(m->data + MIDX_BYTE_NUM_PACKS);
148 cf = init_chunkfile(NULL);
150 if (read_table_of_contents(cf, m->data, midx_size,
151 MIDX_HEADER_SIZE, m->num_chunks))
152 goto cleanup_fail;
154 if (pair_chunk(cf, MIDX_CHUNKID_PACKNAMES, &m->chunk_pack_names) == CHUNK_NOT_FOUND)
155 die(_("multi-pack-index missing required pack-name chunk"));
156 if (read_chunk(cf, MIDX_CHUNKID_OIDFANOUT, midx_read_oid_fanout, m) == CHUNK_NOT_FOUND)
157 die(_("multi-pack-index missing required OID fanout chunk"));
158 if (pair_chunk(cf, MIDX_CHUNKID_OIDLOOKUP, &m->chunk_oid_lookup) == CHUNK_NOT_FOUND)
159 die(_("multi-pack-index missing required OID lookup chunk"));
160 if (pair_chunk(cf, MIDX_CHUNKID_OBJECTOFFSETS, &m->chunk_object_offsets) == CHUNK_NOT_FOUND)
161 die(_("multi-pack-index missing required object offsets chunk"));
163 pair_chunk(cf, MIDX_CHUNKID_LARGEOFFSETS, &m->chunk_large_offsets);
165 if (git_env_bool("GIT_TEST_MIDX_READ_RIDX", 1))
166 pair_chunk(cf, MIDX_CHUNKID_REVINDEX, &m->chunk_revindex);
168 m->num_objects = ntohl(m->chunk_oid_fanout[255]);
170 CALLOC_ARRAY(m->pack_names, m->num_packs);
171 CALLOC_ARRAY(m->packs, m->num_packs);
173 cur_pack_name = (const char *)m->chunk_pack_names;
174 for (i = 0; i < m->num_packs; i++) {
175 m->pack_names[i] = cur_pack_name;
177 cur_pack_name += strlen(cur_pack_name) + 1;
179 if (i && strcmp(m->pack_names[i], m->pack_names[i - 1]) <= 0)
180 die(_("multi-pack-index pack names out of order: '%s' before '%s'"),
181 m->pack_names[i - 1],
182 m->pack_names[i]);
185 trace2_data_intmax("midx", the_repository, "load/num_packs", m->num_packs);
186 trace2_data_intmax("midx", the_repository, "load/num_objects", m->num_objects);
188 free_chunkfile(cf);
189 return m;
191 cleanup_fail:
192 free(m);
193 strbuf_release(&midx_name);
194 free_chunkfile(cf);
195 if (midx_map)
196 munmap(midx_map, midx_size);
197 if (0 <= fd)
198 close(fd);
199 return NULL;
202 void close_midx(struct multi_pack_index *m)
204 uint32_t i;
206 if (!m)
207 return;
209 close_midx(m->next);
211 munmap((unsigned char *)m->data, m->data_len);
213 for (i = 0; i < m->num_packs; i++) {
214 if (m->packs[i])
215 m->packs[i]->multi_pack_index = 0;
217 FREE_AND_NULL(m->packs);
218 FREE_AND_NULL(m->pack_names);
219 free(m);
222 int prepare_midx_pack(struct repository *r, struct multi_pack_index *m, uint32_t pack_int_id)
224 struct strbuf pack_name = STRBUF_INIT;
225 struct packed_git *p;
227 if (pack_int_id >= m->num_packs)
228 die(_("bad pack-int-id: %u (%u total packs)"),
229 pack_int_id, m->num_packs);
231 if (m->packs[pack_int_id])
232 return 0;
234 strbuf_addf(&pack_name, "%s/pack/%s", m->object_dir,
235 m->pack_names[pack_int_id]);
237 p = add_packed_git(pack_name.buf, pack_name.len, m->local);
238 strbuf_release(&pack_name);
240 if (!p)
241 return 1;
243 p->multi_pack_index = 1;
244 m->packs[pack_int_id] = p;
245 install_packed_git(r, p);
246 list_add_tail(&p->mru, &r->objects->packed_git_mru);
248 return 0;
251 int bsearch_midx(const struct object_id *oid, struct multi_pack_index *m, uint32_t *result)
253 return bsearch_hash(oid->hash, m->chunk_oid_fanout, m->chunk_oid_lookup,
254 the_hash_algo->rawsz, result);
257 struct object_id *nth_midxed_object_oid(struct object_id *oid,
258 struct multi_pack_index *m,
259 uint32_t n)
261 if (n >= m->num_objects)
262 return NULL;
264 oidread(oid, m->chunk_oid_lookup + m->hash_len * n);
265 return oid;
268 off_t nth_midxed_offset(struct multi_pack_index *m, uint32_t pos)
270 const unsigned char *offset_data;
271 uint32_t offset32;
273 offset_data = m->chunk_object_offsets + (off_t)pos * MIDX_CHUNK_OFFSET_WIDTH;
274 offset32 = get_be32(offset_data + sizeof(uint32_t));
276 if (m->chunk_large_offsets && offset32 & MIDX_LARGE_OFFSET_NEEDED) {
277 if (sizeof(off_t) < sizeof(uint64_t))
278 die(_("multi-pack-index stores a 64-bit offset, but off_t is too small"));
280 offset32 ^= MIDX_LARGE_OFFSET_NEEDED;
281 return get_be64(m->chunk_large_offsets + sizeof(uint64_t) * offset32);
284 return offset32;
287 uint32_t nth_midxed_pack_int_id(struct multi_pack_index *m, uint32_t pos)
289 return get_be32(m->chunk_object_offsets +
290 (off_t)pos * MIDX_CHUNK_OFFSET_WIDTH);
293 int fill_midx_entry(struct repository * r,
294 const struct object_id *oid,
295 struct pack_entry *e,
296 struct multi_pack_index *m)
298 uint32_t pos;
299 uint32_t pack_int_id;
300 struct packed_git *p;
302 if (!bsearch_midx(oid, m, &pos))
303 return 0;
305 if (pos >= m->num_objects)
306 return 0;
308 pack_int_id = nth_midxed_pack_int_id(m, pos);
310 if (prepare_midx_pack(r, m, pack_int_id))
311 return 0;
312 p = m->packs[pack_int_id];
315 * We are about to tell the caller where they can locate the
316 * requested object. We better make sure the packfile is
317 * still here and can be accessed before supplying that
318 * answer, as it may have been deleted since the MIDX was
319 * loaded!
321 if (!is_pack_valid(p))
322 return 0;
324 if (oidset_size(&p->bad_objects) &&
325 oidset_contains(&p->bad_objects, oid))
326 return 0;
328 e->offset = nth_midxed_offset(m, pos);
329 e->p = p;
331 return 1;
334 /* Match "foo.idx" against either "foo.pack" _or_ "foo.idx". */
335 static int cmp_idx_or_pack_name(const char *idx_or_pack_name,
336 const char *idx_name)
338 /* Skip past any initial matching prefix. */
339 while (*idx_name && *idx_name == *idx_or_pack_name) {
340 idx_name++;
341 idx_or_pack_name++;
345 * If we didn't match completely, we may have matched "pack-1234." and
346 * be left with "idx" and "pack" respectively, which is also OK. We do
347 * not have to check for "idx" and "idx", because that would have been
348 * a complete match (and in that case these strcmps will be false, but
349 * we'll correctly return 0 from the final strcmp() below.
351 * Technically this matches "fooidx" and "foopack", but we'd never have
352 * such names in the first place.
354 if (!strcmp(idx_name, "idx") && !strcmp(idx_or_pack_name, "pack"))
355 return 0;
358 * This not only checks for a complete match, but also orders based on
359 * the first non-identical character, which means our ordering will
360 * match a raw strcmp(). That makes it OK to use this to binary search
361 * a naively-sorted list.
363 return strcmp(idx_or_pack_name, idx_name);
366 int midx_contains_pack(struct multi_pack_index *m, const char *idx_or_pack_name)
368 uint32_t first = 0, last = m->num_packs;
370 while (first < last) {
371 uint32_t mid = first + (last - first) / 2;
372 const char *current;
373 int cmp;
375 current = m->pack_names[mid];
376 cmp = cmp_idx_or_pack_name(idx_or_pack_name, current);
377 if (!cmp)
378 return 1;
379 if (cmp > 0) {
380 first = mid + 1;
381 continue;
383 last = mid;
386 return 0;
389 int prepare_multi_pack_index_one(struct repository *r, const char *object_dir, int local)
391 struct multi_pack_index *m;
392 struct multi_pack_index *m_search;
394 prepare_repo_settings(r);
395 if (!r->settings.core_multi_pack_index)
396 return 0;
398 for (m_search = r->objects->multi_pack_index; m_search; m_search = m_search->next)
399 if (!strcmp(object_dir, m_search->object_dir))
400 return 1;
402 m = load_multi_pack_index(object_dir, local);
404 if (m) {
405 struct multi_pack_index *mp = r->objects->multi_pack_index;
406 if (mp) {
407 m->next = mp->next;
408 mp->next = m;
409 } else
410 r->objects->multi_pack_index = m;
411 return 1;
414 return 0;
417 static size_t write_midx_header(struct hashfile *f,
418 unsigned char num_chunks,
419 uint32_t num_packs)
421 hashwrite_be32(f, MIDX_SIGNATURE);
422 hashwrite_u8(f, MIDX_VERSION);
423 hashwrite_u8(f, oid_version());
424 hashwrite_u8(f, num_chunks);
425 hashwrite_u8(f, 0); /* unused */
426 hashwrite_be32(f, num_packs);
428 return MIDX_HEADER_SIZE;
431 struct pack_info {
432 uint32_t orig_pack_int_id;
433 char *pack_name;
434 struct packed_git *p;
435 unsigned expired : 1;
438 static int pack_info_compare(const void *_a, const void *_b)
440 struct pack_info *a = (struct pack_info *)_a;
441 struct pack_info *b = (struct pack_info *)_b;
442 return strcmp(a->pack_name, b->pack_name);
445 static int idx_or_pack_name_cmp(const void *_va, const void *_vb)
447 const char *pack_name = _va;
448 const struct pack_info *compar = _vb;
450 return cmp_idx_or_pack_name(pack_name, compar->pack_name);
453 struct write_midx_context {
454 struct pack_info *info;
455 uint32_t nr;
456 uint32_t alloc;
457 struct multi_pack_index *m;
458 struct progress *progress;
459 unsigned pack_paths_checked;
461 struct pack_midx_entry *entries;
462 uint32_t entries_nr;
464 uint32_t *pack_perm;
465 uint32_t *pack_order;
466 unsigned large_offsets_needed:1;
467 uint32_t num_large_offsets;
469 int preferred_pack_idx;
471 struct string_list *to_include;
474 static void add_pack_to_midx(const char *full_path, size_t full_path_len,
475 const char *file_name, void *data)
477 struct write_midx_context *ctx = data;
479 if (ends_with(file_name, ".idx")) {
480 display_progress(ctx->progress, ++ctx->pack_paths_checked);
482 * Note that at most one of ctx->m and ctx->to_include are set,
483 * so we are testing midx_contains_pack() and
484 * string_list_has_string() independently (guarded by the
485 * appropriate NULL checks).
487 * We could support passing to_include while reusing an existing
488 * MIDX, but don't currently since the reuse process drags
489 * forward all packs from an existing MIDX (without checking
490 * whether or not they appear in the to_include list).
492 * If we added support for that, these next two conditional
493 * should be performed independently (likely checking
494 * to_include before the existing MIDX).
496 if (ctx->m && midx_contains_pack(ctx->m, file_name))
497 return;
498 else if (ctx->to_include &&
499 !string_list_has_string(ctx->to_include, file_name))
500 return;
502 ALLOC_GROW(ctx->info, ctx->nr + 1, ctx->alloc);
504 ctx->info[ctx->nr].p = add_packed_git(full_path,
505 full_path_len,
508 if (!ctx->info[ctx->nr].p) {
509 warning(_("failed to add packfile '%s'"),
510 full_path);
511 return;
514 if (open_pack_index(ctx->info[ctx->nr].p)) {
515 warning(_("failed to open pack-index '%s'"),
516 full_path);
517 close_pack(ctx->info[ctx->nr].p);
518 FREE_AND_NULL(ctx->info[ctx->nr].p);
519 return;
522 ctx->info[ctx->nr].pack_name = xstrdup(file_name);
523 ctx->info[ctx->nr].orig_pack_int_id = ctx->nr;
524 ctx->info[ctx->nr].expired = 0;
525 ctx->nr++;
529 struct pack_midx_entry {
530 struct object_id oid;
531 uint32_t pack_int_id;
532 time_t pack_mtime;
533 uint64_t offset;
534 unsigned preferred : 1;
537 static int midx_oid_compare(const void *_a, const void *_b)
539 const struct pack_midx_entry *a = (const struct pack_midx_entry *)_a;
540 const struct pack_midx_entry *b = (const struct pack_midx_entry *)_b;
541 int cmp = oidcmp(&a->oid, &b->oid);
543 if (cmp)
544 return cmp;
546 /* Sort objects in a preferred pack first when multiple copies exist. */
547 if (a->preferred > b->preferred)
548 return -1;
549 if (a->preferred < b->preferred)
550 return 1;
552 if (a->pack_mtime > b->pack_mtime)
553 return -1;
554 else if (a->pack_mtime < b->pack_mtime)
555 return 1;
557 return a->pack_int_id - b->pack_int_id;
560 static int nth_midxed_pack_midx_entry(struct multi_pack_index *m,
561 struct pack_midx_entry *e,
562 uint32_t pos)
564 if (pos >= m->num_objects)
565 return 1;
567 nth_midxed_object_oid(&e->oid, m, pos);
568 e->pack_int_id = nth_midxed_pack_int_id(m, pos);
569 e->offset = nth_midxed_offset(m, pos);
571 /* consider objects in midx to be from "old" packs */
572 e->pack_mtime = 0;
573 return 0;
576 static void fill_pack_entry(uint32_t pack_int_id,
577 struct packed_git *p,
578 uint32_t cur_object,
579 struct pack_midx_entry *entry,
580 int preferred)
582 if (nth_packed_object_id(&entry->oid, p, cur_object) < 0)
583 die(_("failed to locate object %d in packfile"), cur_object);
585 entry->pack_int_id = pack_int_id;
586 entry->pack_mtime = p->mtime;
588 entry->offset = nth_packed_object_offset(p, cur_object);
589 entry->preferred = !!preferred;
593 * It is possible to artificially get into a state where there are many
594 * duplicate copies of objects. That can create high memory pressure if
595 * we are to create a list of all objects before de-duplication. To reduce
596 * this memory pressure without a significant performance drop, automatically
597 * group objects by the first byte of their object id. Use the IDX fanout
598 * tables to group the data, copy to a local array, then sort.
600 * Copy only the de-duplicated entries (selected by most-recent modified time
601 * of a packfile containing the object).
603 static struct pack_midx_entry *get_sorted_entries(struct multi_pack_index *m,
604 struct pack_info *info,
605 uint32_t nr_packs,
606 uint32_t *nr_objects,
607 int preferred_pack)
609 uint32_t cur_fanout, cur_pack, cur_object;
610 uint32_t alloc_fanout, alloc_objects, total_objects = 0;
611 struct pack_midx_entry *entries_by_fanout = NULL;
612 struct pack_midx_entry *deduplicated_entries = NULL;
613 uint32_t start_pack = m ? m->num_packs : 0;
615 for (cur_pack = start_pack; cur_pack < nr_packs; cur_pack++)
616 total_objects += info[cur_pack].p->num_objects;
619 * As we de-duplicate by fanout value, we expect the fanout
620 * slices to be evenly distributed, with some noise. Hence,
621 * allocate slightly more than one 256th.
623 alloc_objects = alloc_fanout = total_objects > 3200 ? total_objects / 200 : 16;
625 ALLOC_ARRAY(entries_by_fanout, alloc_fanout);
626 ALLOC_ARRAY(deduplicated_entries, alloc_objects);
627 *nr_objects = 0;
629 for (cur_fanout = 0; cur_fanout < 256; cur_fanout++) {
630 uint32_t nr_fanout = 0;
632 if (m) {
633 uint32_t start = 0, end;
635 if (cur_fanout)
636 start = ntohl(m->chunk_oid_fanout[cur_fanout - 1]);
637 end = ntohl(m->chunk_oid_fanout[cur_fanout]);
639 for (cur_object = start; cur_object < end; cur_object++) {
640 ALLOC_GROW(entries_by_fanout, nr_fanout + 1, alloc_fanout);
641 nth_midxed_pack_midx_entry(m,
642 &entries_by_fanout[nr_fanout],
643 cur_object);
644 if (nth_midxed_pack_int_id(m, cur_object) == preferred_pack)
645 entries_by_fanout[nr_fanout].preferred = 1;
646 else
647 entries_by_fanout[nr_fanout].preferred = 0;
648 nr_fanout++;
652 for (cur_pack = start_pack; cur_pack < nr_packs; cur_pack++) {
653 uint32_t start = 0, end;
654 int preferred = cur_pack == preferred_pack;
656 if (cur_fanout)
657 start = get_pack_fanout(info[cur_pack].p, cur_fanout - 1);
658 end = get_pack_fanout(info[cur_pack].p, cur_fanout);
660 for (cur_object = start; cur_object < end; cur_object++) {
661 ALLOC_GROW(entries_by_fanout, nr_fanout + 1, alloc_fanout);
662 fill_pack_entry(cur_pack,
663 info[cur_pack].p,
664 cur_object,
665 &entries_by_fanout[nr_fanout],
666 preferred);
667 nr_fanout++;
671 QSORT(entries_by_fanout, nr_fanout, midx_oid_compare);
674 * The batch is now sorted by OID and then mtime (descending).
675 * Take only the first duplicate.
677 for (cur_object = 0; cur_object < nr_fanout; cur_object++) {
678 if (cur_object && oideq(&entries_by_fanout[cur_object - 1].oid,
679 &entries_by_fanout[cur_object].oid))
680 continue;
682 ALLOC_GROW(deduplicated_entries, *nr_objects + 1, alloc_objects);
683 memcpy(&deduplicated_entries[*nr_objects],
684 &entries_by_fanout[cur_object],
685 sizeof(struct pack_midx_entry));
686 (*nr_objects)++;
690 free(entries_by_fanout);
691 return deduplicated_entries;
694 static int write_midx_pack_names(struct hashfile *f, void *data)
696 struct write_midx_context *ctx = data;
697 uint32_t i;
698 unsigned char padding[MIDX_CHUNK_ALIGNMENT];
699 size_t written = 0;
701 for (i = 0; i < ctx->nr; i++) {
702 size_t writelen;
704 if (ctx->info[i].expired)
705 continue;
707 if (i && strcmp(ctx->info[i].pack_name, ctx->info[i - 1].pack_name) <= 0)
708 BUG("incorrect pack-file order: %s before %s",
709 ctx->info[i - 1].pack_name,
710 ctx->info[i].pack_name);
712 writelen = strlen(ctx->info[i].pack_name) + 1;
713 hashwrite(f, ctx->info[i].pack_name, writelen);
714 written += writelen;
717 /* add padding to be aligned */
718 i = MIDX_CHUNK_ALIGNMENT - (written % MIDX_CHUNK_ALIGNMENT);
719 if (i < MIDX_CHUNK_ALIGNMENT) {
720 memset(padding, 0, sizeof(padding));
721 hashwrite(f, padding, i);
724 return 0;
727 static int write_midx_oid_fanout(struct hashfile *f,
728 void *data)
730 struct write_midx_context *ctx = data;
731 struct pack_midx_entry *list = ctx->entries;
732 struct pack_midx_entry *last = ctx->entries + ctx->entries_nr;
733 uint32_t count = 0;
734 uint32_t i;
737 * Write the first-level table (the list is sorted,
738 * but we use a 256-entry lookup to be able to avoid
739 * having to do eight extra binary search iterations).
741 for (i = 0; i < 256; i++) {
742 struct pack_midx_entry *next = list;
744 while (next < last && next->oid.hash[0] == i) {
745 count++;
746 next++;
749 hashwrite_be32(f, count);
750 list = next;
753 return 0;
756 static int write_midx_oid_lookup(struct hashfile *f,
757 void *data)
759 struct write_midx_context *ctx = data;
760 unsigned char hash_len = the_hash_algo->rawsz;
761 struct pack_midx_entry *list = ctx->entries;
762 uint32_t i;
764 for (i = 0; i < ctx->entries_nr; i++) {
765 struct pack_midx_entry *obj = list++;
767 if (i < ctx->entries_nr - 1) {
768 struct pack_midx_entry *next = list;
769 if (oidcmp(&obj->oid, &next->oid) >= 0)
770 BUG("OIDs not in order: %s >= %s",
771 oid_to_hex(&obj->oid),
772 oid_to_hex(&next->oid));
775 hashwrite(f, obj->oid.hash, (int)hash_len);
778 return 0;
781 static int write_midx_object_offsets(struct hashfile *f,
782 void *data)
784 struct write_midx_context *ctx = data;
785 struct pack_midx_entry *list = ctx->entries;
786 uint32_t i, nr_large_offset = 0;
788 for (i = 0; i < ctx->entries_nr; i++) {
789 struct pack_midx_entry *obj = list++;
791 if (ctx->pack_perm[obj->pack_int_id] == PACK_EXPIRED)
792 BUG("object %s is in an expired pack with int-id %d",
793 oid_to_hex(&obj->oid),
794 obj->pack_int_id);
796 hashwrite_be32(f, ctx->pack_perm[obj->pack_int_id]);
798 if (ctx->large_offsets_needed && obj->offset >> 31)
799 hashwrite_be32(f, MIDX_LARGE_OFFSET_NEEDED | nr_large_offset++);
800 else if (!ctx->large_offsets_needed && obj->offset >> 32)
801 BUG("object %s requires a large offset (%"PRIx64") but the MIDX is not writing large offsets!",
802 oid_to_hex(&obj->oid),
803 obj->offset);
804 else
805 hashwrite_be32(f, (uint32_t)obj->offset);
808 return 0;
811 static int write_midx_large_offsets(struct hashfile *f,
812 void *data)
814 struct write_midx_context *ctx = data;
815 struct pack_midx_entry *list = ctx->entries;
816 struct pack_midx_entry *end = ctx->entries + ctx->entries_nr;
817 uint32_t nr_large_offset = ctx->num_large_offsets;
819 while (nr_large_offset) {
820 struct pack_midx_entry *obj;
821 uint64_t offset;
823 if (list >= end)
824 BUG("too many large-offset objects");
826 obj = list++;
827 offset = obj->offset;
829 if (!(offset >> 31))
830 continue;
832 hashwrite_be64(f, offset);
834 nr_large_offset--;
837 return 0;
840 static int write_midx_revindex(struct hashfile *f,
841 void *data)
843 struct write_midx_context *ctx = data;
844 uint32_t i;
846 for (i = 0; i < ctx->entries_nr; i++)
847 hashwrite_be32(f, ctx->pack_order[i]);
849 return 0;
852 struct midx_pack_order_data {
853 uint32_t nr;
854 uint32_t pack;
855 off_t offset;
858 static int midx_pack_order_cmp(const void *va, const void *vb)
860 const struct midx_pack_order_data *a = va, *b = vb;
861 if (a->pack < b->pack)
862 return -1;
863 else if (a->pack > b->pack)
864 return 1;
865 else if (a->offset < b->offset)
866 return -1;
867 else if (a->offset > b->offset)
868 return 1;
869 else
870 return 0;
873 static uint32_t *midx_pack_order(struct write_midx_context *ctx)
875 struct midx_pack_order_data *data;
876 uint32_t *pack_order;
877 uint32_t i;
879 ALLOC_ARRAY(data, ctx->entries_nr);
880 for (i = 0; i < ctx->entries_nr; i++) {
881 struct pack_midx_entry *e = &ctx->entries[i];
882 data[i].nr = i;
883 data[i].pack = ctx->pack_perm[e->pack_int_id];
884 if (!e->preferred)
885 data[i].pack |= (1U << 31);
886 data[i].offset = e->offset;
889 QSORT(data, ctx->entries_nr, midx_pack_order_cmp);
891 ALLOC_ARRAY(pack_order, ctx->entries_nr);
892 for (i = 0; i < ctx->entries_nr; i++)
893 pack_order[i] = data[i].nr;
894 free(data);
896 return pack_order;
899 static void write_midx_reverse_index(char *midx_name, unsigned char *midx_hash,
900 struct write_midx_context *ctx)
902 struct strbuf buf = STRBUF_INIT;
903 const char *tmp_file;
905 strbuf_addf(&buf, "%s-%s.rev", midx_name, hash_to_hex(midx_hash));
907 tmp_file = write_rev_file_order(NULL, ctx->pack_order, ctx->entries_nr,
908 midx_hash, WRITE_REV);
910 if (finalize_object_file(tmp_file, buf.buf))
911 die(_("cannot store reverse index file"));
913 strbuf_release(&buf);
916 static void clear_midx_files_ext(const char *object_dir, const char *ext,
917 unsigned char *keep_hash);
919 static int midx_checksum_valid(struct multi_pack_index *m)
921 return hashfile_checksum_valid(m->data, m->data_len);
924 static void prepare_midx_packing_data(struct packing_data *pdata,
925 struct write_midx_context *ctx)
927 uint32_t i;
929 memset(pdata, 0, sizeof(struct packing_data));
930 prepare_packing_data(the_repository, pdata);
932 for (i = 0; i < ctx->entries_nr; i++) {
933 struct pack_midx_entry *from = &ctx->entries[ctx->pack_order[i]];
934 struct object_entry *to = packlist_alloc(pdata, &from->oid);
936 oe_set_in_pack(pdata, to,
937 ctx->info[ctx->pack_perm[from->pack_int_id]].p);
941 static int add_ref_to_pending(const char *refname,
942 const struct object_id *oid,
943 int flag, void *cb_data)
945 struct rev_info *revs = (struct rev_info*)cb_data;
946 struct object *object;
948 if ((flag & REF_ISSYMREF) && (flag & REF_ISBROKEN)) {
949 warning("symbolic ref is dangling: %s", refname);
950 return 0;
953 object = parse_object_or_die(oid, refname);
954 if (object->type != OBJ_COMMIT)
955 return 0;
957 add_pending_object(revs, object, "");
958 if (bitmap_is_preferred_refname(revs->repo, refname))
959 object->flags |= NEEDS_BITMAP;
960 return 0;
963 struct bitmap_commit_cb {
964 struct commit **commits;
965 size_t commits_nr, commits_alloc;
967 struct write_midx_context *ctx;
970 static const struct object_id *bitmap_oid_access(size_t index,
971 const void *_entries)
973 const struct pack_midx_entry *entries = _entries;
974 return &entries[index].oid;
977 static void bitmap_show_commit(struct commit *commit, void *_data)
979 struct bitmap_commit_cb *data = _data;
980 int pos = oid_pos(&commit->object.oid, data->ctx->entries,
981 data->ctx->entries_nr,
982 bitmap_oid_access);
983 if (pos < 0)
984 return;
986 ALLOC_GROW(data->commits, data->commits_nr + 1, data->commits_alloc);
987 data->commits[data->commits_nr++] = commit;
990 static int read_refs_snapshot(const char *refs_snapshot,
991 struct rev_info *revs)
993 struct strbuf buf = STRBUF_INIT;
994 struct object_id oid;
995 FILE *f = xfopen(refs_snapshot, "r");
997 while (strbuf_getline(&buf, f) != EOF) {
998 struct object *object;
999 int preferred = 0;
1000 char *hex = buf.buf;
1001 const char *end = NULL;
1003 if (buf.len && *buf.buf == '+') {
1004 preferred = 1;
1005 hex = &buf.buf[1];
1008 if (parse_oid_hex(hex, &oid, &end) < 0)
1009 die(_("could not parse line: %s"), buf.buf);
1010 if (*end)
1011 die(_("malformed line: %s"), buf.buf);
1013 object = parse_object_or_die(&oid, NULL);
1014 if (preferred)
1015 object->flags |= NEEDS_BITMAP;
1017 add_pending_object(revs, object, "");
1020 fclose(f);
1021 strbuf_release(&buf);
1022 return 0;
1025 static struct commit **find_commits_for_midx_bitmap(uint32_t *indexed_commits_nr_p,
1026 const char *refs_snapshot,
1027 struct write_midx_context *ctx)
1029 struct rev_info revs;
1030 struct bitmap_commit_cb cb = {0};
1032 cb.ctx = ctx;
1034 repo_init_revisions(the_repository, &revs, NULL);
1035 if (refs_snapshot) {
1036 read_refs_snapshot(refs_snapshot, &revs);
1037 } else {
1038 setup_revisions(0, NULL, &revs, NULL);
1039 for_each_ref(add_ref_to_pending, &revs);
1043 * Skipping promisor objects here is intentional, since it only excludes
1044 * them from the list of reachable commits that we want to select from
1045 * when computing the selection of MIDX'd commits to receive bitmaps.
1047 * Reachability bitmaps do require that their objects be closed under
1048 * reachability, but fetching any objects missing from promisors at this
1049 * point is too late. But, if one of those objects can be reached from
1050 * an another object that is included in the bitmap, then we will
1051 * complain later that we don't have reachability closure (and fail
1052 * appropriately).
1054 fetch_if_missing = 0;
1055 revs.exclude_promisor_objects = 1;
1057 if (prepare_revision_walk(&revs))
1058 die(_("revision walk setup failed"));
1060 traverse_commit_list(&revs, bitmap_show_commit, NULL, &cb);
1061 if (indexed_commits_nr_p)
1062 *indexed_commits_nr_p = cb.commits_nr;
1064 return cb.commits;
1067 static int write_midx_bitmap(char *midx_name, unsigned char *midx_hash,
1068 struct write_midx_context *ctx,
1069 const char *refs_snapshot,
1070 unsigned flags)
1072 struct packing_data pdata;
1073 struct pack_idx_entry **index;
1074 struct commit **commits = NULL;
1075 uint32_t i, commits_nr;
1076 uint16_t options = 0;
1077 char *bitmap_name = xstrfmt("%s-%s.bitmap", midx_name, hash_to_hex(midx_hash));
1078 int ret;
1080 if (!ctx->entries_nr)
1081 BUG("cannot write a bitmap without any objects");
1083 if (flags & MIDX_WRITE_BITMAP_HASH_CACHE)
1084 options |= BITMAP_OPT_HASH_CACHE;
1086 prepare_midx_packing_data(&pdata, ctx);
1088 commits = find_commits_for_midx_bitmap(&commits_nr, refs_snapshot, ctx);
1091 * Build the MIDX-order index based on pdata.objects (which is already
1092 * in MIDX order; c.f., 'midx_pack_order_cmp()' for the definition of
1093 * this order).
1095 ALLOC_ARRAY(index, pdata.nr_objects);
1096 for (i = 0; i < pdata.nr_objects; i++)
1097 index[i] = &pdata.objects[i].idx;
1099 bitmap_writer_show_progress(flags & MIDX_PROGRESS);
1100 bitmap_writer_build_type_index(&pdata, index, pdata.nr_objects);
1103 * bitmap_writer_finish expects objects in lex order, but pack_order
1104 * gives us exactly that. use it directly instead of re-sorting the
1105 * array.
1107 * This changes the order of objects in 'index' between
1108 * bitmap_writer_build_type_index and bitmap_writer_finish.
1110 * The same re-ordering takes place in the single-pack bitmap code via
1111 * write_idx_file(), which is called by finish_tmp_packfile(), which
1112 * happens between bitmap_writer_build_type_index() and
1113 * bitmap_writer_finish().
1115 for (i = 0; i < pdata.nr_objects; i++)
1116 index[ctx->pack_order[i]] = &pdata.objects[i].idx;
1118 bitmap_writer_select_commits(commits, commits_nr, -1);
1119 ret = bitmap_writer_build(&pdata);
1120 if (ret < 0)
1121 goto cleanup;
1123 bitmap_writer_set_checksum(midx_hash);
1124 bitmap_writer_finish(index, pdata.nr_objects, bitmap_name, options);
1126 cleanup:
1127 free(index);
1128 free(bitmap_name);
1129 return ret;
1132 static struct multi_pack_index *lookup_multi_pack_index(struct repository *r,
1133 const char *object_dir)
1135 struct multi_pack_index *result = NULL;
1136 struct multi_pack_index *cur;
1137 char *obj_dir_real = real_pathdup(object_dir, 1);
1138 struct strbuf cur_path_real = STRBUF_INIT;
1140 /* Ensure the given object_dir is local, or a known alternate. */
1141 find_odb(r, obj_dir_real);
1143 for (cur = get_multi_pack_index(r); cur; cur = cur->next) {
1144 strbuf_realpath(&cur_path_real, cur->object_dir, 1);
1145 if (!strcmp(obj_dir_real, cur_path_real.buf)) {
1146 result = cur;
1147 goto cleanup;
1151 cleanup:
1152 free(obj_dir_real);
1153 strbuf_release(&cur_path_real);
1154 return result;
1157 static int write_midx_internal(const char *object_dir,
1158 struct string_list *packs_to_include,
1159 struct string_list *packs_to_drop,
1160 const char *preferred_pack_name,
1161 const char *refs_snapshot,
1162 unsigned flags)
1164 struct strbuf midx_name = STRBUF_INIT;
1165 unsigned char midx_hash[GIT_MAX_RAWSZ];
1166 uint32_t i;
1167 struct hashfile *f = NULL;
1168 struct lock_file lk;
1169 struct write_midx_context ctx = { 0 };
1170 int pack_name_concat_len = 0;
1171 int dropped_packs = 0;
1172 int result = 0;
1173 struct chunkfile *cf;
1175 get_midx_filename(&midx_name, object_dir);
1176 if (safe_create_leading_directories(midx_name.buf))
1177 die_errno(_("unable to create leading directories of %s"),
1178 midx_name.buf);
1180 if (!packs_to_include) {
1182 * Only reference an existing MIDX when not filtering which
1183 * packs to include, since all packs and objects are copied
1184 * blindly from an existing MIDX if one is present.
1186 ctx.m = lookup_multi_pack_index(the_repository, object_dir);
1189 if (ctx.m && !midx_checksum_valid(ctx.m)) {
1190 warning(_("ignoring existing multi-pack-index; checksum mismatch"));
1191 ctx.m = NULL;
1194 ctx.nr = 0;
1195 ctx.alloc = ctx.m ? ctx.m->num_packs : 16;
1196 ctx.info = NULL;
1197 ALLOC_ARRAY(ctx.info, ctx.alloc);
1199 if (ctx.m) {
1200 for (i = 0; i < ctx.m->num_packs; i++) {
1201 ALLOC_GROW(ctx.info, ctx.nr + 1, ctx.alloc);
1203 ctx.info[ctx.nr].orig_pack_int_id = i;
1204 ctx.info[ctx.nr].pack_name = xstrdup(ctx.m->pack_names[i]);
1205 ctx.info[ctx.nr].p = ctx.m->packs[i];
1206 ctx.info[ctx.nr].expired = 0;
1208 if (flags & MIDX_WRITE_REV_INDEX) {
1210 * If generating a reverse index, need to have
1211 * packed_git's loaded to compare their
1212 * mtimes and object count.
1214 if (prepare_midx_pack(the_repository, ctx.m, i)) {
1215 error(_("could not load pack"));
1216 result = 1;
1217 goto cleanup;
1220 if (open_pack_index(ctx.m->packs[i]))
1221 die(_("could not open index for %s"),
1222 ctx.m->packs[i]->pack_name);
1223 ctx.info[ctx.nr].p = ctx.m->packs[i];
1226 ctx.nr++;
1230 ctx.pack_paths_checked = 0;
1231 if (flags & MIDX_PROGRESS)
1232 ctx.progress = start_delayed_progress(_("Adding packfiles to multi-pack-index"), 0);
1233 else
1234 ctx.progress = NULL;
1236 ctx.to_include = packs_to_include;
1238 for_each_file_in_pack_dir(object_dir, add_pack_to_midx, &ctx);
1239 stop_progress(&ctx.progress);
1241 if ((ctx.m && ctx.nr == ctx.m->num_packs) &&
1242 !(packs_to_include || packs_to_drop)) {
1243 struct bitmap_index *bitmap_git;
1244 int bitmap_exists;
1245 int want_bitmap = flags & MIDX_WRITE_BITMAP;
1247 bitmap_git = prepare_midx_bitmap_git(ctx.m);
1248 bitmap_exists = bitmap_git && bitmap_is_midx(bitmap_git);
1249 free_bitmap_index(bitmap_git);
1251 if (bitmap_exists || !want_bitmap) {
1253 * The correct MIDX already exists, and so does a
1254 * corresponding bitmap (or one wasn't requested).
1256 if (!want_bitmap)
1257 clear_midx_files_ext(object_dir, ".bitmap",
1258 NULL);
1259 goto cleanup;
1263 if (preferred_pack_name) {
1264 int found = 0;
1265 for (i = 0; i < ctx.nr; i++) {
1266 if (!cmp_idx_or_pack_name(preferred_pack_name,
1267 ctx.info[i].pack_name)) {
1268 ctx.preferred_pack_idx = i;
1269 found = 1;
1270 break;
1274 if (!found)
1275 warning(_("unknown preferred pack: '%s'"),
1276 preferred_pack_name);
1277 } else if (ctx.nr &&
1278 (flags & (MIDX_WRITE_REV_INDEX | MIDX_WRITE_BITMAP))) {
1279 struct packed_git *oldest = ctx.info[ctx.preferred_pack_idx].p;
1280 ctx.preferred_pack_idx = 0;
1282 if (packs_to_drop && packs_to_drop->nr)
1283 BUG("cannot write a MIDX bitmap during expiration");
1286 * set a preferred pack when writing a bitmap to ensure that
1287 * the pack from which the first object is selected in pseudo
1288 * pack-order has all of its objects selected from that pack
1289 * (and not another pack containing a duplicate)
1291 for (i = 1; i < ctx.nr; i++) {
1292 struct packed_git *p = ctx.info[i].p;
1294 if (!oldest->num_objects || p->mtime < oldest->mtime) {
1295 oldest = p;
1296 ctx.preferred_pack_idx = i;
1300 if (!oldest->num_objects) {
1302 * If all packs are empty; unset the preferred index.
1303 * This is acceptable since there will be no duplicate
1304 * objects to resolve, so the preferred value doesn't
1305 * matter.
1307 ctx.preferred_pack_idx = -1;
1309 } else {
1311 * otherwise don't mark any pack as preferred to avoid
1312 * interfering with expiration logic below
1314 ctx.preferred_pack_idx = -1;
1317 if (ctx.preferred_pack_idx > -1) {
1318 struct packed_git *preferred = ctx.info[ctx.preferred_pack_idx].p;
1319 if (!preferred->num_objects) {
1320 error(_("cannot select preferred pack %s with no objects"),
1321 preferred->pack_name);
1322 result = 1;
1323 goto cleanup;
1327 ctx.entries = get_sorted_entries(ctx.m, ctx.info, ctx.nr, &ctx.entries_nr,
1328 ctx.preferred_pack_idx);
1330 ctx.large_offsets_needed = 0;
1331 for (i = 0; i < ctx.entries_nr; i++) {
1332 if (ctx.entries[i].offset > 0x7fffffff)
1333 ctx.num_large_offsets++;
1334 if (ctx.entries[i].offset > 0xffffffff)
1335 ctx.large_offsets_needed = 1;
1338 QSORT(ctx.info, ctx.nr, pack_info_compare);
1340 if (packs_to_drop && packs_to_drop->nr) {
1341 int drop_index = 0;
1342 int missing_drops = 0;
1344 for (i = 0; i < ctx.nr && drop_index < packs_to_drop->nr; i++) {
1345 int cmp = strcmp(ctx.info[i].pack_name,
1346 packs_to_drop->items[drop_index].string);
1348 if (!cmp) {
1349 drop_index++;
1350 ctx.info[i].expired = 1;
1351 } else if (cmp > 0) {
1352 error(_("did not see pack-file %s to drop"),
1353 packs_to_drop->items[drop_index].string);
1354 drop_index++;
1355 missing_drops++;
1356 i--;
1357 } else {
1358 ctx.info[i].expired = 0;
1362 if (missing_drops) {
1363 result = 1;
1364 goto cleanup;
1369 * pack_perm stores a permutation between pack-int-ids from the
1370 * previous multi-pack-index to the new one we are writing:
1372 * pack_perm[old_id] = new_id
1374 ALLOC_ARRAY(ctx.pack_perm, ctx.nr);
1375 for (i = 0; i < ctx.nr; i++) {
1376 if (ctx.info[i].expired) {
1377 dropped_packs++;
1378 ctx.pack_perm[ctx.info[i].orig_pack_int_id] = PACK_EXPIRED;
1379 } else {
1380 ctx.pack_perm[ctx.info[i].orig_pack_int_id] = i - dropped_packs;
1384 for (i = 0; i < ctx.nr; i++) {
1385 if (!ctx.info[i].expired)
1386 pack_name_concat_len += strlen(ctx.info[i].pack_name) + 1;
1389 /* Check that the preferred pack wasn't expired (if given). */
1390 if (preferred_pack_name) {
1391 struct pack_info *preferred = bsearch(preferred_pack_name,
1392 ctx.info, ctx.nr,
1393 sizeof(*ctx.info),
1394 idx_or_pack_name_cmp);
1395 if (preferred) {
1396 uint32_t perm = ctx.pack_perm[preferred->orig_pack_int_id];
1397 if (perm == PACK_EXPIRED)
1398 warning(_("preferred pack '%s' is expired"),
1399 preferred_pack_name);
1403 if (pack_name_concat_len % MIDX_CHUNK_ALIGNMENT)
1404 pack_name_concat_len += MIDX_CHUNK_ALIGNMENT -
1405 (pack_name_concat_len % MIDX_CHUNK_ALIGNMENT);
1407 hold_lock_file_for_update(&lk, midx_name.buf, LOCK_DIE_ON_ERROR);
1408 f = hashfd(get_lock_file_fd(&lk), get_lock_file_path(&lk));
1410 if (ctx.nr - dropped_packs == 0) {
1411 error(_("no pack files to index."));
1412 result = 1;
1413 goto cleanup;
1416 if (!ctx.entries_nr) {
1417 if (flags & MIDX_WRITE_BITMAP)
1418 warning(_("refusing to write multi-pack .bitmap without any objects"));
1419 flags &= ~(MIDX_WRITE_REV_INDEX | MIDX_WRITE_BITMAP);
1422 cf = init_chunkfile(f);
1424 add_chunk(cf, MIDX_CHUNKID_PACKNAMES, pack_name_concat_len,
1425 write_midx_pack_names);
1426 add_chunk(cf, MIDX_CHUNKID_OIDFANOUT, MIDX_CHUNK_FANOUT_SIZE,
1427 write_midx_oid_fanout);
1428 add_chunk(cf, MIDX_CHUNKID_OIDLOOKUP,
1429 (size_t)ctx.entries_nr * the_hash_algo->rawsz,
1430 write_midx_oid_lookup);
1431 add_chunk(cf, MIDX_CHUNKID_OBJECTOFFSETS,
1432 (size_t)ctx.entries_nr * MIDX_CHUNK_OFFSET_WIDTH,
1433 write_midx_object_offsets);
1435 if (ctx.large_offsets_needed)
1436 add_chunk(cf, MIDX_CHUNKID_LARGEOFFSETS,
1437 (size_t)ctx.num_large_offsets * MIDX_CHUNK_LARGE_OFFSET_WIDTH,
1438 write_midx_large_offsets);
1440 if (flags & (MIDX_WRITE_REV_INDEX | MIDX_WRITE_BITMAP)) {
1441 ctx.pack_order = midx_pack_order(&ctx);
1442 add_chunk(cf, MIDX_CHUNKID_REVINDEX,
1443 ctx.entries_nr * sizeof(uint32_t),
1444 write_midx_revindex);
1447 write_midx_header(f, get_num_chunks(cf), ctx.nr - dropped_packs);
1448 write_chunkfile(cf, &ctx);
1450 finalize_hashfile(f, midx_hash, FSYNC_COMPONENT_PACK_METADATA,
1451 CSUM_FSYNC | CSUM_HASH_IN_STREAM);
1452 free_chunkfile(cf);
1454 if (flags & MIDX_WRITE_REV_INDEX &&
1455 git_env_bool("GIT_TEST_MIDX_WRITE_REV", 0))
1456 write_midx_reverse_index(midx_name.buf, midx_hash, &ctx);
1457 if (flags & MIDX_WRITE_BITMAP) {
1458 if (write_midx_bitmap(midx_name.buf, midx_hash, &ctx,
1459 refs_snapshot, flags) < 0) {
1460 error(_("could not write multi-pack bitmap"));
1461 result = 1;
1462 goto cleanup;
1466 if (ctx.m)
1467 close_object_store(the_repository->objects);
1469 if (commit_lock_file(&lk) < 0)
1470 die_errno(_("could not write multi-pack-index"));
1472 clear_midx_files_ext(object_dir, ".bitmap", midx_hash);
1473 clear_midx_files_ext(object_dir, ".rev", midx_hash);
1475 cleanup:
1476 for (i = 0; i < ctx.nr; i++) {
1477 if (ctx.info[i].p) {
1478 close_pack(ctx.info[i].p);
1479 free(ctx.info[i].p);
1481 free(ctx.info[i].pack_name);
1484 free(ctx.info);
1485 free(ctx.entries);
1486 free(ctx.pack_perm);
1487 free(ctx.pack_order);
1488 strbuf_release(&midx_name);
1490 return result;
1493 int write_midx_file(const char *object_dir,
1494 const char *preferred_pack_name,
1495 const char *refs_snapshot,
1496 unsigned flags)
1498 return write_midx_internal(object_dir, NULL, NULL, preferred_pack_name,
1499 refs_snapshot, flags);
1502 int write_midx_file_only(const char *object_dir,
1503 struct string_list *packs_to_include,
1504 const char *preferred_pack_name,
1505 const char *refs_snapshot,
1506 unsigned flags)
1508 return write_midx_internal(object_dir, packs_to_include, NULL,
1509 preferred_pack_name, refs_snapshot, flags);
1512 struct clear_midx_data {
1513 char *keep;
1514 const char *ext;
1517 static void clear_midx_file_ext(const char *full_path, size_t full_path_len,
1518 const char *file_name, void *_data)
1520 struct clear_midx_data *data = _data;
1522 if (!(starts_with(file_name, "multi-pack-index-") &&
1523 ends_with(file_name, data->ext)))
1524 return;
1525 if (data->keep && !strcmp(data->keep, file_name))
1526 return;
1528 if (unlink(full_path))
1529 die_errno(_("failed to remove %s"), full_path);
1532 static void clear_midx_files_ext(const char *object_dir, const char *ext,
1533 unsigned char *keep_hash)
1535 struct clear_midx_data data;
1536 memset(&data, 0, sizeof(struct clear_midx_data));
1538 if (keep_hash)
1539 data.keep = xstrfmt("multi-pack-index-%s%s",
1540 hash_to_hex(keep_hash), ext);
1541 data.ext = ext;
1543 for_each_file_in_pack_dir(object_dir,
1544 clear_midx_file_ext,
1545 &data);
1547 free(data.keep);
1550 void clear_midx_file(struct repository *r)
1552 struct strbuf midx = STRBUF_INIT;
1554 get_midx_filename(&midx, r->objects->odb->path);
1556 if (r->objects && r->objects->multi_pack_index) {
1557 close_midx(r->objects->multi_pack_index);
1558 r->objects->multi_pack_index = NULL;
1561 if (remove_path(midx.buf))
1562 die(_("failed to clear multi-pack-index at %s"), midx.buf);
1564 clear_midx_files_ext(r->objects->odb->path, ".bitmap", NULL);
1565 clear_midx_files_ext(r->objects->odb->path, ".rev", NULL);
1567 strbuf_release(&midx);
1570 static int verify_midx_error;
1572 __attribute__((format (printf, 1, 2)))
1573 static void midx_report(const char *fmt, ...)
1575 va_list ap;
1576 verify_midx_error = 1;
1577 va_start(ap, fmt);
1578 vfprintf(stderr, fmt, ap);
1579 fprintf(stderr, "\n");
1580 va_end(ap);
1583 struct pair_pos_vs_id
1585 uint32_t pos;
1586 uint32_t pack_int_id;
1589 static int compare_pair_pos_vs_id(const void *_a, const void *_b)
1591 struct pair_pos_vs_id *a = (struct pair_pos_vs_id *)_a;
1592 struct pair_pos_vs_id *b = (struct pair_pos_vs_id *)_b;
1594 return b->pack_int_id - a->pack_int_id;
1598 * Limit calls to display_progress() for performance reasons.
1599 * The interval here was arbitrarily chosen.
1601 #define SPARSE_PROGRESS_INTERVAL (1 << 12)
1602 #define midx_display_sparse_progress(progress, n) \
1603 do { \
1604 uint64_t _n = (n); \
1605 if ((_n & (SPARSE_PROGRESS_INTERVAL - 1)) == 0) \
1606 display_progress(progress, _n); \
1607 } while (0)
1609 int verify_midx_file(struct repository *r, const char *object_dir, unsigned flags)
1611 struct pair_pos_vs_id *pairs = NULL;
1612 uint32_t i;
1613 struct progress *progress = NULL;
1614 struct multi_pack_index *m = load_multi_pack_index(object_dir, 1);
1615 verify_midx_error = 0;
1617 if (!m) {
1618 int result = 0;
1619 struct stat sb;
1620 struct strbuf filename = STRBUF_INIT;
1622 get_midx_filename(&filename, object_dir);
1624 if (!stat(filename.buf, &sb)) {
1625 error(_("multi-pack-index file exists, but failed to parse"));
1626 result = 1;
1628 strbuf_release(&filename);
1629 return result;
1632 if (!midx_checksum_valid(m))
1633 midx_report(_("incorrect checksum"));
1635 if (flags & MIDX_PROGRESS)
1636 progress = start_delayed_progress(_("Looking for referenced packfiles"),
1637 m->num_packs);
1638 for (i = 0; i < m->num_packs; i++) {
1639 if (prepare_midx_pack(r, m, i))
1640 midx_report("failed to load pack in position %d", i);
1642 display_progress(progress, i + 1);
1644 stop_progress(&progress);
1646 for (i = 0; i < 255; i++) {
1647 uint32_t oid_fanout1 = ntohl(m->chunk_oid_fanout[i]);
1648 uint32_t oid_fanout2 = ntohl(m->chunk_oid_fanout[i + 1]);
1650 if (oid_fanout1 > oid_fanout2)
1651 midx_report(_("oid fanout out of order: fanout[%d] = %"PRIx32" > %"PRIx32" = fanout[%d]"),
1652 i, oid_fanout1, oid_fanout2, i + 1);
1655 if (m->num_objects == 0) {
1656 midx_report(_("the midx contains no oid"));
1658 * Remaining tests assume that we have objects, so we can
1659 * return here.
1661 goto cleanup;
1664 if (flags & MIDX_PROGRESS)
1665 progress = start_sparse_progress(_("Verifying OID order in multi-pack-index"),
1666 m->num_objects - 1);
1667 for (i = 0; i < m->num_objects - 1; i++) {
1668 struct object_id oid1, oid2;
1670 nth_midxed_object_oid(&oid1, m, i);
1671 nth_midxed_object_oid(&oid2, m, i + 1);
1673 if (oidcmp(&oid1, &oid2) >= 0)
1674 midx_report(_("oid lookup out of order: oid[%d] = %s >= %s = oid[%d]"),
1675 i, oid_to_hex(&oid1), oid_to_hex(&oid2), i + 1);
1677 midx_display_sparse_progress(progress, i + 1);
1679 stop_progress(&progress);
1682 * Create an array mapping each object to its packfile id. Sort it
1683 * to group the objects by packfile. Use this permutation to visit
1684 * each of the objects and only require 1 packfile to be open at a
1685 * time.
1687 ALLOC_ARRAY(pairs, m->num_objects);
1688 for (i = 0; i < m->num_objects; i++) {
1689 pairs[i].pos = i;
1690 pairs[i].pack_int_id = nth_midxed_pack_int_id(m, i);
1693 if (flags & MIDX_PROGRESS)
1694 progress = start_sparse_progress(_("Sorting objects by packfile"),
1695 m->num_objects);
1696 display_progress(progress, 0); /* TODO: Measure QSORT() progress */
1697 QSORT(pairs, m->num_objects, compare_pair_pos_vs_id);
1698 stop_progress(&progress);
1700 if (flags & MIDX_PROGRESS)
1701 progress = start_sparse_progress(_("Verifying object offsets"), m->num_objects);
1702 for (i = 0; i < m->num_objects; i++) {
1703 struct object_id oid;
1704 struct pack_entry e;
1705 off_t m_offset, p_offset;
1707 if (i > 0 && pairs[i-1].pack_int_id != pairs[i].pack_int_id &&
1708 m->packs[pairs[i-1].pack_int_id])
1710 close_pack_fd(m->packs[pairs[i-1].pack_int_id]);
1711 close_pack_index(m->packs[pairs[i-1].pack_int_id]);
1714 nth_midxed_object_oid(&oid, m, pairs[i].pos);
1716 if (!fill_midx_entry(r, &oid, &e, m)) {
1717 midx_report(_("failed to load pack entry for oid[%d] = %s"),
1718 pairs[i].pos, oid_to_hex(&oid));
1719 continue;
1722 if (open_pack_index(e.p)) {
1723 midx_report(_("failed to load pack-index for packfile %s"),
1724 e.p->pack_name);
1725 break;
1728 m_offset = e.offset;
1729 p_offset = find_pack_entry_one(oid.hash, e.p);
1731 if (m_offset != p_offset)
1732 midx_report(_("incorrect object offset for oid[%d] = %s: %"PRIx64" != %"PRIx64),
1733 pairs[i].pos, oid_to_hex(&oid), m_offset, p_offset);
1735 midx_display_sparse_progress(progress, i + 1);
1737 stop_progress(&progress);
1739 cleanup:
1740 free(pairs);
1741 close_midx(m);
1743 return verify_midx_error;
1746 int expire_midx_packs(struct repository *r, const char *object_dir, unsigned flags)
1748 uint32_t i, *count, result = 0;
1749 struct string_list packs_to_drop = STRING_LIST_INIT_DUP;
1750 struct multi_pack_index *m = lookup_multi_pack_index(r, object_dir);
1751 struct progress *progress = NULL;
1753 if (!m)
1754 return 0;
1756 CALLOC_ARRAY(count, m->num_packs);
1758 if (flags & MIDX_PROGRESS)
1759 progress = start_delayed_progress(_("Counting referenced objects"),
1760 m->num_objects);
1761 for (i = 0; i < m->num_objects; i++) {
1762 int pack_int_id = nth_midxed_pack_int_id(m, i);
1763 count[pack_int_id]++;
1764 display_progress(progress, i + 1);
1766 stop_progress(&progress);
1768 if (flags & MIDX_PROGRESS)
1769 progress = start_delayed_progress(_("Finding and deleting unreferenced packfiles"),
1770 m->num_packs);
1771 for (i = 0; i < m->num_packs; i++) {
1772 char *pack_name;
1773 display_progress(progress, i + 1);
1775 if (count[i])
1776 continue;
1778 if (prepare_midx_pack(r, m, i))
1779 continue;
1781 if (m->packs[i]->pack_keep)
1782 continue;
1784 pack_name = xstrdup(m->packs[i]->pack_name);
1785 close_pack(m->packs[i]);
1787 string_list_insert(&packs_to_drop, m->pack_names[i]);
1788 unlink_pack_path(pack_name, 0);
1789 free(pack_name);
1791 stop_progress(&progress);
1793 free(count);
1795 if (packs_to_drop.nr)
1796 result = write_midx_internal(object_dir, NULL, &packs_to_drop, NULL, NULL, flags);
1798 string_list_clear(&packs_to_drop, 0);
1800 return result;
1803 struct repack_info {
1804 timestamp_t mtime;
1805 uint32_t referenced_objects;
1806 uint32_t pack_int_id;
1809 static int compare_by_mtime(const void *a_, const void *b_)
1811 const struct repack_info *a, *b;
1813 a = (const struct repack_info *)a_;
1814 b = (const struct repack_info *)b_;
1816 if (a->mtime < b->mtime)
1817 return -1;
1818 if (a->mtime > b->mtime)
1819 return 1;
1820 return 0;
1823 static int fill_included_packs_all(struct repository *r,
1824 struct multi_pack_index *m,
1825 unsigned char *include_pack)
1827 uint32_t i, count = 0;
1828 int pack_kept_objects = 0;
1830 repo_config_get_bool(r, "repack.packkeptobjects", &pack_kept_objects);
1832 for (i = 0; i < m->num_packs; i++) {
1833 if (prepare_midx_pack(r, m, i))
1834 continue;
1835 if (!pack_kept_objects && m->packs[i]->pack_keep)
1836 continue;
1838 include_pack[i] = 1;
1839 count++;
1842 return count < 2;
1845 static int fill_included_packs_batch(struct repository *r,
1846 struct multi_pack_index *m,
1847 unsigned char *include_pack,
1848 size_t batch_size)
1850 uint32_t i, packs_to_repack;
1851 size_t total_size;
1852 struct repack_info *pack_info = xcalloc(m->num_packs, sizeof(struct repack_info));
1853 int pack_kept_objects = 0;
1855 repo_config_get_bool(r, "repack.packkeptobjects", &pack_kept_objects);
1857 for (i = 0; i < m->num_packs; i++) {
1858 pack_info[i].pack_int_id = i;
1860 if (prepare_midx_pack(r, m, i))
1861 continue;
1863 pack_info[i].mtime = m->packs[i]->mtime;
1866 for (i = 0; batch_size && i < m->num_objects; i++) {
1867 uint32_t pack_int_id = nth_midxed_pack_int_id(m, i);
1868 pack_info[pack_int_id].referenced_objects++;
1871 QSORT(pack_info, m->num_packs, compare_by_mtime);
1873 total_size = 0;
1874 packs_to_repack = 0;
1875 for (i = 0; total_size < batch_size && i < m->num_packs; i++) {
1876 int pack_int_id = pack_info[i].pack_int_id;
1877 struct packed_git *p = m->packs[pack_int_id];
1878 size_t expected_size;
1880 if (!p)
1881 continue;
1882 if (!pack_kept_objects && p->pack_keep)
1883 continue;
1884 if (open_pack_index(p) || !p->num_objects)
1885 continue;
1887 expected_size = (size_t)(p->pack_size
1888 * pack_info[i].referenced_objects);
1889 expected_size /= p->num_objects;
1891 if (expected_size >= batch_size)
1892 continue;
1894 packs_to_repack++;
1895 total_size += expected_size;
1896 include_pack[pack_int_id] = 1;
1899 free(pack_info);
1901 if (packs_to_repack < 2)
1902 return 1;
1904 return 0;
1907 int midx_repack(struct repository *r, const char *object_dir, size_t batch_size, unsigned flags)
1909 int result = 0;
1910 uint32_t i;
1911 unsigned char *include_pack;
1912 struct child_process cmd = CHILD_PROCESS_INIT;
1913 FILE *cmd_in;
1914 struct strbuf base_name = STRBUF_INIT;
1915 struct multi_pack_index *m = lookup_multi_pack_index(r, object_dir);
1918 * When updating the default for these configuration
1919 * variables in builtin/repack.c, these must be adjusted
1920 * to match.
1922 int delta_base_offset = 1;
1923 int use_delta_islands = 0;
1925 if (!m)
1926 return 0;
1928 CALLOC_ARRAY(include_pack, m->num_packs);
1930 if (batch_size) {
1931 if (fill_included_packs_batch(r, m, include_pack, batch_size))
1932 goto cleanup;
1933 } else if (fill_included_packs_all(r, m, include_pack))
1934 goto cleanup;
1936 repo_config_get_bool(r, "repack.usedeltabaseoffset", &delta_base_offset);
1937 repo_config_get_bool(r, "repack.usedeltaislands", &use_delta_islands);
1939 strvec_push(&cmd.args, "pack-objects");
1941 strbuf_addstr(&base_name, object_dir);
1942 strbuf_addstr(&base_name, "/pack/pack");
1943 strvec_push(&cmd.args, base_name.buf);
1945 if (delta_base_offset)
1946 strvec_push(&cmd.args, "--delta-base-offset");
1947 if (use_delta_islands)
1948 strvec_push(&cmd.args, "--delta-islands");
1950 if (flags & MIDX_PROGRESS)
1951 strvec_push(&cmd.args, "--progress");
1952 else
1953 strvec_push(&cmd.args, "-q");
1955 strbuf_release(&base_name);
1957 cmd.git_cmd = 1;
1958 cmd.in = cmd.out = -1;
1960 if (start_command(&cmd)) {
1961 error(_("could not start pack-objects"));
1962 result = 1;
1963 goto cleanup;
1966 cmd_in = xfdopen(cmd.in, "w");
1968 for (i = 0; i < m->num_objects; i++) {
1969 struct object_id oid;
1970 uint32_t pack_int_id = nth_midxed_pack_int_id(m, i);
1972 if (!include_pack[pack_int_id])
1973 continue;
1975 nth_midxed_object_oid(&oid, m, i);
1976 fprintf(cmd_in, "%s\n", oid_to_hex(&oid));
1978 fclose(cmd_in);
1980 if (finish_command(&cmd)) {
1981 error(_("could not finish pack-objects"));
1982 result = 1;
1983 goto cleanup;
1986 result = write_midx_internal(object_dir, NULL, NULL, NULL, NULL, flags);
1988 cleanup:
1989 free(include_pack);
1990 return result;