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