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