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