midx: use chunk-format API in write_midx_internal()
[git/debian.git] / midx.c
blobd2fd9c10feea03e8975c153c47a03ecedc4e6b06
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 "sha1-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"
16 #define MIDX_SIGNATURE 0x4d494458 /* "MIDX" */
17 #define MIDX_VERSION 1
18 #define MIDX_BYTE_FILE_VERSION 4
19 #define MIDX_BYTE_HASH_VERSION 5
20 #define MIDX_BYTE_NUM_CHUNKS 6
21 #define MIDX_BYTE_NUM_PACKS 8
22 #define MIDX_HEADER_SIZE 12
23 #define MIDX_MIN_SIZE (MIDX_HEADER_SIZE + the_hash_algo->rawsz)
25 #define MIDX_CHUNK_ALIGNMENT 4
26 #define MIDX_CHUNKID_PACKNAMES 0x504e414d /* "PNAM" */
27 #define MIDX_CHUNKID_OIDFANOUT 0x4f494446 /* "OIDF" */
28 #define MIDX_CHUNKID_OIDLOOKUP 0x4f49444c /* "OIDL" */
29 #define MIDX_CHUNKID_OBJECTOFFSETS 0x4f4f4646 /* "OOFF" */
30 #define MIDX_CHUNKID_LARGEOFFSETS 0x4c4f4646 /* "LOFF" */
31 #define MIDX_CHUNKLOOKUP_WIDTH (sizeof(uint32_t) + sizeof(uint64_t))
32 #define MIDX_CHUNK_FANOUT_SIZE (sizeof(uint32_t) * 256)
33 #define MIDX_CHUNK_OFFSET_WIDTH (2 * sizeof(uint32_t))
34 #define MIDX_CHUNK_LARGE_OFFSET_WIDTH (sizeof(uint64_t))
35 #define MIDX_LARGE_OFFSET_NEEDED 0x80000000
37 #define PACK_EXPIRED UINT_MAX
39 static uint8_t oid_version(void)
41 switch (hash_algo_by_ptr(the_hash_algo)) {
42 case GIT_HASH_SHA1:
43 return 1;
44 case GIT_HASH_SHA256:
45 return 2;
46 default:
47 die(_("invalid hash version"));
51 static char *get_midx_filename(const char *object_dir)
53 return xstrfmt("%s/pack/multi-pack-index", object_dir);
56 struct multi_pack_index *load_multi_pack_index(const char *object_dir, int local)
58 struct multi_pack_index *m = NULL;
59 int fd;
60 struct stat st;
61 size_t midx_size;
62 void *midx_map = NULL;
63 uint32_t hash_version;
64 char *midx_name = get_midx_filename(object_dir);
65 uint32_t i;
66 const char *cur_pack_name;
68 fd = git_open(midx_name);
70 if (fd < 0)
71 goto cleanup_fail;
72 if (fstat(fd, &st)) {
73 error_errno(_("failed to read %s"), midx_name);
74 goto cleanup_fail;
77 midx_size = xsize_t(st.st_size);
79 if (midx_size < MIDX_MIN_SIZE) {
80 error(_("multi-pack-index file %s is too small"), midx_name);
81 goto cleanup_fail;
84 FREE_AND_NULL(midx_name);
86 midx_map = xmmap(NULL, midx_size, PROT_READ, MAP_PRIVATE, fd, 0);
87 close(fd);
89 FLEX_ALLOC_STR(m, object_dir, object_dir);
90 m->data = midx_map;
91 m->data_len = midx_size;
92 m->local = local;
94 m->signature = get_be32(m->data);
95 if (m->signature != MIDX_SIGNATURE)
96 die(_("multi-pack-index signature 0x%08x does not match signature 0x%08x"),
97 m->signature, MIDX_SIGNATURE);
99 m->version = m->data[MIDX_BYTE_FILE_VERSION];
100 if (m->version != MIDX_VERSION)
101 die(_("multi-pack-index version %d not recognized"),
102 m->version);
104 hash_version = m->data[MIDX_BYTE_HASH_VERSION];
105 if (hash_version != oid_version()) {
106 error(_("multi-pack-index hash version %u does not match version %u"),
107 hash_version, oid_version());
108 goto cleanup_fail;
110 m->hash_len = the_hash_algo->rawsz;
112 m->num_chunks = m->data[MIDX_BYTE_NUM_CHUNKS];
114 m->num_packs = get_be32(m->data + MIDX_BYTE_NUM_PACKS);
116 for (i = 0; i < m->num_chunks; i++) {
117 uint32_t chunk_id = get_be32(m->data + MIDX_HEADER_SIZE +
118 MIDX_CHUNKLOOKUP_WIDTH * i);
119 uint64_t chunk_offset = get_be64(m->data + MIDX_HEADER_SIZE + 4 +
120 MIDX_CHUNKLOOKUP_WIDTH * i);
122 if (chunk_offset >= m->data_len)
123 die(_("invalid chunk offset (too large)"));
125 switch (chunk_id) {
126 case MIDX_CHUNKID_PACKNAMES:
127 m->chunk_pack_names = m->data + chunk_offset;
128 break;
130 case MIDX_CHUNKID_OIDFANOUT:
131 m->chunk_oid_fanout = (uint32_t *)(m->data + chunk_offset);
132 break;
134 case MIDX_CHUNKID_OIDLOOKUP:
135 m->chunk_oid_lookup = m->data + chunk_offset;
136 break;
138 case MIDX_CHUNKID_OBJECTOFFSETS:
139 m->chunk_object_offsets = m->data + chunk_offset;
140 break;
142 case MIDX_CHUNKID_LARGEOFFSETS:
143 m->chunk_large_offsets = m->data + chunk_offset;
144 break;
146 case 0:
147 die(_("terminating multi-pack-index chunk id appears earlier than expected"));
148 break;
150 default:
152 * Do nothing on unrecognized chunks, allowing future
153 * extensions to add optional chunks.
155 break;
159 if (!m->chunk_pack_names)
160 die(_("multi-pack-index missing required pack-name chunk"));
161 if (!m->chunk_oid_fanout)
162 die(_("multi-pack-index missing required OID fanout chunk"));
163 if (!m->chunk_oid_lookup)
164 die(_("multi-pack-index missing required OID lookup chunk"));
165 if (!m->chunk_object_offsets)
166 die(_("multi-pack-index missing required object offsets chunk"));
168 m->num_objects = ntohl(m->chunk_oid_fanout[255]);
170 m->pack_names = xcalloc(m->num_packs, sizeof(*m->pack_names));
171 m->packs = xcalloc(m->num_packs, sizeof(*m->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 return m;
190 cleanup_fail:
191 free(m);
192 free(midx_name);
193 if (midx_map)
194 munmap(midx_map, midx_size);
195 if (0 <= fd)
196 close(fd);
197 return NULL;
200 void close_midx(struct multi_pack_index *m)
202 uint32_t i;
204 if (!m)
205 return;
207 munmap((unsigned char *)m->data, m->data_len);
209 for (i = 0; i < m->num_packs; i++) {
210 if (m->packs[i])
211 m->packs[i]->multi_pack_index = 0;
213 FREE_AND_NULL(m->packs);
214 FREE_AND_NULL(m->pack_names);
217 int prepare_midx_pack(struct repository *r, struct multi_pack_index *m, uint32_t pack_int_id)
219 struct strbuf pack_name = STRBUF_INIT;
220 struct packed_git *p;
222 if (pack_int_id >= m->num_packs)
223 die(_("bad pack-int-id: %u (%u total packs)"),
224 pack_int_id, m->num_packs);
226 if (m->packs[pack_int_id])
227 return 0;
229 strbuf_addf(&pack_name, "%s/pack/%s", m->object_dir,
230 m->pack_names[pack_int_id]);
232 p = add_packed_git(pack_name.buf, pack_name.len, m->local);
233 strbuf_release(&pack_name);
235 if (!p)
236 return 1;
238 p->multi_pack_index = 1;
239 m->packs[pack_int_id] = p;
240 install_packed_git(r, p);
241 list_add_tail(&p->mru, &r->objects->packed_git_mru);
243 return 0;
246 int bsearch_midx(const struct object_id *oid, struct multi_pack_index *m, uint32_t *result)
248 return bsearch_hash(oid->hash, m->chunk_oid_fanout, m->chunk_oid_lookup,
249 the_hash_algo->rawsz, result);
252 struct object_id *nth_midxed_object_oid(struct object_id *oid,
253 struct multi_pack_index *m,
254 uint32_t n)
256 if (n >= m->num_objects)
257 return NULL;
259 hashcpy(oid->hash, m->chunk_oid_lookup + m->hash_len * n);
260 return oid;
263 static off_t nth_midxed_offset(struct multi_pack_index *m, uint32_t pos)
265 const unsigned char *offset_data;
266 uint32_t offset32;
268 offset_data = m->chunk_object_offsets + pos * MIDX_CHUNK_OFFSET_WIDTH;
269 offset32 = get_be32(offset_data + sizeof(uint32_t));
271 if (m->chunk_large_offsets && offset32 & MIDX_LARGE_OFFSET_NEEDED) {
272 if (sizeof(off_t) < sizeof(uint64_t))
273 die(_("multi-pack-index stores a 64-bit offset, but off_t is too small"));
275 offset32 ^= MIDX_LARGE_OFFSET_NEEDED;
276 return get_be64(m->chunk_large_offsets + sizeof(uint64_t) * offset32);
279 return offset32;
282 static uint32_t nth_midxed_pack_int_id(struct multi_pack_index *m, uint32_t pos)
284 return get_be32(m->chunk_object_offsets + pos * MIDX_CHUNK_OFFSET_WIDTH);
287 static int nth_midxed_pack_entry(struct repository *r,
288 struct multi_pack_index *m,
289 struct pack_entry *e,
290 uint32_t pos)
292 uint32_t pack_int_id;
293 struct packed_git *p;
295 if (pos >= m->num_objects)
296 return 0;
298 pack_int_id = nth_midxed_pack_int_id(m, pos);
300 if (prepare_midx_pack(r, m, pack_int_id))
301 return 0;
302 p = m->packs[pack_int_id];
305 * We are about to tell the caller where they can locate the
306 * requested object. We better make sure the packfile is
307 * still here and can be accessed before supplying that
308 * answer, as it may have been deleted since the MIDX was
309 * loaded!
311 if (!is_pack_valid(p))
312 return 0;
314 if (p->num_bad_objects) {
315 uint32_t i;
316 struct object_id oid;
317 nth_midxed_object_oid(&oid, m, pos);
318 for (i = 0; i < p->num_bad_objects; i++)
319 if (hasheq(oid.hash,
320 p->bad_object_sha1 + the_hash_algo->rawsz * i))
321 return 0;
324 e->offset = nth_midxed_offset(m, pos);
325 e->p = p;
327 return 1;
330 int fill_midx_entry(struct repository * r,
331 const struct object_id *oid,
332 struct pack_entry *e,
333 struct multi_pack_index *m)
335 uint32_t pos;
337 if (!bsearch_midx(oid, m, &pos))
338 return 0;
340 return nth_midxed_pack_entry(r, m, e, pos);
343 /* Match "foo.idx" against either "foo.pack" _or_ "foo.idx". */
344 static int cmp_idx_or_pack_name(const char *idx_or_pack_name,
345 const char *idx_name)
347 /* Skip past any initial matching prefix. */
348 while (*idx_name && *idx_name == *idx_or_pack_name) {
349 idx_name++;
350 idx_or_pack_name++;
354 * If we didn't match completely, we may have matched "pack-1234." and
355 * be left with "idx" and "pack" respectively, which is also OK. We do
356 * not have to check for "idx" and "idx", because that would have been
357 * a complete match (and in that case these strcmps will be false, but
358 * we'll correctly return 0 from the final strcmp() below.
360 * Technically this matches "fooidx" and "foopack", but we'd never have
361 * such names in the first place.
363 if (!strcmp(idx_name, "idx") && !strcmp(idx_or_pack_name, "pack"))
364 return 0;
367 * This not only checks for a complete match, but also orders based on
368 * the first non-identical character, which means our ordering will
369 * match a raw strcmp(). That makes it OK to use this to binary search
370 * a naively-sorted list.
372 return strcmp(idx_or_pack_name, idx_name);
375 int midx_contains_pack(struct multi_pack_index *m, const char *idx_or_pack_name)
377 uint32_t first = 0, last = m->num_packs;
379 while (first < last) {
380 uint32_t mid = first + (last - first) / 2;
381 const char *current;
382 int cmp;
384 current = m->pack_names[mid];
385 cmp = cmp_idx_or_pack_name(idx_or_pack_name, current);
386 if (!cmp)
387 return 1;
388 if (cmp > 0) {
389 first = mid + 1;
390 continue;
392 last = mid;
395 return 0;
398 int prepare_multi_pack_index_one(struct repository *r, const char *object_dir, int local)
400 struct multi_pack_index *m;
401 struct multi_pack_index *m_search;
403 prepare_repo_settings(r);
404 if (!r->settings.core_multi_pack_index)
405 return 0;
407 for (m_search = r->objects->multi_pack_index; m_search; m_search = m_search->next)
408 if (!strcmp(object_dir, m_search->object_dir))
409 return 1;
411 m = load_multi_pack_index(object_dir, local);
413 if (m) {
414 struct multi_pack_index *mp = r->objects->multi_pack_index;
415 if (mp) {
416 m->next = mp->next;
417 mp->next = m;
418 } else
419 r->objects->multi_pack_index = m;
420 return 1;
423 return 0;
426 static size_t write_midx_header(struct hashfile *f,
427 unsigned char num_chunks,
428 uint32_t num_packs)
430 hashwrite_be32(f, MIDX_SIGNATURE);
431 hashwrite_u8(f, MIDX_VERSION);
432 hashwrite_u8(f, oid_version());
433 hashwrite_u8(f, num_chunks);
434 hashwrite_u8(f, 0); /* unused */
435 hashwrite_be32(f, num_packs);
437 return MIDX_HEADER_SIZE;
440 struct pack_info {
441 uint32_t orig_pack_int_id;
442 char *pack_name;
443 struct packed_git *p;
444 unsigned expired : 1;
447 static int pack_info_compare(const void *_a, const void *_b)
449 struct pack_info *a = (struct pack_info *)_a;
450 struct pack_info *b = (struct pack_info *)_b;
451 return strcmp(a->pack_name, b->pack_name);
454 struct write_midx_context {
455 struct pack_info *info;
456 uint32_t nr;
457 uint32_t alloc;
458 struct multi_pack_index *m;
459 struct progress *progress;
460 unsigned pack_paths_checked;
462 struct pack_midx_entry *entries;
463 uint32_t entries_nr;
465 uint32_t *pack_perm;
466 unsigned large_offsets_needed:1;
467 uint32_t num_large_offsets;
470 static void add_pack_to_midx(const char *full_path, size_t full_path_len,
471 const char *file_name, void *data)
473 struct write_midx_context *ctx = data;
475 if (ends_with(file_name, ".idx")) {
476 display_progress(ctx->progress, ++ctx->pack_paths_checked);
477 if (ctx->m && midx_contains_pack(ctx->m, file_name))
478 return;
480 ALLOC_GROW(ctx->info, ctx->nr + 1, ctx->alloc);
482 ctx->info[ctx->nr].p = add_packed_git(full_path,
483 full_path_len,
486 if (!ctx->info[ctx->nr].p) {
487 warning(_("failed to add packfile '%s'"),
488 full_path);
489 return;
492 if (open_pack_index(ctx->info[ctx->nr].p)) {
493 warning(_("failed to open pack-index '%s'"),
494 full_path);
495 close_pack(ctx->info[ctx->nr].p);
496 FREE_AND_NULL(ctx->info[ctx->nr].p);
497 return;
500 ctx->info[ctx->nr].pack_name = xstrdup(file_name);
501 ctx->info[ctx->nr].orig_pack_int_id = ctx->nr;
502 ctx->info[ctx->nr].expired = 0;
503 ctx->nr++;
507 struct pack_midx_entry {
508 struct object_id oid;
509 uint32_t pack_int_id;
510 time_t pack_mtime;
511 uint64_t offset;
514 static int midx_oid_compare(const void *_a, const void *_b)
516 const struct pack_midx_entry *a = (const struct pack_midx_entry *)_a;
517 const struct pack_midx_entry *b = (const struct pack_midx_entry *)_b;
518 int cmp = oidcmp(&a->oid, &b->oid);
520 if (cmp)
521 return cmp;
523 if (a->pack_mtime > b->pack_mtime)
524 return -1;
525 else if (a->pack_mtime < b->pack_mtime)
526 return 1;
528 return a->pack_int_id - b->pack_int_id;
531 static int nth_midxed_pack_midx_entry(struct multi_pack_index *m,
532 struct pack_midx_entry *e,
533 uint32_t pos)
535 if (pos >= m->num_objects)
536 return 1;
538 nth_midxed_object_oid(&e->oid, m, pos);
539 e->pack_int_id = nth_midxed_pack_int_id(m, pos);
540 e->offset = nth_midxed_offset(m, pos);
542 /* consider objects in midx to be from "old" packs */
543 e->pack_mtime = 0;
544 return 0;
547 static void fill_pack_entry(uint32_t pack_int_id,
548 struct packed_git *p,
549 uint32_t cur_object,
550 struct pack_midx_entry *entry)
552 if (nth_packed_object_id(&entry->oid, p, cur_object) < 0)
553 die(_("failed to locate object %d in packfile"), cur_object);
555 entry->pack_int_id = pack_int_id;
556 entry->pack_mtime = p->mtime;
558 entry->offset = nth_packed_object_offset(p, cur_object);
562 * It is possible to artificially get into a state where there are many
563 * duplicate copies of objects. That can create high memory pressure if
564 * we are to create a list of all objects before de-duplication. To reduce
565 * this memory pressure without a significant performance drop, automatically
566 * group objects by the first byte of their object id. Use the IDX fanout
567 * tables to group the data, copy to a local array, then sort.
569 * Copy only the de-duplicated entries (selected by most-recent modified time
570 * of a packfile containing the object).
572 static struct pack_midx_entry *get_sorted_entries(struct multi_pack_index *m,
573 struct pack_info *info,
574 uint32_t nr_packs,
575 uint32_t *nr_objects)
577 uint32_t cur_fanout, cur_pack, cur_object;
578 uint32_t alloc_fanout, alloc_objects, total_objects = 0;
579 struct pack_midx_entry *entries_by_fanout = NULL;
580 struct pack_midx_entry *deduplicated_entries = NULL;
581 uint32_t start_pack = m ? m->num_packs : 0;
583 for (cur_pack = start_pack; cur_pack < nr_packs; cur_pack++)
584 total_objects += info[cur_pack].p->num_objects;
587 * As we de-duplicate by fanout value, we expect the fanout
588 * slices to be evenly distributed, with some noise. Hence,
589 * allocate slightly more than one 256th.
591 alloc_objects = alloc_fanout = total_objects > 3200 ? total_objects / 200 : 16;
593 ALLOC_ARRAY(entries_by_fanout, alloc_fanout);
594 ALLOC_ARRAY(deduplicated_entries, alloc_objects);
595 *nr_objects = 0;
597 for (cur_fanout = 0; cur_fanout < 256; cur_fanout++) {
598 uint32_t nr_fanout = 0;
600 if (m) {
601 uint32_t start = 0, end;
603 if (cur_fanout)
604 start = ntohl(m->chunk_oid_fanout[cur_fanout - 1]);
605 end = ntohl(m->chunk_oid_fanout[cur_fanout]);
607 for (cur_object = start; cur_object < end; cur_object++) {
608 ALLOC_GROW(entries_by_fanout, nr_fanout + 1, alloc_fanout);
609 nth_midxed_pack_midx_entry(m,
610 &entries_by_fanout[nr_fanout],
611 cur_object);
612 nr_fanout++;
616 for (cur_pack = start_pack; cur_pack < nr_packs; cur_pack++) {
617 uint32_t start = 0, end;
619 if (cur_fanout)
620 start = get_pack_fanout(info[cur_pack].p, cur_fanout - 1);
621 end = get_pack_fanout(info[cur_pack].p, cur_fanout);
623 for (cur_object = start; cur_object < end; cur_object++) {
624 ALLOC_GROW(entries_by_fanout, nr_fanout + 1, alloc_fanout);
625 fill_pack_entry(cur_pack, info[cur_pack].p, cur_object, &entries_by_fanout[nr_fanout]);
626 nr_fanout++;
630 QSORT(entries_by_fanout, nr_fanout, midx_oid_compare);
633 * The batch is now sorted by OID and then mtime (descending).
634 * Take only the first duplicate.
636 for (cur_object = 0; cur_object < nr_fanout; cur_object++) {
637 if (cur_object && oideq(&entries_by_fanout[cur_object - 1].oid,
638 &entries_by_fanout[cur_object].oid))
639 continue;
641 ALLOC_GROW(deduplicated_entries, *nr_objects + 1, alloc_objects);
642 memcpy(&deduplicated_entries[*nr_objects],
643 &entries_by_fanout[cur_object],
644 sizeof(struct pack_midx_entry));
645 (*nr_objects)++;
649 free(entries_by_fanout);
650 return deduplicated_entries;
653 static int write_midx_pack_names(struct hashfile *f, void *data)
655 struct write_midx_context *ctx = data;
656 uint32_t i;
657 unsigned char padding[MIDX_CHUNK_ALIGNMENT];
658 size_t written = 0;
660 for (i = 0; i < ctx->nr; i++) {
661 size_t writelen;
663 if (ctx->info[i].expired)
664 continue;
666 if (i && strcmp(ctx->info[i].pack_name, ctx->info[i - 1].pack_name) <= 0)
667 BUG("incorrect pack-file order: %s before %s",
668 ctx->info[i - 1].pack_name,
669 ctx->info[i].pack_name);
671 writelen = strlen(ctx->info[i].pack_name) + 1;
672 hashwrite(f, ctx->info[i].pack_name, writelen);
673 written += writelen;
676 /* add padding to be aligned */
677 i = MIDX_CHUNK_ALIGNMENT - (written % MIDX_CHUNK_ALIGNMENT);
678 if (i < MIDX_CHUNK_ALIGNMENT) {
679 memset(padding, 0, sizeof(padding));
680 hashwrite(f, padding, i);
683 return 0;
686 static int write_midx_oid_fanout(struct hashfile *f,
687 void *data)
689 struct write_midx_context *ctx = data;
690 struct pack_midx_entry *list = ctx->entries;
691 struct pack_midx_entry *last = ctx->entries + ctx->entries_nr;
692 uint32_t count = 0;
693 uint32_t i;
696 * Write the first-level table (the list is sorted,
697 * but we use a 256-entry lookup to be able to avoid
698 * having to do eight extra binary search iterations).
700 for (i = 0; i < 256; i++) {
701 struct pack_midx_entry *next = list;
703 while (next < last && next->oid.hash[0] == i) {
704 count++;
705 next++;
708 hashwrite_be32(f, count);
709 list = next;
712 return 0;
715 static int write_midx_oid_lookup(struct hashfile *f,
716 void *data)
718 struct write_midx_context *ctx = data;
719 unsigned char hash_len = the_hash_algo->rawsz;
720 struct pack_midx_entry *list = ctx->entries;
721 uint32_t i;
723 for (i = 0; i < ctx->entries_nr; i++) {
724 struct pack_midx_entry *obj = list++;
726 if (i < ctx->entries_nr - 1) {
727 struct pack_midx_entry *next = list;
728 if (oidcmp(&obj->oid, &next->oid) >= 0)
729 BUG("OIDs not in order: %s >= %s",
730 oid_to_hex(&obj->oid),
731 oid_to_hex(&next->oid));
734 hashwrite(f, obj->oid.hash, (int)hash_len);
737 return 0;
740 static int write_midx_object_offsets(struct hashfile *f,
741 void *data)
743 struct write_midx_context *ctx = data;
744 struct pack_midx_entry *list = ctx->entries;
745 uint32_t i, nr_large_offset = 0;
747 for (i = 0; i < ctx->entries_nr; i++) {
748 struct pack_midx_entry *obj = list++;
750 if (ctx->pack_perm[obj->pack_int_id] == PACK_EXPIRED)
751 BUG("object %s is in an expired pack with int-id %d",
752 oid_to_hex(&obj->oid),
753 obj->pack_int_id);
755 hashwrite_be32(f, ctx->pack_perm[obj->pack_int_id]);
757 if (ctx->large_offsets_needed && obj->offset >> 31)
758 hashwrite_be32(f, MIDX_LARGE_OFFSET_NEEDED | nr_large_offset++);
759 else if (!ctx->large_offsets_needed && obj->offset >> 32)
760 BUG("object %s requires a large offset (%"PRIx64") but the MIDX is not writing large offsets!",
761 oid_to_hex(&obj->oid),
762 obj->offset);
763 else
764 hashwrite_be32(f, (uint32_t)obj->offset);
767 return 0;
770 static int write_midx_large_offsets(struct hashfile *f,
771 void *data)
773 struct write_midx_context *ctx = data;
774 struct pack_midx_entry *list = ctx->entries;
775 struct pack_midx_entry *end = ctx->entries + ctx->entries_nr;
776 uint32_t nr_large_offset = ctx->num_large_offsets;
778 while (nr_large_offset) {
779 struct pack_midx_entry *obj;
780 uint64_t offset;
782 if (list >= end)
783 BUG("too many large-offset objects");
785 obj = list++;
786 offset = obj->offset;
788 if (!(offset >> 31))
789 continue;
791 hashwrite_be64(f, offset);
793 nr_large_offset--;
796 return 0;
799 static int write_midx_internal(const char *object_dir, struct multi_pack_index *m,
800 struct string_list *packs_to_drop, unsigned flags)
802 char *midx_name;
803 uint32_t i;
804 struct hashfile *f = NULL;
805 struct lock_file lk;
806 struct write_midx_context ctx = { 0 };
807 int pack_name_concat_len = 0;
808 int dropped_packs = 0;
809 int result = 0;
810 struct chunkfile *cf;
812 midx_name = get_midx_filename(object_dir);
813 if (safe_create_leading_directories(midx_name))
814 die_errno(_("unable to create leading directories of %s"),
815 midx_name);
817 if (m)
818 ctx.m = m;
819 else
820 ctx.m = load_multi_pack_index(object_dir, 1);
822 ctx.nr = 0;
823 ctx.alloc = ctx.m ? ctx.m->num_packs : 16;
824 ctx.info = NULL;
825 ALLOC_ARRAY(ctx.info, ctx.alloc);
827 if (ctx.m) {
828 for (i = 0; i < ctx.m->num_packs; i++) {
829 ALLOC_GROW(ctx.info, ctx.nr + 1, ctx.alloc);
831 ctx.info[ctx.nr].orig_pack_int_id = i;
832 ctx.info[ctx.nr].pack_name = xstrdup(ctx.m->pack_names[i]);
833 ctx.info[ctx.nr].p = NULL;
834 ctx.info[ctx.nr].expired = 0;
835 ctx.nr++;
839 ctx.pack_paths_checked = 0;
840 if (flags & MIDX_PROGRESS)
841 ctx.progress = start_delayed_progress(_("Adding packfiles to multi-pack-index"), 0);
842 else
843 ctx.progress = NULL;
845 for_each_file_in_pack_dir(object_dir, add_pack_to_midx, &ctx);
846 stop_progress(&ctx.progress);
848 if (ctx.m && ctx.nr == ctx.m->num_packs && !packs_to_drop)
849 goto cleanup;
851 ctx.entries = get_sorted_entries(ctx.m, ctx.info, ctx.nr, &ctx.entries_nr);
853 ctx.large_offsets_needed = 0;
854 for (i = 0; i < ctx.entries_nr; i++) {
855 if (ctx.entries[i].offset > 0x7fffffff)
856 ctx.num_large_offsets++;
857 if (ctx.entries[i].offset > 0xffffffff)
858 ctx.large_offsets_needed = 1;
861 QSORT(ctx.info, ctx.nr, pack_info_compare);
863 if (packs_to_drop && packs_to_drop->nr) {
864 int drop_index = 0;
865 int missing_drops = 0;
867 for (i = 0; i < ctx.nr && drop_index < packs_to_drop->nr; i++) {
868 int cmp = strcmp(ctx.info[i].pack_name,
869 packs_to_drop->items[drop_index].string);
871 if (!cmp) {
872 drop_index++;
873 ctx.info[i].expired = 1;
874 } else if (cmp > 0) {
875 error(_("did not see pack-file %s to drop"),
876 packs_to_drop->items[drop_index].string);
877 drop_index++;
878 missing_drops++;
879 i--;
880 } else {
881 ctx.info[i].expired = 0;
885 if (missing_drops) {
886 result = 1;
887 goto cleanup;
892 * pack_perm stores a permutation between pack-int-ids from the
893 * previous multi-pack-index to the new one we are writing:
895 * pack_perm[old_id] = new_id
897 ALLOC_ARRAY(ctx.pack_perm, ctx.nr);
898 for (i = 0; i < ctx.nr; i++) {
899 if (ctx.info[i].expired) {
900 dropped_packs++;
901 ctx.pack_perm[ctx.info[i].orig_pack_int_id] = PACK_EXPIRED;
902 } else {
903 ctx.pack_perm[ctx.info[i].orig_pack_int_id] = i - dropped_packs;
907 for (i = 0; i < ctx.nr; i++) {
908 if (!ctx.info[i].expired)
909 pack_name_concat_len += strlen(ctx.info[i].pack_name) + 1;
912 if (pack_name_concat_len % MIDX_CHUNK_ALIGNMENT)
913 pack_name_concat_len += MIDX_CHUNK_ALIGNMENT -
914 (pack_name_concat_len % MIDX_CHUNK_ALIGNMENT);
916 hold_lock_file_for_update(&lk, midx_name, LOCK_DIE_ON_ERROR);
917 f = hashfd(lk.tempfile->fd, lk.tempfile->filename.buf);
918 FREE_AND_NULL(midx_name);
920 if (ctx.m)
921 close_midx(ctx.m);
923 if (ctx.nr - dropped_packs == 0) {
924 error(_("no pack files to index."));
925 result = 1;
926 goto cleanup;
929 cf = init_chunkfile(f);
931 add_chunk(cf, MIDX_CHUNKID_PACKNAMES, pack_name_concat_len,
932 write_midx_pack_names);
933 add_chunk(cf, MIDX_CHUNKID_OIDFANOUT, MIDX_CHUNK_FANOUT_SIZE,
934 write_midx_oid_fanout);
935 add_chunk(cf, MIDX_CHUNKID_OIDLOOKUP,
936 ctx.entries_nr * the_hash_algo->rawsz,
937 write_midx_oid_lookup);
938 add_chunk(cf, MIDX_CHUNKID_OBJECTOFFSETS,
939 ctx.entries_nr * MIDX_CHUNK_OFFSET_WIDTH,
940 write_midx_object_offsets);
942 if (ctx.large_offsets_needed)
943 add_chunk(cf, MIDX_CHUNKID_LARGEOFFSETS,
944 ctx.num_large_offsets * MIDX_CHUNK_LARGE_OFFSET_WIDTH,
945 write_midx_large_offsets);
947 write_midx_header(f, get_num_chunks(cf), ctx.nr - dropped_packs);
948 write_chunkfile(cf, &ctx);
950 finalize_hashfile(f, NULL, CSUM_FSYNC | CSUM_HASH_IN_STREAM);
951 free_chunkfile(cf);
952 commit_lock_file(&lk);
954 cleanup:
955 for (i = 0; i < ctx.nr; i++) {
956 if (ctx.info[i].p) {
957 close_pack(ctx.info[i].p);
958 free(ctx.info[i].p);
960 free(ctx.info[i].pack_name);
963 free(ctx.info);
964 free(ctx.entries);
965 free(ctx.pack_perm);
966 free(midx_name);
967 return result;
970 int write_midx_file(const char *object_dir, unsigned flags)
972 return write_midx_internal(object_dir, NULL, NULL, flags);
975 void clear_midx_file(struct repository *r)
977 char *midx = get_midx_filename(r->objects->odb->path);
979 if (r->objects && r->objects->multi_pack_index) {
980 close_midx(r->objects->multi_pack_index);
981 r->objects->multi_pack_index = NULL;
984 if (remove_path(midx))
985 die(_("failed to clear multi-pack-index at %s"), midx);
987 free(midx);
990 static int verify_midx_error;
992 static void midx_report(const char *fmt, ...)
994 va_list ap;
995 verify_midx_error = 1;
996 va_start(ap, fmt);
997 vfprintf(stderr, fmt, ap);
998 fprintf(stderr, "\n");
999 va_end(ap);
1002 struct pair_pos_vs_id
1004 uint32_t pos;
1005 uint32_t pack_int_id;
1008 static int compare_pair_pos_vs_id(const void *_a, const void *_b)
1010 struct pair_pos_vs_id *a = (struct pair_pos_vs_id *)_a;
1011 struct pair_pos_vs_id *b = (struct pair_pos_vs_id *)_b;
1013 return b->pack_int_id - a->pack_int_id;
1017 * Limit calls to display_progress() for performance reasons.
1018 * The interval here was arbitrarily chosen.
1020 #define SPARSE_PROGRESS_INTERVAL (1 << 12)
1021 #define midx_display_sparse_progress(progress, n) \
1022 do { \
1023 uint64_t _n = (n); \
1024 if ((_n & (SPARSE_PROGRESS_INTERVAL - 1)) == 0) \
1025 display_progress(progress, _n); \
1026 } while (0)
1028 int verify_midx_file(struct repository *r, const char *object_dir, unsigned flags)
1030 struct pair_pos_vs_id *pairs = NULL;
1031 uint32_t i;
1032 struct progress *progress = NULL;
1033 struct multi_pack_index *m = load_multi_pack_index(object_dir, 1);
1034 verify_midx_error = 0;
1036 if (!m) {
1037 int result = 0;
1038 struct stat sb;
1039 char *filename = get_midx_filename(object_dir);
1040 if (!stat(filename, &sb)) {
1041 error(_("multi-pack-index file exists, but failed to parse"));
1042 result = 1;
1044 free(filename);
1045 return result;
1048 if (flags & MIDX_PROGRESS)
1049 progress = start_delayed_progress(_("Looking for referenced packfiles"),
1050 m->num_packs);
1051 for (i = 0; i < m->num_packs; i++) {
1052 if (prepare_midx_pack(r, m, i))
1053 midx_report("failed to load pack in position %d", i);
1055 display_progress(progress, i + 1);
1057 stop_progress(&progress);
1059 for (i = 0; i < 255; i++) {
1060 uint32_t oid_fanout1 = ntohl(m->chunk_oid_fanout[i]);
1061 uint32_t oid_fanout2 = ntohl(m->chunk_oid_fanout[i + 1]);
1063 if (oid_fanout1 > oid_fanout2)
1064 midx_report(_("oid fanout out of order: fanout[%d] = %"PRIx32" > %"PRIx32" = fanout[%d]"),
1065 i, oid_fanout1, oid_fanout2, i + 1);
1068 if (m->num_objects == 0) {
1069 midx_report(_("the midx contains no oid"));
1071 * Remaining tests assume that we have objects, so we can
1072 * return here.
1074 return verify_midx_error;
1077 if (flags & MIDX_PROGRESS)
1078 progress = start_sparse_progress(_("Verifying OID order in multi-pack-index"),
1079 m->num_objects - 1);
1080 for (i = 0; i < m->num_objects - 1; i++) {
1081 struct object_id oid1, oid2;
1083 nth_midxed_object_oid(&oid1, m, i);
1084 nth_midxed_object_oid(&oid2, m, i + 1);
1086 if (oidcmp(&oid1, &oid2) >= 0)
1087 midx_report(_("oid lookup out of order: oid[%d] = %s >= %s = oid[%d]"),
1088 i, oid_to_hex(&oid1), oid_to_hex(&oid2), i + 1);
1090 midx_display_sparse_progress(progress, i + 1);
1092 stop_progress(&progress);
1095 * Create an array mapping each object to its packfile id. Sort it
1096 * to group the objects by packfile. Use this permutation to visit
1097 * each of the objects and only require 1 packfile to be open at a
1098 * time.
1100 ALLOC_ARRAY(pairs, m->num_objects);
1101 for (i = 0; i < m->num_objects; i++) {
1102 pairs[i].pos = i;
1103 pairs[i].pack_int_id = nth_midxed_pack_int_id(m, i);
1106 if (flags & MIDX_PROGRESS)
1107 progress = start_sparse_progress(_("Sorting objects by packfile"),
1108 m->num_objects);
1109 display_progress(progress, 0); /* TODO: Measure QSORT() progress */
1110 QSORT(pairs, m->num_objects, compare_pair_pos_vs_id);
1111 stop_progress(&progress);
1113 if (flags & MIDX_PROGRESS)
1114 progress = start_sparse_progress(_("Verifying object offsets"), m->num_objects);
1115 for (i = 0; i < m->num_objects; i++) {
1116 struct object_id oid;
1117 struct pack_entry e;
1118 off_t m_offset, p_offset;
1120 if (i > 0 && pairs[i-1].pack_int_id != pairs[i].pack_int_id &&
1121 m->packs[pairs[i-1].pack_int_id])
1123 close_pack_fd(m->packs[pairs[i-1].pack_int_id]);
1124 close_pack_index(m->packs[pairs[i-1].pack_int_id]);
1127 nth_midxed_object_oid(&oid, m, pairs[i].pos);
1129 if (!fill_midx_entry(r, &oid, &e, m)) {
1130 midx_report(_("failed to load pack entry for oid[%d] = %s"),
1131 pairs[i].pos, oid_to_hex(&oid));
1132 continue;
1135 if (open_pack_index(e.p)) {
1136 midx_report(_("failed to load pack-index for packfile %s"),
1137 e.p->pack_name);
1138 break;
1141 m_offset = e.offset;
1142 p_offset = find_pack_entry_one(oid.hash, e.p);
1144 if (m_offset != p_offset)
1145 midx_report(_("incorrect object offset for oid[%d] = %s: %"PRIx64" != %"PRIx64),
1146 pairs[i].pos, oid_to_hex(&oid), m_offset, p_offset);
1148 midx_display_sparse_progress(progress, i + 1);
1150 stop_progress(&progress);
1152 free(pairs);
1154 return verify_midx_error;
1157 int expire_midx_packs(struct repository *r, const char *object_dir, unsigned flags)
1159 uint32_t i, *count, result = 0;
1160 struct string_list packs_to_drop = STRING_LIST_INIT_DUP;
1161 struct multi_pack_index *m = load_multi_pack_index(object_dir, 1);
1162 struct progress *progress = NULL;
1164 if (!m)
1165 return 0;
1167 count = xcalloc(m->num_packs, sizeof(uint32_t));
1169 if (flags & MIDX_PROGRESS)
1170 progress = start_delayed_progress(_("Counting referenced objects"),
1171 m->num_objects);
1172 for (i = 0; i < m->num_objects; i++) {
1173 int pack_int_id = nth_midxed_pack_int_id(m, i);
1174 count[pack_int_id]++;
1175 display_progress(progress, i + 1);
1177 stop_progress(&progress);
1179 if (flags & MIDX_PROGRESS)
1180 progress = start_delayed_progress(_("Finding and deleting unreferenced packfiles"),
1181 m->num_packs);
1182 for (i = 0; i < m->num_packs; i++) {
1183 char *pack_name;
1184 display_progress(progress, i + 1);
1186 if (count[i])
1187 continue;
1189 if (prepare_midx_pack(r, m, i))
1190 continue;
1192 if (m->packs[i]->pack_keep)
1193 continue;
1195 pack_name = xstrdup(m->packs[i]->pack_name);
1196 close_pack(m->packs[i]);
1198 string_list_insert(&packs_to_drop, m->pack_names[i]);
1199 unlink_pack_path(pack_name, 0);
1200 free(pack_name);
1202 stop_progress(&progress);
1204 free(count);
1206 if (packs_to_drop.nr)
1207 result = write_midx_internal(object_dir, m, &packs_to_drop, flags);
1209 string_list_clear(&packs_to_drop, 0);
1210 return result;
1213 struct repack_info {
1214 timestamp_t mtime;
1215 uint32_t referenced_objects;
1216 uint32_t pack_int_id;
1219 static int compare_by_mtime(const void *a_, const void *b_)
1221 const struct repack_info *a, *b;
1223 a = (const struct repack_info *)a_;
1224 b = (const struct repack_info *)b_;
1226 if (a->mtime < b->mtime)
1227 return -1;
1228 if (a->mtime > b->mtime)
1229 return 1;
1230 return 0;
1233 static int fill_included_packs_all(struct repository *r,
1234 struct multi_pack_index *m,
1235 unsigned char *include_pack)
1237 uint32_t i, count = 0;
1238 int pack_kept_objects = 0;
1240 repo_config_get_bool(r, "repack.packkeptobjects", &pack_kept_objects);
1242 for (i = 0; i < m->num_packs; i++) {
1243 if (prepare_midx_pack(r, m, i))
1244 continue;
1245 if (!pack_kept_objects && m->packs[i]->pack_keep)
1246 continue;
1248 include_pack[i] = 1;
1249 count++;
1252 return count < 2;
1255 static int fill_included_packs_batch(struct repository *r,
1256 struct multi_pack_index *m,
1257 unsigned char *include_pack,
1258 size_t batch_size)
1260 uint32_t i, packs_to_repack;
1261 size_t total_size;
1262 struct repack_info *pack_info = xcalloc(m->num_packs, sizeof(struct repack_info));
1263 int pack_kept_objects = 0;
1265 repo_config_get_bool(r, "repack.packkeptobjects", &pack_kept_objects);
1267 for (i = 0; i < m->num_packs; i++) {
1268 pack_info[i].pack_int_id = i;
1270 if (prepare_midx_pack(r, m, i))
1271 continue;
1273 pack_info[i].mtime = m->packs[i]->mtime;
1276 for (i = 0; batch_size && i < m->num_objects; i++) {
1277 uint32_t pack_int_id = nth_midxed_pack_int_id(m, i);
1278 pack_info[pack_int_id].referenced_objects++;
1281 QSORT(pack_info, m->num_packs, compare_by_mtime);
1283 total_size = 0;
1284 packs_to_repack = 0;
1285 for (i = 0; total_size < batch_size && i < m->num_packs; i++) {
1286 int pack_int_id = pack_info[i].pack_int_id;
1287 struct packed_git *p = m->packs[pack_int_id];
1288 size_t expected_size;
1290 if (!p)
1291 continue;
1292 if (!pack_kept_objects && p->pack_keep)
1293 continue;
1294 if (open_pack_index(p) || !p->num_objects)
1295 continue;
1297 expected_size = (size_t)(p->pack_size
1298 * pack_info[i].referenced_objects);
1299 expected_size /= p->num_objects;
1301 if (expected_size >= batch_size)
1302 continue;
1304 packs_to_repack++;
1305 total_size += expected_size;
1306 include_pack[pack_int_id] = 1;
1309 free(pack_info);
1311 if (packs_to_repack < 2)
1312 return 1;
1314 return 0;
1317 int midx_repack(struct repository *r, const char *object_dir, size_t batch_size, unsigned flags)
1319 int result = 0;
1320 uint32_t i;
1321 unsigned char *include_pack;
1322 struct child_process cmd = CHILD_PROCESS_INIT;
1323 FILE *cmd_in;
1324 struct strbuf base_name = STRBUF_INIT;
1325 struct multi_pack_index *m = load_multi_pack_index(object_dir, 1);
1328 * When updating the default for these configuration
1329 * variables in builtin/repack.c, these must be adjusted
1330 * to match.
1332 int delta_base_offset = 1;
1333 int use_delta_islands = 0;
1335 if (!m)
1336 return 0;
1338 include_pack = xcalloc(m->num_packs, sizeof(unsigned char));
1340 if (batch_size) {
1341 if (fill_included_packs_batch(r, m, include_pack, batch_size))
1342 goto cleanup;
1343 } else if (fill_included_packs_all(r, m, include_pack))
1344 goto cleanup;
1346 repo_config_get_bool(r, "repack.usedeltabaseoffset", &delta_base_offset);
1347 repo_config_get_bool(r, "repack.usedeltaislands", &use_delta_islands);
1349 strvec_push(&cmd.args, "pack-objects");
1351 strbuf_addstr(&base_name, object_dir);
1352 strbuf_addstr(&base_name, "/pack/pack");
1353 strvec_push(&cmd.args, base_name.buf);
1355 if (delta_base_offset)
1356 strvec_push(&cmd.args, "--delta-base-offset");
1357 if (use_delta_islands)
1358 strvec_push(&cmd.args, "--delta-islands");
1360 if (flags & MIDX_PROGRESS)
1361 strvec_push(&cmd.args, "--progress");
1362 else
1363 strvec_push(&cmd.args, "-q");
1365 strbuf_release(&base_name);
1367 cmd.git_cmd = 1;
1368 cmd.in = cmd.out = -1;
1370 if (start_command(&cmd)) {
1371 error(_("could not start pack-objects"));
1372 result = 1;
1373 goto cleanup;
1376 cmd_in = xfdopen(cmd.in, "w");
1378 for (i = 0; i < m->num_objects; i++) {
1379 struct object_id oid;
1380 uint32_t pack_int_id = nth_midxed_pack_int_id(m, i);
1382 if (!include_pack[pack_int_id])
1383 continue;
1385 nth_midxed_object_oid(&oid, m, i);
1386 fprintf(cmd_in, "%s\n", oid_to_hex(&oid));
1388 fclose(cmd_in);
1390 if (finish_command(&cmd)) {
1391 error(_("could not finish pack-objects"));
1392 result = 1;
1393 goto cleanup;
1396 result = write_midx_internal(object_dir, m, NULL, flags);
1397 m = NULL;
1399 cleanup:
1400 if (m)
1401 close_midx(m);
1402 free(include_pack);
1403 return result;