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