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