]> git.ipfire.org Git - thirdparty/git.git/blame - midx.c
midx: avoid opening multiple MIDXs when writing
[thirdparty/git.git] / midx.c
CommitLineData
a3407730 1#include "cache.h"
c4d25228 2#include "config.h"
fc59e748 3#include "csum-file.h"
396f2570 4#include "dir.h"
fc59e748 5#include "lockfile.h"
396f2570 6#include "packfile.h"
4d80560c 7#include "object-store.h"
bc626927 8#include "hash-lookup.h"
a3407730 9#include "midx.h"
144d7033 10#include "progress.h"
d829223a 11#include "trace2.h"
ce1e4a10 12#include "run-command.h"
18e449f8 13#include "repository.h"
63a8f0e9 14#include "chunk-format.h"
38ff7cab 15#include "pack.h"
a3407730 16
fc59e748
DS
17#define MIDX_SIGNATURE 0x4d494458 /* "MIDX" */
18#define MIDX_VERSION 1
4d80560c
DS
19#define MIDX_BYTE_FILE_VERSION 4
20#define MIDX_BYTE_HASH_VERSION 5
21#define MIDX_BYTE_NUM_CHUNKS 6
22#define MIDX_BYTE_NUM_PACKS 8
fc59e748 23#define MIDX_HEADER_SIZE 12
aaa95dfa 24#define MIDX_MIN_SIZE (MIDX_HEADER_SIZE + the_hash_algo->rawsz)
fc59e748 25
32f3c541
DS
26#define MIDX_CHUNK_ALIGNMENT 4
27#define MIDX_CHUNKID_PACKNAMES 0x504e414d /* "PNAM" */
d7cacf29 28#define MIDX_CHUNKID_OIDFANOUT 0x4f494446 /* "OIDF" */
0d5b3a5e 29#define MIDX_CHUNKID_OIDLOOKUP 0x4f49444c /* "OIDL" */
662148c4
DS
30#define MIDX_CHUNKID_OBJECTOFFSETS 0x4f4f4646 /* "OOFF" */
31#define MIDX_CHUNKID_LARGEOFFSETS 0x4c4f4646 /* "LOFF" */
d7cacf29 32#define MIDX_CHUNK_FANOUT_SIZE (sizeof(uint32_t) * 256)
662148c4
DS
33#define MIDX_CHUNK_OFFSET_WIDTH (2 * sizeof(uint32_t))
34#define MIDX_CHUNK_LARGE_OFFSET_WIDTH (sizeof(uint64_t))
35#define MIDX_LARGE_OFFSET_NEEDED 0x80000000
32f3c541 36
19575c7c
DS
37#define PACK_EXPIRED UINT_MAX
38
d9607542
DS
39static uint8_t oid_version(void)
40{
41 switch (hash_algo_by_ptr(the_hash_algo)) {
42 case GIT_HASH_SHA1:
43 return 1;
44 case GIT_HASH_SHA256:
45 return 2;
46 default:
47 die(_("invalid hash version"));
48 }
49}
50
f894081d
TB
51static const unsigned char *get_midx_checksum(struct multi_pack_index *m)
52{
53 return m->data + m->data_len - the_hash_algo->rawsz;
54}
55
fc59e748
DS
56static char *get_midx_filename(const char *object_dir)
57{
58 return xstrfmt("%s/pack/multi-pack-index", object_dir);
59}
60
f894081d
TB
61char *get_midx_rev_filename(struct multi_pack_index *m)
62{
63 return xstrfmt("%s/pack/multi-pack-index-%s.rev",
64 m->object_dir, hash_to_hex(get_midx_checksum(m)));
65}
66
6ab3b8b8
DS
67static int midx_read_oid_fanout(const unsigned char *chunk_start,
68 size_t chunk_size, void *data)
69{
70 struct multi_pack_index *m = data;
71 m->chunk_oid_fanout = (uint32_t *)chunk_start;
72
73 if (chunk_size != 4 * 256) {
74 error(_("multi-pack-index OID fanout is of the wrong size"));
75 return 1;
76 }
77 return 0;
78}
79
2cf489a3 80struct multi_pack_index *load_multi_pack_index(const char *object_dir, int local)
4d80560c
DS
81{
82 struct multi_pack_index *m = NULL;
83 int fd;
84 struct stat st;
85 size_t midx_size;
86 void *midx_map = NULL;
87 uint32_t hash_version;
88 char *midx_name = get_midx_filename(object_dir);
32f3c541 89 uint32_t i;
3227565c 90 const char *cur_pack_name;
6ab3b8b8 91 struct chunkfile *cf = NULL;
4d80560c
DS
92
93 fd = git_open(midx_name);
94
95 if (fd < 0)
96 goto cleanup_fail;
97 if (fstat(fd, &st)) {
98 error_errno(_("failed to read %s"), midx_name);
99 goto cleanup_fail;
100 }
101
102 midx_size = xsize_t(st.st_size);
103
104 if (midx_size < MIDX_MIN_SIZE) {
105 error(_("multi-pack-index file %s is too small"), midx_name);
106 goto cleanup_fail;
107 }
108
109 FREE_AND_NULL(midx_name);
110
111 midx_map = xmmap(NULL, midx_size, PROT_READ, MAP_PRIVATE, fd, 0);
6c7ff7cf 112 close(fd);
4d80560c 113
577314ca 114 FLEX_ALLOC_STR(m, object_dir, object_dir);
4d80560c
DS
115 m->data = midx_map;
116 m->data_len = midx_size;
2cf489a3 117 m->local = local;
4d80560c
DS
118
119 m->signature = get_be32(m->data);
53ad0407
DS
120 if (m->signature != MIDX_SIGNATURE)
121 die(_("multi-pack-index signature 0x%08x does not match signature 0x%08x"),
4d80560c 122 m->signature, MIDX_SIGNATURE);
4d80560c
DS
123
124 m->version = m->data[MIDX_BYTE_FILE_VERSION];
53ad0407
DS
125 if (m->version != MIDX_VERSION)
126 die(_("multi-pack-index version %d not recognized"),
4d80560c 127 m->version);
4d80560c
DS
128
129 hash_version = m->data[MIDX_BYTE_HASH_VERSION];
d9607542
DS
130 if (hash_version != oid_version()) {
131 error(_("multi-pack-index hash version %u does not match version %u"),
132 hash_version, oid_version());
133 goto cleanup_fail;
134 }
aaa95dfa 135 m->hash_len = the_hash_algo->rawsz;
4d80560c
DS
136
137 m->num_chunks = m->data[MIDX_BYTE_NUM_CHUNKS];
138
139 m->num_packs = get_be32(m->data + MIDX_BYTE_NUM_PACKS);
140
6ab3b8b8 141 cf = init_chunkfile(NULL);
32f3c541 142
6ab3b8b8
DS
143 if (read_table_of_contents(cf, m->data, midx_size,
144 MIDX_HEADER_SIZE, m->num_chunks))
145 goto cleanup_fail;
32f3c541 146
6ab3b8b8 147 if (pair_chunk(cf, MIDX_CHUNKID_PACKNAMES, &m->chunk_pack_names) == CHUNK_NOT_FOUND)
32f3c541 148 die(_("multi-pack-index missing required pack-name chunk"));
6ab3b8b8 149 if (read_chunk(cf, MIDX_CHUNKID_OIDFANOUT, midx_read_oid_fanout, m) == CHUNK_NOT_FOUND)
d7cacf29 150 die(_("multi-pack-index missing required OID fanout chunk"));
6ab3b8b8 151 if (pair_chunk(cf, MIDX_CHUNKID_OIDLOOKUP, &m->chunk_oid_lookup) == CHUNK_NOT_FOUND)
0d5b3a5e 152 die(_("multi-pack-index missing required OID lookup chunk"));
6ab3b8b8 153 if (pair_chunk(cf, MIDX_CHUNKID_OBJECTOFFSETS, &m->chunk_object_offsets) == CHUNK_NOT_FOUND)
662148c4 154 die(_("multi-pack-index missing required object offsets chunk"));
32f3c541 155
6ab3b8b8
DS
156 pair_chunk(cf, MIDX_CHUNKID_LARGEOFFSETS, &m->chunk_large_offsets);
157
d7cacf29
DS
158 m->num_objects = ntohl(m->chunk_oid_fanout[255]);
159
ca56dadb
RS
160 CALLOC_ARRAY(m->pack_names, m->num_packs);
161 CALLOC_ARRAY(m->packs, m->num_packs);
3227565c
DS
162
163 cur_pack_name = (const char *)m->chunk_pack_names;
164 for (i = 0; i < m->num_packs; i++) {
165 m->pack_names[i] = cur_pack_name;
166
167 cur_pack_name += strlen(cur_pack_name) + 1;
168
8e72a3c3
DS
169 if (i && strcmp(m->pack_names[i], m->pack_names[i - 1]) <= 0)
170 die(_("multi-pack-index pack names out of order: '%s' before '%s'"),
3227565c
DS
171 m->pack_names[i - 1],
172 m->pack_names[i]);
3227565c
DS
173 }
174
d829223a
JH
175 trace2_data_intmax("midx", the_repository, "load/num_packs", m->num_packs);
176 trace2_data_intmax("midx", the_repository, "load/num_objects", m->num_objects);
177
4d80560c
DS
178 return m;
179
180cleanup_fail:
181 free(m);
182 free(midx_name);
6ab3b8b8 183 free(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
64404a24
DS
282static int nth_midxed_pack_entry(struct repository *r,
283 struct multi_pack_index *m,
284 struct pack_entry *e,
285 uint32_t pos)
3715a633
DS
286{
287 uint32_t pack_int_id;
288 struct packed_git *p;
289
290 if (pos >= m->num_objects)
291 return 0;
292
293 pack_int_id = nth_midxed_pack_int_id(m, pos);
294
64404a24 295 if (prepare_midx_pack(r, m, pack_int_id))
506ec2fb 296 return 0;
3715a633
DS
297 p = m->packs[pack_int_id];
298
299 /*
300 * We are about to tell the caller where they can locate the
301 * requested object. We better make sure the packfile is
302 * still here and can be accessed before supplying that
303 * answer, as it may have been deleted since the MIDX was
304 * loaded!
305 */
306 if (!is_pack_valid(p))
307 return 0;
308
c39b02ae
DS
309 if (p->num_bad_objects) {
310 uint32_t i;
311 struct object_id oid;
312 nth_midxed_object_oid(&oid, m, pos);
313 for (i = 0; i < p->num_bad_objects; i++)
e43d2dcc
JK
314 if (hasheq(oid.hash,
315 p->bad_object_sha1 + the_hash_algo->rawsz * i))
c39b02ae
DS
316 return 0;
317 }
318
3715a633
DS
319 e->offset = nth_midxed_offset(m, pos);
320 e->p = p;
321
322 return 1;
323}
324
64404a24
DS
325int fill_midx_entry(struct repository * r,
326 const struct object_id *oid,
327 struct pack_entry *e,
328 struct multi_pack_index *m)
3715a633
DS
329{
330 uint32_t pos;
331
332 if (!bsearch_midx(oid, m, &pos))
333 return 0;
334
64404a24 335 return nth_midxed_pack_entry(r, m, e, pos);
3715a633
DS
336}
337
013fd7ad
JK
338/* Match "foo.idx" against either "foo.pack" _or_ "foo.idx". */
339static int cmp_idx_or_pack_name(const char *idx_or_pack_name,
340 const char *idx_name)
341{
342 /* Skip past any initial matching prefix. */
343 while (*idx_name && *idx_name == *idx_or_pack_name) {
344 idx_name++;
345 idx_or_pack_name++;
346 }
347
348 /*
349 * If we didn't match completely, we may have matched "pack-1234." and
350 * be left with "idx" and "pack" respectively, which is also OK. We do
351 * not have to check for "idx" and "idx", because that would have been
352 * a complete match (and in that case these strcmps will be false, but
353 * we'll correctly return 0 from the final strcmp() below.
354 *
355 * Technically this matches "fooidx" and "foopack", but we'd never have
356 * such names in the first place.
357 */
358 if (!strcmp(idx_name, "idx") && !strcmp(idx_or_pack_name, "pack"))
359 return 0;
360
361 /*
362 * This not only checks for a complete match, but also orders based on
363 * the first non-identical character, which means our ordering will
364 * match a raw strcmp(). That makes it OK to use this to binary search
365 * a naively-sorted list.
366 */
367 return strcmp(idx_or_pack_name, idx_name);
368}
369
370int midx_contains_pack(struct multi_pack_index *m, const char *idx_or_pack_name)
a40498a1
DS
371{
372 uint32_t first = 0, last = m->num_packs;
373
374 while (first < last) {
375 uint32_t mid = first + (last - first) / 2;
376 const char *current;
377 int cmp;
378
379 current = m->pack_names[mid];
013fd7ad 380 cmp = cmp_idx_or_pack_name(idx_or_pack_name, current);
a40498a1
DS
381 if (!cmp)
382 return 1;
383 if (cmp > 0) {
384 first = mid + 1;
385 continue;
386 }
387 last = mid;
388 }
389
390 return 0;
391}
392
2cf489a3 393int prepare_multi_pack_index_one(struct repository *r, const char *object_dir, int local)
c4d25228 394{
29e2016b 395 struct multi_pack_index *m;
c4d25228 396 struct multi_pack_index *m_search;
c4d25228 397
18e449f8
DS
398 prepare_repo_settings(r);
399 if (!r->settings.core_multi_pack_index)
c4d25228
DS
400 return 0;
401
29e2016b 402 for (m_search = r->objects->multi_pack_index; m_search; m_search = m_search->next)
c4d25228
DS
403 if (!strcmp(object_dir, m_search->object_dir))
404 return 1;
405
29e2016b 406 m = load_multi_pack_index(object_dir, local);
c4d25228 407
29e2016b 408 if (m) {
59552fb3
TB
409 struct multi_pack_index *mp = r->objects->multi_pack_index;
410 if (mp) {
411 m->next = mp->next;
412 mp->next = m;
413 } else
414 r->objects->multi_pack_index = m;
c4d25228
DS
415 return 1;
416 }
417
418 return 0;
419}
420
fc59e748
DS
421static size_t write_midx_header(struct hashfile *f,
422 unsigned char num_chunks,
423 uint32_t num_packs)
424{
fc59e748 425 hashwrite_be32(f, MIDX_SIGNATURE);
014f1447
RS
426 hashwrite_u8(f, MIDX_VERSION);
427 hashwrite_u8(f, oid_version());
428 hashwrite_u8(f, num_chunks);
429 hashwrite_u8(f, 0); /* unused */
fc59e748
DS
430 hashwrite_be32(f, num_packs);
431
432 return MIDX_HEADER_SIZE;
433}
434
d01bf2e6
DS
435struct pack_info {
436 uint32_t orig_pack_int_id;
437 char *pack_name;
438 struct packed_git *p;
19575c7c 439 unsigned expired : 1;
d01bf2e6
DS
440};
441
442static int pack_info_compare(const void *_a, const void *_b)
443{
444 struct pack_info *a = (struct pack_info *)_a;
445 struct pack_info *b = (struct pack_info *)_b;
446 return strcmp(a->pack_name, b->pack_name);
447}
448
9218c6a4
TB
449static int idx_or_pack_name_cmp(const void *_va, const void *_vb)
450{
451 const char *pack_name = _va;
452 const struct pack_info *compar = _vb;
453
454 return cmp_idx_or_pack_name(pack_name, compar->pack_name);
455}
456
577dc496 457struct write_midx_context {
d01bf2e6 458 struct pack_info *info;
396f2570 459 uint32_t nr;
d01bf2e6 460 uint32_t alloc;
a40498a1 461 struct multi_pack_index *m;
840cef0c
WB
462 struct progress *progress;
463 unsigned pack_paths_checked;
31bda9a2
DS
464
465 struct pack_midx_entry *entries;
466 uint32_t entries_nr;
7a3ada11
DS
467
468 uint32_t *pack_perm;
38ff7cab 469 uint32_t *pack_order;
7a3ada11 470 unsigned large_offsets_needed:1;
980f525c 471 uint32_t num_large_offsets;
9218c6a4
TB
472
473 int preferred_pack_idx;
396f2570
DS
474};
475
476static void add_pack_to_midx(const char *full_path, size_t full_path_len,
477 const char *file_name, void *data)
478{
577dc496 479 struct write_midx_context *ctx = data;
396f2570
DS
480
481 if (ends_with(file_name, ".idx")) {
577dc496
DS
482 display_progress(ctx->progress, ++ctx->pack_paths_checked);
483 if (ctx->m && midx_contains_pack(ctx->m, file_name))
a40498a1
DS
484 return;
485
577dc496 486 ALLOC_GROW(ctx->info, ctx->nr + 1, ctx->alloc);
396f2570 487
577dc496
DS
488 ctx->info[ctx->nr].p = add_packed_git(full_path,
489 full_path_len,
490 0);
fe1ed56f 491
577dc496 492 if (!ctx->info[ctx->nr].p) {
396f2570
DS
493 warning(_("failed to add packfile '%s'"),
494 full_path);
495 return;
496 }
497
577dc496 498 if (open_pack_index(ctx->info[ctx->nr].p)) {
fe1ed56f
DS
499 warning(_("failed to open pack-index '%s'"),
500 full_path);
577dc496
DS
501 close_pack(ctx->info[ctx->nr].p);
502 FREE_AND_NULL(ctx->info[ctx->nr].p);
fe1ed56f
DS
503 return;
504 }
505
577dc496
DS
506 ctx->info[ctx->nr].pack_name = xstrdup(file_name);
507 ctx->info[ctx->nr].orig_pack_int_id = ctx->nr;
508 ctx->info[ctx->nr].expired = 0;
509 ctx->nr++;
396f2570
DS
510 }
511}
512
fe1ed56f
DS
513struct pack_midx_entry {
514 struct object_id oid;
515 uint32_t pack_int_id;
516 time_t pack_mtime;
517 uint64_t offset;
9218c6a4 518 unsigned preferred : 1;
fe1ed56f
DS
519};
520
521static int midx_oid_compare(const void *_a, const void *_b)
522{
523 const struct pack_midx_entry *a = (const struct pack_midx_entry *)_a;
524 const struct pack_midx_entry *b = (const struct pack_midx_entry *)_b;
525 int cmp = oidcmp(&a->oid, &b->oid);
526
527 if (cmp)
528 return cmp;
529
9218c6a4
TB
530 /* Sort objects in a preferred pack first when multiple copies exist. */
531 if (a->preferred > b->preferred)
532 return -1;
533 if (a->preferred < b->preferred)
534 return 1;
535
fe1ed56f
DS
536 if (a->pack_mtime > b->pack_mtime)
537 return -1;
538 else if (a->pack_mtime < b->pack_mtime)
539 return 1;
540
541 return a->pack_int_id - b->pack_int_id;
542}
543
a40498a1 544static int nth_midxed_pack_midx_entry(struct multi_pack_index *m,
a40498a1
DS
545 struct pack_midx_entry *e,
546 uint32_t pos)
547{
548 if (pos >= m->num_objects)
549 return 1;
550
551 nth_midxed_object_oid(&e->oid, m, pos);
d01bf2e6 552 e->pack_int_id = nth_midxed_pack_int_id(m, pos);
a40498a1
DS
553 e->offset = nth_midxed_offset(m, pos);
554
555 /* consider objects in midx to be from "old" packs */
556 e->pack_mtime = 0;
557 return 0;
558}
559
fe1ed56f
DS
560static void fill_pack_entry(uint32_t pack_int_id,
561 struct packed_git *p,
562 uint32_t cur_object,
9218c6a4
TB
563 struct pack_midx_entry *entry,
564 int preferred)
fe1ed56f 565{
0763671b 566 if (nth_packed_object_id(&entry->oid, p, cur_object) < 0)
fe1ed56f
DS
567 die(_("failed to locate object %d in packfile"), cur_object);
568
569 entry->pack_int_id = pack_int_id;
570 entry->pack_mtime = p->mtime;
571
572 entry->offset = nth_packed_object_offset(p, cur_object);
9218c6a4 573 entry->preferred = !!preferred;
fe1ed56f
DS
574}
575
576/*
577 * It is possible to artificially get into a state where there are many
578 * duplicate copies of objects. That can create high memory pressure if
579 * we are to create a list of all objects before de-duplication. To reduce
580 * this memory pressure without a significant performance drop, automatically
581 * group objects by the first byte of their object id. Use the IDX fanout
582 * tables to group the data, copy to a local array, then sort.
583 *
584 * Copy only the de-duplicated entries (selected by most-recent modified time
585 * of a packfile containing the object).
586 */
a40498a1 587static struct pack_midx_entry *get_sorted_entries(struct multi_pack_index *m,
d01bf2e6 588 struct pack_info *info,
fe1ed56f 589 uint32_t nr_packs,
9218c6a4
TB
590 uint32_t *nr_objects,
591 int preferred_pack)
fe1ed56f
DS
592{
593 uint32_t cur_fanout, cur_pack, cur_object;
594 uint32_t alloc_fanout, alloc_objects, total_objects = 0;
595 struct pack_midx_entry *entries_by_fanout = NULL;
596 struct pack_midx_entry *deduplicated_entries = NULL;
a40498a1 597 uint32_t start_pack = m ? m->num_packs : 0;
fe1ed56f 598
a40498a1 599 for (cur_pack = start_pack; cur_pack < nr_packs; cur_pack++)
d01bf2e6 600 total_objects += info[cur_pack].p->num_objects;
fe1ed56f
DS
601
602 /*
603 * As we de-duplicate by fanout value, we expect the fanout
604 * slices to be evenly distributed, with some noise. Hence,
605 * allocate slightly more than one 256th.
606 */
607 alloc_objects = alloc_fanout = total_objects > 3200 ? total_objects / 200 : 16;
608
609 ALLOC_ARRAY(entries_by_fanout, alloc_fanout);
610 ALLOC_ARRAY(deduplicated_entries, alloc_objects);
611 *nr_objects = 0;
612
613 for (cur_fanout = 0; cur_fanout < 256; cur_fanout++) {
614 uint32_t nr_fanout = 0;
615
a40498a1
DS
616 if (m) {
617 uint32_t start = 0, end;
618
619 if (cur_fanout)
620 start = ntohl(m->chunk_oid_fanout[cur_fanout - 1]);
621 end = ntohl(m->chunk_oid_fanout[cur_fanout]);
622
623 for (cur_object = start; cur_object < end; cur_object++) {
624 ALLOC_GROW(entries_by_fanout, nr_fanout + 1, alloc_fanout);
d01bf2e6 625 nth_midxed_pack_midx_entry(m,
a40498a1
DS
626 &entries_by_fanout[nr_fanout],
627 cur_object);
9218c6a4
TB
628 if (nth_midxed_pack_int_id(m, cur_object) == preferred_pack)
629 entries_by_fanout[nr_fanout].preferred = 1;
630 else
631 entries_by_fanout[nr_fanout].preferred = 0;
a40498a1
DS
632 nr_fanout++;
633 }
634 }
635
636 for (cur_pack = start_pack; cur_pack < nr_packs; cur_pack++) {
fe1ed56f 637 uint32_t start = 0, end;
9218c6a4 638 int preferred = cur_pack == preferred_pack;
fe1ed56f
DS
639
640 if (cur_fanout)
d01bf2e6
DS
641 start = get_pack_fanout(info[cur_pack].p, cur_fanout - 1);
642 end = get_pack_fanout(info[cur_pack].p, cur_fanout);
fe1ed56f
DS
643
644 for (cur_object = start; cur_object < end; cur_object++) {
645 ALLOC_GROW(entries_by_fanout, nr_fanout + 1, alloc_fanout);
9218c6a4
TB
646 fill_pack_entry(cur_pack,
647 info[cur_pack].p,
648 cur_object,
649 &entries_by_fanout[nr_fanout],
650 preferred);
fe1ed56f
DS
651 nr_fanout++;
652 }
653 }
654
655 QSORT(entries_by_fanout, nr_fanout, midx_oid_compare);
656
657 /*
658 * The batch is now sorted by OID and then mtime (descending).
659 * Take only the first duplicate.
660 */
661 for (cur_object = 0; cur_object < nr_fanout; cur_object++) {
e43d2dcc
JK
662 if (cur_object && oideq(&entries_by_fanout[cur_object - 1].oid,
663 &entries_by_fanout[cur_object].oid))
fe1ed56f
DS
664 continue;
665
666 ALLOC_GROW(deduplicated_entries, *nr_objects + 1, alloc_objects);
667 memcpy(&deduplicated_entries[*nr_objects],
668 &entries_by_fanout[cur_object],
669 sizeof(struct pack_midx_entry));
670 (*nr_objects)++;
671 }
672 }
673
674 free(entries_by_fanout);
675 return deduplicated_entries;
676}
677
0ccd713c 678static int write_midx_pack_names(struct hashfile *f, void *data)
32f3c541 679{
b4d94142 680 struct write_midx_context *ctx = data;
32f3c541
DS
681 uint32_t i;
682 unsigned char padding[MIDX_CHUNK_ALIGNMENT];
683 size_t written = 0;
684
b4d94142 685 for (i = 0; i < ctx->nr; i++) {
19575c7c
DS
686 size_t writelen;
687
b4d94142 688 if (ctx->info[i].expired)
19575c7c 689 continue;
32f3c541 690
b4d94142 691 if (i && strcmp(ctx->info[i].pack_name, ctx->info[i - 1].pack_name) <= 0)
32f3c541 692 BUG("incorrect pack-file order: %s before %s",
b4d94142
DS
693 ctx->info[i - 1].pack_name,
694 ctx->info[i].pack_name);
32f3c541 695
b4d94142
DS
696 writelen = strlen(ctx->info[i].pack_name) + 1;
697 hashwrite(f, ctx->info[i].pack_name, writelen);
32f3c541
DS
698 written += writelen;
699 }
700
701 /* add padding to be aligned */
702 i = MIDX_CHUNK_ALIGNMENT - (written % MIDX_CHUNK_ALIGNMENT);
703 if (i < MIDX_CHUNK_ALIGNMENT) {
704 memset(padding, 0, sizeof(padding));
705 hashwrite(f, padding, i);
32f3c541
DS
706 }
707
0ccd713c 708 return 0;
32f3c541
DS
709}
710
0ccd713c
DS
711static int write_midx_oid_fanout(struct hashfile *f,
712 void *data)
d7cacf29 713{
31bda9a2
DS
714 struct write_midx_context *ctx = data;
715 struct pack_midx_entry *list = ctx->entries;
716 struct pack_midx_entry *last = ctx->entries + ctx->entries_nr;
d7cacf29
DS
717 uint32_t count = 0;
718 uint32_t i;
719
720 /*
721 * Write the first-level table (the list is sorted,
722 * but we use a 256-entry lookup to be able to avoid
723 * having to do eight extra binary search iterations).
724 */
725 for (i = 0; i < 256; i++) {
726 struct pack_midx_entry *next = list;
727
728 while (next < last && next->oid.hash[0] == i) {
729 count++;
730 next++;
731 }
732
733 hashwrite_be32(f, count);
734 list = next;
735 }
736
0ccd713c 737 return 0;
d7cacf29
DS
738}
739
0ccd713c
DS
740static int write_midx_oid_lookup(struct hashfile *f,
741 void *data)
0d5b3a5e 742{
31bda9a2
DS
743 struct write_midx_context *ctx = data;
744 unsigned char hash_len = the_hash_algo->rawsz;
745 struct pack_midx_entry *list = ctx->entries;
0d5b3a5e 746 uint32_t i;
0d5b3a5e 747
31bda9a2 748 for (i = 0; i < ctx->entries_nr; i++) {
0d5b3a5e
DS
749 struct pack_midx_entry *obj = list++;
750
31bda9a2 751 if (i < ctx->entries_nr - 1) {
0d5b3a5e
DS
752 struct pack_midx_entry *next = list;
753 if (oidcmp(&obj->oid, &next->oid) >= 0)
754 BUG("OIDs not in order: %s >= %s",
755 oid_to_hex(&obj->oid),
756 oid_to_hex(&next->oid));
757 }
758
759 hashwrite(f, obj->oid.hash, (int)hash_len);
0d5b3a5e
DS
760 }
761
0ccd713c 762 return 0;
0d5b3a5e
DS
763}
764
0ccd713c
DS
765static int write_midx_object_offsets(struct hashfile *f,
766 void *data)
662148c4 767{
7a3ada11
DS
768 struct write_midx_context *ctx = data;
769 struct pack_midx_entry *list = ctx->entries;
662148c4 770 uint32_t i, nr_large_offset = 0;
662148c4 771
7a3ada11 772 for (i = 0; i < ctx->entries_nr; i++) {
662148c4
DS
773 struct pack_midx_entry *obj = list++;
774
7a3ada11 775 if (ctx->pack_perm[obj->pack_int_id] == PACK_EXPIRED)
19575c7c
DS
776 BUG("object %s is in an expired pack with int-id %d",
777 oid_to_hex(&obj->oid),
778 obj->pack_int_id);
779
7a3ada11 780 hashwrite_be32(f, ctx->pack_perm[obj->pack_int_id]);
662148c4 781
7a3ada11 782 if (ctx->large_offsets_needed && obj->offset >> 31)
662148c4 783 hashwrite_be32(f, MIDX_LARGE_OFFSET_NEEDED | nr_large_offset++);
7a3ada11 784 else if (!ctx->large_offsets_needed && obj->offset >> 32)
662148c4
DS
785 BUG("object %s requires a large offset (%"PRIx64") but the MIDX is not writing large offsets!",
786 oid_to_hex(&obj->oid),
787 obj->offset);
788 else
789 hashwrite_be32(f, (uint32_t)obj->offset);
662148c4
DS
790 }
791
0ccd713c 792 return 0;
662148c4
DS
793}
794
0ccd713c
DS
795static int write_midx_large_offsets(struct hashfile *f,
796 void *data)
662148c4 797{
980f525c
DS
798 struct write_midx_context *ctx = data;
799 struct pack_midx_entry *list = ctx->entries;
800 struct pack_midx_entry *end = ctx->entries + ctx->entries_nr;
980f525c 801 uint32_t nr_large_offset = ctx->num_large_offsets;
662148c4
DS
802
803 while (nr_large_offset) {
61b0fcbb
JK
804 struct pack_midx_entry *obj;
805 uint64_t offset;
806
807 if (list >= end)
808 BUG("too many large-offset objects");
809
810 obj = list++;
811 offset = obj->offset;
662148c4
DS
812
813 if (!(offset >> 31))
814 continue;
815
0ccd713c 816 hashwrite_be64(f, offset);
662148c4
DS
817
818 nr_large_offset--;
819 }
820
0ccd713c 821 return 0;
662148c4
DS
822}
823
30077524
JK
824struct midx_pack_order_data {
825 uint32_t nr;
826 uint32_t pack;
827 off_t offset;
828};
38ff7cab 829
30077524
JK
830static int midx_pack_order_cmp(const void *va, const void *vb)
831{
832 const struct midx_pack_order_data *a = va, *b = vb;
833 if (a->pack < b->pack)
38ff7cab 834 return -1;
30077524 835 else if (a->pack > b->pack)
38ff7cab 836 return 1;
30077524 837 else if (a->offset < b->offset)
38ff7cab 838 return -1;
30077524 839 else if (a->offset > b->offset)
38ff7cab 840 return 1;
30077524
JK
841 else
842 return 0;
38ff7cab
TB
843}
844
845static uint32_t *midx_pack_order(struct write_midx_context *ctx)
846{
30077524 847 struct midx_pack_order_data *data;
38ff7cab
TB
848 uint32_t *pack_order;
849 uint32_t i;
850
30077524
JK
851 ALLOC_ARRAY(data, ctx->entries_nr);
852 for (i = 0; i < ctx->entries_nr; i++) {
853 struct pack_midx_entry *e = &ctx->entries[i];
854 data[i].nr = i;
855 data[i].pack = ctx->pack_perm[e->pack_int_id];
856 if (!e->preferred)
857 data[i].pack |= (1U << 31);
858 data[i].offset = e->offset;
859 }
860
861 QSORT(data, ctx->entries_nr, midx_pack_order_cmp);
862
38ff7cab
TB
863 ALLOC_ARRAY(pack_order, ctx->entries_nr);
864 for (i = 0; i < ctx->entries_nr; i++)
30077524
JK
865 pack_order[i] = data[i].nr;
866 free(data);
38ff7cab
TB
867
868 return pack_order;
869}
870
871static void write_midx_reverse_index(char *midx_name, unsigned char *midx_hash,
872 struct write_midx_context *ctx)
873{
874 struct strbuf buf = STRBUF_INIT;
875 const char *tmp_file;
876
877 strbuf_addf(&buf, "%s-%s.rev", midx_name, hash_to_hex(midx_hash));
878
879 tmp_file = write_rev_file_order(NULL, ctx->pack_order, ctx->entries_nr,
880 midx_hash, WRITE_REV);
881
882 if (finalize_object_file(tmp_file, buf.buf))
883 die(_("cannot store reverse index file"));
884
885 strbuf_release(&buf);
886}
887
426c00e4 888static void clear_midx_files_ext(const char *object_dir, const char *ext,
38ff7cab
TB
889 unsigned char *keep_hash);
890
ec1e28ef
TB
891static int midx_checksum_valid(struct multi_pack_index *m)
892{
893 return hashfile_checksum_valid(m->data, m->data_len);
894}
895
f57a7396 896static int write_midx_internal(const char *object_dir,
9218c6a4
TB
897 struct string_list *packs_to_drop,
898 const char *preferred_pack_name,
899 unsigned flags)
a3407730 900{
fc59e748 901 char *midx_name;
9f191611 902 unsigned char midx_hash[GIT_MAX_RAWSZ];
396f2570 903 uint32_t i;
fc59e748
DS
904 struct hashfile *f = NULL;
905 struct lock_file lk;
577dc496 906 struct write_midx_context ctx = { 0 };
f57a7396 907 struct multi_pack_index *cur;
dba6175c 908 int pack_name_concat_len = 0;
19575c7c
DS
909 int dropped_packs = 0;
910 int result = 0;
63a8f0e9 911 struct chunkfile *cf;
fc59e748 912
f57a7396
TB
913 /* Ensure the given object_dir is local, or a known alternate. */
914 find_odb(the_repository, object_dir);
915
fc59e748 916 midx_name = get_midx_filename(object_dir);
d5e1961c 917 if (safe_create_leading_directories(midx_name))
fc59e748
DS
918 die_errno(_("unable to create leading directories of %s"),
919 midx_name);
fc59e748 920
f57a7396
TB
921 for (cur = get_multi_pack_index(the_repository); cur; cur = cur->next) {
922 if (!strcmp(object_dir, cur->object_dir)) {
923 ctx.m = cur;
924 break;
925 }
926 }
577dc496 927
ec1e28ef
TB
928 if (ctx.m && !midx_checksum_valid(ctx.m)) {
929 warning(_("ignoring existing multi-pack-index; checksum mismatch"));
930 ctx.m = NULL;
931 }
932
577dc496
DS
933 ctx.nr = 0;
934 ctx.alloc = ctx.m ? ctx.m->num_packs : 16;
935 ctx.info = NULL;
936 ALLOC_ARRAY(ctx.info, ctx.alloc);
937
938 if (ctx.m) {
939 for (i = 0; i < ctx.m->num_packs; i++) {
940 ALLOC_GROW(ctx.info, ctx.nr + 1, ctx.alloc);
941
942 ctx.info[ctx.nr].orig_pack_int_id = i;
943 ctx.info[ctx.nr].pack_name = xstrdup(ctx.m->pack_names[i]);
944 ctx.info[ctx.nr].p = NULL;
945 ctx.info[ctx.nr].expired = 0;
5d3cd09a
TB
946
947 if (flags & MIDX_WRITE_REV_INDEX) {
948 /*
949 * If generating a reverse index, need to have
950 * packed_git's loaded to compare their
951 * mtimes and object count.
952 */
953 if (prepare_midx_pack(the_repository, ctx.m, i)) {
954 error(_("could not load pack"));
955 result = 1;
956 goto cleanup;
957 }
958
959 if (open_pack_index(ctx.m->packs[i]))
960 die(_("could not open index for %s"),
961 ctx.m->packs[i]->pack_name);
962 ctx.info[ctx.nr].p = ctx.m->packs[i];
963 }
964
577dc496 965 ctx.nr++;
a40498a1
DS
966 }
967 }
968
577dc496 969 ctx.pack_paths_checked = 0;
840cef0c 970 if (flags & MIDX_PROGRESS)
577dc496 971 ctx.progress = start_delayed_progress(_("Adding packfiles to multi-pack-index"), 0);
840cef0c 972 else
577dc496 973 ctx.progress = NULL;
840cef0c 974
577dc496
DS
975 for_each_file_in_pack_dir(object_dir, add_pack_to_midx, &ctx);
976 stop_progress(&ctx.progress);
396f2570 977
577dc496 978 if (ctx.m && ctx.nr == ctx.m->num_packs && !packs_to_drop)
a40498a1
DS
979 goto cleanup;
980
9218c6a4 981 if (preferred_pack_name) {
177c0d6e 982 int found = 0;
9218c6a4
TB
983 for (i = 0; i < ctx.nr; i++) {
984 if (!cmp_idx_or_pack_name(preferred_pack_name,
985 ctx.info[i].pack_name)) {
986 ctx.preferred_pack_idx = i;
177c0d6e 987 found = 1;
9218c6a4
TB
988 break;
989 }
990 }
177c0d6e
TB
991
992 if (!found)
993 warning(_("unknown preferred pack: '%s'"),
994 preferred_pack_name);
995 } else if (ctx.nr && (flags & MIDX_WRITE_REV_INDEX)) {
996 struct packed_git *oldest = ctx.info[ctx.preferred_pack_idx].p;
997 ctx.preferred_pack_idx = 0;
998
999 if (packs_to_drop && packs_to_drop->nr)
1000 BUG("cannot write a MIDX bitmap during expiration");
1001
1002 /*
1003 * set a preferred pack when writing a bitmap to ensure that
1004 * the pack from which the first object is selected in pseudo
1005 * pack-order has all of its objects selected from that pack
1006 * (and not another pack containing a duplicate)
1007 */
1008 for (i = 1; i < ctx.nr; i++) {
1009 struct packed_git *p = ctx.info[i].p;
1010
1011 if (!oldest->num_objects || p->mtime < oldest->mtime) {
1012 oldest = p;
1013 ctx.preferred_pack_idx = i;
1014 }
1015 }
1016
1017 if (!oldest->num_objects) {
1018 /*
1019 * If all packs are empty; unset the preferred index.
1020 * This is acceptable since there will be no duplicate
1021 * objects to resolve, so the preferred value doesn't
1022 * matter.
1023 */
1024 ctx.preferred_pack_idx = -1;
1025 }
1026 } else {
1027 /*
1028 * otherwise don't mark any pack as preferred to avoid
1029 * interfering with expiration logic below
1030 */
1031 ctx.preferred_pack_idx = -1;
9218c6a4
TB
1032 }
1033
5d3cd09a
TB
1034 if (ctx.preferred_pack_idx > -1) {
1035 struct packed_git *preferred = ctx.info[ctx.preferred_pack_idx].p;
1036 if (!preferred->num_objects) {
1037 error(_("cannot select preferred pack %s with no objects"),
1038 preferred->pack_name);
1039 result = 1;
1040 goto cleanup;
1041 }
1042 }
1043
9218c6a4
TB
1044 ctx.entries = get_sorted_entries(ctx.m, ctx.info, ctx.nr, &ctx.entries_nr,
1045 ctx.preferred_pack_idx);
a40498a1 1046
7a3ada11 1047 ctx.large_offsets_needed = 0;
31bda9a2
DS
1048 for (i = 0; i < ctx.entries_nr; i++) {
1049 if (ctx.entries[i].offset > 0x7fffffff)
980f525c 1050 ctx.num_large_offsets++;
31bda9a2 1051 if (ctx.entries[i].offset > 0xffffffff)
7a3ada11 1052 ctx.large_offsets_needed = 1;
662148c4 1053 }
fe1ed56f 1054
577dc496 1055 QSORT(ctx.info, ctx.nr, pack_info_compare);
d01bf2e6 1056
19575c7c
DS
1057 if (packs_to_drop && packs_to_drop->nr) {
1058 int drop_index = 0;
1059 int missing_drops = 0;
1060
577dc496
DS
1061 for (i = 0; i < ctx.nr && drop_index < packs_to_drop->nr; i++) {
1062 int cmp = strcmp(ctx.info[i].pack_name,
19575c7c
DS
1063 packs_to_drop->items[drop_index].string);
1064
1065 if (!cmp) {
1066 drop_index++;
577dc496 1067 ctx.info[i].expired = 1;
19575c7c
DS
1068 } else if (cmp > 0) {
1069 error(_("did not see pack-file %s to drop"),
1070 packs_to_drop->items[drop_index].string);
1071 drop_index++;
1072 missing_drops++;
1073 i--;
1074 } else {
577dc496 1075 ctx.info[i].expired = 0;
19575c7c
DS
1076 }
1077 }
1078
1079 if (missing_drops) {
1080 result = 1;
1081 goto cleanup;
1082 }
1083 }
1084
d01bf2e6
DS
1085 /*
1086 * pack_perm stores a permutation between pack-int-ids from the
1087 * previous multi-pack-index to the new one we are writing:
1088 *
1089 * pack_perm[old_id] = new_id
1090 */
7a3ada11 1091 ALLOC_ARRAY(ctx.pack_perm, ctx.nr);
577dc496
DS
1092 for (i = 0; i < ctx.nr; i++) {
1093 if (ctx.info[i].expired) {
19575c7c 1094 dropped_packs++;
7a3ada11 1095 ctx.pack_perm[ctx.info[i].orig_pack_int_id] = PACK_EXPIRED;
19575c7c 1096 } else {
7a3ada11 1097 ctx.pack_perm[ctx.info[i].orig_pack_int_id] = i - dropped_packs;
19575c7c 1098 }
d01bf2e6
DS
1099 }
1100
577dc496
DS
1101 for (i = 0; i < ctx.nr; i++) {
1102 if (!ctx.info[i].expired)
1103 pack_name_concat_len += strlen(ctx.info[i].pack_name) + 1;
19575c7c 1104 }
dba6175c 1105
9218c6a4
TB
1106 /* Check that the preferred pack wasn't expired (if given). */
1107 if (preferred_pack_name) {
1108 struct pack_info *preferred = bsearch(preferred_pack_name,
1109 ctx.info, ctx.nr,
1110 sizeof(*ctx.info),
1111 idx_or_pack_name_cmp);
177c0d6e 1112 if (preferred) {
9218c6a4
TB
1113 uint32_t perm = ctx.pack_perm[preferred->orig_pack_int_id];
1114 if (perm == PACK_EXPIRED)
1115 warning(_("preferred pack '%s' is expired"),
1116 preferred_pack_name);
1117 }
1118 }
1119
dba6175c
DS
1120 if (pack_name_concat_len % MIDX_CHUNK_ALIGNMENT)
1121 pack_name_concat_len += MIDX_CHUNK_ALIGNMENT -
1122 (pack_name_concat_len % MIDX_CHUNK_ALIGNMENT);
1123
fc59e748 1124 hold_lock_file_for_update(&lk, midx_name, LOCK_DIE_ON_ERROR);
acd71602 1125 f = hashfd(get_lock_file_fd(&lk), get_lock_file_path(&lk));
fc59e748 1126
577dc496 1127 if (ctx.m)
f57a7396 1128 close_object_store(the_repository->objects);
a40498a1 1129
577dc496 1130 if (ctx.nr - dropped_packs == 0) {
796d61cd
DR
1131 error(_("no pack files to index."));
1132 result = 1;
1133 goto cleanup;
1134 }
1135
63a8f0e9 1136 cf = init_chunkfile(f);
32f3c541 1137
63a8f0e9
DS
1138 add_chunk(cf, MIDX_CHUNKID_PACKNAMES, pack_name_concat_len,
1139 write_midx_pack_names);
1140 add_chunk(cf, MIDX_CHUNKID_OIDFANOUT, MIDX_CHUNK_FANOUT_SIZE,
1141 write_midx_oid_fanout);
1142 add_chunk(cf, MIDX_CHUNKID_OIDLOOKUP,
329fac3a 1143 (size_t)ctx.entries_nr * the_hash_algo->rawsz,
63a8f0e9
DS
1144 write_midx_oid_lookup);
1145 add_chunk(cf, MIDX_CHUNKID_OBJECTOFFSETS,
329fac3a 1146 (size_t)ctx.entries_nr * MIDX_CHUNK_OFFSET_WIDTH,
63a8f0e9 1147 write_midx_object_offsets);
32f3c541 1148
63a8f0e9
DS
1149 if (ctx.large_offsets_needed)
1150 add_chunk(cf, MIDX_CHUNKID_LARGEOFFSETS,
329fac3a 1151 (size_t)ctx.num_large_offsets * MIDX_CHUNK_LARGE_OFFSET_WIDTH,
63a8f0e9 1152 write_midx_large_offsets);
32f3c541 1153
63a8f0e9
DS
1154 write_midx_header(f, get_num_chunks(cf), ctx.nr - dropped_packs);
1155 write_chunkfile(cf, &ctx);
fc59e748 1156
9f191611 1157 finalize_hashfile(f, midx_hash, CSUM_FSYNC | CSUM_HASH_IN_STREAM);
63a8f0e9 1158 free_chunkfile(cf);
38ff7cab
TB
1159
1160 if (flags & MIDX_WRITE_REV_INDEX)
1161 ctx.pack_order = midx_pack_order(&ctx);
1162
1163 if (flags & MIDX_WRITE_REV_INDEX)
1164 write_midx_reverse_index(midx_name, midx_hash, &ctx);
38ff7cab 1165
fc59e748
DS
1166 commit_lock_file(&lk);
1167
f5909d34
TB
1168 clear_midx_files_ext(object_dir, ".rev", midx_hash);
1169
a40498a1 1170cleanup:
577dc496
DS
1171 for (i = 0; i < ctx.nr; i++) {
1172 if (ctx.info[i].p) {
1173 close_pack(ctx.info[i].p);
1174 free(ctx.info[i].p);
396f2570 1175 }
577dc496 1176 free(ctx.info[i].pack_name);
396f2570
DS
1177 }
1178
577dc496 1179 free(ctx.info);
31bda9a2 1180 free(ctx.entries);
7a3ada11 1181 free(ctx.pack_perm);
38ff7cab 1182 free(ctx.pack_order);
a40498a1 1183 free(midx_name);
19575c7c
DS
1184 return result;
1185}
1186
9218c6a4
TB
1187int write_midx_file(const char *object_dir,
1188 const char *preferred_pack_name,
1189 unsigned flags)
19575c7c 1190{
f57a7396 1191 return write_midx_internal(object_dir, NULL, preferred_pack_name, flags);
a3407730 1192}
525e18c0 1193
38ff7cab
TB
1194struct clear_midx_data {
1195 char *keep;
1196 const char *ext;
1197};
1198
1199static void clear_midx_file_ext(const char *full_path, size_t full_path_len,
1200 const char *file_name, void *_data)
1201{
1202 struct clear_midx_data *data = _data;
1203
1204 if (!(starts_with(file_name, "multi-pack-index-") &&
1205 ends_with(file_name, data->ext)))
1206 return;
1207 if (data->keep && !strcmp(data->keep, file_name))
1208 return;
1209
1210 if (unlink(full_path))
1211 die_errno(_("failed to remove %s"), full_path);
1212}
1213
426c00e4 1214static void clear_midx_files_ext(const char *object_dir, const char *ext,
38ff7cab
TB
1215 unsigned char *keep_hash)
1216{
1217 struct clear_midx_data data;
1218 memset(&data, 0, sizeof(struct clear_midx_data));
1219
1220 if (keep_hash)
1221 data.keep = xstrfmt("multi-pack-index-%s%s",
1222 hash_to_hex(keep_hash), ext);
1223 data.ext = ext;
1224
426c00e4 1225 for_each_file_in_pack_dir(object_dir,
38ff7cab
TB
1226 clear_midx_file_ext,
1227 &data);
1228
1229 free(data.keep);
a3407730 1230}
525e18c0 1231
1dcd9f20 1232void clear_midx_file(struct repository *r)
525e18c0 1233{
3b2f8a02 1234 char *midx = get_midx_filename(r->objects->odb->path);
1dcd9f20
DS
1235
1236 if (r->objects && r->objects->multi_pack_index) {
1237 close_midx(r->objects->multi_pack_index);
1238 r->objects->multi_pack_index = NULL;
1239 }
525e18c0 1240
d5e1961c 1241 if (remove_path(midx))
525e18c0 1242 die(_("failed to clear multi-pack-index at %s"), midx);
525e18c0 1243
426c00e4 1244 clear_midx_files_ext(r->objects->odb->path, ".rev", NULL);
38ff7cab 1245
525e18c0
DS
1246 free(midx);
1247}
56ee7ff1
DS
1248
1249static int verify_midx_error;
1250
48ca53ca 1251__attribute__((format (printf, 1, 2)))
d4bf1d88
DS
1252static void midx_report(const char *fmt, ...)
1253{
1254 va_list ap;
1255 verify_midx_error = 1;
1256 va_start(ap, fmt);
1257 vfprintf(stderr, fmt, ap);
1258 fprintf(stderr, "\n");
1259 va_end(ap);
1260}
1261
5ae18df9
JH
1262struct pair_pos_vs_id
1263{
1264 uint32_t pos;
1265 uint32_t pack_int_id;
1266};
1267
1268static int compare_pair_pos_vs_id(const void *_a, const void *_b)
1269{
1270 struct pair_pos_vs_id *a = (struct pair_pos_vs_id *)_a;
1271 struct pair_pos_vs_id *b = (struct pair_pos_vs_id *)_b;
1272
1273 return b->pack_int_id - a->pack_int_id;
1274}
1275
430efb8a
JH
1276/*
1277 * Limit calls to display_progress() for performance reasons.
1278 * The interval here was arbitrarily chosen.
1279 */
1280#define SPARSE_PROGRESS_INTERVAL (1 << 12)
1281#define midx_display_sparse_progress(progress, n) \
1282 do { \
1283 uint64_t _n = (n); \
1284 if ((_n & (SPARSE_PROGRESS_INTERVAL - 1)) == 0) \
1285 display_progress(progress, _n); \
1286 } while (0)
1287
efbc3aee 1288int verify_midx_file(struct repository *r, const char *object_dir, unsigned flags)
56ee7ff1 1289{
5ae18df9 1290 struct pair_pos_vs_id *pairs = NULL;
d4bf1d88 1291 uint32_t i;
ad60096d 1292 struct progress *progress = NULL;
56ee7ff1
DS
1293 struct multi_pack_index *m = load_multi_pack_index(object_dir, 1);
1294 verify_midx_error = 0;
1295
d9607542
DS
1296 if (!m) {
1297 int result = 0;
1298 struct stat sb;
1299 char *filename = get_midx_filename(object_dir);
1300 if (!stat(filename, &sb)) {
1301 error(_("multi-pack-index file exists, but failed to parse"));
1302 result = 1;
1303 }
1304 free(filename);
1305 return result;
1306 }
56ee7ff1 1307
f89ecf79
TB
1308 if (!midx_checksum_valid(m))
1309 midx_report(_("incorrect checksum"));
1310
ad60096d 1311 if (flags & MIDX_PROGRESS)
efdd2f0d 1312 progress = start_delayed_progress(_("Looking for referenced packfiles"),
ad60096d 1313 m->num_packs);
d4bf1d88 1314 for (i = 0; i < m->num_packs; i++) {
64404a24 1315 if (prepare_midx_pack(r, m, i))
d4bf1d88 1316 midx_report("failed to load pack in position %d", i);
430efb8a
JH
1317
1318 display_progress(progress, i + 1);
d4bf1d88 1319 }
430efb8a 1320 stop_progress(&progress);
d4bf1d88 1321
2f23d3f3
DS
1322 for (i = 0; i < 255; i++) {
1323 uint32_t oid_fanout1 = ntohl(m->chunk_oid_fanout[i]);
1324 uint32_t oid_fanout2 = ntohl(m->chunk_oid_fanout[i + 1]);
1325
1326 if (oid_fanout1 > oid_fanout2)
1327 midx_report(_("oid fanout out of order: fanout[%d] = %"PRIx32" > %"PRIx32" = fanout[%d]"),
1328 i, oid_fanout1, oid_fanout2, i + 1);
1329 }
1330
796d61cd
DR
1331 if (m->num_objects == 0) {
1332 midx_report(_("the midx contains no oid"));
1333 /*
1334 * Remaining tests assume that we have objects, so we can
1335 * return here.
1336 */
1337 return verify_midx_error;
1338 }
1339
ad60096d
WB
1340 if (flags & MIDX_PROGRESS)
1341 progress = start_sparse_progress(_("Verifying OID order in multi-pack-index"),
1342 m->num_objects - 1);
55c5648d
DS
1343 for (i = 0; i < m->num_objects - 1; i++) {
1344 struct object_id oid1, oid2;
1345
1346 nth_midxed_object_oid(&oid1, m, i);
1347 nth_midxed_object_oid(&oid2, m, i + 1);
1348
1349 if (oidcmp(&oid1, &oid2) >= 0)
1350 midx_report(_("oid lookup out of order: oid[%d] = %s >= %s = oid[%d]"),
1351 i, oid_to_hex(&oid1), oid_to_hex(&oid2), i + 1);
430efb8a
JH
1352
1353 midx_display_sparse_progress(progress, i + 1);
55c5648d 1354 }
430efb8a 1355 stop_progress(&progress);
55c5648d 1356
5ae18df9
JH
1357 /*
1358 * Create an array mapping each object to its packfile id. Sort it
1359 * to group the objects by packfile. Use this permutation to visit
1360 * each of the objects and only require 1 packfile to be open at a
1361 * time.
1362 */
1363 ALLOC_ARRAY(pairs, m->num_objects);
1364 for (i = 0; i < m->num_objects; i++) {
1365 pairs[i].pos = i;
1366 pairs[i].pack_int_id = nth_midxed_pack_int_id(m, i);
1367 }
1368
ad60096d
WB
1369 if (flags & MIDX_PROGRESS)
1370 progress = start_sparse_progress(_("Sorting objects by packfile"),
1371 m->num_objects);
5ae18df9
JH
1372 display_progress(progress, 0); /* TODO: Measure QSORT() progress */
1373 QSORT(pairs, m->num_objects, compare_pair_pos_vs_id);
1374 stop_progress(&progress);
1375
ad60096d
WB
1376 if (flags & MIDX_PROGRESS)
1377 progress = start_sparse_progress(_("Verifying object offsets"), m->num_objects);
cc6af73c
DS
1378 for (i = 0; i < m->num_objects; i++) {
1379 struct object_id oid;
1380 struct pack_entry e;
1381 off_t m_offset, p_offset;
1382
5ae18df9
JH
1383 if (i > 0 && pairs[i-1].pack_int_id != pairs[i].pack_int_id &&
1384 m->packs[pairs[i-1].pack_int_id])
1385 {
1386 close_pack_fd(m->packs[pairs[i-1].pack_int_id]);
1387 close_pack_index(m->packs[pairs[i-1].pack_int_id]);
1388 }
1389
1390 nth_midxed_object_oid(&oid, m, pairs[i].pos);
1391
64404a24 1392 if (!fill_midx_entry(r, &oid, &e, m)) {
cc6af73c 1393 midx_report(_("failed to load pack entry for oid[%d] = %s"),
5ae18df9 1394 pairs[i].pos, oid_to_hex(&oid));
cc6af73c
DS
1395 continue;
1396 }
1397
1398 if (open_pack_index(e.p)) {
1399 midx_report(_("failed to load pack-index for packfile %s"),
1400 e.p->pack_name);
1401 break;
1402 }
1403
1404 m_offset = e.offset;
1405 p_offset = find_pack_entry_one(oid.hash, e.p);
1406
1407 if (m_offset != p_offset)
1408 midx_report(_("incorrect object offset for oid[%d] = %s: %"PRIx64" != %"PRIx64),
5ae18df9 1409 pairs[i].pos, oid_to_hex(&oid), m_offset, p_offset);
144d7033 1410
430efb8a 1411 midx_display_sparse_progress(progress, i + 1);
cc6af73c 1412 }
144d7033 1413 stop_progress(&progress);
cc6af73c 1414
5ae18df9
JH
1415 free(pairs);
1416
56ee7ff1
DS
1417 return verify_midx_error;
1418}
cff97116 1419
efbc3aee 1420int expire_midx_packs(struct repository *r, const char *object_dir, unsigned flags)
cff97116 1421{
19575c7c
DS
1422 uint32_t i, *count, result = 0;
1423 struct string_list packs_to_drop = STRING_LIST_INIT_DUP;
1424 struct multi_pack_index *m = load_multi_pack_index(object_dir, 1);
8dc18f89 1425 struct progress *progress = NULL;
19575c7c
DS
1426
1427 if (!m)
1428 return 0;
1429
ca56dadb 1430 CALLOC_ARRAY(count, m->num_packs);
8dc18f89
WB
1431
1432 if (flags & MIDX_PROGRESS)
efdd2f0d 1433 progress = start_delayed_progress(_("Counting referenced objects"),
8dc18f89 1434 m->num_objects);
19575c7c
DS
1435 for (i = 0; i < m->num_objects; i++) {
1436 int pack_int_id = nth_midxed_pack_int_id(m, i);
1437 count[pack_int_id]++;
8dc18f89 1438 display_progress(progress, i + 1);
19575c7c 1439 }
8dc18f89 1440 stop_progress(&progress);
19575c7c 1441
8dc18f89 1442 if (flags & MIDX_PROGRESS)
efdd2f0d 1443 progress = start_delayed_progress(_("Finding and deleting unreferenced packfiles"),
8dc18f89 1444 m->num_packs);
19575c7c
DS
1445 for (i = 0; i < m->num_packs; i++) {
1446 char *pack_name;
8dc18f89 1447 display_progress(progress, i + 1);
19575c7c
DS
1448
1449 if (count[i])
1450 continue;
1451
1452 if (prepare_midx_pack(r, m, i))
1453 continue;
1454
1455 if (m->packs[i]->pack_keep)
1456 continue;
1457
1458 pack_name = xstrdup(m->packs[i]->pack_name);
1459 close_pack(m->packs[i]);
1460
1461 string_list_insert(&packs_to_drop, m->pack_names[i]);
1462 unlink_pack_path(pack_name, 0);
1463 free(pack_name);
1464 }
8dc18f89 1465 stop_progress(&progress);
19575c7c
DS
1466
1467 free(count);
1468
f57a7396
TB
1469 if (packs_to_drop.nr) {
1470 result = write_midx_internal(object_dir, &packs_to_drop, NULL, flags);
1471 m = NULL;
1472 }
19575c7c
DS
1473
1474 string_list_clear(&packs_to_drop, 0);
1475 return result;
cff97116 1476}
2af890bb 1477
ce1e4a10
DS
1478struct repack_info {
1479 timestamp_t mtime;
1480 uint32_t referenced_objects;
1481 uint32_t pack_int_id;
1482};
1483
1484static int compare_by_mtime(const void *a_, const void *b_)
2af890bb 1485{
ce1e4a10
DS
1486 const struct repack_info *a, *b;
1487
1488 a = (const struct repack_info *)a_;
1489 b = (const struct repack_info *)b_;
1490
1491 if (a->mtime < b->mtime)
1492 return -1;
1493 if (a->mtime > b->mtime)
1494 return 1;
1495 return 0;
1496}
1497
3ce4ca0a
DS
1498static int fill_included_packs_all(struct repository *r,
1499 struct multi_pack_index *m,
ce1e4a10
DS
1500 unsigned char *include_pack)
1501{
3ce4ca0a
DS
1502 uint32_t i, count = 0;
1503 int pack_kept_objects = 0;
1504
1505 repo_config_get_bool(r, "repack.packkeptobjects", &pack_kept_objects);
1506
1507 for (i = 0; i < m->num_packs; i++) {
1508 if (prepare_midx_pack(r, m, i))
1509 continue;
1510 if (!pack_kept_objects && m->packs[i]->pack_keep)
1511 continue;
ce1e4a10 1512
ce1e4a10 1513 include_pack[i] = 1;
3ce4ca0a
DS
1514 count++;
1515 }
ce1e4a10 1516
3ce4ca0a 1517 return count < 2;
ce1e4a10
DS
1518}
1519
1520static int fill_included_packs_batch(struct repository *r,
1521 struct multi_pack_index *m,
1522 unsigned char *include_pack,
1523 size_t batch_size)
1524{
1525 uint32_t i, packs_to_repack;
1526 size_t total_size;
1527 struct repack_info *pack_info = xcalloc(m->num_packs, sizeof(struct repack_info));
3ce4ca0a
DS
1528 int pack_kept_objects = 0;
1529
1530 repo_config_get_bool(r, "repack.packkeptobjects", &pack_kept_objects);
ce1e4a10
DS
1531
1532 for (i = 0; i < m->num_packs; i++) {
1533 pack_info[i].pack_int_id = i;
1534
1535 if (prepare_midx_pack(r, m, i))
1536 continue;
1537
1538 pack_info[i].mtime = m->packs[i]->mtime;
1539 }
1540
1541 for (i = 0; batch_size && i < m->num_objects; i++) {
1542 uint32_t pack_int_id = nth_midxed_pack_int_id(m, i);
1543 pack_info[pack_int_id].referenced_objects++;
1544 }
1545
1546 QSORT(pack_info, m->num_packs, compare_by_mtime);
1547
1548 total_size = 0;
1549 packs_to_repack = 0;
1550 for (i = 0; total_size < batch_size && i < m->num_packs; i++) {
1551 int pack_int_id = pack_info[i].pack_int_id;
1552 struct packed_git *p = m->packs[pack_int_id];
1553 size_t expected_size;
1554
1555 if (!p)
1556 continue;
3ce4ca0a
DS
1557 if (!pack_kept_objects && p->pack_keep)
1558 continue;
ce1e4a10
DS
1559 if (open_pack_index(p) || !p->num_objects)
1560 continue;
1561
1562 expected_size = (size_t)(p->pack_size
1563 * pack_info[i].referenced_objects);
1564 expected_size /= p->num_objects;
1565
1566 if (expected_size >= batch_size)
1567 continue;
1568
1569 packs_to_repack++;
1570 total_size += expected_size;
1571 include_pack[pack_int_id] = 1;
1572 }
1573
1574 free(pack_info);
1575
1eb22c7d 1576 if (packs_to_repack < 2)
ce1e4a10
DS
1577 return 1;
1578
2af890bb
DS
1579 return 0;
1580}
ce1e4a10 1581
efbc3aee 1582int midx_repack(struct repository *r, const char *object_dir, size_t batch_size, unsigned flags)
ce1e4a10
DS
1583{
1584 int result = 0;
1585 uint32_t i;
1586 unsigned char *include_pack;
1587 struct child_process cmd = CHILD_PROCESS_INIT;
6af3b00a 1588 FILE *cmd_in;
ce1e4a10
DS
1589 struct strbuf base_name = STRBUF_INIT;
1590 struct multi_pack_index *m = load_multi_pack_index(object_dir, 1);
1591
e11d86de
SLN
1592 /*
1593 * When updating the default for these configuration
1594 * variables in builtin/repack.c, these must be adjusted
1595 * to match.
1596 */
1597 int delta_base_offset = 1;
1598 int use_delta_islands = 0;
1599
ce1e4a10
DS
1600 if (!m)
1601 return 0;
1602
ca56dadb 1603 CALLOC_ARRAY(include_pack, m->num_packs);
ce1e4a10
DS
1604
1605 if (batch_size) {
1606 if (fill_included_packs_batch(r, m, include_pack, batch_size))
1607 goto cleanup;
3ce4ca0a 1608 } else if (fill_included_packs_all(r, m, include_pack))
ce1e4a10
DS
1609 goto cleanup;
1610
e11d86de
SLN
1611 repo_config_get_bool(r, "repack.usedeltabaseoffset", &delta_base_offset);
1612 repo_config_get_bool(r, "repack.usedeltaislands", &use_delta_islands);
1613
c972bf4c 1614 strvec_push(&cmd.args, "pack-objects");
ce1e4a10
DS
1615
1616 strbuf_addstr(&base_name, object_dir);
1617 strbuf_addstr(&base_name, "/pack/pack");
c972bf4c 1618 strvec_push(&cmd.args, base_name.buf);
64d80e7d 1619
e11d86de 1620 if (delta_base_offset)
c972bf4c 1621 strvec_push(&cmd.args, "--delta-base-offset");
e11d86de 1622 if (use_delta_islands)
c972bf4c 1623 strvec_push(&cmd.args, "--delta-islands");
e11d86de 1624
64d80e7d 1625 if (flags & MIDX_PROGRESS)
c972bf4c 1626 strvec_push(&cmd.args, "--progress");
64d80e7d 1627 else
c972bf4c 1628 strvec_push(&cmd.args, "-q");
64d80e7d 1629
ce1e4a10
DS
1630 strbuf_release(&base_name);
1631
1632 cmd.git_cmd = 1;
1633 cmd.in = cmd.out = -1;
1634
1635 if (start_command(&cmd)) {
1636 error(_("could not start pack-objects"));
1637 result = 1;
1638 goto cleanup;
1639 }
1640
6af3b00a
RS
1641 cmd_in = xfdopen(cmd.in, "w");
1642
ce1e4a10
DS
1643 for (i = 0; i < m->num_objects; i++) {
1644 struct object_id oid;
1645 uint32_t pack_int_id = nth_midxed_pack_int_id(m, i);
1646
1647 if (!include_pack[pack_int_id])
1648 continue;
1649
1650 nth_midxed_object_oid(&oid, m, i);
6af3b00a 1651 fprintf(cmd_in, "%s\n", oid_to_hex(&oid));
ce1e4a10 1652 }
6af3b00a 1653 fclose(cmd_in);
ce1e4a10
DS
1654
1655 if (finish_command(&cmd)) {
1656 error(_("could not finish pack-objects"));
1657 result = 1;
1658 goto cleanup;
1659 }
1660
f57a7396 1661 result = write_midx_internal(object_dir, NULL, NULL, flags);
ce1e4a10
DS
1662 m = NULL;
1663
1664cleanup:
1665 if (m)
1666 close_midx(m);
1667 free(include_pack);
1668 return result;
1669}