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