]> git.ipfire.org Git - thirdparty/git.git/blame - midx.c
midx.c: make changing the preferred pack safe
[thirdparty/git.git] / midx.c
CommitLineData
a3407730 1#include "cache.h"
c4d25228 2#include "config.h"
fc59e748 3#include "csum-file.h"
396f2570 4#include "dir.h"
fc59e748 5#include "lockfile.h"
396f2570 6#include "packfile.h"
4d80560c 7#include "object-store.h"
bc626927 8#include "hash-lookup.h"
a3407730 9#include "midx.h"
144d7033 10#include "progress.h"
d829223a 11#include "trace2.h"
ce1e4a10 12#include "run-command.h"
18e449f8 13#include "repository.h"
63a8f0e9 14#include "chunk-format.h"
38ff7cab 15#include "pack.h"
c528e179
TB
16#include "pack-bitmap.h"
17#include "refs.h"
18#include "revision.h"
19#include "list-objects.h"
a3407730 20
fc59e748
DS
21#define MIDX_SIGNATURE 0x4d494458 /* "MIDX" */
22#define MIDX_VERSION 1
4d80560c
DS
23#define MIDX_BYTE_FILE_VERSION 4
24#define MIDX_BYTE_HASH_VERSION 5
25#define MIDX_BYTE_NUM_CHUNKS 6
26#define MIDX_BYTE_NUM_PACKS 8
fc59e748 27#define MIDX_HEADER_SIZE 12
aaa95dfa 28#define MIDX_MIN_SIZE (MIDX_HEADER_SIZE + the_hash_algo->rawsz)
fc59e748 29
32f3c541
DS
30#define MIDX_CHUNK_ALIGNMENT 4
31#define MIDX_CHUNKID_PACKNAMES 0x504e414d /* "PNAM" */
d7cacf29 32#define MIDX_CHUNKID_OIDFANOUT 0x4f494446 /* "OIDF" */
0d5b3a5e 33#define MIDX_CHUNKID_OIDLOOKUP 0x4f49444c /* "OIDL" */
662148c4
DS
34#define MIDX_CHUNKID_OBJECTOFFSETS 0x4f4f4646 /* "OOFF" */
35#define MIDX_CHUNKID_LARGEOFFSETS 0x4c4f4646 /* "LOFF" */
95e8383b 36#define MIDX_CHUNKID_REVINDEX 0x52494458 /* "RIDX" */
d7cacf29 37#define MIDX_CHUNK_FANOUT_SIZE (sizeof(uint32_t) * 256)
662148c4
DS
38#define MIDX_CHUNK_OFFSET_WIDTH (2 * sizeof(uint32_t))
39#define MIDX_CHUNK_LARGE_OFFSET_WIDTH (sizeof(uint64_t))
40#define MIDX_LARGE_OFFSET_NEEDED 0x80000000
32f3c541 41
19575c7c
DS
42#define PACK_EXPIRED UINT_MAX
43
d9607542
DS
44static uint8_t oid_version(void)
45{
46 switch (hash_algo_by_ptr(the_hash_algo)) {
47 case GIT_HASH_SHA1:
48 return 1;
49 case GIT_HASH_SHA256:
50 return 2;
51 default:
52 die(_("invalid hash version"));
53 }
54}
55
0f533c72 56const unsigned char *get_midx_checksum(struct multi_pack_index *m)
f894081d
TB
57{
58 return m->data + m->data_len - the_hash_algo->rawsz;
59}
60
60980aed 61void get_midx_filename(struct strbuf *out, const char *object_dir)
fc59e748 62{
60980aed 63 strbuf_addf(out, "%s/pack/multi-pack-index", object_dir);
fc59e748
DS
64}
65
60980aed 66void get_midx_rev_filename(struct strbuf *out, struct multi_pack_index *m)
f894081d 67{
60980aed
TB
68 get_midx_filename(out, m->object_dir);
69 strbuf_addf(out, "-%s.rev", hash_to_hex(get_midx_checksum(m)));
f894081d
TB
70}
71
6ab3b8b8
DS
72static int midx_read_oid_fanout(const unsigned char *chunk_start,
73 size_t chunk_size, void *data)
74{
75 struct multi_pack_index *m = data;
76 m->chunk_oid_fanout = (uint32_t *)chunk_start;
77
78 if (chunk_size != 4 * 256) {
79 error(_("multi-pack-index OID fanout is of the wrong size"));
80 return 1;
81 }
82 return 0;
83}
84
2cf489a3 85struct multi_pack_index *load_multi_pack_index(const char *object_dir, int local)
4d80560c
DS
86{
87 struct multi_pack_index *m = NULL;
88 int fd;
89 struct stat st;
90 size_t midx_size;
91 void *midx_map = NULL;
92 uint32_t hash_version;
60980aed 93 struct strbuf midx_name = STRBUF_INIT;
32f3c541 94 uint32_t i;
3227565c 95 const char *cur_pack_name;
6ab3b8b8 96 struct chunkfile *cf = NULL;
4d80560c 97
60980aed
TB
98 get_midx_filename(&midx_name, object_dir);
99
100 fd = git_open(midx_name.buf);
4d80560c
DS
101
102 if (fd < 0)
103 goto cleanup_fail;
104 if (fstat(fd, &st)) {
60980aed 105 error_errno(_("failed to read %s"), midx_name.buf);
4d80560c
DS
106 goto cleanup_fail;
107 }
108
109 midx_size = xsize_t(st.st_size);
110
111 if (midx_size < MIDX_MIN_SIZE) {
60980aed 112 error(_("multi-pack-index file %s is too small"), midx_name.buf);
4d80560c
DS
113 goto cleanup_fail;
114 }
115
60980aed 116 strbuf_release(&midx_name);
4d80560c
DS
117
118 midx_map = xmmap(NULL, midx_size, PROT_READ, MAP_PRIVATE, fd, 0);
6c7ff7cf 119 close(fd);
4d80560c 120
577314ca 121 FLEX_ALLOC_STR(m, object_dir, object_dir);
4d80560c
DS
122 m->data = midx_map;
123 m->data_len = midx_size;
2cf489a3 124 m->local = local;
4d80560c
DS
125
126 m->signature = get_be32(m->data);
53ad0407
DS
127 if (m->signature != MIDX_SIGNATURE)
128 die(_("multi-pack-index signature 0x%08x does not match signature 0x%08x"),
4d80560c 129 m->signature, MIDX_SIGNATURE);
4d80560c
DS
130
131 m->version = m->data[MIDX_BYTE_FILE_VERSION];
53ad0407
DS
132 if (m->version != MIDX_VERSION)
133 die(_("multi-pack-index version %d not recognized"),
4d80560c 134 m->version);
4d80560c
DS
135
136 hash_version = m->data[MIDX_BYTE_HASH_VERSION];
d9607542
DS
137 if (hash_version != oid_version()) {
138 error(_("multi-pack-index hash version %u does not match version %u"),
139 hash_version, oid_version());
140 goto cleanup_fail;
141 }
aaa95dfa 142 m->hash_len = the_hash_algo->rawsz;
4d80560c
DS
143
144 m->num_chunks = m->data[MIDX_BYTE_NUM_CHUNKS];
145
146 m->num_packs = get_be32(m->data + MIDX_BYTE_NUM_PACKS);
147
6ab3b8b8 148 cf = init_chunkfile(NULL);
32f3c541 149
6ab3b8b8
DS
150 if (read_table_of_contents(cf, m->data, midx_size,
151 MIDX_HEADER_SIZE, m->num_chunks))
152 goto cleanup_fail;
32f3c541 153
6ab3b8b8 154 if (pair_chunk(cf, MIDX_CHUNKID_PACKNAMES, &m->chunk_pack_names) == CHUNK_NOT_FOUND)
32f3c541 155 die(_("multi-pack-index missing required pack-name chunk"));
6ab3b8b8 156 if (read_chunk(cf, MIDX_CHUNKID_OIDFANOUT, midx_read_oid_fanout, m) == CHUNK_NOT_FOUND)
d7cacf29 157 die(_("multi-pack-index missing required OID fanout chunk"));
6ab3b8b8 158 if (pair_chunk(cf, MIDX_CHUNKID_OIDLOOKUP, &m->chunk_oid_lookup) == CHUNK_NOT_FOUND)
0d5b3a5e 159 die(_("multi-pack-index missing required OID lookup chunk"));
6ab3b8b8 160 if (pair_chunk(cf, MIDX_CHUNKID_OBJECTOFFSETS, &m->chunk_object_offsets) == CHUNK_NOT_FOUND)
662148c4 161 die(_("multi-pack-index missing required object offsets chunk"));
32f3c541 162
6ab3b8b8
DS
163 pair_chunk(cf, MIDX_CHUNKID_LARGEOFFSETS, &m->chunk_large_offsets);
164
d7cacf29
DS
165 m->num_objects = ntohl(m->chunk_oid_fanout[255]);
166
ca56dadb
RS
167 CALLOC_ARRAY(m->pack_names, m->num_packs);
168 CALLOC_ARRAY(m->packs, m->num_packs);
3227565c
DS
169
170 cur_pack_name = (const char *)m->chunk_pack_names;
171 for (i = 0; i < m->num_packs; i++) {
172 m->pack_names[i] = cur_pack_name;
173
174 cur_pack_name += strlen(cur_pack_name) + 1;
175
8e72a3c3
DS
176 if (i && strcmp(m->pack_names[i], m->pack_names[i - 1]) <= 0)
177 die(_("multi-pack-index pack names out of order: '%s' before '%s'"),
3227565c
DS
178 m->pack_names[i - 1],
179 m->pack_names[i]);
3227565c
DS
180 }
181
d829223a
JH
182 trace2_data_intmax("midx", the_repository, "load/num_packs", m->num_packs);
183 trace2_data_intmax("midx", the_repository, "load/num_objects", m->num_objects);
184
692305ec 185 free_chunkfile(cf);
4d80560c
DS
186 return m;
187
188cleanup_fail:
189 free(m);
60980aed 190 strbuf_release(&midx_name);
692305ec 191 free_chunkfile(cf);
4d80560c
DS
192 if (midx_map)
193 munmap(midx_map, midx_size);
194 if (0 <= fd)
195 close(fd);
196 return NULL;
197}
198
1dcd9f20 199void close_midx(struct multi_pack_index *m)
a40498a1
DS
200{
201 uint32_t i;
1dcd9f20
DS
202
203 if (!m)
204 return;
205
9bb6c2e5
TB
206 close_midx(m->next);
207
a40498a1 208 munmap((unsigned char *)m->data, m->data_len);
a40498a1
DS
209
210 for (i = 0; i < m->num_packs; i++) {
af96fe33
DS
211 if (m->packs[i])
212 m->packs[i]->multi_pack_index = 0;
a40498a1
DS
213 }
214 FREE_AND_NULL(m->packs);
215 FREE_AND_NULL(m->pack_names);
9bb6c2e5 216 free(m);
a40498a1
DS
217}
218
64404a24 219int prepare_midx_pack(struct repository *r, struct multi_pack_index *m, uint32_t pack_int_id)
3715a633
DS
220{
221 struct strbuf pack_name = STRBUF_INIT;
af96fe33 222 struct packed_git *p;
3715a633
DS
223
224 if (pack_int_id >= m->num_packs)
d355e46a 225 die(_("bad pack-int-id: %u (%u total packs)"),
cc6af73c 226 pack_int_id, m->num_packs);
3715a633
DS
227
228 if (m->packs[pack_int_id])
229 return 0;
230
231 strbuf_addf(&pack_name, "%s/pack/%s", m->object_dir,
232 m->pack_names[pack_int_id]);
233
af96fe33 234 p = add_packed_git(pack_name.buf, pack_name.len, m->local);
3715a633 235 strbuf_release(&pack_name);
af96fe33
DS
236
237 if (!p)
238 return 1;
239
240 p->multi_pack_index = 1;
241 m->packs[pack_int_id] = p;
242 install_packed_git(r, p);
243 list_add_tail(&p->mru, &r->objects->packed_git_mru);
244
245 return 0;
3715a633
DS
246}
247
248int bsearch_midx(const struct object_id *oid, struct multi_pack_index *m, uint32_t *result)
249{
250 return bsearch_hash(oid->hash, m->chunk_oid_fanout, m->chunk_oid_lookup,
aaa95dfa 251 the_hash_algo->rawsz, result);
3715a633
DS
252}
253
8aac67a1
DS
254struct object_id *nth_midxed_object_oid(struct object_id *oid,
255 struct multi_pack_index *m,
256 uint32_t n)
257{
258 if (n >= m->num_objects)
259 return NULL;
260
92e2cab9 261 oidread(oid, m->chunk_oid_lookup + m->hash_len * n);
8aac67a1
DS
262 return oid;
263}
264
62f2c1b5 265off_t nth_midxed_offset(struct multi_pack_index *m, uint32_t pos)
3715a633
DS
266{
267 const unsigned char *offset_data;
268 uint32_t offset32;
269
329fac3a 270 offset_data = m->chunk_object_offsets + (off_t)pos * MIDX_CHUNK_OFFSET_WIDTH;
3715a633
DS
271 offset32 = get_be32(offset_data + sizeof(uint32_t));
272
273 if (m->chunk_large_offsets && offset32 & MIDX_LARGE_OFFSET_NEEDED) {
d8ac9ee1 274 if (sizeof(off_t) < sizeof(uint64_t))
3715a633
DS
275 die(_("multi-pack-index stores a 64-bit offset, but off_t is too small"));
276
277 offset32 ^= MIDX_LARGE_OFFSET_NEEDED;
278 return get_be64(m->chunk_large_offsets + sizeof(uint64_t) * offset32);
279 }
280
281 return offset32;
282}
283
62f2c1b5 284uint32_t nth_midxed_pack_int_id(struct multi_pack_index *m, uint32_t pos)
3715a633 285{
329fac3a
DS
286 return get_be32(m->chunk_object_offsets +
287 (off_t)pos * MIDX_CHUNK_OFFSET_WIDTH);
3715a633
DS
288}
289
893b5635
RS
290int fill_midx_entry(struct repository * r,
291 const struct object_id *oid,
292 struct pack_entry *e,
293 struct multi_pack_index *m)
3715a633 294{
893b5635 295 uint32_t pos;
3715a633
DS
296 uint32_t pack_int_id;
297 struct packed_git *p;
298
893b5635
RS
299 if (!bsearch_midx(oid, m, &pos))
300 return 0;
301
3715a633
DS
302 if (pos >= m->num_objects)
303 return 0;
304
305 pack_int_id = nth_midxed_pack_int_id(m, pos);
306
64404a24 307 if (prepare_midx_pack(r, m, pack_int_id))
506ec2fb 308 return 0;
3715a633
DS
309 p = m->packs[pack_int_id];
310
311 /*
312 * We are about to tell the caller where they can locate the
313 * requested object. We better make sure the packfile is
314 * still here and can be accessed before supplying that
315 * answer, as it may have been deleted since the MIDX was
316 * loaded!
317 */
318 if (!is_pack_valid(p))
319 return 0;
320
09ef6617
RS
321 if (oidset_size(&p->bad_objects) &&
322 oidset_contains(&p->bad_objects, oid))
323 return 0;
c39b02ae 324
3715a633
DS
325 e->offset = nth_midxed_offset(m, pos);
326 e->p = p;
327
328 return 1;
329}
330
013fd7ad
JK
331/* Match "foo.idx" against either "foo.pack" _or_ "foo.idx". */
332static int cmp_idx_or_pack_name(const char *idx_or_pack_name,
333 const char *idx_name)
334{
335 /* Skip past any initial matching prefix. */
336 while (*idx_name && *idx_name == *idx_or_pack_name) {
337 idx_name++;
338 idx_or_pack_name++;
339 }
340
341 /*
342 * If we didn't match completely, we may have matched "pack-1234." and
343 * be left with "idx" and "pack" respectively, which is also OK. We do
344 * not have to check for "idx" and "idx", because that would have been
345 * a complete match (and in that case these strcmps will be false, but
346 * we'll correctly return 0 from the final strcmp() below.
347 *
348 * Technically this matches "fooidx" and "foopack", but we'd never have
349 * such names in the first place.
350 */
351 if (!strcmp(idx_name, "idx") && !strcmp(idx_or_pack_name, "pack"))
352 return 0;
353
354 /*
355 * This not only checks for a complete match, but also orders based on
356 * the first non-identical character, which means our ordering will
357 * match a raw strcmp(). That makes it OK to use this to binary search
358 * a naively-sorted list.
359 */
360 return strcmp(idx_or_pack_name, idx_name);
361}
362
363int midx_contains_pack(struct multi_pack_index *m, const char *idx_or_pack_name)
a40498a1
DS
364{
365 uint32_t first = 0, last = m->num_packs;
366
367 while (first < last) {
368 uint32_t mid = first + (last - first) / 2;
369 const char *current;
370 int cmp;
371
372 current = m->pack_names[mid];
013fd7ad 373 cmp = cmp_idx_or_pack_name(idx_or_pack_name, current);
a40498a1
DS
374 if (!cmp)
375 return 1;
376 if (cmp > 0) {
377 first = mid + 1;
378 continue;
379 }
380 last = mid;
381 }
382
383 return 0;
384}
385
2cf489a3 386int prepare_multi_pack_index_one(struct repository *r, const char *object_dir, int local)
c4d25228 387{
29e2016b 388 struct multi_pack_index *m;
c4d25228 389 struct multi_pack_index *m_search;
c4d25228 390
18e449f8
DS
391 prepare_repo_settings(r);
392 if (!r->settings.core_multi_pack_index)
c4d25228
DS
393 return 0;
394
29e2016b 395 for (m_search = r->objects->multi_pack_index; m_search; m_search = m_search->next)
c4d25228
DS
396 if (!strcmp(object_dir, m_search->object_dir))
397 return 1;
398
29e2016b 399 m = load_multi_pack_index(object_dir, local);
c4d25228 400
29e2016b 401 if (m) {
59552fb3
TB
402 struct multi_pack_index *mp = r->objects->multi_pack_index;
403 if (mp) {
404 m->next = mp->next;
405 mp->next = m;
406 } else
407 r->objects->multi_pack_index = m;
c4d25228
DS
408 return 1;
409 }
410
411 return 0;
412}
413
fc59e748
DS
414static size_t write_midx_header(struct hashfile *f,
415 unsigned char num_chunks,
416 uint32_t num_packs)
417{
fc59e748 418 hashwrite_be32(f, MIDX_SIGNATURE);
014f1447
RS
419 hashwrite_u8(f, MIDX_VERSION);
420 hashwrite_u8(f, oid_version());
421 hashwrite_u8(f, num_chunks);
422 hashwrite_u8(f, 0); /* unused */
fc59e748
DS
423 hashwrite_be32(f, num_packs);
424
425 return MIDX_HEADER_SIZE;
426}
427
d01bf2e6
DS
428struct pack_info {
429 uint32_t orig_pack_int_id;
430 char *pack_name;
431 struct packed_git *p;
19575c7c 432 unsigned expired : 1;
d01bf2e6
DS
433};
434
435static int pack_info_compare(const void *_a, const void *_b)
436{
437 struct pack_info *a = (struct pack_info *)_a;
438 struct pack_info *b = (struct pack_info *)_b;
439 return strcmp(a->pack_name, b->pack_name);
440}
441
9218c6a4
TB
442static int idx_or_pack_name_cmp(const void *_va, const void *_vb)
443{
444 const char *pack_name = _va;
445 const struct pack_info *compar = _vb;
446
447 return cmp_idx_or_pack_name(pack_name, compar->pack_name);
448}
449
577dc496 450struct write_midx_context {
d01bf2e6 451 struct pack_info *info;
396f2570 452 uint32_t nr;
d01bf2e6 453 uint32_t alloc;
a40498a1 454 struct multi_pack_index *m;
840cef0c
WB
455 struct progress *progress;
456 unsigned pack_paths_checked;
31bda9a2
DS
457
458 struct pack_midx_entry *entries;
459 uint32_t entries_nr;
7a3ada11
DS
460
461 uint32_t *pack_perm;
38ff7cab 462 uint32_t *pack_order;
7a3ada11 463 unsigned large_offsets_needed:1;
980f525c 464 uint32_t num_large_offsets;
9218c6a4
TB
465
466 int preferred_pack_idx;
56d863e9
TB
467
468 struct string_list *to_include;
396f2570
DS
469};
470
471static void add_pack_to_midx(const char *full_path, size_t full_path_len,
472 const char *file_name, void *data)
473{
577dc496 474 struct write_midx_context *ctx = data;
396f2570
DS
475
476 if (ends_with(file_name, ".idx")) {
577dc496 477 display_progress(ctx->progress, ++ctx->pack_paths_checked);
56d863e9
TB
478 /*
479 * Note that at most one of ctx->m and ctx->to_include are set,
480 * so we are testing midx_contains_pack() and
481 * string_list_has_string() independently (guarded by the
482 * appropriate NULL checks).
483 *
484 * We could support passing to_include while reusing an existing
485 * MIDX, but don't currently since the reuse process drags
486 * forward all packs from an existing MIDX (without checking
487 * whether or not they appear in the to_include list).
488 *
489 * If we added support for that, these next two conditional
490 * should be performed independently (likely checking
491 * to_include before the existing MIDX).
492 */
577dc496 493 if (ctx->m && midx_contains_pack(ctx->m, file_name))
a40498a1 494 return;
56d863e9
TB
495 else if (ctx->to_include &&
496 !string_list_has_string(ctx->to_include, file_name))
497 return;
a40498a1 498
577dc496 499 ALLOC_GROW(ctx->info, ctx->nr + 1, ctx->alloc);
396f2570 500
577dc496
DS
501 ctx->info[ctx->nr].p = add_packed_git(full_path,
502 full_path_len,
503 0);
fe1ed56f 504
577dc496 505 if (!ctx->info[ctx->nr].p) {
396f2570
DS
506 warning(_("failed to add packfile '%s'"),
507 full_path);
508 return;
509 }
510
577dc496 511 if (open_pack_index(ctx->info[ctx->nr].p)) {
fe1ed56f
DS
512 warning(_("failed to open pack-index '%s'"),
513 full_path);
577dc496
DS
514 close_pack(ctx->info[ctx->nr].p);
515 FREE_AND_NULL(ctx->info[ctx->nr].p);
fe1ed56f
DS
516 return;
517 }
518
577dc496
DS
519 ctx->info[ctx->nr].pack_name = xstrdup(file_name);
520 ctx->info[ctx->nr].orig_pack_int_id = ctx->nr;
521 ctx->info[ctx->nr].expired = 0;
522 ctx->nr++;
396f2570
DS
523 }
524}
525
fe1ed56f
DS
526struct pack_midx_entry {
527 struct object_id oid;
528 uint32_t pack_int_id;
529 time_t pack_mtime;
530 uint64_t offset;
9218c6a4 531 unsigned preferred : 1;
fe1ed56f
DS
532};
533
534static int midx_oid_compare(const void *_a, const void *_b)
535{
536 const struct pack_midx_entry *a = (const struct pack_midx_entry *)_a;
537 const struct pack_midx_entry *b = (const struct pack_midx_entry *)_b;
538 int cmp = oidcmp(&a->oid, &b->oid);
539
540 if (cmp)
541 return cmp;
542
9218c6a4
TB
543 /* Sort objects in a preferred pack first when multiple copies exist. */
544 if (a->preferred > b->preferred)
545 return -1;
546 if (a->preferred < b->preferred)
547 return 1;
548
fe1ed56f
DS
549 if (a->pack_mtime > b->pack_mtime)
550 return -1;
551 else if (a->pack_mtime < b->pack_mtime)
552 return 1;
553
554 return a->pack_int_id - b->pack_int_id;
555}
556
a40498a1 557static int nth_midxed_pack_midx_entry(struct multi_pack_index *m,
a40498a1
DS
558 struct pack_midx_entry *e,
559 uint32_t pos)
560{
561 if (pos >= m->num_objects)
562 return 1;
563
564 nth_midxed_object_oid(&e->oid, m, pos);
d01bf2e6 565 e->pack_int_id = nth_midxed_pack_int_id(m, pos);
a40498a1
DS
566 e->offset = nth_midxed_offset(m, pos);
567
568 /* consider objects in midx to be from "old" packs */
569 e->pack_mtime = 0;
570 return 0;
571}
572
fe1ed56f
DS
573static void fill_pack_entry(uint32_t pack_int_id,
574 struct packed_git *p,
575 uint32_t cur_object,
9218c6a4
TB
576 struct pack_midx_entry *entry,
577 int preferred)
fe1ed56f 578{
0763671b 579 if (nth_packed_object_id(&entry->oid, p, cur_object) < 0)
fe1ed56f
DS
580 die(_("failed to locate object %d in packfile"), cur_object);
581
582 entry->pack_int_id = pack_int_id;
583 entry->pack_mtime = p->mtime;
584
585 entry->offset = nth_packed_object_offset(p, cur_object);
9218c6a4 586 entry->preferred = !!preferred;
fe1ed56f
DS
587}
588
589/*
590 * It is possible to artificially get into a state where there are many
591 * duplicate copies of objects. That can create high memory pressure if
592 * we are to create a list of all objects before de-duplication. To reduce
593 * this memory pressure without a significant performance drop, automatically
594 * group objects by the first byte of their object id. Use the IDX fanout
595 * tables to group the data, copy to a local array, then sort.
596 *
597 * Copy only the de-duplicated entries (selected by most-recent modified time
598 * of a packfile containing the object).
599 */
a40498a1 600static struct pack_midx_entry *get_sorted_entries(struct multi_pack_index *m,
d01bf2e6 601 struct pack_info *info,
fe1ed56f 602 uint32_t nr_packs,
9218c6a4
TB
603 uint32_t *nr_objects,
604 int preferred_pack)
fe1ed56f
DS
605{
606 uint32_t cur_fanout, cur_pack, cur_object;
607 uint32_t alloc_fanout, alloc_objects, total_objects = 0;
608 struct pack_midx_entry *entries_by_fanout = NULL;
609 struct pack_midx_entry *deduplicated_entries = NULL;
a40498a1 610 uint32_t start_pack = m ? m->num_packs : 0;
fe1ed56f 611
a40498a1 612 for (cur_pack = start_pack; cur_pack < nr_packs; cur_pack++)
d01bf2e6 613 total_objects += info[cur_pack].p->num_objects;
fe1ed56f
DS
614
615 /*
616 * As we de-duplicate by fanout value, we expect the fanout
617 * slices to be evenly distributed, with some noise. Hence,
618 * allocate slightly more than one 256th.
619 */
620 alloc_objects = alloc_fanout = total_objects > 3200 ? total_objects / 200 : 16;
621
622 ALLOC_ARRAY(entries_by_fanout, alloc_fanout);
623 ALLOC_ARRAY(deduplicated_entries, alloc_objects);
624 *nr_objects = 0;
625
626 for (cur_fanout = 0; cur_fanout < 256; cur_fanout++) {
627 uint32_t nr_fanout = 0;
628
a40498a1
DS
629 if (m) {
630 uint32_t start = 0, end;
631
632 if (cur_fanout)
633 start = ntohl(m->chunk_oid_fanout[cur_fanout - 1]);
634 end = ntohl(m->chunk_oid_fanout[cur_fanout]);
635
636 for (cur_object = start; cur_object < end; cur_object++) {
637 ALLOC_GROW(entries_by_fanout, nr_fanout + 1, alloc_fanout);
d01bf2e6 638 nth_midxed_pack_midx_entry(m,
a40498a1
DS
639 &entries_by_fanout[nr_fanout],
640 cur_object);
9218c6a4
TB
641 if (nth_midxed_pack_int_id(m, cur_object) == preferred_pack)
642 entries_by_fanout[nr_fanout].preferred = 1;
643 else
644 entries_by_fanout[nr_fanout].preferred = 0;
a40498a1
DS
645 nr_fanout++;
646 }
647 }
648
649 for (cur_pack = start_pack; cur_pack < nr_packs; cur_pack++) {
fe1ed56f 650 uint32_t start = 0, end;
9218c6a4 651 int preferred = cur_pack == preferred_pack;
fe1ed56f
DS
652
653 if (cur_fanout)
d01bf2e6
DS
654 start = get_pack_fanout(info[cur_pack].p, cur_fanout - 1);
655 end = get_pack_fanout(info[cur_pack].p, cur_fanout);
fe1ed56f
DS
656
657 for (cur_object = start; cur_object < end; cur_object++) {
658 ALLOC_GROW(entries_by_fanout, nr_fanout + 1, alloc_fanout);
9218c6a4
TB
659 fill_pack_entry(cur_pack,
660 info[cur_pack].p,
661 cur_object,
662 &entries_by_fanout[nr_fanout],
663 preferred);
fe1ed56f
DS
664 nr_fanout++;
665 }
666 }
667
668 QSORT(entries_by_fanout, nr_fanout, midx_oid_compare);
669
670 /*
671 * The batch is now sorted by OID and then mtime (descending).
672 * Take only the first duplicate.
673 */
674 for (cur_object = 0; cur_object < nr_fanout; cur_object++) {
e43d2dcc
JK
675 if (cur_object && oideq(&entries_by_fanout[cur_object - 1].oid,
676 &entries_by_fanout[cur_object].oid))
fe1ed56f
DS
677 continue;
678
679 ALLOC_GROW(deduplicated_entries, *nr_objects + 1, alloc_objects);
680 memcpy(&deduplicated_entries[*nr_objects],
681 &entries_by_fanout[cur_object],
682 sizeof(struct pack_midx_entry));
683 (*nr_objects)++;
684 }
685 }
686
687 free(entries_by_fanout);
688 return deduplicated_entries;
689}
690
0ccd713c 691static int write_midx_pack_names(struct hashfile *f, void *data)
32f3c541 692{
b4d94142 693 struct write_midx_context *ctx = data;
32f3c541
DS
694 uint32_t i;
695 unsigned char padding[MIDX_CHUNK_ALIGNMENT];
696 size_t written = 0;
697
b4d94142 698 for (i = 0; i < ctx->nr; i++) {
19575c7c
DS
699 size_t writelen;
700
b4d94142 701 if (ctx->info[i].expired)
19575c7c 702 continue;
32f3c541 703
b4d94142 704 if (i && strcmp(ctx->info[i].pack_name, ctx->info[i - 1].pack_name) <= 0)
32f3c541 705 BUG("incorrect pack-file order: %s before %s",
b4d94142
DS
706 ctx->info[i - 1].pack_name,
707 ctx->info[i].pack_name);
32f3c541 708
b4d94142
DS
709 writelen = strlen(ctx->info[i].pack_name) + 1;
710 hashwrite(f, ctx->info[i].pack_name, writelen);
32f3c541
DS
711 written += writelen;
712 }
713
714 /* add padding to be aligned */
715 i = MIDX_CHUNK_ALIGNMENT - (written % MIDX_CHUNK_ALIGNMENT);
716 if (i < MIDX_CHUNK_ALIGNMENT) {
717 memset(padding, 0, sizeof(padding));
718 hashwrite(f, padding, i);
32f3c541
DS
719 }
720
0ccd713c 721 return 0;
32f3c541
DS
722}
723
0ccd713c
DS
724static int write_midx_oid_fanout(struct hashfile *f,
725 void *data)
d7cacf29 726{
31bda9a2
DS
727 struct write_midx_context *ctx = data;
728 struct pack_midx_entry *list = ctx->entries;
729 struct pack_midx_entry *last = ctx->entries + ctx->entries_nr;
d7cacf29
DS
730 uint32_t count = 0;
731 uint32_t i;
732
733 /*
734 * Write the first-level table (the list is sorted,
735 * but we use a 256-entry lookup to be able to avoid
736 * having to do eight extra binary search iterations).
737 */
738 for (i = 0; i < 256; i++) {
739 struct pack_midx_entry *next = list;
740
741 while (next < last && next->oid.hash[0] == i) {
742 count++;
743 next++;
744 }
745
746 hashwrite_be32(f, count);
747 list = next;
748 }
749
0ccd713c 750 return 0;
d7cacf29
DS
751}
752
0ccd713c
DS
753static int write_midx_oid_lookup(struct hashfile *f,
754 void *data)
0d5b3a5e 755{
31bda9a2
DS
756 struct write_midx_context *ctx = data;
757 unsigned char hash_len = the_hash_algo->rawsz;
758 struct pack_midx_entry *list = ctx->entries;
0d5b3a5e 759 uint32_t i;
0d5b3a5e 760
31bda9a2 761 for (i = 0; i < ctx->entries_nr; i++) {
0d5b3a5e
DS
762 struct pack_midx_entry *obj = list++;
763
31bda9a2 764 if (i < ctx->entries_nr - 1) {
0d5b3a5e
DS
765 struct pack_midx_entry *next = list;
766 if (oidcmp(&obj->oid, &next->oid) >= 0)
767 BUG("OIDs not in order: %s >= %s",
768 oid_to_hex(&obj->oid),
769 oid_to_hex(&next->oid));
770 }
771
772 hashwrite(f, obj->oid.hash, (int)hash_len);
0d5b3a5e
DS
773 }
774
0ccd713c 775 return 0;
0d5b3a5e
DS
776}
777
0ccd713c
DS
778static int write_midx_object_offsets(struct hashfile *f,
779 void *data)
662148c4 780{
7a3ada11
DS
781 struct write_midx_context *ctx = data;
782 struct pack_midx_entry *list = ctx->entries;
662148c4 783 uint32_t i, nr_large_offset = 0;
662148c4 784
7a3ada11 785 for (i = 0; i < ctx->entries_nr; i++) {
662148c4
DS
786 struct pack_midx_entry *obj = list++;
787
7a3ada11 788 if (ctx->pack_perm[obj->pack_int_id] == PACK_EXPIRED)
19575c7c
DS
789 BUG("object %s is in an expired pack with int-id %d",
790 oid_to_hex(&obj->oid),
791 obj->pack_int_id);
792
7a3ada11 793 hashwrite_be32(f, ctx->pack_perm[obj->pack_int_id]);
662148c4 794
7a3ada11 795 if (ctx->large_offsets_needed && obj->offset >> 31)
662148c4 796 hashwrite_be32(f, MIDX_LARGE_OFFSET_NEEDED | nr_large_offset++);
7a3ada11 797 else if (!ctx->large_offsets_needed && obj->offset >> 32)
662148c4
DS
798 BUG("object %s requires a large offset (%"PRIx64") but the MIDX is not writing large offsets!",
799 oid_to_hex(&obj->oid),
800 obj->offset);
801 else
802 hashwrite_be32(f, (uint32_t)obj->offset);
662148c4
DS
803 }
804
0ccd713c 805 return 0;
662148c4
DS
806}
807
0ccd713c
DS
808static int write_midx_large_offsets(struct hashfile *f,
809 void *data)
662148c4 810{
980f525c
DS
811 struct write_midx_context *ctx = data;
812 struct pack_midx_entry *list = ctx->entries;
813 struct pack_midx_entry *end = ctx->entries + ctx->entries_nr;
980f525c 814 uint32_t nr_large_offset = ctx->num_large_offsets;
662148c4
DS
815
816 while (nr_large_offset) {
61b0fcbb
JK
817 struct pack_midx_entry *obj;
818 uint64_t offset;
819
820 if (list >= end)
821 BUG("too many large-offset objects");
822
823 obj = list++;
824 offset = obj->offset;
662148c4
DS
825
826 if (!(offset >> 31))
827 continue;
828
0ccd713c 829 hashwrite_be64(f, offset);
662148c4
DS
830
831 nr_large_offset--;
832 }
833
0ccd713c 834 return 0;
662148c4
DS
835}
836
95e8383b
TB
837static int write_midx_revindex(struct hashfile *f,
838 void *data)
839{
840 struct write_midx_context *ctx = data;
841 uint32_t i;
842
843 for (i = 0; i < ctx->entries_nr; i++)
844 hashwrite_be32(f, ctx->pack_order[i]);
845
846 return 0;
847}
848
30077524
JK
849struct midx_pack_order_data {
850 uint32_t nr;
851 uint32_t pack;
852 off_t offset;
853};
38ff7cab 854
30077524
JK
855static int midx_pack_order_cmp(const void *va, const void *vb)
856{
857 const struct midx_pack_order_data *a = va, *b = vb;
858 if (a->pack < b->pack)
38ff7cab 859 return -1;
30077524 860 else if (a->pack > b->pack)
38ff7cab 861 return 1;
30077524 862 else if (a->offset < b->offset)
38ff7cab 863 return -1;
30077524 864 else if (a->offset > b->offset)
38ff7cab 865 return 1;
30077524
JK
866 else
867 return 0;
38ff7cab
TB
868}
869
870static uint32_t *midx_pack_order(struct write_midx_context *ctx)
871{
30077524 872 struct midx_pack_order_data *data;
38ff7cab
TB
873 uint32_t *pack_order;
874 uint32_t i;
875
30077524
JK
876 ALLOC_ARRAY(data, ctx->entries_nr);
877 for (i = 0; i < ctx->entries_nr; i++) {
878 struct pack_midx_entry *e = &ctx->entries[i];
879 data[i].nr = i;
880 data[i].pack = ctx->pack_perm[e->pack_int_id];
881 if (!e->preferred)
882 data[i].pack |= (1U << 31);
883 data[i].offset = e->offset;
884 }
885
886 QSORT(data, ctx->entries_nr, midx_pack_order_cmp);
887
38ff7cab
TB
888 ALLOC_ARRAY(pack_order, ctx->entries_nr);
889 for (i = 0; i < ctx->entries_nr; i++)
30077524
JK
890 pack_order[i] = data[i].nr;
891 free(data);
38ff7cab
TB
892
893 return pack_order;
894}
895
896static void write_midx_reverse_index(char *midx_name, unsigned char *midx_hash,
897 struct write_midx_context *ctx)
898{
899 struct strbuf buf = STRBUF_INIT;
900 const char *tmp_file;
901
902 strbuf_addf(&buf, "%s-%s.rev", midx_name, hash_to_hex(midx_hash));
903
904 tmp_file = write_rev_file_order(NULL, ctx->pack_order, ctx->entries_nr,
905 midx_hash, WRITE_REV);
906
907 if (finalize_object_file(tmp_file, buf.buf))
908 die(_("cannot store reverse index file"));
909
910 strbuf_release(&buf);
911}
912
426c00e4 913static void clear_midx_files_ext(const char *object_dir, const char *ext,
38ff7cab
TB
914 unsigned char *keep_hash);
915
ec1e28ef
TB
916static int midx_checksum_valid(struct multi_pack_index *m)
917{
918 return hashfile_checksum_valid(m->data, m->data_len);
919}
920
c528e179
TB
921static void prepare_midx_packing_data(struct packing_data *pdata,
922 struct write_midx_context *ctx)
923{
924 uint32_t i;
925
926 memset(pdata, 0, sizeof(struct packing_data));
927 prepare_packing_data(the_repository, pdata);
928
929 for (i = 0; i < ctx->entries_nr; i++) {
930 struct pack_midx_entry *from = &ctx->entries[ctx->pack_order[i]];
931 struct object_entry *to = packlist_alloc(pdata, &from->oid);
932
933 oe_set_in_pack(pdata, to,
934 ctx->info[ctx->pack_perm[from->pack_int_id]].p);
935 }
936}
937
938static int add_ref_to_pending(const char *refname,
939 const struct object_id *oid,
940 int flag, void *cb_data)
941{
942 struct rev_info *revs = (struct rev_info*)cb_data;
943 struct object *object;
944
945 if ((flag & REF_ISSYMREF) && (flag & REF_ISBROKEN)) {
946 warning("symbolic ref is dangling: %s", refname);
947 return 0;
948 }
949
950 object = parse_object_or_die(oid, refname);
951 if (object->type != OBJ_COMMIT)
952 return 0;
953
954 add_pending_object(revs, object, "");
955 if (bitmap_is_preferred_refname(revs->repo, refname))
956 object->flags |= NEEDS_BITMAP;
957 return 0;
958}
959
960struct bitmap_commit_cb {
961 struct commit **commits;
962 size_t commits_nr, commits_alloc;
963
964 struct write_midx_context *ctx;
965};
966
967static const struct object_id *bitmap_oid_access(size_t index,
968 const void *_entries)
969{
970 const struct pack_midx_entry *entries = _entries;
971 return &entries[index].oid;
972}
973
974static void bitmap_show_commit(struct commit *commit, void *_data)
975{
976 struct bitmap_commit_cb *data = _data;
977 int pos = oid_pos(&commit->object.oid, data->ctx->entries,
978 data->ctx->entries_nr,
979 bitmap_oid_access);
980 if (pos < 0)
981 return;
982
983 ALLOC_GROW(data->commits, data->commits_nr + 1, data->commits_alloc);
984 data->commits[data->commits_nr++] = commit;
985}
986
08944d1c
TB
987static int read_refs_snapshot(const char *refs_snapshot,
988 struct rev_info *revs)
989{
990 struct strbuf buf = STRBUF_INIT;
991 struct object_id oid;
992 FILE *f = xfopen(refs_snapshot, "r");
993
994 while (strbuf_getline(&buf, f) != EOF) {
995 struct object *object;
996 int preferred = 0;
997 char *hex = buf.buf;
998 const char *end = NULL;
999
1000 if (buf.len && *buf.buf == '+') {
1001 preferred = 1;
1002 hex = &buf.buf[1];
1003 }
1004
1005 if (parse_oid_hex(hex, &oid, &end) < 0)
1006 die(_("could not parse line: %s"), buf.buf);
1007 if (*end)
1008 die(_("malformed line: %s"), buf.buf);
1009
1010 object = parse_object_or_die(&oid, NULL);
1011 if (preferred)
1012 object->flags |= NEEDS_BITMAP;
1013
1014 add_pending_object(revs, object, "");
1015 }
1016
1017 fclose(f);
1018 strbuf_release(&buf);
1019 return 0;
1020}
1021
c528e179 1022static struct commit **find_commits_for_midx_bitmap(uint32_t *indexed_commits_nr_p,
08944d1c 1023 const char *refs_snapshot,
c528e179
TB
1024 struct write_midx_context *ctx)
1025{
1026 struct rev_info revs;
1027 struct bitmap_commit_cb cb = {0};
1028
1029 cb.ctx = ctx;
1030
1031 repo_init_revisions(the_repository, &revs, NULL);
08944d1c
TB
1032 if (refs_snapshot) {
1033 read_refs_snapshot(refs_snapshot, &revs);
1034 } else {
1035 setup_revisions(0, NULL, &revs, NULL);
1036 for_each_ref(add_ref_to_pending, &revs);
1037 }
c528e179
TB
1038
1039 /*
1040 * Skipping promisor objects here is intentional, since it only excludes
1041 * them from the list of reachable commits that we want to select from
1042 * when computing the selection of MIDX'd commits to receive bitmaps.
1043 *
1044 * Reachability bitmaps do require that their objects be closed under
1045 * reachability, but fetching any objects missing from promisors at this
1046 * point is too late. But, if one of those objects can be reached from
1047 * an another object that is included in the bitmap, then we will
1048 * complain later that we don't have reachability closure (and fail
1049 * appropriately).
1050 */
1051 fetch_if_missing = 0;
1052 revs.exclude_promisor_objects = 1;
1053
1054 if (prepare_revision_walk(&revs))
1055 die(_("revision walk setup failed"));
1056
1057 traverse_commit_list(&revs, bitmap_show_commit, NULL, &cb);
1058 if (indexed_commits_nr_p)
1059 *indexed_commits_nr_p = cb.commits_nr;
1060
1061 return cb.commits;
1062}
1063
1064static int write_midx_bitmap(char *midx_name, unsigned char *midx_hash,
1065 struct write_midx_context *ctx,
08944d1c 1066 const char *refs_snapshot,
c528e179
TB
1067 unsigned flags)
1068{
1069 struct packing_data pdata;
1070 struct pack_idx_entry **index;
1071 struct commit **commits = NULL;
1072 uint32_t i, commits_nr;
caca3c9f 1073 uint16_t options = 0;
c528e179
TB
1074 char *bitmap_name = xstrfmt("%s-%s.bitmap", midx_name, hash_to_hex(midx_hash));
1075 int ret;
1076
caca3c9f
TB
1077 if (flags & MIDX_WRITE_BITMAP_HASH_CACHE)
1078 options |= BITMAP_OPT_HASH_CACHE;
1079
c528e179
TB
1080 prepare_midx_packing_data(&pdata, ctx);
1081
08944d1c 1082 commits = find_commits_for_midx_bitmap(&commits_nr, refs_snapshot, ctx);
c528e179
TB
1083
1084 /*
1085 * Build the MIDX-order index based on pdata.objects (which is already
1086 * in MIDX order; c.f., 'midx_pack_order_cmp()' for the definition of
1087 * this order).
1088 */
1089 ALLOC_ARRAY(index, pdata.nr_objects);
1090 for (i = 0; i < pdata.nr_objects; i++)
1091 index[i] = &pdata.objects[i].idx;
1092
1093 bitmap_writer_show_progress(flags & MIDX_PROGRESS);
1094 bitmap_writer_build_type_index(&pdata, index, pdata.nr_objects);
1095
1096 /*
1097 * bitmap_writer_finish expects objects in lex order, but pack_order
1098 * gives us exactly that. use it directly instead of re-sorting the
1099 * array.
1100 *
1101 * This changes the order of objects in 'index' between
1102 * bitmap_writer_build_type_index and bitmap_writer_finish.
1103 *
1104 * The same re-ordering takes place in the single-pack bitmap code via
1105 * write_idx_file(), which is called by finish_tmp_packfile(), which
1106 * happens between bitmap_writer_build_type_index() and
1107 * bitmap_writer_finish().
1108 */
1109 for (i = 0; i < pdata.nr_objects; i++)
1110 index[ctx->pack_order[i]] = &pdata.objects[i].idx;
1111
1112 bitmap_writer_select_commits(commits, commits_nr, -1);
1113 ret = bitmap_writer_build(&pdata);
1114 if (ret < 0)
1115 goto cleanup;
1116
1117 bitmap_writer_set_checksum(midx_hash);
caca3c9f 1118 bitmap_writer_finish(index, pdata.nr_objects, bitmap_name, options);
c528e179
TB
1119
1120cleanup:
1121 free(index);
1122 free(bitmap_name);
1123 return ret;
1124}
1125
504131ac
TB
1126static struct multi_pack_index *lookup_multi_pack_index(struct repository *r,
1127 const char *object_dir)
1128{
1129 struct multi_pack_index *cur;
1130
1131 /* Ensure the given object_dir is local, or a known alternate. */
1132 find_odb(r, object_dir);
1133
1134 for (cur = get_multi_pack_index(r); cur; cur = cur->next) {
1135 if (!strcmp(object_dir, cur->object_dir))
1136 return cur;
1137 }
1138
1139 return NULL;
1140}
1141
f57a7396 1142static int write_midx_internal(const char *object_dir,
56d863e9 1143 struct string_list *packs_to_include,
9218c6a4
TB
1144 struct string_list *packs_to_drop,
1145 const char *preferred_pack_name,
08944d1c 1146 const char *refs_snapshot,
9218c6a4 1147 unsigned flags)
a3407730 1148{
60980aed 1149 struct strbuf midx_name = STRBUF_INIT;
9f191611 1150 unsigned char midx_hash[GIT_MAX_RAWSZ];
396f2570 1151 uint32_t i;
fc59e748
DS
1152 struct hashfile *f = NULL;
1153 struct lock_file lk;
577dc496 1154 struct write_midx_context ctx = { 0 };
dba6175c 1155 int pack_name_concat_len = 0;
19575c7c
DS
1156 int dropped_packs = 0;
1157 int result = 0;
63a8f0e9 1158 struct chunkfile *cf;
fc59e748 1159
60980aed
TB
1160 get_midx_filename(&midx_name, object_dir);
1161 if (safe_create_leading_directories(midx_name.buf))
fc59e748 1162 die_errno(_("unable to create leading directories of %s"),
60980aed 1163 midx_name.buf);
fc59e748 1164
56d863e9
TB
1165 if (!packs_to_include) {
1166 /*
1167 * Only reference an existing MIDX when not filtering which
1168 * packs to include, since all packs and objects are copied
1169 * blindly from an existing MIDX if one is present.
1170 */
504131ac 1171 ctx.m = lookup_multi_pack_index(the_repository, object_dir);
f57a7396 1172 }
577dc496 1173
ec1e28ef
TB
1174 if (ctx.m && !midx_checksum_valid(ctx.m)) {
1175 warning(_("ignoring existing multi-pack-index; checksum mismatch"));
1176 ctx.m = NULL;
1177 }
1178
577dc496
DS
1179 ctx.nr = 0;
1180 ctx.alloc = ctx.m ? ctx.m->num_packs : 16;
1181 ctx.info = NULL;
1182 ALLOC_ARRAY(ctx.info, ctx.alloc);
1183
1184 if (ctx.m) {
1185 for (i = 0; i < ctx.m->num_packs; i++) {
1186 ALLOC_GROW(ctx.info, ctx.nr + 1, ctx.alloc);
1187
1188 ctx.info[ctx.nr].orig_pack_int_id = i;
1189 ctx.info[ctx.nr].pack_name = xstrdup(ctx.m->pack_names[i]);
c528e179 1190 ctx.info[ctx.nr].p = ctx.m->packs[i];
577dc496 1191 ctx.info[ctx.nr].expired = 0;
5d3cd09a
TB
1192
1193 if (flags & MIDX_WRITE_REV_INDEX) {
1194 /*
1195 * If generating a reverse index, need to have
1196 * packed_git's loaded to compare their
1197 * mtimes and object count.
1198 */
1199 if (prepare_midx_pack(the_repository, ctx.m, i)) {
1200 error(_("could not load pack"));
1201 result = 1;
1202 goto cleanup;
1203 }
1204
1205 if (open_pack_index(ctx.m->packs[i]))
1206 die(_("could not open index for %s"),
1207 ctx.m->packs[i]->pack_name);
1208 ctx.info[ctx.nr].p = ctx.m->packs[i];
1209 }
1210
577dc496 1211 ctx.nr++;
a40498a1
DS
1212 }
1213 }
1214
577dc496 1215 ctx.pack_paths_checked = 0;
840cef0c 1216 if (flags & MIDX_PROGRESS)
577dc496 1217 ctx.progress = start_delayed_progress(_("Adding packfiles to multi-pack-index"), 0);
840cef0c 1218 else
577dc496 1219 ctx.progress = NULL;
840cef0c 1220
56d863e9
TB
1221 ctx.to_include = packs_to_include;
1222
577dc496
DS
1223 for_each_file_in_pack_dir(object_dir, add_pack_to_midx, &ctx);
1224 stop_progress(&ctx.progress);
396f2570 1225
56d863e9
TB
1226 if ((ctx.m && ctx.nr == ctx.m->num_packs) &&
1227 !(packs_to_include || packs_to_drop)) {
c528e179
TB
1228 struct bitmap_index *bitmap_git;
1229 int bitmap_exists;
1230 int want_bitmap = flags & MIDX_WRITE_BITMAP;
1231
bfbb60d3 1232 bitmap_git = prepare_midx_bitmap_git(ctx.m);
c528e179
TB
1233 bitmap_exists = bitmap_git && bitmap_is_midx(bitmap_git);
1234 free_bitmap_index(bitmap_git);
1235
1236 if (bitmap_exists || !want_bitmap) {
1237 /*
1238 * The correct MIDX already exists, and so does a
1239 * corresponding bitmap (or one wasn't requested).
1240 */
1241 if (!want_bitmap)
1242 clear_midx_files_ext(object_dir, ".bitmap",
1243 NULL);
1244 goto cleanup;
1245 }
1246 }
a40498a1 1247
9218c6a4 1248 if (preferred_pack_name) {
177c0d6e 1249 int found = 0;
9218c6a4
TB
1250 for (i = 0; i < ctx.nr; i++) {
1251 if (!cmp_idx_or_pack_name(preferred_pack_name,
1252 ctx.info[i].pack_name)) {
1253 ctx.preferred_pack_idx = i;
177c0d6e 1254 found = 1;
9218c6a4
TB
1255 break;
1256 }
1257 }
177c0d6e
TB
1258
1259 if (!found)
1260 warning(_("unknown preferred pack: '%s'"),
1261 preferred_pack_name);
c528e179
TB
1262 } else if (ctx.nr &&
1263 (flags & (MIDX_WRITE_REV_INDEX | MIDX_WRITE_BITMAP))) {
177c0d6e
TB
1264 struct packed_git *oldest = ctx.info[ctx.preferred_pack_idx].p;
1265 ctx.preferred_pack_idx = 0;
1266
1267 if (packs_to_drop && packs_to_drop->nr)
1268 BUG("cannot write a MIDX bitmap during expiration");
1269
1270 /*
1271 * set a preferred pack when writing a bitmap to ensure that
1272 * the pack from which the first object is selected in pseudo
1273 * pack-order has all of its objects selected from that pack
1274 * (and not another pack containing a duplicate)
1275 */
1276 for (i = 1; i < ctx.nr; i++) {
1277 struct packed_git *p = ctx.info[i].p;
1278
1279 if (!oldest->num_objects || p->mtime < oldest->mtime) {
1280 oldest = p;
1281 ctx.preferred_pack_idx = i;
1282 }
1283 }
1284
1285 if (!oldest->num_objects) {
1286 /*
1287 * If all packs are empty; unset the preferred index.
1288 * This is acceptable since there will be no duplicate
1289 * objects to resolve, so the preferred value doesn't
1290 * matter.
1291 */
1292 ctx.preferred_pack_idx = -1;
1293 }
1294 } else {
1295 /*
1296 * otherwise don't mark any pack as preferred to avoid
1297 * interfering with expiration logic below
1298 */
1299 ctx.preferred_pack_idx = -1;
9218c6a4
TB
1300 }
1301
5d3cd09a
TB
1302 if (ctx.preferred_pack_idx > -1) {
1303 struct packed_git *preferred = ctx.info[ctx.preferred_pack_idx].p;
1304 if (!preferred->num_objects) {
1305 error(_("cannot select preferred pack %s with no objects"),
1306 preferred->pack_name);
1307 result = 1;
1308 goto cleanup;
1309 }
1310 }
1311
9218c6a4
TB
1312 ctx.entries = get_sorted_entries(ctx.m, ctx.info, ctx.nr, &ctx.entries_nr,
1313 ctx.preferred_pack_idx);
a40498a1 1314
7a3ada11 1315 ctx.large_offsets_needed = 0;
31bda9a2
DS
1316 for (i = 0; i < ctx.entries_nr; i++) {
1317 if (ctx.entries[i].offset > 0x7fffffff)
980f525c 1318 ctx.num_large_offsets++;
31bda9a2 1319 if (ctx.entries[i].offset > 0xffffffff)
7a3ada11 1320 ctx.large_offsets_needed = 1;
662148c4 1321 }
fe1ed56f 1322
577dc496 1323 QSORT(ctx.info, ctx.nr, pack_info_compare);
d01bf2e6 1324
19575c7c
DS
1325 if (packs_to_drop && packs_to_drop->nr) {
1326 int drop_index = 0;
1327 int missing_drops = 0;
1328
577dc496
DS
1329 for (i = 0; i < ctx.nr && drop_index < packs_to_drop->nr; i++) {
1330 int cmp = strcmp(ctx.info[i].pack_name,
19575c7c
DS
1331 packs_to_drop->items[drop_index].string);
1332
1333 if (!cmp) {
1334 drop_index++;
577dc496 1335 ctx.info[i].expired = 1;
19575c7c
DS
1336 } else if (cmp > 0) {
1337 error(_("did not see pack-file %s to drop"),
1338 packs_to_drop->items[drop_index].string);
1339 drop_index++;
1340 missing_drops++;
1341 i--;
1342 } else {
577dc496 1343 ctx.info[i].expired = 0;
19575c7c
DS
1344 }
1345 }
1346
1347 if (missing_drops) {
1348 result = 1;
1349 goto cleanup;
1350 }
1351 }
1352
d01bf2e6
DS
1353 /*
1354 * pack_perm stores a permutation between pack-int-ids from the
1355 * previous multi-pack-index to the new one we are writing:
1356 *
1357 * pack_perm[old_id] = new_id
1358 */
7a3ada11 1359 ALLOC_ARRAY(ctx.pack_perm, ctx.nr);
577dc496
DS
1360 for (i = 0; i < ctx.nr; i++) {
1361 if (ctx.info[i].expired) {
19575c7c 1362 dropped_packs++;
7a3ada11 1363 ctx.pack_perm[ctx.info[i].orig_pack_int_id] = PACK_EXPIRED;
19575c7c 1364 } else {
7a3ada11 1365 ctx.pack_perm[ctx.info[i].orig_pack_int_id] = i - dropped_packs;
19575c7c 1366 }
d01bf2e6
DS
1367 }
1368
577dc496
DS
1369 for (i = 0; i < ctx.nr; i++) {
1370 if (!ctx.info[i].expired)
1371 pack_name_concat_len += strlen(ctx.info[i].pack_name) + 1;
19575c7c 1372 }
dba6175c 1373
9218c6a4
TB
1374 /* Check that the preferred pack wasn't expired (if given). */
1375 if (preferred_pack_name) {
1376 struct pack_info *preferred = bsearch(preferred_pack_name,
1377 ctx.info, ctx.nr,
1378 sizeof(*ctx.info),
1379 idx_or_pack_name_cmp);
177c0d6e 1380 if (preferred) {
9218c6a4
TB
1381 uint32_t perm = ctx.pack_perm[preferred->orig_pack_int_id];
1382 if (perm == PACK_EXPIRED)
1383 warning(_("preferred pack '%s' is expired"),
1384 preferred_pack_name);
1385 }
1386 }
1387
dba6175c
DS
1388 if (pack_name_concat_len % MIDX_CHUNK_ALIGNMENT)
1389 pack_name_concat_len += MIDX_CHUNK_ALIGNMENT -
1390 (pack_name_concat_len % MIDX_CHUNK_ALIGNMENT);
1391
60980aed 1392 hold_lock_file_for_update(&lk, midx_name.buf, LOCK_DIE_ON_ERROR);
acd71602 1393 f = hashfd(get_lock_file_fd(&lk), get_lock_file_path(&lk));
fc59e748 1394
577dc496 1395 if (ctx.nr - dropped_packs == 0) {
796d61cd
DR
1396 error(_("no pack files to index."));
1397 result = 1;
1398 goto cleanup;
1399 }
1400
63a8f0e9 1401 cf = init_chunkfile(f);
32f3c541 1402
63a8f0e9
DS
1403 add_chunk(cf, MIDX_CHUNKID_PACKNAMES, pack_name_concat_len,
1404 write_midx_pack_names);
1405 add_chunk(cf, MIDX_CHUNKID_OIDFANOUT, MIDX_CHUNK_FANOUT_SIZE,
1406 write_midx_oid_fanout);
1407 add_chunk(cf, MIDX_CHUNKID_OIDLOOKUP,
329fac3a 1408 (size_t)ctx.entries_nr * the_hash_algo->rawsz,
63a8f0e9
DS
1409 write_midx_oid_lookup);
1410 add_chunk(cf, MIDX_CHUNKID_OBJECTOFFSETS,
329fac3a 1411 (size_t)ctx.entries_nr * MIDX_CHUNK_OFFSET_WIDTH,
63a8f0e9 1412 write_midx_object_offsets);
32f3c541 1413
63a8f0e9
DS
1414 if (ctx.large_offsets_needed)
1415 add_chunk(cf, MIDX_CHUNKID_LARGEOFFSETS,
329fac3a 1416 (size_t)ctx.num_large_offsets * MIDX_CHUNK_LARGE_OFFSET_WIDTH,
63a8f0e9 1417 write_midx_large_offsets);
32f3c541 1418
95e8383b
TB
1419 if (flags & (MIDX_WRITE_REV_INDEX | MIDX_WRITE_BITMAP)) {
1420 ctx.pack_order = midx_pack_order(&ctx);
1421 add_chunk(cf, MIDX_CHUNKID_REVINDEX,
1422 ctx.entries_nr * sizeof(uint32_t),
1423 write_midx_revindex);
1424 }
1425
63a8f0e9
DS
1426 write_midx_header(f, get_num_chunks(cf), ctx.nr - dropped_packs);
1427 write_chunkfile(cf, &ctx);
fc59e748 1428
9f191611 1429 finalize_hashfile(f, midx_hash, CSUM_FSYNC | CSUM_HASH_IN_STREAM);
63a8f0e9 1430 free_chunkfile(cf);
38ff7cab 1431
38ff7cab 1432 if (flags & MIDX_WRITE_REV_INDEX)
60980aed 1433 write_midx_reverse_index(midx_name.buf, midx_hash, &ctx);
c528e179 1434 if (flags & MIDX_WRITE_BITMAP) {
60980aed 1435 if (write_midx_bitmap(midx_name.buf, midx_hash, &ctx,
08944d1c 1436 refs_snapshot, flags) < 0) {
c528e179
TB
1437 error(_("could not write multi-pack bitmap"));
1438 result = 1;
1439 goto cleanup;
1440 }
1441 }
1442
1443 if (ctx.m)
1444 close_object_store(the_repository->objects);
38ff7cab 1445
ae22e841
TB
1446 if (commit_lock_file(&lk) < 0)
1447 die_errno(_("could not write multi-pack-index"));
fc59e748 1448
c528e179 1449 clear_midx_files_ext(object_dir, ".bitmap", midx_hash);
f5909d34
TB
1450 clear_midx_files_ext(object_dir, ".rev", midx_hash);
1451
a40498a1 1452cleanup:
577dc496
DS
1453 for (i = 0; i < ctx.nr; i++) {
1454 if (ctx.info[i].p) {
1455 close_pack(ctx.info[i].p);
1456 free(ctx.info[i].p);
396f2570 1457 }
577dc496 1458 free(ctx.info[i].pack_name);
396f2570
DS
1459 }
1460
577dc496 1461 free(ctx.info);
31bda9a2 1462 free(ctx.entries);
7a3ada11 1463 free(ctx.pack_perm);
38ff7cab 1464 free(ctx.pack_order);
60980aed 1465 strbuf_release(&midx_name);
c528e179 1466
19575c7c
DS
1467 return result;
1468}
1469
9218c6a4
TB
1470int write_midx_file(const char *object_dir,
1471 const char *preferred_pack_name,
08944d1c 1472 const char *refs_snapshot,
9218c6a4 1473 unsigned flags)
19575c7c 1474{
56d863e9 1475 return write_midx_internal(object_dir, NULL, NULL, preferred_pack_name,
08944d1c 1476 refs_snapshot, flags);
56d863e9
TB
1477}
1478
1479int write_midx_file_only(const char *object_dir,
1480 struct string_list *packs_to_include,
1481 const char *preferred_pack_name,
08944d1c 1482 const char *refs_snapshot,
56d863e9
TB
1483 unsigned flags)
1484{
1485 return write_midx_internal(object_dir, packs_to_include, NULL,
08944d1c 1486 preferred_pack_name, refs_snapshot, flags);
a3407730 1487}
525e18c0 1488
38ff7cab
TB
1489struct clear_midx_data {
1490 char *keep;
1491 const char *ext;
1492};
1493
1494static void clear_midx_file_ext(const char *full_path, size_t full_path_len,
1495 const char *file_name, void *_data)
1496{
1497 struct clear_midx_data *data = _data;
1498
1499 if (!(starts_with(file_name, "multi-pack-index-") &&
1500 ends_with(file_name, data->ext)))
1501 return;
1502 if (data->keep && !strcmp(data->keep, file_name))
1503 return;
1504
1505 if (unlink(full_path))
1506 die_errno(_("failed to remove %s"), full_path);
1507}
1508
426c00e4 1509static void clear_midx_files_ext(const char *object_dir, const char *ext,
38ff7cab
TB
1510 unsigned char *keep_hash)
1511{
1512 struct clear_midx_data data;
1513 memset(&data, 0, sizeof(struct clear_midx_data));
1514
1515 if (keep_hash)
1516 data.keep = xstrfmt("multi-pack-index-%s%s",
1517 hash_to_hex(keep_hash), ext);
1518 data.ext = ext;
1519
426c00e4 1520 for_each_file_in_pack_dir(object_dir,
38ff7cab
TB
1521 clear_midx_file_ext,
1522 &data);
1523
1524 free(data.keep);
a3407730 1525}
525e18c0 1526
1dcd9f20 1527void clear_midx_file(struct repository *r)
525e18c0 1528{
60980aed
TB
1529 struct strbuf midx = STRBUF_INIT;
1530
1531 get_midx_filename(&midx, r->objects->odb->path);
1dcd9f20
DS
1532
1533 if (r->objects && r->objects->multi_pack_index) {
1534 close_midx(r->objects->multi_pack_index);
1535 r->objects->multi_pack_index = NULL;
1536 }
525e18c0 1537
60980aed
TB
1538 if (remove_path(midx.buf))
1539 die(_("failed to clear multi-pack-index at %s"), midx.buf);
525e18c0 1540
c528e179 1541 clear_midx_files_ext(r->objects->odb->path, ".bitmap", NULL);
426c00e4 1542 clear_midx_files_ext(r->objects->odb->path, ".rev", NULL);
38ff7cab 1543
60980aed 1544 strbuf_release(&midx);
525e18c0 1545}
56ee7ff1
DS
1546
1547static int verify_midx_error;
1548
48ca53ca 1549__attribute__((format (printf, 1, 2)))
d4bf1d88
DS
1550static void midx_report(const char *fmt, ...)
1551{
1552 va_list ap;
1553 verify_midx_error = 1;
1554 va_start(ap, fmt);
1555 vfprintf(stderr, fmt, ap);
1556 fprintf(stderr, "\n");
1557 va_end(ap);
1558}
1559
5ae18df9
JH
1560struct pair_pos_vs_id
1561{
1562 uint32_t pos;
1563 uint32_t pack_int_id;
1564};
1565
1566static int compare_pair_pos_vs_id(const void *_a, const void *_b)
1567{
1568 struct pair_pos_vs_id *a = (struct pair_pos_vs_id *)_a;
1569 struct pair_pos_vs_id *b = (struct pair_pos_vs_id *)_b;
1570
1571 return b->pack_int_id - a->pack_int_id;
1572}
1573
430efb8a
JH
1574/*
1575 * Limit calls to display_progress() for performance reasons.
1576 * The interval here was arbitrarily chosen.
1577 */
1578#define SPARSE_PROGRESS_INTERVAL (1 << 12)
1579#define midx_display_sparse_progress(progress, n) \
1580 do { \
1581 uint64_t _n = (n); \
1582 if ((_n & (SPARSE_PROGRESS_INTERVAL - 1)) == 0) \
1583 display_progress(progress, _n); \
1584 } while (0)
1585
efbc3aee 1586int verify_midx_file(struct repository *r, const char *object_dir, unsigned flags)
56ee7ff1 1587{
5ae18df9 1588 struct pair_pos_vs_id *pairs = NULL;
d4bf1d88 1589 uint32_t i;
ad60096d 1590 struct progress *progress = NULL;
56ee7ff1
DS
1591 struct multi_pack_index *m = load_multi_pack_index(object_dir, 1);
1592 verify_midx_error = 0;
1593
d9607542
DS
1594 if (!m) {
1595 int result = 0;
1596 struct stat sb;
60980aed
TB
1597 struct strbuf filename = STRBUF_INIT;
1598
1599 get_midx_filename(&filename, object_dir);
1600
1601 if (!stat(filename.buf, &sb)) {
d9607542
DS
1602 error(_("multi-pack-index file exists, but failed to parse"));
1603 result = 1;
1604 }
60980aed 1605 strbuf_release(&filename);
d9607542
DS
1606 return result;
1607 }
56ee7ff1 1608
f89ecf79
TB
1609 if (!midx_checksum_valid(m))
1610 midx_report(_("incorrect checksum"));
1611
ad60096d 1612 if (flags & MIDX_PROGRESS)
efdd2f0d 1613 progress = start_delayed_progress(_("Looking for referenced packfiles"),
ad60096d 1614 m->num_packs);
d4bf1d88 1615 for (i = 0; i < m->num_packs; i++) {
64404a24 1616 if (prepare_midx_pack(r, m, i))
d4bf1d88 1617 midx_report("failed to load pack in position %d", i);
430efb8a
JH
1618
1619 display_progress(progress, i + 1);
d4bf1d88 1620 }
430efb8a 1621 stop_progress(&progress);
d4bf1d88 1622
2f23d3f3
DS
1623 for (i = 0; i < 255; i++) {
1624 uint32_t oid_fanout1 = ntohl(m->chunk_oid_fanout[i]);
1625 uint32_t oid_fanout2 = ntohl(m->chunk_oid_fanout[i + 1]);
1626
1627 if (oid_fanout1 > oid_fanout2)
1628 midx_report(_("oid fanout out of order: fanout[%d] = %"PRIx32" > %"PRIx32" = fanout[%d]"),
1629 i, oid_fanout1, oid_fanout2, i + 1);
1630 }
1631
796d61cd
DR
1632 if (m->num_objects == 0) {
1633 midx_report(_("the midx contains no oid"));
1634 /*
1635 * Remaining tests assume that we have objects, so we can
1636 * return here.
1637 */
492cb394 1638 goto cleanup;
796d61cd
DR
1639 }
1640
ad60096d
WB
1641 if (flags & MIDX_PROGRESS)
1642 progress = start_sparse_progress(_("Verifying OID order in multi-pack-index"),
1643 m->num_objects - 1);
55c5648d
DS
1644 for (i = 0; i < m->num_objects - 1; i++) {
1645 struct object_id oid1, oid2;
1646
1647 nth_midxed_object_oid(&oid1, m, i);
1648 nth_midxed_object_oid(&oid2, m, i + 1);
1649
1650 if (oidcmp(&oid1, &oid2) >= 0)
1651 midx_report(_("oid lookup out of order: oid[%d] = %s >= %s = oid[%d]"),
1652 i, oid_to_hex(&oid1), oid_to_hex(&oid2), i + 1);
430efb8a
JH
1653
1654 midx_display_sparse_progress(progress, i + 1);
55c5648d 1655 }
430efb8a 1656 stop_progress(&progress);
55c5648d 1657
5ae18df9
JH
1658 /*
1659 * Create an array mapping each object to its packfile id. Sort it
1660 * to group the objects by packfile. Use this permutation to visit
1661 * each of the objects and only require 1 packfile to be open at a
1662 * time.
1663 */
1664 ALLOC_ARRAY(pairs, m->num_objects);
1665 for (i = 0; i < m->num_objects; i++) {
1666 pairs[i].pos = i;
1667 pairs[i].pack_int_id = nth_midxed_pack_int_id(m, i);
1668 }
1669
ad60096d
WB
1670 if (flags & MIDX_PROGRESS)
1671 progress = start_sparse_progress(_("Sorting objects by packfile"),
1672 m->num_objects);
5ae18df9
JH
1673 display_progress(progress, 0); /* TODO: Measure QSORT() progress */
1674 QSORT(pairs, m->num_objects, compare_pair_pos_vs_id);
1675 stop_progress(&progress);
1676
ad60096d
WB
1677 if (flags & MIDX_PROGRESS)
1678 progress = start_sparse_progress(_("Verifying object offsets"), m->num_objects);
cc6af73c
DS
1679 for (i = 0; i < m->num_objects; i++) {
1680 struct object_id oid;
1681 struct pack_entry e;
1682 off_t m_offset, p_offset;
1683
5ae18df9
JH
1684 if (i > 0 && pairs[i-1].pack_int_id != pairs[i].pack_int_id &&
1685 m->packs[pairs[i-1].pack_int_id])
1686 {
1687 close_pack_fd(m->packs[pairs[i-1].pack_int_id]);
1688 close_pack_index(m->packs[pairs[i-1].pack_int_id]);
1689 }
1690
1691 nth_midxed_object_oid(&oid, m, pairs[i].pos);
1692
64404a24 1693 if (!fill_midx_entry(r, &oid, &e, m)) {
cc6af73c 1694 midx_report(_("failed to load pack entry for oid[%d] = %s"),
5ae18df9 1695 pairs[i].pos, oid_to_hex(&oid));
cc6af73c
DS
1696 continue;
1697 }
1698
1699 if (open_pack_index(e.p)) {
1700 midx_report(_("failed to load pack-index for packfile %s"),
1701 e.p->pack_name);
1702 break;
1703 }
1704
1705 m_offset = e.offset;
1706 p_offset = find_pack_entry_one(oid.hash, e.p);
1707
1708 if (m_offset != p_offset)
1709 midx_report(_("incorrect object offset for oid[%d] = %s: %"PRIx64" != %"PRIx64),
5ae18df9 1710 pairs[i].pos, oid_to_hex(&oid), m_offset, p_offset);
144d7033 1711
430efb8a 1712 midx_display_sparse_progress(progress, i + 1);
cc6af73c 1713 }
144d7033 1714 stop_progress(&progress);
cc6af73c 1715
492cb394 1716cleanup:
5ae18df9 1717 free(pairs);
492cb394 1718 close_midx(m);
5ae18df9 1719
56ee7ff1
DS
1720 return verify_midx_error;
1721}
cff97116 1722
efbc3aee 1723int expire_midx_packs(struct repository *r, const char *object_dir, unsigned flags)
cff97116 1724{
19575c7c
DS
1725 uint32_t i, *count, result = 0;
1726 struct string_list packs_to_drop = STRING_LIST_INIT_DUP;
98926e0d 1727 struct multi_pack_index *m = lookup_multi_pack_index(r, object_dir);
8dc18f89 1728 struct progress *progress = NULL;
19575c7c
DS
1729
1730 if (!m)
1731 return 0;
1732
ca56dadb 1733 CALLOC_ARRAY(count, m->num_packs);
8dc18f89
WB
1734
1735 if (flags & MIDX_PROGRESS)
efdd2f0d 1736 progress = start_delayed_progress(_("Counting referenced objects"),
8dc18f89 1737 m->num_objects);
19575c7c
DS
1738 for (i = 0; i < m->num_objects; i++) {
1739 int pack_int_id = nth_midxed_pack_int_id(m, i);
1740 count[pack_int_id]++;
8dc18f89 1741 display_progress(progress, i + 1);
19575c7c 1742 }
8dc18f89 1743 stop_progress(&progress);
19575c7c 1744
8dc18f89 1745 if (flags & MIDX_PROGRESS)
efdd2f0d 1746 progress = start_delayed_progress(_("Finding and deleting unreferenced packfiles"),
8dc18f89 1747 m->num_packs);
19575c7c
DS
1748 for (i = 0; i < m->num_packs; i++) {
1749 char *pack_name;
8dc18f89 1750 display_progress(progress, i + 1);
19575c7c
DS
1751
1752 if (count[i])
1753 continue;
1754
1755 if (prepare_midx_pack(r, m, i))
1756 continue;
1757
1758 if (m->packs[i]->pack_keep)
1759 continue;
1760
1761 pack_name = xstrdup(m->packs[i]->pack_name);
1762 close_pack(m->packs[i]);
1763
1764 string_list_insert(&packs_to_drop, m->pack_names[i]);
1765 unlink_pack_path(pack_name, 0);
1766 free(pack_name);
1767 }
8dc18f89 1768 stop_progress(&progress);
19575c7c
DS
1769
1770 free(count);
1771
98926e0d 1772 if (packs_to_drop.nr)
08944d1c 1773 result = write_midx_internal(object_dir, NULL, &packs_to_drop, NULL, NULL, flags);
19575c7c
DS
1774
1775 string_list_clear(&packs_to_drop, 0);
98926e0d 1776
19575c7c 1777 return result;
cff97116 1778}
2af890bb 1779
ce1e4a10
DS
1780struct repack_info {
1781 timestamp_t mtime;
1782 uint32_t referenced_objects;
1783 uint32_t pack_int_id;
1784};
1785
1786static int compare_by_mtime(const void *a_, const void *b_)
2af890bb 1787{
ce1e4a10
DS
1788 const struct repack_info *a, *b;
1789
1790 a = (const struct repack_info *)a_;
1791 b = (const struct repack_info *)b_;
1792
1793 if (a->mtime < b->mtime)
1794 return -1;
1795 if (a->mtime > b->mtime)
1796 return 1;
1797 return 0;
1798}
1799
3ce4ca0a
DS
1800static int fill_included_packs_all(struct repository *r,
1801 struct multi_pack_index *m,
ce1e4a10
DS
1802 unsigned char *include_pack)
1803{
3ce4ca0a
DS
1804 uint32_t i, count = 0;
1805 int pack_kept_objects = 0;
1806
1807 repo_config_get_bool(r, "repack.packkeptobjects", &pack_kept_objects);
1808
1809 for (i = 0; i < m->num_packs; i++) {
1810 if (prepare_midx_pack(r, m, i))
1811 continue;
1812 if (!pack_kept_objects && m->packs[i]->pack_keep)
1813 continue;
ce1e4a10 1814
ce1e4a10 1815 include_pack[i] = 1;
3ce4ca0a
DS
1816 count++;
1817 }
ce1e4a10 1818
3ce4ca0a 1819 return count < 2;
ce1e4a10
DS
1820}
1821
1822static int fill_included_packs_batch(struct repository *r,
1823 struct multi_pack_index *m,
1824 unsigned char *include_pack,
1825 size_t batch_size)
1826{
1827 uint32_t i, packs_to_repack;
1828 size_t total_size;
1829 struct repack_info *pack_info = xcalloc(m->num_packs, sizeof(struct repack_info));
3ce4ca0a
DS
1830 int pack_kept_objects = 0;
1831
1832 repo_config_get_bool(r, "repack.packkeptobjects", &pack_kept_objects);
ce1e4a10
DS
1833
1834 for (i = 0; i < m->num_packs; i++) {
1835 pack_info[i].pack_int_id = i;
1836
1837 if (prepare_midx_pack(r, m, i))
1838 continue;
1839
1840 pack_info[i].mtime = m->packs[i]->mtime;
1841 }
1842
1843 for (i = 0; batch_size && i < m->num_objects; i++) {
1844 uint32_t pack_int_id = nth_midxed_pack_int_id(m, i);
1845 pack_info[pack_int_id].referenced_objects++;
1846 }
1847
1848 QSORT(pack_info, m->num_packs, compare_by_mtime);
1849
1850 total_size = 0;
1851 packs_to_repack = 0;
1852 for (i = 0; total_size < batch_size && i < m->num_packs; i++) {
1853 int pack_int_id = pack_info[i].pack_int_id;
1854 struct packed_git *p = m->packs[pack_int_id];
1855 size_t expected_size;
1856
1857 if (!p)
1858 continue;
3ce4ca0a
DS
1859 if (!pack_kept_objects && p->pack_keep)
1860 continue;
ce1e4a10
DS
1861 if (open_pack_index(p) || !p->num_objects)
1862 continue;
1863
1864 expected_size = (size_t)(p->pack_size
1865 * pack_info[i].referenced_objects);
1866 expected_size /= p->num_objects;
1867
1868 if (expected_size >= batch_size)
1869 continue;
1870
1871 packs_to_repack++;
1872 total_size += expected_size;
1873 include_pack[pack_int_id] = 1;
1874 }
1875
1876 free(pack_info);
1877
1eb22c7d 1878 if (packs_to_repack < 2)
ce1e4a10
DS
1879 return 1;
1880
2af890bb
DS
1881 return 0;
1882}
ce1e4a10 1883
efbc3aee 1884int midx_repack(struct repository *r, const char *object_dir, size_t batch_size, unsigned flags)
ce1e4a10
DS
1885{
1886 int result = 0;
1887 uint32_t i;
1888 unsigned char *include_pack;
1889 struct child_process cmd = CHILD_PROCESS_INIT;
6af3b00a 1890 FILE *cmd_in;
ce1e4a10 1891 struct strbuf base_name = STRBUF_INIT;
c0f1f9de 1892 struct multi_pack_index *m = lookup_multi_pack_index(r, object_dir);
ce1e4a10 1893
e11d86de
SLN
1894 /*
1895 * When updating the default for these configuration
1896 * variables in builtin/repack.c, these must be adjusted
1897 * to match.
1898 */
1899 int delta_base_offset = 1;
1900 int use_delta_islands = 0;
1901
ce1e4a10
DS
1902 if (!m)
1903 return 0;
1904
ca56dadb 1905 CALLOC_ARRAY(include_pack, m->num_packs);
ce1e4a10
DS
1906
1907 if (batch_size) {
1908 if (fill_included_packs_batch(r, m, include_pack, batch_size))
1909 goto cleanup;
3ce4ca0a 1910 } else if (fill_included_packs_all(r, m, include_pack))
ce1e4a10
DS
1911 goto cleanup;
1912
e11d86de
SLN
1913 repo_config_get_bool(r, "repack.usedeltabaseoffset", &delta_base_offset);
1914 repo_config_get_bool(r, "repack.usedeltaislands", &use_delta_islands);
1915
c972bf4c 1916 strvec_push(&cmd.args, "pack-objects");
ce1e4a10
DS
1917
1918 strbuf_addstr(&base_name, object_dir);
1919 strbuf_addstr(&base_name, "/pack/pack");
c972bf4c 1920 strvec_push(&cmd.args, base_name.buf);
64d80e7d 1921
e11d86de 1922 if (delta_base_offset)
c972bf4c 1923 strvec_push(&cmd.args, "--delta-base-offset");
e11d86de 1924 if (use_delta_islands)
c972bf4c 1925 strvec_push(&cmd.args, "--delta-islands");
e11d86de 1926
64d80e7d 1927 if (flags & MIDX_PROGRESS)
c972bf4c 1928 strvec_push(&cmd.args, "--progress");
64d80e7d 1929 else
c972bf4c 1930 strvec_push(&cmd.args, "-q");
64d80e7d 1931
ce1e4a10
DS
1932 strbuf_release(&base_name);
1933
1934 cmd.git_cmd = 1;
1935 cmd.in = cmd.out = -1;
1936
1937 if (start_command(&cmd)) {
1938 error(_("could not start pack-objects"));
1939 result = 1;
1940 goto cleanup;
1941 }
1942
6af3b00a
RS
1943 cmd_in = xfdopen(cmd.in, "w");
1944
ce1e4a10
DS
1945 for (i = 0; i < m->num_objects; i++) {
1946 struct object_id oid;
1947 uint32_t pack_int_id = nth_midxed_pack_int_id(m, i);
1948
1949 if (!include_pack[pack_int_id])
1950 continue;
1951
1952 nth_midxed_object_oid(&oid, m, i);
6af3b00a 1953 fprintf(cmd_in, "%s\n", oid_to_hex(&oid));
ce1e4a10 1954 }
6af3b00a 1955 fclose(cmd_in);
ce1e4a10
DS
1956
1957 if (finish_command(&cmd)) {
1958 error(_("could not finish pack-objects"));
1959 result = 1;
1960 goto cleanup;
1961 }
1962
08944d1c 1963 result = write_midx_internal(object_dir, NULL, NULL, NULL, NULL, flags);
ce1e4a10
DS
1964
1965cleanup:
ce1e4a10
DS
1966 free(include_pack);
1967 return result;
1968}