]> git.ipfire.org Git - thirdparty/git.git/blob - midx.c
midx: prevent writing a .bitmap without any objects
[thirdparty/git.git] / midx.c
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"
20
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)
29
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
40
41 #define PACK_EXPIRED UINT_MAX
42
43 static uint8_t oid_version(void)
44 {
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"));
52 }
53 }
54
55 const unsigned char *get_midx_checksum(struct multi_pack_index *m)
56 {
57 return m->data + m->data_len - the_hash_algo->rawsz;
58 }
59
60 void get_midx_filename(struct strbuf *out, const char *object_dir)
61 {
62 strbuf_addf(out, "%s/pack/multi-pack-index", object_dir);
63 }
64
65 void get_midx_rev_filename(struct strbuf *out, struct multi_pack_index *m)
66 {
67 get_midx_filename(out, m->object_dir);
68 strbuf_addf(out, "-%s.rev", hash_to_hex(get_midx_checksum(m)));
69 }
70
71 static int midx_read_oid_fanout(const unsigned char *chunk_start,
72 size_t chunk_size, void *data)
73 {
74 struct multi_pack_index *m = data;
75 m->chunk_oid_fanout = (uint32_t *)chunk_start;
76
77 if (chunk_size != 4 * 256) {
78 error(_("multi-pack-index OID fanout is of the wrong size"));
79 return 1;
80 }
81 return 0;
82 }
83
84 struct multi_pack_index *load_multi_pack_index(const char *object_dir, int local)
85 {
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 struct strbuf midx_name = STRBUF_INIT;
93 uint32_t i;
94 const char *cur_pack_name;
95 struct chunkfile *cf = NULL;
96
97 get_midx_filename(&midx_name, object_dir);
98
99 fd = git_open(midx_name.buf);
100
101 if (fd < 0)
102 goto cleanup_fail;
103 if (fstat(fd, &st)) {
104 error_errno(_("failed to read %s"), midx_name.buf);
105 goto cleanup_fail;
106 }
107
108 midx_size = xsize_t(st.st_size);
109
110 if (midx_size < MIDX_MIN_SIZE) {
111 error(_("multi-pack-index file %s is too small"), midx_name.buf);
112 goto cleanup_fail;
113 }
114
115 strbuf_release(&midx_name);
116
117 midx_map = xmmap(NULL, midx_size, PROT_READ, MAP_PRIVATE, fd, 0);
118 close(fd);
119
120 FLEX_ALLOC_STR(m, object_dir, object_dir);
121 m->data = midx_map;
122 m->data_len = midx_size;
123 m->local = local;
124
125 m->signature = get_be32(m->data);
126 if (m->signature != MIDX_SIGNATURE)
127 die(_("multi-pack-index signature 0x%08x does not match signature 0x%08x"),
128 m->signature, MIDX_SIGNATURE);
129
130 m->version = m->data[MIDX_BYTE_FILE_VERSION];
131 if (m->version != MIDX_VERSION)
132 die(_("multi-pack-index version %d not recognized"),
133 m->version);
134
135 hash_version = m->data[MIDX_BYTE_HASH_VERSION];
136 if (hash_version != oid_version()) {
137 error(_("multi-pack-index hash version %u does not match version %u"),
138 hash_version, oid_version());
139 goto cleanup_fail;
140 }
141 m->hash_len = the_hash_algo->rawsz;
142
143 m->num_chunks = m->data[MIDX_BYTE_NUM_CHUNKS];
144
145 m->num_packs = get_be32(m->data + MIDX_BYTE_NUM_PACKS);
146
147 cf = init_chunkfile(NULL);
148
149 if (read_table_of_contents(cf, m->data, midx_size,
150 MIDX_HEADER_SIZE, m->num_chunks))
151 goto cleanup_fail;
152
153 if (pair_chunk(cf, MIDX_CHUNKID_PACKNAMES, &m->chunk_pack_names) == CHUNK_NOT_FOUND)
154 die(_("multi-pack-index missing required pack-name chunk"));
155 if (read_chunk(cf, MIDX_CHUNKID_OIDFANOUT, midx_read_oid_fanout, m) == CHUNK_NOT_FOUND)
156 die(_("multi-pack-index missing required OID fanout chunk"));
157 if (pair_chunk(cf, MIDX_CHUNKID_OIDLOOKUP, &m->chunk_oid_lookup) == CHUNK_NOT_FOUND)
158 die(_("multi-pack-index missing required OID lookup chunk"));
159 if (pair_chunk(cf, MIDX_CHUNKID_OBJECTOFFSETS, &m->chunk_object_offsets) == CHUNK_NOT_FOUND)
160 die(_("multi-pack-index missing required object offsets chunk"));
161
162 pair_chunk(cf, MIDX_CHUNKID_LARGEOFFSETS, &m->chunk_large_offsets);
163
164 m->num_objects = ntohl(m->chunk_oid_fanout[255]);
165
166 CALLOC_ARRAY(m->pack_names, m->num_packs);
167 CALLOC_ARRAY(m->packs, m->num_packs);
168
169 cur_pack_name = (const char *)m->chunk_pack_names;
170 for (i = 0; i < m->num_packs; i++) {
171 m->pack_names[i] = cur_pack_name;
172
173 cur_pack_name += strlen(cur_pack_name) + 1;
174
175 if (i && strcmp(m->pack_names[i], m->pack_names[i - 1]) <= 0)
176 die(_("multi-pack-index pack names out of order: '%s' before '%s'"),
177 m->pack_names[i - 1],
178 m->pack_names[i]);
179 }
180
181 trace2_data_intmax("midx", the_repository, "load/num_packs", m->num_packs);
182 trace2_data_intmax("midx", the_repository, "load/num_objects", m->num_objects);
183
184 free_chunkfile(cf);
185 return m;
186
187 cleanup_fail:
188 free(m);
189 strbuf_release(&midx_name);
190 free_chunkfile(cf);
191 if (midx_map)
192 munmap(midx_map, midx_size);
193 if (0 <= fd)
194 close(fd);
195 return NULL;
196 }
197
198 void close_midx(struct multi_pack_index *m)
199 {
200 uint32_t i;
201
202 if (!m)
203 return;
204
205 close_midx(m->next);
206
207 munmap((unsigned char *)m->data, m->data_len);
208
209 for (i = 0; i < m->num_packs; i++) {
210 if (m->packs[i])
211 m->packs[i]->multi_pack_index = 0;
212 }
213 FREE_AND_NULL(m->packs);
214 FREE_AND_NULL(m->pack_names);
215 free(m);
216 }
217
218 int prepare_midx_pack(struct repository *r, struct multi_pack_index *m, uint32_t pack_int_id)
219 {
220 struct strbuf pack_name = STRBUF_INIT;
221 struct packed_git *p;
222
223 if (pack_int_id >= m->num_packs)
224 die(_("bad pack-int-id: %u (%u total packs)"),
225 pack_int_id, m->num_packs);
226
227 if (m->packs[pack_int_id])
228 return 0;
229
230 strbuf_addf(&pack_name, "%s/pack/%s", m->object_dir,
231 m->pack_names[pack_int_id]);
232
233 p = add_packed_git(pack_name.buf, pack_name.len, m->local);
234 strbuf_release(&pack_name);
235
236 if (!p)
237 return 1;
238
239 p->multi_pack_index = 1;
240 m->packs[pack_int_id] = p;
241 install_packed_git(r, p);
242 list_add_tail(&p->mru, &r->objects->packed_git_mru);
243
244 return 0;
245 }
246
247 int bsearch_midx(const struct object_id *oid, struct multi_pack_index *m, uint32_t *result)
248 {
249 return bsearch_hash(oid->hash, m->chunk_oid_fanout, m->chunk_oid_lookup,
250 the_hash_algo->rawsz, result);
251 }
252
253 struct object_id *nth_midxed_object_oid(struct object_id *oid,
254 struct multi_pack_index *m,
255 uint32_t n)
256 {
257 if (n >= m->num_objects)
258 return NULL;
259
260 oidread(oid, m->chunk_oid_lookup + m->hash_len * n);
261 return oid;
262 }
263
264 off_t nth_midxed_offset(struct multi_pack_index *m, uint32_t pos)
265 {
266 const unsigned char *offset_data;
267 uint32_t offset32;
268
269 offset_data = m->chunk_object_offsets + (off_t)pos * MIDX_CHUNK_OFFSET_WIDTH;
270 offset32 = get_be32(offset_data + sizeof(uint32_t));
271
272 if (m->chunk_large_offsets && offset32 & MIDX_LARGE_OFFSET_NEEDED) {
273 if (sizeof(off_t) < sizeof(uint64_t))
274 die(_("multi-pack-index stores a 64-bit offset, but off_t is too small"));
275
276 offset32 ^= MIDX_LARGE_OFFSET_NEEDED;
277 return get_be64(m->chunk_large_offsets + sizeof(uint64_t) * offset32);
278 }
279
280 return offset32;
281 }
282
283 uint32_t nth_midxed_pack_int_id(struct multi_pack_index *m, uint32_t pos)
284 {
285 return get_be32(m->chunk_object_offsets +
286 (off_t)pos * MIDX_CHUNK_OFFSET_WIDTH);
287 }
288
289 int fill_midx_entry(struct repository * r,
290 const struct object_id *oid,
291 struct pack_entry *e,
292 struct multi_pack_index *m)
293 {
294 uint32_t pos;
295 uint32_t pack_int_id;
296 struct packed_git *p;
297
298 if (!bsearch_midx(oid, m, &pos))
299 return 0;
300
301 if (pos >= m->num_objects)
302 return 0;
303
304 pack_int_id = nth_midxed_pack_int_id(m, pos);
305
306 if (prepare_midx_pack(r, m, pack_int_id))
307 return 0;
308 p = m->packs[pack_int_id];
309
310 /*
311 * We are about to tell the caller where they can locate the
312 * requested object. We better make sure the packfile is
313 * still here and can be accessed before supplying that
314 * answer, as it may have been deleted since the MIDX was
315 * loaded!
316 */
317 if (!is_pack_valid(p))
318 return 0;
319
320 if (oidset_size(&p->bad_objects) &&
321 oidset_contains(&p->bad_objects, oid))
322 return 0;
323
324 e->offset = nth_midxed_offset(m, pos);
325 e->p = p;
326
327 return 1;
328 }
329
330 /* Match "foo.idx" against either "foo.pack" _or_ "foo.idx". */
331 static int cmp_idx_or_pack_name(const char *idx_or_pack_name,
332 const char *idx_name)
333 {
334 /* Skip past any initial matching prefix. */
335 while (*idx_name && *idx_name == *idx_or_pack_name) {
336 idx_name++;
337 idx_or_pack_name++;
338 }
339
340 /*
341 * If we didn't match completely, we may have matched "pack-1234." and
342 * be left with "idx" and "pack" respectively, which is also OK. We do
343 * not have to check for "idx" and "idx", because that would have been
344 * a complete match (and in that case these strcmps will be false, but
345 * we'll correctly return 0 from the final strcmp() below.
346 *
347 * Technically this matches "fooidx" and "foopack", but we'd never have
348 * such names in the first place.
349 */
350 if (!strcmp(idx_name, "idx") && !strcmp(idx_or_pack_name, "pack"))
351 return 0;
352
353 /*
354 * This not only checks for a complete match, but also orders based on
355 * the first non-identical character, which means our ordering will
356 * match a raw strcmp(). That makes it OK to use this to binary search
357 * a naively-sorted list.
358 */
359 return strcmp(idx_or_pack_name, idx_name);
360 }
361
362 int midx_contains_pack(struct multi_pack_index *m, const char *idx_or_pack_name)
363 {
364 uint32_t first = 0, last = m->num_packs;
365
366 while (first < last) {
367 uint32_t mid = first + (last - first) / 2;
368 const char *current;
369 int cmp;
370
371 current = m->pack_names[mid];
372 cmp = cmp_idx_or_pack_name(idx_or_pack_name, current);
373 if (!cmp)
374 return 1;
375 if (cmp > 0) {
376 first = mid + 1;
377 continue;
378 }
379 last = mid;
380 }
381
382 return 0;
383 }
384
385 int prepare_multi_pack_index_one(struct repository *r, const char *object_dir, int local)
386 {
387 struct multi_pack_index *m;
388 struct multi_pack_index *m_search;
389
390 prepare_repo_settings(r);
391 if (!r->settings.core_multi_pack_index)
392 return 0;
393
394 for (m_search = r->objects->multi_pack_index; m_search; m_search = m_search->next)
395 if (!strcmp(object_dir, m_search->object_dir))
396 return 1;
397
398 m = load_multi_pack_index(object_dir, local);
399
400 if (m) {
401 struct multi_pack_index *mp = r->objects->multi_pack_index;
402 if (mp) {
403 m->next = mp->next;
404 mp->next = m;
405 } else
406 r->objects->multi_pack_index = m;
407 return 1;
408 }
409
410 return 0;
411 }
412
413 static size_t write_midx_header(struct hashfile *f,
414 unsigned char num_chunks,
415 uint32_t num_packs)
416 {
417 hashwrite_be32(f, MIDX_SIGNATURE);
418 hashwrite_u8(f, MIDX_VERSION);
419 hashwrite_u8(f, oid_version());
420 hashwrite_u8(f, num_chunks);
421 hashwrite_u8(f, 0); /* unused */
422 hashwrite_be32(f, num_packs);
423
424 return MIDX_HEADER_SIZE;
425 }
426
427 struct pack_info {
428 uint32_t orig_pack_int_id;
429 char *pack_name;
430 struct packed_git *p;
431 unsigned expired : 1;
432 };
433
434 static int pack_info_compare(const void *_a, const void *_b)
435 {
436 struct pack_info *a = (struct pack_info *)_a;
437 struct pack_info *b = (struct pack_info *)_b;
438 return strcmp(a->pack_name, b->pack_name);
439 }
440
441 static int idx_or_pack_name_cmp(const void *_va, const void *_vb)
442 {
443 const char *pack_name = _va;
444 const struct pack_info *compar = _vb;
445
446 return cmp_idx_or_pack_name(pack_name, compar->pack_name);
447 }
448
449 struct write_midx_context {
450 struct pack_info *info;
451 uint32_t nr;
452 uint32_t alloc;
453 struct multi_pack_index *m;
454 struct progress *progress;
455 unsigned pack_paths_checked;
456
457 struct pack_midx_entry *entries;
458 uint32_t entries_nr;
459
460 uint32_t *pack_perm;
461 uint32_t *pack_order;
462 unsigned large_offsets_needed:1;
463 uint32_t num_large_offsets;
464
465 int preferred_pack_idx;
466
467 struct string_list *to_include;
468 };
469
470 static void add_pack_to_midx(const char *full_path, size_t full_path_len,
471 const char *file_name, void *data)
472 {
473 struct write_midx_context *ctx = data;
474
475 if (ends_with(file_name, ".idx")) {
476 display_progress(ctx->progress, ++ctx->pack_paths_checked);
477 /*
478 * Note that at most one of ctx->m and ctx->to_include are set,
479 * so we are testing midx_contains_pack() and
480 * string_list_has_string() independently (guarded by the
481 * appropriate NULL checks).
482 *
483 * We could support passing to_include while reusing an existing
484 * MIDX, but don't currently since the reuse process drags
485 * forward all packs from an existing MIDX (without checking
486 * whether or not they appear in the to_include list).
487 *
488 * If we added support for that, these next two conditional
489 * should be performed independently (likely checking
490 * to_include before the existing MIDX).
491 */
492 if (ctx->m && midx_contains_pack(ctx->m, file_name))
493 return;
494 else if (ctx->to_include &&
495 !string_list_has_string(ctx->to_include, file_name))
496 return;
497
498 ALLOC_GROW(ctx->info, ctx->nr + 1, ctx->alloc);
499
500 ctx->info[ctx->nr].p = add_packed_git(full_path,
501 full_path_len,
502 0);
503
504 if (!ctx->info[ctx->nr].p) {
505 warning(_("failed to add packfile '%s'"),
506 full_path);
507 return;
508 }
509
510 if (open_pack_index(ctx->info[ctx->nr].p)) {
511 warning(_("failed to open pack-index '%s'"),
512 full_path);
513 close_pack(ctx->info[ctx->nr].p);
514 FREE_AND_NULL(ctx->info[ctx->nr].p);
515 return;
516 }
517
518 ctx->info[ctx->nr].pack_name = xstrdup(file_name);
519 ctx->info[ctx->nr].orig_pack_int_id = ctx->nr;
520 ctx->info[ctx->nr].expired = 0;
521 ctx->nr++;
522 }
523 }
524
525 struct pack_midx_entry {
526 struct object_id oid;
527 uint32_t pack_int_id;
528 time_t pack_mtime;
529 uint64_t offset;
530 unsigned preferred : 1;
531 };
532
533 static int midx_oid_compare(const void *_a, const void *_b)
534 {
535 const struct pack_midx_entry *a = (const struct pack_midx_entry *)_a;
536 const struct pack_midx_entry *b = (const struct pack_midx_entry *)_b;
537 int cmp = oidcmp(&a->oid, &b->oid);
538
539 if (cmp)
540 return cmp;
541
542 /* Sort objects in a preferred pack first when multiple copies exist. */
543 if (a->preferred > b->preferred)
544 return -1;
545 if (a->preferred < b->preferred)
546 return 1;
547
548 if (a->pack_mtime > b->pack_mtime)
549 return -1;
550 else if (a->pack_mtime < b->pack_mtime)
551 return 1;
552
553 return a->pack_int_id - b->pack_int_id;
554 }
555
556 static int nth_midxed_pack_midx_entry(struct multi_pack_index *m,
557 struct pack_midx_entry *e,
558 uint32_t pos)
559 {
560 if (pos >= m->num_objects)
561 return 1;
562
563 nth_midxed_object_oid(&e->oid, m, pos);
564 e->pack_int_id = nth_midxed_pack_int_id(m, pos);
565 e->offset = nth_midxed_offset(m, pos);
566
567 /* consider objects in midx to be from "old" packs */
568 e->pack_mtime = 0;
569 return 0;
570 }
571
572 static void fill_pack_entry(uint32_t pack_int_id,
573 struct packed_git *p,
574 uint32_t cur_object,
575 struct pack_midx_entry *entry,
576 int preferred)
577 {
578 if (nth_packed_object_id(&entry->oid, p, cur_object) < 0)
579 die(_("failed to locate object %d in packfile"), cur_object);
580
581 entry->pack_int_id = pack_int_id;
582 entry->pack_mtime = p->mtime;
583
584 entry->offset = nth_packed_object_offset(p, cur_object);
585 entry->preferred = !!preferred;
586 }
587
588 /*
589 * It is possible to artificially get into a state where there are many
590 * duplicate copies of objects. That can create high memory pressure if
591 * we are to create a list of all objects before de-duplication. To reduce
592 * this memory pressure without a significant performance drop, automatically
593 * group objects by the first byte of their object id. Use the IDX fanout
594 * tables to group the data, copy to a local array, then sort.
595 *
596 * Copy only the de-duplicated entries (selected by most-recent modified time
597 * of a packfile containing the object).
598 */
599 static struct pack_midx_entry *get_sorted_entries(struct multi_pack_index *m,
600 struct pack_info *info,
601 uint32_t nr_packs,
602 uint32_t *nr_objects,
603 int preferred_pack)
604 {
605 uint32_t cur_fanout, cur_pack, cur_object;
606 uint32_t alloc_fanout, alloc_objects, total_objects = 0;
607 struct pack_midx_entry *entries_by_fanout = NULL;
608 struct pack_midx_entry *deduplicated_entries = NULL;
609 uint32_t start_pack = m ? m->num_packs : 0;
610
611 for (cur_pack = start_pack; cur_pack < nr_packs; cur_pack++)
612 total_objects += info[cur_pack].p->num_objects;
613
614 /*
615 * As we de-duplicate by fanout value, we expect the fanout
616 * slices to be evenly distributed, with some noise. Hence,
617 * allocate slightly more than one 256th.
618 */
619 alloc_objects = alloc_fanout = total_objects > 3200 ? total_objects / 200 : 16;
620
621 ALLOC_ARRAY(entries_by_fanout, alloc_fanout);
622 ALLOC_ARRAY(deduplicated_entries, alloc_objects);
623 *nr_objects = 0;
624
625 for (cur_fanout = 0; cur_fanout < 256; cur_fanout++) {
626 uint32_t nr_fanout = 0;
627
628 if (m) {
629 uint32_t start = 0, end;
630
631 if (cur_fanout)
632 start = ntohl(m->chunk_oid_fanout[cur_fanout - 1]);
633 end = ntohl(m->chunk_oid_fanout[cur_fanout]);
634
635 for (cur_object = start; cur_object < end; cur_object++) {
636 ALLOC_GROW(entries_by_fanout, nr_fanout + 1, alloc_fanout);
637 nth_midxed_pack_midx_entry(m,
638 &entries_by_fanout[nr_fanout],
639 cur_object);
640 if (nth_midxed_pack_int_id(m, cur_object) == preferred_pack)
641 entries_by_fanout[nr_fanout].preferred = 1;
642 else
643 entries_by_fanout[nr_fanout].preferred = 0;
644 nr_fanout++;
645 }
646 }
647
648 for (cur_pack = start_pack; cur_pack < nr_packs; cur_pack++) {
649 uint32_t start = 0, end;
650 int preferred = cur_pack == preferred_pack;
651
652 if (cur_fanout)
653 start = get_pack_fanout(info[cur_pack].p, cur_fanout - 1);
654 end = get_pack_fanout(info[cur_pack].p, cur_fanout);
655
656 for (cur_object = start; cur_object < end; cur_object++) {
657 ALLOC_GROW(entries_by_fanout, nr_fanout + 1, alloc_fanout);
658 fill_pack_entry(cur_pack,
659 info[cur_pack].p,
660 cur_object,
661 &entries_by_fanout[nr_fanout],
662 preferred);
663 nr_fanout++;
664 }
665 }
666
667 QSORT(entries_by_fanout, nr_fanout, midx_oid_compare);
668
669 /*
670 * The batch is now sorted by OID and then mtime (descending).
671 * Take only the first duplicate.
672 */
673 for (cur_object = 0; cur_object < nr_fanout; cur_object++) {
674 if (cur_object && oideq(&entries_by_fanout[cur_object - 1].oid,
675 &entries_by_fanout[cur_object].oid))
676 continue;
677
678 ALLOC_GROW(deduplicated_entries, *nr_objects + 1, alloc_objects);
679 memcpy(&deduplicated_entries[*nr_objects],
680 &entries_by_fanout[cur_object],
681 sizeof(struct pack_midx_entry));
682 (*nr_objects)++;
683 }
684 }
685
686 free(entries_by_fanout);
687 return deduplicated_entries;
688 }
689
690 static int write_midx_pack_names(struct hashfile *f, void *data)
691 {
692 struct write_midx_context *ctx = data;
693 uint32_t i;
694 unsigned char padding[MIDX_CHUNK_ALIGNMENT];
695 size_t written = 0;
696
697 for (i = 0; i < ctx->nr; i++) {
698 size_t writelen;
699
700 if (ctx->info[i].expired)
701 continue;
702
703 if (i && strcmp(ctx->info[i].pack_name, ctx->info[i - 1].pack_name) <= 0)
704 BUG("incorrect pack-file order: %s before %s",
705 ctx->info[i - 1].pack_name,
706 ctx->info[i].pack_name);
707
708 writelen = strlen(ctx->info[i].pack_name) + 1;
709 hashwrite(f, ctx->info[i].pack_name, writelen);
710 written += writelen;
711 }
712
713 /* add padding to be aligned */
714 i = MIDX_CHUNK_ALIGNMENT - (written % MIDX_CHUNK_ALIGNMENT);
715 if (i < MIDX_CHUNK_ALIGNMENT) {
716 memset(padding, 0, sizeof(padding));
717 hashwrite(f, padding, i);
718 }
719
720 return 0;
721 }
722
723 static int write_midx_oid_fanout(struct hashfile *f,
724 void *data)
725 {
726 struct write_midx_context *ctx = data;
727 struct pack_midx_entry *list = ctx->entries;
728 struct pack_midx_entry *last = ctx->entries + ctx->entries_nr;
729 uint32_t count = 0;
730 uint32_t i;
731
732 /*
733 * Write the first-level table (the list is sorted,
734 * but we use a 256-entry lookup to be able to avoid
735 * having to do eight extra binary search iterations).
736 */
737 for (i = 0; i < 256; i++) {
738 struct pack_midx_entry *next = list;
739
740 while (next < last && next->oid.hash[0] == i) {
741 count++;
742 next++;
743 }
744
745 hashwrite_be32(f, count);
746 list = next;
747 }
748
749 return 0;
750 }
751
752 static int write_midx_oid_lookup(struct hashfile *f,
753 void *data)
754 {
755 struct write_midx_context *ctx = data;
756 unsigned char hash_len = the_hash_algo->rawsz;
757 struct pack_midx_entry *list = ctx->entries;
758 uint32_t i;
759
760 for (i = 0; i < ctx->entries_nr; i++) {
761 struct pack_midx_entry *obj = list++;
762
763 if (i < ctx->entries_nr - 1) {
764 struct pack_midx_entry *next = list;
765 if (oidcmp(&obj->oid, &next->oid) >= 0)
766 BUG("OIDs not in order: %s >= %s",
767 oid_to_hex(&obj->oid),
768 oid_to_hex(&next->oid));
769 }
770
771 hashwrite(f, obj->oid.hash, (int)hash_len);
772 }
773
774 return 0;
775 }
776
777 static int write_midx_object_offsets(struct hashfile *f,
778 void *data)
779 {
780 struct write_midx_context *ctx = data;
781 struct pack_midx_entry *list = ctx->entries;
782 uint32_t i, nr_large_offset = 0;
783
784 for (i = 0; i < ctx->entries_nr; i++) {
785 struct pack_midx_entry *obj = list++;
786
787 if (ctx->pack_perm[obj->pack_int_id] == PACK_EXPIRED)
788 BUG("object %s is in an expired pack with int-id %d",
789 oid_to_hex(&obj->oid),
790 obj->pack_int_id);
791
792 hashwrite_be32(f, ctx->pack_perm[obj->pack_int_id]);
793
794 if (ctx->large_offsets_needed && obj->offset >> 31)
795 hashwrite_be32(f, MIDX_LARGE_OFFSET_NEEDED | nr_large_offset++);
796 else if (!ctx->large_offsets_needed && obj->offset >> 32)
797 BUG("object %s requires a large offset (%"PRIx64") but the MIDX is not writing large offsets!",
798 oid_to_hex(&obj->oid),
799 obj->offset);
800 else
801 hashwrite_be32(f, (uint32_t)obj->offset);
802 }
803
804 return 0;
805 }
806
807 static int write_midx_large_offsets(struct hashfile *f,
808 void *data)
809 {
810 struct write_midx_context *ctx = data;
811 struct pack_midx_entry *list = ctx->entries;
812 struct pack_midx_entry *end = ctx->entries + ctx->entries_nr;
813 uint32_t nr_large_offset = ctx->num_large_offsets;
814
815 while (nr_large_offset) {
816 struct pack_midx_entry *obj;
817 uint64_t offset;
818
819 if (list >= end)
820 BUG("too many large-offset objects");
821
822 obj = list++;
823 offset = obj->offset;
824
825 if (!(offset >> 31))
826 continue;
827
828 hashwrite_be64(f, offset);
829
830 nr_large_offset--;
831 }
832
833 return 0;
834 }
835
836 struct midx_pack_order_data {
837 uint32_t nr;
838 uint32_t pack;
839 off_t offset;
840 };
841
842 static int midx_pack_order_cmp(const void *va, const void *vb)
843 {
844 const struct midx_pack_order_data *a = va, *b = vb;
845 if (a->pack < b->pack)
846 return -1;
847 else if (a->pack > b->pack)
848 return 1;
849 else if (a->offset < b->offset)
850 return -1;
851 else if (a->offset > b->offset)
852 return 1;
853 else
854 return 0;
855 }
856
857 static uint32_t *midx_pack_order(struct write_midx_context *ctx)
858 {
859 struct midx_pack_order_data *data;
860 uint32_t *pack_order;
861 uint32_t i;
862
863 ALLOC_ARRAY(data, ctx->entries_nr);
864 for (i = 0; i < ctx->entries_nr; i++) {
865 struct pack_midx_entry *e = &ctx->entries[i];
866 data[i].nr = i;
867 data[i].pack = ctx->pack_perm[e->pack_int_id];
868 if (!e->preferred)
869 data[i].pack |= (1U << 31);
870 data[i].offset = e->offset;
871 }
872
873 QSORT(data, ctx->entries_nr, midx_pack_order_cmp);
874
875 ALLOC_ARRAY(pack_order, ctx->entries_nr);
876 for (i = 0; i < ctx->entries_nr; i++)
877 pack_order[i] = data[i].nr;
878 free(data);
879
880 return pack_order;
881 }
882
883 static void write_midx_reverse_index(char *midx_name, unsigned char *midx_hash,
884 struct write_midx_context *ctx)
885 {
886 struct strbuf buf = STRBUF_INIT;
887 const char *tmp_file;
888
889 strbuf_addf(&buf, "%s-%s.rev", midx_name, hash_to_hex(midx_hash));
890
891 tmp_file = write_rev_file_order(NULL, ctx->pack_order, ctx->entries_nr,
892 midx_hash, WRITE_REV);
893
894 if (finalize_object_file(tmp_file, buf.buf))
895 die(_("cannot store reverse index file"));
896
897 strbuf_release(&buf);
898 }
899
900 static void clear_midx_files_ext(const char *object_dir, const char *ext,
901 unsigned char *keep_hash);
902
903 static int midx_checksum_valid(struct multi_pack_index *m)
904 {
905 return hashfile_checksum_valid(m->data, m->data_len);
906 }
907
908 static void prepare_midx_packing_data(struct packing_data *pdata,
909 struct write_midx_context *ctx)
910 {
911 uint32_t i;
912
913 memset(pdata, 0, sizeof(struct packing_data));
914 prepare_packing_data(the_repository, pdata);
915
916 for (i = 0; i < ctx->entries_nr; i++) {
917 struct pack_midx_entry *from = &ctx->entries[ctx->pack_order[i]];
918 struct object_entry *to = packlist_alloc(pdata, &from->oid);
919
920 oe_set_in_pack(pdata, to,
921 ctx->info[ctx->pack_perm[from->pack_int_id]].p);
922 }
923 }
924
925 static int add_ref_to_pending(const char *refname,
926 const struct object_id *oid,
927 int flag, void *cb_data)
928 {
929 struct rev_info *revs = (struct rev_info*)cb_data;
930 struct object *object;
931
932 if ((flag & REF_ISSYMREF) && (flag & REF_ISBROKEN)) {
933 warning("symbolic ref is dangling: %s", refname);
934 return 0;
935 }
936
937 object = parse_object_or_die(oid, refname);
938 if (object->type != OBJ_COMMIT)
939 return 0;
940
941 add_pending_object(revs, object, "");
942 if (bitmap_is_preferred_refname(revs->repo, refname))
943 object->flags |= NEEDS_BITMAP;
944 return 0;
945 }
946
947 struct bitmap_commit_cb {
948 struct commit **commits;
949 size_t commits_nr, commits_alloc;
950
951 struct write_midx_context *ctx;
952 };
953
954 static const struct object_id *bitmap_oid_access(size_t index,
955 const void *_entries)
956 {
957 const struct pack_midx_entry *entries = _entries;
958 return &entries[index].oid;
959 }
960
961 static void bitmap_show_commit(struct commit *commit, void *_data)
962 {
963 struct bitmap_commit_cb *data = _data;
964 int pos = oid_pos(&commit->object.oid, data->ctx->entries,
965 data->ctx->entries_nr,
966 bitmap_oid_access);
967 if (pos < 0)
968 return;
969
970 ALLOC_GROW(data->commits, data->commits_nr + 1, data->commits_alloc);
971 data->commits[data->commits_nr++] = commit;
972 }
973
974 static int read_refs_snapshot(const char *refs_snapshot,
975 struct rev_info *revs)
976 {
977 struct strbuf buf = STRBUF_INIT;
978 struct object_id oid;
979 FILE *f = xfopen(refs_snapshot, "r");
980
981 while (strbuf_getline(&buf, f) != EOF) {
982 struct object *object;
983 int preferred = 0;
984 char *hex = buf.buf;
985 const char *end = NULL;
986
987 if (buf.len && *buf.buf == '+') {
988 preferred = 1;
989 hex = &buf.buf[1];
990 }
991
992 if (parse_oid_hex(hex, &oid, &end) < 0)
993 die(_("could not parse line: %s"), buf.buf);
994 if (*end)
995 die(_("malformed line: %s"), buf.buf);
996
997 object = parse_object_or_die(&oid, NULL);
998 if (preferred)
999 object->flags |= NEEDS_BITMAP;
1000
1001 add_pending_object(revs, object, "");
1002 }
1003
1004 fclose(f);
1005 strbuf_release(&buf);
1006 return 0;
1007 }
1008
1009 static struct commit **find_commits_for_midx_bitmap(uint32_t *indexed_commits_nr_p,
1010 const char *refs_snapshot,
1011 struct write_midx_context *ctx)
1012 {
1013 struct rev_info revs;
1014 struct bitmap_commit_cb cb = {0};
1015
1016 cb.ctx = ctx;
1017
1018 repo_init_revisions(the_repository, &revs, NULL);
1019 if (refs_snapshot) {
1020 read_refs_snapshot(refs_snapshot, &revs);
1021 } else {
1022 setup_revisions(0, NULL, &revs, NULL);
1023 for_each_ref(add_ref_to_pending, &revs);
1024 }
1025
1026 /*
1027 * Skipping promisor objects here is intentional, since it only excludes
1028 * them from the list of reachable commits that we want to select from
1029 * when computing the selection of MIDX'd commits to receive bitmaps.
1030 *
1031 * Reachability bitmaps do require that their objects be closed under
1032 * reachability, but fetching any objects missing from promisors at this
1033 * point is too late. But, if one of those objects can be reached from
1034 * an another object that is included in the bitmap, then we will
1035 * complain later that we don't have reachability closure (and fail
1036 * appropriately).
1037 */
1038 fetch_if_missing = 0;
1039 revs.exclude_promisor_objects = 1;
1040
1041 if (prepare_revision_walk(&revs))
1042 die(_("revision walk setup failed"));
1043
1044 traverse_commit_list(&revs, bitmap_show_commit, NULL, &cb);
1045 if (indexed_commits_nr_p)
1046 *indexed_commits_nr_p = cb.commits_nr;
1047
1048 return cb.commits;
1049 }
1050
1051 static int write_midx_bitmap(char *midx_name, unsigned char *midx_hash,
1052 struct write_midx_context *ctx,
1053 const char *refs_snapshot,
1054 unsigned flags)
1055 {
1056 struct packing_data pdata;
1057 struct pack_idx_entry **index;
1058 struct commit **commits = NULL;
1059 uint32_t i, commits_nr;
1060 uint16_t options = 0;
1061 char *bitmap_name = xstrfmt("%s-%s.bitmap", midx_name, hash_to_hex(midx_hash));
1062 int ret;
1063
1064 if (!ctx->entries_nr)
1065 BUG("cannot write a bitmap without any objects");
1066
1067 if (flags & MIDX_WRITE_BITMAP_HASH_CACHE)
1068 options |= BITMAP_OPT_HASH_CACHE;
1069
1070 prepare_midx_packing_data(&pdata, ctx);
1071
1072 commits = find_commits_for_midx_bitmap(&commits_nr, refs_snapshot, ctx);
1073
1074 /*
1075 * Build the MIDX-order index based on pdata.objects (which is already
1076 * in MIDX order; c.f., 'midx_pack_order_cmp()' for the definition of
1077 * this order).
1078 */
1079 ALLOC_ARRAY(index, pdata.nr_objects);
1080 for (i = 0; i < pdata.nr_objects; i++)
1081 index[i] = &pdata.objects[i].idx;
1082
1083 bitmap_writer_show_progress(flags & MIDX_PROGRESS);
1084 bitmap_writer_build_type_index(&pdata, index, pdata.nr_objects);
1085
1086 /*
1087 * bitmap_writer_finish expects objects in lex order, but pack_order
1088 * gives us exactly that. use it directly instead of re-sorting the
1089 * array.
1090 *
1091 * This changes the order of objects in 'index' between
1092 * bitmap_writer_build_type_index and bitmap_writer_finish.
1093 *
1094 * The same re-ordering takes place in the single-pack bitmap code via
1095 * write_idx_file(), which is called by finish_tmp_packfile(), which
1096 * happens between bitmap_writer_build_type_index() and
1097 * bitmap_writer_finish().
1098 */
1099 for (i = 0; i < pdata.nr_objects; i++)
1100 index[ctx->pack_order[i]] = &pdata.objects[i].idx;
1101
1102 bitmap_writer_select_commits(commits, commits_nr, -1);
1103 ret = bitmap_writer_build(&pdata);
1104 if (ret < 0)
1105 goto cleanup;
1106
1107 bitmap_writer_set_checksum(midx_hash);
1108 bitmap_writer_finish(index, pdata.nr_objects, bitmap_name, options);
1109
1110 cleanup:
1111 free(index);
1112 free(bitmap_name);
1113 return ret;
1114 }
1115
1116 static struct multi_pack_index *lookup_multi_pack_index(struct repository *r,
1117 const char *object_dir)
1118 {
1119 struct multi_pack_index *cur;
1120
1121 /* Ensure the given object_dir is local, or a known alternate. */
1122 find_odb(r, object_dir);
1123
1124 for (cur = get_multi_pack_index(r); cur; cur = cur->next) {
1125 if (!strcmp(object_dir, cur->object_dir))
1126 return cur;
1127 }
1128
1129 return NULL;
1130 }
1131
1132 static int write_midx_internal(const char *object_dir,
1133 struct string_list *packs_to_include,
1134 struct string_list *packs_to_drop,
1135 const char *preferred_pack_name,
1136 const char *refs_snapshot,
1137 unsigned flags)
1138 {
1139 struct strbuf midx_name = STRBUF_INIT;
1140 unsigned char midx_hash[GIT_MAX_RAWSZ];
1141 uint32_t i;
1142 struct hashfile *f = NULL;
1143 struct lock_file lk;
1144 struct write_midx_context ctx = { 0 };
1145 int pack_name_concat_len = 0;
1146 int dropped_packs = 0;
1147 int result = 0;
1148 struct chunkfile *cf;
1149
1150 get_midx_filename(&midx_name, object_dir);
1151 if (safe_create_leading_directories(midx_name.buf))
1152 die_errno(_("unable to create leading directories of %s"),
1153 midx_name.buf);
1154
1155 if (!packs_to_include) {
1156 /*
1157 * Only reference an existing MIDX when not filtering which
1158 * packs to include, since all packs and objects are copied
1159 * blindly from an existing MIDX if one is present.
1160 */
1161 ctx.m = lookup_multi_pack_index(the_repository, object_dir);
1162 }
1163
1164 if (ctx.m && !midx_checksum_valid(ctx.m)) {
1165 warning(_("ignoring existing multi-pack-index; checksum mismatch"));
1166 ctx.m = NULL;
1167 }
1168
1169 ctx.nr = 0;
1170 ctx.alloc = ctx.m ? ctx.m->num_packs : 16;
1171 ctx.info = NULL;
1172 ALLOC_ARRAY(ctx.info, ctx.alloc);
1173
1174 if (ctx.m) {
1175 for (i = 0; i < ctx.m->num_packs; i++) {
1176 ALLOC_GROW(ctx.info, ctx.nr + 1, ctx.alloc);
1177
1178 ctx.info[ctx.nr].orig_pack_int_id = i;
1179 ctx.info[ctx.nr].pack_name = xstrdup(ctx.m->pack_names[i]);
1180 ctx.info[ctx.nr].p = ctx.m->packs[i];
1181 ctx.info[ctx.nr].expired = 0;
1182
1183 if (flags & MIDX_WRITE_REV_INDEX) {
1184 /*
1185 * If generating a reverse index, need to have
1186 * packed_git's loaded to compare their
1187 * mtimes and object count.
1188 */
1189 if (prepare_midx_pack(the_repository, ctx.m, i)) {
1190 error(_("could not load pack"));
1191 result = 1;
1192 goto cleanup;
1193 }
1194
1195 if (open_pack_index(ctx.m->packs[i]))
1196 die(_("could not open index for %s"),
1197 ctx.m->packs[i]->pack_name);
1198 ctx.info[ctx.nr].p = ctx.m->packs[i];
1199 }
1200
1201 ctx.nr++;
1202 }
1203 }
1204
1205 ctx.pack_paths_checked = 0;
1206 if (flags & MIDX_PROGRESS)
1207 ctx.progress = start_delayed_progress(_("Adding packfiles to multi-pack-index"), 0);
1208 else
1209 ctx.progress = NULL;
1210
1211 ctx.to_include = packs_to_include;
1212
1213 for_each_file_in_pack_dir(object_dir, add_pack_to_midx, &ctx);
1214 stop_progress(&ctx.progress);
1215
1216 if ((ctx.m && ctx.nr == ctx.m->num_packs) &&
1217 !(packs_to_include || packs_to_drop)) {
1218 struct bitmap_index *bitmap_git;
1219 int bitmap_exists;
1220 int want_bitmap = flags & MIDX_WRITE_BITMAP;
1221
1222 bitmap_git = prepare_midx_bitmap_git(ctx.m);
1223 bitmap_exists = bitmap_git && bitmap_is_midx(bitmap_git);
1224 free_bitmap_index(bitmap_git);
1225
1226 if (bitmap_exists || !want_bitmap) {
1227 /*
1228 * The correct MIDX already exists, and so does a
1229 * corresponding bitmap (or one wasn't requested).
1230 */
1231 if (!want_bitmap)
1232 clear_midx_files_ext(object_dir, ".bitmap",
1233 NULL);
1234 goto cleanup;
1235 }
1236 }
1237
1238 if (preferred_pack_name) {
1239 int found = 0;
1240 for (i = 0; i < ctx.nr; i++) {
1241 if (!cmp_idx_or_pack_name(preferred_pack_name,
1242 ctx.info[i].pack_name)) {
1243 ctx.preferred_pack_idx = i;
1244 found = 1;
1245 break;
1246 }
1247 }
1248
1249 if (!found)
1250 warning(_("unknown preferred pack: '%s'"),
1251 preferred_pack_name);
1252 } else if (ctx.nr &&
1253 (flags & (MIDX_WRITE_REV_INDEX | MIDX_WRITE_BITMAP))) {
1254 struct packed_git *oldest = ctx.info[ctx.preferred_pack_idx].p;
1255 ctx.preferred_pack_idx = 0;
1256
1257 if (packs_to_drop && packs_to_drop->nr)
1258 BUG("cannot write a MIDX bitmap during expiration");
1259
1260 /*
1261 * set a preferred pack when writing a bitmap to ensure that
1262 * the pack from which the first object is selected in pseudo
1263 * pack-order has all of its objects selected from that pack
1264 * (and not another pack containing a duplicate)
1265 */
1266 for (i = 1; i < ctx.nr; i++) {
1267 struct packed_git *p = ctx.info[i].p;
1268
1269 if (!oldest->num_objects || p->mtime < oldest->mtime) {
1270 oldest = p;
1271 ctx.preferred_pack_idx = i;
1272 }
1273 }
1274
1275 if (!oldest->num_objects) {
1276 /*
1277 * If all packs are empty; unset the preferred index.
1278 * This is acceptable since there will be no duplicate
1279 * objects to resolve, so the preferred value doesn't
1280 * matter.
1281 */
1282 ctx.preferred_pack_idx = -1;
1283 }
1284 } else {
1285 /*
1286 * otherwise don't mark any pack as preferred to avoid
1287 * interfering with expiration logic below
1288 */
1289 ctx.preferred_pack_idx = -1;
1290 }
1291
1292 if (ctx.preferred_pack_idx > -1) {
1293 struct packed_git *preferred = ctx.info[ctx.preferred_pack_idx].p;
1294 if (!preferred->num_objects) {
1295 error(_("cannot select preferred pack %s with no objects"),
1296 preferred->pack_name);
1297 result = 1;
1298 goto cleanup;
1299 }
1300 }
1301
1302 ctx.entries = get_sorted_entries(ctx.m, ctx.info, ctx.nr, &ctx.entries_nr,
1303 ctx.preferred_pack_idx);
1304
1305 ctx.large_offsets_needed = 0;
1306 for (i = 0; i < ctx.entries_nr; i++) {
1307 if (ctx.entries[i].offset > 0x7fffffff)
1308 ctx.num_large_offsets++;
1309 if (ctx.entries[i].offset > 0xffffffff)
1310 ctx.large_offsets_needed = 1;
1311 }
1312
1313 QSORT(ctx.info, ctx.nr, pack_info_compare);
1314
1315 if (packs_to_drop && packs_to_drop->nr) {
1316 int drop_index = 0;
1317 int missing_drops = 0;
1318
1319 for (i = 0; i < ctx.nr && drop_index < packs_to_drop->nr; i++) {
1320 int cmp = strcmp(ctx.info[i].pack_name,
1321 packs_to_drop->items[drop_index].string);
1322
1323 if (!cmp) {
1324 drop_index++;
1325 ctx.info[i].expired = 1;
1326 } else if (cmp > 0) {
1327 error(_("did not see pack-file %s to drop"),
1328 packs_to_drop->items[drop_index].string);
1329 drop_index++;
1330 missing_drops++;
1331 i--;
1332 } else {
1333 ctx.info[i].expired = 0;
1334 }
1335 }
1336
1337 if (missing_drops) {
1338 result = 1;
1339 goto cleanup;
1340 }
1341 }
1342
1343 /*
1344 * pack_perm stores a permutation between pack-int-ids from the
1345 * previous multi-pack-index to the new one we are writing:
1346 *
1347 * pack_perm[old_id] = new_id
1348 */
1349 ALLOC_ARRAY(ctx.pack_perm, ctx.nr);
1350 for (i = 0; i < ctx.nr; i++) {
1351 if (ctx.info[i].expired) {
1352 dropped_packs++;
1353 ctx.pack_perm[ctx.info[i].orig_pack_int_id] = PACK_EXPIRED;
1354 } else {
1355 ctx.pack_perm[ctx.info[i].orig_pack_int_id] = i - dropped_packs;
1356 }
1357 }
1358
1359 for (i = 0; i < ctx.nr; i++) {
1360 if (!ctx.info[i].expired)
1361 pack_name_concat_len += strlen(ctx.info[i].pack_name) + 1;
1362 }
1363
1364 /* Check that the preferred pack wasn't expired (if given). */
1365 if (preferred_pack_name) {
1366 struct pack_info *preferred = bsearch(preferred_pack_name,
1367 ctx.info, ctx.nr,
1368 sizeof(*ctx.info),
1369 idx_or_pack_name_cmp);
1370 if (preferred) {
1371 uint32_t perm = ctx.pack_perm[preferred->orig_pack_int_id];
1372 if (perm == PACK_EXPIRED)
1373 warning(_("preferred pack '%s' is expired"),
1374 preferred_pack_name);
1375 }
1376 }
1377
1378 if (pack_name_concat_len % MIDX_CHUNK_ALIGNMENT)
1379 pack_name_concat_len += MIDX_CHUNK_ALIGNMENT -
1380 (pack_name_concat_len % MIDX_CHUNK_ALIGNMENT);
1381
1382 hold_lock_file_for_update(&lk, midx_name.buf, LOCK_DIE_ON_ERROR);
1383 f = hashfd(get_lock_file_fd(&lk), get_lock_file_path(&lk));
1384
1385 if (ctx.nr - dropped_packs == 0) {
1386 error(_("no pack files to index."));
1387 result = 1;
1388 goto cleanup;
1389 }
1390
1391 if (!ctx.entries_nr) {
1392 if (flags & MIDX_WRITE_BITMAP)
1393 warning(_("refusing to write multi-pack .bitmap without any objects"));
1394 flags &= ~(MIDX_WRITE_REV_INDEX | MIDX_WRITE_BITMAP);
1395 }
1396
1397 cf = init_chunkfile(f);
1398
1399 add_chunk(cf, MIDX_CHUNKID_PACKNAMES, pack_name_concat_len,
1400 write_midx_pack_names);
1401 add_chunk(cf, MIDX_CHUNKID_OIDFANOUT, MIDX_CHUNK_FANOUT_SIZE,
1402 write_midx_oid_fanout);
1403 add_chunk(cf, MIDX_CHUNKID_OIDLOOKUP,
1404 (size_t)ctx.entries_nr * the_hash_algo->rawsz,
1405 write_midx_oid_lookup);
1406 add_chunk(cf, MIDX_CHUNKID_OBJECTOFFSETS,
1407 (size_t)ctx.entries_nr * MIDX_CHUNK_OFFSET_WIDTH,
1408 write_midx_object_offsets);
1409
1410 if (ctx.large_offsets_needed)
1411 add_chunk(cf, MIDX_CHUNKID_LARGEOFFSETS,
1412 (size_t)ctx.num_large_offsets * MIDX_CHUNK_LARGE_OFFSET_WIDTH,
1413 write_midx_large_offsets);
1414
1415 write_midx_header(f, get_num_chunks(cf), ctx.nr - dropped_packs);
1416 write_chunkfile(cf, &ctx);
1417
1418 finalize_hashfile(f, midx_hash, CSUM_FSYNC | CSUM_HASH_IN_STREAM);
1419 free_chunkfile(cf);
1420
1421 if (flags & (MIDX_WRITE_REV_INDEX | MIDX_WRITE_BITMAP))
1422 ctx.pack_order = midx_pack_order(&ctx);
1423
1424 if (flags & MIDX_WRITE_REV_INDEX)
1425 write_midx_reverse_index(midx_name.buf, midx_hash, &ctx);
1426 if (flags & MIDX_WRITE_BITMAP) {
1427 if (write_midx_bitmap(midx_name.buf, midx_hash, &ctx,
1428 refs_snapshot, flags) < 0) {
1429 error(_("could not write multi-pack bitmap"));
1430 result = 1;
1431 goto cleanup;
1432 }
1433 }
1434
1435 if (ctx.m)
1436 close_object_store(the_repository->objects);
1437
1438 if (commit_lock_file(&lk) < 0)
1439 die_errno(_("could not write multi-pack-index"));
1440
1441 clear_midx_files_ext(object_dir, ".bitmap", midx_hash);
1442 clear_midx_files_ext(object_dir, ".rev", midx_hash);
1443
1444 cleanup:
1445 for (i = 0; i < ctx.nr; i++) {
1446 if (ctx.info[i].p) {
1447 close_pack(ctx.info[i].p);
1448 free(ctx.info[i].p);
1449 }
1450 free(ctx.info[i].pack_name);
1451 }
1452
1453 free(ctx.info);
1454 free(ctx.entries);
1455 free(ctx.pack_perm);
1456 free(ctx.pack_order);
1457 strbuf_release(&midx_name);
1458
1459 return result;
1460 }
1461
1462 int write_midx_file(const char *object_dir,
1463 const char *preferred_pack_name,
1464 const char *refs_snapshot,
1465 unsigned flags)
1466 {
1467 return write_midx_internal(object_dir, NULL, NULL, preferred_pack_name,
1468 refs_snapshot, flags);
1469 }
1470
1471 int write_midx_file_only(const char *object_dir,
1472 struct string_list *packs_to_include,
1473 const char *preferred_pack_name,
1474 const char *refs_snapshot,
1475 unsigned flags)
1476 {
1477 return write_midx_internal(object_dir, packs_to_include, NULL,
1478 preferred_pack_name, refs_snapshot, flags);
1479 }
1480
1481 struct clear_midx_data {
1482 char *keep;
1483 const char *ext;
1484 };
1485
1486 static void clear_midx_file_ext(const char *full_path, size_t full_path_len,
1487 const char *file_name, void *_data)
1488 {
1489 struct clear_midx_data *data = _data;
1490
1491 if (!(starts_with(file_name, "multi-pack-index-") &&
1492 ends_with(file_name, data->ext)))
1493 return;
1494 if (data->keep && !strcmp(data->keep, file_name))
1495 return;
1496
1497 if (unlink(full_path))
1498 die_errno(_("failed to remove %s"), full_path);
1499 }
1500
1501 static void clear_midx_files_ext(const char *object_dir, const char *ext,
1502 unsigned char *keep_hash)
1503 {
1504 struct clear_midx_data data;
1505 memset(&data, 0, sizeof(struct clear_midx_data));
1506
1507 if (keep_hash)
1508 data.keep = xstrfmt("multi-pack-index-%s%s",
1509 hash_to_hex(keep_hash), ext);
1510 data.ext = ext;
1511
1512 for_each_file_in_pack_dir(object_dir,
1513 clear_midx_file_ext,
1514 &data);
1515
1516 free(data.keep);
1517 }
1518
1519 void clear_midx_file(struct repository *r)
1520 {
1521 struct strbuf midx = STRBUF_INIT;
1522
1523 get_midx_filename(&midx, r->objects->odb->path);
1524
1525 if (r->objects && r->objects->multi_pack_index) {
1526 close_midx(r->objects->multi_pack_index);
1527 r->objects->multi_pack_index = NULL;
1528 }
1529
1530 if (remove_path(midx.buf))
1531 die(_("failed to clear multi-pack-index at %s"), midx.buf);
1532
1533 clear_midx_files_ext(r->objects->odb->path, ".bitmap", NULL);
1534 clear_midx_files_ext(r->objects->odb->path, ".rev", NULL);
1535
1536 strbuf_release(&midx);
1537 }
1538
1539 static int verify_midx_error;
1540
1541 __attribute__((format (printf, 1, 2)))
1542 static void midx_report(const char *fmt, ...)
1543 {
1544 va_list ap;
1545 verify_midx_error = 1;
1546 va_start(ap, fmt);
1547 vfprintf(stderr, fmt, ap);
1548 fprintf(stderr, "\n");
1549 va_end(ap);
1550 }
1551
1552 struct pair_pos_vs_id
1553 {
1554 uint32_t pos;
1555 uint32_t pack_int_id;
1556 };
1557
1558 static int compare_pair_pos_vs_id(const void *_a, const void *_b)
1559 {
1560 struct pair_pos_vs_id *a = (struct pair_pos_vs_id *)_a;
1561 struct pair_pos_vs_id *b = (struct pair_pos_vs_id *)_b;
1562
1563 return b->pack_int_id - a->pack_int_id;
1564 }
1565
1566 /*
1567 * Limit calls to display_progress() for performance reasons.
1568 * The interval here was arbitrarily chosen.
1569 */
1570 #define SPARSE_PROGRESS_INTERVAL (1 << 12)
1571 #define midx_display_sparse_progress(progress, n) \
1572 do { \
1573 uint64_t _n = (n); \
1574 if ((_n & (SPARSE_PROGRESS_INTERVAL - 1)) == 0) \
1575 display_progress(progress, _n); \
1576 } while (0)
1577
1578 int verify_midx_file(struct repository *r, const char *object_dir, unsigned flags)
1579 {
1580 struct pair_pos_vs_id *pairs = NULL;
1581 uint32_t i;
1582 struct progress *progress = NULL;
1583 struct multi_pack_index *m = load_multi_pack_index(object_dir, 1);
1584 verify_midx_error = 0;
1585
1586 if (!m) {
1587 int result = 0;
1588 struct stat sb;
1589 struct strbuf filename = STRBUF_INIT;
1590
1591 get_midx_filename(&filename, object_dir);
1592
1593 if (!stat(filename.buf, &sb)) {
1594 error(_("multi-pack-index file exists, but failed to parse"));
1595 result = 1;
1596 }
1597 strbuf_release(&filename);
1598 return result;
1599 }
1600
1601 if (!midx_checksum_valid(m))
1602 midx_report(_("incorrect checksum"));
1603
1604 if (flags & MIDX_PROGRESS)
1605 progress = start_delayed_progress(_("Looking for referenced packfiles"),
1606 m->num_packs);
1607 for (i = 0; i < m->num_packs; i++) {
1608 if (prepare_midx_pack(r, m, i))
1609 midx_report("failed to load pack in position %d", i);
1610
1611 display_progress(progress, i + 1);
1612 }
1613 stop_progress(&progress);
1614
1615 for (i = 0; i < 255; i++) {
1616 uint32_t oid_fanout1 = ntohl(m->chunk_oid_fanout[i]);
1617 uint32_t oid_fanout2 = ntohl(m->chunk_oid_fanout[i + 1]);
1618
1619 if (oid_fanout1 > oid_fanout2)
1620 midx_report(_("oid fanout out of order: fanout[%d] = %"PRIx32" > %"PRIx32" = fanout[%d]"),
1621 i, oid_fanout1, oid_fanout2, i + 1);
1622 }
1623
1624 if (m->num_objects == 0) {
1625 midx_report(_("the midx contains no oid"));
1626 /*
1627 * Remaining tests assume that we have objects, so we can
1628 * return here.
1629 */
1630 goto cleanup;
1631 }
1632
1633 if (flags & MIDX_PROGRESS)
1634 progress = start_sparse_progress(_("Verifying OID order in multi-pack-index"),
1635 m->num_objects - 1);
1636 for (i = 0; i < m->num_objects - 1; i++) {
1637 struct object_id oid1, oid2;
1638
1639 nth_midxed_object_oid(&oid1, m, i);
1640 nth_midxed_object_oid(&oid2, m, i + 1);
1641
1642 if (oidcmp(&oid1, &oid2) >= 0)
1643 midx_report(_("oid lookup out of order: oid[%d] = %s >= %s = oid[%d]"),
1644 i, oid_to_hex(&oid1), oid_to_hex(&oid2), i + 1);
1645
1646 midx_display_sparse_progress(progress, i + 1);
1647 }
1648 stop_progress(&progress);
1649
1650 /*
1651 * Create an array mapping each object to its packfile id. Sort it
1652 * to group the objects by packfile. Use this permutation to visit
1653 * each of the objects and only require 1 packfile to be open at a
1654 * time.
1655 */
1656 ALLOC_ARRAY(pairs, m->num_objects);
1657 for (i = 0; i < m->num_objects; i++) {
1658 pairs[i].pos = i;
1659 pairs[i].pack_int_id = nth_midxed_pack_int_id(m, i);
1660 }
1661
1662 if (flags & MIDX_PROGRESS)
1663 progress = start_sparse_progress(_("Sorting objects by packfile"),
1664 m->num_objects);
1665 display_progress(progress, 0); /* TODO: Measure QSORT() progress */
1666 QSORT(pairs, m->num_objects, compare_pair_pos_vs_id);
1667 stop_progress(&progress);
1668
1669 if (flags & MIDX_PROGRESS)
1670 progress = start_sparse_progress(_("Verifying object offsets"), m->num_objects);
1671 for (i = 0; i < m->num_objects; i++) {
1672 struct object_id oid;
1673 struct pack_entry e;
1674 off_t m_offset, p_offset;
1675
1676 if (i > 0 && pairs[i-1].pack_int_id != pairs[i].pack_int_id &&
1677 m->packs[pairs[i-1].pack_int_id])
1678 {
1679 close_pack_fd(m->packs[pairs[i-1].pack_int_id]);
1680 close_pack_index(m->packs[pairs[i-1].pack_int_id]);
1681 }
1682
1683 nth_midxed_object_oid(&oid, m, pairs[i].pos);
1684
1685 if (!fill_midx_entry(r, &oid, &e, m)) {
1686 midx_report(_("failed to load pack entry for oid[%d] = %s"),
1687 pairs[i].pos, oid_to_hex(&oid));
1688 continue;
1689 }
1690
1691 if (open_pack_index(e.p)) {
1692 midx_report(_("failed to load pack-index for packfile %s"),
1693 e.p->pack_name);
1694 break;
1695 }
1696
1697 m_offset = e.offset;
1698 p_offset = find_pack_entry_one(oid.hash, e.p);
1699
1700 if (m_offset != p_offset)
1701 midx_report(_("incorrect object offset for oid[%d] = %s: %"PRIx64" != %"PRIx64),
1702 pairs[i].pos, oid_to_hex(&oid), m_offset, p_offset);
1703
1704 midx_display_sparse_progress(progress, i + 1);
1705 }
1706 stop_progress(&progress);
1707
1708 cleanup:
1709 free(pairs);
1710 close_midx(m);
1711
1712 return verify_midx_error;
1713 }
1714
1715 int expire_midx_packs(struct repository *r, const char *object_dir, unsigned flags)
1716 {
1717 uint32_t i, *count, result = 0;
1718 struct string_list packs_to_drop = STRING_LIST_INIT_DUP;
1719 struct multi_pack_index *m = lookup_multi_pack_index(r, object_dir);
1720 struct progress *progress = NULL;
1721
1722 if (!m)
1723 return 0;
1724
1725 CALLOC_ARRAY(count, m->num_packs);
1726
1727 if (flags & MIDX_PROGRESS)
1728 progress = start_delayed_progress(_("Counting referenced objects"),
1729 m->num_objects);
1730 for (i = 0; i < m->num_objects; i++) {
1731 int pack_int_id = nth_midxed_pack_int_id(m, i);
1732 count[pack_int_id]++;
1733 display_progress(progress, i + 1);
1734 }
1735 stop_progress(&progress);
1736
1737 if (flags & MIDX_PROGRESS)
1738 progress = start_delayed_progress(_("Finding and deleting unreferenced packfiles"),
1739 m->num_packs);
1740 for (i = 0; i < m->num_packs; i++) {
1741 char *pack_name;
1742 display_progress(progress, i + 1);
1743
1744 if (count[i])
1745 continue;
1746
1747 if (prepare_midx_pack(r, m, i))
1748 continue;
1749
1750 if (m->packs[i]->pack_keep)
1751 continue;
1752
1753 pack_name = xstrdup(m->packs[i]->pack_name);
1754 close_pack(m->packs[i]);
1755
1756 string_list_insert(&packs_to_drop, m->pack_names[i]);
1757 unlink_pack_path(pack_name, 0);
1758 free(pack_name);
1759 }
1760 stop_progress(&progress);
1761
1762 free(count);
1763
1764 if (packs_to_drop.nr)
1765 result = write_midx_internal(object_dir, NULL, &packs_to_drop, NULL, NULL, flags);
1766
1767 string_list_clear(&packs_to_drop, 0);
1768
1769 return result;
1770 }
1771
1772 struct repack_info {
1773 timestamp_t mtime;
1774 uint32_t referenced_objects;
1775 uint32_t pack_int_id;
1776 };
1777
1778 static int compare_by_mtime(const void *a_, const void *b_)
1779 {
1780 const struct repack_info *a, *b;
1781
1782 a = (const struct repack_info *)a_;
1783 b = (const struct repack_info *)b_;
1784
1785 if (a->mtime < b->mtime)
1786 return -1;
1787 if (a->mtime > b->mtime)
1788 return 1;
1789 return 0;
1790 }
1791
1792 static int fill_included_packs_all(struct repository *r,
1793 struct multi_pack_index *m,
1794 unsigned char *include_pack)
1795 {
1796 uint32_t i, count = 0;
1797 int pack_kept_objects = 0;
1798
1799 repo_config_get_bool(r, "repack.packkeptobjects", &pack_kept_objects);
1800
1801 for (i = 0; i < m->num_packs; i++) {
1802 if (prepare_midx_pack(r, m, i))
1803 continue;
1804 if (!pack_kept_objects && m->packs[i]->pack_keep)
1805 continue;
1806
1807 include_pack[i] = 1;
1808 count++;
1809 }
1810
1811 return count < 2;
1812 }
1813
1814 static int fill_included_packs_batch(struct repository *r,
1815 struct multi_pack_index *m,
1816 unsigned char *include_pack,
1817 size_t batch_size)
1818 {
1819 uint32_t i, packs_to_repack;
1820 size_t total_size;
1821 struct repack_info *pack_info = xcalloc(m->num_packs, sizeof(struct repack_info));
1822 int pack_kept_objects = 0;
1823
1824 repo_config_get_bool(r, "repack.packkeptobjects", &pack_kept_objects);
1825
1826 for (i = 0; i < m->num_packs; i++) {
1827 pack_info[i].pack_int_id = i;
1828
1829 if (prepare_midx_pack(r, m, i))
1830 continue;
1831
1832 pack_info[i].mtime = m->packs[i]->mtime;
1833 }
1834
1835 for (i = 0; batch_size && i < m->num_objects; i++) {
1836 uint32_t pack_int_id = nth_midxed_pack_int_id(m, i);
1837 pack_info[pack_int_id].referenced_objects++;
1838 }
1839
1840 QSORT(pack_info, m->num_packs, compare_by_mtime);
1841
1842 total_size = 0;
1843 packs_to_repack = 0;
1844 for (i = 0; total_size < batch_size && i < m->num_packs; i++) {
1845 int pack_int_id = pack_info[i].pack_int_id;
1846 struct packed_git *p = m->packs[pack_int_id];
1847 size_t expected_size;
1848
1849 if (!p)
1850 continue;
1851 if (!pack_kept_objects && p->pack_keep)
1852 continue;
1853 if (open_pack_index(p) || !p->num_objects)
1854 continue;
1855
1856 expected_size = (size_t)(p->pack_size
1857 * pack_info[i].referenced_objects);
1858 expected_size /= p->num_objects;
1859
1860 if (expected_size >= batch_size)
1861 continue;
1862
1863 packs_to_repack++;
1864 total_size += expected_size;
1865 include_pack[pack_int_id] = 1;
1866 }
1867
1868 free(pack_info);
1869
1870 if (packs_to_repack < 2)
1871 return 1;
1872
1873 return 0;
1874 }
1875
1876 int midx_repack(struct repository *r, const char *object_dir, size_t batch_size, unsigned flags)
1877 {
1878 int result = 0;
1879 uint32_t i;
1880 unsigned char *include_pack;
1881 struct child_process cmd = CHILD_PROCESS_INIT;
1882 FILE *cmd_in;
1883 struct strbuf base_name = STRBUF_INIT;
1884 struct multi_pack_index *m = lookup_multi_pack_index(r, object_dir);
1885
1886 /*
1887 * When updating the default for these configuration
1888 * variables in builtin/repack.c, these must be adjusted
1889 * to match.
1890 */
1891 int delta_base_offset = 1;
1892 int use_delta_islands = 0;
1893
1894 if (!m)
1895 return 0;
1896
1897 CALLOC_ARRAY(include_pack, m->num_packs);
1898
1899 if (batch_size) {
1900 if (fill_included_packs_batch(r, m, include_pack, batch_size))
1901 goto cleanup;
1902 } else if (fill_included_packs_all(r, m, include_pack))
1903 goto cleanup;
1904
1905 repo_config_get_bool(r, "repack.usedeltabaseoffset", &delta_base_offset);
1906 repo_config_get_bool(r, "repack.usedeltaislands", &use_delta_islands);
1907
1908 strvec_push(&cmd.args, "pack-objects");
1909
1910 strbuf_addstr(&base_name, object_dir);
1911 strbuf_addstr(&base_name, "/pack/pack");
1912 strvec_push(&cmd.args, base_name.buf);
1913
1914 if (delta_base_offset)
1915 strvec_push(&cmd.args, "--delta-base-offset");
1916 if (use_delta_islands)
1917 strvec_push(&cmd.args, "--delta-islands");
1918
1919 if (flags & MIDX_PROGRESS)
1920 strvec_push(&cmd.args, "--progress");
1921 else
1922 strvec_push(&cmd.args, "-q");
1923
1924 strbuf_release(&base_name);
1925
1926 cmd.git_cmd = 1;
1927 cmd.in = cmd.out = -1;
1928
1929 if (start_command(&cmd)) {
1930 error(_("could not start pack-objects"));
1931 result = 1;
1932 goto cleanup;
1933 }
1934
1935 cmd_in = xfdopen(cmd.in, "w");
1936
1937 for (i = 0; i < m->num_objects; i++) {
1938 struct object_id oid;
1939 uint32_t pack_int_id = nth_midxed_pack_int_id(m, i);
1940
1941 if (!include_pack[pack_int_id])
1942 continue;
1943
1944 nth_midxed_object_oid(&oid, m, i);
1945 fprintf(cmd_in, "%s\n", oid_to_hex(&oid));
1946 }
1947 fclose(cmd_in);
1948
1949 if (finish_command(&cmd)) {
1950 error(_("could not finish pack-objects"));
1951 result = 1;
1952 goto cleanup;
1953 }
1954
1955 result = write_midx_internal(object_dir, NULL, NULL, NULL, NULL, flags);
1956
1957 cleanup:
1958 free(include_pack);
1959 return result;
1960 }