Merge branch 'nd/command-list-gen-fix'
[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 int midx_contains_pack(struct multi_pack_index *m, const char *idx_name)
311 {
312         uint32_t first = 0, last = m->num_packs;
313
314         while (first < last) {
315                 uint32_t mid = first + (last - first) / 2;
316                 const char *current;
317                 int cmp;
318
319                 current = m->pack_names[mid];
320                 cmp = strcmp(idx_name, current);
321                 if (!cmp)
322                         return 1;
323                 if (cmp > 0) {
324                         first = mid + 1;
325                         continue;
326                 }
327                 last = mid;
328         }
329
330         return 0;
331 }
332
333 int prepare_multi_pack_index_one(struct repository *r, const char *object_dir, int local)
334 {
335         struct multi_pack_index *m;
336         struct multi_pack_index *m_search;
337         int config_value;
338         static int env_value = -1;
339
340         if (env_value < 0)
341                 env_value = git_env_bool(GIT_TEST_MULTI_PACK_INDEX, 0);
342
343         if (!env_value &&
344             (repo_config_get_bool(r, "core.multipackindex", &config_value) ||
345             !config_value))
346                 return 0;
347
348         for (m_search = r->objects->multi_pack_index; m_search; m_search = m_search->next)
349                 if (!strcmp(object_dir, m_search->object_dir))
350                         return 1;
351
352         m = load_multi_pack_index(object_dir, local);
353
354         if (m) {
355                 m->next = r->objects->multi_pack_index;
356                 r->objects->multi_pack_index = m;
357                 return 1;
358         }
359
360         return 0;
361 }
362
363 static size_t write_midx_header(struct hashfile *f,
364                                 unsigned char num_chunks,
365                                 uint32_t num_packs)
366 {
367         unsigned char byte_values[4];
368
369         hashwrite_be32(f, MIDX_SIGNATURE);
370         byte_values[0] = MIDX_VERSION;
371         byte_values[1] = MIDX_HASH_VERSION;
372         byte_values[2] = num_chunks;
373         byte_values[3] = 0; /* unused */
374         hashwrite(f, byte_values, sizeof(byte_values));
375         hashwrite_be32(f, num_packs);
376
377         return MIDX_HEADER_SIZE;
378 }
379
380 struct pack_list {
381         struct packed_git **list;
382         char **names;
383         uint32_t nr;
384         uint32_t alloc_list;
385         uint32_t alloc_names;
386         size_t pack_name_concat_len;
387         struct multi_pack_index *m;
388 };
389
390 static void add_pack_to_midx(const char *full_path, size_t full_path_len,
391                              const char *file_name, void *data)
392 {
393         struct pack_list *packs = (struct pack_list *)data;
394
395         if (ends_with(file_name, ".idx")) {
396                 if (packs->m && midx_contains_pack(packs->m, file_name))
397                         return;
398
399                 ALLOC_GROW(packs->list, packs->nr + 1, packs->alloc_list);
400                 ALLOC_GROW(packs->names, packs->nr + 1, packs->alloc_names);
401
402                 packs->list[packs->nr] = add_packed_git(full_path,
403                                                         full_path_len,
404                                                         0);
405
406                 if (!packs->list[packs->nr]) {
407                         warning(_("failed to add packfile '%s'"),
408                                 full_path);
409                         return;
410                 }
411
412                 if (open_pack_index(packs->list[packs->nr])) {
413                         warning(_("failed to open pack-index '%s'"),
414                                 full_path);
415                         close_pack(packs->list[packs->nr]);
416                         FREE_AND_NULL(packs->list[packs->nr]);
417                         return;
418                 }
419
420                 packs->names[packs->nr] = xstrdup(file_name);
421                 packs->pack_name_concat_len += strlen(file_name) + 1;
422                 packs->nr++;
423         }
424 }
425
426 struct pack_pair {
427         uint32_t pack_int_id;
428         char *pack_name;
429 };
430
431 static int pack_pair_compare(const void *_a, const void *_b)
432 {
433         struct pack_pair *a = (struct pack_pair *)_a;
434         struct pack_pair *b = (struct pack_pair *)_b;
435         return strcmp(a->pack_name, b->pack_name);
436 }
437
438 static void sort_packs_by_name(char **pack_names, uint32_t nr_packs, uint32_t *perm)
439 {
440         uint32_t i;
441         struct pack_pair *pairs;
442
443         ALLOC_ARRAY(pairs, nr_packs);
444
445         for (i = 0; i < nr_packs; i++) {
446                 pairs[i].pack_int_id = i;
447                 pairs[i].pack_name = pack_names[i];
448         }
449
450         QSORT(pairs, nr_packs, pack_pair_compare);
451
452         for (i = 0; i < nr_packs; i++) {
453                 pack_names[i] = pairs[i].pack_name;
454                 perm[pairs[i].pack_int_id] = i;
455         }
456
457         free(pairs);
458 }
459
460 struct pack_midx_entry {
461         struct object_id oid;
462         uint32_t pack_int_id;
463         time_t pack_mtime;
464         uint64_t offset;
465 };
466
467 static int midx_oid_compare(const void *_a, const void *_b)
468 {
469         const struct pack_midx_entry *a = (const struct pack_midx_entry *)_a;
470         const struct pack_midx_entry *b = (const struct pack_midx_entry *)_b;
471         int cmp = oidcmp(&a->oid, &b->oid);
472
473         if (cmp)
474                 return cmp;
475
476         if (a->pack_mtime > b->pack_mtime)
477                 return -1;
478         else if (a->pack_mtime < b->pack_mtime)
479                 return 1;
480
481         return a->pack_int_id - b->pack_int_id;
482 }
483
484 static int nth_midxed_pack_midx_entry(struct multi_pack_index *m,
485                                       uint32_t *pack_perm,
486                                       struct pack_midx_entry *e,
487                                       uint32_t pos)
488 {
489         if (pos >= m->num_objects)
490                 return 1;
491
492         nth_midxed_object_oid(&e->oid, m, pos);
493         e->pack_int_id = pack_perm[nth_midxed_pack_int_id(m, pos)];
494         e->offset = nth_midxed_offset(m, pos);
495
496         /* consider objects in midx to be from "old" packs */
497         e->pack_mtime = 0;
498         return 0;
499 }
500
501 static void fill_pack_entry(uint32_t pack_int_id,
502                             struct packed_git *p,
503                             uint32_t cur_object,
504                             struct pack_midx_entry *entry)
505 {
506         if (!nth_packed_object_oid(&entry->oid, p, cur_object))
507                 die(_("failed to locate object %d in packfile"), cur_object);
508
509         entry->pack_int_id = pack_int_id;
510         entry->pack_mtime = p->mtime;
511
512         entry->offset = nth_packed_object_offset(p, cur_object);
513 }
514
515 /*
516  * It is possible to artificially get into a state where there are many
517  * duplicate copies of objects. That can create high memory pressure if
518  * we are to create a list of all objects before de-duplication. To reduce
519  * this memory pressure without a significant performance drop, automatically
520  * group objects by the first byte of their object id. Use the IDX fanout
521  * tables to group the data, copy to a local array, then sort.
522  *
523  * Copy only the de-duplicated entries (selected by most-recent modified time
524  * of a packfile containing the object).
525  */
526 static struct pack_midx_entry *get_sorted_entries(struct multi_pack_index *m,
527                                                   struct packed_git **p,
528                                                   uint32_t *perm,
529                                                   uint32_t nr_packs,
530                                                   uint32_t *nr_objects)
531 {
532         uint32_t cur_fanout, cur_pack, cur_object;
533         uint32_t alloc_fanout, alloc_objects, total_objects = 0;
534         struct pack_midx_entry *entries_by_fanout = NULL;
535         struct pack_midx_entry *deduplicated_entries = NULL;
536         uint32_t start_pack = m ? m->num_packs : 0;
537
538         for (cur_pack = start_pack; cur_pack < nr_packs; cur_pack++)
539                 total_objects += p[cur_pack]->num_objects;
540
541         /*
542          * As we de-duplicate by fanout value, we expect the fanout
543          * slices to be evenly distributed, with some noise. Hence,
544          * allocate slightly more than one 256th.
545          */
546         alloc_objects = alloc_fanout = total_objects > 3200 ? total_objects / 200 : 16;
547
548         ALLOC_ARRAY(entries_by_fanout, alloc_fanout);
549         ALLOC_ARRAY(deduplicated_entries, alloc_objects);
550         *nr_objects = 0;
551
552         for (cur_fanout = 0; cur_fanout < 256; cur_fanout++) {
553                 uint32_t nr_fanout = 0;
554
555                 if (m) {
556                         uint32_t start = 0, end;
557
558                         if (cur_fanout)
559                                 start = ntohl(m->chunk_oid_fanout[cur_fanout - 1]);
560                         end = ntohl(m->chunk_oid_fanout[cur_fanout]);
561
562                         for (cur_object = start; cur_object < end; cur_object++) {
563                                 ALLOC_GROW(entries_by_fanout, nr_fanout + 1, alloc_fanout);
564                                 nth_midxed_pack_midx_entry(m, perm,
565                                                            &entries_by_fanout[nr_fanout],
566                                                            cur_object);
567                                 nr_fanout++;
568                         }
569                 }
570
571                 for (cur_pack = start_pack; cur_pack < nr_packs; cur_pack++) {
572                         uint32_t start = 0, end;
573
574                         if (cur_fanout)
575                                 start = get_pack_fanout(p[cur_pack], cur_fanout - 1);
576                         end = get_pack_fanout(p[cur_pack], cur_fanout);
577
578                         for (cur_object = start; cur_object < end; cur_object++) {
579                                 ALLOC_GROW(entries_by_fanout, nr_fanout + 1, alloc_fanout);
580                                 fill_pack_entry(perm[cur_pack], p[cur_pack], cur_object, &entries_by_fanout[nr_fanout]);
581                                 nr_fanout++;
582                         }
583                 }
584
585                 QSORT(entries_by_fanout, nr_fanout, midx_oid_compare);
586
587                 /*
588                  * The batch is now sorted by OID and then mtime (descending).
589                  * Take only the first duplicate.
590                  */
591                 for (cur_object = 0; cur_object < nr_fanout; cur_object++) {
592                         if (cur_object && oideq(&entries_by_fanout[cur_object - 1].oid,
593                                                 &entries_by_fanout[cur_object].oid))
594                                 continue;
595
596                         ALLOC_GROW(deduplicated_entries, *nr_objects + 1, alloc_objects);
597                         memcpy(&deduplicated_entries[*nr_objects],
598                                &entries_by_fanout[cur_object],
599                                sizeof(struct pack_midx_entry));
600                         (*nr_objects)++;
601                 }
602         }
603
604         free(entries_by_fanout);
605         return deduplicated_entries;
606 }
607
608 static size_t write_midx_pack_names(struct hashfile *f,
609                                     char **pack_names,
610                                     uint32_t num_packs)
611 {
612         uint32_t i;
613         unsigned char padding[MIDX_CHUNK_ALIGNMENT];
614         size_t written = 0;
615
616         for (i = 0; i < num_packs; i++) {
617                 size_t writelen = strlen(pack_names[i]) + 1;
618
619                 if (i && strcmp(pack_names[i], pack_names[i - 1]) <= 0)
620                         BUG("incorrect pack-file order: %s before %s",
621                             pack_names[i - 1],
622                             pack_names[i]);
623
624                 hashwrite(f, pack_names[i], writelen);
625                 written += writelen;
626         }
627
628         /* add padding to be aligned */
629         i = MIDX_CHUNK_ALIGNMENT - (written % MIDX_CHUNK_ALIGNMENT);
630         if (i < MIDX_CHUNK_ALIGNMENT) {
631                 memset(padding, 0, sizeof(padding));
632                 hashwrite(f, padding, i);
633                 written += i;
634         }
635
636         return written;
637 }
638
639 static size_t write_midx_oid_fanout(struct hashfile *f,
640                                     struct pack_midx_entry *objects,
641                                     uint32_t nr_objects)
642 {
643         struct pack_midx_entry *list = objects;
644         struct pack_midx_entry *last = objects + nr_objects;
645         uint32_t count = 0;
646         uint32_t i;
647
648         /*
649         * Write the first-level table (the list is sorted,
650         * but we use a 256-entry lookup to be able to avoid
651         * having to do eight extra binary search iterations).
652         */
653         for (i = 0; i < 256; i++) {
654                 struct pack_midx_entry *next = list;
655
656                 while (next < last && next->oid.hash[0] == i) {
657                         count++;
658                         next++;
659                 }
660
661                 hashwrite_be32(f, count);
662                 list = next;
663         }
664
665         return MIDX_CHUNK_FANOUT_SIZE;
666 }
667
668 static size_t write_midx_oid_lookup(struct hashfile *f, unsigned char hash_len,
669                                     struct pack_midx_entry *objects,
670                                     uint32_t nr_objects)
671 {
672         struct pack_midx_entry *list = objects;
673         uint32_t i;
674         size_t written = 0;
675
676         for (i = 0; i < nr_objects; i++) {
677                 struct pack_midx_entry *obj = list++;
678
679                 if (i < nr_objects - 1) {
680                         struct pack_midx_entry *next = list;
681                         if (oidcmp(&obj->oid, &next->oid) >= 0)
682                                 BUG("OIDs not in order: %s >= %s",
683                                     oid_to_hex(&obj->oid),
684                                     oid_to_hex(&next->oid));
685                 }
686
687                 hashwrite(f, obj->oid.hash, (int)hash_len);
688                 written += hash_len;
689         }
690
691         return written;
692 }
693
694 static size_t write_midx_object_offsets(struct hashfile *f, int large_offset_needed,
695                                         struct pack_midx_entry *objects, uint32_t nr_objects)
696 {
697         struct pack_midx_entry *list = objects;
698         uint32_t i, nr_large_offset = 0;
699         size_t written = 0;
700
701         for (i = 0; i < nr_objects; i++) {
702                 struct pack_midx_entry *obj = list++;
703
704                 hashwrite_be32(f, obj->pack_int_id);
705
706                 if (large_offset_needed && obj->offset >> 31)
707                         hashwrite_be32(f, MIDX_LARGE_OFFSET_NEEDED | nr_large_offset++);
708                 else if (!large_offset_needed && obj->offset >> 32)
709                         BUG("object %s requires a large offset (%"PRIx64") but the MIDX is not writing large offsets!",
710                             oid_to_hex(&obj->oid),
711                             obj->offset);
712                 else
713                         hashwrite_be32(f, (uint32_t)obj->offset);
714
715                 written += MIDX_CHUNK_OFFSET_WIDTH;
716         }
717
718         return written;
719 }
720
721 static size_t write_midx_large_offsets(struct hashfile *f, uint32_t nr_large_offset,
722                                        struct pack_midx_entry *objects, uint32_t nr_objects)
723 {
724         struct pack_midx_entry *list = objects, *end = objects + nr_objects;
725         size_t written = 0;
726
727         while (nr_large_offset) {
728                 struct pack_midx_entry *obj;
729                 uint64_t offset;
730
731                 if (list >= end)
732                         BUG("too many large-offset objects");
733
734                 obj = list++;
735                 offset = obj->offset;
736
737                 if (!(offset >> 31))
738                         continue;
739
740                 hashwrite_be32(f, offset >> 32);
741                 hashwrite_be32(f, offset & 0xffffffffUL);
742                 written += 2 * sizeof(uint32_t);
743
744                 nr_large_offset--;
745         }
746
747         return written;
748 }
749
750 int write_midx_file(const char *object_dir)
751 {
752         unsigned char cur_chunk, num_chunks = 0;
753         char *midx_name;
754         uint32_t i;
755         struct hashfile *f = NULL;
756         struct lock_file lk;
757         struct pack_list packs;
758         uint32_t *pack_perm = NULL;
759         uint64_t written = 0;
760         uint32_t chunk_ids[MIDX_MAX_CHUNKS + 1];
761         uint64_t chunk_offsets[MIDX_MAX_CHUNKS + 1];
762         uint32_t nr_entries, num_large_offsets = 0;
763         struct pack_midx_entry *entries = NULL;
764         int large_offsets_needed = 0;
765
766         midx_name = get_midx_filename(object_dir);
767         if (safe_create_leading_directories(midx_name)) {
768                 UNLEAK(midx_name);
769                 die_errno(_("unable to create leading directories of %s"),
770                           midx_name);
771         }
772
773         packs.m = load_multi_pack_index(object_dir, 1);
774
775         packs.nr = 0;
776         packs.alloc_list = packs.m ? packs.m->num_packs : 16;
777         packs.alloc_names = packs.alloc_list;
778         packs.list = NULL;
779         packs.names = NULL;
780         packs.pack_name_concat_len = 0;
781         ALLOC_ARRAY(packs.list, packs.alloc_list);
782         ALLOC_ARRAY(packs.names, packs.alloc_names);
783
784         if (packs.m) {
785                 for (i = 0; i < packs.m->num_packs; i++) {
786                         ALLOC_GROW(packs.list, packs.nr + 1, packs.alloc_list);
787                         ALLOC_GROW(packs.names, packs.nr + 1, packs.alloc_names);
788
789                         packs.list[packs.nr] = NULL;
790                         packs.names[packs.nr] = xstrdup(packs.m->pack_names[i]);
791                         packs.pack_name_concat_len += strlen(packs.names[packs.nr]) + 1;
792                         packs.nr++;
793                 }
794         }
795
796         for_each_file_in_pack_dir(object_dir, add_pack_to_midx, &packs);
797
798         if (packs.m && packs.nr == packs.m->num_packs)
799                 goto cleanup;
800
801         if (packs.pack_name_concat_len % MIDX_CHUNK_ALIGNMENT)
802                 packs.pack_name_concat_len += MIDX_CHUNK_ALIGNMENT -
803                                               (packs.pack_name_concat_len % MIDX_CHUNK_ALIGNMENT);
804
805         ALLOC_ARRAY(pack_perm, packs.nr);
806         sort_packs_by_name(packs.names, packs.nr, pack_perm);
807
808         entries = get_sorted_entries(packs.m, packs.list, pack_perm, packs.nr, &nr_entries);
809
810         for (i = 0; i < nr_entries; i++) {
811                 if (entries[i].offset > 0x7fffffff)
812                         num_large_offsets++;
813                 if (entries[i].offset > 0xffffffff)
814                         large_offsets_needed = 1;
815         }
816
817         hold_lock_file_for_update(&lk, midx_name, LOCK_DIE_ON_ERROR);
818         f = hashfd(lk.tempfile->fd, lk.tempfile->filename.buf);
819         FREE_AND_NULL(midx_name);
820
821         if (packs.m)
822                 close_midx(packs.m);
823
824         cur_chunk = 0;
825         num_chunks = large_offsets_needed ? 5 : 4;
826
827         written = write_midx_header(f, num_chunks, packs.nr);
828
829         chunk_ids[cur_chunk] = MIDX_CHUNKID_PACKNAMES;
830         chunk_offsets[cur_chunk] = written + (num_chunks + 1) * MIDX_CHUNKLOOKUP_WIDTH;
831
832         cur_chunk++;
833         chunk_ids[cur_chunk] = MIDX_CHUNKID_OIDFANOUT;
834         chunk_offsets[cur_chunk] = chunk_offsets[cur_chunk - 1] + packs.pack_name_concat_len;
835
836         cur_chunk++;
837         chunk_ids[cur_chunk] = MIDX_CHUNKID_OIDLOOKUP;
838         chunk_offsets[cur_chunk] = chunk_offsets[cur_chunk - 1] + MIDX_CHUNK_FANOUT_SIZE;
839
840         cur_chunk++;
841         chunk_ids[cur_chunk] = MIDX_CHUNKID_OBJECTOFFSETS;
842         chunk_offsets[cur_chunk] = chunk_offsets[cur_chunk - 1] + nr_entries * MIDX_HASH_LEN;
843
844         cur_chunk++;
845         chunk_offsets[cur_chunk] = chunk_offsets[cur_chunk - 1] + nr_entries * MIDX_CHUNK_OFFSET_WIDTH;
846         if (large_offsets_needed) {
847                 chunk_ids[cur_chunk] = MIDX_CHUNKID_LARGEOFFSETS;
848
849                 cur_chunk++;
850                 chunk_offsets[cur_chunk] = chunk_offsets[cur_chunk - 1] +
851                                            num_large_offsets * MIDX_CHUNK_LARGE_OFFSET_WIDTH;
852         }
853
854         chunk_ids[cur_chunk] = 0;
855
856         for (i = 0; i <= num_chunks; i++) {
857                 if (i && chunk_offsets[i] < chunk_offsets[i - 1])
858                         BUG("incorrect chunk offsets: %"PRIu64" before %"PRIu64,
859                             chunk_offsets[i - 1],
860                             chunk_offsets[i]);
861
862                 if (chunk_offsets[i] % MIDX_CHUNK_ALIGNMENT)
863                         BUG("chunk offset %"PRIu64" is not properly aligned",
864                             chunk_offsets[i]);
865
866                 hashwrite_be32(f, chunk_ids[i]);
867                 hashwrite_be32(f, chunk_offsets[i] >> 32);
868                 hashwrite_be32(f, chunk_offsets[i]);
869
870                 written += MIDX_CHUNKLOOKUP_WIDTH;
871         }
872
873         for (i = 0; i < num_chunks; i++) {
874                 if (written != chunk_offsets[i])
875                         BUG("incorrect chunk offset (%"PRIu64" != %"PRIu64") for chunk id %"PRIx32,
876                             chunk_offsets[i],
877                             written,
878                             chunk_ids[i]);
879
880                 switch (chunk_ids[i]) {
881                         case MIDX_CHUNKID_PACKNAMES:
882                                 written += write_midx_pack_names(f, packs.names, packs.nr);
883                                 break;
884
885                         case MIDX_CHUNKID_OIDFANOUT:
886                                 written += write_midx_oid_fanout(f, entries, nr_entries);
887                                 break;
888
889                         case MIDX_CHUNKID_OIDLOOKUP:
890                                 written += write_midx_oid_lookup(f, MIDX_HASH_LEN, entries, nr_entries);
891                                 break;
892
893                         case MIDX_CHUNKID_OBJECTOFFSETS:
894                                 written += write_midx_object_offsets(f, large_offsets_needed, entries, nr_entries);
895                                 break;
896
897                         case MIDX_CHUNKID_LARGEOFFSETS:
898                                 written += write_midx_large_offsets(f, num_large_offsets, entries, nr_entries);
899                                 break;
900
901                         default:
902                                 BUG("trying to write unknown chunk id %"PRIx32,
903                                     chunk_ids[i]);
904                 }
905         }
906
907         if (written != chunk_offsets[num_chunks])
908                 BUG("incorrect final offset %"PRIu64" != %"PRIu64,
909                     written,
910                     chunk_offsets[num_chunks]);
911
912         finalize_hashfile(f, NULL, CSUM_FSYNC | CSUM_HASH_IN_STREAM);
913         commit_lock_file(&lk);
914
915 cleanup:
916         for (i = 0; i < packs.nr; i++) {
917                 if (packs.list[i]) {
918                         close_pack(packs.list[i]);
919                         free(packs.list[i]);
920                 }
921                 free(packs.names[i]);
922         }
923
924         free(packs.list);
925         free(packs.names);
926         free(entries);
927         free(pack_perm);
928         free(midx_name);
929         return 0;
930 }
931
932 void clear_midx_file(struct repository *r)
933 {
934         char *midx = get_midx_filename(r->objects->objectdir);
935
936         if (r->objects && r->objects->multi_pack_index) {
937                 close_midx(r->objects->multi_pack_index);
938                 r->objects->multi_pack_index = NULL;
939         }
940
941         if (remove_path(midx)) {
942                 UNLEAK(midx);
943                 die(_("failed to clear multi-pack-index at %s"), midx);
944         }
945
946         free(midx);
947 }
948
949 static int verify_midx_error;
950
951 static void midx_report(const char *fmt, ...)
952 {
953         va_list ap;
954         verify_midx_error = 1;
955         va_start(ap, fmt);
956         vfprintf(stderr, fmt, ap);
957         fprintf(stderr, "\n");
958         va_end(ap);
959 }
960
961 int verify_midx_file(const char *object_dir)
962 {
963         uint32_t i;
964         struct progress *progress;
965         struct multi_pack_index *m = load_multi_pack_index(object_dir, 1);
966         verify_midx_error = 0;
967
968         if (!m)
969                 return 0;
970
971         for (i = 0; i < m->num_packs; i++) {
972                 if (prepare_midx_pack(m, i))
973                         midx_report("failed to load pack in position %d", i);
974         }
975
976         for (i = 0; i < 255; i++) {
977                 uint32_t oid_fanout1 = ntohl(m->chunk_oid_fanout[i]);
978                 uint32_t oid_fanout2 = ntohl(m->chunk_oid_fanout[i + 1]);
979
980                 if (oid_fanout1 > oid_fanout2)
981                         midx_report(_("oid fanout out of order: fanout[%d] = %"PRIx32" > %"PRIx32" = fanout[%d]"),
982                                     i, oid_fanout1, oid_fanout2, i + 1);
983         }
984
985         for (i = 0; i < m->num_objects - 1; i++) {
986                 struct object_id oid1, oid2;
987
988                 nth_midxed_object_oid(&oid1, m, i);
989                 nth_midxed_object_oid(&oid2, m, i + 1);
990
991                 if (oidcmp(&oid1, &oid2) >= 0)
992                         midx_report(_("oid lookup out of order: oid[%d] = %s >= %s = oid[%d]"),
993                                     i, oid_to_hex(&oid1), oid_to_hex(&oid2), i + 1);
994         }
995
996         progress = start_progress(_("Verifying object offsets"), m->num_objects);
997         for (i = 0; i < m->num_objects; i++) {
998                 struct object_id oid;
999                 struct pack_entry e;
1000                 off_t m_offset, p_offset;
1001
1002                 nth_midxed_object_oid(&oid, m, i);
1003                 if (!fill_midx_entry(&oid, &e, m)) {
1004                         midx_report(_("failed to load pack entry for oid[%d] = %s"),
1005                                     i, oid_to_hex(&oid));
1006                         continue;
1007                 }
1008
1009                 if (open_pack_index(e.p)) {
1010                         midx_report(_("failed to load pack-index for packfile %s"),
1011                                     e.p->pack_name);
1012                         break;
1013                 }
1014
1015                 m_offset = e.offset;
1016                 p_offset = find_pack_entry_one(oid.hash, e.p);
1017
1018                 if (m_offset != p_offset)
1019                         midx_report(_("incorrect object offset for oid[%d] = %s: %"PRIx64" != %"PRIx64),
1020                                     i, oid_to_hex(&oid), m_offset, p_offset);
1021
1022                 display_progress(progress, i + 1);
1023         }
1024         stop_progress(&progress);
1025
1026         return verify_midx_error;
1027 }