midx: clear midx on repack
[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 "sha1-lookup.h"
9 #include "midx.h"
10
11 #define MIDX_SIGNATURE 0x4d494458 /* "MIDX" */
12 #define MIDX_VERSION 1
13 #define MIDX_BYTE_FILE_VERSION 4
14 #define MIDX_BYTE_HASH_VERSION 5
15 #define MIDX_BYTE_NUM_CHUNKS 6
16 #define MIDX_BYTE_NUM_PACKS 8
17 #define MIDX_HASH_VERSION 1
18 #define MIDX_HEADER_SIZE 12
19 #define MIDX_HASH_LEN 20
20 #define MIDX_MIN_SIZE (MIDX_HEADER_SIZE + MIDX_HASH_LEN)
21
22 #define MIDX_MAX_CHUNKS 5
23 #define MIDX_CHUNK_ALIGNMENT 4
24 #define MIDX_CHUNKID_PACKNAMES 0x504e414d /* "PNAM" */
25 #define MIDX_CHUNKID_OIDFANOUT 0x4f494446 /* "OIDF" */
26 #define MIDX_CHUNKID_OIDLOOKUP 0x4f49444c /* "OIDL" */
27 #define MIDX_CHUNKID_OBJECTOFFSETS 0x4f4f4646 /* "OOFF" */
28 #define MIDX_CHUNKID_LARGEOFFSETS 0x4c4f4646 /* "LOFF" */
29 #define MIDX_CHUNKLOOKUP_WIDTH (sizeof(uint32_t) + sizeof(uint64_t))
30 #define MIDX_CHUNK_FANOUT_SIZE (sizeof(uint32_t) * 256)
31 #define MIDX_CHUNK_OFFSET_WIDTH (2 * sizeof(uint32_t))
32 #define MIDX_CHUNK_LARGE_OFFSET_WIDTH (sizeof(uint64_t))
33 #define MIDX_LARGE_OFFSET_NEEDED 0x80000000
34
35 static char *get_midx_filename(const char *object_dir)
36 {
37         return xstrfmt("%s/pack/multi-pack-index", object_dir);
38 }
39
40 struct multi_pack_index *load_multi_pack_index(const char *object_dir)
41 {
42         struct multi_pack_index *m = NULL;
43         int fd;
44         struct stat st;
45         size_t midx_size;
46         void *midx_map = NULL;
47         uint32_t hash_version;
48         char *midx_name = get_midx_filename(object_dir);
49         uint32_t i;
50         const char *cur_pack_name;
51
52         fd = git_open(midx_name);
53
54         if (fd < 0)
55                 goto cleanup_fail;
56         if (fstat(fd, &st)) {
57                 error_errno(_("failed to read %s"), midx_name);
58                 goto cleanup_fail;
59         }
60
61         midx_size = xsize_t(st.st_size);
62
63         if (midx_size < MIDX_MIN_SIZE) {
64                 error(_("multi-pack-index file %s is too small"), midx_name);
65                 goto cleanup_fail;
66         }
67
68         FREE_AND_NULL(midx_name);
69
70         midx_map = xmmap(NULL, midx_size, PROT_READ, MAP_PRIVATE, fd, 0);
71
72         FLEX_ALLOC_MEM(m, object_dir, object_dir, strlen(object_dir));
73         m->fd = fd;
74         m->data = midx_map;
75         m->data_len = midx_size;
76
77         m->signature = get_be32(m->data);
78         if (m->signature != MIDX_SIGNATURE) {
79                 error(_("multi-pack-index signature 0x%08x does not match signature 0x%08x"),
80                       m->signature, MIDX_SIGNATURE);
81                 goto cleanup_fail;
82         }
83
84         m->version = m->data[MIDX_BYTE_FILE_VERSION];
85         if (m->version != MIDX_VERSION) {
86                 error(_("multi-pack-index version %d not recognized"),
87                       m->version);
88                 goto cleanup_fail;
89         }
90
91         hash_version = m->data[MIDX_BYTE_HASH_VERSION];
92         if (hash_version != MIDX_HASH_VERSION) {
93                 error(_("hash version %u does not match"), hash_version);
94                 goto cleanup_fail;
95         }
96         m->hash_len = MIDX_HASH_LEN;
97
98         m->num_chunks = m->data[MIDX_BYTE_NUM_CHUNKS];
99
100         m->num_packs = get_be32(m->data + MIDX_BYTE_NUM_PACKS);
101
102         for (i = 0; i < m->num_chunks; i++) {
103                 uint32_t chunk_id = get_be32(m->data + MIDX_HEADER_SIZE +
104                                              MIDX_CHUNKLOOKUP_WIDTH * i);
105                 uint64_t chunk_offset = get_be64(m->data + MIDX_HEADER_SIZE + 4 +
106                                                  MIDX_CHUNKLOOKUP_WIDTH * i);
107
108                 switch (chunk_id) {
109                         case MIDX_CHUNKID_PACKNAMES:
110                                 m->chunk_pack_names = m->data + chunk_offset;
111                                 break;
112
113                         case MIDX_CHUNKID_OIDFANOUT:
114                                 m->chunk_oid_fanout = (uint32_t *)(m->data + chunk_offset);
115                                 break;
116
117                         case MIDX_CHUNKID_OIDLOOKUP:
118                                 m->chunk_oid_lookup = m->data + chunk_offset;
119                                 break;
120
121                         case MIDX_CHUNKID_OBJECTOFFSETS:
122                                 m->chunk_object_offsets = m->data + chunk_offset;
123                                 break;
124
125                         case MIDX_CHUNKID_LARGEOFFSETS:
126                                 m->chunk_large_offsets = m->data + chunk_offset;
127                                 break;
128
129                         case 0:
130                                 die(_("terminating multi-pack-index chunk id appears earlier than expected"));
131                                 break;
132
133                         default:
134                                 /*
135                                  * Do nothing on unrecognized chunks, allowing future
136                                  * extensions to add optional chunks.
137                                  */
138                                 break;
139                 }
140         }
141
142         if (!m->chunk_pack_names)
143                 die(_("multi-pack-index missing required pack-name chunk"));
144         if (!m->chunk_oid_fanout)
145                 die(_("multi-pack-index missing required OID fanout chunk"));
146         if (!m->chunk_oid_lookup)
147                 die(_("multi-pack-index missing required OID lookup chunk"));
148         if (!m->chunk_object_offsets)
149                 die(_("multi-pack-index missing required object offsets chunk"));
150
151         m->num_objects = ntohl(m->chunk_oid_fanout[255]);
152
153         m->pack_names = xcalloc(m->num_packs, sizeof(*m->pack_names));
154         m->packs = xcalloc(m->num_packs, sizeof(*m->packs));
155
156         cur_pack_name = (const char *)m->chunk_pack_names;
157         for (i = 0; i < m->num_packs; i++) {
158                 m->pack_names[i] = cur_pack_name;
159
160                 cur_pack_name += strlen(cur_pack_name) + 1;
161
162                 if (i && strcmp(m->pack_names[i], m->pack_names[i - 1]) <= 0) {
163                         error(_("multi-pack-index pack names out of order: '%s' before '%s'"),
164                               m->pack_names[i - 1],
165                               m->pack_names[i]);
166                         goto cleanup_fail;
167                 }
168         }
169
170         return m;
171
172 cleanup_fail:
173         free(m);
174         free(midx_name);
175         if (midx_map)
176                 munmap(midx_map, midx_size);
177         if (0 <= fd)
178                 close(fd);
179         return NULL;
180 }
181
182 static void close_midx(struct multi_pack_index *m)
183 {
184         uint32_t i;
185         munmap((unsigned char *)m->data, m->data_len);
186         close(m->fd);
187         m->fd = -1;
188
189         for (i = 0; i < m->num_packs; i++) {
190                 if (m->packs[i]) {
191                         close_pack(m->packs[i]);
192                         free(m->packs);
193                 }
194         }
195         FREE_AND_NULL(m->packs);
196         FREE_AND_NULL(m->pack_names);
197 }
198
199 static int prepare_midx_pack(struct multi_pack_index *m, uint32_t pack_int_id)
200 {
201         struct strbuf pack_name = STRBUF_INIT;
202
203         if (pack_int_id >= m->num_packs)
204                 BUG("bad pack-int-id");
205
206         if (m->packs[pack_int_id])
207                 return 0;
208
209         strbuf_addf(&pack_name, "%s/pack/%s", m->object_dir,
210                     m->pack_names[pack_int_id]);
211
212         m->packs[pack_int_id] = add_packed_git(pack_name.buf, pack_name.len, 1);
213         strbuf_release(&pack_name);
214         return !m->packs[pack_int_id];
215 }
216
217 int bsearch_midx(const struct object_id *oid, struct multi_pack_index *m, uint32_t *result)
218 {
219         return bsearch_hash(oid->hash, m->chunk_oid_fanout, m->chunk_oid_lookup,
220                             MIDX_HASH_LEN, result);
221 }
222
223 struct object_id *nth_midxed_object_oid(struct object_id *oid,
224                                         struct multi_pack_index *m,
225                                         uint32_t n)
226 {
227         if (n >= m->num_objects)
228                 return NULL;
229
230         hashcpy(oid->hash, m->chunk_oid_lookup + m->hash_len * n);
231         return oid;
232 }
233
234 static off_t nth_midxed_offset(struct multi_pack_index *m, uint32_t pos)
235 {
236         const unsigned char *offset_data;
237         uint32_t offset32;
238
239         offset_data = m->chunk_object_offsets + pos * MIDX_CHUNK_OFFSET_WIDTH;
240         offset32 = get_be32(offset_data + sizeof(uint32_t));
241
242         if (m->chunk_large_offsets && offset32 & MIDX_LARGE_OFFSET_NEEDED) {
243                 if (sizeof(offset32) < sizeof(uint64_t))
244                         die(_("multi-pack-index stores a 64-bit offset, but off_t is too small"));
245
246                 offset32 ^= MIDX_LARGE_OFFSET_NEEDED;
247                 return get_be64(m->chunk_large_offsets + sizeof(uint64_t) * offset32);
248         }
249
250         return offset32;
251 }
252
253 static uint32_t nth_midxed_pack_int_id(struct multi_pack_index *m, uint32_t pos)
254 {
255         return get_be32(m->chunk_object_offsets + pos * MIDX_CHUNK_OFFSET_WIDTH);
256 }
257
258 static int nth_midxed_pack_entry(struct multi_pack_index *m, struct pack_entry *e, uint32_t pos)
259 {
260         uint32_t pack_int_id;
261         struct packed_git *p;
262
263         if (pos >= m->num_objects)
264                 return 0;
265
266         pack_int_id = nth_midxed_pack_int_id(m, pos);
267
268         if (prepare_midx_pack(m, pack_int_id))
269                 die(_("error preparing packfile from multi-pack-index"));
270         p = m->packs[pack_int_id];
271
272         /*
273         * We are about to tell the caller where they can locate the
274         * requested object.  We better make sure the packfile is
275         * still here and can be accessed before supplying that
276         * answer, as it may have been deleted since the MIDX was
277         * loaded!
278         */
279         if (!is_pack_valid(p))
280                 return 0;
281
282         e->offset = nth_midxed_offset(m, pos);
283         e->p = p;
284
285         return 1;
286 }
287
288 int fill_midx_entry(const struct object_id *oid, struct pack_entry *e, struct multi_pack_index *m)
289 {
290         uint32_t pos;
291
292         if (!bsearch_midx(oid, m, &pos))
293                 return 0;
294
295         return nth_midxed_pack_entry(m, e, pos);
296 }
297
298 int midx_contains_pack(struct multi_pack_index *m, const char *idx_name)
299 {
300         uint32_t first = 0, last = m->num_packs;
301
302         while (first < last) {
303                 uint32_t mid = first + (last - first) / 2;
304                 const char *current;
305                 int cmp;
306
307                 current = m->pack_names[mid];
308                 cmp = strcmp(idx_name, current);
309                 if (!cmp)
310                         return 1;
311                 if (cmp > 0) {
312                         first = mid + 1;
313                         continue;
314                 }
315                 last = mid;
316         }
317
318         return 0;
319 }
320
321 int prepare_multi_pack_index_one(struct repository *r, const char *object_dir)
322 {
323         struct multi_pack_index *m = r->objects->multi_pack_index;
324         struct multi_pack_index *m_search;
325         int config_value;
326
327         if (repo_config_get_bool(r, "core.multipackindex", &config_value) ||
328             !config_value)
329                 return 0;
330
331         for (m_search = m; m_search; m_search = m_search->next)
332                 if (!strcmp(object_dir, m_search->object_dir))
333                         return 1;
334
335         r->objects->multi_pack_index = load_multi_pack_index(object_dir);
336
337         if (r->objects->multi_pack_index) {
338                 r->objects->multi_pack_index->next = m;
339                 return 1;
340         }
341
342         return 0;
343 }
344
345 static size_t write_midx_header(struct hashfile *f,
346                                 unsigned char num_chunks,
347                                 uint32_t num_packs)
348 {
349         unsigned char byte_values[4];
350
351         hashwrite_be32(f, MIDX_SIGNATURE);
352         byte_values[0] = MIDX_VERSION;
353         byte_values[1] = MIDX_HASH_VERSION;
354         byte_values[2] = num_chunks;
355         byte_values[3] = 0; /* unused */
356         hashwrite(f, byte_values, sizeof(byte_values));
357         hashwrite_be32(f, num_packs);
358
359         return MIDX_HEADER_SIZE;
360 }
361
362 struct pack_list {
363         struct packed_git **list;
364         char **names;
365         uint32_t nr;
366         uint32_t alloc_list;
367         uint32_t alloc_names;
368         size_t pack_name_concat_len;
369         struct multi_pack_index *m;
370 };
371
372 static void add_pack_to_midx(const char *full_path, size_t full_path_len,
373                              const char *file_name, void *data)
374 {
375         struct pack_list *packs = (struct pack_list *)data;
376
377         if (ends_with(file_name, ".idx")) {
378                 if (packs->m && midx_contains_pack(packs->m, file_name))
379                         return;
380
381                 ALLOC_GROW(packs->list, packs->nr + 1, packs->alloc_list);
382                 ALLOC_GROW(packs->names, packs->nr + 1, packs->alloc_names);
383
384                 packs->list[packs->nr] = add_packed_git(full_path,
385                                                         full_path_len,
386                                                         0);
387
388                 if (!packs->list[packs->nr]) {
389                         warning(_("failed to add packfile '%s'"),
390                                 full_path);
391                         return;
392                 }
393
394                 if (open_pack_index(packs->list[packs->nr])) {
395                         warning(_("failed to open pack-index '%s'"),
396                                 full_path);
397                         close_pack(packs->list[packs->nr]);
398                         FREE_AND_NULL(packs->list[packs->nr]);
399                         return;
400                 }
401
402                 packs->names[packs->nr] = xstrdup(file_name);
403                 packs->pack_name_concat_len += strlen(file_name) + 1;
404                 packs->nr++;
405         }
406 }
407
408 struct pack_pair {
409         uint32_t pack_int_id;
410         char *pack_name;
411 };
412
413 static int pack_pair_compare(const void *_a, const void *_b)
414 {
415         struct pack_pair *a = (struct pack_pair *)_a;
416         struct pack_pair *b = (struct pack_pair *)_b;
417         return strcmp(a->pack_name, b->pack_name);
418 }
419
420 static void sort_packs_by_name(char **pack_names, uint32_t nr_packs, uint32_t *perm)
421 {
422         uint32_t i;
423         struct pack_pair *pairs;
424
425         ALLOC_ARRAY(pairs, nr_packs);
426
427         for (i = 0; i < nr_packs; i++) {
428                 pairs[i].pack_int_id = i;
429                 pairs[i].pack_name = pack_names[i];
430         }
431
432         QSORT(pairs, nr_packs, pack_pair_compare);
433
434         for (i = 0; i < nr_packs; i++) {
435                 pack_names[i] = pairs[i].pack_name;
436                 perm[pairs[i].pack_int_id] = i;
437         }
438
439         free(pairs);
440 }
441
442 struct pack_midx_entry {
443         struct object_id oid;
444         uint32_t pack_int_id;
445         time_t pack_mtime;
446         uint64_t offset;
447 };
448
449 static int midx_oid_compare(const void *_a, const void *_b)
450 {
451         const struct pack_midx_entry *a = (const struct pack_midx_entry *)_a;
452         const struct pack_midx_entry *b = (const struct pack_midx_entry *)_b;
453         int cmp = oidcmp(&a->oid, &b->oid);
454
455         if (cmp)
456                 return cmp;
457
458         if (a->pack_mtime > b->pack_mtime)
459                 return -1;
460         else if (a->pack_mtime < b->pack_mtime)
461                 return 1;
462
463         return a->pack_int_id - b->pack_int_id;
464 }
465
466 static int nth_midxed_pack_midx_entry(struct multi_pack_index *m,
467                                       uint32_t *pack_perm,
468                                       struct pack_midx_entry *e,
469                                       uint32_t pos)
470 {
471         if (pos >= m->num_objects)
472                 return 1;
473
474         nth_midxed_object_oid(&e->oid, m, pos);
475         e->pack_int_id = pack_perm[nth_midxed_pack_int_id(m, pos)];
476         e->offset = nth_midxed_offset(m, pos);
477
478         /* consider objects in midx to be from "old" packs */
479         e->pack_mtime = 0;
480         return 0;
481 }
482
483 static void fill_pack_entry(uint32_t pack_int_id,
484                             struct packed_git *p,
485                             uint32_t cur_object,
486                             struct pack_midx_entry *entry)
487 {
488         if (!nth_packed_object_oid(&entry->oid, p, cur_object))
489                 die(_("failed to locate object %d in packfile"), cur_object);
490
491         entry->pack_int_id = pack_int_id;
492         entry->pack_mtime = p->mtime;
493
494         entry->offset = nth_packed_object_offset(p, cur_object);
495 }
496
497 /*
498  * It is possible to artificially get into a state where there are many
499  * duplicate copies of objects. That can create high memory pressure if
500  * we are to create a list of all objects before de-duplication. To reduce
501  * this memory pressure without a significant performance drop, automatically
502  * group objects by the first byte of their object id. Use the IDX fanout
503  * tables to group the data, copy to a local array, then sort.
504  *
505  * Copy only the de-duplicated entries (selected by most-recent modified time
506  * of a packfile containing the object).
507  */
508 static struct pack_midx_entry *get_sorted_entries(struct multi_pack_index *m,
509                                                   struct packed_git **p,
510                                                   uint32_t *perm,
511                                                   uint32_t nr_packs,
512                                                   uint32_t *nr_objects)
513 {
514         uint32_t cur_fanout, cur_pack, cur_object;
515         uint32_t alloc_fanout, alloc_objects, total_objects = 0;
516         struct pack_midx_entry *entries_by_fanout = NULL;
517         struct pack_midx_entry *deduplicated_entries = NULL;
518         uint32_t start_pack = m ? m->num_packs : 0;
519
520         for (cur_pack = start_pack; cur_pack < nr_packs; cur_pack++)
521                 total_objects += p[cur_pack]->num_objects;
522
523         /*
524          * As we de-duplicate by fanout value, we expect the fanout
525          * slices to be evenly distributed, with some noise. Hence,
526          * allocate slightly more than one 256th.
527          */
528         alloc_objects = alloc_fanout = total_objects > 3200 ? total_objects / 200 : 16;
529
530         ALLOC_ARRAY(entries_by_fanout, alloc_fanout);
531         ALLOC_ARRAY(deduplicated_entries, alloc_objects);
532         *nr_objects = 0;
533
534         for (cur_fanout = 0; cur_fanout < 256; cur_fanout++) {
535                 uint32_t nr_fanout = 0;
536
537                 if (m) {
538                         uint32_t start = 0, end;
539
540                         if (cur_fanout)
541                                 start = ntohl(m->chunk_oid_fanout[cur_fanout - 1]);
542                         end = ntohl(m->chunk_oid_fanout[cur_fanout]);
543
544                         for (cur_object = start; cur_object < end; cur_object++) {
545                                 ALLOC_GROW(entries_by_fanout, nr_fanout + 1, alloc_fanout);
546                                 nth_midxed_pack_midx_entry(m, perm,
547                                                            &entries_by_fanout[nr_fanout],
548                                                            cur_object);
549                                 nr_fanout++;
550                         }
551                 }
552
553                 for (cur_pack = start_pack; cur_pack < nr_packs; cur_pack++) {
554                         uint32_t start = 0, end;
555
556                         if (cur_fanout)
557                                 start = get_pack_fanout(p[cur_pack], cur_fanout - 1);
558                         end = get_pack_fanout(p[cur_pack], cur_fanout);
559
560                         for (cur_object = start; cur_object < end; cur_object++) {
561                                 ALLOC_GROW(entries_by_fanout, nr_fanout + 1, alloc_fanout);
562                                 fill_pack_entry(perm[cur_pack], p[cur_pack], cur_object, &entries_by_fanout[nr_fanout]);
563                                 nr_fanout++;
564                         }
565                 }
566
567                 QSORT(entries_by_fanout, nr_fanout, midx_oid_compare);
568
569                 /*
570                  * The batch is now sorted by OID and then mtime (descending).
571                  * Take only the first duplicate.
572                  */
573                 for (cur_object = 0; cur_object < nr_fanout; cur_object++) {
574                         if (cur_object && !oidcmp(&entries_by_fanout[cur_object - 1].oid,
575                                                   &entries_by_fanout[cur_object].oid))
576                                 continue;
577
578                         ALLOC_GROW(deduplicated_entries, *nr_objects + 1, alloc_objects);
579                         memcpy(&deduplicated_entries[*nr_objects],
580                                &entries_by_fanout[cur_object],
581                                sizeof(struct pack_midx_entry));
582                         (*nr_objects)++;
583                 }
584         }
585
586         free(entries_by_fanout);
587         return deduplicated_entries;
588 }
589
590 static size_t write_midx_pack_names(struct hashfile *f,
591                                     char **pack_names,
592                                     uint32_t num_packs)
593 {
594         uint32_t i;
595         unsigned char padding[MIDX_CHUNK_ALIGNMENT];
596         size_t written = 0;
597
598         for (i = 0; i < num_packs; i++) {
599                 size_t writelen = strlen(pack_names[i]) + 1;
600
601                 if (i && strcmp(pack_names[i], pack_names[i - 1]) <= 0)
602                         BUG("incorrect pack-file order: %s before %s",
603                             pack_names[i - 1],
604                             pack_names[i]);
605
606                 hashwrite(f, pack_names[i], writelen);
607                 written += writelen;
608         }
609
610         /* add padding to be aligned */
611         i = MIDX_CHUNK_ALIGNMENT - (written % MIDX_CHUNK_ALIGNMENT);
612         if (i < MIDX_CHUNK_ALIGNMENT) {
613                 memset(padding, 0, sizeof(padding));
614                 hashwrite(f, padding, i);
615                 written += i;
616         }
617
618         return written;
619 }
620
621 static size_t write_midx_oid_fanout(struct hashfile *f,
622                                     struct pack_midx_entry *objects,
623                                     uint32_t nr_objects)
624 {
625         struct pack_midx_entry *list = objects;
626         struct pack_midx_entry *last = objects + nr_objects;
627         uint32_t count = 0;
628         uint32_t i;
629
630         /*
631         * Write the first-level table (the list is sorted,
632         * but we use a 256-entry lookup to be able to avoid
633         * having to do eight extra binary search iterations).
634         */
635         for (i = 0; i < 256; i++) {
636                 struct pack_midx_entry *next = list;
637
638                 while (next < last && next->oid.hash[0] == i) {
639                         count++;
640                         next++;
641                 }
642
643                 hashwrite_be32(f, count);
644                 list = next;
645         }
646
647         return MIDX_CHUNK_FANOUT_SIZE;
648 }
649
650 static size_t write_midx_oid_lookup(struct hashfile *f, unsigned char hash_len,
651                                     struct pack_midx_entry *objects,
652                                     uint32_t nr_objects)
653 {
654         struct pack_midx_entry *list = objects;
655         uint32_t i;
656         size_t written = 0;
657
658         for (i = 0; i < nr_objects; i++) {
659                 struct pack_midx_entry *obj = list++;
660
661                 if (i < nr_objects - 1) {
662                         struct pack_midx_entry *next = list;
663                         if (oidcmp(&obj->oid, &next->oid) >= 0)
664                                 BUG("OIDs not in order: %s >= %s",
665                                     oid_to_hex(&obj->oid),
666                                     oid_to_hex(&next->oid));
667                 }
668
669                 hashwrite(f, obj->oid.hash, (int)hash_len);
670                 written += hash_len;
671         }
672
673         return written;
674 }
675
676 static size_t write_midx_object_offsets(struct hashfile *f, int large_offset_needed,
677                                         struct pack_midx_entry *objects, uint32_t nr_objects)
678 {
679         struct pack_midx_entry *list = objects;
680         uint32_t i, nr_large_offset = 0;
681         size_t written = 0;
682
683         for (i = 0; i < nr_objects; i++) {
684                 struct pack_midx_entry *obj = list++;
685
686                 hashwrite_be32(f, obj->pack_int_id);
687
688                 if (large_offset_needed && obj->offset >> 31)
689                         hashwrite_be32(f, MIDX_LARGE_OFFSET_NEEDED | nr_large_offset++);
690                 else if (!large_offset_needed && obj->offset >> 32)
691                         BUG("object %s requires a large offset (%"PRIx64") but the MIDX is not writing large offsets!",
692                             oid_to_hex(&obj->oid),
693                             obj->offset);
694                 else
695                         hashwrite_be32(f, (uint32_t)obj->offset);
696
697                 written += MIDX_CHUNK_OFFSET_WIDTH;
698         }
699
700         return written;
701 }
702
703 static size_t write_midx_large_offsets(struct hashfile *f, uint32_t nr_large_offset,
704                                        struct pack_midx_entry *objects, uint32_t nr_objects)
705 {
706         struct pack_midx_entry *list = objects;
707         size_t written = 0;
708
709         while (nr_large_offset) {
710                 struct pack_midx_entry *obj = list++;
711                 uint64_t offset = obj->offset;
712
713                 if (!(offset >> 31))
714                         continue;
715
716                 hashwrite_be32(f, offset >> 32);
717                 hashwrite_be32(f, offset & 0xffffffffUL);
718                 written += 2 * sizeof(uint32_t);
719
720                 nr_large_offset--;
721         }
722
723         return written;
724 }
725
726 int write_midx_file(const char *object_dir)
727 {
728         unsigned char cur_chunk, num_chunks = 0;
729         char *midx_name;
730         uint32_t i;
731         struct hashfile *f = NULL;
732         struct lock_file lk;
733         struct pack_list packs;
734         uint32_t *pack_perm = NULL;
735         uint64_t written = 0;
736         uint32_t chunk_ids[MIDX_MAX_CHUNKS + 1];
737         uint64_t chunk_offsets[MIDX_MAX_CHUNKS + 1];
738         uint32_t nr_entries, num_large_offsets = 0;
739         struct pack_midx_entry *entries = NULL;
740         int large_offsets_needed = 0;
741
742         midx_name = get_midx_filename(object_dir);
743         if (safe_create_leading_directories(midx_name)) {
744                 UNLEAK(midx_name);
745                 die_errno(_("unable to create leading directories of %s"),
746                           midx_name);
747         }
748
749         packs.m = load_multi_pack_index(object_dir);
750
751         packs.nr = 0;
752         packs.alloc_list = packs.m ? packs.m->num_packs : 16;
753         packs.alloc_names = packs.alloc_list;
754         packs.list = NULL;
755         packs.names = NULL;
756         packs.pack_name_concat_len = 0;
757         ALLOC_ARRAY(packs.list, packs.alloc_list);
758         ALLOC_ARRAY(packs.names, packs.alloc_names);
759
760         if (packs.m) {
761                 for (i = 0; i < packs.m->num_packs; i++) {
762                         ALLOC_GROW(packs.list, packs.nr + 1, packs.alloc_list);
763                         ALLOC_GROW(packs.names, packs.nr + 1, packs.alloc_names);
764
765                         packs.list[packs.nr] = NULL;
766                         packs.names[packs.nr] = xstrdup(packs.m->pack_names[i]);
767                         packs.pack_name_concat_len += strlen(packs.names[packs.nr]) + 1;
768                         packs.nr++;
769                 }
770         }
771
772         for_each_file_in_pack_dir(object_dir, add_pack_to_midx, &packs);
773
774         if (packs.m && packs.nr == packs.m->num_packs)
775                 goto cleanup;
776
777         if (packs.pack_name_concat_len % MIDX_CHUNK_ALIGNMENT)
778                 packs.pack_name_concat_len += MIDX_CHUNK_ALIGNMENT -
779                                               (packs.pack_name_concat_len % MIDX_CHUNK_ALIGNMENT);
780
781         ALLOC_ARRAY(pack_perm, packs.nr);
782         sort_packs_by_name(packs.names, packs.nr, pack_perm);
783
784         entries = get_sorted_entries(packs.m, packs.list, pack_perm, packs.nr, &nr_entries);
785
786         for (i = 0; i < nr_entries; i++) {
787                 if (entries[i].offset > 0x7fffffff)
788                         num_large_offsets++;
789                 if (entries[i].offset > 0xffffffff)
790                         large_offsets_needed = 1;
791         }
792
793         hold_lock_file_for_update(&lk, midx_name, LOCK_DIE_ON_ERROR);
794         f = hashfd(lk.tempfile->fd, lk.tempfile->filename.buf);
795         FREE_AND_NULL(midx_name);
796
797         if (packs.m)
798                 close_midx(packs.m);
799
800         cur_chunk = 0;
801         num_chunks = large_offsets_needed ? 5 : 4;
802
803         written = write_midx_header(f, num_chunks, packs.nr);
804
805         chunk_ids[cur_chunk] = MIDX_CHUNKID_PACKNAMES;
806         chunk_offsets[cur_chunk] = written + (num_chunks + 1) * MIDX_CHUNKLOOKUP_WIDTH;
807
808         cur_chunk++;
809         chunk_ids[cur_chunk] = MIDX_CHUNKID_OIDFANOUT;
810         chunk_offsets[cur_chunk] = chunk_offsets[cur_chunk - 1] + packs.pack_name_concat_len;
811
812         cur_chunk++;
813         chunk_ids[cur_chunk] = MIDX_CHUNKID_OIDLOOKUP;
814         chunk_offsets[cur_chunk] = chunk_offsets[cur_chunk - 1] + MIDX_CHUNK_FANOUT_SIZE;
815
816         cur_chunk++;
817         chunk_ids[cur_chunk] = MIDX_CHUNKID_OBJECTOFFSETS;
818         chunk_offsets[cur_chunk] = chunk_offsets[cur_chunk - 1] + nr_entries * MIDX_HASH_LEN;
819
820         cur_chunk++;
821         chunk_offsets[cur_chunk] = chunk_offsets[cur_chunk - 1] + nr_entries * MIDX_CHUNK_OFFSET_WIDTH;
822         if (large_offsets_needed) {
823                 chunk_ids[cur_chunk] = MIDX_CHUNKID_LARGEOFFSETS;
824
825                 cur_chunk++;
826                 chunk_offsets[cur_chunk] = chunk_offsets[cur_chunk - 1] +
827                                            num_large_offsets * MIDX_CHUNK_LARGE_OFFSET_WIDTH;
828         }
829
830         chunk_ids[cur_chunk] = 0;
831
832         for (i = 0; i <= num_chunks; i++) {
833                 if (i && chunk_offsets[i] < chunk_offsets[i - 1])
834                         BUG("incorrect chunk offsets: %"PRIu64" before %"PRIu64,
835                             chunk_offsets[i - 1],
836                             chunk_offsets[i]);
837
838                 if (chunk_offsets[i] % MIDX_CHUNK_ALIGNMENT)
839                         BUG("chunk offset %"PRIu64" is not properly aligned",
840                             chunk_offsets[i]);
841
842                 hashwrite_be32(f, chunk_ids[i]);
843                 hashwrite_be32(f, chunk_offsets[i] >> 32);
844                 hashwrite_be32(f, chunk_offsets[i]);
845
846                 written += MIDX_CHUNKLOOKUP_WIDTH;
847         }
848
849         for (i = 0; i < num_chunks; i++) {
850                 if (written != chunk_offsets[i])
851                         BUG("incorrect chunk offset (%"PRIu64" != %"PRIu64") for chunk id %"PRIx32,
852                             chunk_offsets[i],
853                             written,
854                             chunk_ids[i]);
855
856                 switch (chunk_ids[i]) {
857                         case MIDX_CHUNKID_PACKNAMES:
858                                 written += write_midx_pack_names(f, packs.names, packs.nr);
859                                 break;
860
861                         case MIDX_CHUNKID_OIDFANOUT:
862                                 written += write_midx_oid_fanout(f, entries, nr_entries);
863                                 break;
864
865                         case MIDX_CHUNKID_OIDLOOKUP:
866                                 written += write_midx_oid_lookup(f, MIDX_HASH_LEN, entries, nr_entries);
867                                 break;
868
869                         case MIDX_CHUNKID_OBJECTOFFSETS:
870                                 written += write_midx_object_offsets(f, large_offsets_needed, entries, nr_entries);
871                                 break;
872
873                         case MIDX_CHUNKID_LARGEOFFSETS:
874                                 written += write_midx_large_offsets(f, num_large_offsets, entries, nr_entries);
875                                 break;
876
877                         default:
878                                 BUG("trying to write unknown chunk id %"PRIx32,
879                                     chunk_ids[i]);
880                 }
881         }
882
883         if (written != chunk_offsets[num_chunks])
884                 BUG("incorrect final offset %"PRIu64" != %"PRIu64,
885                     written,
886                     chunk_offsets[num_chunks]);
887
888         finalize_hashfile(f, NULL, CSUM_FSYNC | CSUM_HASH_IN_STREAM);
889         commit_lock_file(&lk);
890
891 cleanup:
892         for (i = 0; i < packs.nr; i++) {
893                 if (packs.list[i]) {
894                         close_pack(packs.list[i]);
895                         free(packs.list[i]);
896                 }
897                 free(packs.names[i]);
898         }
899
900         free(packs.list);
901         free(packs.names);
902         free(entries);
903         free(pack_perm);
904         free(midx_name);
905         return 0;
906 }
907
908 void clear_midx_file(const char *object_dir)
909 {
910         char *midx = get_midx_filename(object_dir);
911
912         if (remove_path(midx)) {
913                 UNLEAK(midx);
914                 die(_("failed to clear multi-pack-index at %s"), midx);
915         }
916
917         free(midx);
918 }