]> git.ipfire.org Git - thirdparty/git.git/blame - builtin/pack-objects.c
Merge branch 'ea/blame-use-oideq'
[thirdparty/git.git] / builtin / pack-objects.c
CommitLineData
5d4a6003 1#include "builtin.h"
c323ac7d 2#include "cache.h"
a80d72db 3#include "repository.h"
b2141fc1 4#include "config.h"
a74db82e 5#include "attr.h"
c323ac7d 6#include "object.h"
8e440259
PE
7#include "blob.h"
8#include "commit.h"
9#include "tag.h"
10#include "tree.h"
c323ac7d 11#include "delta.h"
a733cb60 12#include "pack.h"
3449f8c4 13#include "pack-revindex.h"
c38138cd 14#include "csum-file.h"
1b0c7174 15#include "tree-walk.h"
b5d97e6b
JH
16#include "diff.h"
17#include "revision.h"
18#include "list-objects.h"
9535ce73
JH
19#include "list-objects-filter.h"
20#include "list-objects-filter-options.h"
2834bc27 21#include "pack-objects.h"
96a02f8f 22#include "progress.h"
f0a24aa5 23#include "refs.h"
cf2ba13a 24#include "streaming.h"
93749194 25#include "thread-utils.h"
6b8fda2d 26#include "pack-bitmap.h"
28b8a730 27#include "delta-islands.h"
abcb8655 28#include "reachable.h"
fe299ec5 29#include "oid-array.h"
dbbcd44f 30#include "strvec.h"
ec2dd32c 31#include "list.h"
0317f455 32#include "packfile.h"
a80d72db 33#include "object-store.h"
ed7e5fc3 34#include "dir.h"
6a22d521 35#include "midx.h"
ae417807 36#include "trace2.h"
120ad2b0 37#include "shallow.h"
e00549aa 38#include "promisor-remote.h"
8ecce684 39
43fa44fa 40#define IN_PACK(obj) oe_in_pack(&to_pack, obj)
ac77d0c3
NTND
41#define SIZE(obj) oe_size(&to_pack, obj)
42#define SET_SIZE(obj,size) oe_set_size(&to_pack, obj, size)
0aca34e8 43#define DELTA_SIZE(obj) oe_delta_size(&to_pack, obj)
898eba5e
NTND
44#define DELTA(obj) oe_delta(&to_pack, obj)
45#define DELTA_CHILD(obj) oe_delta_child(&to_pack, obj)
46#define DELTA_SIBLING(obj) oe_delta_sibling(&to_pack, obj)
47#define SET_DELTA(obj, val) oe_set_delta(&to_pack, obj, val)
6a1e32d5 48#define SET_DELTA_EXT(obj, oid) oe_set_delta_ext(&to_pack, obj, oid)
0aca34e8 49#define SET_DELTA_SIZE(obj, val) oe_set_delta_size(&to_pack, obj, val)
898eba5e
NTND
50#define SET_DELTA_CHILD(obj, val) oe_set_delta_child(&to_pack, obj, val)
51#define SET_DELTA_SIBLING(obj, val) oe_set_delta_sibling(&to_pack, obj, val)
43fa44fa 52
99fb6e04 53static const char *pack_usage[] = {
b8c1d275
AH
54 N_("git pack-objects --stdout [<options>...] [< <ref-list> | < <object-list>]"),
55 N_("git pack-objects [<options>...] <base-name> [< <ref-list> | < <object-list>]"),
99fb6e04
NTND
56 NULL
57};
c323ac7d 58
3f9ac8d2 59/*
2834bc27
VM
60 * Objects we are going to pack are collected in the `to_pack` structure.
61 * It contains an array (dynamically expanded) of the object data, and a map
62 * that can resolve SHA1s to their position in the array.
3f9ac8d2 63 */
2834bc27
VM
64static struct packing_data to_pack;
65
79814f42 66static struct pack_idx_entry **written_list;
5af05043 67static uint32_t nr_result, nr_written, nr_seen;
6a1e32d5 68static struct bitmap_index *bitmap_git;
28b8a730 69static uint32_t write_layer;
3f9ac8d2 70
96f1e58f 71static int non_empty;
a7de7130 72static int reuse_delta = 1, reuse_object = 1;
e5e9714a 73static int keep_unreachable, unpack_unreachable, include_tag;
dddbad72 74static timestamp_t unpack_unreachable_expiration;
e26a8c47 75static int pack_loose_unreachable;
96f1e58f 76static int local;
56dfeb62 77static int have_non_local_packs;
96f1e58f 78static int incremental;
ed7e5fc3
NTND
79static int ignore_packed_keep_on_disk;
80static int ignore_packed_keep_in_core;
be6b1914 81static int allow_ofs_delta;
ebcfb379 82static struct pack_idx_option pack_idx_opts;
d01fb92f 83static const char *base_name;
024701f1 84static int progress = 1;
4812a93a 85static int window = 10;
568508e7 86static unsigned long pack_size_limit;
618e613a 87static int depth = 50;
43cc2b42 88static int delta_search_threads;
df6d6101 89static int pack_to_stdout;
4f6d26b1 90static int sparse;
6a1e32d5 91static int thin;
8d1d8f83 92static int num_preferred_base;
dc6a0757 93static struct progress *progress_state;
c323ac7d 94
6b8fda2d
VM
95static struct packed_git *reuse_packfile;
96static uint32_t reuse_packfile_objects;
bb514de3 97static struct bitmap *reuse_packfile_bitmap;
6b8fda2d 98
645c432d
KS
99static int use_bitmap_index_default = 1;
100static int use_bitmap_index = -1;
e704fc79 101static int allow_pack_reuse = 1;
25575015
JK
102static enum {
103 WRITE_BITMAP_FALSE = 0,
104 WRITE_BITMAP_QUIET,
105 WRITE_BITMAP_TRUE,
106} write_bitmap_index;
d4316604 107static uint16_t write_bitmap_options = BITMAP_OPT_HASH_CACHE;
6b8fda2d 108
0c16cd49
JT
109static int exclude_promisor_objects;
110
28b8a730
JK
111static int use_delta_islands;
112
074b2eea 113static unsigned long delta_cache_size = 0;
9806f5a7 114static unsigned long max_delta_cache_size = DEFAULT_DELTA_CACHE_SIZE;
e3dfddb3 115static unsigned long cache_max_small_delta_size = 1000;
074b2eea 116
a97773ce
BD
117static unsigned long window_memory_limit = 0;
118
9535ce73
JH
119static struct list_objects_filter_options filter_options;
120
dd4b732d
JT
121static struct string_list uri_protocols = STRING_LIST_INIT_NODUP;
122
9535ce73 123enum missing_action {
0c16cd49
JT
124 MA_ERROR = 0, /* fail if any missing objects are encountered */
125 MA_ALLOW_ANY, /* silently allow ALL missing objects */
126 MA_ALLOW_PROMISOR, /* silently allow all missing PROMISOR objects */
9535ce73
JH
127};
128static enum missing_action arg_missing_action;
129static show_object_fn fn_show_object;
130
dd4b732d
JT
131struct configured_exclusion {
132 struct oidmap_entry e;
133 char *pack_hash_hex;
134 char *uri;
135};
136static struct oidmap configured_exclusions;
137
138static struct oidset excluded_by_config;
139
3f9ac8d2
JH
140/*
141 * stats
142 */
7cadf491
SP
143static uint32_t written, written_delta;
144static uint32_t reused, reused_delta;
3f9ac8d2 145
7cc8f971
VM
146/*
147 * Indexed commits
148 */
149static struct commit **indexed_commits;
150static unsigned int indexed_commits_nr;
151static unsigned int indexed_commits_alloc;
152
153static void index_commit_for_bitmap(struct commit *commit)
154{
155 if (indexed_commits_nr >= indexed_commits_alloc) {
156 indexed_commits_alloc = (indexed_commits_alloc + 32) * 2;
2756ca43 157 REALLOC_ARRAY(indexed_commits, indexed_commits_alloc);
7cc8f971
VM
158 }
159
160 indexed_commits[indexed_commits_nr++] = commit;
161}
780e6e73 162
3613f9b4 163static void *get_delta(struct object_entry *entry)
c323ac7d 164{
3613f9b4
NP
165 unsigned long size, base_size, delta_size;
166 void *buf, *base_buf, *delta_buf;
21666f1a 167 enum object_type type;
c323ac7d 168
b4f5aca4 169 buf = read_object_file(&entry->idx.oid, &type, &size);
3613f9b4 170 if (!buf)
f616db6a 171 die(_("unable to read %s"), oid_to_hex(&entry->idx.oid));
898eba5e
NTND
172 base_buf = read_object_file(&DELTA(entry)->idx.oid, &type,
173 &base_size);
3613f9b4 174 if (!base_buf)
e6a492b7 175 die("unable to read %s",
898eba5e 176 oid_to_hex(&DELTA(entry)->idx.oid));
3613f9b4 177 delta_buf = diff_delta(base_buf, base_size,
dcde55bc 178 buf, size, &delta_size, 0);
1a07e59c 179 /*
15beaaa3 180 * We successfully computed this delta once but dropped it for
1a07e59c
NTND
181 * memory reasons. Something is very wrong if this time we
182 * recompute and create a different delta.
183 */
0aca34e8 184 if (!delta_buf || delta_size != DELTA_SIZE(entry))
1a07e59c 185 BUG("delta size changed");
3613f9b4
NP
186 free(buf);
187 free(base_buf);
c323ac7d
LT
188 return delta_buf;
189}
190
30ebb40a
NP
191static unsigned long do_compress(void **pptr, unsigned long size)
192{
ef49a7a0 193 git_zstream stream;
30ebb40a
NP
194 void *in, *out;
195 unsigned long maxsize;
196
55bb5c91 197 git_deflate_init(&stream, pack_compression_level);
225a6f10 198 maxsize = git_deflate_bound(&stream, size);
30ebb40a
NP
199
200 in = *pptr;
201 out = xmalloc(maxsize);
202 *pptr = out;
203
204 stream.next_in = in;
205 stream.avail_in = size;
206 stream.next_out = out;
207 stream.avail_out = maxsize;
55bb5c91 208 while (git_deflate(&stream, Z_FINISH) == Z_OK)
30ebb40a 209 ; /* nothing */
55bb5c91 210 git_deflate_end(&stream);
30ebb40a
NP
211
212 free(in);
213 return stream.total_out;
214}
215
98a3beab 216static unsigned long write_large_blob_data(struct git_istream *st, struct hashfile *f,
188960b4 217 const struct object_id *oid)
cf2ba13a
NTND
218{
219 git_zstream stream;
220 unsigned char ibuf[1024 * 16];
221 unsigned char obuf[1024 * 16];
222 unsigned long olen = 0;
223
cf2ba13a
NTND
224 git_deflate_init(&stream, pack_compression_level);
225
226 for (;;) {
227 ssize_t readlen;
228 int zret = Z_OK;
229 readlen = read_istream(st, ibuf, sizeof(ibuf));
230 if (readlen == -1)
188960b4 231 die(_("unable to read %s"), oid_to_hex(oid));
cf2ba13a
NTND
232
233 stream.next_in = ibuf;
234 stream.avail_in = readlen;
235 while ((stream.avail_in || readlen == 0) &&
236 (zret == Z_OK || zret == Z_BUF_ERROR)) {
237 stream.next_out = obuf;
238 stream.avail_out = sizeof(obuf);
239 zret = git_deflate(&stream, readlen ? 0 : Z_FINISH);
98a3beab 240 hashwrite(f, obuf, stream.next_out - obuf);
cf2ba13a
NTND
241 olen += stream.next_out - obuf;
242 }
243 if (stream.avail_in)
244 die(_("deflate error (%d)"), zret);
245 if (readlen == 0) {
246 if (zret != Z_STREAM_END)
247 die(_("deflate error (%d)"), zret);
248 break;
249 }
250 }
251 git_deflate_end(&stream);
252 return olen;
253}
254
780e6e73
NP
255/*
256 * we are going to reuse the existing object data as is. make
257 * sure it is not corrupt.
258 */
079afb18
SP
259static int check_pack_inflate(struct packed_git *p,
260 struct pack_window **w_curs,
6777a59f
SP
261 off_t offset,
262 off_t len,
079afb18
SP
263 unsigned long expect)
264{
ef49a7a0 265 git_zstream stream;
079afb18
SP
266 unsigned char fakebuf[4096], *in;
267 int st;
268
269 memset(&stream, 0, sizeof(stream));
39c68542 270 git_inflate_init(&stream);
079afb18
SP
271 do {
272 in = use_pack(p, w_curs, offset, &stream.avail_in);
273 stream.next_in = in;
274 stream.next_out = fakebuf;
275 stream.avail_out = sizeof(fakebuf);
39c68542 276 st = git_inflate(&stream, Z_FINISH);
079afb18
SP
277 offset += stream.next_in - in;
278 } while (st == Z_OK || st == Z_BUF_ERROR);
39c68542 279 git_inflate_end(&stream);
079afb18
SP
280 return (st == Z_STREAM_END &&
281 stream.total_out == expect &&
282 stream.total_in == len) ? 0 : -1;
283}
284
98a3beab 285static void copy_pack_data(struct hashfile *f,
079afb18
SP
286 struct packed_git *p,
287 struct pack_window **w_curs,
6777a59f
SP
288 off_t offset,
289 off_t len)
079afb18
SP
290{
291 unsigned char *in;
ef49a7a0 292 unsigned long avail;
079afb18
SP
293
294 while (len) {
295 in = use_pack(p, w_curs, offset, &avail);
296 if (avail > len)
ef49a7a0 297 avail = (unsigned long)len;
98a3beab 298 hashwrite(f, in, avail);
079afb18
SP
299 offset += avail;
300 len -= avail;
301 }
302}
303
1b4bb16b 304/* Return 0 if we will bust the pack-size limit */
98a3beab 305static unsigned long write_no_reuse_object(struct hashfile *f, struct object_entry *entry,
c9018b03 306 unsigned long limit, int usable_delta)
c323ac7d 307{
c9018b03 308 unsigned long size, datalen;
2c5e2865
JK
309 unsigned char header[MAX_PACK_OBJECT_HEADER],
310 dheader[MAX_PACK_OBJECT_HEADER];
6777a59f 311 unsigned hdrlen;
2c5ef824 312 enum object_type type;
c9018b03 313 void *buf;
cf2ba13a 314 struct git_istream *st = NULL;
41179100 315 const unsigned hashsz = the_hash_algo->rawsz;
c9018b03
NTND
316
317 if (!usable_delta) {
fd9b1bae 318 if (oe_type(entry) == OBJ_BLOB &&
ac77d0c3 319 oe_size_greater_than(&to_pack, entry, big_file_threshold) &&
c8123e72
MT
320 (st = open_istream(the_repository, &entry->idx.oid, &type,
321 &size, NULL)) != NULL)
cf2ba13a
NTND
322 buf = NULL;
323 else {
b4f5aca4 324 buf = read_object_file(&entry->idx.oid, &type, &size);
cf2ba13a 325 if (!buf)
e6a492b7 326 die(_("unable to read %s"),
327 oid_to_hex(&entry->idx.oid));
cf2ba13a 328 }
c9018b03
NTND
329 /*
330 * make sure no cached delta data remains from a
331 * previous attempt before a pack split occurred.
332 */
6a83d902 333 FREE_AND_NULL(entry->delta_data);
c9018b03
NTND
334 entry->z_delta_size = 0;
335 } else if (entry->delta_data) {
0aca34e8 336 size = DELTA_SIZE(entry);
c9018b03
NTND
337 buf = entry->delta_data;
338 entry->delta_data = NULL;
898eba5e 339 type = (allow_ofs_delta && DELTA(entry)->idx.offset) ?
c9018b03
NTND
340 OBJ_OFS_DELTA : OBJ_REF_DELTA;
341 } else {
342 buf = get_delta(entry);
0aca34e8 343 size = DELTA_SIZE(entry);
898eba5e 344 type = (allow_ofs_delta && DELTA(entry)->idx.offset) ?
c9018b03
NTND
345 OBJ_OFS_DELTA : OBJ_REF_DELTA;
346 }
347
cf2ba13a
NTND
348 if (st) /* large blob case, just assume we don't compress well */
349 datalen = size;
350 else if (entry->z_delta_size)
c9018b03
NTND
351 datalen = entry->z_delta_size;
352 else
353 datalen = do_compress(&buf, size);
354
355 /*
356 * The object header is a byte of 'type' followed by zero or
357 * more bytes of length.
358 */
7202a6fa
JK
359 hdrlen = encode_in_pack_object_header(header, sizeof(header),
360 type, size);
c9018b03
NTND
361
362 if (type == OBJ_OFS_DELTA) {
363 /*
364 * Deltas with relative base contain an additional
365 * encoding of the relative offset for the delta
366 * base from this object's position in the pack.
367 */
898eba5e 368 off_t ofs = entry->idx.offset - DELTA(entry)->idx.offset;
c9018b03
NTND
369 unsigned pos = sizeof(dheader) - 1;
370 dheader[pos] = ofs & 127;
371 while (ofs >>= 7)
372 dheader[--pos] = 128 | (--ofs & 127);
41179100 373 if (limit && hdrlen + sizeof(dheader) - pos + datalen + hashsz >= limit) {
cf2ba13a
NTND
374 if (st)
375 close_istream(st);
c9018b03
NTND
376 free(buf);
377 return 0;
378 }
98a3beab 379 hashwrite(f, header, hdrlen);
380 hashwrite(f, dheader + pos, sizeof(dheader) - pos);
c9018b03
NTND
381 hdrlen += sizeof(dheader) - pos;
382 } else if (type == OBJ_REF_DELTA) {
383 /*
384 * Deltas with a base reference contain
41179100 385 * additional bytes for the base object ID.
c9018b03 386 */
41179100 387 if (limit && hdrlen + hashsz + datalen + hashsz >= limit) {
cf2ba13a
NTND
388 if (st)
389 close_istream(st);
c9018b03
NTND
390 free(buf);
391 return 0;
392 }
98a3beab 393 hashwrite(f, header, hdrlen);
42c8ce1c 394 hashwrite(f, DELTA(entry)->idx.oid.hash, hashsz);
41179100 395 hdrlen += hashsz;
c9018b03 396 } else {
41179100 397 if (limit && hdrlen + datalen + hashsz >= limit) {
cf2ba13a
NTND
398 if (st)
399 close_istream(st);
c9018b03
NTND
400 free(buf);
401 return 0;
402 }
98a3beab 403 hashwrite(f, header, hdrlen);
c9018b03 404 }
cf2ba13a 405 if (st) {
188960b4 406 datalen = write_large_blob_data(st, f, &entry->idx.oid);
cf2ba13a
NTND
407 close_istream(st);
408 } else {
98a3beab 409 hashwrite(f, buf, datalen);
cf2ba13a
NTND
410 free(buf);
411 }
c9018b03
NTND
412
413 return hdrlen + datalen;
414}
415
416/* Return 0 if we will bust the pack-size limit */
98a3beab 417static off_t write_reuse_object(struct hashfile *f, struct object_entry *entry,
af92a645 418 unsigned long limit, int usable_delta)
c9018b03 419{
43fa44fa 420 struct packed_git *p = IN_PACK(entry);
c9018b03
NTND
421 struct pack_window *w_curs = NULL;
422 struct revindex_entry *revidx;
423 off_t offset;
fd9b1bae 424 enum object_type type = oe_type(entry);
211c61c6 425 off_t datalen;
2c5e2865
JK
426 unsigned char header[MAX_PACK_OBJECT_HEADER],
427 dheader[MAX_PACK_OBJECT_HEADER];
c9018b03 428 unsigned hdrlen;
41179100 429 const unsigned hashsz = the_hash_algo->rawsz;
ac77d0c3 430 unsigned long entry_size = SIZE(entry);
c9018b03 431
898eba5e
NTND
432 if (DELTA(entry))
433 type = (allow_ofs_delta && DELTA(entry)->idx.offset) ?
c9018b03 434 OBJ_OFS_DELTA : OBJ_REF_DELTA;
7202a6fa 435 hdrlen = encode_in_pack_object_header(header, sizeof(header),
ac77d0c3 436 type, entry_size);
c9018b03
NTND
437
438 offset = entry->in_pack_offset;
439 revidx = find_pack_revindex(p, offset);
440 datalen = revidx[1].offset - offset;
441 if (!pack_to_stdout && p->index_version > 1 &&
442 check_pack_crc(p, &w_curs, offset, datalen, revidx->nr)) {
f616db6a 443 error(_("bad packed object CRC for %s"),
e6a492b7 444 oid_to_hex(&entry->idx.oid));
c9018b03
NTND
445 unuse_pack(&w_curs);
446 return write_no_reuse_object(f, entry, limit, usable_delta);
447 }
448
449 offset += entry->in_pack_header_size;
450 datalen -= entry->in_pack_header_size;
451
452 if (!pack_to_stdout && p->index_version == 1 &&
ac77d0c3 453 check_pack_inflate(p, &w_curs, offset, datalen, entry_size)) {
f616db6a 454 error(_("corrupt packed object for %s"),
e6a492b7 455 oid_to_hex(&entry->idx.oid));
c9018b03
NTND
456 unuse_pack(&w_curs);
457 return write_no_reuse_object(f, entry, limit, usable_delta);
458 }
459
460 if (type == OBJ_OFS_DELTA) {
898eba5e 461 off_t ofs = entry->idx.offset - DELTA(entry)->idx.offset;
c9018b03
NTND
462 unsigned pos = sizeof(dheader) - 1;
463 dheader[pos] = ofs & 127;
464 while (ofs >>= 7)
465 dheader[--pos] = 128 | (--ofs & 127);
41179100 466 if (limit && hdrlen + sizeof(dheader) - pos + datalen + hashsz >= limit) {
c9018b03
NTND
467 unuse_pack(&w_curs);
468 return 0;
469 }
98a3beab 470 hashwrite(f, header, hdrlen);
471 hashwrite(f, dheader + pos, sizeof(dheader) - pos);
c9018b03
NTND
472 hdrlen += sizeof(dheader) - pos;
473 reused_delta++;
474 } else if (type == OBJ_REF_DELTA) {
41179100 475 if (limit && hdrlen + hashsz + datalen + hashsz >= limit) {
c9018b03
NTND
476 unuse_pack(&w_curs);
477 return 0;
478 }
98a3beab 479 hashwrite(f, header, hdrlen);
42c8ce1c 480 hashwrite(f, DELTA(entry)->idx.oid.hash, hashsz);
41179100 481 hdrlen += hashsz;
c9018b03
NTND
482 reused_delta++;
483 } else {
41179100 484 if (limit && hdrlen + datalen + hashsz >= limit) {
c9018b03
NTND
485 unuse_pack(&w_curs);
486 return 0;
487 }
98a3beab 488 hashwrite(f, header, hdrlen);
c9018b03
NTND
489 }
490 copy_pack_data(f, p, &w_curs, offset, datalen);
491 unuse_pack(&w_curs);
492 reused++;
493 return hdrlen + datalen;
494}
495
496/* Return 0 if we will bust the pack-size limit */
98a3beab 497static off_t write_object(struct hashfile *f,
af92a645
NTND
498 struct object_entry *entry,
499 off_t write_offset)
c9018b03 500{
af92a645
NTND
501 unsigned long limit;
502 off_t len;
2c5ef824 503 int usable_delta, to_reuse;
c323ac7d 504
78d1e84f
NP
505 if (!pack_to_stdout)
506 crc32_begin(f);
507
a2430dde 508 /* apply size limit if limited packsize and not first object */
a1e4760f
NP
509 if (!pack_size_limit || !nr_written)
510 limit = 0;
511 else if (pack_size_limit <= write_offset)
512 /*
513 * the earlier object did not fit the limit; avoid
514 * mistaking this with unlimited (i.e. limit = 0).
515 */
516 limit = 1;
517 else
518 limit = pack_size_limit - write_offset;
2c5ef824 519
898eba5e 520 if (!DELTA(entry))
2c5ef824
NP
521 usable_delta = 0; /* no delta */
522 else if (!pack_size_limit)
523 usable_delta = 1; /* unlimited packfile */
898eba5e 524 else if (DELTA(entry)->idx.offset == (off_t)-1)
2c5ef824 525 usable_delta = 0; /* base was written to another pack */
898eba5e 526 else if (DELTA(entry)->idx.offset)
2c5ef824
NP
527 usable_delta = 1; /* base already exists in this pack */
528 else
529 usable_delta = 0; /* base could end up in another pack */
530
a7de7130 531 if (!reuse_object)
fa736f72 532 to_reuse = 0; /* explicit */
43fa44fa 533 else if (!IN_PACK(entry))
ab7cd7bb 534 to_reuse = 0; /* can't reuse what we don't have */
fd9b1bae
NTND
535 else if (oe_type(entry) == OBJ_REF_DELTA ||
536 oe_type(entry) == OBJ_OFS_DELTA)
17b08f2c
DH
537 /* check_object() decided it for us ... */
538 to_reuse = usable_delta;
539 /* ... but pack split may override that */
fd9b1bae 540 else if (oe_type(entry) != entry->in_pack_type)
ab7cd7bb 541 to_reuse = 0; /* pack has delta which is unusable */
898eba5e 542 else if (DELTA(entry))
ab7cd7bb
JH
543 to_reuse = 0; /* we want to pack afresh */
544 else
545 to_reuse = 1; /* we have it in-pack undeltified,
546 * and we do not need to deltify it.
547 */
548
c9018b03
NTND
549 if (!to_reuse)
550 len = write_no_reuse_object(f, entry, limit, usable_delta);
551 else
552 len = write_reuse_object(f, entry, limit, usable_delta);
553 if (!len)
554 return 0;
64bd76b1 555
17b08f2c 556 if (usable_delta)
ab7cd7bb 557 written_delta++;
3f9ac8d2 558 written++;
78d1e84f 559 if (!pack_to_stdout)
aa7e44bf 560 entry->idx.crc32 = crc32_end(f);
c9018b03 561 return len;
c323ac7d
LT
562}
563
f63c79db
JH
564enum write_one_status {
565 WRITE_ONE_SKIP = -1, /* already written */
566 WRITE_ONE_BREAK = 0, /* writing this will bust the limit; not written */
567 WRITE_ONE_WRITTEN = 1, /* normal */
568 WRITE_ONE_RECURSIVE = 2 /* already scheduled to be written */
569};
570
98a3beab 571static enum write_one_status write_one(struct hashfile *f,
f63c79db
JH
572 struct object_entry *e,
573 off_t *offset)
9d5ab962 574{
af92a645 575 off_t size;
f63c79db 576 int recursing;
d7dd0223 577
f63c79db
JH
578 /*
579 * we set offset to 1 (which is an impossible value) to mark
580 * the fact that this object is involved in "write its base
581 * first before writing a deltified object" recursion.
582 */
583 recursing = (e->idx.offset == 1);
584 if (recursing) {
f616db6a 585 warning(_("recursive delta detected for object %s"),
e6a492b7 586 oid_to_hex(&e->idx.oid));
f63c79db
JH
587 return WRITE_ONE_RECURSIVE;
588 } else if (e->idx.offset || e->preferred_base) {
589 /* offset is non zero if object is written already. */
590 return WRITE_ONE_SKIP;
591 }
d7dd0223 592
720c9f7b 593 /* if we are deltified, write out base object first. */
898eba5e 594 if (DELTA(e)) {
f63c79db 595 e->idx.offset = 1; /* now recurse */
898eba5e 596 switch (write_one(f, DELTA(e), offset)) {
f63c79db
JH
597 case WRITE_ONE_RECURSIVE:
598 /* we cannot depend on this one */
898eba5e 599 SET_DELTA(e, NULL);
f63c79db
JH
600 break;
601 default:
602 break;
603 case WRITE_ONE_BREAK:
604 e->idx.offset = recursing;
605 return WRITE_ONE_BREAK;
606 }
607 }
d7dd0223 608
6ed7f25e
NP
609 e->idx.offset = *offset;
610 size = write_object(f, e, *offset);
17b08f2c 611 if (!size) {
f63c79db
JH
612 e->idx.offset = recursing;
613 return WRITE_ONE_BREAK;
17b08f2c 614 }
79814f42 615 written_list[nr_written++] = &e->idx;
d7dd0223
NP
616
617 /* make sure off_t is sufficiently large not to wrap */
c03c8315 618 if (signed_add_overflows(*offset, size))
f616db6a 619 die(_("pack too large for current definition of off_t"));
6ed7f25e 620 *offset += size;
f63c79db 621 return WRITE_ONE_WRITTEN;
9d5ab962
JH
622}
623
d155254c 624static int mark_tagged(const char *path, const struct object_id *oid, int flag,
1b4bb16b
JH
625 void *cb_data)
626{
188960b4 627 struct object_id peeled;
3a37876b 628 struct object_entry *entry = packlist_find(&to_pack, oid);
1b4bb16b
JH
629
630 if (entry)
631 entry->tagged = 1;
b420d909 632 if (!peel_ref(path, &peeled)) {
3a37876b 633 entry = packlist_find(&to_pack, &peeled);
1b4bb16b
JH
634 if (entry)
635 entry->tagged = 1;
636 }
637 return 0;
638}
639
be126818 640static inline void add_to_write_order(struct object_entry **wo,
92bef1a1 641 unsigned int *endp,
1b4bb16b
JH
642 struct object_entry *e)
643{
fe0ac2fb 644 if (e->filled || oe_layer(&to_pack, e) != write_layer)
1b4bb16b
JH
645 return;
646 wo[(*endp)++] = e;
647 e->filled = 1;
648}
649
650static void add_descendants_to_write_order(struct object_entry **wo,
92bef1a1 651 unsigned int *endp,
1b4bb16b
JH
652 struct object_entry *e)
653{
f380872f
DM
654 int add_to_order = 1;
655 while (e) {
656 if (add_to_order) {
657 struct object_entry *s;
658 /* add this node... */
659 add_to_write_order(wo, endp, e);
660 /* all its siblings... */
898eba5e 661 for (s = DELTA_SIBLING(e); s; s = DELTA_SIBLING(s)) {
f380872f
DM
662 add_to_write_order(wo, endp, s);
663 }
664 }
665 /* drop down a level to add left subtree nodes if possible */
898eba5e 666 if (DELTA_CHILD(e)) {
f380872f 667 add_to_order = 1;
898eba5e 668 e = DELTA_CHILD(e);
f380872f
DM
669 } else {
670 add_to_order = 0;
671 /* our sibling might have some children, it is next */
898eba5e
NTND
672 if (DELTA_SIBLING(e)) {
673 e = DELTA_SIBLING(e);
f380872f
DM
674 continue;
675 }
676 /* go back to our parent node */
898eba5e
NTND
677 e = DELTA(e);
678 while (e && !DELTA_SIBLING(e)) {
f380872f
DM
679 /* we're on the right side of a subtree, keep
680 * going up until we can go right again */
898eba5e 681 e = DELTA(e);
f380872f
DM
682 }
683 if (!e) {
684 /* done- we hit our original root node */
685 return;
686 }
687 /* pass it off to sibling at this level */
898eba5e 688 e = DELTA_SIBLING(e);
f380872f
DM
689 }
690 };
1b4bb16b
JH
691}
692
693static void add_family_to_write_order(struct object_entry **wo,
92bef1a1 694 unsigned int *endp,
1b4bb16b
JH
695 struct object_entry *e)
696{
697 struct object_entry *root;
698
898eba5e 699 for (root = e; DELTA(root); root = DELTA(root))
1b4bb16b 700 ; /* nothing */
1b4bb16b
JH
701 add_descendants_to_write_order(wo, endp, root);
702}
703
f64ba53e 704static void compute_layer_order(struct object_entry **wo, unsigned int *wo_end)
1b4bb16b 705{
f64ba53e 706 unsigned int i, last_untagged;
2834bc27 707 struct object_entry *objects = to_pack.objects;
1b4bb16b 708
2834bc27 709 for (i = 0; i < to_pack.nr_objects; i++) {
1b4bb16b
JH
710 if (objects[i].tagged)
711 break;
f64ba53e 712 add_to_write_order(wo, wo_end, &objects[i]);
1b4bb16b 713 }
38d4debb 714 last_untagged = i;
1b4bb16b
JH
715
716 /*
717 * Then fill all the tagged tips.
718 */
2834bc27 719 for (; i < to_pack.nr_objects; i++) {
1b4bb16b 720 if (objects[i].tagged)
f64ba53e 721 add_to_write_order(wo, wo_end, &objects[i]);
1b4bb16b
JH
722 }
723
724 /*
725 * And then all remaining commits and tags.
726 */
2834bc27 727 for (i = last_untagged; i < to_pack.nr_objects; i++) {
fd9b1bae
NTND
728 if (oe_type(&objects[i]) != OBJ_COMMIT &&
729 oe_type(&objects[i]) != OBJ_TAG)
1b4bb16b 730 continue;
f64ba53e 731 add_to_write_order(wo, wo_end, &objects[i]);
1b4bb16b
JH
732 }
733
734 /*
735 * And then all the trees.
736 */
2834bc27 737 for (i = last_untagged; i < to_pack.nr_objects; i++) {
fd9b1bae 738 if (oe_type(&objects[i]) != OBJ_TREE)
1b4bb16b 739 continue;
f64ba53e 740 add_to_write_order(wo, wo_end, &objects[i]);
1b4bb16b
JH
741 }
742
743 /*
744 * Finally all the rest in really tight order
745 */
2834bc27 746 for (i = last_untagged; i < to_pack.nr_objects; i++) {
fe0ac2fb 747 if (!objects[i].filled && oe_layer(&to_pack, &objects[i]) == write_layer)
f64ba53e 748 add_family_to_write_order(wo, wo_end, &objects[i]);
38d4debb 749 }
f64ba53e
CC
750}
751
752static struct object_entry **compute_write_order(void)
753{
28b8a730 754 uint32_t max_layers = 1;
f64ba53e
CC
755 unsigned int i, wo_end;
756
757 struct object_entry **wo;
758 struct object_entry *objects = to_pack.objects;
759
760 for (i = 0; i < to_pack.nr_objects; i++) {
761 objects[i].tagged = 0;
762 objects[i].filled = 0;
763 SET_DELTA_CHILD(&objects[i], NULL);
764 SET_DELTA_SIBLING(&objects[i], NULL);
765 }
766
767 /*
768 * Fully connect delta_child/delta_sibling network.
769 * Make sure delta_sibling is sorted in the original
770 * recency order.
771 */
772 for (i = to_pack.nr_objects; i > 0;) {
773 struct object_entry *e = &objects[--i];
774 if (!DELTA(e))
775 continue;
776 /* Mark me as the first child */
777 e->delta_sibling_idx = DELTA(e)->delta_child_idx;
778 SET_DELTA_CHILD(DELTA(e), e);
38d4debb
DM
779 }
780
f64ba53e
CC
781 /*
782 * Mark objects that are at the tip of tags.
783 */
784 for_each_tag_ref(mark_tagged, NULL);
785
28b8a730
JK
786 if (use_delta_islands)
787 max_layers = compute_pack_layers(&to_pack);
788
f64ba53e
CC
789 ALLOC_ARRAY(wo, to_pack.nr_objects);
790 wo_end = 0;
791
28b8a730
JK
792 for (; write_layer < max_layers; ++write_layer)
793 compute_layer_order(wo, &wo_end);
38d4debb 794
2834bc27 795 if (wo_end != to_pack.nr_objects)
f616db6a
NTND
796 die(_("ordered %u objects, expected %"PRIu32),
797 wo_end, to_pack.nr_objects);
1b4bb16b
JH
798
799 return wo;
800}
801
bb514de3
JK
802
803/*
804 * A reused set of objects. All objects in a chunk have the same
805 * relative position in the original packfile and the generated
806 * packfile.
807 */
808
809static struct reused_chunk {
810 /* The offset of the first object of this chunk in the original
811 * packfile. */
812 off_t original;
813 /* The offset of the first object of this chunk in the generated
814 * packfile minus "original". */
815 off_t difference;
816} *reused_chunks;
817static int reused_chunks_nr;
818static int reused_chunks_alloc;
819
820static void record_reused_object(off_t where, off_t offset)
821{
822 if (reused_chunks_nr && reused_chunks[reused_chunks_nr-1].difference == offset)
823 return;
824
825 ALLOC_GROW(reused_chunks, reused_chunks_nr + 1,
826 reused_chunks_alloc);
827 reused_chunks[reused_chunks_nr].original = where;
828 reused_chunks[reused_chunks_nr].difference = offset;
829 reused_chunks_nr++;
830}
831
832/*
833 * Binary search to find the chunk that "where" is in. Note
834 * that we're not looking for an exact match, just the first
835 * chunk that contains it (which implicitly ends at the start
836 * of the next chunk.
837 */
838static off_t find_reused_offset(off_t where)
6b8fda2d 839{
bb514de3
JK
840 int lo = 0, hi = reused_chunks_nr;
841 while (lo < hi) {
842 int mi = lo + ((hi - lo) / 2);
843 if (where == reused_chunks[mi].original)
844 return reused_chunks[mi].difference;
845 if (where < reused_chunks[mi].original)
846 hi = mi;
847 else
848 lo = mi + 1;
849 }
6b8fda2d 850
bb514de3
JK
851 /*
852 * The first chunk starts at zero, so we can't have gone below
853 * there.
854 */
855 assert(lo);
856 return reused_chunks[lo-1].difference;
857}
6b8fda2d 858
bb514de3
JK
859static void write_reused_pack_one(size_t pos, struct hashfile *out,
860 struct pack_window **w_curs)
6b8fda2d 861{
bb514de3
JK
862 off_t offset, next, cur;
863 enum object_type type;
864 unsigned long size;
6b8fda2d 865
bb514de3
JK
866 offset = reuse_packfile->revindex[pos].offset;
867 next = reuse_packfile->revindex[pos + 1].offset;
6b8fda2d 868
bb514de3 869 record_reused_object(offset, offset - hashfile_total(out));
6b8fda2d 870
bb514de3
JK
871 cur = offset;
872 type = unpack_object_header(reuse_packfile, w_curs, &cur, &size);
873 assert(type >= 0);
6b8fda2d 874
bb514de3
JK
875 if (type == OBJ_OFS_DELTA) {
876 off_t base_offset;
877 off_t fixup;
878
879 unsigned char header[MAX_PACK_OBJECT_HEADER];
880 unsigned len;
881
882 base_offset = get_delta_base(reuse_packfile, w_curs, &cur, type, offset);
883 assert(base_offset != 0);
884
885 /* Convert to REF_DELTA if we must... */
886 if (!allow_ofs_delta) {
887 int base_pos = find_revindex_position(reuse_packfile, base_offset);
f66d4e02
JK
888 struct object_id base_oid;
889
890 nth_packed_object_id(&base_oid, reuse_packfile,
891 reuse_packfile->revindex[base_pos].nr);
bb514de3
JK
892
893 len = encode_in_pack_object_header(header, sizeof(header),
894 OBJ_REF_DELTA, size);
895 hashwrite(out, header, len);
f8cb64e3 896 hashwrite(out, base_oid.hash, the_hash_algo->rawsz);
bb514de3
JK
897 copy_pack_data(out, reuse_packfile, w_curs, cur, next - cur);
898 return;
899 }
6b8fda2d 900
bb514de3
JK
901 /* Otherwise see if we need to rewrite the offset... */
902 fixup = find_reused_offset(offset) -
903 find_reused_offset(base_offset);
904 if (fixup) {
905 unsigned char ofs_header[10];
906 unsigned i, ofs_len;
907 off_t ofs = offset - base_offset - fixup;
6b8fda2d 908
bb514de3
JK
909 len = encode_in_pack_object_header(header, sizeof(header),
910 OBJ_OFS_DELTA, size);
6b8fda2d 911
bb514de3
JK
912 i = sizeof(ofs_header) - 1;
913 ofs_header[i] = ofs & 127;
914 while (ofs >>= 7)
915 ofs_header[--i] = 128 | (--ofs & 127);
6b8fda2d 916
bb514de3 917 ofs_len = sizeof(ofs_header) - i;
6b8fda2d 918
bb514de3
JK
919 hashwrite(out, header, len);
920 hashwrite(out, ofs_header + sizeof(ofs_header) - ofs_len, ofs_len);
921 copy_pack_data(out, reuse_packfile, w_curs, cur, next - cur);
922 return;
923 }
924
925 /* ...otherwise we have no fixup, and can write it verbatim */
926 }
927
928 copy_pack_data(out, reuse_packfile, w_curs, offset, next - offset);
929}
930
931static size_t write_reused_pack_verbatim(struct hashfile *out,
932 struct pack_window **w_curs)
933{
934 size_t pos = 0;
935
936 while (pos < reuse_packfile_bitmap->word_alloc &&
937 reuse_packfile_bitmap->words[pos] == (eword_t)~0)
938 pos++;
939
940 if (pos) {
941 off_t to_write;
942
943 written = (pos * BITS_IN_EWORD);
944 to_write = reuse_packfile->revindex[written].offset
945 - sizeof(struct pack_header);
946
947 /* We're recording one chunk, not one object. */
948 record_reused_object(sizeof(struct pack_header), 0);
949 hashflush(out);
950 copy_pack_data(out, reuse_packfile, w_curs,
951 sizeof(struct pack_header), to_write);
657673f1 952
657673f1 953 display_progress(progress_state, written);
6b8fda2d 954 }
bb514de3
JK
955 return pos;
956}
957
958static void write_reused_pack(struct hashfile *f)
959{
960 size_t i = 0;
961 uint32_t offset;
962 struct pack_window *w_curs = NULL;
963
964 if (allow_ofs_delta)
965 i = write_reused_pack_verbatim(f, &w_curs);
966
967 for (; i < reuse_packfile_bitmap->word_alloc; ++i) {
968 eword_t word = reuse_packfile_bitmap->words[i];
969 size_t pos = (i * BITS_IN_EWORD);
6b8fda2d 970
bb514de3
JK
971 for (offset = 0; offset < BITS_IN_EWORD; ++offset) {
972 if ((word >> offset) == 0)
973 break;
974
975 offset += ewah_bit_ctz64(word >> offset);
976 write_reused_pack_one(pos + offset, f, &w_curs);
977 display_progress(progress_state, ++written);
978 }
979 }
6b8fda2d 980
bb514de3 981 unuse_pack(&w_curs);
6b8fda2d
VM
982}
983
dd4b732d
JT
984static void write_excluded_by_configs(void)
985{
986 struct oidset_iter iter;
987 const struct object_id *oid;
988
989 oidset_iter_init(&excluded_by_config, &iter);
990 while ((oid = oidset_iter_next(&iter))) {
991 struct configured_exclusion *ex =
992 oidmap_get(&configured_exclusions, oid);
993
994 if (!ex)
995 BUG("configured exclusion wasn't configured");
996 write_in_full(1, ex->pack_hash_hex, strlen(ex->pack_hash_hex));
997 write_in_full(1, " ", 1);
998 write_in_full(1, ex->uri, strlen(ex->uri));
999 write_in_full(1, "\n", 1);
1000 }
1001}
1002
9cea46cd
EW
1003static const char no_split_warning[] = N_(
1004"disabling bitmap writing, packs are split due to pack.packSizeLimit"
1005);
1006
d01fb92f 1007static void write_pack_file(void)
c323ac7d 1008{
ebe27b13 1009 uint32_t i = 0, j;
98a3beab 1010 struct hashfile *f;
6ed7f25e 1011 off_t offset;
ebe27b13 1012 uint32_t nr_remaining = nr_result;
f746bae8 1013 time_t last_mtime = 0;
1b4bb16b 1014 struct object_entry **write_order;
81a216a5 1015
bcd7954e 1016 if (progress > pack_to_stdout)
754dbc43 1017 progress_state = start_progress(_("Writing objects"), nr_result);
b32fa95f 1018 ALLOC_ARRAY(written_list, to_pack.nr_objects);
1b4bb16b 1019 write_order = compute_write_order();
183bdb2c 1020
ebe27b13 1021 do {
188960b4 1022 struct object_id oid;
7ba502c4 1023 char *pack_tmp_name = NULL;
aa7e44bf 1024
cdf9db3c 1025 if (pack_to_stdout)
98a3beab 1026 f = hashfd_throughput(1, "<stdout>", progress_state);
cdf9db3c
JH
1027 else
1028 f = create_tmp_packfile(&pack_tmp_name);
ebe27b13 1029
c0ad4657 1030 offset = write_pack_header(f, nr_remaining);
6b8fda2d
VM
1031
1032 if (reuse_packfile) {
6b8fda2d 1033 assert(pack_to_stdout);
bb514de3
JK
1034 write_reused_pack(f);
1035 offset = hashfile_total(f);
6b8fda2d
VM
1036 }
1037
ebe27b13 1038 nr_written = 0;
2834bc27 1039 for (; i < to_pack.nr_objects; i++) {
1b4bb16b 1040 struct object_entry *e = write_order[i];
cddec4f8 1041 if (write_one(f, e, &offset) == WRITE_ONE_BREAK)
720c9f7b
NP
1042 break;
1043 display_progress(progress_state, written);
1044 }
c553ca25 1045
ebe27b13
DH
1046 /*
1047 * Did we write the wrong # entries in the header?
1048 * If so, rewrite it like in fast-import
1049 */
54352bb2 1050 if (pack_to_stdout) {
cfe83216 1051 finalize_hashfile(f, oid.hash, CSUM_HASH_IN_STREAM | CSUM_CLOSE);
54352bb2 1052 } else if (nr_written == nr_remaining) {
cfe83216 1053 finalize_hashfile(f, oid.hash, CSUM_HASH_IN_STREAM | CSUM_FSYNC | CSUM_CLOSE);
ebe27b13 1054 } else {
f2af9f5e 1055 int fd = finalize_hashfile(f, oid.hash, 0);
188960b4 1056 fixup_pack_header_footer(fd, oid.hash, pack_tmp_name,
1057 nr_written, oid.hash, offset);
7ba502c4 1058 close(fd);
9cea46cd 1059 if (write_bitmap_index) {
25575015
JK
1060 if (write_bitmap_index != WRITE_BITMAP_QUIET)
1061 warning(_(no_split_warning));
9cea46cd
EW
1062 write_bitmap_index = 0;
1063 }
ebe27b13
DH
1064 }
1065
1066 if (!pack_to_stdout) {
f746bae8 1067 struct stat st;
58892711 1068 struct strbuf tmpname = STRBUF_INIT;
d01fb92f 1069
f746bae8
NP
1070 /*
1071 * Packs are runtime accessed in their mtime
1072 * order since newer packs are more likely to contain
1073 * younger objects. So if we are creating multiple
1074 * packs then we should modify the mtime of later ones
1075 * to preserve this property.
1076 */
0e990530 1077 if (stat(pack_tmp_name, &st) < 0) {
f616db6a 1078 warning_errno(_("failed to stat %s"), pack_tmp_name);
f746bae8
NP
1079 } else if (!last_mtime) {
1080 last_mtime = st.st_mtime;
1081 } else {
1082 struct utimbuf utb;
1083 utb.actime = st.st_atime;
1084 utb.modtime = --last_mtime;
0e990530 1085 if (utime(pack_tmp_name, &utb) < 0)
f616db6a 1086 warning_errno(_("failed utime() on %s"), pack_tmp_name);
f746bae8
NP
1087 }
1088
58892711 1089 strbuf_addf(&tmpname, "%s-", base_name);
7cc8f971
VM
1090
1091 if (write_bitmap_index) {
188960b4 1092 bitmap_writer_set_checksum(oid.hash);
06af3bba
NTND
1093 bitmap_writer_build_type_index(
1094 &to_pack, written_list, nr_written);
7cc8f971
VM
1095 }
1096
58892711 1097 finish_tmp_packfile(&tmpname, pack_tmp_name,
0e990530 1098 written_list, nr_written,
188960b4 1099 &pack_idx_opts, oid.hash);
7cc8f971
VM
1100
1101 if (write_bitmap_index) {
188960b4 1102 strbuf_addf(&tmpname, "%s.bitmap", oid_to_hex(&oid));
7cc8f971
VM
1103
1104 stop_progress(&progress_state);
1105
1106 bitmap_writer_show_progress(progress);
1107 bitmap_writer_reuse_bitmaps(&to_pack);
1108 bitmap_writer_select_commits(indexed_commits, indexed_commits_nr, -1);
1109 bitmap_writer_build(&to_pack);
ae4f07fb 1110 bitmap_writer_finish(written_list, nr_written,
58892711 1111 tmpname.buf, write_bitmap_options);
7cc8f971
VM
1112 write_bitmap_index = 0;
1113 }
1114
58892711 1115 strbuf_release(&tmpname);
7ba502c4 1116 free(pack_tmp_name);
188960b4 1117 puts(oid_to_hex(&oid));
ebe27b13
DH
1118 }
1119
1120 /* mark written objects as written to previous pack */
1121 for (j = 0; j < nr_written; j++) {
79814f42 1122 written_list[j]->offset = (off_t)-1;
ebe27b13
DH
1123 }
1124 nr_remaining -= nr_written;
2834bc27 1125 } while (nr_remaining && i < to_pack.nr_objects);
ebe27b13
DH
1126
1127 free(written_list);
1b4bb16b 1128 free(write_order);
4d4fcc54 1129 stop_progress(&progress_state);
67c08ce1 1130 if (written != nr_result)
f616db6a
NTND
1131 die(_("wrote %"PRIu32" objects while expecting %"PRIu32),
1132 written, nr_result);
9ed87902
JT
1133 trace2_data_intmax("pack-objects", the_repository,
1134 "write_pack_file/wrote", nr_result);
c323ac7d
LT
1135}
1136
a74db82e
JH
1137static int no_try_delta(const char *path)
1138{
2aef63d3 1139 static struct attr_check *check;
a74db82e 1140
2aef63d3
JH
1141 if (!check)
1142 check = attr_check_initl("delta", NULL);
f8adbec9 1143 git_check_attr(the_repository->index, path, check);
2aef63d3 1144 if (ATTR_FALSE(check->items[0].value))
a74db82e
JH
1145 return 1;
1146 return 0;
1147}
1148
ce2bc424
JK
1149/*
1150 * When adding an object, check whether we have already added it
1151 * to our packing list. If so, we can skip. However, if we are
1152 * being asked to excludei t, but the previous mention was to include
1153 * it, make sure to adjust its flags and tweak our numbers accordingly.
1154 *
1155 * As an optimization, we pass out the index position where we would have
1156 * found the item, since that saves us from having to look it up again a
1157 * few lines later when we want to add the new entry.
1158 */
188960b4 1159static int have_duplicate_entry(const struct object_id *oid,
3a37876b 1160 int exclude)
c323ac7d 1161{
c323ac7d 1162 struct object_entry *entry;
29b734e4 1163
92fb0db9
JK
1164 if (reuse_packfile_bitmap &&
1165 bitmap_walk_contains(bitmap_git, reuse_packfile_bitmap, oid))
1166 return 1;
1167
3a37876b 1168 entry = packlist_find(&to_pack, oid);
ce2bc424 1169 if (!entry)
29b734e4 1170 return 0;
ce2bc424
JK
1171
1172 if (exclude) {
1173 if (!entry->preferred_base)
1174 nr_result--;
1175 entry->preferred_base = 1;
29b734e4 1176 }
c323ac7d 1177
ce2bc424
JK
1178 return 1;
1179}
1180
702d1b95
KS
1181static int want_found_object(int exclude, struct packed_git *p)
1182{
1183 if (exclude)
1184 return 1;
1185 if (incremental)
1186 return 0;
1187
1188 /*
1189 * When asked to do --local (do not include an object that appears in a
1190 * pack we borrow from elsewhere) or --honor-pack-keep (do not include
1191 * an object that appears in a pack marked with .keep), finding a pack
1192 * that matches the criteria is sufficient for us to decide to omit it.
1193 * However, even if this pack does not satisfy the criteria, we need to
1194 * make sure no copy of this object appears in _any_ pack that makes us
1195 * to omit the object, so we need to check all the packs.
1196 *
1197 * We can however first check whether these options can possible matter;
1198 * if they do not matter we know we want the object in generated pack.
1199 * Otherwise, we signal "-1" at the end to tell the caller that we do
1200 * not know either way, and it needs to check more packs.
1201 */
ed7e5fc3
NTND
1202 if (!ignore_packed_keep_on_disk &&
1203 !ignore_packed_keep_in_core &&
702d1b95
KS
1204 (!local || !have_non_local_packs))
1205 return 1;
1206
1207 if (local && !p->pack_local)
1208 return 0;
ed7e5fc3
NTND
1209 if (p->pack_local &&
1210 ((ignore_packed_keep_on_disk && p->pack_keep) ||
1211 (ignore_packed_keep_in_core && p->pack_keep_in_core)))
702d1b95
KS
1212 return 0;
1213
1214 /* we don't know yet; keep looking for more packs */
1215 return -1;
1216}
1217
ce2bc424
JK
1218/*
1219 * Check whether we want the object in the pack (e.g., we do not want
1220 * objects found in non-local stores if the "--local" option was used).
1221 *
702d1b95
KS
1222 * If the caller already knows an existing pack it wants to take the object
1223 * from, that is passed in *found_pack and *found_offset; otherwise this
1224 * function finds if there is any pack that has the object and returns the pack
1225 * and its offset in these variables.
ce2bc424 1226 */
188960b4 1227static int want_object_in_pack(const struct object_id *oid,
ce2bc424
JK
1228 int exclude,
1229 struct packed_git **found_pack,
1230 off_t *found_offset)
1231{
702d1b95 1232 int want;
8865859d 1233 struct list_head *pos;
6a22d521 1234 struct multi_pack_index *m;
ce2bc424 1235
6862ebbf 1236 if (!exclude && local && has_loose_object_nonlocal(oid))
daae0625
BC
1237 return 0;
1238
702d1b95
KS
1239 /*
1240 * If we already know the pack object lives in, start checks from that
1241 * pack - in the usual case when neither --local was given nor .keep files
1242 * are present we will determine the answer right now.
1243 */
1244 if (*found_pack) {
1245 want = want_found_object(exclude, *found_pack);
1246 if (want != -1)
1247 return want;
1248 }
6a22d521
DS
1249
1250 for (m = get_multi_pack_index(the_repository); m; m = m->next) {
1251 struct pack_entry e;
64404a24 1252 if (fill_midx_entry(the_repository, oid, &e, m)) {
6a22d521
DS
1253 struct packed_git *p = e.p;
1254 off_t offset;
1255
1256 if (p == *found_pack)
1257 offset = *found_offset;
1258 else
1259 offset = find_pack_entry_one(oid->hash, p);
1260
1261 if (offset) {
1262 if (!*found_pack) {
1263 if (!is_pack_valid(p))
1264 continue;
1265 *found_offset = offset;
1266 *found_pack = p;
1267 }
1268 want = want_found_object(exclude, p);
1269 if (want != -1)
1270 return want;
1271 }
1272 }
1273 }
1274
a80d72db 1275 list_for_each(pos, get_packed_git_mru(the_repository)) {
ec2dd32c 1276 struct packed_git *p = list_entry(pos, struct packed_git, mru);
702d1b95
KS
1277 off_t offset;
1278
1279 if (p == *found_pack)
1280 offset = *found_offset;
1281 else
188960b4 1282 offset = find_pack_entry_one(oid->hash, p);
702d1b95 1283
5c49c116 1284 if (offset) {
ce2bc424 1285 if (!*found_pack) {
319b678a 1286 if (!is_pack_valid(p))
4c080182 1287 continue;
ce2bc424
JK
1288 *found_offset = offset;
1289 *found_pack = p;
64560374 1290 }
702d1b95 1291 want = want_found_object(exclude, p);
e6e24c94 1292 if (!exclude && want > 0)
a80d72db
SB
1293 list_move(&p->mru,
1294 get_packed_git_mru(the_repository));
702d1b95
KS
1295 if (want != -1)
1296 return want;
64560374
LT
1297 }
1298 }
eb019375 1299
dd4b732d
JT
1300 if (uri_protocols.nr) {
1301 struct configured_exclusion *ex =
1302 oidmap_get(&configured_exclusions, oid);
1303 int i;
1304 const char *p;
1305
1306 if (ex) {
1307 for (i = 0; i < uri_protocols.nr; i++) {
1308 if (skip_prefix(ex->uri,
1309 uri_protocols.items[i].string,
1310 &p) &&
1311 *p == ':') {
1312 oidset_insert(&excluded_by_config, oid);
1313 return 0;
1314 }
1315 }
1316 }
1317 }
1318
ce2bc424
JK
1319 return 1;
1320}
1321
188960b4 1322static void create_object_entry(const struct object_id *oid,
ce2bc424
JK
1323 enum object_type type,
1324 uint32_t hash,
1325 int exclude,
1326 int no_try_delta,
ce2bc424
JK
1327 struct packed_git *found_pack,
1328 off_t found_offset)
1329{
1330 struct object_entry *entry;
29b734e4 1331
3a37876b 1332 entry = packlist_alloc(&to_pack, oid);
27225f2e 1333 entry->hash = hash;
fd9b1bae 1334 oe_set_type(entry, type);
29b734e4
NP
1335 if (exclude)
1336 entry->preferred_base = 1;
81a216a5
NP
1337 else
1338 nr_result++;
29b734e4 1339 if (found_pack) {
43fa44fa 1340 oe_set_in_pack(&to_pack, entry, found_pack);
29b734e4
NP
1341 entry->in_pack_offset = found_offset;
1342 }
7a979d99 1343
ce2bc424
JK
1344 entry->no_try_delta = no_try_delta;
1345}
29b734e4 1346
373c67da
JK
1347static const char no_closure_warning[] = N_(
1348"disabling bitmap writing, as some objects are not being packed"
1349);
1350
188960b4 1351static int add_object_entry(const struct object_id *oid, enum object_type type,
ce2bc424
JK
1352 const char *name, int exclude)
1353{
702d1b95
KS
1354 struct packed_git *found_pack = NULL;
1355 off_t found_offset = 0;
7a979d99 1356
5af05043
NTND
1357 display_progress(progress_state, ++nr_seen);
1358
3a37876b 1359 if (have_duplicate_entry(oid, exclude))
ce2bc424 1360 return 0;
a74db82e 1361
188960b4 1362 if (!want_object_in_pack(oid, exclude, &found_pack, &found_offset)) {
373c67da
JK
1363 /* The pack is missing an object, so it will not have closure */
1364 if (write_bitmap_index) {
25575015
JK
1365 if (write_bitmap_index != WRITE_BITMAP_QUIET)
1366 warning(_(no_closure_warning));
373c67da
JK
1367 write_bitmap_index = 0;
1368 }
ce2bc424 1369 return 0;
373c67da 1370 }
29b734e4 1371
188960b4 1372 create_object_entry(oid, type, pack_name_hash(name),
ce2bc424 1373 exclude, name && no_try_delta(name),
3a37876b 1374 found_pack, found_offset);
29b734e4 1375 return 1;
c323ac7d
LT
1376}
1377
20664967 1378static int add_object_entry_from_bitmap(const struct object_id *oid,
6b8fda2d
VM
1379 enum object_type type,
1380 int flags, uint32_t name_hash,
1381 struct packed_git *pack, off_t offset)
1382{
5af05043
NTND
1383 display_progress(progress_state, ++nr_seen);
1384
3a37876b 1385 if (have_duplicate_entry(oid, 0))
6b8fda2d
VM
1386 return 0;
1387
188960b4 1388 if (!want_object_in_pack(oid, 0, &pack, &offset))
702d1b95
KS
1389 return 0;
1390
3a37876b 1391 create_object_entry(oid, type, name_hash, 0, 0, pack, offset);
29b734e4 1392 return 1;
c323ac7d
LT
1393}
1394
5379a5c5 1395struct pbase_tree_cache {
188960b4 1396 struct object_id oid;
5379a5c5
JH
1397 int ref;
1398 int temporary;
1399 void *tree_data;
1400 unsigned long tree_size;
1401};
1402
1403static struct pbase_tree_cache *(pbase_tree_cache[256]);
188960b4 1404static int pbase_tree_cache_ix(const struct object_id *oid)
5379a5c5 1405{
188960b4 1406 return oid->hash[0] % ARRAY_SIZE(pbase_tree_cache);
5379a5c5
JH
1407}
1408static int pbase_tree_cache_ix_incr(int ix)
1409{
1410 return (ix+1) % ARRAY_SIZE(pbase_tree_cache);
1411}
1412
1413static struct pbase_tree {
1414 struct pbase_tree *next;
1415 /* This is a phony "cache" entry; we are not
01689909 1416 * going to evict it or find it through _get()
5379a5c5
JH
1417 * mechanism -- this is for the toplevel node that
1418 * would almost always change with any commit.
1419 */
1420 struct pbase_tree_cache pcache;
1421} *pbase_tree;
1422
188960b4 1423static struct pbase_tree_cache *pbase_tree_get(const struct object_id *oid)
5379a5c5
JH
1424{
1425 struct pbase_tree_cache *ent, *nent;
1426 void *data;
1427 unsigned long size;
21666f1a 1428 enum object_type type;
5379a5c5 1429 int neigh;
188960b4 1430 int my_ix = pbase_tree_cache_ix(oid);
5379a5c5
JH
1431 int available_ix = -1;
1432
1433 /* pbase-tree-cache acts as a limited hashtable.
1434 * your object will be found at your index or within a few
1435 * slots after that slot if it is cached.
1436 */
1437 for (neigh = 0; neigh < 8; neigh++) {
1438 ent = pbase_tree_cache[my_ix];
4a7e27e9 1439 if (ent && oideq(&ent->oid, oid)) {
5379a5c5
JH
1440 ent->ref++;
1441 return ent;
1442 }
1443 else if (((available_ix < 0) && (!ent || !ent->ref)) ||
1444 ((0 <= available_ix) &&
1445 (!ent && pbase_tree_cache[available_ix])))
1446 available_ix = my_ix;
1447 if (!ent)
1448 break;
1449 my_ix = pbase_tree_cache_ix_incr(my_ix);
1450 }
1451
1452 /* Did not find one. Either we got a bogus request or
1453 * we need to read and perhaps cache.
1454 */
b4f5aca4 1455 data = read_object_file(oid, &type, &size);
5379a5c5
JH
1456 if (!data)
1457 return NULL;
21666f1a 1458 if (type != OBJ_TREE) {
5379a5c5
JH
1459 free(data);
1460 return NULL;
1461 }
1462
1463 /* We need to either cache or return a throwaway copy */
1464
1465 if (available_ix < 0)
1466 ent = NULL;
1467 else {
1468 ent = pbase_tree_cache[available_ix];
1469 my_ix = available_ix;
1470 }
1471
1472 if (!ent) {
1473 nent = xmalloc(sizeof(*nent));
1474 nent->temporary = (available_ix < 0);
1475 }
1476 else {
1477 /* evict and reuse */
1478 free(ent->tree_data);
1479 nent = ent;
1480 }
188960b4 1481 oidcpy(&nent->oid, oid);
5379a5c5
JH
1482 nent->tree_data = data;
1483 nent->tree_size = size;
1484 nent->ref = 1;
1485 if (!nent->temporary)
1486 pbase_tree_cache[my_ix] = nent;
1487 return nent;
1488}
1489
1490static void pbase_tree_put(struct pbase_tree_cache *cache)
1491{
1492 if (!cache->temporary) {
1493 cache->ref--;
1494 return;
1495 }
1496 free(cache->tree_data);
1497 free(cache);
1498}
1499
1500static int name_cmp_len(const char *name)
1501{
1502 int i;
1503 for (i = 0; name[i] && name[i] != '\n' && name[i] != '/'; i++)
1504 ;
1505 return i;
1506}
1507
1508static void add_pbase_object(struct tree_desc *tree,
5379a5c5 1509 const char *name,
ce0bd642
LT
1510 int cmplen,
1511 const char *fullname)
3f9ac8d2 1512{
4c068a98 1513 struct name_entry entry;
8a5a8d6c 1514 int cmp;
4c068a98
LT
1515
1516 while (tree_entry(tree,&entry)) {
1211be6b
LT
1517 if (S_ISGITLINK(entry.mode))
1518 continue;
0de16337 1519 cmp = tree_entry_len(&entry) != cmplen ? 1 :
8a5a8d6c
NP
1520 memcmp(name, entry.path, cmplen);
1521 if (cmp > 0)
7a979d99 1522 continue;
8a5a8d6c
NP
1523 if (cmp < 0)
1524 return;
5379a5c5 1525 if (name[cmplen] != '/') {
ea82b2a0 1526 add_object_entry(&entry.oid,
4d1012c3 1527 object_type(entry.mode),
bc32fed5 1528 fullname, 1);
5379a5c5
JH
1529 return;
1530 }
8a5a8d6c 1531 if (S_ISDIR(entry.mode)) {
7a979d99 1532 struct tree_desc sub;
5379a5c5
JH
1533 struct pbase_tree_cache *tree;
1534 const char *down = name+cmplen+1;
1535 int downlen = name_cmp_len(down);
1536
ea82b2a0 1537 tree = pbase_tree_get(&entry.oid);
5379a5c5
JH
1538 if (!tree)
1539 return;
6fda5e51 1540 init_tree_desc(&sub, tree->tree_data, tree->tree_size);
5379a5c5 1541
ce0bd642 1542 add_pbase_object(&sub, down, downlen, fullname);
5379a5c5
JH
1543 pbase_tree_put(tree);
1544 }
1545 }
1546}
1d6b38cc 1547
5379a5c5
JH
1548static unsigned *done_pbase_paths;
1549static int done_pbase_paths_num;
1550static int done_pbase_paths_alloc;
1551static int done_pbase_path_pos(unsigned hash)
1552{
1553 int lo = 0;
1554 int hi = done_pbase_paths_num;
1555 while (lo < hi) {
19716b21 1556 int mi = lo + (hi - lo) / 2;
5379a5c5
JH
1557 if (done_pbase_paths[mi] == hash)
1558 return mi;
1559 if (done_pbase_paths[mi] < hash)
1560 hi = mi;
1561 else
1562 lo = mi + 1;
1563 }
1564 return -lo-1;
1565}
1566
1567static int check_pbase_path(unsigned hash)
1568{
c7b07805 1569 int pos = done_pbase_path_pos(hash);
5379a5c5
JH
1570 if (0 <= pos)
1571 return 1;
1572 pos = -pos - 1;
25e19407
DD
1573 ALLOC_GROW(done_pbase_paths,
1574 done_pbase_paths_num + 1,
1575 done_pbase_paths_alloc);
5379a5c5
JH
1576 done_pbase_paths_num++;
1577 if (pos < done_pbase_paths_num)
f331ab9d
RS
1578 MOVE_ARRAY(done_pbase_paths + pos + 1, done_pbase_paths + pos,
1579 done_pbase_paths_num - pos - 1);
5379a5c5
JH
1580 done_pbase_paths[pos] = hash;
1581 return 0;
1582}
1583
bc32fed5 1584static void add_preferred_base_object(const char *name)
5379a5c5
JH
1585{
1586 struct pbase_tree *it;
8a5a8d6c 1587 int cmplen;
68fb36eb 1588 unsigned hash = pack_name_hash(name);
5379a5c5 1589
8a5a8d6c 1590 if (!num_preferred_base || check_pbase_path(hash))
5379a5c5
JH
1591 return;
1592
8a5a8d6c 1593 cmplen = name_cmp_len(name);
5379a5c5
JH
1594 for (it = pbase_tree; it; it = it->next) {
1595 if (cmplen == 0) {
188960b4 1596 add_object_entry(&it->pcache.oid, OBJ_TREE, NULL, 1);
5379a5c5
JH
1597 }
1598 else {
1599 struct tree_desc tree;
6fda5e51 1600 init_tree_desc(&tree, it->pcache.tree_data, it->pcache.tree_size);
ce0bd642 1601 add_pbase_object(&tree, name, cmplen, name);
7a979d99 1602 }
3f9ac8d2 1603 }
3f9ac8d2
JH
1604}
1605
188960b4 1606static void add_preferred_base(struct object_id *oid)
3f9ac8d2 1607{
5379a5c5
JH
1608 struct pbase_tree *it;
1609 void *data;
1610 unsigned long size;
188960b4 1611 struct object_id tree_oid;
1d6b38cc 1612
8d1d8f83
JH
1613 if (window <= num_preferred_base++)
1614 return;
1615
d3b4705a
NTND
1616 data = read_object_with_reference(the_repository, oid,
1617 tree_type, &size, &tree_oid);
5379a5c5 1618 if (!data)
7a979d99 1619 return;
5379a5c5
JH
1620
1621 for (it = pbase_tree; it; it = it->next) {
4a7e27e9 1622 if (oideq(&it->pcache.oid, &tree_oid)) {
5379a5c5
JH
1623 free(data);
1624 return;
1625 }
1626 }
1627
1628 it = xcalloc(1, sizeof(*it));
1629 it->next = pbase_tree;
1630 pbase_tree = it;
1631
188960b4 1632 oidcpy(&it->pcache.oid, &tree_oid);
5379a5c5
JH
1633 it->pcache.tree_data = data;
1634 it->pcache.tree_size = size;
3f9ac8d2
JH
1635}
1636
0ef95f72
NP
1637static void cleanup_preferred_base(void)
1638{
1639 struct pbase_tree *it;
1640 unsigned i;
1641
1642 it = pbase_tree;
1643 pbase_tree = NULL;
1644 while (it) {
095b3b2c
BW
1645 struct pbase_tree *tmp = it;
1646 it = tmp->next;
1647 free(tmp->pcache.tree_data);
1648 free(tmp);
0ef95f72
NP
1649 }
1650
1651 for (i = 0; i < ARRAY_SIZE(pbase_tree_cache); i++) {
1652 if (!pbase_tree_cache[i])
1653 continue;
1654 free(pbase_tree_cache[i]->tree_data);
6a83d902 1655 FREE_AND_NULL(pbase_tree_cache[i]);
0ef95f72
NP
1656 }
1657
6a83d902 1658 FREE_AND_NULL(done_pbase_paths);
0ef95f72
NP
1659 done_pbase_paths_num = done_pbase_paths_alloc = 0;
1660}
1661
2fa233a5
JK
1662/*
1663 * Return 1 iff the object specified by "delta" can be sent
1664 * literally as a delta against the base in "base_sha1". If
1665 * so, then *base_out will point to the entry in our packing
1666 * list, or NULL if we must use the external-base list.
1667 *
1668 * Depth value does not matter - find_deltas() will
1669 * never consider reused delta as the base object to
1670 * deltify other objects against, in order to avoid
1671 * circular deltas.
1672 */
3f83fd5e 1673static int can_reuse_delta(const struct object_id *base_oid,
2fa233a5
JK
1674 struct object_entry *delta,
1675 struct object_entry **base_out)
1676{
1677 struct object_entry *base;
3df28cae 1678
2fa233a5
JK
1679 /*
1680 * First see if we're already sending the base (or it's explicitly in
1681 * our "excluded" list).
1682 */
3f83fd5e 1683 base = packlist_find(&to_pack, base_oid);
2fa233a5
JK
1684 if (base) {
1685 if (!in_same_island(&delta->idx.oid, &base->idx.oid))
1686 return 0;
1687 *base_out = base;
1688 return 1;
1689 }
1690
1691 /*
1692 * Otherwise, reachability bitmaps may tell us if the receiver has it,
1693 * even if it was buried too deep in history to make it into the
1694 * packing list.
1695 */
3f83fd5e 1696 if (thin && bitmap_has_oid_in_uninteresting(bitmap_git, base_oid)) {
2fa233a5 1697 if (use_delta_islands) {
3f83fd5e 1698 if (!in_same_island(&delta->idx.oid, base_oid))
2fa233a5
JK
1699 return 0;
1700 }
1701 *base_out = NULL;
1702 return 1;
1703 }
1704
1705 return 0;
1706}
1707
e00549aa
JT
1708static void prefetch_to_pack(uint32_t object_index_start) {
1709 struct oid_array to_fetch = OID_ARRAY_INIT;
1710 uint32_t i;
1711
1712 for (i = object_index_start; i < to_pack.nr_objects; i++) {
1713 struct object_entry *entry = to_pack.objects + i;
1714
1715 if (!oid_object_info_extended(the_repository,
1716 &entry->idx.oid,
1717 NULL,
1718 OBJECT_INFO_FOR_PREFETCH))
1719 continue;
1720 oid_array_append(&to_fetch, &entry->idx.oid);
1721 }
1722 promisor_remote_get_direct(the_repository,
1723 to_fetch.oid, to_fetch.nr);
1724 oid_array_clear(&to_fetch);
1725}
1726
1727static void check_object(struct object_entry *entry, uint32_t object_index)
c323ac7d 1728{
ac77d0c3 1729 unsigned long canonical_size;
8d5cf957
JT
1730 enum object_type type;
1731 struct object_info oi = {.typep = &type, .sizep = &canonical_size};
ac77d0c3 1732
43fa44fa
NTND
1733 if (IN_PACK(entry)) {
1734 struct packed_git *p = IN_PACK(entry);
03e79c88 1735 struct pack_window *w_curs = NULL;
3f83fd5e
JK
1736 int have_base = 0;
1737 struct object_id base_ref;
5c49c116
NP
1738 struct object_entry *base_entry;
1739 unsigned long used, used_0;
ef49a7a0 1740 unsigned long avail;
5c49c116
NP
1741 off_t ofs;
1742 unsigned char *buf, c;
fd9b1bae 1743 enum object_type type;
27a7d067 1744 unsigned long in_pack_size;
780e6e73 1745
6777a59f 1746 buf = use_pack(p, &w_curs, entry->in_pack_offset, &avail);
ab7cd7bb 1747
5c49c116 1748 /*
fa736f72
NP
1749 * We want in_pack_type even if we do not reuse delta
1750 * since non-delta representations could still be reused.
ab7cd7bb 1751 */
09ded04b 1752 used = unpack_object_header_buffer(buf, avail,
fd9b1bae 1753 &type,
27a7d067 1754 &in_pack_size);
03d66015
NP
1755 if (used == 0)
1756 goto give_up;
ab7cd7bb 1757
fd9b1bae
NTND
1758 if (type < 0)
1759 BUG("invalid type %d", type);
1760 entry->in_pack_type = type;
1761
5c49c116
NP
1762 /*
1763 * Determine if this is a delta and if so whether we can
1764 * reuse it or not. Otherwise let's find out as cheaply as
1765 * possible what the actual type and size for this object is.
3f9ac8d2 1766 */
5c49c116
NP
1767 switch (entry->in_pack_type) {
1768 default:
1769 /* Not a delta hence we've already got all we need. */
fd9b1bae 1770 oe_set_type(entry, entry->in_pack_type);
ac77d0c3 1771 SET_SIZE(entry, in_pack_size);
5c49c116 1772 entry->in_pack_header_size = used;
fd9b1bae 1773 if (oe_type(entry) < OBJ_COMMIT || oe_type(entry) > OBJ_BLOB)
03d66015 1774 goto give_up;
5c49c116
NP
1775 unuse_pack(&w_curs);
1776 return;
1777 case OBJ_REF_DELTA:
3f83fd5e
JK
1778 if (reuse_delta && !entry->preferred_base) {
1779 oidread(&base_ref,
1780 use_pack(p, &w_curs,
1781 entry->in_pack_offset + used,
1782 NULL));
1783 have_base = 1;
1784 }
41179100 1785 entry->in_pack_header_size = used + the_hash_algo->rawsz;
5c49c116
NP
1786 break;
1787 case OBJ_OFS_DELTA:
1788 buf = use_pack(p, &w_curs,
1789 entry->in_pack_offset + used, NULL);
1790 used_0 = 0;
1791 c = buf[used_0++];
1792 ofs = c & 127;
1793 while (c & 128) {
1794 ofs += 1;
03d66015 1795 if (!ofs || MSB(ofs, 7)) {
f616db6a 1796 error(_("delta base offset overflow in pack for %s"),
e6a492b7 1797 oid_to_hex(&entry->idx.oid));
03d66015
NP
1798 goto give_up;
1799 }
5c49c116
NP
1800 c = buf[used_0++];
1801 ofs = (ofs << 7) + (c & 127);
780e6e73 1802 }
5c49c116 1803 ofs = entry->in_pack_offset - ofs;
03d66015 1804 if (ofs <= 0 || ofs >= entry->in_pack_offset) {
f616db6a 1805 error(_("delta base offset out of bound for %s"),
e6a492b7 1806 oid_to_hex(&entry->idx.oid));
03d66015
NP
1807 goto give_up;
1808 }
a7de7130 1809 if (reuse_delta && !entry->preferred_base) {
3449f8c4
NP
1810 struct revindex_entry *revidx;
1811 revidx = find_pack_revindex(p, ofs);
08698b1e
NP
1812 if (!revidx)
1813 goto give_up;
3f83fd5e
JK
1814 if (!nth_packed_object_id(&base_ref, p, revidx->nr))
1815 have_base = 1;
3449f8c4 1816 }
5c49c116
NP
1817 entry->in_pack_header_size = used + used_0;
1818 break;
780e6e73 1819 }
780e6e73 1820
3f83fd5e
JK
1821 if (have_base &&
1822 can_reuse_delta(&base_ref, entry, &base_entry)) {
fd9b1bae 1823 oe_set_type(entry, entry->in_pack_type);
ac77d0c3 1824 SET_SIZE(entry, in_pack_size); /* delta size */
0aca34e8 1825 SET_DELTA_SIZE(entry, in_pack_size);
6a1e32d5
JK
1826
1827 if (base_entry) {
1828 SET_DELTA(entry, base_entry);
1829 entry->delta_sibling_idx = base_entry->delta_child_idx;
1830 SET_DELTA_CHILD(base_entry, entry);
1831 } else {
a93c141d 1832 SET_DELTA_EXT(entry, &base_ref);
6a1e32d5
JK
1833 }
1834
5c49c116
NP
1835 unuse_pack(&w_curs);
1836 return;
1837 }
ab7cd7bb 1838
fd9b1bae 1839 if (oe_type(entry)) {
27a7d067
NTND
1840 off_t delta_pos;
1841
5c49c116
NP
1842 /*
1843 * This must be a delta and we already know what the
1844 * final object type is. Let's extract the actual
1845 * object size from the delta header.
1846 */
27a7d067 1847 delta_pos = entry->in_pack_offset + entry->in_pack_header_size;
ac77d0c3
NTND
1848 canonical_size = get_size_from_delta(p, &w_curs, delta_pos);
1849 if (canonical_size == 0)
03d66015 1850 goto give_up;
ac77d0c3 1851 SET_SIZE(entry, canonical_size);
5c49c116 1852 unuse_pack(&w_curs);
3f9ac8d2
JH
1853 return;
1854 }
5c49c116
NP
1855
1856 /*
1857 * No choice but to fall back to the recursive delta walk
c93206b4 1858 * with oid_object_info() to find about the object type
5c49c116
NP
1859 * at this point...
1860 */
03d66015 1861 give_up:
5c49c116 1862 unuse_pack(&w_curs);
36e4d74a 1863 }
3f9ac8d2 1864
8d5cf957 1865 if (oid_object_info_extended(the_repository, &entry->idx.oid, &oi,
e00549aa
JT
1866 OBJECT_INFO_SKIP_FETCH_OBJECT | OBJECT_INFO_LOOKUP_REPLACE) < 0) {
1867 if (has_promisor_remote()) {
1868 prefetch_to_pack(object_index);
1869 if (oid_object_info_extended(the_repository, &entry->idx.oid, &oi,
1870 OBJECT_INFO_SKIP_FETCH_OBJECT | OBJECT_INFO_LOOKUP_REPLACE) < 0)
1871 type = -1;
1872 } else {
1873 type = -1;
1874 }
1875 }
8d5cf957 1876 oe_set_type(entry, type);
ac77d0c3
NTND
1877 if (entry->type_valid) {
1878 SET_SIZE(entry, canonical_size);
1879 } else {
1880 /*
1881 * Bad object type is checked in prepare_pack(). This is
1882 * to permit a missing preferred base object to be ignored
1883 * as a preferred base. Doing so can result in a larger
1884 * pack file, but the transfer will still take place.
1885 */
1886 }
3f9ac8d2
JH
1887}
1888
5c49c116
NP
1889static int pack_offset_sort(const void *_a, const void *_b)
1890{
1891 const struct object_entry *a = *(struct object_entry **)_a;
1892 const struct object_entry *b = *(struct object_entry **)_b;
43fa44fa
NTND
1893 const struct packed_git *a_in_pack = IN_PACK(a);
1894 const struct packed_git *b_in_pack = IN_PACK(b);
5c49c116
NP
1895
1896 /* avoid filesystem trashing with loose objects */
43fa44fa 1897 if (!a_in_pack && !b_in_pack)
e6a492b7 1898 return oidcmp(&a->idx.oid, &b->idx.oid);
5c49c116 1899
43fa44fa 1900 if (a_in_pack < b_in_pack)
5c49c116 1901 return -1;
43fa44fa 1902 if (a_in_pack > b_in_pack)
5c49c116
NP
1903 return 1;
1904 return a->in_pack_offset < b->in_pack_offset ? -1 :
1905 (a->in_pack_offset > b->in_pack_offset);
1906}
1907
4cf2143e
JK
1908/*
1909 * Drop an on-disk delta we were planning to reuse. Naively, this would
1910 * just involve blanking out the "delta" field, but we have to deal
1911 * with some extra book-keeping:
1912 *
1913 * 1. Removing ourselves from the delta_sibling linked list.
1914 *
1915 * 2. Updating our size/type to the non-delta representation. These were
1916 * either not recorded initially (size) or overwritten with the delta type
1917 * (type) when check_object() decided to reuse the delta.
7dbabbbe
JK
1918 *
1919 * 3. Resetting our delta depth, as we are now a base object.
4cf2143e
JK
1920 */
1921static void drop_reused_delta(struct object_entry *entry)
1922{
898eba5e 1923 unsigned *idx = &to_pack.objects[entry->delta_idx - 1].delta_child_idx;
4cf2143e 1924 struct object_info oi = OBJECT_INFO_INIT;
fd9b1bae 1925 enum object_type type;
ac77d0c3 1926 unsigned long size;
4cf2143e 1927
898eba5e
NTND
1928 while (*idx) {
1929 struct object_entry *oe = &to_pack.objects[*idx - 1];
4cf2143e 1930
898eba5e
NTND
1931 if (oe == entry)
1932 *idx = oe->delta_sibling_idx;
4cf2143e 1933 else
898eba5e 1934 idx = &oe->delta_sibling_idx;
4cf2143e 1935 }
898eba5e 1936 SET_DELTA(entry, NULL);
7dbabbbe 1937 entry->depth = 0;
4cf2143e 1938
ac77d0c3 1939 oi.sizep = &size;
fd9b1bae 1940 oi.typep = &type;
ad635e82 1941 if (packed_object_info(the_repository, IN_PACK(entry), entry->in_pack_offset, &oi) < 0) {
4cf2143e
JK
1942 /*
1943 * We failed to get the info from this pack for some reason;
c93206b4 1944 * fall back to oid_object_info, which may find another copy.
fd9b1bae 1945 * And if that fails, the error will be recorded in oe_type(entry)
4cf2143e
JK
1946 * and dealt with in prepare_pack().
1947 */
ad635e82
JH
1948 oe_set_type(entry,
1949 oid_object_info(the_repository, &entry->idx.oid, &size));
fd9b1bae
NTND
1950 } else {
1951 oe_set_type(entry, type);
4cf2143e 1952 }
ac77d0c3 1953 SET_SIZE(entry, size);
4cf2143e
JK
1954}
1955
1956/*
1957 * Follow the chain of deltas from this entry onward, throwing away any links
1958 * that cause us to hit a cycle (as determined by the DFS state flags in
1959 * the entries).
7dbabbbe
JK
1960 *
1961 * We also detect too-long reused chains that would violate our --depth
1962 * limit.
4cf2143e
JK
1963 */
1964static void break_delta_chains(struct object_entry *entry)
1965{
42b766d7
JK
1966 /*
1967 * The actual depth of each object we will write is stored as an int,
1968 * as it cannot exceed our int "depth" limit. But before we break
1969 * changes based no that limit, we may potentially go as deep as the
1970 * number of objects, which is elsewhere bounded to a uint32_t.
1971 */
1972 uint32_t total_depth;
1973 struct object_entry *cur, *next;
1974
1975 for (cur = entry, total_depth = 0;
1976 cur;
898eba5e 1977 cur = DELTA(cur), total_depth++) {
42b766d7
JK
1978 if (cur->dfs_state == DFS_DONE) {
1979 /*
1980 * We've already seen this object and know it isn't
1981 * part of a cycle. We do need to append its depth
1982 * to our count.
1983 */
1984 total_depth += cur->depth;
1985 break;
1986 }
4cf2143e 1987
4cf2143e 1988 /*
42b766d7
JK
1989 * We break cycles before looping, so an ACTIVE state (or any
1990 * other cruft which made its way into the state variable)
1991 * is a bug.
4cf2143e 1992 */
42b766d7 1993 if (cur->dfs_state != DFS_NONE)
033abf97 1994 BUG("confusing delta dfs state in first pass: %d",
42b766d7 1995 cur->dfs_state);
4cf2143e 1996
4cf2143e 1997 /*
42b766d7
JK
1998 * Now we know this is the first time we've seen the object. If
1999 * it's not a delta, we're done traversing, but we'll mark it
2000 * done to save time on future traversals.
4cf2143e 2001 */
898eba5e 2002 if (!DELTA(cur)) {
42b766d7
JK
2003 cur->dfs_state = DFS_DONE;
2004 break;
2005 }
4cf2143e 2006
4cf2143e 2007 /*
42b766d7
JK
2008 * Mark ourselves as active and see if the next step causes
2009 * us to cycle to another active object. It's important to do
2010 * this _before_ we loop, because it impacts where we make the
2011 * cut, and thus how our total_depth counter works.
2012 * E.g., We may see a partial loop like:
2013 *
2014 * A -> B -> C -> D -> B
2015 *
2016 * Cutting B->C breaks the cycle. But now the depth of A is
2017 * only 1, and our total_depth counter is at 3. The size of the
2018 * error is always one less than the size of the cycle we
2019 * broke. Commits C and D were "lost" from A's chain.
2020 *
2021 * If we instead cut D->B, then the depth of A is correct at 3.
2022 * We keep all commits in the chain that we examined.
4cf2143e 2023 */
42b766d7 2024 cur->dfs_state = DFS_ACTIVE;
898eba5e 2025 if (DELTA(cur)->dfs_state == DFS_ACTIVE) {
42b766d7
JK
2026 drop_reused_delta(cur);
2027 cur->dfs_state = DFS_DONE;
2028 break;
7dbabbbe 2029 }
42b766d7 2030 }
7dbabbbe 2031
42b766d7
JK
2032 /*
2033 * And now that we've gone all the way to the bottom of the chain, we
2034 * need to clear the active flags and set the depth fields as
2035 * appropriate. Unlike the loop above, which can quit when it drops a
2036 * delta, we need to keep going to look for more depth cuts. So we need
2037 * an extra "next" pointer to keep going after we reset cur->delta.
2038 */
2039 for (cur = entry; cur; cur = next) {
898eba5e 2040 next = DELTA(cur);
4cf2143e 2041
42b766d7
JK
2042 /*
2043 * We should have a chain of zero or more ACTIVE states down to
2044 * a final DONE. We can quit after the DONE, because either it
2045 * has no bases, or we've already handled them in a previous
2046 * call.
2047 */
2048 if (cur->dfs_state == DFS_DONE)
2049 break;
2050 else if (cur->dfs_state != DFS_ACTIVE)
033abf97 2051 BUG("confusing delta dfs state in second pass: %d",
42b766d7 2052 cur->dfs_state);
4cf2143e 2053
4cf2143e 2054 /*
42b766d7
JK
2055 * If the total_depth is more than depth, then we need to snip
2056 * the chain into two or more smaller chains that don't exceed
2057 * the maximum depth. Most of the resulting chains will contain
2058 * (depth + 1) entries (i.e., depth deltas plus one base), and
2059 * the last chain (i.e., the one containing entry) will contain
2060 * whatever entries are left over, namely
2061 * (total_depth % (depth + 1)) of them.
2062 *
2063 * Since we are iterating towards decreasing depth, we need to
2064 * decrement total_depth as we go, and we need to write to the
2065 * entry what its final depth will be after all of the
2066 * snipping. Since we're snipping into chains of length (depth
2067 * + 1) entries, the final depth of an entry will be its
2068 * original depth modulo (depth + 1). Any time we encounter an
2069 * entry whose final depth is supposed to be zero, we snip it
2070 * from its delta base, thereby making it so.
4cf2143e 2071 */
42b766d7
JK
2072 cur->depth = (total_depth--) % (depth + 1);
2073 if (!cur->depth)
2074 drop_reused_delta(cur);
2075
2076 cur->dfs_state = DFS_DONE;
4cf2143e
JK
2077 }
2078}
2079
c323ac7d
LT
2080static void get_object_details(void)
2081{
7cadf491 2082 uint32_t i;
5c49c116
NP
2083 struct object_entry **sorted_by_offset;
2084
5af05043
NTND
2085 if (progress)
2086 progress_state = start_progress(_("Counting objects"),
2087 to_pack.nr_objects);
2088
2834bc27
VM
2089 sorted_by_offset = xcalloc(to_pack.nr_objects, sizeof(struct object_entry *));
2090 for (i = 0; i < to_pack.nr_objects; i++)
2091 sorted_by_offset[i] = to_pack.objects + i;
9ed0d8d6 2092 QSORT(sorted_by_offset, to_pack.nr_objects, pack_offset_sort);
c323ac7d 2093
2834bc27 2094 for (i = 0; i < to_pack.nr_objects; i++) {
15366280 2095 struct object_entry *entry = sorted_by_offset[i];
e00549aa 2096 check_object(entry, i);
ac77d0c3
NTND
2097 if (entry->type_valid &&
2098 oe_size_greater_than(&to_pack, entry, big_file_threshold))
15366280 2099 entry->no_try_delta = 1;
5af05043 2100 display_progress(progress_state, i + 1);
15366280 2101 }
5af05043 2102 stop_progress(&progress_state);
3449f8c4 2103
4cf2143e
JK
2104 /*
2105 * This must happen in a second pass, since we rely on the delta
2106 * information for the whole list being completed.
2107 */
2108 for (i = 0; i < to_pack.nr_objects; i++)
2109 break_delta_chains(&to_pack.objects[i]);
2110
5c49c116 2111 free(sorted_by_offset);
c323ac7d
LT
2112}
2113
b904166c
NP
2114/*
2115 * We search for deltas in a list sorted by type, by filename hash, and then
2116 * by size, so that we see progressively smaller and smaller files.
2117 * That's because we prefer deltas to be from the bigger file
2118 * to the smaller -- deletes are potentially cheaper, but perhaps
2119 * more importantly, the bigger file is likely the more recent
2120 * one. The deepest deltas are therefore the oldest objects which are
2121 * less susceptible to be accessed often.
2122 */
9668cf59 2123static int type_size_sort(const void *_a, const void *_b)
c323ac7d 2124{
9668cf59
NP
2125 const struct object_entry *a = *(struct object_entry **)_a;
2126 const struct object_entry *b = *(struct object_entry **)_b;
33de80b1
SL
2127 const enum object_type a_type = oe_type(a);
2128 const enum object_type b_type = oe_type(b);
2129 const unsigned long a_size = SIZE(a);
2130 const unsigned long b_size = SIZE(b);
9668cf59 2131
fd9b1bae 2132 if (a_type > b_type)
27225f2e 2133 return -1;
fd9b1bae 2134 if (a_type < b_type)
27225f2e 2135 return 1;
b904166c 2136 if (a->hash > b->hash)
7a979d99 2137 return -1;
b904166c 2138 if (a->hash < b->hash)
7a979d99 2139 return 1;
b904166c 2140 if (a->preferred_base > b->preferred_base)
c323ac7d 2141 return -1;
b904166c
NP
2142 if (a->preferred_base < b->preferred_base)
2143 return 1;
28b8a730 2144 if (use_delta_islands) {
33de80b1 2145 const int island_cmp = island_delta_cmp(&a->idx.oid, &b->idx.oid);
28b8a730
JK
2146 if (island_cmp)
2147 return island_cmp;
2148 }
ac77d0c3 2149 if (a_size > b_size)
b904166c 2150 return -1;
ac77d0c3 2151 if (a_size < b_size)
c323ac7d 2152 return 1;
b904166c 2153 return a < b ? -1 : (a > b); /* newest first */
c323ac7d
LT
2154}
2155
2156struct unpacked {
2157 struct object_entry *entry;
2158 void *data;
f6c7081a 2159 struct delta_index *index;
5a235b5e 2160 unsigned depth;
c323ac7d
LT
2161};
2162
d250626c
NP
2163static int delta_cacheable(unsigned long src_size, unsigned long trg_size,
2164 unsigned long delta_size)
074b2eea
MK
2165{
2166 if (max_delta_cache_size && delta_cache_size + delta_size > max_delta_cache_size)
2167 return 0;
2168
e3dfddb3
MK
2169 if (delta_size < cache_max_small_delta_size)
2170 return 1;
2171
074b2eea
MK
2172 /* cache delta, if objects are large enough compared to delta size */
2173 if ((src_size >> 20) + (trg_size >> 21) > (delta_size >> 10))
2174 return 1;
2175
2176 return 0;
2177}
2178
ffbd51cc 2179/* Protect delta_cache_size */
44626dc7 2180static pthread_mutex_t cache_mutex;
3c701839
NP
2181#define cache_lock() pthread_mutex_lock(&cache_mutex)
2182#define cache_unlock() pthread_mutex_unlock(&cache_mutex)
2183
ffbd51cc
NTND
2184/*
2185 * Protect object list partitioning (e.g. struct thread_param) and
2186 * progress_state
2187 */
44626dc7 2188static pthread_mutex_t progress_mutex;
8ecce684
NP
2189#define progress_lock() pthread_mutex_lock(&progress_mutex)
2190#define progress_unlock() pthread_mutex_unlock(&progress_mutex)
2191
ffbd51cc
NTND
2192/*
2193 * Access to struct object_entry is unprotected since each thread owns
2194 * a portion of the main object list. Just don't access object entries
2195 * ahead in the list because they can be stolen and would need
2196 * progress_mutex for protection.
2197 */
8ecce684 2198
ac77d0c3
NTND
2199/*
2200 * Return the size of the object without doing any delta
2201 * reconstruction (so non-deltas are true object sizes, but deltas
2202 * return the size of the delta data).
2203 */
2204unsigned long oe_get_size_slow(struct packing_data *pack,
2205 const struct object_entry *e)
2206{
2207 struct packed_git *p;
2208 struct pack_window *w_curs;
2209 unsigned char *buf;
2210 enum object_type type;
2211 unsigned long used, avail, size;
2212
2213 if (e->type_ != OBJ_OFS_DELTA && e->type_ != OBJ_REF_DELTA) {
edb673cf 2214 packing_data_lock(&to_pack);
ad635e82 2215 if (oid_object_info(the_repository, &e->idx.oid, &size) < 0)
ac77d0c3
NTND
2216 die(_("unable to get size of %s"),
2217 oid_to_hex(&e->idx.oid));
edb673cf 2218 packing_data_unlock(&to_pack);
ac77d0c3
NTND
2219 return size;
2220 }
2221
2222 p = oe_in_pack(pack, e);
2223 if (!p)
2224 BUG("when e->type is a delta, it must belong to a pack");
2225
edb673cf 2226 packing_data_lock(&to_pack);
ac77d0c3
NTND
2227 w_curs = NULL;
2228 buf = use_pack(p, &w_curs, e->in_pack_offset, &avail);
2229 used = unpack_object_header_buffer(buf, avail, &type, &size);
2230 if (used == 0)
2231 die(_("unable to parse object header of %s"),
2232 oid_to_hex(&e->idx.oid));
2233
2234 unuse_pack(&w_curs);
edb673cf 2235 packing_data_unlock(&to_pack);
ac77d0c3
NTND
2236 return size;
2237}
2238
f6c7081a 2239static int try_delta(struct unpacked *trg, struct unpacked *src,
ef0316fc 2240 unsigned max_depth, unsigned long *mem_usage)
c323ac7d 2241{
f6c7081a
NP
2242 struct object_entry *trg_entry = trg->entry;
2243 struct object_entry *src_entry = src->entry;
560b25a8 2244 unsigned long trg_size, src_size, delta_size, sizediff, max_size, sz;
c83f032e 2245 unsigned ref_depth;
21666f1a 2246 enum object_type type;
c323ac7d
LT
2247 void *delta_buf;
2248
2249 /* Don't bother doing diffs between different types */
fd9b1bae 2250 if (oe_type(trg_entry) != oe_type(src_entry))
c323ac7d
LT
2251 return -1;
2252
51d1e83f 2253 /*
15f07e06
JK
2254 * We do not bother to try a delta that we discarded on an
2255 * earlier try, but only when reusing delta data. Note that
2256 * src_entry that is marked as the preferred_base should always
2257 * be considered, as even if we produce a suboptimal delta against
2258 * it, we will still save the transfer cost, as we already know
2259 * the other side has it and we won't send src_entry at all.
51d1e83f 2260 */
43fa44fa
NTND
2261 if (reuse_delta && IN_PACK(trg_entry) &&
2262 IN_PACK(trg_entry) == IN_PACK(src_entry) &&
15f07e06 2263 !src_entry->preferred_base &&
e9195b58
JH
2264 trg_entry->in_pack_type != OBJ_REF_DELTA &&
2265 trg_entry->in_pack_type != OBJ_OFS_DELTA)
51d1e83f
LT
2266 return 0;
2267
898b14ce 2268 /* Let's not bust the allowed depth. */
5a235b5e 2269 if (src->depth >= max_depth)
d116a45a 2270 return 0;
c323ac7d 2271
c3b06a69 2272 /* Now some size filtering heuristics. */
ac77d0c3 2273 trg_size = SIZE(trg_entry);
898eba5e 2274 if (!DELTA(trg_entry)) {
41179100 2275 max_size = trg_size/2 - the_hash_algo->rawsz;
c83f032e
NP
2276 ref_depth = 1;
2277 } else {
0aca34e8 2278 max_size = DELTA_SIZE(trg_entry);
5a235b5e 2279 ref_depth = trg->depth;
c83f032e 2280 }
720fe22d 2281 max_size = (uint64_t)max_size * (max_depth - src->depth) /
c83f032e 2282 (max_depth - ref_depth + 1);
c3b06a69
NP
2283 if (max_size == 0)
2284 return 0;
ac77d0c3 2285 src_size = SIZE(src_entry);
560b25a8 2286 sizediff = src_size < trg_size ? trg_size - src_size : 0;
27225f2e 2287 if (sizediff >= max_size)
f527cb8c 2288 return 0;
a1dab41a
BD
2289 if (trg_size < src_size / 32)
2290 return 0;
f6c7081a 2291
28b8a730
JK
2292 if (!in_same_island(&trg->entry->idx.oid, &src->entry->idx.oid))
2293 return 0;
2294
560b25a8
NP
2295 /* Load data if not already done */
2296 if (!trg->data) {
edb673cf 2297 packing_data_lock(&to_pack);
b4f5aca4 2298 trg->data = read_object_file(&trg_entry->idx.oid, &type, &sz);
edb673cf 2299 packing_data_unlock(&to_pack);
2e3404c3 2300 if (!trg->data)
f616db6a 2301 die(_("object %s cannot be read"),
e6a492b7 2302 oid_to_hex(&trg_entry->idx.oid));
560b25a8 2303 if (sz != trg_size)
ca473cef
TB
2304 die(_("object %s inconsistent object length (%"PRIuMAX" vs %"PRIuMAX")"),
2305 oid_to_hex(&trg_entry->idx.oid), (uintmax_t)sz,
2306 (uintmax_t)trg_size);
ef0316fc 2307 *mem_usage += sz;
560b25a8
NP
2308 }
2309 if (!src->data) {
edb673cf 2310 packing_data_lock(&to_pack);
b4f5aca4 2311 src->data = read_object_file(&src_entry->idx.oid, &type, &sz);
edb673cf 2312 packing_data_unlock(&to_pack);
71064a95
NP
2313 if (!src->data) {
2314 if (src_entry->preferred_base) {
2315 static int warned = 0;
2316 if (!warned++)
f616db6a 2317 warning(_("object %s cannot be read"),
e6a492b7 2318 oid_to_hex(&src_entry->idx.oid));
71064a95
NP
2319 /*
2320 * Those objects are not included in the
2321 * resulting pack. Be resilient and ignore
2322 * them if they can't be read, in case the
2323 * pack could be created nevertheless.
2324 */
2325 return 0;
2326 }
f616db6a 2327 die(_("object %s cannot be read"),
e6a492b7 2328 oid_to_hex(&src_entry->idx.oid));
71064a95 2329 }
560b25a8 2330 if (sz != src_size)
ca473cef
TB
2331 die(_("object %s inconsistent object length (%"PRIuMAX" vs %"PRIuMAX")"),
2332 oid_to_hex(&src_entry->idx.oid), (uintmax_t)sz,
2333 (uintmax_t)src_size);
ef0316fc 2334 *mem_usage += sz;
560b25a8
NP
2335 }
2336 if (!src->index) {
2337 src->index = create_delta_index(src->data, src_size);
a588d88a
MK
2338 if (!src->index) {
2339 static int warned = 0;
2340 if (!warned++)
f616db6a 2341 warning(_("suboptimal pack - out of memory"));
a588d88a
MK
2342 return 0;
2343 }
ef0316fc 2344 *mem_usage += sizeof_delta_index(src->index);
560b25a8
NP
2345 }
2346
2347 delta_buf = create_delta(src->index, trg->data, trg_size, &delta_size, max_size);
c323ac7d 2348 if (!delta_buf)
75c42d8c 2349 return 0;
f6c7081a 2350
898eba5e 2351 if (DELTA(trg_entry)) {
848d732c 2352 /* Prefer only shallower same-sized deltas. */
0aca34e8 2353 if (delta_size == DELTA_SIZE(trg_entry) &&
5a235b5e 2354 src->depth + 1 >= trg->depth) {
848d732c
BD
2355 free(delta_buf);
2356 return 0;
2357 }
074b2eea 2358 }
9e2d57a0 2359
3c701839
NP
2360 /*
2361 * Handle memory allocation outside of the cache
2362 * accounting lock. Compiler will optimize the strangeness
7eb151d6 2363 * away when NO_PTHREADS is defined.
3c701839 2364 */
8e0f7003 2365 free(trg_entry->delta_data);
3c701839 2366 cache_lock();
9e2d57a0 2367 if (trg_entry->delta_data) {
0aca34e8 2368 delta_cache_size -= DELTA_SIZE(trg_entry);
9e2d57a0
NP
2369 trg_entry->delta_data = NULL;
2370 }
d250626c 2371 if (delta_cacheable(src_size, trg_size, delta_size)) {
b7a28f78 2372 delta_cache_size += delta_size;
3c701839
NP
2373 cache_unlock();
2374 trg_entry->delta_data = xrealloc(delta_buf, delta_size);
2375 } else {
2376 cache_unlock();
074b2eea 2377 free(delta_buf);
3c701839
NP
2378 }
2379
898eba5e 2380 SET_DELTA(trg_entry, src_entry);
0aca34e8 2381 SET_DELTA_SIZE(trg_entry, delta_size);
b7a28f78
NP
2382 trg->depth = src->depth + 1;
2383
f6c7081a 2384 return 1;
c323ac7d
LT
2385}
2386
898b14ce 2387static unsigned int check_delta_limit(struct object_entry *me, unsigned int n)
b2504a0d 2388{
898eba5e 2389 struct object_entry *child = DELTA_CHILD(me);
898b14ce
NP
2390 unsigned int m = n;
2391 while (child) {
33de80b1 2392 const unsigned int c = check_delta_limit(child, n + 1);
898b14ce
NP
2393 if (m < c)
2394 m = c;
898eba5e 2395 child = DELTA_SIBLING(child);
898b14ce
NP
2396 }
2397 return m;
b2504a0d
NP
2398}
2399
75ad235c 2400static unsigned long free_unpacked(struct unpacked *n)
a97773ce 2401{
ef0316fc 2402 unsigned long freed_mem = sizeof_delta_index(n->index);
a97773ce
BD
2403 free_delta_index(n->index);
2404 n->index = NULL;
2405 if (n->data) {
ac77d0c3 2406 freed_mem += SIZE(n->entry);
6a83d902 2407 FREE_AND_NULL(n->data);
a97773ce
BD
2408 }
2409 n->entry = NULL;
7d7baa5e 2410 n->depth = 0;
ef0316fc 2411 return freed_mem;
a97773ce
BD
2412}
2413
384b32c0 2414static void find_deltas(struct object_entry **list, unsigned *list_size,
e334977d 2415 int window, int depth, unsigned *processed)
c323ac7d 2416{
384b32c0 2417 uint32_t i, idx = 0, count = 0;
7cadf491 2418 struct unpacked *array;
ef0316fc 2419 unsigned long mem_usage = 0;
c323ac7d 2420
19d4b416 2421 array = xcalloc(window, sizeof(struct unpacked));
21fcd1bd 2422
384b32c0 2423 for (;;) {
421b488a 2424 struct object_entry *entry;
c323ac7d 2425 struct unpacked *n = array + idx;
ef0316fc 2426 int j, max_depth, best_base = -1;
c323ac7d 2427
384b32c0
NP
2428 progress_lock();
2429 if (!*list_size) {
2430 progress_unlock();
2431 break;
2432 }
421b488a 2433 entry = *list++;
384b32c0
NP
2434 (*list_size)--;
2435 if (!entry->preferred_base) {
2436 (*processed)++;
2437 display_progress(progress_state, *processed);
2438 }
2439 progress_unlock();
2440
ef0316fc 2441 mem_usage -= free_unpacked(n);
c323ac7d 2442 n->entry = entry;
ab7cd7bb 2443
a97773ce 2444 while (window_memory_limit &&
ef0316fc 2445 mem_usage > window_memory_limit &&
a97773ce 2446 count > 1) {
33de80b1 2447 const uint32_t tail = (idx + window - count) % window;
75ad235c 2448 mem_usage -= free_unpacked(array + tail);
a97773ce
BD
2449 count--;
2450 }
2451
75d39853
NP
2452 /* We do not compute delta to *create* objects we are not
2453 * going to pack.
2454 */
2455 if (entry->preferred_base)
2456 goto next;
2457
898b14ce
NP
2458 /*
2459 * If the current object is at pack edge, take the depth the
2460 * objects that depend on the current object into account
2461 * otherwise they would become too deep.
2462 */
2463 max_depth = depth;
898eba5e 2464 if (DELTA_CHILD(entry)) {
898b14ce
NP
2465 max_depth -= check_delta_limit(entry, 0);
2466 if (max_depth <= 0)
2467 goto next;
2468 }
2469
78817c15
LT
2470 j = window;
2471 while (--j > 0) {
77639870 2472 int ret;
7cadf491 2473 uint32_t other_idx = idx + j;
c323ac7d 2474 struct unpacked *m;
78817c15
LT
2475 if (other_idx >= window)
2476 other_idx -= window;
c323ac7d
LT
2477 m = array + other_idx;
2478 if (!m->entry)
2479 break;
ef0316fc 2480 ret = try_delta(n, m, max_depth, &mem_usage);
77639870 2481 if (ret < 0)
c323ac7d 2482 break;
77639870
JH
2483 else if (ret > 0)
2484 best_base = other_idx;
c323ac7d 2485 }
898b14ce 2486
ed4a9031
NP
2487 /*
2488 * If we decided to cache the delta data, then it is best
2489 * to compress it right away. First because we have to do
2490 * it anyway, and doing it here while we're threaded will
2491 * save a lot of time in the non threaded write phase,
2492 * as well as allow for caching more deltas within
2493 * the same cache size limit.
2494 * ...
2495 * But only if not writing to stdout, since in that case
2496 * the network is most likely throttling writes anyway,
2497 * and therefore it is best to go to the write phase ASAP
2498 * instead, as we can afford spending more time compressing
2499 * between writes at that moment.
2500 */
2501 if (entry->delta_data && !pack_to_stdout) {
0cb3c142
NTND
2502 unsigned long size;
2503
0aca34e8 2504 size = do_compress(&entry->delta_data, DELTA_SIZE(entry));
0cb3c142
NTND
2505 if (size < (1U << OE_Z_DELTA_BITS)) {
2506 entry->z_delta_size = size;
2507 cache_lock();
0aca34e8 2508 delta_cache_size -= DELTA_SIZE(entry);
0cb3c142
NTND
2509 delta_cache_size += entry->z_delta_size;
2510 cache_unlock();
2511 } else {
2512 FREE_AND_NULL(entry->delta_data);
2513 entry->z_delta_size = 0;
2514 }
ed4a9031
NP
2515 }
2516
70ca1a3f
JH
2517 /* if we made n a delta, and if n is already at max
2518 * depth, leaving it in the window is pointless. we
2519 * should evict it first.
70ca1a3f 2520 */
898eba5e 2521 if (DELTA(entry) && max_depth <= n->depth)
70ca1a3f 2522 continue;
ff45715c 2523
77639870
JH
2524 /*
2525 * Move the best delta base up in the window, after the
2526 * currently deltified object, to keep it longer. It will
2527 * be the first base object to be attempted next.
2528 */
898eba5e 2529 if (DELTA(entry)) {
77639870
JH
2530 struct unpacked swap = array[best_base];
2531 int dist = (window + idx - best_base) % window;
2532 int dst = best_base;
2533 while (dist--) {
2534 int src = (dst + 1) % window;
2535 array[dst] = array[src];
2536 dst = src;
2537 }
2538 array[dst] = swap;
2539 }
2540
898b14ce 2541 next:
521a4f4c 2542 idx++;
a97773ce
BD
2543 if (count + 1 < window)
2544 count++;
521a4f4c
LT
2545 if (idx >= window)
2546 idx = 0;
384b32c0 2547 }
adee7bdf 2548
f6c7081a 2549 for (i = 0; i < window; ++i) {
ff45715c 2550 free_delta_index(array[i].index);
adee7bdf 2551 free(array[i].data);
f6c7081a 2552 }
adee7bdf 2553 free(array);
c323ac7d
LT
2554}
2555
50f22ada 2556/*
ffbd51cc
NTND
2557 * The main object list is split into smaller lists, each is handed to
2558 * one worker.
2559 *
50f22ada
JS
2560 * The main thread waits on the condition that (at least) one of the workers
2561 * has stopped working (which is indicated in the .working member of
2562 * struct thread_params).
ffbd51cc 2563 *
50f22ada
JS
2564 * When a work thread has completed its work, it sets .working to 0 and
2565 * signals the main thread and waits on the condition that .data_ready
2566 * becomes 1.
ffbd51cc
NTND
2567 *
2568 * The main thread steals half of the work from the worker that has
2569 * most work left to hand it to the idle worker.
50f22ada
JS
2570 */
2571
8ecce684
NP
2572struct thread_params {
2573 pthread_t thread;
2574 struct object_entry **list;
2575 unsigned list_size;
384b32c0 2576 unsigned remaining;
8ecce684
NP
2577 int window;
2578 int depth;
50f22ada
JS
2579 int working;
2580 int data_ready;
2581 pthread_mutex_t mutex;
2582 pthread_cond_t cond;
8ecce684
NP
2583 unsigned *processed;
2584};
2585
44626dc7
AH
2586static pthread_cond_t progress_cond;
2587
2588/*
2589 * Mutex and conditional variable can't be statically-initialized on Windows.
2590 */
2591static void init_threaded_search(void)
2592{
44626dc7
AH
2593 pthread_mutex_init(&cache_mutex, NULL);
2594 pthread_mutex_init(&progress_mutex, NULL);
2595 pthread_cond_init(&progress_cond, NULL);
2596}
2597
2598static void cleanup_threaded_search(void)
2599{
2600 pthread_cond_destroy(&progress_cond);
44626dc7
AH
2601 pthread_mutex_destroy(&cache_mutex);
2602 pthread_mutex_destroy(&progress_mutex);
2603}
c2a33679 2604
8ecce684
NP
2605static void *threaded_find_deltas(void *arg)
2606{
c2a33679
NP
2607 struct thread_params *me = arg;
2608
0c2ad00b 2609 progress_lock();
50f22ada 2610 while (me->remaining) {
0c2ad00b
2611 progress_unlock();
2612
384b32c0 2613 find_deltas(me->list, &me->remaining,
c2a33679 2614 me->window, me->depth, me->processed);
50f22ada
JS
2615
2616 progress_lock();
2617 me->working = 0;
2618 pthread_cond_signal(&progress_cond);
2619 progress_unlock();
2620
2621 /*
2622 * We must not set ->data_ready before we wait on the
2623 * condition because the main thread may have set it to 1
2624 * before we get here. In order to be sure that new
2625 * work is available if we see 1 in ->data_ready, it
2626 * was initialized to 0 before this thread was spawned
2627 * and we reset it to 0 right away.
2628 */
2629 pthread_mutex_lock(&me->mutex);
2630 while (!me->data_ready)
2631 pthread_cond_wait(&me->cond, &me->mutex);
2632 me->data_ready = 0;
2633 pthread_mutex_unlock(&me->mutex);
0c2ad00b
2634
2635 progress_lock();
c2a33679 2636 }
0c2ad00b 2637 progress_unlock();
50f22ada
JS
2638 /* leave ->working 1 so that this doesn't get more work assigned */
2639 return NULL;
8ecce684
NP
2640}
2641
8ecce684
NP
2642static void ll_find_deltas(struct object_entry **list, unsigned list_size,
2643 int window, int depth, unsigned *processed)
2644{
dcda3614 2645 struct thread_params *p;
384b32c0 2646 int i, ret, active_threads = 0;
c2a33679 2647
44626dc7
AH
2648 init_threaded_search();
2649
367f4a43 2650 if (delta_search_threads <= 1) {
384b32c0 2651 find_deltas(list, &list_size, window, depth, processed);
44626dc7 2652 cleanup_threaded_search();
367f4a43
NP
2653 return;
2654 }
43cc2b42 2655 if (progress > pack_to_stdout)
f616db6a 2656 fprintf_ln(stderr, _("Delta compression using up to %d threads"),
1a07e59c 2657 delta_search_threads);
dcda3614 2658 p = xcalloc(delta_search_threads, sizeof(*p));
367f4a43 2659
50f22ada 2660 /* Partition the work amongst work threads. */
367f4a43 2661 for (i = 0; i < delta_search_threads; i++) {
50f22ada
JS
2662 unsigned sub_size = list_size / (delta_search_threads - i);
2663
bf874896
NP
2664 /* don't use too small segments or no deltas will be found */
2665 if (sub_size < 2*window && i+1 < delta_search_threads)
2666 sub_size = 0;
2667
8ecce684
NP
2668 p[i].window = window;
2669 p[i].depth = depth;
2670 p[i].processed = processed;
50f22ada
JS
2671 p[i].working = 1;
2672 p[i].data_ready = 0;
c2a33679 2673
59921b4b 2674 /* try to split chunks on "path" boundaries */
6fc74703
NP
2675 while (sub_size && sub_size < list_size &&
2676 list[sub_size]->hash &&
384b32c0
NP
2677 list[sub_size]->hash == list[sub_size-1]->hash)
2678 sub_size++;
2679
50f22ada
JS
2680 p[i].list = list;
2681 p[i].list_size = sub_size;
2682 p[i].remaining = sub_size;
59921b4b 2683
384b32c0
NP
2684 list += sub_size;
2685 list_size -= sub_size;
2686 }
2687
50f22ada
JS
2688 /* Start work threads. */
2689 for (i = 0; i < delta_search_threads; i++) {
2690 if (!p[i].list_size)
2691 continue;
68e6a4f8
JS
2692 pthread_mutex_init(&p[i].mutex, NULL);
2693 pthread_cond_init(&p[i].cond, NULL);
50f22ada
JS
2694 ret = pthread_create(&p[i].thread, NULL,
2695 threaded_find_deltas, &p[i]);
2696 if (ret)
f616db6a 2697 die(_("unable to create thread: %s"), strerror(ret));
50f22ada
JS
2698 active_threads++;
2699 }
2700
384b32c0
NP
2701 /*
2702 * Now let's wait for work completion. Each time a thread is done
2703 * with its work, we steal half of the remaining work from the
2704 * thread with the largest number of unprocessed objects and give
2705 * it to that newly idle thread. This ensure good load balancing
2706 * until the remaining object list segments are simply too short
2707 * to be worth splitting anymore.
2708 */
50f22ada
JS
2709 while (active_threads) {
2710 struct thread_params *target = NULL;
384b32c0
NP
2711 struct thread_params *victim = NULL;
2712 unsigned sub_size = 0;
384b32c0
NP
2713
2714 progress_lock();
50f22ada
JS
2715 for (;;) {
2716 for (i = 0; !target && i < delta_search_threads; i++)
2717 if (!p[i].working)
2718 target = &p[i];
2719 if (target)
2720 break;
2721 pthread_cond_wait(&progress_cond, &progress_mutex);
2722 }
2723
384b32c0
NP
2724 for (i = 0; i < delta_search_threads; i++)
2725 if (p[i].remaining > 2*window &&
2726 (!victim || victim->remaining < p[i].remaining))
2727 victim = &p[i];
2728 if (victim) {
2729 sub_size = victim->remaining / 2;
2730 list = victim->list + victim->list_size - sub_size;
2731 while (sub_size && list[0]->hash &&
2732 list[0]->hash == list[-1]->hash) {
2733 list++;
2734 sub_size--;
2735 }
eb9688ff
NP
2736 if (!sub_size) {
2737 /*
2738 * It is possible for some "paths" to have
2739 * so many objects that no hash boundary
2740 * might be found. Let's just steal the
2741 * exact half in that case.
2742 */
2743 sub_size = victim->remaining / 2;
2744 list -= sub_size;
2745 }
384b32c0
NP
2746 target->list = list;
2747 victim->list_size -= sub_size;
2748 victim->remaining -= sub_size;
2749 }
384b32c0
NP
2750 target->list_size = sub_size;
2751 target->remaining = sub_size;
50f22ada
JS
2752 target->working = 1;
2753 progress_unlock();
2754
2755 pthread_mutex_lock(&target->mutex);
2756 target->data_ready = 1;
2757 pthread_cond_signal(&target->cond);
2758 pthread_mutex_unlock(&target->mutex);
c2a33679 2759
384b32c0 2760 if (!sub_size) {
b81d9af7 2761 pthread_join(target->thread, NULL);
50f22ada
JS
2762 pthread_cond_destroy(&target->cond);
2763 pthread_mutex_destroy(&target->mutex);
384b32c0 2764 active_threads--;
c2a33679 2765 }
50f22ada 2766 }
44626dc7 2767 cleanup_threaded_search();
dcda3614 2768 free(p);
8ecce684
NP
2769}
2770
ff483026
JK
2771static int obj_is_packed(const struct object_id *oid)
2772{
a14aebea 2773 return packlist_find(&to_pack, oid) ||
92fb0db9
JK
2774 (reuse_packfile_bitmap &&
2775 bitmap_walk_contains(bitmap_git, reuse_packfile_bitmap, oid));
ff483026
JK
2776}
2777
b773ddea
JK
2778static void add_tag_chain(const struct object_id *oid)
2779{
2780 struct tag *tag;
2781
2782 /*
2783 * We catch duplicates already in add_object_entry(), but we'd
2784 * prefer to do this extra check to avoid having to parse the
2785 * tag at all if we already know that it's being packed (e.g., if
2786 * it was included via bitmaps, we would not have parsed it
2787 * previously).
2788 */
ff483026 2789 if (obj_is_packed(oid))
b773ddea
JK
2790 return;
2791
ce71efb7 2792 tag = lookup_tag(the_repository, oid);
b773ddea
JK
2793 while (1) {
2794 if (!tag || parse_tag(tag) || !tag->tagged)
f616db6a 2795 die(_("unable to pack objects reachable from tag %s"),
b773ddea
JK
2796 oid_to_hex(oid));
2797
188960b4 2798 add_object_entry(&tag->object.oid, OBJ_TAG, NULL, 0);
b773ddea
JK
2799
2800 if (tag->tagged->type != OBJ_TAG)
2801 return;
2802
2803 tag = (struct tag *)tag->tagged;
2804 }
2805}
2806
d155254c 2807static int add_ref_tag(const char *path, const struct object_id *oid, int flag, void *cb_data)
f0a24aa5 2808{
d155254c 2809 struct object_id peeled;
f0a24aa5 2810
59556548 2811 if (starts_with(path, "refs/tags/") && /* is a tag? */
b420d909 2812 !peel_ref(path, &peeled) && /* peelable? */
ff483026 2813 obj_is_packed(&peeled)) /* object packed? */
b773ddea 2814 add_tag_chain(oid);
f0a24aa5
SP
2815 return 0;
2816}
2817
f3123c4a
JH
2818static void prepare_pack(int window, int depth)
2819{
9668cf59 2820 struct object_entry **delta_list;
6e1c2344
RJ
2821 uint32_t i, nr_deltas;
2822 unsigned n;
9668cf59 2823
28b8a730 2824 if (use_delta_islands)
385cb64f 2825 resolve_tree_islands(the_repository, progress, &to_pack);
28b8a730 2826
3f9ac8d2 2827 get_object_details();
9668cf59 2828
0e8189e2
NP
2829 /*
2830 * If we're locally repacking then we need to be doubly careful
2831 * from now on in order to make sure no stealth corruption gets
2832 * propagated to the new pack. Clients receiving streamed packs
2833 * should validate everything they get anyway so no need to incur
2834 * the additional cost here in that case.
2835 */
2836 if (!pack_to_stdout)
2837 do_check_packed_object_crc = 1;
2838
2834bc27 2839 if (!to_pack.nr_objects || !window || !depth)
9668cf59
NP
2840 return;
2841
b32fa95f 2842 ALLOC_ARRAY(delta_list, to_pack.nr_objects);
75d39853
NP
2843 nr_deltas = n = 0;
2844
2834bc27
VM
2845 for (i = 0; i < to_pack.nr_objects; i++) {
2846 struct object_entry *entry = to_pack.objects + i;
75d39853 2847
898eba5e 2848 if (DELTA(entry))
75d39853 2849 /* This happens if we decided to reuse existing
a7de7130 2850 * delta from a pack. "reuse_delta &&" is implied.
75d39853
NP
2851 */
2852 continue;
2853
ac77d0c3
NTND
2854 if (!entry->type_valid ||
2855 oe_size_less_than(&to_pack, entry, 50))
75d39853
NP
2856 continue;
2857
2858 if (entry->no_try_delta)
2859 continue;
2860
6d6f9cdd 2861 if (!entry->preferred_base) {
75d39853 2862 nr_deltas++;
fd9b1bae 2863 if (oe_type(entry) < 0)
f616db6a 2864 die(_("unable to get type of object %s"),
e6a492b7 2865 oid_to_hex(&entry->idx.oid));
eede9f42 2866 } else {
fd9b1bae 2867 if (oe_type(entry) < 0) {
eede9f42
NP
2868 /*
2869 * This object is not found, but we
2870 * don't have to include it anyway.
2871 */
2872 continue;
2873 }
6d6f9cdd 2874 }
75d39853
NP
2875
2876 delta_list[n++] = entry;
2877 }
2878
2f8b8947 2879 if (nr_deltas && n > 1) {
e334977d 2880 unsigned nr_done = 0;
bb514de3 2881
e334977d 2882 if (progress)
754dbc43 2883 progress_state = start_progress(_("Compressing objects"),
dc6a0757 2884 nr_deltas);
9ed0d8d6 2885 QSORT(delta_list, n, type_size_sort);
8ecce684 2886 ll_find_deltas(delta_list, n, window+1, depth, &nr_done);
4d4fcc54 2887 stop_progress(&progress_state);
e334977d 2888 if (nr_done != nr_deltas)
f616db6a 2889 die(_("inconsistency with delta count"));
75d39853 2890 }
9668cf59 2891 free(delta_list);
f3123c4a
JH
2892}
2893
ef90d6d4 2894static int git_pack_config(const char *k, const char *v, void *cb)
4812a93a 2895{
eeefa7c9 2896 if (!strcmp(k, "pack.window")) {
4812a93a
JK
2897 window = git_config_int(k, v);
2898 return 0;
2899 }
a97773ce
BD
2900 if (!strcmp(k, "pack.windowmemory")) {
2901 window_memory_limit = git_config_ulong(k, v);
2902 return 0;
2903 }
2904 if (!strcmp(k, "pack.depth")) {
842aaf93
TT
2905 depth = git_config_int(k, v);
2906 return 0;
2907 }
074b2eea
MK
2908 if (!strcmp(k, "pack.deltacachesize")) {
2909 max_delta_cache_size = git_config_int(k, v);
2910 return 0;
2911 }
e3dfddb3
MK
2912 if (!strcmp(k, "pack.deltacachelimit")) {
2913 cache_max_small_delta_size = git_config_int(k, v);
2914 return 0;
2915 }
ae4f07fb
VM
2916 if (!strcmp(k, "pack.writebitmaphashcache")) {
2917 if (git_config_bool(k, v))
2918 write_bitmap_options |= BITMAP_OPT_HASH_CACHE;
2919 else
2920 write_bitmap_options &= ~BITMAP_OPT_HASH_CACHE;
2921 }
6b8fda2d 2922 if (!strcmp(k, "pack.usebitmaps")) {
645c432d 2923 use_bitmap_index_default = git_config_bool(k, v);
6b8fda2d
VM
2924 return 0;
2925 }
e704fc79
JK
2926 if (!strcmp(k, "pack.allowpackreuse")) {
2927 allow_pack_reuse = git_config_bool(k, v);
2928 return 0;
2929 }
693b86ff
NP
2930 if (!strcmp(k, "pack.threads")) {
2931 delta_search_threads = git_config_int(k, v);
833e3df1 2932 if (delta_search_threads < 0)
f616db6a 2933 die(_("invalid number of threads specified (%d)"),
693b86ff 2934 delta_search_threads);
9c897c5c 2935 if (!HAVE_THREADS && delta_search_threads != 1) {
f616db6a 2936 warning(_("no threads support, ignoring %s"), k);
2e96d815
ÆAB
2937 delta_search_threads = 0;
2938 }
693b86ff
NP
2939 return 0;
2940 }
4d00bda2 2941 if (!strcmp(k, "pack.indexversion")) {
ebcfb379
JH
2942 pack_idx_opts.version = git_config_int(k, v);
2943 if (pack_idx_opts.version > 2)
f616db6a 2944 die(_("bad pack.indexversion=%"PRIu32),
ebcfb379 2945 pack_idx_opts.version);
4d00bda2
NP
2946 return 0;
2947 }
dd4b732d
JT
2948 if (!strcmp(k, "uploadpack.blobpackfileuri")) {
2949 struct configured_exclusion *ex = xmalloc(sizeof(*ex));
2950 const char *oid_end, *pack_end;
2951 /*
2952 * Stores the pack hash. This is not a true object ID, but is
2953 * of the same form.
2954 */
2955 struct object_id pack_hash;
2956
2957 if (parse_oid_hex(v, &ex->e.oid, &oid_end) ||
2958 *oid_end != ' ' ||
2959 parse_oid_hex(oid_end + 1, &pack_hash, &pack_end) ||
2960 *pack_end != ' ')
2961 die(_("value of uploadpack.blobpackfileuri must be "
2962 "of the form '<object-hash> <pack-hash> <uri>' (got '%s')"), v);
2963 if (oidmap_get(&configured_exclusions, &ex->e.oid))
2964 die(_("object already configured in another "
2965 "uploadpack.blobpackfileuri (got '%s')"), v);
2966 ex->pack_hash_hex = xcalloc(1, pack_end - oid_end);
2967 memcpy(ex->pack_hash_hex, oid_end + 1, pack_end - oid_end - 1);
2968 ex->uri = xstrdup(pack_end + 1);
2969 oidmap_put(&configured_exclusions, ex);
2970 }
ef90d6d4 2971 return git_default_config(k, v, cb);
4812a93a
JK
2972}
2973
b5d97e6b 2974static void read_object_list_from_stdin(void)
c323ac7d 2975{
188960b4 2976 char line[GIT_MAX_HEXSZ + 1 + PATH_MAX + 2];
2977 struct object_id oid;
2978 const char *p;
b2504a0d 2979
da93d12b 2980 for (;;) {
da93d12b
LT
2981 if (!fgets(line, sizeof(line), stdin)) {
2982 if (feof(stdin))
2983 break;
2984 if (!ferror(stdin))
1a07e59c 2985 die("BUG: fgets returned NULL, not EOF, not error!");
687dd75c 2986 if (errno != EINTR)
d824cbba 2987 die_errno("fgets");
687dd75c
JH
2988 clearerr(stdin);
2989 continue;
da93d12b 2990 }
7a979d99 2991 if (line[0] == '-') {
188960b4 2992 if (get_oid_hex(line+1, &oid))
f616db6a 2993 die(_("expected edge object ID, got garbage:\n %s"),
b5d97e6b 2994 line);
188960b4 2995 add_preferred_base(&oid);
7a979d99 2996 continue;
21fcd1bd 2997 }
188960b4 2998 if (parse_oid_hex(line, &oid, &p))
f616db6a 2999 die(_("expected object ID, got garbage:\n %s"), line);
b5d97e6b 3000
188960b4 3001 add_preferred_base_object(p + 1);
fd9b1bae 3002 add_object_entry(&oid, OBJ_NONE, p + 1, 0);
c323ac7d 3003 }
b5d97e6b
JH
3004}
3005
95308d64 3006/* Remember to update object flag allocation in object.h */
08cdfb13
JH
3007#define OBJECT_ADDED (1u<<20)
3008
11c211fa 3009static void show_commit(struct commit *commit, void *data)
b5d97e6b 3010{
188960b4 3011 add_object_entry(&commit->object.oid, OBJ_COMMIT, NULL, 0);
08cdfb13 3012 commit->object.flags |= OBJECT_ADDED;
7cc8f971
VM
3013
3014 if (write_bitmap_index)
3015 index_commit_for_bitmap(commit);
28b8a730
JK
3016
3017 if (use_delta_islands)
3018 propagate_island_marks(commit);
b5d97e6b
JH
3019}
3020
de1e67d0 3021static void show_object(struct object *obj, const char *name, void *data)
b5d97e6b 3022{
8d2dfc49 3023 add_preferred_base_object(name);
188960b4 3024 add_object_entry(&obj->oid, obj->type, name, 0);
8d2dfc49 3025 obj->flags |= OBJECT_ADDED;
28b8a730
JK
3026
3027 if (use_delta_islands) {
3028 const char *p;
39490536 3029 unsigned depth;
28b8a730
JK
3030 struct object_entry *ent;
3031
39490536
JK
3032 /* the empty string is a root tree, which is depth 0 */
3033 depth = *name ? 1 : 0;
28b8a730
JK
3034 for (p = strchr(name, '/'); p; p = strchr(p + 1, '/'))
3035 depth++;
3036
3a37876b 3037 ent = packlist_find(&to_pack, &obj->oid);
108f5303
CC
3038 if (ent && depth > oe_tree_depth(&to_pack, ent))
3039 oe_set_tree_depth(&to_pack, ent, depth);
28b8a730 3040 }
b5d97e6b
JH
3041}
3042
9535ce73
JH
3043static void show_object__ma_allow_any(struct object *obj, const char *name, void *data)
3044{
3045 assert(arg_missing_action == MA_ALLOW_ANY);
3046
3047 /*
3048 * Quietly ignore ALL missing objects. This avoids problems with
3049 * staging them now and getting an odd error later.
3050 */
ee47243d 3051 if (!has_object(the_repository, &obj->oid, 0))
9535ce73
JH
3052 return;
3053
3054 show_object(obj, name, data);
3055}
3056
0c16cd49
JT
3057static void show_object__ma_allow_promisor(struct object *obj, const char *name, void *data)
3058{
3059 assert(arg_missing_action == MA_ALLOW_PROMISOR);
3060
3061 /*
3062 * Quietly ignore EXPECTED missing objects. This avoids problems with
3063 * staging them now and getting an odd error later.
3064 */
ee47243d 3065 if (!has_object(the_repository, &obj->oid, 0) && is_promisor_object(&obj->oid))
0c16cd49
JT
3066 return;
3067
3068 show_object(obj, name, data);
3069}
3070
9535ce73
JH
3071static int option_parse_missing_action(const struct option *opt,
3072 const char *arg, int unset)
3073{
3074 assert(arg);
3075 assert(!unset);
3076
3077 if (!strcmp(arg, "error")) {
3078 arg_missing_action = MA_ERROR;
3079 fn_show_object = show_object;
3080 return 0;
3081 }
3082
3083 if (!strcmp(arg, "allow-any")) {
3084 arg_missing_action = MA_ALLOW_ANY;
0c16cd49 3085 fetch_if_missing = 0;
9535ce73
JH
3086 fn_show_object = show_object__ma_allow_any;
3087 return 0;
3088 }
3089
0c16cd49
JT
3090 if (!strcmp(arg, "allow-promisor")) {
3091 arg_missing_action = MA_ALLOW_PROMISOR;
3092 fetch_if_missing = 0;
3093 fn_show_object = show_object__ma_allow_promisor;
3094 return 0;
3095 }
3096
9535ce73
JH
3097 die(_("invalid value for --missing"));
3098 return 0;
3099}
3100
8d1d8f83
JH
3101static void show_edge(struct commit *commit)
3102{
188960b4 3103 add_preferred_base(&commit->object.oid);
8d1d8f83
JH
3104}
3105
08cdfb13
JH
3106struct in_pack_object {
3107 off_t offset;
3108 struct object *object;
3109};
3110
3111struct in_pack {
071bcaab
RJ
3112 unsigned int alloc;
3113 unsigned int nr;
08cdfb13
JH
3114 struct in_pack_object *array;
3115};
3116
3117static void mark_in_pack_object(struct object *object, struct packed_git *p, struct in_pack *in_pack)
3118{
ed1c9977 3119 in_pack->array[in_pack->nr].offset = find_pack_entry_one(object->oid.hash, p);
08cdfb13
JH
3120 in_pack->array[in_pack->nr].object = object;
3121 in_pack->nr++;
3122}
3123
3124/*
3125 * Compare the objects in the offset order, in order to emulate the
f18d244a 3126 * "git rev-list --objects" output that produced the pack originally.
08cdfb13
JH
3127 */
3128static int ofscmp(const void *a_, const void *b_)
3129{
3130 struct in_pack_object *a = (struct in_pack_object *)a_;
3131 struct in_pack_object *b = (struct in_pack_object *)b_;
3132
3133 if (a->offset < b->offset)
3134 return -1;
3135 else if (a->offset > b->offset)
3136 return 1;
3137 else
f2fd0760 3138 return oidcmp(&a->object->oid, &b->object->oid);
08cdfb13
JH
3139}
3140
7a2a7216 3141static void add_objects_in_unpacked_packs(void)
08cdfb13
JH
3142{
3143 struct packed_git *p;
3144 struct in_pack in_pack;
3145 uint32_t i;
3146
3147 memset(&in_pack, 0, sizeof(in_pack));
3148
454ea2e4 3149 for (p = get_all_packs(the_repository); p; p = p->next) {
188960b4 3150 struct object_id oid;
08cdfb13
JH
3151 struct object *o;
3152
ed7e5fc3 3153 if (!p->pack_local || p->pack_keep || p->pack_keep_in_core)
08cdfb13
JH
3154 continue;
3155 if (open_pack_index(p))
f616db6a 3156 die(_("cannot open pack index"));
08cdfb13
JH
3157
3158 ALLOC_GROW(in_pack.array,
3159 in_pack.nr + p->num_objects,
3160 in_pack.alloc);
3161
3162 for (i = 0; i < p->num_objects; i++) {
0763671b 3163 nth_packed_object_id(&oid, p, i);
0ebbcf70 3164 o = lookup_unknown_object(&oid);
08cdfb13
JH
3165 if (!(o->flags & OBJECT_ADDED))
3166 mark_in_pack_object(o, p, &in_pack);
3167 o->flags |= OBJECT_ADDED;
3168 }
3169 }
3170
3171 if (in_pack.nr) {
9ed0d8d6 3172 QSORT(in_pack.array, in_pack.nr, ofscmp);
08cdfb13
JH
3173 for (i = 0; i < in_pack.nr; i++) {
3174 struct object *o = in_pack.array[i].object;
188960b4 3175 add_object_entry(&o->oid, o->type, "", 0);
08cdfb13
JH
3176 }
3177 }
3178 free(in_pack.array);
3179}
3180
76c1d9a0 3181static int add_loose_object(const struct object_id *oid, const char *path,
e26a8c47
JK
3182 void *data)
3183{
0df8e965 3184 enum object_type type = oid_object_info(the_repository, oid, NULL);
e26a8c47
JK
3185
3186 if (type < 0) {
f616db6a 3187 warning(_("loose object at %s could not be examined"), path);
e26a8c47
JK
3188 return 0;
3189 }
3190
188960b4 3191 add_object_entry(oid, type, "", 0);
e26a8c47
JK
3192 return 0;
3193}
3194
3195/*
3196 * We actually don't even have to worry about reachability here.
3197 * add_object_entry will weed out duplicates, so we just add every
3198 * loose object we find.
3199 */
3200static void add_unreachable_loose_objects(void)
3201{
3202 for_each_loose_file_in_objdir(get_object_directory(),
3203 add_loose_object,
3204 NULL, NULL, NULL);
3205}
3206
188960b4 3207static int has_sha1_pack_kept_or_nonlocal(const struct object_id *oid)
094085e3
BC
3208{
3209 static struct packed_git *last_found = (void *)1;
3210 struct packed_git *p;
3211
a80d72db 3212 p = (last_found != (void *)1) ? last_found :
454ea2e4 3213 get_all_packs(the_repository);
094085e3
BC
3214
3215 while (p) {
ed7e5fc3
NTND
3216 if ((!p->pack_local || p->pack_keep ||
3217 p->pack_keep_in_core) &&
188960b4 3218 find_pack_entry_one(oid->hash, p)) {
094085e3
BC
3219 last_found = p;
3220 return 1;
3221 }
3222 if (p == last_found)
454ea2e4 3223 p = get_all_packs(the_repository);
094085e3
BC
3224 else
3225 p = p->next;
3226 if (p == last_found)
3227 p = p->next;
3228 }
3229 return 0;
3230}
3231
abcb8655
JK
3232/*
3233 * Store a list of sha1s that are should not be discarded
3234 * because they are either written too recently, or are
3235 * reachable from another object that was.
3236 *
3237 * This is filled by get_object_list.
3238 */
910650d2 3239static struct oid_array recent_objects;
abcb8655 3240
4ce3621a 3241static int loosened_object_can_be_discarded(const struct object_id *oid,
dddbad72 3242 timestamp_t mtime)
d0d46abc
JK
3243{
3244 if (!unpack_unreachable_expiration)
3245 return 0;
3246 if (mtime > unpack_unreachable_expiration)
3247 return 0;
910650d2 3248 if (oid_array_lookup(&recent_objects, oid) >= 0)
abcb8655 3249 return 0;
d0d46abc
JK
3250 return 1;
3251}
3252
7a2a7216 3253static void loosen_unused_packed_objects(void)
ca11b212
NP
3254{
3255 struct packed_git *p;
3256 uint32_t i;
4ce3621a 3257 struct object_id oid;
ca11b212 3258
454ea2e4 3259 for (p = get_all_packs(the_repository); p; p = p->next) {
ed7e5fc3 3260 if (!p->pack_local || p->pack_keep || p->pack_keep_in_core)
ca11b212
NP
3261 continue;
3262
3263 if (open_pack_index(p))
f616db6a 3264 die(_("cannot open pack index"));
ca11b212
NP
3265
3266 for (i = 0; i < p->num_objects; i++) {
0763671b 3267 nth_packed_object_id(&oid, p, i);
3a37876b 3268 if (!packlist_find(&to_pack, &oid) &&
188960b4 3269 !has_sha1_pack_kept_or_nonlocal(&oid) &&
4ce3621a 3270 !loosened_object_can_be_discarded(&oid, p->mtime))
4bdb70a4 3271 if (force_object_loose(&oid, p->mtime))
f616db6a 3272 die(_("unable to force loose object"));
ca11b212
NP
3273 }
3274 }
3275}
3276
69e4b342 3277/*
645c432d
KS
3278 * This tracks any options which pack-reuse code expects to be on, or which a
3279 * reader of the pack might not understand, and which would therefore prevent
3280 * blind reuse of what we have on disk.
69e4b342
JK
3281 */
3282static int pack_options_allow_reuse(void)
3283{
e704fc79
JK
3284 return allow_pack_reuse &&
3285 pack_to_stdout &&
ed7e5fc3
NTND
3286 !ignore_packed_keep_on_disk &&
3287 !ignore_packed_keep_in_core &&
9df4a607
JK
3288 (!local || !have_non_local_packs) &&
3289 !incremental;
69e4b342
JK
3290}
3291
6b8fda2d
VM
3292static int get_object_list_from_bitmap(struct rev_info *revs)
3293{
3ab3185f 3294 if (!(bitmap_git = prepare_bitmap_walk(revs, &filter_options)))
6b8fda2d
VM
3295 return -1;
3296
69e4b342
JK
3297 if (pack_options_allow_reuse() &&
3298 !reuse_partial_packfile_from_bitmap(
3ae5fa07 3299 bitmap_git,
6b8fda2d
VM
3300 &reuse_packfile,
3301 &reuse_packfile_objects,
bb514de3 3302 &reuse_packfile_bitmap)) {
6b8fda2d
VM
3303 assert(reuse_packfile_objects);
3304 nr_result += reuse_packfile_objects;
78d2214e 3305 display_progress(progress_state, nr_result);
6b8fda2d
VM
3306 }
3307
4eb707eb
JK
3308 traverse_bitmap_commit_list(bitmap_git, revs,
3309 &add_object_entry_from_bitmap);
6b8fda2d
VM
3310 return 0;
3311}
3312
abcb8655 3313static void record_recent_object(struct object *obj,
de1e67d0 3314 const char *name,
abcb8655
JK
3315 void *data)
3316{
910650d2 3317 oid_array_append(&recent_objects, &obj->oid);
abcb8655
JK
3318}
3319
3320static void record_recent_commit(struct commit *commit, void *data)
3321{
910650d2 3322 oid_array_append(&recent_objects, &commit->object.oid);
abcb8655
JK
3323}
3324
8d1d8f83 3325static void get_object_list(int ac, const char **av)
b5d97e6b
JH
3326{
3327 struct rev_info revs;
bbcde41a
MD
3328 struct setup_revision_opt s_r_opt = {
3329 .allow_exclude_promisor_objects = 1,
3330 };
b5d97e6b 3331 char line[1000];
b5d97e6b 3332 int flags = 0;
a4544b31 3333 int save_warning;
b5d97e6b 3334
2abf3503 3335 repo_init_revisions(the_repository, &revs, NULL);
b5d97e6b 3336 save_commit_buffer = 0;
bbcde41a 3337 setup_revisions(ac, av, &revs, &s_r_opt);
b5d97e6b 3338
b790e0f6 3339 /* make sure shallows are read */
c8813487 3340 is_repository_shallow(the_repository);
b790e0f6 3341
a4544b31
DS
3342 save_warning = warn_on_object_refname_ambiguity;
3343 warn_on_object_refname_ambiguity = 0;
3344
b5d97e6b
JH
3345 while (fgets(line, sizeof(line), stdin) != NULL) {
3346 int len = strlen(line);
872c930d 3347 if (len && line[len - 1] == '\n')
b5d97e6b
JH
3348 line[--len] = 0;
3349 if (!len)
3350 break;
3351 if (*line == '-') {
3352 if (!strcmp(line, "--not")) {
3353 flags ^= UNINTERESTING;
7cc8f971 3354 write_bitmap_index = 0;
b5d97e6b
JH
3355 continue;
3356 }
b790e0f6 3357 if (starts_with(line, "--shallow ")) {
e92b848c 3358 struct object_id oid;
3359 if (get_oid_hex(line + 10, &oid))
4279000d 3360 die("not an object name '%s'", line + 10);
19143f13 3361 register_shallow(the_repository, &oid);
f7f91086 3362 use_bitmap_index = 0;
b790e0f6
NTND
3363 continue;
3364 }
f616db6a 3365 die(_("not a rev '%s'"), line);
b5d97e6b 3366 }
8e676e8b 3367 if (handle_revision_arg(line, &revs, flags, REVARG_CANNOT_BE_FILENAME))
f616db6a 3368 die(_("bad revision '%s'"), line);
b5d97e6b
JH
3369 }
3370
a4544b31
DS
3371 warn_on_object_refname_ambiguity = save_warning;
3372
6b8fda2d
VM
3373 if (use_bitmap_index && !get_object_list_from_bitmap(&revs))
3374 return;
3375
28b8a730 3376 if (use_delta_islands)
bdbdf42f 3377 load_delta_islands(the_repository, progress);
28b8a730 3378
3d51e1b5 3379 if (prepare_revision_walk(&revs))
f616db6a 3380 die(_("revision walk setup failed"));
4f6d26b1 3381 mark_edges_uninteresting(&revs, show_edge, sparse);
9535ce73
JH
3382
3383 if (!fn_show_object)
3384 fn_show_object = show_object;
3385 traverse_commit_list_filtered(&filter_options, &revs,
3386 show_commit, fn_show_object, NULL,
3387 NULL);
08cdfb13 3388
abcb8655
JK
3389 if (unpack_unreachable_expiration) {
3390 revs.ignore_missing_links = 1;
3391 if (add_unseen_recent_objects_to_traversal(&revs,
3392 unpack_unreachable_expiration))
f616db6a 3393 die(_("unable to add recent objects"));
abcb8655 3394 if (prepare_revision_walk(&revs))
f616db6a 3395 die(_("revision walk setup failed"));
abcb8655
JK
3396 traverse_commit_list(&revs, record_recent_commit,
3397 record_recent_object, NULL);
3398 }
3399
08cdfb13 3400 if (keep_unreachable)
7a2a7216 3401 add_objects_in_unpacked_packs();
e26a8c47
JK
3402 if (pack_loose_unreachable)
3403 add_unreachable_loose_objects();
ca11b212 3404 if (unpack_unreachable)
7a2a7216 3405 loosen_unused_packed_objects();
abcb8655 3406
910650d2 3407 oid_array_clear(&recent_objects);
b5d97e6b
JH
3408}
3409
ed7e5fc3
NTND
3410static void add_extra_kept_packs(const struct string_list *names)
3411{
3412 struct packed_git *p;
3413
3414 if (!names->nr)
3415 return;
3416
454ea2e4 3417 for (p = get_all_packs(the_repository); p; p = p->next) {
ed7e5fc3
NTND
3418 const char *name = basename(p->pack_name);
3419 int i;
3420
3421 if (!p->pack_local)
3422 continue;
3423
3424 for (i = 0; i < names->nr; i++)
3425 if (!fspathcmp(name, names->items[i].string))
3426 break;
3427
3428 if (i < names->nr) {
3429 p->pack_keep_in_core = 1;
3430 ignore_packed_keep_in_core = 1;
3431 continue;
3432 }
3433 }
3434}
3435
99fb6e04
NTND
3436static int option_parse_index_version(const struct option *opt,
3437 const char *arg, int unset)
3438{
3439 char *c;
3440 const char *val = arg;
517fe807
JK
3441
3442 BUG_ON_OPT_NEG(unset);
3443
99fb6e04
NTND
3444 pack_idx_opts.version = strtoul(val, &c, 10);
3445 if (pack_idx_opts.version > 2)
3446 die(_("unsupported index version %s"), val);
3447 if (*c == ',' && c[1])
3448 pack_idx_opts.off32_limit = strtoul(c+1, &c, 0);
3449 if (*c || pack_idx_opts.off32_limit & 0x80000000)
3450 die(_("bad index version '%s'"), val);
3451 return 0;
3452}
3453
7e52f566
JK
3454static int option_parse_unpack_unreachable(const struct option *opt,
3455 const char *arg, int unset)
3456{
3457 if (unset) {
3458 unpack_unreachable = 0;
3459 unpack_unreachable_expiration = 0;
3460 }
3461 else {
3462 unpack_unreachable = 1;
3463 if (arg)
3464 unpack_unreachable_expiration = approxidate(arg);
3465 }
3466 return 0;
3467}
3468
b5d97e6b
JH
3469int cmd_pack_objects(int argc, const char **argv, const char *prefix)
3470{
b5d97e6b 3471 int use_internal_rev_list = 0;
2dacf26d 3472 int shallow = 0;
4f366275 3473 int all_progress_implied = 0;
22f9b7f3 3474 struct strvec rp = STRVEC_INIT;
99fb6e04 3475 int rev_list_unpacked = 0, rev_list_all = 0, rev_list_reflog = 0;
c90f9e13 3476 int rev_list_index = 0;
ed7e5fc3 3477 struct string_list keep_pack_list = STRING_LIST_INIT_NODUP;
99fb6e04
NTND
3478 struct option pack_objects_options[] = {
3479 OPT_SET_INT('q', "quiet", &progress,
4c688120 3480 N_("do not show progress meter"), 0),
99fb6e04 3481 OPT_SET_INT(0, "progress", &progress,
4c688120 3482 N_("show progress meter"), 1),
99fb6e04 3483 OPT_SET_INT(0, "all-progress", &progress,
4c688120 3484 N_("show progress meter during object writing phase"), 2),
99fb6e04
NTND
3485 OPT_BOOL(0, "all-progress-implied",
3486 &all_progress_implied,
4c688120 3487 N_("similar to --all-progress when progress meter is shown")),
203c8533 3488 OPT_CALLBACK_F(0, "index-version", NULL, N_("<version>[,<offset>]"),
4c688120 3489 N_("write the pack index file in the specified idx format version"),
203c8533 3490 PARSE_OPT_NONEG, option_parse_index_version),
2a514ed8
CB
3491 OPT_MAGNITUDE(0, "max-pack-size", &pack_size_limit,
3492 N_("maximum size of each output pack file")),
99fb6e04 3493 OPT_BOOL(0, "local", &local,
4c688120 3494 N_("ignore borrowed objects from alternate object store")),
99fb6e04 3495 OPT_BOOL(0, "incremental", &incremental,
4c688120 3496 N_("ignore packed objects")),
99fb6e04 3497 OPT_INTEGER(0, "window", &window,
4c688120 3498 N_("limit pack window by objects")),
2a514ed8
CB
3499 OPT_MAGNITUDE(0, "window-memory", &window_memory_limit,
3500 N_("limit pack window by memory in addition to object limit")),
99fb6e04 3501 OPT_INTEGER(0, "depth", &depth,
4c688120 3502 N_("maximum length of delta chain allowed in the resulting pack")),
99fb6e04 3503 OPT_BOOL(0, "reuse-delta", &reuse_delta,
4c688120 3504 N_("reuse existing deltas")),
99fb6e04 3505 OPT_BOOL(0, "reuse-object", &reuse_object,
4c688120 3506 N_("reuse existing objects")),
99fb6e04 3507 OPT_BOOL(0, "delta-base-offset", &allow_ofs_delta,
4c688120 3508 N_("use OFS_DELTA objects")),
99fb6e04 3509 OPT_INTEGER(0, "threads", &delta_search_threads,
4c688120 3510 N_("use threads when searching for best delta matches")),
99fb6e04 3511 OPT_BOOL(0, "non-empty", &non_empty,
4c688120 3512 N_("do not create an empty pack output")),
99fb6e04 3513 OPT_BOOL(0, "revs", &use_internal_rev_list,
4c688120 3514 N_("read revision arguments from standard input")),
3e4a67b4
NTND
3515 OPT_SET_INT_F(0, "unpacked", &rev_list_unpacked,
3516 N_("limit the objects to those that are not yet packed"),
3517 1, PARSE_OPT_NONEG),
3518 OPT_SET_INT_F(0, "all", &rev_list_all,
3519 N_("include objects reachable from any reference"),
3520 1, PARSE_OPT_NONEG),
3521 OPT_SET_INT_F(0, "reflog", &rev_list_reflog,
3522 N_("include objects referred by reflog entries"),
3523 1, PARSE_OPT_NONEG),
3524 OPT_SET_INT_F(0, "indexed-objects", &rev_list_index,
3525 N_("include objects referred to by the index"),
3526 1, PARSE_OPT_NONEG),
99fb6e04 3527 OPT_BOOL(0, "stdout", &pack_to_stdout,
4c688120 3528 N_("output pack to stdout")),
99fb6e04 3529 OPT_BOOL(0, "include-tag", &include_tag,
4c688120 3530 N_("include tag objects that refer to objects to be packed")),
99fb6e04 3531 OPT_BOOL(0, "keep-unreachable", &keep_unreachable,
4c688120 3532 N_("keep unreachable objects")),
e26a8c47
JK
3533 OPT_BOOL(0, "pack-loose-unreachable", &pack_loose_unreachable,
3534 N_("pack loose unreachable objects")),
203c8533 3535 OPT_CALLBACK_F(0, "unpack-unreachable", NULL, N_("time"),
4c688120 3536 N_("unpack unreachable objects newer than <time>"),
203c8533 3537 PARSE_OPT_OPTARG, option_parse_unpack_unreachable),
4f6d26b1
DS
3538 OPT_BOOL(0, "sparse", &sparse,
3539 N_("use the sparse reachability algorithm")),
99fb6e04 3540 OPT_BOOL(0, "thin", &thin,
4c688120 3541 N_("create thin packs")),
2dacf26d 3542 OPT_BOOL(0, "shallow", &shallow,
3543 N_("create packs suitable for shallow fetches")),
ed7e5fc3 3544 OPT_BOOL(0, "honor-pack-keep", &ignore_packed_keep_on_disk,
4c688120 3545 N_("ignore packs that have companion .keep file")),
ed7e5fc3
NTND
3546 OPT_STRING_LIST(0, "keep-pack", &keep_pack_list, N_("name"),
3547 N_("ignore this pack")),
99fb6e04 3548 OPT_INTEGER(0, "compression", &pack_compression_level,
4c688120 3549 N_("pack compression level")),
99fb6e04 3550 OPT_SET_INT(0, "keep-true-parents", &grafts_replace_parents,
4c688120 3551 N_("do not hide commits by grafts"), 0),
6b8fda2d
VM
3552 OPT_BOOL(0, "use-bitmap-index", &use_bitmap_index,
3553 N_("use a bitmap index if available to speed up counting objects")),
25575015
JK
3554 OPT_SET_INT(0, "write-bitmap-index", &write_bitmap_index,
3555 N_("write a bitmap index together with the pack index"),
3556 WRITE_BITMAP_TRUE),
3557 OPT_SET_INT_F(0, "write-bitmap-index-quiet",
3558 &write_bitmap_index,
3559 N_("write a bitmap index if possible"),
3560 WRITE_BITMAP_QUIET, PARSE_OPT_HIDDEN),
9535ce73 3561 OPT_PARSE_LIST_OBJECTS_FILTER(&filter_options),
203c8533 3562 OPT_CALLBACK_F(0, "missing", NULL, N_("action"),
9535ce73 3563 N_("handling for missing objects"), PARSE_OPT_NONEG,
203c8533 3564 option_parse_missing_action),
0c16cd49
JT
3565 OPT_BOOL(0, "exclude-promisor-objects", &exclude_promisor_objects,
3566 N_("do not pack objects in promisor packfiles")),
28b8a730
JK
3567 OPT_BOOL(0, "delta-islands", &use_delta_islands,
3568 N_("respect islands during delta compression")),
dd4b732d
JT
3569 OPT_STRING_LIST(0, "uri-protocol", &uri_protocols,
3570 N_("protocol"),
3571 N_("exclude any configured uploadpack.blobpackfileuri with this protocol")),
99fb6e04
NTND
3572 OPT_END(),
3573 };
8d1d8f83 3574
0c6804ab
NTND
3575 if (DFS_NUM_STATES > (1 << OE_DFS_STATE_BITS))
3576 BUG("too many dfs states, increase OE_DFS_STATE_BITS");
3577
6ebd1caf 3578 read_replace_refs = 0;
dae556bd 3579
2d657ab9 3580 sparse = git_env_bool("GIT_TEST_PACK_SPARSE", -1);
7211b9e7 3581 prepare_repo_settings(the_repository);
2d657ab9 3582 if (sparse < 0)
7211b9e7
DS
3583 sparse = the_repository->settings.pack_use_sparse;
3584
ebcfb379 3585 reset_pack_idx_option(&pack_idx_opts);
ef90d6d4 3586 git_config(git_pack_config, NULL);
b5d97e6b
JH
3587
3588 progress = isatty(2);
99fb6e04
NTND
3589 argc = parse_options(argc, argv, prefix, pack_objects_options,
3590 pack_usage, 0);
b5d97e6b 3591
99fb6e04
NTND
3592 if (argc) {
3593 base_name = argv[0];
3594 argc--;
b5d97e6b 3595 }
99fb6e04
NTND
3596 if (pack_to_stdout != !base_name || argc)
3597 usage_with_options(pack_usage, pack_objects_options);
b5d97e6b 3598
b5c0cbd8
NTND
3599 if (depth >= (1 << OE_DEPTH_BITS)) {
3600 warning(_("delta chain depth %d is too deep, forcing %d"),
3601 depth, (1 << OE_DEPTH_BITS) - 1);
3602 depth = (1 << OE_DEPTH_BITS) - 1;
3603 }
0cb3c142
NTND
3604 if (cache_max_small_delta_size >= (1U << OE_Z_DELTA_BITS)) {
3605 warning(_("pack.deltaCacheLimit is too high, forcing %d"),
3606 (1U << OE_Z_DELTA_BITS) - 1);
3607 cache_max_small_delta_size = (1U << OE_Z_DELTA_BITS) - 1;
3608 }
b5c0cbd8 3609
22f9b7f3 3610 strvec_push(&rp, "pack-objects");
99fb6e04
NTND
3611 if (thin) {
3612 use_internal_rev_list = 1;
22f9b7f3 3613 strvec_push(&rp, shallow
2dacf26d 3614 ? "--objects-edge-aggressive"
3615 : "--objects-edge");
99fb6e04 3616 } else
22f9b7f3 3617 strvec_push(&rp, "--objects");
b5d97e6b 3618
99fb6e04
NTND
3619 if (rev_list_all) {
3620 use_internal_rev_list = 1;
22f9b7f3 3621 strvec_push(&rp, "--all");
99fb6e04
NTND
3622 }
3623 if (rev_list_reflog) {
3624 use_internal_rev_list = 1;
22f9b7f3 3625 strvec_push(&rp, "--reflog");
99fb6e04 3626 }
c90f9e13
JK
3627 if (rev_list_index) {
3628 use_internal_rev_list = 1;
22f9b7f3 3629 strvec_push(&rp, "--indexed-objects");
99fb6e04
NTND
3630 }
3631 if (rev_list_unpacked) {
3632 use_internal_rev_list = 1;
22f9b7f3 3633 strvec_push(&rp, "--unpacked");
99fb6e04 3634 }
b5d97e6b 3635
0c16cd49
JT
3636 if (exclude_promisor_objects) {
3637 use_internal_rev_list = 1;
3638 fetch_if_missing = 0;
22f9b7f3 3639 strvec_push(&rp, "--exclude-promisor-objects");
0c16cd49 3640 }
58bd77b6
NTND
3641 if (unpack_unreachable || keep_unreachable || pack_loose_unreachable)
3642 use_internal_rev_list = 1;
0c16cd49 3643
99fb6e04
NTND
3644 if (!reuse_object)
3645 reuse_delta = 0;
3646 if (pack_compression_level == -1)
3647 pack_compression_level = Z_DEFAULT_COMPRESSION;
3648 else if (pack_compression_level < 0 || pack_compression_level > Z_BEST_COMPRESSION)
f616db6a 3649 die(_("bad pack compression level %d"), pack_compression_level);
0c45d258
JH
3650
3651 if (!delta_search_threads) /* --threads=0 means autodetect */
3652 delta_search_threads = online_cpus();
3653
9c897c5c 3654 if (!HAVE_THREADS && delta_search_threads != 1)
f616db6a 3655 warning(_("no threads support, ignoring --threads"));
2b84b5a8
JS
3656 if (!pack_to_stdout && !pack_size_limit)
3657 pack_size_limit = pack_size_limit_cfg;
01c12a23 3658 if (pack_to_stdout && pack_size_limit)
f616db6a 3659 die(_("--max-pack-size cannot be used to build a pack for transfer"));
07cf0f24 3660 if (pack_size_limit && pack_size_limit < 1024*1024) {
f616db6a 3661 warning(_("minimum pack size limit is 1 MiB"));
07cf0f24
NP
3662 pack_size_limit = 1024*1024;
3663 }
01c12a23 3664
8d1d8f83 3665 if (!pack_to_stdout && thin)
f616db6a 3666 die(_("--thin cannot be used to build an indexable pack"));
b5d97e6b 3667
ca11b212 3668 if (keep_unreachable && unpack_unreachable)
f616db6a 3669 die(_("--keep-unreachable and --unpack-unreachable are incompatible"));
b1e757f3
JK
3670 if (!rev_list_all || !rev_list_reflog || !rev_list_index)
3671 unpack_unreachable_expiration = 0;
ca11b212 3672
9535ce73
JH
3673 if (filter_options.choice) {
3674 if (!pack_to_stdout)
f616db6a 3675 die(_("cannot use --filter without --stdout"));
9535ce73
JH
3676 }
3677
645c432d
KS
3678 /*
3679 * "soft" reasons not to use bitmaps - for on-disk repack by default we want
3680 *
3681 * - to produce good pack (with bitmap index not-yet-packed objects are
3682 * packed in suboptimal order).
3683 *
3684 * - to use more robust pack-generation codepath (avoiding possible
3685 * bugs in bitmap code and possible bitmap index corruption).
3686 */
3687 if (!pack_to_stdout)
3688 use_bitmap_index_default = 0;
3689
3690 if (use_bitmap_index < 0)
3691 use_bitmap_index = use_bitmap_index_default;
3692
3693 /* "hard" reasons not to use bitmaps; these just won't work at all */
c8813487 3694 if (!use_internal_rev_list || (!pack_to_stdout && write_bitmap_index) || is_repository_shallow(the_repository))
6b8fda2d
VM
3695 use_bitmap_index = 0;
3696
7cc8f971
VM
3697 if (pack_to_stdout || !rev_list_all)
3698 write_bitmap_index = 0;
3699
28b8a730 3700 if (use_delta_islands)
22f9b7f3 3701 strvec_push(&rp, "--topo-order");
28b8a730 3702
4f366275
NP
3703 if (progress && all_progress_implied)
3704 progress = 2;
3705
ed7e5fc3
NTND
3706 add_extra_kept_packs(&keep_pack_list);
3707 if (ignore_packed_keep_on_disk) {
56dfeb62 3708 struct packed_git *p;
454ea2e4 3709 for (p = get_all_packs(the_repository); p; p = p->next)
56dfeb62
JK
3710 if (p->pack_local && p->pack_keep)
3711 break;
3712 if (!p) /* no keep-able packs found */
ed7e5fc3 3713 ignore_packed_keep_on_disk = 0;
56dfeb62
JK
3714 }
3715 if (local) {
3716 /*
ed7e5fc3
NTND
3717 * unlike ignore_packed_keep_on_disk above, we do not
3718 * want to unset "local" based on looking at packs, as
3719 * it also covers non-local objects
56dfeb62
JK
3720 */
3721 struct packed_git *p;
454ea2e4 3722 for (p = get_all_packs(the_repository); p; p = p->next) {
56dfeb62
JK
3723 if (!p->pack_local) {
3724 have_non_local_packs = 1;
3725 break;
3726 }
3727 }
3728 }
b5d97e6b 3729
ae417807
DS
3730 trace2_region_enter("pack-objects", "enumerate-objects",
3731 the_repository);
7c141127 3732 prepare_packing_data(the_repository, &to_pack);
43fa44fa 3733
13aaf148 3734 if (progress)
5af05043 3735 progress_state = start_progress(_("Enumerating objects"), 0);
b5d97e6b
JH
3736 if (!use_internal_rev_list)
3737 read_object_list_from_stdin();
8d1d8f83 3738 else {
d70a9eb6 3739 get_object_list(rp.nr, rp.v);
22f9b7f3 3740 strvec_clear(&rp);
8d1d8f83 3741 }
0ef95f72 3742 cleanup_preferred_base();
d155254c
MH
3743 if (include_tag && nr_result)
3744 for_each_ref(add_ref_tag, NULL);
4d4fcc54 3745 stop_progress(&progress_state);
ae417807
DS
3746 trace2_region_leave("pack-objects", "enumerate-objects",
3747 the_repository);
96a02f8f 3748
f0b0af1b 3749 if (non_empty && !nr_result)
1c4a2912 3750 return 0;
ae417807
DS
3751 if (nr_result) {
3752 trace2_region_enter("pack-objects", "prepare-pack",
3753 the_repository);
f7ae6a93 3754 prepare_pack(window, depth);
ae417807
DS
3755 trace2_region_leave("pack-objects", "prepare-pack",
3756 the_repository);
3757 }
3758
3759 trace2_region_enter("pack-objects", "write-pack-file", the_repository);
dd4b732d 3760 write_excluded_by_configs();
d01fb92f 3761 write_pack_file();
ae417807
DS
3762 trace2_region_leave("pack-objects", "write-pack-file", the_repository);
3763
ab7cd7bb 3764 if (progress)
f616db6a
NTND
3765 fprintf_ln(stderr,
3766 _("Total %"PRIu32" (delta %"PRIu32"),"
bab28d9f
JK
3767 " reused %"PRIu32" (delta %"PRIu32"),"
3768 " pack-reused %"PRIu32),
3769 written, written_delta, reused, reused_delta,
3770 reuse_packfile_objects);
c323ac7d
LT
3771 return 0;
3772}