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