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