doc: log, gitk: move '-L' description to 'line-range-options.txt'
[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 #include "run-command.h"
13 #include "repository.h"
14
15 #define MIDX_SIGNATURE 0x4d494458 /* "MIDX" */
16 #define MIDX_VERSION 1
17 #define MIDX_BYTE_FILE_VERSION 4
18 #define MIDX_BYTE_HASH_VERSION 5
19 #define MIDX_BYTE_NUM_CHUNKS 6
20 #define MIDX_BYTE_NUM_PACKS 8
21 #define MIDX_HEADER_SIZE 12
22 #define MIDX_MIN_SIZE (MIDX_HEADER_SIZE + the_hash_algo->rawsz)
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 #define PACK_EXPIRED UINT_MAX
38
39 static uint8_t oid_version(void)
40 {
41         switch (hash_algo_by_ptr(the_hash_algo)) {
42         case GIT_HASH_SHA1:
43                 return 1;
44         case GIT_HASH_SHA256:
45                 return 2;
46         default:
47                 die(_("invalid hash version"));
48         }
49 }
50
51 static char *get_midx_filename(const char *object_dir)
52 {
53         return xstrfmt("%s/pack/multi-pack-index", object_dir);
54 }
55
56 struct multi_pack_index *load_multi_pack_index(const char *object_dir, int local)
57 {
58         struct multi_pack_index *m = NULL;
59         int fd;
60         struct stat st;
61         size_t midx_size;
62         void *midx_map = NULL;
63         uint32_t hash_version;
64         char *midx_name = get_midx_filename(object_dir);
65         uint32_t i;
66         const char *cur_pack_name;
67
68         fd = git_open(midx_name);
69
70         if (fd < 0)
71                 goto cleanup_fail;
72         if (fstat(fd, &st)) {
73                 error_errno(_("failed to read %s"), midx_name);
74                 goto cleanup_fail;
75         }
76
77         midx_size = xsize_t(st.st_size);
78
79         if (midx_size < MIDX_MIN_SIZE) {
80                 error(_("multi-pack-index file %s is too small"), midx_name);
81                 goto cleanup_fail;
82         }
83
84         FREE_AND_NULL(midx_name);
85
86         midx_map = xmmap(NULL, midx_size, PROT_READ, MAP_PRIVATE, fd, 0);
87         close(fd);
88
89         FLEX_ALLOC_STR(m, object_dir, object_dir);
90         m->data = midx_map;
91         m->data_len = midx_size;
92         m->local = local;
93
94         m->signature = get_be32(m->data);
95         if (m->signature != MIDX_SIGNATURE)
96                 die(_("multi-pack-index signature 0x%08x does not match signature 0x%08x"),
97                       m->signature, MIDX_SIGNATURE);
98
99         m->version = m->data[MIDX_BYTE_FILE_VERSION];
100         if (m->version != MIDX_VERSION)
101                 die(_("multi-pack-index version %d not recognized"),
102                       m->version);
103
104         hash_version = m->data[MIDX_BYTE_HASH_VERSION];
105         if (hash_version != oid_version()) {
106                 error(_("multi-pack-index hash version %u does not match version %u"),
107                       hash_version, oid_version());
108                 goto cleanup_fail;
109         }
110         m->hash_len = the_hash_algo->rawsz;
111
112         m->num_chunks = m->data[MIDX_BYTE_NUM_CHUNKS];
113
114         m->num_packs = get_be32(m->data + MIDX_BYTE_NUM_PACKS);
115
116         for (i = 0; i < m->num_chunks; i++) {
117                 uint32_t chunk_id = get_be32(m->data + MIDX_HEADER_SIZE +
118                                              MIDX_CHUNKLOOKUP_WIDTH * i);
119                 uint64_t chunk_offset = get_be64(m->data + MIDX_HEADER_SIZE + 4 +
120                                                  MIDX_CHUNKLOOKUP_WIDTH * i);
121
122                 if (chunk_offset >= m->data_len)
123                         die(_("invalid chunk offset (too large)"));
124
125                 switch (chunk_id) {
126                         case MIDX_CHUNKID_PACKNAMES:
127                                 m->chunk_pack_names = m->data + chunk_offset;
128                                 break;
129
130                         case MIDX_CHUNKID_OIDFANOUT:
131                                 m->chunk_oid_fanout = (uint32_t *)(m->data + chunk_offset);
132                                 break;
133
134                         case MIDX_CHUNKID_OIDLOOKUP:
135                                 m->chunk_oid_lookup = m->data + chunk_offset;
136                                 break;
137
138                         case MIDX_CHUNKID_OBJECTOFFSETS:
139                                 m->chunk_object_offsets = m->data + chunk_offset;
140                                 break;
141
142                         case MIDX_CHUNKID_LARGEOFFSETS:
143                                 m->chunk_large_offsets = m->data + chunk_offset;
144                                 break;
145
146                         case 0:
147                                 die(_("terminating multi-pack-index chunk id appears earlier than expected"));
148                                 break;
149
150                         default:
151                                 /*
152                                  * Do nothing on unrecognized chunks, allowing future
153                                  * extensions to add optional chunks.
154                                  */
155                                 break;
156                 }
157         }
158
159         if (!m->chunk_pack_names)
160                 die(_("multi-pack-index missing required pack-name chunk"));
161         if (!m->chunk_oid_fanout)
162                 die(_("multi-pack-index missing required OID fanout chunk"));
163         if (!m->chunk_oid_lookup)
164                 die(_("multi-pack-index missing required OID lookup chunk"));
165         if (!m->chunk_object_offsets)
166                 die(_("multi-pack-index missing required object offsets chunk"));
167
168         m->num_objects = ntohl(m->chunk_oid_fanout[255]);
169
170         m->pack_names = xcalloc(m->num_packs, sizeof(*m->pack_names));
171         m->packs = xcalloc(m->num_packs, sizeof(*m->packs));
172
173         cur_pack_name = (const char *)m->chunk_pack_names;
174         for (i = 0; i < m->num_packs; i++) {
175                 m->pack_names[i] = cur_pack_name;
176
177                 cur_pack_name += strlen(cur_pack_name) + 1;
178
179                 if (i && strcmp(m->pack_names[i], m->pack_names[i - 1]) <= 0)
180                         die(_("multi-pack-index pack names out of order: '%s' before '%s'"),
181                               m->pack_names[i - 1],
182                               m->pack_names[i]);
183         }
184
185         trace2_data_intmax("midx", the_repository, "load/num_packs", m->num_packs);
186         trace2_data_intmax("midx", the_repository, "load/num_objects", m->num_objects);
187
188         return m;
189
190 cleanup_fail:
191         free(m);
192         free(midx_name);
193         if (midx_map)
194                 munmap(midx_map, midx_size);
195         if (0 <= fd)
196                 close(fd);
197         return NULL;
198 }
199
200 void close_midx(struct multi_pack_index *m)
201 {
202         uint32_t i;
203
204         if (!m)
205                 return;
206
207         munmap((unsigned char *)m->data, m->data_len);
208
209         for (i = 0; i < m->num_packs; i++) {
210                 if (m->packs[i])
211                         m->packs[i]->multi_pack_index = 0;
212         }
213         FREE_AND_NULL(m->packs);
214         FREE_AND_NULL(m->pack_names);
215 }
216
217 int prepare_midx_pack(struct repository *r, struct multi_pack_index *m, uint32_t pack_int_id)
218 {
219         struct strbuf pack_name = STRBUF_INIT;
220         struct packed_git *p;
221
222         if (pack_int_id >= m->num_packs)
223                 die(_("bad pack-int-id: %u (%u total packs)"),
224                     pack_int_id, m->num_packs);
225
226         if (m->packs[pack_int_id])
227                 return 0;
228
229         strbuf_addf(&pack_name, "%s/pack/%s", m->object_dir,
230                     m->pack_names[pack_int_id]);
231
232         p = add_packed_git(pack_name.buf, pack_name.len, m->local);
233         strbuf_release(&pack_name);
234
235         if (!p)
236                 return 1;
237
238         p->multi_pack_index = 1;
239         m->packs[pack_int_id] = p;
240         install_packed_git(r, p);
241         list_add_tail(&p->mru, &r->objects->packed_git_mru);
242
243         return 0;
244 }
245
246 int bsearch_midx(const struct object_id *oid, struct multi_pack_index *m, uint32_t *result)
247 {
248         return bsearch_hash(oid->hash, m->chunk_oid_fanout, m->chunk_oid_lookup,
249                             the_hash_algo->rawsz, result);
250 }
251
252 struct object_id *nth_midxed_object_oid(struct object_id *oid,
253                                         struct multi_pack_index *m,
254                                         uint32_t n)
255 {
256         if (n >= m->num_objects)
257                 return NULL;
258
259         hashcpy(oid->hash, m->chunk_oid_lookup + m->hash_len * n);
260         return oid;
261 }
262
263 static off_t nth_midxed_offset(struct multi_pack_index *m, uint32_t pos)
264 {
265         const unsigned char *offset_data;
266         uint32_t offset32;
267
268         offset_data = m->chunk_object_offsets + pos * MIDX_CHUNK_OFFSET_WIDTH;
269         offset32 = get_be32(offset_data + sizeof(uint32_t));
270
271         if (m->chunk_large_offsets && offset32 & MIDX_LARGE_OFFSET_NEEDED) {
272                 if (sizeof(off_t) < sizeof(uint64_t))
273                         die(_("multi-pack-index stores a 64-bit offset, but off_t is too small"));
274
275                 offset32 ^= MIDX_LARGE_OFFSET_NEEDED;
276                 return get_be64(m->chunk_large_offsets + sizeof(uint64_t) * offset32);
277         }
278
279         return offset32;
280 }
281
282 static uint32_t nth_midxed_pack_int_id(struct multi_pack_index *m, uint32_t pos)
283 {
284         return get_be32(m->chunk_object_offsets + pos * MIDX_CHUNK_OFFSET_WIDTH);
285 }
286
287 static int nth_midxed_pack_entry(struct repository *r,
288                                  struct multi_pack_index *m,
289                                  struct pack_entry *e,
290                                  uint32_t pos)
291 {
292         uint32_t pack_int_id;
293         struct packed_git *p;
294
295         if (pos >= m->num_objects)
296                 return 0;
297
298         pack_int_id = nth_midxed_pack_int_id(m, pos);
299
300         if (prepare_midx_pack(r, m, pack_int_id))
301                 die(_("error preparing packfile from multi-pack-index"));
302         p = m->packs[pack_int_id];
303
304         /*
305         * We are about to tell the caller where they can locate the
306         * requested object.  We better make sure the packfile is
307         * still here and can be accessed before supplying that
308         * answer, as it may have been deleted since the MIDX was
309         * loaded!
310         */
311         if (!is_pack_valid(p))
312                 return 0;
313
314         if (p->num_bad_objects) {
315                 uint32_t i;
316                 struct object_id oid;
317                 nth_midxed_object_oid(&oid, m, pos);
318                 for (i = 0; i < p->num_bad_objects; i++)
319                         if (hasheq(oid.hash,
320                                    p->bad_object_sha1 + the_hash_algo->rawsz * i))
321                                 return 0;
322         }
323
324         e->offset = nth_midxed_offset(m, pos);
325         e->p = p;
326
327         return 1;
328 }
329
330 int fill_midx_entry(struct repository * r,
331                     const struct object_id *oid,
332                     struct pack_entry *e,
333                     struct multi_pack_index *m)
334 {
335         uint32_t pos;
336
337         if (!bsearch_midx(oid, m, &pos))
338                 return 0;
339
340         return nth_midxed_pack_entry(r, m, e, pos);
341 }
342
343 /* Match "foo.idx" against either "foo.pack" _or_ "foo.idx". */
344 static int cmp_idx_or_pack_name(const char *idx_or_pack_name,
345                                 const char *idx_name)
346 {
347         /* Skip past any initial matching prefix. */
348         while (*idx_name && *idx_name == *idx_or_pack_name) {
349                 idx_name++;
350                 idx_or_pack_name++;
351         }
352
353         /*
354          * If we didn't match completely, we may have matched "pack-1234." and
355          * be left with "idx" and "pack" respectively, which is also OK. We do
356          * not have to check for "idx" and "idx", because that would have been
357          * a complete match (and in that case these strcmps will be false, but
358          * we'll correctly return 0 from the final strcmp() below.
359          *
360          * Technically this matches "fooidx" and "foopack", but we'd never have
361          * such names in the first place.
362          */
363         if (!strcmp(idx_name, "idx") && !strcmp(idx_or_pack_name, "pack"))
364                 return 0;
365
366         /*
367          * This not only checks for a complete match, but also orders based on
368          * the first non-identical character, which means our ordering will
369          * match a raw strcmp(). That makes it OK to use this to binary search
370          * a naively-sorted list.
371          */
372         return strcmp(idx_or_pack_name, idx_name);
373 }
374
375 int midx_contains_pack(struct multi_pack_index *m, const char *idx_or_pack_name)
376 {
377         uint32_t first = 0, last = m->num_packs;
378
379         while (first < last) {
380                 uint32_t mid = first + (last - first) / 2;
381                 const char *current;
382                 int cmp;
383
384                 current = m->pack_names[mid];
385                 cmp = cmp_idx_or_pack_name(idx_or_pack_name, current);
386                 if (!cmp)
387                         return 1;
388                 if (cmp > 0) {
389                         first = mid + 1;
390                         continue;
391                 }
392                 last = mid;
393         }
394
395         return 0;
396 }
397
398 int prepare_multi_pack_index_one(struct repository *r, const char *object_dir, int local)
399 {
400         struct multi_pack_index *m;
401         struct multi_pack_index *m_search;
402
403         prepare_repo_settings(r);
404         if (!r->settings.core_multi_pack_index)
405                 return 0;
406
407         for (m_search = r->objects->multi_pack_index; m_search; m_search = m_search->next)
408                 if (!strcmp(object_dir, m_search->object_dir))
409                         return 1;
410
411         m = load_multi_pack_index(object_dir, local);
412
413         if (m) {
414                 struct multi_pack_index *mp = r->objects->multi_pack_index;
415                 if (mp) {
416                         m->next = mp->next;
417                         mp->next = m;
418                 } else
419                         r->objects->multi_pack_index = m;
420                 return 1;
421         }
422
423         return 0;
424 }
425
426 static size_t write_midx_header(struct hashfile *f,
427                                 unsigned char num_chunks,
428                                 uint32_t num_packs)
429 {
430         hashwrite_be32(f, MIDX_SIGNATURE);
431         hashwrite_u8(f, MIDX_VERSION);
432         hashwrite_u8(f, oid_version());
433         hashwrite_u8(f, num_chunks);
434         hashwrite_u8(f, 0); /* unused */
435         hashwrite_be32(f, num_packs);
436
437         return MIDX_HEADER_SIZE;
438 }
439
440 struct pack_info {
441         uint32_t orig_pack_int_id;
442         char *pack_name;
443         struct packed_git *p;
444         unsigned expired : 1;
445 };
446
447 static int pack_info_compare(const void *_a, const void *_b)
448 {
449         struct pack_info *a = (struct pack_info *)_a;
450         struct pack_info *b = (struct pack_info *)_b;
451         return strcmp(a->pack_name, b->pack_name);
452 }
453
454 struct pack_list {
455         struct pack_info *info;
456         uint32_t nr;
457         uint32_t alloc;
458         struct multi_pack_index *m;
459         struct progress *progress;
460         unsigned pack_paths_checked;
461 };
462
463 static void add_pack_to_midx(const char *full_path, size_t full_path_len,
464                              const char *file_name, void *data)
465 {
466         struct pack_list *packs = (struct pack_list *)data;
467
468         if (ends_with(file_name, ".idx")) {
469                 display_progress(packs->progress, ++packs->pack_paths_checked);
470                 if (packs->m && midx_contains_pack(packs->m, file_name))
471                         return;
472
473                 ALLOC_GROW(packs->info, packs->nr + 1, packs->alloc);
474
475                 packs->info[packs->nr].p = add_packed_git(full_path,
476                                                           full_path_len,
477                                                           0);
478
479                 if (!packs->info[packs->nr].p) {
480                         warning(_("failed to add packfile '%s'"),
481                                 full_path);
482                         return;
483                 }
484
485                 if (open_pack_index(packs->info[packs->nr].p)) {
486                         warning(_("failed to open pack-index '%s'"),
487                                 full_path);
488                         close_pack(packs->info[packs->nr].p);
489                         FREE_AND_NULL(packs->info[packs->nr].p);
490                         return;
491                 }
492
493                 packs->info[packs->nr].pack_name = xstrdup(file_name);
494                 packs->info[packs->nr].orig_pack_int_id = packs->nr;
495                 packs->info[packs->nr].expired = 0;
496                 packs->nr++;
497         }
498 }
499
500 struct pack_midx_entry {
501         struct object_id oid;
502         uint32_t pack_int_id;
503         time_t pack_mtime;
504         uint64_t offset;
505 };
506
507 static int midx_oid_compare(const void *_a, const void *_b)
508 {
509         const struct pack_midx_entry *a = (const struct pack_midx_entry *)_a;
510         const struct pack_midx_entry *b = (const struct pack_midx_entry *)_b;
511         int cmp = oidcmp(&a->oid, &b->oid);
512
513         if (cmp)
514                 return cmp;
515
516         if (a->pack_mtime > b->pack_mtime)
517                 return -1;
518         else if (a->pack_mtime < b->pack_mtime)
519                 return 1;
520
521         return a->pack_int_id - b->pack_int_id;
522 }
523
524 static int nth_midxed_pack_midx_entry(struct multi_pack_index *m,
525                                       struct pack_midx_entry *e,
526                                       uint32_t pos)
527 {
528         if (pos >= m->num_objects)
529                 return 1;
530
531         nth_midxed_object_oid(&e->oid, m, pos);
532         e->pack_int_id = nth_midxed_pack_int_id(m, pos);
533         e->offset = nth_midxed_offset(m, pos);
534
535         /* consider objects in midx to be from "old" packs */
536         e->pack_mtime = 0;
537         return 0;
538 }
539
540 static void fill_pack_entry(uint32_t pack_int_id,
541                             struct packed_git *p,
542                             uint32_t cur_object,
543                             struct pack_midx_entry *entry)
544 {
545         if (nth_packed_object_id(&entry->oid, p, cur_object) < 0)
546                 die(_("failed to locate object %d in packfile"), cur_object);
547
548         entry->pack_int_id = pack_int_id;
549         entry->pack_mtime = p->mtime;
550
551         entry->offset = nth_packed_object_offset(p, cur_object);
552 }
553
554 /*
555  * It is possible to artificially get into a state where there are many
556  * duplicate copies of objects. That can create high memory pressure if
557  * we are to create a list of all objects before de-duplication. To reduce
558  * this memory pressure without a significant performance drop, automatically
559  * group objects by the first byte of their object id. Use the IDX fanout
560  * tables to group the data, copy to a local array, then sort.
561  *
562  * Copy only the de-duplicated entries (selected by most-recent modified time
563  * of a packfile containing the object).
564  */
565 static struct pack_midx_entry *get_sorted_entries(struct multi_pack_index *m,
566                                                   struct pack_info *info,
567                                                   uint32_t nr_packs,
568                                                   uint32_t *nr_objects)
569 {
570         uint32_t cur_fanout, cur_pack, cur_object;
571         uint32_t alloc_fanout, alloc_objects, total_objects = 0;
572         struct pack_midx_entry *entries_by_fanout = NULL;
573         struct pack_midx_entry *deduplicated_entries = NULL;
574         uint32_t start_pack = m ? m->num_packs : 0;
575
576         for (cur_pack = start_pack; cur_pack < nr_packs; cur_pack++)
577                 total_objects += info[cur_pack].p->num_objects;
578
579         /*
580          * As we de-duplicate by fanout value, we expect the fanout
581          * slices to be evenly distributed, with some noise. Hence,
582          * allocate slightly more than one 256th.
583          */
584         alloc_objects = alloc_fanout = total_objects > 3200 ? total_objects / 200 : 16;
585
586         ALLOC_ARRAY(entries_by_fanout, alloc_fanout);
587         ALLOC_ARRAY(deduplicated_entries, alloc_objects);
588         *nr_objects = 0;
589
590         for (cur_fanout = 0; cur_fanout < 256; cur_fanout++) {
591                 uint32_t nr_fanout = 0;
592
593                 if (m) {
594                         uint32_t start = 0, end;
595
596                         if (cur_fanout)
597                                 start = ntohl(m->chunk_oid_fanout[cur_fanout - 1]);
598                         end = ntohl(m->chunk_oid_fanout[cur_fanout]);
599
600                         for (cur_object = start; cur_object < end; cur_object++) {
601                                 ALLOC_GROW(entries_by_fanout, nr_fanout + 1, alloc_fanout);
602                                 nth_midxed_pack_midx_entry(m,
603                                                            &entries_by_fanout[nr_fanout],
604                                                            cur_object);
605                                 nr_fanout++;
606                         }
607                 }
608
609                 for (cur_pack = start_pack; cur_pack < nr_packs; cur_pack++) {
610                         uint32_t start = 0, end;
611
612                         if (cur_fanout)
613                                 start = get_pack_fanout(info[cur_pack].p, cur_fanout - 1);
614                         end = get_pack_fanout(info[cur_pack].p, cur_fanout);
615
616                         for (cur_object = start; cur_object < end; cur_object++) {
617                                 ALLOC_GROW(entries_by_fanout, nr_fanout + 1, alloc_fanout);
618                                 fill_pack_entry(cur_pack, info[cur_pack].p, cur_object, &entries_by_fanout[nr_fanout]);
619                                 nr_fanout++;
620                         }
621                 }
622
623                 QSORT(entries_by_fanout, nr_fanout, midx_oid_compare);
624
625                 /*
626                  * The batch is now sorted by OID and then mtime (descending).
627                  * Take only the first duplicate.
628                  */
629                 for (cur_object = 0; cur_object < nr_fanout; cur_object++) {
630                         if (cur_object && oideq(&entries_by_fanout[cur_object - 1].oid,
631                                                 &entries_by_fanout[cur_object].oid))
632                                 continue;
633
634                         ALLOC_GROW(deduplicated_entries, *nr_objects + 1, alloc_objects);
635                         memcpy(&deduplicated_entries[*nr_objects],
636                                &entries_by_fanout[cur_object],
637                                sizeof(struct pack_midx_entry));
638                         (*nr_objects)++;
639                 }
640         }
641
642         free(entries_by_fanout);
643         return deduplicated_entries;
644 }
645
646 static size_t write_midx_pack_names(struct hashfile *f,
647                                     struct pack_info *info,
648                                     uint32_t num_packs)
649 {
650         uint32_t i;
651         unsigned char padding[MIDX_CHUNK_ALIGNMENT];
652         size_t written = 0;
653
654         for (i = 0; i < num_packs; i++) {
655                 size_t writelen;
656
657                 if (info[i].expired)
658                         continue;
659
660                 if (i && strcmp(info[i].pack_name, info[i - 1].pack_name) <= 0)
661                         BUG("incorrect pack-file order: %s before %s",
662                             info[i - 1].pack_name,
663                             info[i].pack_name);
664
665                 writelen = strlen(info[i].pack_name) + 1;
666                 hashwrite(f, info[i].pack_name, writelen);
667                 written += writelen;
668         }
669
670         /* add padding to be aligned */
671         i = MIDX_CHUNK_ALIGNMENT - (written % MIDX_CHUNK_ALIGNMENT);
672         if (i < MIDX_CHUNK_ALIGNMENT) {
673                 memset(padding, 0, sizeof(padding));
674                 hashwrite(f, padding, i);
675                 written += i;
676         }
677
678         return written;
679 }
680
681 static size_t write_midx_oid_fanout(struct hashfile *f,
682                                     struct pack_midx_entry *objects,
683                                     uint32_t nr_objects)
684 {
685         struct pack_midx_entry *list = objects;
686         struct pack_midx_entry *last = objects + nr_objects;
687         uint32_t count = 0;
688         uint32_t i;
689
690         /*
691         * Write the first-level table (the list is sorted,
692         * but we use a 256-entry lookup to be able to avoid
693         * having to do eight extra binary search iterations).
694         */
695         for (i = 0; i < 256; i++) {
696                 struct pack_midx_entry *next = list;
697
698                 while (next < last && next->oid.hash[0] == i) {
699                         count++;
700                         next++;
701                 }
702
703                 hashwrite_be32(f, count);
704                 list = next;
705         }
706
707         return MIDX_CHUNK_FANOUT_SIZE;
708 }
709
710 static size_t write_midx_oid_lookup(struct hashfile *f, unsigned char hash_len,
711                                     struct pack_midx_entry *objects,
712                                     uint32_t nr_objects)
713 {
714         struct pack_midx_entry *list = objects;
715         uint32_t i;
716         size_t written = 0;
717
718         for (i = 0; i < nr_objects; i++) {
719                 struct pack_midx_entry *obj = list++;
720
721                 if (i < nr_objects - 1) {
722                         struct pack_midx_entry *next = list;
723                         if (oidcmp(&obj->oid, &next->oid) >= 0)
724                                 BUG("OIDs not in order: %s >= %s",
725                                     oid_to_hex(&obj->oid),
726                                     oid_to_hex(&next->oid));
727                 }
728
729                 hashwrite(f, obj->oid.hash, (int)hash_len);
730                 written += hash_len;
731         }
732
733         return written;
734 }
735
736 static size_t write_midx_object_offsets(struct hashfile *f, int large_offset_needed,
737                                         uint32_t *perm,
738                                         struct pack_midx_entry *objects, uint32_t nr_objects)
739 {
740         struct pack_midx_entry *list = objects;
741         uint32_t i, nr_large_offset = 0;
742         size_t written = 0;
743
744         for (i = 0; i < nr_objects; i++) {
745                 struct pack_midx_entry *obj = list++;
746
747                 if (perm[obj->pack_int_id] == PACK_EXPIRED)
748                         BUG("object %s is in an expired pack with int-id %d",
749                             oid_to_hex(&obj->oid),
750                             obj->pack_int_id);
751
752                 hashwrite_be32(f, perm[obj->pack_int_id]);
753
754                 if (large_offset_needed && obj->offset >> 31)
755                         hashwrite_be32(f, MIDX_LARGE_OFFSET_NEEDED | nr_large_offset++);
756                 else if (!large_offset_needed && obj->offset >> 32)
757                         BUG("object %s requires a large offset (%"PRIx64") but the MIDX is not writing large offsets!",
758                             oid_to_hex(&obj->oid),
759                             obj->offset);
760                 else
761                         hashwrite_be32(f, (uint32_t)obj->offset);
762
763                 written += MIDX_CHUNK_OFFSET_WIDTH;
764         }
765
766         return written;
767 }
768
769 static size_t write_midx_large_offsets(struct hashfile *f, uint32_t nr_large_offset,
770                                        struct pack_midx_entry *objects, uint32_t nr_objects)
771 {
772         struct pack_midx_entry *list = objects, *end = objects + nr_objects;
773         size_t written = 0;
774
775         while (nr_large_offset) {
776                 struct pack_midx_entry *obj;
777                 uint64_t offset;
778
779                 if (list >= end)
780                         BUG("too many large-offset objects");
781
782                 obj = list++;
783                 offset = obj->offset;
784
785                 if (!(offset >> 31))
786                         continue;
787
788                 hashwrite_be32(f, offset >> 32);
789                 hashwrite_be32(f, offset & 0xffffffffUL);
790                 written += 2 * sizeof(uint32_t);
791
792                 nr_large_offset--;
793         }
794
795         return written;
796 }
797
798 static int write_midx_internal(const char *object_dir, struct multi_pack_index *m,
799                                struct string_list *packs_to_drop, unsigned flags)
800 {
801         unsigned char cur_chunk, num_chunks = 0;
802         char *midx_name;
803         uint32_t i;
804         struct hashfile *f = NULL;
805         struct lock_file lk;
806         struct pack_list packs;
807         uint32_t *pack_perm = NULL;
808         uint64_t written = 0;
809         uint32_t chunk_ids[MIDX_MAX_CHUNKS + 1];
810         uint64_t chunk_offsets[MIDX_MAX_CHUNKS + 1];
811         uint32_t nr_entries, num_large_offsets = 0;
812         struct pack_midx_entry *entries = NULL;
813         struct progress *progress = NULL;
814         int large_offsets_needed = 0;
815         int pack_name_concat_len = 0;
816         int dropped_packs = 0;
817         int result = 0;
818
819         midx_name = get_midx_filename(object_dir);
820         if (safe_create_leading_directories(midx_name))
821                 die_errno(_("unable to create leading directories of %s"),
822                           midx_name);
823
824         if (m)
825                 packs.m = m;
826         else
827                 packs.m = load_multi_pack_index(object_dir, 1);
828
829         packs.nr = 0;
830         packs.alloc = packs.m ? packs.m->num_packs : 16;
831         packs.info = NULL;
832         ALLOC_ARRAY(packs.info, packs.alloc);
833
834         if (packs.m) {
835                 for (i = 0; i < packs.m->num_packs; i++) {
836                         ALLOC_GROW(packs.info, packs.nr + 1, packs.alloc);
837
838                         packs.info[packs.nr].orig_pack_int_id = i;
839                         packs.info[packs.nr].pack_name = xstrdup(packs.m->pack_names[i]);
840                         packs.info[packs.nr].p = NULL;
841                         packs.info[packs.nr].expired = 0;
842                         packs.nr++;
843                 }
844         }
845
846         packs.pack_paths_checked = 0;
847         if (flags & MIDX_PROGRESS)
848                 packs.progress = start_delayed_progress(_("Adding packfiles to multi-pack-index"), 0);
849         else
850                 packs.progress = NULL;
851
852         for_each_file_in_pack_dir(object_dir, add_pack_to_midx, &packs);
853         stop_progress(&packs.progress);
854
855         if (packs.m && packs.nr == packs.m->num_packs && !packs_to_drop)
856                 goto cleanup;
857
858         entries = get_sorted_entries(packs.m, packs.info, packs.nr, &nr_entries);
859
860         for (i = 0; i < nr_entries; i++) {
861                 if (entries[i].offset > 0x7fffffff)
862                         num_large_offsets++;
863                 if (entries[i].offset > 0xffffffff)
864                         large_offsets_needed = 1;
865         }
866
867         QSORT(packs.info, packs.nr, pack_info_compare);
868
869         if (packs_to_drop && packs_to_drop->nr) {
870                 int drop_index = 0;
871                 int missing_drops = 0;
872
873                 for (i = 0; i < packs.nr && drop_index < packs_to_drop->nr; i++) {
874                         int cmp = strcmp(packs.info[i].pack_name,
875                                          packs_to_drop->items[drop_index].string);
876
877                         if (!cmp) {
878                                 drop_index++;
879                                 packs.info[i].expired = 1;
880                         } else if (cmp > 0) {
881                                 error(_("did not see pack-file %s to drop"),
882                                       packs_to_drop->items[drop_index].string);
883                                 drop_index++;
884                                 missing_drops++;
885                                 i--;
886                         } else {
887                                 packs.info[i].expired = 0;
888                         }
889                 }
890
891                 if (missing_drops) {
892                         result = 1;
893                         goto cleanup;
894                 }
895         }
896
897         /*
898          * pack_perm stores a permutation between pack-int-ids from the
899          * previous multi-pack-index to the new one we are writing:
900          *
901          * pack_perm[old_id] = new_id
902          */
903         ALLOC_ARRAY(pack_perm, packs.nr);
904         for (i = 0; i < packs.nr; i++) {
905                 if (packs.info[i].expired) {
906                         dropped_packs++;
907                         pack_perm[packs.info[i].orig_pack_int_id] = PACK_EXPIRED;
908                 } else {
909                         pack_perm[packs.info[i].orig_pack_int_id] = i - dropped_packs;
910                 }
911         }
912
913         for (i = 0; i < packs.nr; i++) {
914                 if (!packs.info[i].expired)
915                         pack_name_concat_len += strlen(packs.info[i].pack_name) + 1;
916         }
917
918         if (pack_name_concat_len % MIDX_CHUNK_ALIGNMENT)
919                 pack_name_concat_len += MIDX_CHUNK_ALIGNMENT -
920                                         (pack_name_concat_len % MIDX_CHUNK_ALIGNMENT);
921
922         hold_lock_file_for_update(&lk, midx_name, LOCK_DIE_ON_ERROR);
923         f = hashfd(lk.tempfile->fd, lk.tempfile->filename.buf);
924         FREE_AND_NULL(midx_name);
925
926         if (packs.m)
927                 close_midx(packs.m);
928
929         cur_chunk = 0;
930         num_chunks = large_offsets_needed ? 5 : 4;
931
932         if (packs.nr - dropped_packs == 0) {
933                 error(_("no pack files to index."));
934                 result = 1;
935                 goto cleanup;
936         }
937
938         written = write_midx_header(f, num_chunks, packs.nr - dropped_packs);
939
940         chunk_ids[cur_chunk] = MIDX_CHUNKID_PACKNAMES;
941         chunk_offsets[cur_chunk] = written + (num_chunks + 1) * MIDX_CHUNKLOOKUP_WIDTH;
942
943         cur_chunk++;
944         chunk_ids[cur_chunk] = MIDX_CHUNKID_OIDFANOUT;
945         chunk_offsets[cur_chunk] = chunk_offsets[cur_chunk - 1] + pack_name_concat_len;
946
947         cur_chunk++;
948         chunk_ids[cur_chunk] = MIDX_CHUNKID_OIDLOOKUP;
949         chunk_offsets[cur_chunk] = chunk_offsets[cur_chunk - 1] + MIDX_CHUNK_FANOUT_SIZE;
950
951         cur_chunk++;
952         chunk_ids[cur_chunk] = MIDX_CHUNKID_OBJECTOFFSETS;
953         chunk_offsets[cur_chunk] = chunk_offsets[cur_chunk - 1] + nr_entries * the_hash_algo->rawsz;
954
955         cur_chunk++;
956         chunk_offsets[cur_chunk] = chunk_offsets[cur_chunk - 1] + nr_entries * MIDX_CHUNK_OFFSET_WIDTH;
957         if (large_offsets_needed) {
958                 chunk_ids[cur_chunk] = MIDX_CHUNKID_LARGEOFFSETS;
959
960                 cur_chunk++;
961                 chunk_offsets[cur_chunk] = chunk_offsets[cur_chunk - 1] +
962                                            num_large_offsets * MIDX_CHUNK_LARGE_OFFSET_WIDTH;
963         }
964
965         chunk_ids[cur_chunk] = 0;
966
967         for (i = 0; i <= num_chunks; i++) {
968                 if (i && chunk_offsets[i] < chunk_offsets[i - 1])
969                         BUG("incorrect chunk offsets: %"PRIu64" before %"PRIu64,
970                             chunk_offsets[i - 1],
971                             chunk_offsets[i]);
972
973                 if (chunk_offsets[i] % MIDX_CHUNK_ALIGNMENT)
974                         BUG("chunk offset %"PRIu64" is not properly aligned",
975                             chunk_offsets[i]);
976
977                 hashwrite_be32(f, chunk_ids[i]);
978                 hashwrite_be32(f, chunk_offsets[i] >> 32);
979                 hashwrite_be32(f, chunk_offsets[i]);
980
981                 written += MIDX_CHUNKLOOKUP_WIDTH;
982         }
983
984         if (flags & MIDX_PROGRESS)
985                 progress = start_delayed_progress(_("Writing chunks to multi-pack-index"),
986                                           num_chunks);
987         for (i = 0; i < num_chunks; i++) {
988                 if (written != chunk_offsets[i])
989                         BUG("incorrect chunk offset (%"PRIu64" != %"PRIu64") for chunk id %"PRIx32,
990                             chunk_offsets[i],
991                             written,
992                             chunk_ids[i]);
993
994                 switch (chunk_ids[i]) {
995                         case MIDX_CHUNKID_PACKNAMES:
996                                 written += write_midx_pack_names(f, packs.info, packs.nr);
997                                 break;
998
999                         case MIDX_CHUNKID_OIDFANOUT:
1000                                 written += write_midx_oid_fanout(f, entries, nr_entries);
1001                                 break;
1002
1003                         case MIDX_CHUNKID_OIDLOOKUP:
1004                                 written += write_midx_oid_lookup(f, the_hash_algo->rawsz, entries, nr_entries);
1005                                 break;
1006
1007                         case MIDX_CHUNKID_OBJECTOFFSETS:
1008                                 written += write_midx_object_offsets(f, large_offsets_needed, pack_perm, entries, nr_entries);
1009                                 break;
1010
1011                         case MIDX_CHUNKID_LARGEOFFSETS:
1012                                 written += write_midx_large_offsets(f, num_large_offsets, entries, nr_entries);
1013                                 break;
1014
1015                         default:
1016                                 BUG("trying to write unknown chunk id %"PRIx32,
1017                                     chunk_ids[i]);
1018                 }
1019
1020                 display_progress(progress, i + 1);
1021         }
1022         stop_progress(&progress);
1023
1024         if (written != chunk_offsets[num_chunks])
1025                 BUG("incorrect final offset %"PRIu64" != %"PRIu64,
1026                     written,
1027                     chunk_offsets[num_chunks]);
1028
1029         finalize_hashfile(f, NULL, CSUM_FSYNC | CSUM_HASH_IN_STREAM);
1030         commit_lock_file(&lk);
1031
1032 cleanup:
1033         for (i = 0; i < packs.nr; i++) {
1034                 if (packs.info[i].p) {
1035                         close_pack(packs.info[i].p);
1036                         free(packs.info[i].p);
1037                 }
1038                 free(packs.info[i].pack_name);
1039         }
1040
1041         free(packs.info);
1042         free(entries);
1043         free(pack_perm);
1044         free(midx_name);
1045         return result;
1046 }
1047
1048 int write_midx_file(const char *object_dir, unsigned flags)
1049 {
1050         return write_midx_internal(object_dir, NULL, NULL, flags);
1051 }
1052
1053 void clear_midx_file(struct repository *r)
1054 {
1055         char *midx = get_midx_filename(r->objects->odb->path);
1056
1057         if (r->objects && r->objects->multi_pack_index) {
1058                 close_midx(r->objects->multi_pack_index);
1059                 r->objects->multi_pack_index = NULL;
1060         }
1061
1062         if (remove_path(midx))
1063                 die(_("failed to clear multi-pack-index at %s"), midx);
1064
1065         free(midx);
1066 }
1067
1068 static int verify_midx_error;
1069
1070 static void midx_report(const char *fmt, ...)
1071 {
1072         va_list ap;
1073         verify_midx_error = 1;
1074         va_start(ap, fmt);
1075         vfprintf(stderr, fmt, ap);
1076         fprintf(stderr, "\n");
1077         va_end(ap);
1078 }
1079
1080 struct pair_pos_vs_id
1081 {
1082         uint32_t pos;
1083         uint32_t pack_int_id;
1084 };
1085
1086 static int compare_pair_pos_vs_id(const void *_a, const void *_b)
1087 {
1088         struct pair_pos_vs_id *a = (struct pair_pos_vs_id *)_a;
1089         struct pair_pos_vs_id *b = (struct pair_pos_vs_id *)_b;
1090
1091         return b->pack_int_id - a->pack_int_id;
1092 }
1093
1094 /*
1095  * Limit calls to display_progress() for performance reasons.
1096  * The interval here was arbitrarily chosen.
1097  */
1098 #define SPARSE_PROGRESS_INTERVAL (1 << 12)
1099 #define midx_display_sparse_progress(progress, n) \
1100         do { \
1101                 uint64_t _n = (n); \
1102                 if ((_n & (SPARSE_PROGRESS_INTERVAL - 1)) == 0) \
1103                         display_progress(progress, _n); \
1104         } while (0)
1105
1106 int verify_midx_file(struct repository *r, const char *object_dir, unsigned flags)
1107 {
1108         struct pair_pos_vs_id *pairs = NULL;
1109         uint32_t i;
1110         struct progress *progress = NULL;
1111         struct multi_pack_index *m = load_multi_pack_index(object_dir, 1);
1112         verify_midx_error = 0;
1113
1114         if (!m) {
1115                 int result = 0;
1116                 struct stat sb;
1117                 char *filename = get_midx_filename(object_dir);
1118                 if (!stat(filename, &sb)) {
1119                         error(_("multi-pack-index file exists, but failed to parse"));
1120                         result = 1;
1121                 }
1122                 free(filename);
1123                 return result;
1124         }
1125
1126         if (flags & MIDX_PROGRESS)
1127                 progress = start_delayed_progress(_("Looking for referenced packfiles"),
1128                                           m->num_packs);
1129         for (i = 0; i < m->num_packs; i++) {
1130                 if (prepare_midx_pack(r, m, i))
1131                         midx_report("failed to load pack in position %d", i);
1132
1133                 display_progress(progress, i + 1);
1134         }
1135         stop_progress(&progress);
1136
1137         for (i = 0; i < 255; i++) {
1138                 uint32_t oid_fanout1 = ntohl(m->chunk_oid_fanout[i]);
1139                 uint32_t oid_fanout2 = ntohl(m->chunk_oid_fanout[i + 1]);
1140
1141                 if (oid_fanout1 > oid_fanout2)
1142                         midx_report(_("oid fanout out of order: fanout[%d] = %"PRIx32" > %"PRIx32" = fanout[%d]"),
1143                                     i, oid_fanout1, oid_fanout2, i + 1);
1144         }
1145
1146         if (m->num_objects == 0) {
1147                 midx_report(_("the midx contains no oid"));
1148                 /*
1149                  * Remaining tests assume that we have objects, so we can
1150                  * return here.
1151                  */
1152                 return verify_midx_error;
1153         }
1154
1155         if (flags & MIDX_PROGRESS)
1156                 progress = start_sparse_progress(_("Verifying OID order in multi-pack-index"),
1157                                                  m->num_objects - 1);
1158         for (i = 0; i < m->num_objects - 1; i++) {
1159                 struct object_id oid1, oid2;
1160
1161                 nth_midxed_object_oid(&oid1, m, i);
1162                 nth_midxed_object_oid(&oid2, m, i + 1);
1163
1164                 if (oidcmp(&oid1, &oid2) >= 0)
1165                         midx_report(_("oid lookup out of order: oid[%d] = %s >= %s = oid[%d]"),
1166                                     i, oid_to_hex(&oid1), oid_to_hex(&oid2), i + 1);
1167
1168                 midx_display_sparse_progress(progress, i + 1);
1169         }
1170         stop_progress(&progress);
1171
1172         /*
1173          * Create an array mapping each object to its packfile id.  Sort it
1174          * to group the objects by packfile.  Use this permutation to visit
1175          * each of the objects and only require 1 packfile to be open at a
1176          * time.
1177          */
1178         ALLOC_ARRAY(pairs, m->num_objects);
1179         for (i = 0; i < m->num_objects; i++) {
1180                 pairs[i].pos = i;
1181                 pairs[i].pack_int_id = nth_midxed_pack_int_id(m, i);
1182         }
1183
1184         if (flags & MIDX_PROGRESS)
1185                 progress = start_sparse_progress(_("Sorting objects by packfile"),
1186                                                  m->num_objects);
1187         display_progress(progress, 0); /* TODO: Measure QSORT() progress */
1188         QSORT(pairs, m->num_objects, compare_pair_pos_vs_id);
1189         stop_progress(&progress);
1190
1191         if (flags & MIDX_PROGRESS)
1192                 progress = start_sparse_progress(_("Verifying object offsets"), m->num_objects);
1193         for (i = 0; i < m->num_objects; i++) {
1194                 struct object_id oid;
1195                 struct pack_entry e;
1196                 off_t m_offset, p_offset;
1197
1198                 if (i > 0 && pairs[i-1].pack_int_id != pairs[i].pack_int_id &&
1199                     m->packs[pairs[i-1].pack_int_id])
1200                 {
1201                         close_pack_fd(m->packs[pairs[i-1].pack_int_id]);
1202                         close_pack_index(m->packs[pairs[i-1].pack_int_id]);
1203                 }
1204
1205                 nth_midxed_object_oid(&oid, m, pairs[i].pos);
1206
1207                 if (!fill_midx_entry(r, &oid, &e, m)) {
1208                         midx_report(_("failed to load pack entry for oid[%d] = %s"),
1209                                     pairs[i].pos, oid_to_hex(&oid));
1210                         continue;
1211                 }
1212
1213                 if (open_pack_index(e.p)) {
1214                         midx_report(_("failed to load pack-index for packfile %s"),
1215                                     e.p->pack_name);
1216                         break;
1217                 }
1218
1219                 m_offset = e.offset;
1220                 p_offset = find_pack_entry_one(oid.hash, e.p);
1221
1222                 if (m_offset != p_offset)
1223                         midx_report(_("incorrect object offset for oid[%d] = %s: %"PRIx64" != %"PRIx64),
1224                                     pairs[i].pos, oid_to_hex(&oid), m_offset, p_offset);
1225
1226                 midx_display_sparse_progress(progress, i + 1);
1227         }
1228         stop_progress(&progress);
1229
1230         free(pairs);
1231
1232         return verify_midx_error;
1233 }
1234
1235 int expire_midx_packs(struct repository *r, const char *object_dir, unsigned flags)
1236 {
1237         uint32_t i, *count, result = 0;
1238         struct string_list packs_to_drop = STRING_LIST_INIT_DUP;
1239         struct multi_pack_index *m = load_multi_pack_index(object_dir, 1);
1240         struct progress *progress = NULL;
1241
1242         if (!m)
1243                 return 0;
1244
1245         count = xcalloc(m->num_packs, sizeof(uint32_t));
1246
1247         if (flags & MIDX_PROGRESS)
1248                 progress = start_delayed_progress(_("Counting referenced objects"),
1249                                           m->num_objects);
1250         for (i = 0; i < m->num_objects; i++) {
1251                 int pack_int_id = nth_midxed_pack_int_id(m, i);
1252                 count[pack_int_id]++;
1253                 display_progress(progress, i + 1);
1254         }
1255         stop_progress(&progress);
1256
1257         if (flags & MIDX_PROGRESS)
1258                 progress = start_delayed_progress(_("Finding and deleting unreferenced packfiles"),
1259                                           m->num_packs);
1260         for (i = 0; i < m->num_packs; i++) {
1261                 char *pack_name;
1262                 display_progress(progress, i + 1);
1263
1264                 if (count[i])
1265                         continue;
1266
1267                 if (prepare_midx_pack(r, m, i))
1268                         continue;
1269
1270                 if (m->packs[i]->pack_keep)
1271                         continue;
1272
1273                 pack_name = xstrdup(m->packs[i]->pack_name);
1274                 close_pack(m->packs[i]);
1275
1276                 string_list_insert(&packs_to_drop, m->pack_names[i]);
1277                 unlink_pack_path(pack_name, 0);
1278                 free(pack_name);
1279         }
1280         stop_progress(&progress);
1281
1282         free(count);
1283
1284         if (packs_to_drop.nr)
1285                 result = write_midx_internal(object_dir, m, &packs_to_drop, flags);
1286
1287         string_list_clear(&packs_to_drop, 0);
1288         return result;
1289 }
1290
1291 struct repack_info {
1292         timestamp_t mtime;
1293         uint32_t referenced_objects;
1294         uint32_t pack_int_id;
1295 };
1296
1297 static int compare_by_mtime(const void *a_, const void *b_)
1298 {
1299         const struct repack_info *a, *b;
1300
1301         a = (const struct repack_info *)a_;
1302         b = (const struct repack_info *)b_;
1303
1304         if (a->mtime < b->mtime)
1305                 return -1;
1306         if (a->mtime > b->mtime)
1307                 return 1;
1308         return 0;
1309 }
1310
1311 static int fill_included_packs_all(struct repository *r,
1312                                    struct multi_pack_index *m,
1313                                    unsigned char *include_pack)
1314 {
1315         uint32_t i, count = 0;
1316         int pack_kept_objects = 0;
1317
1318         repo_config_get_bool(r, "repack.packkeptobjects", &pack_kept_objects);
1319
1320         for (i = 0; i < m->num_packs; i++) {
1321                 if (prepare_midx_pack(r, m, i))
1322                         continue;
1323                 if (!pack_kept_objects && m->packs[i]->pack_keep)
1324                         continue;
1325
1326                 include_pack[i] = 1;
1327                 count++;
1328         }
1329
1330         return count < 2;
1331 }
1332
1333 static int fill_included_packs_batch(struct repository *r,
1334                                      struct multi_pack_index *m,
1335                                      unsigned char *include_pack,
1336                                      size_t batch_size)
1337 {
1338         uint32_t i, packs_to_repack;
1339         size_t total_size;
1340         struct repack_info *pack_info = xcalloc(m->num_packs, sizeof(struct repack_info));
1341         int pack_kept_objects = 0;
1342
1343         repo_config_get_bool(r, "repack.packkeptobjects", &pack_kept_objects);
1344
1345         for (i = 0; i < m->num_packs; i++) {
1346                 pack_info[i].pack_int_id = i;
1347
1348                 if (prepare_midx_pack(r, m, i))
1349                         continue;
1350
1351                 pack_info[i].mtime = m->packs[i]->mtime;
1352         }
1353
1354         for (i = 0; batch_size && i < m->num_objects; i++) {
1355                 uint32_t pack_int_id = nth_midxed_pack_int_id(m, i);
1356                 pack_info[pack_int_id].referenced_objects++;
1357         }
1358
1359         QSORT(pack_info, m->num_packs, compare_by_mtime);
1360
1361         total_size = 0;
1362         packs_to_repack = 0;
1363         for (i = 0; total_size < batch_size && i < m->num_packs; i++) {
1364                 int pack_int_id = pack_info[i].pack_int_id;
1365                 struct packed_git *p = m->packs[pack_int_id];
1366                 size_t expected_size;
1367
1368                 if (!p)
1369                         continue;
1370                 if (!pack_kept_objects && p->pack_keep)
1371                         continue;
1372                 if (open_pack_index(p) || !p->num_objects)
1373                         continue;
1374
1375                 expected_size = (size_t)(p->pack_size
1376                                          * pack_info[i].referenced_objects);
1377                 expected_size /= p->num_objects;
1378
1379                 if (expected_size >= batch_size)
1380                         continue;
1381
1382                 packs_to_repack++;
1383                 total_size += expected_size;
1384                 include_pack[pack_int_id] = 1;
1385         }
1386
1387         free(pack_info);
1388
1389         if (packs_to_repack < 2)
1390                 return 1;
1391
1392         return 0;
1393 }
1394
1395 int midx_repack(struct repository *r, const char *object_dir, size_t batch_size, unsigned flags)
1396 {
1397         int result = 0;
1398         uint32_t i;
1399         unsigned char *include_pack;
1400         struct child_process cmd = CHILD_PROCESS_INIT;
1401         FILE *cmd_in;
1402         struct strbuf base_name = STRBUF_INIT;
1403         struct multi_pack_index *m = load_multi_pack_index(object_dir, 1);
1404
1405         /*
1406          * When updating the default for these configuration
1407          * variables in builtin/repack.c, these must be adjusted
1408          * to match.
1409          */
1410         int delta_base_offset = 1;
1411         int use_delta_islands = 0;
1412
1413         if (!m)
1414                 return 0;
1415
1416         include_pack = xcalloc(m->num_packs, sizeof(unsigned char));
1417
1418         if (batch_size) {
1419                 if (fill_included_packs_batch(r, m, include_pack, batch_size))
1420                         goto cleanup;
1421         } else if (fill_included_packs_all(r, m, include_pack))
1422                 goto cleanup;
1423
1424         repo_config_get_bool(r, "repack.usedeltabaseoffset", &delta_base_offset);
1425         repo_config_get_bool(r, "repack.usedeltaislands", &use_delta_islands);
1426
1427         strvec_push(&cmd.args, "pack-objects");
1428
1429         strbuf_addstr(&base_name, object_dir);
1430         strbuf_addstr(&base_name, "/pack/pack");
1431         strvec_push(&cmd.args, base_name.buf);
1432
1433         if (delta_base_offset)
1434                 strvec_push(&cmd.args, "--delta-base-offset");
1435         if (use_delta_islands)
1436                 strvec_push(&cmd.args, "--delta-islands");
1437
1438         if (flags & MIDX_PROGRESS)
1439                 strvec_push(&cmd.args, "--progress");
1440         else
1441                 strvec_push(&cmd.args, "-q");
1442
1443         strbuf_release(&base_name);
1444
1445         cmd.git_cmd = 1;
1446         cmd.in = cmd.out = -1;
1447
1448         if (start_command(&cmd)) {
1449                 error(_("could not start pack-objects"));
1450                 result = 1;
1451                 goto cleanup;
1452         }
1453
1454         cmd_in = xfdopen(cmd.in, "w");
1455
1456         for (i = 0; i < m->num_objects; i++) {
1457                 struct object_id oid;
1458                 uint32_t pack_int_id = nth_midxed_pack_int_id(m, i);
1459
1460                 if (!include_pack[pack_int_id])
1461                         continue;
1462
1463                 nth_midxed_object_oid(&oid, m, i);
1464                 fprintf(cmd_in, "%s\n", oid_to_hex(&oid));
1465         }
1466         fclose(cmd_in);
1467
1468         if (finish_command(&cmd)) {
1469                 error(_("could not finish pack-objects"));
1470                 result = 1;
1471                 goto cleanup;
1472         }
1473
1474         result = write_midx_internal(object_dir, m, NULL, flags);
1475         m = NULL;
1476
1477 cleanup:
1478         if (m)
1479                 close_midx(m);
1480         free(include_pack);
1481         return result;
1482 }