Merge branch 'ma/doc-sha-256-is-experimental'
[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                 m->next = r->objects->multi_pack_index;
420                 r->objects->multi_pack_index = m;
421                 return 1;
422         }
423
424         return 0;
425 }
426
427 static size_t write_midx_header(struct hashfile *f,
428                                 unsigned char num_chunks,
429                                 uint32_t num_packs)
430 {
431         unsigned char byte_values[4];
432
433         hashwrite_be32(f, MIDX_SIGNATURE);
434         byte_values[0] = MIDX_VERSION;
435         byte_values[1] = oid_version();
436         byte_values[2] = num_chunks;
437         byte_values[3] = 0; /* unused */
438         hashwrite(f, byte_values, sizeof(byte_values));
439         hashwrite_be32(f, num_packs);
440
441         return MIDX_HEADER_SIZE;
442 }
443
444 struct pack_info {
445         uint32_t orig_pack_int_id;
446         char *pack_name;
447         struct packed_git *p;
448         unsigned expired : 1;
449 };
450
451 static int pack_info_compare(const void *_a, const void *_b)
452 {
453         struct pack_info *a = (struct pack_info *)_a;
454         struct pack_info *b = (struct pack_info *)_b;
455         return strcmp(a->pack_name, b->pack_name);
456 }
457
458 struct pack_list {
459         struct pack_info *info;
460         uint32_t nr;
461         uint32_t alloc;
462         struct multi_pack_index *m;
463         struct progress *progress;
464         unsigned pack_paths_checked;
465 };
466
467 static void add_pack_to_midx(const char *full_path, size_t full_path_len,
468                              const char *file_name, void *data)
469 {
470         struct pack_list *packs = (struct pack_list *)data;
471
472         if (ends_with(file_name, ".idx")) {
473                 display_progress(packs->progress, ++packs->pack_paths_checked);
474                 if (packs->m && midx_contains_pack(packs->m, file_name))
475                         return;
476
477                 ALLOC_GROW(packs->info, packs->nr + 1, packs->alloc);
478
479                 packs->info[packs->nr].p = add_packed_git(full_path,
480                                                           full_path_len,
481                                                           0);
482
483                 if (!packs->info[packs->nr].p) {
484                         warning(_("failed to add packfile '%s'"),
485                                 full_path);
486                         return;
487                 }
488
489                 if (open_pack_index(packs->info[packs->nr].p)) {
490                         warning(_("failed to open pack-index '%s'"),
491                                 full_path);
492                         close_pack(packs->info[packs->nr].p);
493                         FREE_AND_NULL(packs->info[packs->nr].p);
494                         return;
495                 }
496
497                 packs->info[packs->nr].pack_name = xstrdup(file_name);
498                 packs->info[packs->nr].orig_pack_int_id = packs->nr;
499                 packs->info[packs->nr].expired = 0;
500                 packs->nr++;
501         }
502 }
503
504 struct pack_midx_entry {
505         struct object_id oid;
506         uint32_t pack_int_id;
507         time_t pack_mtime;
508         uint64_t offset;
509 };
510
511 static int midx_oid_compare(const void *_a, const void *_b)
512 {
513         const struct pack_midx_entry *a = (const struct pack_midx_entry *)_a;
514         const struct pack_midx_entry *b = (const struct pack_midx_entry *)_b;
515         int cmp = oidcmp(&a->oid, &b->oid);
516
517         if (cmp)
518                 return cmp;
519
520         if (a->pack_mtime > b->pack_mtime)
521                 return -1;
522         else if (a->pack_mtime < b->pack_mtime)
523                 return 1;
524
525         return a->pack_int_id - b->pack_int_id;
526 }
527
528 static int nth_midxed_pack_midx_entry(struct multi_pack_index *m,
529                                       struct pack_midx_entry *e,
530                                       uint32_t pos)
531 {
532         if (pos >= m->num_objects)
533                 return 1;
534
535         nth_midxed_object_oid(&e->oid, m, pos);
536         e->pack_int_id = nth_midxed_pack_int_id(m, pos);
537         e->offset = nth_midxed_offset(m, pos);
538
539         /* consider objects in midx to be from "old" packs */
540         e->pack_mtime = 0;
541         return 0;
542 }
543
544 static void fill_pack_entry(uint32_t pack_int_id,
545                             struct packed_git *p,
546                             uint32_t cur_object,
547                             struct pack_midx_entry *entry)
548 {
549         if (nth_packed_object_id(&entry->oid, p, cur_object) < 0)
550                 die(_("failed to locate object %d in packfile"), cur_object);
551
552         entry->pack_int_id = pack_int_id;
553         entry->pack_mtime = p->mtime;
554
555         entry->offset = nth_packed_object_offset(p, cur_object);
556 }
557
558 /*
559  * It is possible to artificially get into a state where there are many
560  * duplicate copies of objects. That can create high memory pressure if
561  * we are to create a list of all objects before de-duplication. To reduce
562  * this memory pressure without a significant performance drop, automatically
563  * group objects by the first byte of their object id. Use the IDX fanout
564  * tables to group the data, copy to a local array, then sort.
565  *
566  * Copy only the de-duplicated entries (selected by most-recent modified time
567  * of a packfile containing the object).
568  */
569 static struct pack_midx_entry *get_sorted_entries(struct multi_pack_index *m,
570                                                   struct pack_info *info,
571                                                   uint32_t nr_packs,
572                                                   uint32_t *nr_objects)
573 {
574         uint32_t cur_fanout, cur_pack, cur_object;
575         uint32_t alloc_fanout, alloc_objects, total_objects = 0;
576         struct pack_midx_entry *entries_by_fanout = NULL;
577         struct pack_midx_entry *deduplicated_entries = NULL;
578         uint32_t start_pack = m ? m->num_packs : 0;
579
580         for (cur_pack = start_pack; cur_pack < nr_packs; cur_pack++)
581                 total_objects += info[cur_pack].p->num_objects;
582
583         /*
584          * As we de-duplicate by fanout value, we expect the fanout
585          * slices to be evenly distributed, with some noise. Hence,
586          * allocate slightly more than one 256th.
587          */
588         alloc_objects = alloc_fanout = total_objects > 3200 ? total_objects / 200 : 16;
589
590         ALLOC_ARRAY(entries_by_fanout, alloc_fanout);
591         ALLOC_ARRAY(deduplicated_entries, alloc_objects);
592         *nr_objects = 0;
593
594         for (cur_fanout = 0; cur_fanout < 256; cur_fanout++) {
595                 uint32_t nr_fanout = 0;
596
597                 if (m) {
598                         uint32_t start = 0, end;
599
600                         if (cur_fanout)
601                                 start = ntohl(m->chunk_oid_fanout[cur_fanout - 1]);
602                         end = ntohl(m->chunk_oid_fanout[cur_fanout]);
603
604                         for (cur_object = start; cur_object < end; cur_object++) {
605                                 ALLOC_GROW(entries_by_fanout, nr_fanout + 1, alloc_fanout);
606                                 nth_midxed_pack_midx_entry(m,
607                                                            &entries_by_fanout[nr_fanout],
608                                                            cur_object);
609                                 nr_fanout++;
610                         }
611                 }
612
613                 for (cur_pack = start_pack; cur_pack < nr_packs; cur_pack++) {
614                         uint32_t start = 0, end;
615
616                         if (cur_fanout)
617                                 start = get_pack_fanout(info[cur_pack].p, cur_fanout - 1);
618                         end = get_pack_fanout(info[cur_pack].p, cur_fanout);
619
620                         for (cur_object = start; cur_object < end; cur_object++) {
621                                 ALLOC_GROW(entries_by_fanout, nr_fanout + 1, alloc_fanout);
622                                 fill_pack_entry(cur_pack, info[cur_pack].p, cur_object, &entries_by_fanout[nr_fanout]);
623                                 nr_fanout++;
624                         }
625                 }
626
627                 QSORT(entries_by_fanout, nr_fanout, midx_oid_compare);
628
629                 /*
630                  * The batch is now sorted by OID and then mtime (descending).
631                  * Take only the first duplicate.
632                  */
633                 for (cur_object = 0; cur_object < nr_fanout; cur_object++) {
634                         if (cur_object && oideq(&entries_by_fanout[cur_object - 1].oid,
635                                                 &entries_by_fanout[cur_object].oid))
636                                 continue;
637
638                         ALLOC_GROW(deduplicated_entries, *nr_objects + 1, alloc_objects);
639                         memcpy(&deduplicated_entries[*nr_objects],
640                                &entries_by_fanout[cur_object],
641                                sizeof(struct pack_midx_entry));
642                         (*nr_objects)++;
643                 }
644         }
645
646         free(entries_by_fanout);
647         return deduplicated_entries;
648 }
649
650 static size_t write_midx_pack_names(struct hashfile *f,
651                                     struct pack_info *info,
652                                     uint32_t num_packs)
653 {
654         uint32_t i;
655         unsigned char padding[MIDX_CHUNK_ALIGNMENT];
656         size_t written = 0;
657
658         for (i = 0; i < num_packs; i++) {
659                 size_t writelen;
660
661                 if (info[i].expired)
662                         continue;
663
664                 if (i && strcmp(info[i].pack_name, info[i - 1].pack_name) <= 0)
665                         BUG("incorrect pack-file order: %s before %s",
666                             info[i - 1].pack_name,
667                             info[i].pack_name);
668
669                 writelen = strlen(info[i].pack_name) + 1;
670                 hashwrite(f, info[i].pack_name, writelen);
671                 written += writelen;
672         }
673
674         /* add padding to be aligned */
675         i = MIDX_CHUNK_ALIGNMENT - (written % MIDX_CHUNK_ALIGNMENT);
676         if (i < MIDX_CHUNK_ALIGNMENT) {
677                 memset(padding, 0, sizeof(padding));
678                 hashwrite(f, padding, i);
679                 written += i;
680         }
681
682         return written;
683 }
684
685 static size_t write_midx_oid_fanout(struct hashfile *f,
686                                     struct pack_midx_entry *objects,
687                                     uint32_t nr_objects)
688 {
689         struct pack_midx_entry *list = objects;
690         struct pack_midx_entry *last = objects + nr_objects;
691         uint32_t count = 0;
692         uint32_t i;
693
694         /*
695         * Write the first-level table (the list is sorted,
696         * but we use a 256-entry lookup to be able to avoid
697         * having to do eight extra binary search iterations).
698         */
699         for (i = 0; i < 256; i++) {
700                 struct pack_midx_entry *next = list;
701
702                 while (next < last && next->oid.hash[0] == i) {
703                         count++;
704                         next++;
705                 }
706
707                 hashwrite_be32(f, count);
708                 list = next;
709         }
710
711         return MIDX_CHUNK_FANOUT_SIZE;
712 }
713
714 static size_t write_midx_oid_lookup(struct hashfile *f, unsigned char hash_len,
715                                     struct pack_midx_entry *objects,
716                                     uint32_t nr_objects)
717 {
718         struct pack_midx_entry *list = objects;
719         uint32_t i;
720         size_t written = 0;
721
722         for (i = 0; i < nr_objects; i++) {
723                 struct pack_midx_entry *obj = list++;
724
725                 if (i < nr_objects - 1) {
726                         struct pack_midx_entry *next = list;
727                         if (oidcmp(&obj->oid, &next->oid) >= 0)
728                                 BUG("OIDs not in order: %s >= %s",
729                                     oid_to_hex(&obj->oid),
730                                     oid_to_hex(&next->oid));
731                 }
732
733                 hashwrite(f, obj->oid.hash, (int)hash_len);
734                 written += hash_len;
735         }
736
737         return written;
738 }
739
740 static size_t write_midx_object_offsets(struct hashfile *f, int large_offset_needed,
741                                         uint32_t *perm,
742                                         struct pack_midx_entry *objects, uint32_t nr_objects)
743 {
744         struct pack_midx_entry *list = objects;
745         uint32_t i, nr_large_offset = 0;
746         size_t written = 0;
747
748         for (i = 0; i < nr_objects; i++) {
749                 struct pack_midx_entry *obj = list++;
750
751                 if (perm[obj->pack_int_id] == PACK_EXPIRED)
752                         BUG("object %s is in an expired pack with int-id %d",
753                             oid_to_hex(&obj->oid),
754                             obj->pack_int_id);
755
756                 hashwrite_be32(f, perm[obj->pack_int_id]);
757
758                 if (large_offset_needed && obj->offset >> 31)
759                         hashwrite_be32(f, MIDX_LARGE_OFFSET_NEEDED | nr_large_offset++);
760                 else if (!large_offset_needed && obj->offset >> 32)
761                         BUG("object %s requires a large offset (%"PRIx64") but the MIDX is not writing large offsets!",
762                             oid_to_hex(&obj->oid),
763                             obj->offset);
764                 else
765                         hashwrite_be32(f, (uint32_t)obj->offset);
766
767                 written += MIDX_CHUNK_OFFSET_WIDTH;
768         }
769
770         return written;
771 }
772
773 static size_t write_midx_large_offsets(struct hashfile *f, uint32_t nr_large_offset,
774                                        struct pack_midx_entry *objects, uint32_t nr_objects)
775 {
776         struct pack_midx_entry *list = objects, *end = objects + nr_objects;
777         size_t written = 0;
778
779         while (nr_large_offset) {
780                 struct pack_midx_entry *obj;
781                 uint64_t offset;
782
783                 if (list >= end)
784                         BUG("too many large-offset objects");
785
786                 obj = list++;
787                 offset = obj->offset;
788
789                 if (!(offset >> 31))
790                         continue;
791
792                 hashwrite_be32(f, offset >> 32);
793                 hashwrite_be32(f, offset & 0xffffffffUL);
794                 written += 2 * sizeof(uint32_t);
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 pack_list packs;
811         uint32_t *pack_perm = NULL;
812         uint64_t written = 0;
813         uint32_t chunk_ids[MIDX_MAX_CHUNKS + 1];
814         uint64_t chunk_offsets[MIDX_MAX_CHUNKS + 1];
815         uint32_t nr_entries, num_large_offsets = 0;
816         struct pack_midx_entry *entries = NULL;
817         struct progress *progress = NULL;
818         int large_offsets_needed = 0;
819         int pack_name_concat_len = 0;
820         int dropped_packs = 0;
821         int result = 0;
822
823         midx_name = get_midx_filename(object_dir);
824         if (safe_create_leading_directories(midx_name))
825                 die_errno(_("unable to create leading directories of %s"),
826                           midx_name);
827
828         if (m)
829                 packs.m = m;
830         else
831                 packs.m = load_multi_pack_index(object_dir, 1);
832
833         packs.nr = 0;
834         packs.alloc = packs.m ? packs.m->num_packs : 16;
835         packs.info = NULL;
836         ALLOC_ARRAY(packs.info, packs.alloc);
837
838         if (packs.m) {
839                 for (i = 0; i < packs.m->num_packs; i++) {
840                         ALLOC_GROW(packs.info, packs.nr + 1, packs.alloc);
841
842                         packs.info[packs.nr].orig_pack_int_id = i;
843                         packs.info[packs.nr].pack_name = xstrdup(packs.m->pack_names[i]);
844                         packs.info[packs.nr].p = NULL;
845                         packs.info[packs.nr].expired = 0;
846                         packs.nr++;
847                 }
848         }
849
850         packs.pack_paths_checked = 0;
851         if (flags & MIDX_PROGRESS)
852                 packs.progress = start_progress(_("Adding packfiles to multi-pack-index"), 0);
853         else
854                 packs.progress = NULL;
855
856         for_each_file_in_pack_dir(object_dir, add_pack_to_midx, &packs);
857         stop_progress(&packs.progress);
858
859         if (packs.m && packs.nr == packs.m->num_packs && !packs_to_drop)
860                 goto cleanup;
861
862         entries = get_sorted_entries(packs.m, packs.info, packs.nr, &nr_entries);
863
864         for (i = 0; i < nr_entries; i++) {
865                 if (entries[i].offset > 0x7fffffff)
866                         num_large_offsets++;
867                 if (entries[i].offset > 0xffffffff)
868                         large_offsets_needed = 1;
869         }
870
871         QSORT(packs.info, packs.nr, pack_info_compare);
872
873         if (packs_to_drop && packs_to_drop->nr) {
874                 int drop_index = 0;
875                 int missing_drops = 0;
876
877                 for (i = 0; i < packs.nr && drop_index < packs_to_drop->nr; i++) {
878                         int cmp = strcmp(packs.info[i].pack_name,
879                                          packs_to_drop->items[drop_index].string);
880
881                         if (!cmp) {
882                                 drop_index++;
883                                 packs.info[i].expired = 1;
884                         } else if (cmp > 0) {
885                                 error(_("did not see pack-file %s to drop"),
886                                       packs_to_drop->items[drop_index].string);
887                                 drop_index++;
888                                 missing_drops++;
889                                 i--;
890                         } else {
891                                 packs.info[i].expired = 0;
892                         }
893                 }
894
895                 if (missing_drops) {
896                         result = 1;
897                         goto cleanup;
898                 }
899         }
900
901         /*
902          * pack_perm stores a permutation between pack-int-ids from the
903          * previous multi-pack-index to the new one we are writing:
904          *
905          * pack_perm[old_id] = new_id
906          */
907         ALLOC_ARRAY(pack_perm, packs.nr);
908         for (i = 0; i < packs.nr; i++) {
909                 if (packs.info[i].expired) {
910                         dropped_packs++;
911                         pack_perm[packs.info[i].orig_pack_int_id] = PACK_EXPIRED;
912                 } else {
913                         pack_perm[packs.info[i].orig_pack_int_id] = i - dropped_packs;
914                 }
915         }
916
917         for (i = 0; i < packs.nr; i++) {
918                 if (!packs.info[i].expired)
919                         pack_name_concat_len += strlen(packs.info[i].pack_name) + 1;
920         }
921
922         if (pack_name_concat_len % MIDX_CHUNK_ALIGNMENT)
923                 pack_name_concat_len += MIDX_CHUNK_ALIGNMENT -
924                                         (pack_name_concat_len % MIDX_CHUNK_ALIGNMENT);
925
926         hold_lock_file_for_update(&lk, midx_name, LOCK_DIE_ON_ERROR);
927         f = hashfd(lk.tempfile->fd, lk.tempfile->filename.buf);
928         FREE_AND_NULL(midx_name);
929
930         if (packs.m)
931                 close_midx(packs.m);
932
933         cur_chunk = 0;
934         num_chunks = large_offsets_needed ? 5 : 4;
935
936         if (packs.nr - dropped_packs == 0) {
937                 error(_("no pack files to index."));
938                 result = 1;
939                 goto cleanup;
940         }
941
942         written = write_midx_header(f, num_chunks, packs.nr - dropped_packs);
943
944         chunk_ids[cur_chunk] = MIDX_CHUNKID_PACKNAMES;
945         chunk_offsets[cur_chunk] = written + (num_chunks + 1) * MIDX_CHUNKLOOKUP_WIDTH;
946
947         cur_chunk++;
948         chunk_ids[cur_chunk] = MIDX_CHUNKID_OIDFANOUT;
949         chunk_offsets[cur_chunk] = chunk_offsets[cur_chunk - 1] + pack_name_concat_len;
950
951         cur_chunk++;
952         chunk_ids[cur_chunk] = MIDX_CHUNKID_OIDLOOKUP;
953         chunk_offsets[cur_chunk] = chunk_offsets[cur_chunk - 1] + MIDX_CHUNK_FANOUT_SIZE;
954
955         cur_chunk++;
956         chunk_ids[cur_chunk] = MIDX_CHUNKID_OBJECTOFFSETS;
957         chunk_offsets[cur_chunk] = chunk_offsets[cur_chunk - 1] + nr_entries * the_hash_algo->rawsz;
958
959         cur_chunk++;
960         chunk_offsets[cur_chunk] = chunk_offsets[cur_chunk - 1] + nr_entries * MIDX_CHUNK_OFFSET_WIDTH;
961         if (large_offsets_needed) {
962                 chunk_ids[cur_chunk] = MIDX_CHUNKID_LARGEOFFSETS;
963
964                 cur_chunk++;
965                 chunk_offsets[cur_chunk] = chunk_offsets[cur_chunk - 1] +
966                                            num_large_offsets * MIDX_CHUNK_LARGE_OFFSET_WIDTH;
967         }
968
969         chunk_ids[cur_chunk] = 0;
970
971         for (i = 0; i <= num_chunks; i++) {
972                 if (i && chunk_offsets[i] < chunk_offsets[i - 1])
973                         BUG("incorrect chunk offsets: %"PRIu64" before %"PRIu64,
974                             chunk_offsets[i - 1],
975                             chunk_offsets[i]);
976
977                 if (chunk_offsets[i] % MIDX_CHUNK_ALIGNMENT)
978                         BUG("chunk offset %"PRIu64" is not properly aligned",
979                             chunk_offsets[i]);
980
981                 hashwrite_be32(f, chunk_ids[i]);
982                 hashwrite_be32(f, chunk_offsets[i] >> 32);
983                 hashwrite_be32(f, chunk_offsets[i]);
984
985                 written += MIDX_CHUNKLOOKUP_WIDTH;
986         }
987
988         if (flags & MIDX_PROGRESS)
989                 progress = start_progress(_("Writing chunks to multi-pack-index"),
990                                           num_chunks);
991         for (i = 0; i < num_chunks; i++) {
992                 if (written != chunk_offsets[i])
993                         BUG("incorrect chunk offset (%"PRIu64" != %"PRIu64") for chunk id %"PRIx32,
994                             chunk_offsets[i],
995                             written,
996                             chunk_ids[i]);
997
998                 switch (chunk_ids[i]) {
999                         case MIDX_CHUNKID_PACKNAMES:
1000                                 written += write_midx_pack_names(f, packs.info, packs.nr);
1001                                 break;
1002
1003                         case MIDX_CHUNKID_OIDFANOUT:
1004                                 written += write_midx_oid_fanout(f, entries, nr_entries);
1005                                 break;
1006
1007                         case MIDX_CHUNKID_OIDLOOKUP:
1008                                 written += write_midx_oid_lookup(f, the_hash_algo->rawsz, entries, nr_entries);
1009                                 break;
1010
1011                         case MIDX_CHUNKID_OBJECTOFFSETS:
1012                                 written += write_midx_object_offsets(f, large_offsets_needed, pack_perm, entries, nr_entries);
1013                                 break;
1014
1015                         case MIDX_CHUNKID_LARGEOFFSETS:
1016                                 written += write_midx_large_offsets(f, num_large_offsets, entries, nr_entries);
1017                                 break;
1018
1019                         default:
1020                                 BUG("trying to write unknown chunk id %"PRIx32,
1021                                     chunk_ids[i]);
1022                 }
1023
1024                 display_progress(progress, i + 1);
1025         }
1026         stop_progress(&progress);
1027
1028         if (written != chunk_offsets[num_chunks])
1029                 BUG("incorrect final offset %"PRIu64" != %"PRIu64,
1030                     written,
1031                     chunk_offsets[num_chunks]);
1032
1033         finalize_hashfile(f, NULL, CSUM_FSYNC | CSUM_HASH_IN_STREAM);
1034         commit_lock_file(&lk);
1035
1036 cleanup:
1037         for (i = 0; i < packs.nr; i++) {
1038                 if (packs.info[i].p) {
1039                         close_pack(packs.info[i].p);
1040                         free(packs.info[i].p);
1041                 }
1042                 free(packs.info[i].pack_name);
1043         }
1044
1045         free(packs.info);
1046         free(entries);
1047         free(pack_perm);
1048         free(midx_name);
1049         return result;
1050 }
1051
1052 int write_midx_file(const char *object_dir, unsigned flags)
1053 {
1054         return write_midx_internal(object_dir, NULL, NULL, flags);
1055 }
1056
1057 void clear_midx_file(struct repository *r)
1058 {
1059         char *midx = get_midx_filename(r->objects->odb->path);
1060
1061         if (r->objects && r->objects->multi_pack_index) {
1062                 close_midx(r->objects->multi_pack_index);
1063                 r->objects->multi_pack_index = NULL;
1064         }
1065
1066         if (remove_path(midx))
1067                 die(_("failed to clear multi-pack-index at %s"), midx);
1068
1069         free(midx);
1070 }
1071
1072 static int verify_midx_error;
1073
1074 static void midx_report(const char *fmt, ...)
1075 {
1076         va_list ap;
1077         verify_midx_error = 1;
1078         va_start(ap, fmt);
1079         vfprintf(stderr, fmt, ap);
1080         fprintf(stderr, "\n");
1081         va_end(ap);
1082 }
1083
1084 struct pair_pos_vs_id
1085 {
1086         uint32_t pos;
1087         uint32_t pack_int_id;
1088 };
1089
1090 static int compare_pair_pos_vs_id(const void *_a, const void *_b)
1091 {
1092         struct pair_pos_vs_id *a = (struct pair_pos_vs_id *)_a;
1093         struct pair_pos_vs_id *b = (struct pair_pos_vs_id *)_b;
1094
1095         return b->pack_int_id - a->pack_int_id;
1096 }
1097
1098 /*
1099  * Limit calls to display_progress() for performance reasons.
1100  * The interval here was arbitrarily chosen.
1101  */
1102 #define SPARSE_PROGRESS_INTERVAL (1 << 12)
1103 #define midx_display_sparse_progress(progress, n) \
1104         do { \
1105                 uint64_t _n = (n); \
1106                 if ((_n & (SPARSE_PROGRESS_INTERVAL - 1)) == 0) \
1107                         display_progress(progress, _n); \
1108         } while (0)
1109
1110 int verify_midx_file(struct repository *r, const char *object_dir, unsigned flags)
1111 {
1112         struct pair_pos_vs_id *pairs = NULL;
1113         uint32_t i;
1114         struct progress *progress = NULL;
1115         struct multi_pack_index *m = load_multi_pack_index(object_dir, 1);
1116         verify_midx_error = 0;
1117
1118         if (!m) {
1119                 int result = 0;
1120                 struct stat sb;
1121                 char *filename = get_midx_filename(object_dir);
1122                 if (!stat(filename, &sb)) {
1123                         error(_("multi-pack-index file exists, but failed to parse"));
1124                         result = 1;
1125                 }
1126                 free(filename);
1127                 return result;
1128         }
1129
1130         if (flags & MIDX_PROGRESS)
1131                 progress = start_progress(_("Looking for referenced packfiles"),
1132                                           m->num_packs);
1133         for (i = 0; i < m->num_packs; i++) {
1134                 if (prepare_midx_pack(r, m, i))
1135                         midx_report("failed to load pack in position %d", i);
1136
1137                 display_progress(progress, i + 1);
1138         }
1139         stop_progress(&progress);
1140
1141         for (i = 0; i < 255; i++) {
1142                 uint32_t oid_fanout1 = ntohl(m->chunk_oid_fanout[i]);
1143                 uint32_t oid_fanout2 = ntohl(m->chunk_oid_fanout[i + 1]);
1144
1145                 if (oid_fanout1 > oid_fanout2)
1146                         midx_report(_("oid fanout out of order: fanout[%d] = %"PRIx32" > %"PRIx32" = fanout[%d]"),
1147                                     i, oid_fanout1, oid_fanout2, i + 1);
1148         }
1149
1150         if (m->num_objects == 0) {
1151                 midx_report(_("the midx contains no oid"));
1152                 /*
1153                  * Remaining tests assume that we have objects, so we can
1154                  * return here.
1155                  */
1156                 return verify_midx_error;
1157         }
1158
1159         if (flags & MIDX_PROGRESS)
1160                 progress = start_sparse_progress(_("Verifying OID order in multi-pack-index"),
1161                                                  m->num_objects - 1);
1162         for (i = 0; i < m->num_objects - 1; i++) {
1163                 struct object_id oid1, oid2;
1164
1165                 nth_midxed_object_oid(&oid1, m, i);
1166                 nth_midxed_object_oid(&oid2, m, i + 1);
1167
1168                 if (oidcmp(&oid1, &oid2) >= 0)
1169                         midx_report(_("oid lookup out of order: oid[%d] = %s >= %s = oid[%d]"),
1170                                     i, oid_to_hex(&oid1), oid_to_hex(&oid2), i + 1);
1171
1172                 midx_display_sparse_progress(progress, i + 1);
1173         }
1174         stop_progress(&progress);
1175
1176         /*
1177          * Create an array mapping each object to its packfile id.  Sort it
1178          * to group the objects by packfile.  Use this permutation to visit
1179          * each of the objects and only require 1 packfile to be open at a
1180          * time.
1181          */
1182         ALLOC_ARRAY(pairs, m->num_objects);
1183         for (i = 0; i < m->num_objects; i++) {
1184                 pairs[i].pos = i;
1185                 pairs[i].pack_int_id = nth_midxed_pack_int_id(m, i);
1186         }
1187
1188         if (flags & MIDX_PROGRESS)
1189                 progress = start_sparse_progress(_("Sorting objects by packfile"),
1190                                                  m->num_objects);
1191         display_progress(progress, 0); /* TODO: Measure QSORT() progress */
1192         QSORT(pairs, m->num_objects, compare_pair_pos_vs_id);
1193         stop_progress(&progress);
1194
1195         if (flags & MIDX_PROGRESS)
1196                 progress = start_sparse_progress(_("Verifying object offsets"), m->num_objects);
1197         for (i = 0; i < m->num_objects; i++) {
1198                 struct object_id oid;
1199                 struct pack_entry e;
1200                 off_t m_offset, p_offset;
1201
1202                 if (i > 0 && pairs[i-1].pack_int_id != pairs[i].pack_int_id &&
1203                     m->packs[pairs[i-1].pack_int_id])
1204                 {
1205                         close_pack_fd(m->packs[pairs[i-1].pack_int_id]);
1206                         close_pack_index(m->packs[pairs[i-1].pack_int_id]);
1207                 }
1208
1209                 nth_midxed_object_oid(&oid, m, pairs[i].pos);
1210
1211                 if (!fill_midx_entry(r, &oid, &e, m)) {
1212                         midx_report(_("failed to load pack entry for oid[%d] = %s"),
1213                                     pairs[i].pos, oid_to_hex(&oid));
1214                         continue;
1215                 }
1216
1217                 if (open_pack_index(e.p)) {
1218                         midx_report(_("failed to load pack-index for packfile %s"),
1219                                     e.p->pack_name);
1220                         break;
1221                 }
1222
1223                 m_offset = e.offset;
1224                 p_offset = find_pack_entry_one(oid.hash, e.p);
1225
1226                 if (m_offset != p_offset)
1227                         midx_report(_("incorrect object offset for oid[%d] = %s: %"PRIx64" != %"PRIx64),
1228                                     pairs[i].pos, oid_to_hex(&oid), m_offset, p_offset);
1229
1230                 midx_display_sparse_progress(progress, i + 1);
1231         }
1232         stop_progress(&progress);
1233
1234         free(pairs);
1235
1236         return verify_midx_error;
1237 }
1238
1239 int expire_midx_packs(struct repository *r, const char *object_dir, unsigned flags)
1240 {
1241         uint32_t i, *count, result = 0;
1242         struct string_list packs_to_drop = STRING_LIST_INIT_DUP;
1243         struct multi_pack_index *m = load_multi_pack_index(object_dir, 1);
1244         struct progress *progress = NULL;
1245
1246         if (!m)
1247                 return 0;
1248
1249         count = xcalloc(m->num_packs, sizeof(uint32_t));
1250
1251         if (flags & MIDX_PROGRESS)
1252                 progress = start_progress(_("Counting referenced objects"),
1253                                           m->num_objects);
1254         for (i = 0; i < m->num_objects; i++) {
1255                 int pack_int_id = nth_midxed_pack_int_id(m, i);
1256                 count[pack_int_id]++;
1257                 display_progress(progress, i + 1);
1258         }
1259         stop_progress(&progress);
1260
1261         if (flags & MIDX_PROGRESS)
1262                 progress = start_progress(_("Finding and deleting unreferenced packfiles"),
1263                                           m->num_packs);
1264         for (i = 0; i < m->num_packs; i++) {
1265                 char *pack_name;
1266                 display_progress(progress, i + 1);
1267
1268                 if (count[i])
1269                         continue;
1270
1271                 if (prepare_midx_pack(r, m, i))
1272                         continue;
1273
1274                 if (m->packs[i]->pack_keep)
1275                         continue;
1276
1277                 pack_name = xstrdup(m->packs[i]->pack_name);
1278                 close_pack(m->packs[i]);
1279
1280                 string_list_insert(&packs_to_drop, m->pack_names[i]);
1281                 unlink_pack_path(pack_name, 0);
1282                 free(pack_name);
1283         }
1284         stop_progress(&progress);
1285
1286         free(count);
1287
1288         if (packs_to_drop.nr)
1289                 result = write_midx_internal(object_dir, m, &packs_to_drop, flags);
1290
1291         string_list_clear(&packs_to_drop, 0);
1292         return result;
1293 }
1294
1295 struct repack_info {
1296         timestamp_t mtime;
1297         uint32_t referenced_objects;
1298         uint32_t pack_int_id;
1299 };
1300
1301 static int compare_by_mtime(const void *a_, const void *b_)
1302 {
1303         const struct repack_info *a, *b;
1304
1305         a = (const struct repack_info *)a_;
1306         b = (const struct repack_info *)b_;
1307
1308         if (a->mtime < b->mtime)
1309                 return -1;
1310         if (a->mtime > b->mtime)
1311                 return 1;
1312         return 0;
1313 }
1314
1315 static int fill_included_packs_all(struct repository *r,
1316                                    struct multi_pack_index *m,
1317                                    unsigned char *include_pack)
1318 {
1319         uint32_t i, count = 0;
1320         int pack_kept_objects = 0;
1321
1322         repo_config_get_bool(r, "repack.packkeptobjects", &pack_kept_objects);
1323
1324         for (i = 0; i < m->num_packs; i++) {
1325                 if (prepare_midx_pack(r, m, i))
1326                         continue;
1327                 if (!pack_kept_objects && m->packs[i]->pack_keep)
1328                         continue;
1329
1330                 include_pack[i] = 1;
1331                 count++;
1332         }
1333
1334         return count < 2;
1335 }
1336
1337 static int fill_included_packs_batch(struct repository *r,
1338                                      struct multi_pack_index *m,
1339                                      unsigned char *include_pack,
1340                                      size_t batch_size)
1341 {
1342         uint32_t i, packs_to_repack;
1343         size_t total_size;
1344         struct repack_info *pack_info = xcalloc(m->num_packs, sizeof(struct repack_info));
1345         int pack_kept_objects = 0;
1346
1347         repo_config_get_bool(r, "repack.packkeptobjects", &pack_kept_objects);
1348
1349         for (i = 0; i < m->num_packs; i++) {
1350                 pack_info[i].pack_int_id = i;
1351
1352                 if (prepare_midx_pack(r, m, i))
1353                         continue;
1354
1355                 pack_info[i].mtime = m->packs[i]->mtime;
1356         }
1357
1358         for (i = 0; batch_size && i < m->num_objects; i++) {
1359                 uint32_t pack_int_id = nth_midxed_pack_int_id(m, i);
1360                 pack_info[pack_int_id].referenced_objects++;
1361         }
1362
1363         QSORT(pack_info, m->num_packs, compare_by_mtime);
1364
1365         total_size = 0;
1366         packs_to_repack = 0;
1367         for (i = 0; total_size < batch_size && i < m->num_packs; i++) {
1368                 int pack_int_id = pack_info[i].pack_int_id;
1369                 struct packed_git *p = m->packs[pack_int_id];
1370                 size_t expected_size;
1371
1372                 if (!p)
1373                         continue;
1374                 if (!pack_kept_objects && p->pack_keep)
1375                         continue;
1376                 if (open_pack_index(p) || !p->num_objects)
1377                         continue;
1378
1379                 expected_size = (size_t)(p->pack_size
1380                                          * pack_info[i].referenced_objects);
1381                 expected_size /= p->num_objects;
1382
1383                 if (expected_size >= batch_size)
1384                         continue;
1385
1386                 packs_to_repack++;
1387                 total_size += expected_size;
1388                 include_pack[pack_int_id] = 1;
1389         }
1390
1391         free(pack_info);
1392
1393         if (packs_to_repack < 2)
1394                 return 1;
1395
1396         return 0;
1397 }
1398
1399 int midx_repack(struct repository *r, const char *object_dir, size_t batch_size, unsigned flags)
1400 {
1401         int result = 0;
1402         uint32_t i;
1403         unsigned char *include_pack;
1404         struct child_process cmd = CHILD_PROCESS_INIT;
1405         FILE *cmd_in;
1406         struct strbuf base_name = STRBUF_INIT;
1407         struct multi_pack_index *m = load_multi_pack_index(object_dir, 1);
1408
1409         /*
1410          * When updating the default for these configuration
1411          * variables in builtin/repack.c, these must be adjusted
1412          * to match.
1413          */
1414         int delta_base_offset = 1;
1415         int use_delta_islands = 0;
1416
1417         if (!m)
1418                 return 0;
1419
1420         include_pack = xcalloc(m->num_packs, sizeof(unsigned char));
1421
1422         if (batch_size) {
1423                 if (fill_included_packs_batch(r, m, include_pack, batch_size))
1424                         goto cleanup;
1425         } else if (fill_included_packs_all(r, m, include_pack))
1426                 goto cleanup;
1427
1428         repo_config_get_bool(r, "repack.usedeltabaseoffset", &delta_base_offset);
1429         repo_config_get_bool(r, "repack.usedeltaislands", &use_delta_islands);
1430
1431         strvec_push(&cmd.args, "pack-objects");
1432
1433         strbuf_addstr(&base_name, object_dir);
1434         strbuf_addstr(&base_name, "/pack/pack");
1435         strvec_push(&cmd.args, base_name.buf);
1436
1437         if (delta_base_offset)
1438                 strvec_push(&cmd.args, "--delta-base-offset");
1439         if (use_delta_islands)
1440                 strvec_push(&cmd.args, "--delta-islands");
1441
1442         if (flags & MIDX_PROGRESS)
1443                 strvec_push(&cmd.args, "--progress");
1444         else
1445                 strvec_push(&cmd.args, "-q");
1446
1447         strbuf_release(&base_name);
1448
1449         cmd.git_cmd = 1;
1450         cmd.in = cmd.out = -1;
1451
1452         if (start_command(&cmd)) {
1453                 error(_("could not start pack-objects"));
1454                 result = 1;
1455                 goto cleanup;
1456         }
1457
1458         cmd_in = xfdopen(cmd.in, "w");
1459
1460         for (i = 0; i < m->num_objects; i++) {
1461                 struct object_id oid;
1462                 uint32_t pack_int_id = nth_midxed_pack_int_id(m, i);
1463
1464                 if (!include_pack[pack_int_id])
1465                         continue;
1466
1467                 nth_midxed_object_oid(&oid, m, i);
1468                 fprintf(cmd_in, "%s\n", oid_to_hex(&oid));
1469         }
1470         fclose(cmd_in);
1471
1472         if (finish_command(&cmd)) {
1473                 error(_("could not finish pack-objects"));
1474                 result = 1;
1475                 goto cleanup;
1476         }
1477
1478         result = write_midx_internal(object_dir, m, NULL, flags);
1479         m = NULL;
1480
1481 cleanup:
1482         if (m)
1483                 close_midx(m);
1484         free(include_pack);
1485         return result;
1486 }