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