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