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