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