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