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