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