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