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