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