ci: reintroduce prevention from perforce being quarantined in macOS
[git/debian.git] / builtin / pack-objects.c
blob014dcd4bc98459315b6fbac672df828e06299be0
1 #include "builtin.h"
2 #include "cache.h"
3 #include "repository.h"
4 #include "config.h"
5 #include "attr.h"
6 #include "object.h"
7 #include "blob.h"
8 #include "commit.h"
9 #include "tag.h"
10 #include "tree.h"
11 #include "delta.h"
12 #include "pack.h"
13 #include "pack-revindex.h"
14 #include "csum-file.h"
15 #include "tree-walk.h"
16 #include "diff.h"
17 #include "revision.h"
18 #include "list-objects.h"
19 #include "list-objects-filter.h"
20 #include "list-objects-filter-options.h"
21 #include "pack-objects.h"
22 #include "progress.h"
23 #include "refs.h"
24 #include "streaming.h"
25 #include "thread-utils.h"
26 #include "pack-bitmap.h"
27 #include "delta-islands.h"
28 #include "reachable.h"
29 #include "oid-array.h"
30 #include "strvec.h"
31 #include "list.h"
32 #include "packfile.h"
33 #include "object-store.h"
34 #include "dir.h"
35 #include "midx.h"
36 #include "trace2.h"
37 #include "shallow.h"
38 #include "promisor-remote.h"
41 * Objects we are going to pack are collected in the `to_pack` structure.
42 * It contains an array (dynamically expanded) of the object data, and a map
43 * that can resolve SHA1s to their position in the array.
45 static struct packing_data to_pack;
47 static inline struct object_entry *oe_delta(
48 const struct packing_data *pack,
49 const struct object_entry *e)
51 if (!e->delta_idx)
52 return NULL;
53 if (e->ext_base)
54 return &pack->ext_bases[e->delta_idx - 1];
55 else
56 return &pack->objects[e->delta_idx - 1];
59 static inline unsigned long oe_delta_size(struct packing_data *pack,
60 const struct object_entry *e)
62 if (e->delta_size_valid)
63 return e->delta_size_;
66 * pack->delta_size[] can't be NULL because oe_set_delta_size()
67 * must have been called when a new delta is saved with
68 * oe_set_delta().
69 * If oe_delta() returns NULL (i.e. default state, which means
70 * delta_size_valid is also false), then the caller must never
71 * call oe_delta_size().
73 return pack->delta_size[e - pack->objects];
76 unsigned long oe_get_size_slow(struct packing_data *pack,
77 const struct object_entry *e);
79 static inline unsigned long oe_size(struct packing_data *pack,
80 const struct object_entry *e)
82 if (e->size_valid)
83 return e->size_;
85 return oe_get_size_slow(pack, e);
88 static inline void oe_set_delta(struct packing_data *pack,
89 struct object_entry *e,
90 struct object_entry *delta)
92 if (delta)
93 e->delta_idx = (delta - pack->objects) + 1;
94 else
95 e->delta_idx = 0;
98 static inline struct object_entry *oe_delta_sibling(
99 const struct packing_data *pack,
100 const struct object_entry *e)
102 if (e->delta_sibling_idx)
103 return &pack->objects[e->delta_sibling_idx - 1];
104 return NULL;
107 static inline struct object_entry *oe_delta_child(
108 const struct packing_data *pack,
109 const struct object_entry *e)
111 if (e->delta_child_idx)
112 return &pack->objects[e->delta_child_idx - 1];
113 return NULL;
116 static inline void oe_set_delta_child(struct packing_data *pack,
117 struct object_entry *e,
118 struct object_entry *delta)
120 if (delta)
121 e->delta_child_idx = (delta - pack->objects) + 1;
122 else
123 e->delta_child_idx = 0;
126 static inline void oe_set_delta_sibling(struct packing_data *pack,
127 struct object_entry *e,
128 struct object_entry *delta)
130 if (delta)
131 e->delta_sibling_idx = (delta - pack->objects) + 1;
132 else
133 e->delta_sibling_idx = 0;
136 static inline void oe_set_size(struct packing_data *pack,
137 struct object_entry *e,
138 unsigned long size)
140 if (size < pack->oe_size_limit) {
141 e->size_ = size;
142 e->size_valid = 1;
143 } else {
144 e->size_valid = 0;
145 if (oe_get_size_slow(pack, e) != size)
146 BUG("'size' is supposed to be the object size!");
150 static inline void oe_set_delta_size(struct packing_data *pack,
151 struct object_entry *e,
152 unsigned long size)
154 if (size < pack->oe_delta_size_limit) {
155 e->delta_size_ = size;
156 e->delta_size_valid = 1;
157 } else {
158 packing_data_lock(pack);
159 if (!pack->delta_size)
160 ALLOC_ARRAY(pack->delta_size, pack->nr_alloc);
161 packing_data_unlock(pack);
163 pack->delta_size[e - pack->objects] = size;
164 e->delta_size_valid = 0;
168 #define IN_PACK(obj) oe_in_pack(&to_pack, obj)
169 #define SIZE(obj) oe_size(&to_pack, obj)
170 #define SET_SIZE(obj,size) oe_set_size(&to_pack, obj, size)
171 #define DELTA_SIZE(obj) oe_delta_size(&to_pack, obj)
172 #define DELTA(obj) oe_delta(&to_pack, obj)
173 #define DELTA_CHILD(obj) oe_delta_child(&to_pack, obj)
174 #define DELTA_SIBLING(obj) oe_delta_sibling(&to_pack, obj)
175 #define SET_DELTA(obj, val) oe_set_delta(&to_pack, obj, val)
176 #define SET_DELTA_EXT(obj, oid) oe_set_delta_ext(&to_pack, obj, oid)
177 #define SET_DELTA_SIZE(obj, val) oe_set_delta_size(&to_pack, obj, val)
178 #define SET_DELTA_CHILD(obj, val) oe_set_delta_child(&to_pack, obj, val)
179 #define SET_DELTA_SIBLING(obj, val) oe_set_delta_sibling(&to_pack, obj, val)
181 static const char *pack_usage[] = {
182 N_("git pack-objects --stdout [<options>...] [< <ref-list> | < <object-list>]"),
183 N_("git pack-objects [<options>...] <base-name> [< <ref-list> | < <object-list>]"),
184 NULL
187 static struct pack_idx_entry **written_list;
188 static uint32_t nr_result, nr_written, nr_seen;
189 static struct bitmap_index *bitmap_git;
190 static uint32_t write_layer;
192 static int non_empty;
193 static int reuse_delta = 1, reuse_object = 1;
194 static int keep_unreachable, unpack_unreachable, include_tag;
195 static timestamp_t unpack_unreachable_expiration;
196 static int pack_loose_unreachable;
197 static int local;
198 static int have_non_local_packs;
199 static int incremental;
200 static int ignore_packed_keep_on_disk;
201 static int ignore_packed_keep_in_core;
202 static int allow_ofs_delta;
203 static struct pack_idx_option pack_idx_opts;
204 static const char *base_name;
205 static int progress = 1;
206 static int window = 10;
207 static unsigned long pack_size_limit;
208 static int depth = 50;
209 static int delta_search_threads;
210 static int pack_to_stdout;
211 static int sparse;
212 static int thin;
213 static int num_preferred_base;
214 static struct progress *progress_state;
216 static struct packed_git *reuse_packfile;
217 static uint32_t reuse_packfile_objects;
218 static struct bitmap *reuse_packfile_bitmap;
220 static int use_bitmap_index_default = 1;
221 static int use_bitmap_index = -1;
222 static int allow_pack_reuse = 1;
223 static enum {
224 WRITE_BITMAP_FALSE = 0,
225 WRITE_BITMAP_QUIET,
226 WRITE_BITMAP_TRUE,
227 } write_bitmap_index;
228 static uint16_t write_bitmap_options = BITMAP_OPT_HASH_CACHE;
230 static int exclude_promisor_objects;
232 static int use_delta_islands;
234 static unsigned long delta_cache_size = 0;
235 static unsigned long max_delta_cache_size = DEFAULT_DELTA_CACHE_SIZE;
236 static unsigned long cache_max_small_delta_size = 1000;
238 static unsigned long window_memory_limit = 0;
240 static struct string_list uri_protocols = STRING_LIST_INIT_NODUP;
242 enum missing_action {
243 MA_ERROR = 0, /* fail if any missing objects are encountered */
244 MA_ALLOW_ANY, /* silently allow ALL missing objects */
245 MA_ALLOW_PROMISOR, /* silently allow all missing PROMISOR objects */
247 static enum missing_action arg_missing_action;
248 static show_object_fn fn_show_object;
250 struct configured_exclusion {
251 struct oidmap_entry e;
252 char *pack_hash_hex;
253 char *uri;
255 static struct oidmap configured_exclusions;
257 static struct oidset excluded_by_config;
260 * stats
262 static uint32_t written, written_delta;
263 static uint32_t reused, reused_delta;
266 * Indexed commits
268 static struct commit **indexed_commits;
269 static unsigned int indexed_commits_nr;
270 static unsigned int indexed_commits_alloc;
272 static void index_commit_for_bitmap(struct commit *commit)
274 if (indexed_commits_nr >= indexed_commits_alloc) {
275 indexed_commits_alloc = (indexed_commits_alloc + 32) * 2;
276 REALLOC_ARRAY(indexed_commits, indexed_commits_alloc);
279 indexed_commits[indexed_commits_nr++] = commit;
282 static void *get_delta(struct object_entry *entry)
284 unsigned long size, base_size, delta_size;
285 void *buf, *base_buf, *delta_buf;
286 enum object_type type;
288 buf = read_object_file(&entry->idx.oid, &type, &size);
289 if (!buf)
290 die(_("unable to read %s"), oid_to_hex(&entry->idx.oid));
291 base_buf = read_object_file(&DELTA(entry)->idx.oid, &type,
292 &base_size);
293 if (!base_buf)
294 die("unable to read %s",
295 oid_to_hex(&DELTA(entry)->idx.oid));
296 delta_buf = diff_delta(base_buf, base_size,
297 buf, size, &delta_size, 0);
299 * We successfully computed this delta once but dropped it for
300 * memory reasons. Something is very wrong if this time we
301 * recompute and create a different delta.
303 if (!delta_buf || delta_size != DELTA_SIZE(entry))
304 BUG("delta size changed");
305 free(buf);
306 free(base_buf);
307 return delta_buf;
310 static unsigned long do_compress(void **pptr, unsigned long size)
312 git_zstream stream;
313 void *in, *out;
314 unsigned long maxsize;
316 git_deflate_init(&stream, pack_compression_level);
317 maxsize = git_deflate_bound(&stream, size);
319 in = *pptr;
320 out = xmalloc(maxsize);
321 *pptr = out;
323 stream.next_in = in;
324 stream.avail_in = size;
325 stream.next_out = out;
326 stream.avail_out = maxsize;
327 while (git_deflate(&stream, Z_FINISH) == Z_OK)
328 ; /* nothing */
329 git_deflate_end(&stream);
331 free(in);
332 return stream.total_out;
335 static unsigned long write_large_blob_data(struct git_istream *st, struct hashfile *f,
336 const struct object_id *oid)
338 git_zstream stream;
339 unsigned char ibuf[1024 * 16];
340 unsigned char obuf[1024 * 16];
341 unsigned long olen = 0;
343 git_deflate_init(&stream, pack_compression_level);
345 for (;;) {
346 ssize_t readlen;
347 int zret = Z_OK;
348 readlen = read_istream(st, ibuf, sizeof(ibuf));
349 if (readlen == -1)
350 die(_("unable to read %s"), oid_to_hex(oid));
352 stream.next_in = ibuf;
353 stream.avail_in = readlen;
354 while ((stream.avail_in || readlen == 0) &&
355 (zret == Z_OK || zret == Z_BUF_ERROR)) {
356 stream.next_out = obuf;
357 stream.avail_out = sizeof(obuf);
358 zret = git_deflate(&stream, readlen ? 0 : Z_FINISH);
359 hashwrite(f, obuf, stream.next_out - obuf);
360 olen += stream.next_out - obuf;
362 if (stream.avail_in)
363 die(_("deflate error (%d)"), zret);
364 if (readlen == 0) {
365 if (zret != Z_STREAM_END)
366 die(_("deflate error (%d)"), zret);
367 break;
370 git_deflate_end(&stream);
371 return olen;
375 * we are going to reuse the existing object data as is. make
376 * sure it is not corrupt.
378 static int check_pack_inflate(struct packed_git *p,
379 struct pack_window **w_curs,
380 off_t offset,
381 off_t len,
382 unsigned long expect)
384 git_zstream stream;
385 unsigned char fakebuf[4096], *in;
386 int st;
388 memset(&stream, 0, sizeof(stream));
389 git_inflate_init(&stream);
390 do {
391 in = use_pack(p, w_curs, offset, &stream.avail_in);
392 stream.next_in = in;
393 stream.next_out = fakebuf;
394 stream.avail_out = sizeof(fakebuf);
395 st = git_inflate(&stream, Z_FINISH);
396 offset += stream.next_in - in;
397 } while (st == Z_OK || st == Z_BUF_ERROR);
398 git_inflate_end(&stream);
399 return (st == Z_STREAM_END &&
400 stream.total_out == expect &&
401 stream.total_in == len) ? 0 : -1;
404 static void copy_pack_data(struct hashfile *f,
405 struct packed_git *p,
406 struct pack_window **w_curs,
407 off_t offset,
408 off_t len)
410 unsigned char *in;
411 unsigned long avail;
413 while (len) {
414 in = use_pack(p, w_curs, offset, &avail);
415 if (avail > len)
416 avail = (unsigned long)len;
417 hashwrite(f, in, avail);
418 offset += avail;
419 len -= avail;
423 static inline int oe_size_greater_than(struct packing_data *pack,
424 const struct object_entry *lhs,
425 unsigned long rhs)
427 if (lhs->size_valid)
428 return lhs->size_ > rhs;
429 if (rhs < pack->oe_size_limit) /* rhs < 2^x <= lhs ? */
430 return 1;
431 return oe_get_size_slow(pack, lhs) > rhs;
434 /* Return 0 if we will bust the pack-size limit */
435 static unsigned long write_no_reuse_object(struct hashfile *f, struct object_entry *entry,
436 unsigned long limit, int usable_delta)
438 unsigned long size, datalen;
439 unsigned char header[MAX_PACK_OBJECT_HEADER],
440 dheader[MAX_PACK_OBJECT_HEADER];
441 unsigned hdrlen;
442 enum object_type type;
443 void *buf;
444 struct git_istream *st = NULL;
445 const unsigned hashsz = the_hash_algo->rawsz;
447 if (!usable_delta) {
448 if (oe_type(entry) == OBJ_BLOB &&
449 oe_size_greater_than(&to_pack, entry, big_file_threshold) &&
450 (st = open_istream(the_repository, &entry->idx.oid, &type,
451 &size, NULL)) != NULL)
452 buf = NULL;
453 else {
454 buf = read_object_file(&entry->idx.oid, &type, &size);
455 if (!buf)
456 die(_("unable to read %s"),
457 oid_to_hex(&entry->idx.oid));
460 * make sure no cached delta data remains from a
461 * previous attempt before a pack split occurred.
463 FREE_AND_NULL(entry->delta_data);
464 entry->z_delta_size = 0;
465 } else if (entry->delta_data) {
466 size = DELTA_SIZE(entry);
467 buf = entry->delta_data;
468 entry->delta_data = NULL;
469 type = (allow_ofs_delta && DELTA(entry)->idx.offset) ?
470 OBJ_OFS_DELTA : OBJ_REF_DELTA;
471 } else {
472 buf = get_delta(entry);
473 size = DELTA_SIZE(entry);
474 type = (allow_ofs_delta && DELTA(entry)->idx.offset) ?
475 OBJ_OFS_DELTA : OBJ_REF_DELTA;
478 if (st) /* large blob case, just assume we don't compress well */
479 datalen = size;
480 else if (entry->z_delta_size)
481 datalen = entry->z_delta_size;
482 else
483 datalen = do_compress(&buf, size);
486 * The object header is a byte of 'type' followed by zero or
487 * more bytes of length.
489 hdrlen = encode_in_pack_object_header(header, sizeof(header),
490 type, size);
492 if (type == OBJ_OFS_DELTA) {
494 * Deltas with relative base contain an additional
495 * encoding of the relative offset for the delta
496 * base from this object's position in the pack.
498 off_t ofs = entry->idx.offset - DELTA(entry)->idx.offset;
499 unsigned pos = sizeof(dheader) - 1;
500 dheader[pos] = ofs & 127;
501 while (ofs >>= 7)
502 dheader[--pos] = 128 | (--ofs & 127);
503 if (limit && hdrlen + sizeof(dheader) - pos + datalen + hashsz >= limit) {
504 if (st)
505 close_istream(st);
506 free(buf);
507 return 0;
509 hashwrite(f, header, hdrlen);
510 hashwrite(f, dheader + pos, sizeof(dheader) - pos);
511 hdrlen += sizeof(dheader) - pos;
512 } else if (type == OBJ_REF_DELTA) {
514 * Deltas with a base reference contain
515 * additional bytes for the base object ID.
517 if (limit && hdrlen + hashsz + datalen + hashsz >= limit) {
518 if (st)
519 close_istream(st);
520 free(buf);
521 return 0;
523 hashwrite(f, header, hdrlen);
524 hashwrite(f, DELTA(entry)->idx.oid.hash, hashsz);
525 hdrlen += hashsz;
526 } else {
527 if (limit && hdrlen + datalen + hashsz >= limit) {
528 if (st)
529 close_istream(st);
530 free(buf);
531 return 0;
533 hashwrite(f, header, hdrlen);
535 if (st) {
536 datalen = write_large_blob_data(st, f, &entry->idx.oid);
537 close_istream(st);
538 } else {
539 hashwrite(f, buf, datalen);
540 free(buf);
543 return hdrlen + datalen;
546 /* Return 0 if we will bust the pack-size limit */
547 static off_t write_reuse_object(struct hashfile *f, struct object_entry *entry,
548 unsigned long limit, int usable_delta)
550 struct packed_git *p = IN_PACK(entry);
551 struct pack_window *w_curs = NULL;
552 uint32_t pos;
553 off_t offset;
554 enum object_type type = oe_type(entry);
555 off_t datalen;
556 unsigned char header[MAX_PACK_OBJECT_HEADER],
557 dheader[MAX_PACK_OBJECT_HEADER];
558 unsigned hdrlen;
559 const unsigned hashsz = the_hash_algo->rawsz;
560 unsigned long entry_size = SIZE(entry);
562 if (DELTA(entry))
563 type = (allow_ofs_delta && DELTA(entry)->idx.offset) ?
564 OBJ_OFS_DELTA : OBJ_REF_DELTA;
565 hdrlen = encode_in_pack_object_header(header, sizeof(header),
566 type, entry_size);
568 offset = entry->in_pack_offset;
569 if (offset_to_pack_pos(p, offset, &pos) < 0)
570 die(_("write_reuse_object: could not locate %s, expected at "
571 "offset %"PRIuMAX" in pack %s"),
572 oid_to_hex(&entry->idx.oid), (uintmax_t)offset,
573 p->pack_name);
574 datalen = pack_pos_to_offset(p, pos + 1) - offset;
575 if (!pack_to_stdout && p->index_version > 1 &&
576 check_pack_crc(p, &w_curs, offset, datalen,
577 pack_pos_to_index(p, pos))) {
578 error(_("bad packed object CRC for %s"),
579 oid_to_hex(&entry->idx.oid));
580 unuse_pack(&w_curs);
581 return write_no_reuse_object(f, entry, limit, usable_delta);
584 offset += entry->in_pack_header_size;
585 datalen -= entry->in_pack_header_size;
587 if (!pack_to_stdout && p->index_version == 1 &&
588 check_pack_inflate(p, &w_curs, offset, datalen, entry_size)) {
589 error(_("corrupt packed object for %s"),
590 oid_to_hex(&entry->idx.oid));
591 unuse_pack(&w_curs);
592 return write_no_reuse_object(f, entry, limit, usable_delta);
595 if (type == OBJ_OFS_DELTA) {
596 off_t ofs = entry->idx.offset - DELTA(entry)->idx.offset;
597 unsigned pos = sizeof(dheader) - 1;
598 dheader[pos] = ofs & 127;
599 while (ofs >>= 7)
600 dheader[--pos] = 128 | (--ofs & 127);
601 if (limit && hdrlen + sizeof(dheader) - pos + datalen + hashsz >= limit) {
602 unuse_pack(&w_curs);
603 return 0;
605 hashwrite(f, header, hdrlen);
606 hashwrite(f, dheader + pos, sizeof(dheader) - pos);
607 hdrlen += sizeof(dheader) - pos;
608 reused_delta++;
609 } else if (type == OBJ_REF_DELTA) {
610 if (limit && hdrlen + hashsz + datalen + hashsz >= limit) {
611 unuse_pack(&w_curs);
612 return 0;
614 hashwrite(f, header, hdrlen);
615 hashwrite(f, DELTA(entry)->idx.oid.hash, hashsz);
616 hdrlen += hashsz;
617 reused_delta++;
618 } else {
619 if (limit && hdrlen + datalen + hashsz >= limit) {
620 unuse_pack(&w_curs);
621 return 0;
623 hashwrite(f, header, hdrlen);
625 copy_pack_data(f, p, &w_curs, offset, datalen);
626 unuse_pack(&w_curs);
627 reused++;
628 return hdrlen + datalen;
631 /* Return 0 if we will bust the pack-size limit */
632 static off_t write_object(struct hashfile *f,
633 struct object_entry *entry,
634 off_t write_offset)
636 unsigned long limit;
637 off_t len;
638 int usable_delta, to_reuse;
640 if (!pack_to_stdout)
641 crc32_begin(f);
643 /* apply size limit if limited packsize and not first object */
644 if (!pack_size_limit || !nr_written)
645 limit = 0;
646 else if (pack_size_limit <= write_offset)
648 * the earlier object did not fit the limit; avoid
649 * mistaking this with unlimited (i.e. limit = 0).
651 limit = 1;
652 else
653 limit = pack_size_limit - write_offset;
655 if (!DELTA(entry))
656 usable_delta = 0; /* no delta */
657 else if (!pack_size_limit)
658 usable_delta = 1; /* unlimited packfile */
659 else if (DELTA(entry)->idx.offset == (off_t)-1)
660 usable_delta = 0; /* base was written to another pack */
661 else if (DELTA(entry)->idx.offset)
662 usable_delta = 1; /* base already exists in this pack */
663 else
664 usable_delta = 0; /* base could end up in another pack */
666 if (!reuse_object)
667 to_reuse = 0; /* explicit */
668 else if (!IN_PACK(entry))
669 to_reuse = 0; /* can't reuse what we don't have */
670 else if (oe_type(entry) == OBJ_REF_DELTA ||
671 oe_type(entry) == OBJ_OFS_DELTA)
672 /* check_object() decided it for us ... */
673 to_reuse = usable_delta;
674 /* ... but pack split may override that */
675 else if (oe_type(entry) != entry->in_pack_type)
676 to_reuse = 0; /* pack has delta which is unusable */
677 else if (DELTA(entry))
678 to_reuse = 0; /* we want to pack afresh */
679 else
680 to_reuse = 1; /* we have it in-pack undeltified,
681 * and we do not need to deltify it.
684 if (!to_reuse)
685 len = write_no_reuse_object(f, entry, limit, usable_delta);
686 else
687 len = write_reuse_object(f, entry, limit, usable_delta);
688 if (!len)
689 return 0;
691 if (usable_delta)
692 written_delta++;
693 written++;
694 if (!pack_to_stdout)
695 entry->idx.crc32 = crc32_end(f);
696 return len;
699 enum write_one_status {
700 WRITE_ONE_SKIP = -1, /* already written */
701 WRITE_ONE_BREAK = 0, /* writing this will bust the limit; not written */
702 WRITE_ONE_WRITTEN = 1, /* normal */
703 WRITE_ONE_RECURSIVE = 2 /* already scheduled to be written */
706 static enum write_one_status write_one(struct hashfile *f,
707 struct object_entry *e,
708 off_t *offset)
710 off_t size;
711 int recursing;
714 * we set offset to 1 (which is an impossible value) to mark
715 * the fact that this object is involved in "write its base
716 * first before writing a deltified object" recursion.
718 recursing = (e->idx.offset == 1);
719 if (recursing) {
720 warning(_("recursive delta detected for object %s"),
721 oid_to_hex(&e->idx.oid));
722 return WRITE_ONE_RECURSIVE;
723 } else if (e->idx.offset || e->preferred_base) {
724 /* offset is non zero if object is written already. */
725 return WRITE_ONE_SKIP;
728 /* if we are deltified, write out base object first. */
729 if (DELTA(e)) {
730 e->idx.offset = 1; /* now recurse */
731 switch (write_one(f, DELTA(e), offset)) {
732 case WRITE_ONE_RECURSIVE:
733 /* we cannot depend on this one */
734 SET_DELTA(e, NULL);
735 break;
736 default:
737 break;
738 case WRITE_ONE_BREAK:
739 e->idx.offset = recursing;
740 return WRITE_ONE_BREAK;
744 e->idx.offset = *offset;
745 size = write_object(f, e, *offset);
746 if (!size) {
747 e->idx.offset = recursing;
748 return WRITE_ONE_BREAK;
750 written_list[nr_written++] = &e->idx;
752 /* make sure off_t is sufficiently large not to wrap */
753 if (signed_add_overflows(*offset, size))
754 die(_("pack too large for current definition of off_t"));
755 *offset += size;
756 return WRITE_ONE_WRITTEN;
759 static int mark_tagged(const char *path, const struct object_id *oid, int flag,
760 void *cb_data)
762 struct object_id peeled;
763 struct object_entry *entry = packlist_find(&to_pack, oid);
765 if (entry)
766 entry->tagged = 1;
767 if (!peel_iterated_oid(oid, &peeled)) {
768 entry = packlist_find(&to_pack, &peeled);
769 if (entry)
770 entry->tagged = 1;
772 return 0;
775 static inline unsigned char oe_layer(struct packing_data *pack,
776 struct object_entry *e)
778 if (!pack->layer)
779 return 0;
780 return pack->layer[e - pack->objects];
783 static inline void add_to_write_order(struct object_entry **wo,
784 unsigned int *endp,
785 struct object_entry *e)
787 if (e->filled || oe_layer(&to_pack, e) != write_layer)
788 return;
789 wo[(*endp)++] = e;
790 e->filled = 1;
793 static void add_descendants_to_write_order(struct object_entry **wo,
794 unsigned int *endp,
795 struct object_entry *e)
797 int add_to_order = 1;
798 while (e) {
799 if (add_to_order) {
800 struct object_entry *s;
801 /* add this node... */
802 add_to_write_order(wo, endp, e);
803 /* all its siblings... */
804 for (s = DELTA_SIBLING(e); s; s = DELTA_SIBLING(s)) {
805 add_to_write_order(wo, endp, s);
808 /* drop down a level to add left subtree nodes if possible */
809 if (DELTA_CHILD(e)) {
810 add_to_order = 1;
811 e = DELTA_CHILD(e);
812 } else {
813 add_to_order = 0;
814 /* our sibling might have some children, it is next */
815 if (DELTA_SIBLING(e)) {
816 e = DELTA_SIBLING(e);
817 continue;
819 /* go back to our parent node */
820 e = DELTA(e);
821 while (e && !DELTA_SIBLING(e)) {
822 /* we're on the right side of a subtree, keep
823 * going up until we can go right again */
824 e = DELTA(e);
826 if (!e) {
827 /* done- we hit our original root node */
828 return;
830 /* pass it off to sibling at this level */
831 e = DELTA_SIBLING(e);
836 static void add_family_to_write_order(struct object_entry **wo,
837 unsigned int *endp,
838 struct object_entry *e)
840 struct object_entry *root;
842 for (root = e; DELTA(root); root = DELTA(root))
843 ; /* nothing */
844 add_descendants_to_write_order(wo, endp, root);
847 static void compute_layer_order(struct object_entry **wo, unsigned int *wo_end)
849 unsigned int i, last_untagged;
850 struct object_entry *objects = to_pack.objects;
852 for (i = 0; i < to_pack.nr_objects; i++) {
853 if (objects[i].tagged)
854 break;
855 add_to_write_order(wo, wo_end, &objects[i]);
857 last_untagged = i;
860 * Then fill all the tagged tips.
862 for (; i < to_pack.nr_objects; i++) {
863 if (objects[i].tagged)
864 add_to_write_order(wo, wo_end, &objects[i]);
868 * And then all remaining commits and tags.
870 for (i = last_untagged; i < to_pack.nr_objects; i++) {
871 if (oe_type(&objects[i]) != OBJ_COMMIT &&
872 oe_type(&objects[i]) != OBJ_TAG)
873 continue;
874 add_to_write_order(wo, wo_end, &objects[i]);
878 * And then all the trees.
880 for (i = last_untagged; i < to_pack.nr_objects; i++) {
881 if (oe_type(&objects[i]) != OBJ_TREE)
882 continue;
883 add_to_write_order(wo, wo_end, &objects[i]);
887 * Finally all the rest in really tight order
889 for (i = last_untagged; i < to_pack.nr_objects; i++) {
890 if (!objects[i].filled && oe_layer(&to_pack, &objects[i]) == write_layer)
891 add_family_to_write_order(wo, wo_end, &objects[i]);
895 static struct object_entry **compute_write_order(void)
897 uint32_t max_layers = 1;
898 unsigned int i, wo_end;
900 struct object_entry **wo;
901 struct object_entry *objects = to_pack.objects;
903 for (i = 0; i < to_pack.nr_objects; i++) {
904 objects[i].tagged = 0;
905 objects[i].filled = 0;
906 SET_DELTA_CHILD(&objects[i], NULL);
907 SET_DELTA_SIBLING(&objects[i], NULL);
911 * Fully connect delta_child/delta_sibling network.
912 * Make sure delta_sibling is sorted in the original
913 * recency order.
915 for (i = to_pack.nr_objects; i > 0;) {
916 struct object_entry *e = &objects[--i];
917 if (!DELTA(e))
918 continue;
919 /* Mark me as the first child */
920 e->delta_sibling_idx = DELTA(e)->delta_child_idx;
921 SET_DELTA_CHILD(DELTA(e), e);
925 * Mark objects that are at the tip of tags.
927 for_each_tag_ref(mark_tagged, NULL);
929 if (use_delta_islands)
930 max_layers = compute_pack_layers(&to_pack);
932 ALLOC_ARRAY(wo, to_pack.nr_objects);
933 wo_end = 0;
935 for (; write_layer < max_layers; ++write_layer)
936 compute_layer_order(wo, &wo_end);
938 if (wo_end != to_pack.nr_objects)
939 die(_("ordered %u objects, expected %"PRIu32),
940 wo_end, to_pack.nr_objects);
942 return wo;
947 * A reused set of objects. All objects in a chunk have the same
948 * relative position in the original packfile and the generated
949 * packfile.
952 static struct reused_chunk {
953 /* The offset of the first object of this chunk in the original
954 * packfile. */
955 off_t original;
956 /* The difference for "original" minus the offset of the first object of
957 * this chunk in the generated packfile. */
958 off_t difference;
959 } *reused_chunks;
960 static int reused_chunks_nr;
961 static int reused_chunks_alloc;
963 static void record_reused_object(off_t where, off_t offset)
965 if (reused_chunks_nr && reused_chunks[reused_chunks_nr-1].difference == offset)
966 return;
968 ALLOC_GROW(reused_chunks, reused_chunks_nr + 1,
969 reused_chunks_alloc);
970 reused_chunks[reused_chunks_nr].original = where;
971 reused_chunks[reused_chunks_nr].difference = offset;
972 reused_chunks_nr++;
976 * Binary search to find the chunk that "where" is in. Note
977 * that we're not looking for an exact match, just the first
978 * chunk that contains it (which implicitly ends at the start
979 * of the next chunk.
981 static off_t find_reused_offset(off_t where)
983 int lo = 0, hi = reused_chunks_nr;
984 while (lo < hi) {
985 int mi = lo + ((hi - lo) / 2);
986 if (where == reused_chunks[mi].original)
987 return reused_chunks[mi].difference;
988 if (where < reused_chunks[mi].original)
989 hi = mi;
990 else
991 lo = mi + 1;
995 * The first chunk starts at zero, so we can't have gone below
996 * there.
998 assert(lo);
999 return reused_chunks[lo-1].difference;
1002 static void write_reused_pack_one(size_t pos, struct hashfile *out,
1003 struct pack_window **w_curs)
1005 off_t offset, next, cur;
1006 enum object_type type;
1007 unsigned long size;
1009 offset = pack_pos_to_offset(reuse_packfile, pos);
1010 next = pack_pos_to_offset(reuse_packfile, pos + 1);
1012 record_reused_object(offset, offset - hashfile_total(out));
1014 cur = offset;
1015 type = unpack_object_header(reuse_packfile, w_curs, &cur, &size);
1016 assert(type >= 0);
1018 if (type == OBJ_OFS_DELTA) {
1019 off_t base_offset;
1020 off_t fixup;
1022 unsigned char header[MAX_PACK_OBJECT_HEADER];
1023 unsigned len;
1025 base_offset = get_delta_base(reuse_packfile, w_curs, &cur, type, offset);
1026 assert(base_offset != 0);
1028 /* Convert to REF_DELTA if we must... */
1029 if (!allow_ofs_delta) {
1030 uint32_t base_pos;
1031 struct object_id base_oid;
1033 if (offset_to_pack_pos(reuse_packfile, base_offset, &base_pos) < 0)
1034 die(_("expected object at offset %"PRIuMAX" "
1035 "in pack %s"),
1036 (uintmax_t)base_offset,
1037 reuse_packfile->pack_name);
1039 nth_packed_object_id(&base_oid, reuse_packfile,
1040 pack_pos_to_index(reuse_packfile, base_pos));
1042 len = encode_in_pack_object_header(header, sizeof(header),
1043 OBJ_REF_DELTA, size);
1044 hashwrite(out, header, len);
1045 hashwrite(out, base_oid.hash, the_hash_algo->rawsz);
1046 copy_pack_data(out, reuse_packfile, w_curs, cur, next - cur);
1047 return;
1050 /* Otherwise see if we need to rewrite the offset... */
1051 fixup = find_reused_offset(offset) -
1052 find_reused_offset(base_offset);
1053 if (fixup) {
1054 unsigned char ofs_header[10];
1055 unsigned i, ofs_len;
1056 off_t ofs = offset - base_offset - fixup;
1058 len = encode_in_pack_object_header(header, sizeof(header),
1059 OBJ_OFS_DELTA, size);
1061 i = sizeof(ofs_header) - 1;
1062 ofs_header[i] = ofs & 127;
1063 while (ofs >>= 7)
1064 ofs_header[--i] = 128 | (--ofs & 127);
1066 ofs_len = sizeof(ofs_header) - i;
1068 hashwrite(out, header, len);
1069 hashwrite(out, ofs_header + sizeof(ofs_header) - ofs_len, ofs_len);
1070 copy_pack_data(out, reuse_packfile, w_curs, cur, next - cur);
1071 return;
1074 /* ...otherwise we have no fixup, and can write it verbatim */
1077 copy_pack_data(out, reuse_packfile, w_curs, offset, next - offset);
1080 static size_t write_reused_pack_verbatim(struct hashfile *out,
1081 struct pack_window **w_curs)
1083 size_t pos = 0;
1085 while (pos < reuse_packfile_bitmap->word_alloc &&
1086 reuse_packfile_bitmap->words[pos] == (eword_t)~0)
1087 pos++;
1089 if (pos) {
1090 off_t to_write;
1092 written = (pos * BITS_IN_EWORD);
1093 to_write = pack_pos_to_offset(reuse_packfile, written)
1094 - sizeof(struct pack_header);
1096 /* We're recording one chunk, not one object. */
1097 record_reused_object(sizeof(struct pack_header), 0);
1098 hashflush(out);
1099 copy_pack_data(out, reuse_packfile, w_curs,
1100 sizeof(struct pack_header), to_write);
1102 display_progress(progress_state, written);
1104 return pos;
1107 static void write_reused_pack(struct hashfile *f)
1109 size_t i = 0;
1110 uint32_t offset;
1111 struct pack_window *w_curs = NULL;
1113 if (allow_ofs_delta)
1114 i = write_reused_pack_verbatim(f, &w_curs);
1116 for (; i < reuse_packfile_bitmap->word_alloc; ++i) {
1117 eword_t word = reuse_packfile_bitmap->words[i];
1118 size_t pos = (i * BITS_IN_EWORD);
1120 for (offset = 0; offset < BITS_IN_EWORD; ++offset) {
1121 if ((word >> offset) == 0)
1122 break;
1124 offset += ewah_bit_ctz64(word >> offset);
1126 * Can use bit positions directly, even for MIDX
1127 * bitmaps. See comment in try_partial_reuse()
1128 * for why.
1130 write_reused_pack_one(pos + offset, f, &w_curs);
1131 display_progress(progress_state, ++written);
1135 unuse_pack(&w_curs);
1138 static void write_excluded_by_configs(void)
1140 struct oidset_iter iter;
1141 const struct object_id *oid;
1143 oidset_iter_init(&excluded_by_config, &iter);
1144 while ((oid = oidset_iter_next(&iter))) {
1145 struct configured_exclusion *ex =
1146 oidmap_get(&configured_exclusions, oid);
1148 if (!ex)
1149 BUG("configured exclusion wasn't configured");
1150 write_in_full(1, ex->pack_hash_hex, strlen(ex->pack_hash_hex));
1151 write_in_full(1, " ", 1);
1152 write_in_full(1, ex->uri, strlen(ex->uri));
1153 write_in_full(1, "\n", 1);
1157 static const char no_split_warning[] = N_(
1158 "disabling bitmap writing, packs are split due to pack.packSizeLimit"
1161 static void write_pack_file(void)
1163 uint32_t i = 0, j;
1164 struct hashfile *f;
1165 off_t offset;
1166 uint32_t nr_remaining = nr_result;
1167 time_t last_mtime = 0;
1168 struct object_entry **write_order;
1170 if (progress > pack_to_stdout)
1171 progress_state = start_progress(_("Writing objects"), nr_result);
1172 ALLOC_ARRAY(written_list, to_pack.nr_objects);
1173 write_order = compute_write_order();
1175 do {
1176 unsigned char hash[GIT_MAX_RAWSZ];
1177 char *pack_tmp_name = NULL;
1179 if (pack_to_stdout)
1180 f = hashfd_throughput(1, "<stdout>", progress_state);
1181 else
1182 f = create_tmp_packfile(&pack_tmp_name);
1184 offset = write_pack_header(f, nr_remaining);
1186 if (reuse_packfile) {
1187 assert(pack_to_stdout);
1188 write_reused_pack(f);
1189 offset = hashfile_total(f);
1192 nr_written = 0;
1193 for (; i < to_pack.nr_objects; i++) {
1194 struct object_entry *e = write_order[i];
1195 if (write_one(f, e, &offset) == WRITE_ONE_BREAK)
1196 break;
1197 display_progress(progress_state, written);
1200 if (pack_to_stdout) {
1202 * We never fsync when writing to stdout since we may
1203 * not be writing to an actual pack file. For instance,
1204 * the upload-pack code passes a pipe here. Calling
1205 * fsync on a pipe results in unnecessary
1206 * synchronization with the reader on some platforms.
1208 finalize_hashfile(f, hash, FSYNC_COMPONENT_NONE,
1209 CSUM_HASH_IN_STREAM | CSUM_CLOSE);
1210 } else if (nr_written == nr_remaining) {
1211 finalize_hashfile(f, hash, FSYNC_COMPONENT_PACK,
1212 CSUM_HASH_IN_STREAM | CSUM_FSYNC | CSUM_CLOSE);
1213 } else {
1215 * If we wrote the wrong number of entries in the
1216 * header, rewrite it like in fast-import.
1219 int fd = finalize_hashfile(f, hash, FSYNC_COMPONENT_PACK, 0);
1220 fixup_pack_header_footer(fd, hash, pack_tmp_name,
1221 nr_written, hash, offset);
1222 close(fd);
1223 if (write_bitmap_index) {
1224 if (write_bitmap_index != WRITE_BITMAP_QUIET)
1225 warning(_(no_split_warning));
1226 write_bitmap_index = 0;
1230 if (!pack_to_stdout) {
1231 struct stat st;
1232 struct strbuf tmpname = STRBUF_INIT;
1233 char *idx_tmp_name = NULL;
1236 * Packs are runtime accessed in their mtime
1237 * order since newer packs are more likely to contain
1238 * younger objects. So if we are creating multiple
1239 * packs then we should modify the mtime of later ones
1240 * to preserve this property.
1242 if (stat(pack_tmp_name, &st) < 0) {
1243 warning_errno(_("failed to stat %s"), pack_tmp_name);
1244 } else if (!last_mtime) {
1245 last_mtime = st.st_mtime;
1246 } else {
1247 struct utimbuf utb;
1248 utb.actime = st.st_atime;
1249 utb.modtime = --last_mtime;
1250 if (utime(pack_tmp_name, &utb) < 0)
1251 warning_errno(_("failed utime() on %s"), pack_tmp_name);
1254 strbuf_addf(&tmpname, "%s-%s.", base_name,
1255 hash_to_hex(hash));
1257 if (write_bitmap_index) {
1258 bitmap_writer_set_checksum(hash);
1259 bitmap_writer_build_type_index(
1260 &to_pack, written_list, nr_written);
1263 stage_tmp_packfiles(&tmpname, pack_tmp_name,
1264 written_list, nr_written,
1265 &pack_idx_opts, hash, &idx_tmp_name);
1267 if (write_bitmap_index) {
1268 size_t tmpname_len = tmpname.len;
1270 strbuf_addstr(&tmpname, "bitmap");
1271 stop_progress(&progress_state);
1273 bitmap_writer_show_progress(progress);
1274 bitmap_writer_select_commits(indexed_commits, indexed_commits_nr, -1);
1275 if (bitmap_writer_build(&to_pack) < 0)
1276 die(_("failed to write bitmap index"));
1277 bitmap_writer_finish(written_list, nr_written,
1278 tmpname.buf, write_bitmap_options);
1279 write_bitmap_index = 0;
1280 strbuf_setlen(&tmpname, tmpname_len);
1283 rename_tmp_packfile_idx(&tmpname, &idx_tmp_name);
1285 free(idx_tmp_name);
1286 strbuf_release(&tmpname);
1287 free(pack_tmp_name);
1288 puts(hash_to_hex(hash));
1291 /* mark written objects as written to previous pack */
1292 for (j = 0; j < nr_written; j++) {
1293 written_list[j]->offset = (off_t)-1;
1295 nr_remaining -= nr_written;
1296 } while (nr_remaining && i < to_pack.nr_objects);
1298 free(written_list);
1299 free(write_order);
1300 stop_progress(&progress_state);
1301 if (written != nr_result)
1302 die(_("wrote %"PRIu32" objects while expecting %"PRIu32),
1303 written, nr_result);
1304 trace2_data_intmax("pack-objects", the_repository,
1305 "write_pack_file/wrote", nr_result);
1308 static int no_try_delta(const char *path)
1310 static struct attr_check *check;
1312 if (!check)
1313 check = attr_check_initl("delta", NULL);
1314 git_check_attr(the_repository->index, path, check);
1315 if (ATTR_FALSE(check->items[0].value))
1316 return 1;
1317 return 0;
1321 * When adding an object, check whether we have already added it
1322 * to our packing list. If so, we can skip. However, if we are
1323 * being asked to excludei t, but the previous mention was to include
1324 * it, make sure to adjust its flags and tweak our numbers accordingly.
1326 * As an optimization, we pass out the index position where we would have
1327 * found the item, since that saves us from having to look it up again a
1328 * few lines later when we want to add the new entry.
1330 static int have_duplicate_entry(const struct object_id *oid,
1331 int exclude)
1333 struct object_entry *entry;
1335 if (reuse_packfile_bitmap &&
1336 bitmap_walk_contains(bitmap_git, reuse_packfile_bitmap, oid))
1337 return 1;
1339 entry = packlist_find(&to_pack, oid);
1340 if (!entry)
1341 return 0;
1343 if (exclude) {
1344 if (!entry->preferred_base)
1345 nr_result--;
1346 entry->preferred_base = 1;
1349 return 1;
1352 static int want_found_object(const struct object_id *oid, int exclude,
1353 struct packed_git *p)
1355 if (exclude)
1356 return 1;
1357 if (incremental)
1358 return 0;
1361 * When asked to do --local (do not include an object that appears in a
1362 * pack we borrow from elsewhere) or --honor-pack-keep (do not include
1363 * an object that appears in a pack marked with .keep), finding a pack
1364 * that matches the criteria is sufficient for us to decide to omit it.
1365 * However, even if this pack does not satisfy the criteria, we need to
1366 * make sure no copy of this object appears in _any_ pack that makes us
1367 * to omit the object, so we need to check all the packs.
1369 * We can however first check whether these options can possibly matter;
1370 * if they do not matter we know we want the object in generated pack.
1371 * Otherwise, we signal "-1" at the end to tell the caller that we do
1372 * not know either way, and it needs to check more packs.
1376 * Objects in packs borrowed from elsewhere are discarded regardless of
1377 * if they appear in other packs that weren't borrowed.
1379 if (local && !p->pack_local)
1380 return 0;
1383 * Then handle .keep first, as we have a fast(er) path there.
1385 if (ignore_packed_keep_on_disk || ignore_packed_keep_in_core) {
1387 * Set the flags for the kept-pack cache to be the ones we want
1388 * to ignore.
1390 * That is, if we are ignoring objects in on-disk keep packs,
1391 * then we want to search through the on-disk keep and ignore
1392 * the in-core ones.
1394 unsigned flags = 0;
1395 if (ignore_packed_keep_on_disk)
1396 flags |= ON_DISK_KEEP_PACKS;
1397 if (ignore_packed_keep_in_core)
1398 flags |= IN_CORE_KEEP_PACKS;
1400 if (ignore_packed_keep_on_disk && p->pack_keep)
1401 return 0;
1402 if (ignore_packed_keep_in_core && p->pack_keep_in_core)
1403 return 0;
1404 if (has_object_kept_pack(oid, flags))
1405 return 0;
1409 * At this point we know definitively that either we don't care about
1410 * keep-packs, or the object is not in one. Keep checking other
1411 * conditions...
1413 if (!local || !have_non_local_packs)
1414 return 1;
1416 /* we don't know yet; keep looking for more packs */
1417 return -1;
1420 static int want_object_in_pack_one(struct packed_git *p,
1421 const struct object_id *oid,
1422 int exclude,
1423 struct packed_git **found_pack,
1424 off_t *found_offset)
1426 off_t offset;
1428 if (p == *found_pack)
1429 offset = *found_offset;
1430 else
1431 offset = find_pack_entry_one(oid->hash, p);
1433 if (offset) {
1434 if (!*found_pack) {
1435 if (!is_pack_valid(p))
1436 return -1;
1437 *found_offset = offset;
1438 *found_pack = p;
1440 return want_found_object(oid, exclude, p);
1442 return -1;
1446 * Check whether we want the object in the pack (e.g., we do not want
1447 * objects found in non-local stores if the "--local" option was used).
1449 * If the caller already knows an existing pack it wants to take the object
1450 * from, that is passed in *found_pack and *found_offset; otherwise this
1451 * function finds if there is any pack that has the object and returns the pack
1452 * and its offset in these variables.
1454 static int want_object_in_pack(const struct object_id *oid,
1455 int exclude,
1456 struct packed_git **found_pack,
1457 off_t *found_offset)
1459 int want;
1460 struct list_head *pos;
1461 struct multi_pack_index *m;
1463 if (!exclude && local && has_loose_object_nonlocal(oid))
1464 return 0;
1467 * If we already know the pack object lives in, start checks from that
1468 * pack - in the usual case when neither --local was given nor .keep files
1469 * are present we will determine the answer right now.
1471 if (*found_pack) {
1472 want = want_found_object(oid, exclude, *found_pack);
1473 if (want != -1)
1474 return want;
1477 for (m = get_multi_pack_index(the_repository); m; m = m->next) {
1478 struct pack_entry e;
1479 if (fill_midx_entry(the_repository, oid, &e, m)) {
1480 want = want_object_in_pack_one(e.p, oid, exclude, found_pack, found_offset);
1481 if (want != -1)
1482 return want;
1486 list_for_each(pos, get_packed_git_mru(the_repository)) {
1487 struct packed_git *p = list_entry(pos, struct packed_git, mru);
1488 want = want_object_in_pack_one(p, oid, exclude, found_pack, found_offset);
1489 if (!exclude && want > 0)
1490 list_move(&p->mru,
1491 get_packed_git_mru(the_repository));
1492 if (want != -1)
1493 return want;
1496 if (uri_protocols.nr) {
1497 struct configured_exclusion *ex =
1498 oidmap_get(&configured_exclusions, oid);
1499 int i;
1500 const char *p;
1502 if (ex) {
1503 for (i = 0; i < uri_protocols.nr; i++) {
1504 if (skip_prefix(ex->uri,
1505 uri_protocols.items[i].string,
1506 &p) &&
1507 *p == ':') {
1508 oidset_insert(&excluded_by_config, oid);
1509 return 0;
1515 return 1;
1518 static void create_object_entry(const struct object_id *oid,
1519 enum object_type type,
1520 uint32_t hash,
1521 int exclude,
1522 int no_try_delta,
1523 struct packed_git *found_pack,
1524 off_t found_offset)
1526 struct object_entry *entry;
1528 entry = packlist_alloc(&to_pack, oid);
1529 entry->hash = hash;
1530 oe_set_type(entry, type);
1531 if (exclude)
1532 entry->preferred_base = 1;
1533 else
1534 nr_result++;
1535 if (found_pack) {
1536 oe_set_in_pack(&to_pack, entry, found_pack);
1537 entry->in_pack_offset = found_offset;
1540 entry->no_try_delta = no_try_delta;
1543 static const char no_closure_warning[] = N_(
1544 "disabling bitmap writing, as some objects are not being packed"
1547 static int add_object_entry(const struct object_id *oid, enum object_type type,
1548 const char *name, int exclude)
1550 struct packed_git *found_pack = NULL;
1551 off_t found_offset = 0;
1553 display_progress(progress_state, ++nr_seen);
1555 if (have_duplicate_entry(oid, exclude))
1556 return 0;
1558 if (!want_object_in_pack(oid, exclude, &found_pack, &found_offset)) {
1559 /* The pack is missing an object, so it will not have closure */
1560 if (write_bitmap_index) {
1561 if (write_bitmap_index != WRITE_BITMAP_QUIET)
1562 warning(_(no_closure_warning));
1563 write_bitmap_index = 0;
1565 return 0;
1568 create_object_entry(oid, type, pack_name_hash(name),
1569 exclude, name && no_try_delta(name),
1570 found_pack, found_offset);
1571 return 1;
1574 static int add_object_entry_from_bitmap(const struct object_id *oid,
1575 enum object_type type,
1576 int flags, uint32_t name_hash,
1577 struct packed_git *pack, off_t offset)
1579 display_progress(progress_state, ++nr_seen);
1581 if (have_duplicate_entry(oid, 0))
1582 return 0;
1584 if (!want_object_in_pack(oid, 0, &pack, &offset))
1585 return 0;
1587 create_object_entry(oid, type, name_hash, 0, 0, pack, offset);
1588 return 1;
1591 struct pbase_tree_cache {
1592 struct object_id oid;
1593 int ref;
1594 int temporary;
1595 void *tree_data;
1596 unsigned long tree_size;
1599 static struct pbase_tree_cache *(pbase_tree_cache[256]);
1600 static int pbase_tree_cache_ix(const struct object_id *oid)
1602 return oid->hash[0] % ARRAY_SIZE(pbase_tree_cache);
1604 static int pbase_tree_cache_ix_incr(int ix)
1606 return (ix+1) % ARRAY_SIZE(pbase_tree_cache);
1609 static struct pbase_tree {
1610 struct pbase_tree *next;
1611 /* This is a phony "cache" entry; we are not
1612 * going to evict it or find it through _get()
1613 * mechanism -- this is for the toplevel node that
1614 * would almost always change with any commit.
1616 struct pbase_tree_cache pcache;
1617 } *pbase_tree;
1619 static struct pbase_tree_cache *pbase_tree_get(const struct object_id *oid)
1621 struct pbase_tree_cache *ent, *nent;
1622 void *data;
1623 unsigned long size;
1624 enum object_type type;
1625 int neigh;
1626 int my_ix = pbase_tree_cache_ix(oid);
1627 int available_ix = -1;
1629 /* pbase-tree-cache acts as a limited hashtable.
1630 * your object will be found at your index or within a few
1631 * slots after that slot if it is cached.
1633 for (neigh = 0; neigh < 8; neigh++) {
1634 ent = pbase_tree_cache[my_ix];
1635 if (ent && oideq(&ent->oid, oid)) {
1636 ent->ref++;
1637 return ent;
1639 else if (((available_ix < 0) && (!ent || !ent->ref)) ||
1640 ((0 <= available_ix) &&
1641 (!ent && pbase_tree_cache[available_ix])))
1642 available_ix = my_ix;
1643 if (!ent)
1644 break;
1645 my_ix = pbase_tree_cache_ix_incr(my_ix);
1648 /* Did not find one. Either we got a bogus request or
1649 * we need to read and perhaps cache.
1651 data = read_object_file(oid, &type, &size);
1652 if (!data)
1653 return NULL;
1654 if (type != OBJ_TREE) {
1655 free(data);
1656 return NULL;
1659 /* We need to either cache or return a throwaway copy */
1661 if (available_ix < 0)
1662 ent = NULL;
1663 else {
1664 ent = pbase_tree_cache[available_ix];
1665 my_ix = available_ix;
1668 if (!ent) {
1669 nent = xmalloc(sizeof(*nent));
1670 nent->temporary = (available_ix < 0);
1672 else {
1673 /* evict and reuse */
1674 free(ent->tree_data);
1675 nent = ent;
1677 oidcpy(&nent->oid, oid);
1678 nent->tree_data = data;
1679 nent->tree_size = size;
1680 nent->ref = 1;
1681 if (!nent->temporary)
1682 pbase_tree_cache[my_ix] = nent;
1683 return nent;
1686 static void pbase_tree_put(struct pbase_tree_cache *cache)
1688 if (!cache->temporary) {
1689 cache->ref--;
1690 return;
1692 free(cache->tree_data);
1693 free(cache);
1696 static int name_cmp_len(const char *name)
1698 int i;
1699 for (i = 0; name[i] && name[i] != '\n' && name[i] != '/'; i++)
1701 return i;
1704 static void add_pbase_object(struct tree_desc *tree,
1705 const char *name,
1706 int cmplen,
1707 const char *fullname)
1709 struct name_entry entry;
1710 int cmp;
1712 while (tree_entry(tree,&entry)) {
1713 if (S_ISGITLINK(entry.mode))
1714 continue;
1715 cmp = tree_entry_len(&entry) != cmplen ? 1 :
1716 memcmp(name, entry.path, cmplen);
1717 if (cmp > 0)
1718 continue;
1719 if (cmp < 0)
1720 return;
1721 if (name[cmplen] != '/') {
1722 add_object_entry(&entry.oid,
1723 object_type(entry.mode),
1724 fullname, 1);
1725 return;
1727 if (S_ISDIR(entry.mode)) {
1728 struct tree_desc sub;
1729 struct pbase_tree_cache *tree;
1730 const char *down = name+cmplen+1;
1731 int downlen = name_cmp_len(down);
1733 tree = pbase_tree_get(&entry.oid);
1734 if (!tree)
1735 return;
1736 init_tree_desc(&sub, tree->tree_data, tree->tree_size);
1738 add_pbase_object(&sub, down, downlen, fullname);
1739 pbase_tree_put(tree);
1744 static unsigned *done_pbase_paths;
1745 static int done_pbase_paths_num;
1746 static int done_pbase_paths_alloc;
1747 static int done_pbase_path_pos(unsigned hash)
1749 int lo = 0;
1750 int hi = done_pbase_paths_num;
1751 while (lo < hi) {
1752 int mi = lo + (hi - lo) / 2;
1753 if (done_pbase_paths[mi] == hash)
1754 return mi;
1755 if (done_pbase_paths[mi] < hash)
1756 hi = mi;
1757 else
1758 lo = mi + 1;
1760 return -lo-1;
1763 static int check_pbase_path(unsigned hash)
1765 int pos = done_pbase_path_pos(hash);
1766 if (0 <= pos)
1767 return 1;
1768 pos = -pos - 1;
1769 ALLOC_GROW(done_pbase_paths,
1770 done_pbase_paths_num + 1,
1771 done_pbase_paths_alloc);
1772 done_pbase_paths_num++;
1773 if (pos < done_pbase_paths_num)
1774 MOVE_ARRAY(done_pbase_paths + pos + 1, done_pbase_paths + pos,
1775 done_pbase_paths_num - pos - 1);
1776 done_pbase_paths[pos] = hash;
1777 return 0;
1780 static void add_preferred_base_object(const char *name)
1782 struct pbase_tree *it;
1783 int cmplen;
1784 unsigned hash = pack_name_hash(name);
1786 if (!num_preferred_base || check_pbase_path(hash))
1787 return;
1789 cmplen = name_cmp_len(name);
1790 for (it = pbase_tree; it; it = it->next) {
1791 if (cmplen == 0) {
1792 add_object_entry(&it->pcache.oid, OBJ_TREE, NULL, 1);
1794 else {
1795 struct tree_desc tree;
1796 init_tree_desc(&tree, it->pcache.tree_data, it->pcache.tree_size);
1797 add_pbase_object(&tree, name, cmplen, name);
1802 static void add_preferred_base(struct object_id *oid)
1804 struct pbase_tree *it;
1805 void *data;
1806 unsigned long size;
1807 struct object_id tree_oid;
1809 if (window <= num_preferred_base++)
1810 return;
1812 data = read_object_with_reference(the_repository, oid,
1813 OBJ_TREE, &size, &tree_oid);
1814 if (!data)
1815 return;
1817 for (it = pbase_tree; it; it = it->next) {
1818 if (oideq(&it->pcache.oid, &tree_oid)) {
1819 free(data);
1820 return;
1824 CALLOC_ARRAY(it, 1);
1825 it->next = pbase_tree;
1826 pbase_tree = it;
1828 oidcpy(&it->pcache.oid, &tree_oid);
1829 it->pcache.tree_data = data;
1830 it->pcache.tree_size = size;
1833 static void cleanup_preferred_base(void)
1835 struct pbase_tree *it;
1836 unsigned i;
1838 it = pbase_tree;
1839 pbase_tree = NULL;
1840 while (it) {
1841 struct pbase_tree *tmp = it;
1842 it = tmp->next;
1843 free(tmp->pcache.tree_data);
1844 free(tmp);
1847 for (i = 0; i < ARRAY_SIZE(pbase_tree_cache); i++) {
1848 if (!pbase_tree_cache[i])
1849 continue;
1850 free(pbase_tree_cache[i]->tree_data);
1851 FREE_AND_NULL(pbase_tree_cache[i]);
1854 FREE_AND_NULL(done_pbase_paths);
1855 done_pbase_paths_num = done_pbase_paths_alloc = 0;
1859 * Return 1 iff the object specified by "delta" can be sent
1860 * literally as a delta against the base in "base_sha1". If
1861 * so, then *base_out will point to the entry in our packing
1862 * list, or NULL if we must use the external-base list.
1864 * Depth value does not matter - find_deltas() will
1865 * never consider reused delta as the base object to
1866 * deltify other objects against, in order to avoid
1867 * circular deltas.
1869 static int can_reuse_delta(const struct object_id *base_oid,
1870 struct object_entry *delta,
1871 struct object_entry **base_out)
1873 struct object_entry *base;
1876 * First see if we're already sending the base (or it's explicitly in
1877 * our "excluded" list).
1879 base = packlist_find(&to_pack, base_oid);
1880 if (base) {
1881 if (!in_same_island(&delta->idx.oid, &base->idx.oid))
1882 return 0;
1883 *base_out = base;
1884 return 1;
1888 * Otherwise, reachability bitmaps may tell us if the receiver has it,
1889 * even if it was buried too deep in history to make it into the
1890 * packing list.
1892 if (thin && bitmap_has_oid_in_uninteresting(bitmap_git, base_oid)) {
1893 if (use_delta_islands) {
1894 if (!in_same_island(&delta->idx.oid, base_oid))
1895 return 0;
1897 *base_out = NULL;
1898 return 1;
1901 return 0;
1904 static void prefetch_to_pack(uint32_t object_index_start) {
1905 struct oid_array to_fetch = OID_ARRAY_INIT;
1906 uint32_t i;
1908 for (i = object_index_start; i < to_pack.nr_objects; i++) {
1909 struct object_entry *entry = to_pack.objects + i;
1911 if (!oid_object_info_extended(the_repository,
1912 &entry->idx.oid,
1913 NULL,
1914 OBJECT_INFO_FOR_PREFETCH))
1915 continue;
1916 oid_array_append(&to_fetch, &entry->idx.oid);
1918 promisor_remote_get_direct(the_repository,
1919 to_fetch.oid, to_fetch.nr);
1920 oid_array_clear(&to_fetch);
1923 static void check_object(struct object_entry *entry, uint32_t object_index)
1925 unsigned long canonical_size;
1926 enum object_type type;
1927 struct object_info oi = {.typep = &type, .sizep = &canonical_size};
1929 if (IN_PACK(entry)) {
1930 struct packed_git *p = IN_PACK(entry);
1931 struct pack_window *w_curs = NULL;
1932 int have_base = 0;
1933 struct object_id base_ref;
1934 struct object_entry *base_entry;
1935 unsigned long used, used_0;
1936 unsigned long avail;
1937 off_t ofs;
1938 unsigned char *buf, c;
1939 enum object_type type;
1940 unsigned long in_pack_size;
1942 buf = use_pack(p, &w_curs, entry->in_pack_offset, &avail);
1945 * We want in_pack_type even if we do not reuse delta
1946 * since non-delta representations could still be reused.
1948 used = unpack_object_header_buffer(buf, avail,
1949 &type,
1950 &in_pack_size);
1951 if (used == 0)
1952 goto give_up;
1954 if (type < 0)
1955 BUG("invalid type %d", type);
1956 entry->in_pack_type = type;
1959 * Determine if this is a delta and if so whether we can
1960 * reuse it or not. Otherwise let's find out as cheaply as
1961 * possible what the actual type and size for this object is.
1963 switch (entry->in_pack_type) {
1964 default:
1965 /* Not a delta hence we've already got all we need. */
1966 oe_set_type(entry, entry->in_pack_type);
1967 SET_SIZE(entry, in_pack_size);
1968 entry->in_pack_header_size = used;
1969 if (oe_type(entry) < OBJ_COMMIT || oe_type(entry) > OBJ_BLOB)
1970 goto give_up;
1971 unuse_pack(&w_curs);
1972 return;
1973 case OBJ_REF_DELTA:
1974 if (reuse_delta && !entry->preferred_base) {
1975 oidread(&base_ref,
1976 use_pack(p, &w_curs,
1977 entry->in_pack_offset + used,
1978 NULL));
1979 have_base = 1;
1981 entry->in_pack_header_size = used + the_hash_algo->rawsz;
1982 break;
1983 case OBJ_OFS_DELTA:
1984 buf = use_pack(p, &w_curs,
1985 entry->in_pack_offset + used, NULL);
1986 used_0 = 0;
1987 c = buf[used_0++];
1988 ofs = c & 127;
1989 while (c & 128) {
1990 ofs += 1;
1991 if (!ofs || MSB(ofs, 7)) {
1992 error(_("delta base offset overflow in pack for %s"),
1993 oid_to_hex(&entry->idx.oid));
1994 goto give_up;
1996 c = buf[used_0++];
1997 ofs = (ofs << 7) + (c & 127);
1999 ofs = entry->in_pack_offset - ofs;
2000 if (ofs <= 0 || ofs >= entry->in_pack_offset) {
2001 error(_("delta base offset out of bound for %s"),
2002 oid_to_hex(&entry->idx.oid));
2003 goto give_up;
2005 if (reuse_delta && !entry->preferred_base) {
2006 uint32_t pos;
2007 if (offset_to_pack_pos(p, ofs, &pos) < 0)
2008 goto give_up;
2009 if (!nth_packed_object_id(&base_ref, p,
2010 pack_pos_to_index(p, pos)))
2011 have_base = 1;
2013 entry->in_pack_header_size = used + used_0;
2014 break;
2017 if (have_base &&
2018 can_reuse_delta(&base_ref, entry, &base_entry)) {
2019 oe_set_type(entry, entry->in_pack_type);
2020 SET_SIZE(entry, in_pack_size); /* delta size */
2021 SET_DELTA_SIZE(entry, in_pack_size);
2023 if (base_entry) {
2024 SET_DELTA(entry, base_entry);
2025 entry->delta_sibling_idx = base_entry->delta_child_idx;
2026 SET_DELTA_CHILD(base_entry, entry);
2027 } else {
2028 SET_DELTA_EXT(entry, &base_ref);
2031 unuse_pack(&w_curs);
2032 return;
2035 if (oe_type(entry)) {
2036 off_t delta_pos;
2039 * This must be a delta and we already know what the
2040 * final object type is. Let's extract the actual
2041 * object size from the delta header.
2043 delta_pos = entry->in_pack_offset + entry->in_pack_header_size;
2044 canonical_size = get_size_from_delta(p, &w_curs, delta_pos);
2045 if (canonical_size == 0)
2046 goto give_up;
2047 SET_SIZE(entry, canonical_size);
2048 unuse_pack(&w_curs);
2049 return;
2053 * No choice but to fall back to the recursive delta walk
2054 * with oid_object_info() to find about the object type
2055 * at this point...
2057 give_up:
2058 unuse_pack(&w_curs);
2061 if (oid_object_info_extended(the_repository, &entry->idx.oid, &oi,
2062 OBJECT_INFO_SKIP_FETCH_OBJECT | OBJECT_INFO_LOOKUP_REPLACE) < 0) {
2063 if (has_promisor_remote()) {
2064 prefetch_to_pack(object_index);
2065 if (oid_object_info_extended(the_repository, &entry->idx.oid, &oi,
2066 OBJECT_INFO_SKIP_FETCH_OBJECT | OBJECT_INFO_LOOKUP_REPLACE) < 0)
2067 type = -1;
2068 } else {
2069 type = -1;
2072 oe_set_type(entry, type);
2073 if (entry->type_valid) {
2074 SET_SIZE(entry, canonical_size);
2075 } else {
2077 * Bad object type is checked in prepare_pack(). This is
2078 * to permit a missing preferred base object to be ignored
2079 * as a preferred base. Doing so can result in a larger
2080 * pack file, but the transfer will still take place.
2085 static int pack_offset_sort(const void *_a, const void *_b)
2087 const struct object_entry *a = *(struct object_entry **)_a;
2088 const struct object_entry *b = *(struct object_entry **)_b;
2089 const struct packed_git *a_in_pack = IN_PACK(a);
2090 const struct packed_git *b_in_pack = IN_PACK(b);
2092 /* avoid filesystem trashing with loose objects */
2093 if (!a_in_pack && !b_in_pack)
2094 return oidcmp(&a->idx.oid, &b->idx.oid);
2096 if (a_in_pack < b_in_pack)
2097 return -1;
2098 if (a_in_pack > b_in_pack)
2099 return 1;
2100 return a->in_pack_offset < b->in_pack_offset ? -1 :
2101 (a->in_pack_offset > b->in_pack_offset);
2105 * Drop an on-disk delta we were planning to reuse. Naively, this would
2106 * just involve blanking out the "delta" field, but we have to deal
2107 * with some extra book-keeping:
2109 * 1. Removing ourselves from the delta_sibling linked list.
2111 * 2. Updating our size/type to the non-delta representation. These were
2112 * either not recorded initially (size) or overwritten with the delta type
2113 * (type) when check_object() decided to reuse the delta.
2115 * 3. Resetting our delta depth, as we are now a base object.
2117 static void drop_reused_delta(struct object_entry *entry)
2119 unsigned *idx = &to_pack.objects[entry->delta_idx - 1].delta_child_idx;
2120 struct object_info oi = OBJECT_INFO_INIT;
2121 enum object_type type;
2122 unsigned long size;
2124 while (*idx) {
2125 struct object_entry *oe = &to_pack.objects[*idx - 1];
2127 if (oe == entry)
2128 *idx = oe->delta_sibling_idx;
2129 else
2130 idx = &oe->delta_sibling_idx;
2132 SET_DELTA(entry, NULL);
2133 entry->depth = 0;
2135 oi.sizep = &size;
2136 oi.typep = &type;
2137 if (packed_object_info(the_repository, IN_PACK(entry), entry->in_pack_offset, &oi) < 0) {
2139 * We failed to get the info from this pack for some reason;
2140 * fall back to oid_object_info, which may find another copy.
2141 * And if that fails, the error will be recorded in oe_type(entry)
2142 * and dealt with in prepare_pack().
2144 oe_set_type(entry,
2145 oid_object_info(the_repository, &entry->idx.oid, &size));
2146 } else {
2147 oe_set_type(entry, type);
2149 SET_SIZE(entry, size);
2153 * Follow the chain of deltas from this entry onward, throwing away any links
2154 * that cause us to hit a cycle (as determined by the DFS state flags in
2155 * the entries).
2157 * We also detect too-long reused chains that would violate our --depth
2158 * limit.
2160 static void break_delta_chains(struct object_entry *entry)
2163 * The actual depth of each object we will write is stored as an int,
2164 * as it cannot exceed our int "depth" limit. But before we break
2165 * changes based no that limit, we may potentially go as deep as the
2166 * number of objects, which is elsewhere bounded to a uint32_t.
2168 uint32_t total_depth;
2169 struct object_entry *cur, *next;
2171 for (cur = entry, total_depth = 0;
2172 cur;
2173 cur = DELTA(cur), total_depth++) {
2174 if (cur->dfs_state == DFS_DONE) {
2176 * We've already seen this object and know it isn't
2177 * part of a cycle. We do need to append its depth
2178 * to our count.
2180 total_depth += cur->depth;
2181 break;
2185 * We break cycles before looping, so an ACTIVE state (or any
2186 * other cruft which made its way into the state variable)
2187 * is a bug.
2189 if (cur->dfs_state != DFS_NONE)
2190 BUG("confusing delta dfs state in first pass: %d",
2191 cur->dfs_state);
2194 * Now we know this is the first time we've seen the object. If
2195 * it's not a delta, we're done traversing, but we'll mark it
2196 * done to save time on future traversals.
2198 if (!DELTA(cur)) {
2199 cur->dfs_state = DFS_DONE;
2200 break;
2204 * Mark ourselves as active and see if the next step causes
2205 * us to cycle to another active object. It's important to do
2206 * this _before_ we loop, because it impacts where we make the
2207 * cut, and thus how our total_depth counter works.
2208 * E.g., We may see a partial loop like:
2210 * A -> B -> C -> D -> B
2212 * Cutting B->C breaks the cycle. But now the depth of A is
2213 * only 1, and our total_depth counter is at 3. The size of the
2214 * error is always one less than the size of the cycle we
2215 * broke. Commits C and D were "lost" from A's chain.
2217 * If we instead cut D->B, then the depth of A is correct at 3.
2218 * We keep all commits in the chain that we examined.
2220 cur->dfs_state = DFS_ACTIVE;
2221 if (DELTA(cur)->dfs_state == DFS_ACTIVE) {
2222 drop_reused_delta(cur);
2223 cur->dfs_state = DFS_DONE;
2224 break;
2229 * And now that we've gone all the way to the bottom of the chain, we
2230 * need to clear the active flags and set the depth fields as
2231 * appropriate. Unlike the loop above, which can quit when it drops a
2232 * delta, we need to keep going to look for more depth cuts. So we need
2233 * an extra "next" pointer to keep going after we reset cur->delta.
2235 for (cur = entry; cur; cur = next) {
2236 next = DELTA(cur);
2239 * We should have a chain of zero or more ACTIVE states down to
2240 * a final DONE. We can quit after the DONE, because either it
2241 * has no bases, or we've already handled them in a previous
2242 * call.
2244 if (cur->dfs_state == DFS_DONE)
2245 break;
2246 else if (cur->dfs_state != DFS_ACTIVE)
2247 BUG("confusing delta dfs state in second pass: %d",
2248 cur->dfs_state);
2251 * If the total_depth is more than depth, then we need to snip
2252 * the chain into two or more smaller chains that don't exceed
2253 * the maximum depth. Most of the resulting chains will contain
2254 * (depth + 1) entries (i.e., depth deltas plus one base), and
2255 * the last chain (i.e., the one containing entry) will contain
2256 * whatever entries are left over, namely
2257 * (total_depth % (depth + 1)) of them.
2259 * Since we are iterating towards decreasing depth, we need to
2260 * decrement total_depth as we go, and we need to write to the
2261 * entry what its final depth will be after all of the
2262 * snipping. Since we're snipping into chains of length (depth
2263 * + 1) entries, the final depth of an entry will be its
2264 * original depth modulo (depth + 1). Any time we encounter an
2265 * entry whose final depth is supposed to be zero, we snip it
2266 * from its delta base, thereby making it so.
2268 cur->depth = (total_depth--) % (depth + 1);
2269 if (!cur->depth)
2270 drop_reused_delta(cur);
2272 cur->dfs_state = DFS_DONE;
2276 static void get_object_details(void)
2278 uint32_t i;
2279 struct object_entry **sorted_by_offset;
2281 if (progress)
2282 progress_state = start_progress(_("Counting objects"),
2283 to_pack.nr_objects);
2285 CALLOC_ARRAY(sorted_by_offset, to_pack.nr_objects);
2286 for (i = 0; i < to_pack.nr_objects; i++)
2287 sorted_by_offset[i] = to_pack.objects + i;
2288 QSORT(sorted_by_offset, to_pack.nr_objects, pack_offset_sort);
2290 for (i = 0; i < to_pack.nr_objects; i++) {
2291 struct object_entry *entry = sorted_by_offset[i];
2292 check_object(entry, i);
2293 if (entry->type_valid &&
2294 oe_size_greater_than(&to_pack, entry, big_file_threshold))
2295 entry->no_try_delta = 1;
2296 display_progress(progress_state, i + 1);
2298 stop_progress(&progress_state);
2301 * This must happen in a second pass, since we rely on the delta
2302 * information for the whole list being completed.
2304 for (i = 0; i < to_pack.nr_objects; i++)
2305 break_delta_chains(&to_pack.objects[i]);
2307 free(sorted_by_offset);
2311 * We search for deltas in a list sorted by type, by filename hash, and then
2312 * by size, so that we see progressively smaller and smaller files.
2313 * That's because we prefer deltas to be from the bigger file
2314 * to the smaller -- deletes are potentially cheaper, but perhaps
2315 * more importantly, the bigger file is likely the more recent
2316 * one. The deepest deltas are therefore the oldest objects which are
2317 * less susceptible to be accessed often.
2319 static int type_size_sort(const void *_a, const void *_b)
2321 const struct object_entry *a = *(struct object_entry **)_a;
2322 const struct object_entry *b = *(struct object_entry **)_b;
2323 const enum object_type a_type = oe_type(a);
2324 const enum object_type b_type = oe_type(b);
2325 const unsigned long a_size = SIZE(a);
2326 const unsigned long b_size = SIZE(b);
2328 if (a_type > b_type)
2329 return -1;
2330 if (a_type < b_type)
2331 return 1;
2332 if (a->hash > b->hash)
2333 return -1;
2334 if (a->hash < b->hash)
2335 return 1;
2336 if (a->preferred_base > b->preferred_base)
2337 return -1;
2338 if (a->preferred_base < b->preferred_base)
2339 return 1;
2340 if (use_delta_islands) {
2341 const int island_cmp = island_delta_cmp(&a->idx.oid, &b->idx.oid);
2342 if (island_cmp)
2343 return island_cmp;
2345 if (a_size > b_size)
2346 return -1;
2347 if (a_size < b_size)
2348 return 1;
2349 return a < b ? -1 : (a > b); /* newest first */
2352 struct unpacked {
2353 struct object_entry *entry;
2354 void *data;
2355 struct delta_index *index;
2356 unsigned depth;
2359 static int delta_cacheable(unsigned long src_size, unsigned long trg_size,
2360 unsigned long delta_size)
2362 if (max_delta_cache_size && delta_cache_size + delta_size > max_delta_cache_size)
2363 return 0;
2365 if (delta_size < cache_max_small_delta_size)
2366 return 1;
2368 /* cache delta, if objects are large enough compared to delta size */
2369 if ((src_size >> 20) + (trg_size >> 21) > (delta_size >> 10))
2370 return 1;
2372 return 0;
2375 /* Protect delta_cache_size */
2376 static pthread_mutex_t cache_mutex;
2377 #define cache_lock() pthread_mutex_lock(&cache_mutex)
2378 #define cache_unlock() pthread_mutex_unlock(&cache_mutex)
2381 * Protect object list partitioning (e.g. struct thread_param) and
2382 * progress_state
2384 static pthread_mutex_t progress_mutex;
2385 #define progress_lock() pthread_mutex_lock(&progress_mutex)
2386 #define progress_unlock() pthread_mutex_unlock(&progress_mutex)
2389 * Access to struct object_entry is unprotected since each thread owns
2390 * a portion of the main object list. Just don't access object entries
2391 * ahead in the list because they can be stolen and would need
2392 * progress_mutex for protection.
2395 static inline int oe_size_less_than(struct packing_data *pack,
2396 const struct object_entry *lhs,
2397 unsigned long rhs)
2399 if (lhs->size_valid)
2400 return lhs->size_ < rhs;
2401 if (rhs < pack->oe_size_limit) /* rhs < 2^x <= lhs ? */
2402 return 0;
2403 return oe_get_size_slow(pack, lhs) < rhs;
2406 static inline void oe_set_tree_depth(struct packing_data *pack,
2407 struct object_entry *e,
2408 unsigned int tree_depth)
2410 if (!pack->tree_depth)
2411 CALLOC_ARRAY(pack->tree_depth, pack->nr_alloc);
2412 pack->tree_depth[e - pack->objects] = tree_depth;
2416 * Return the size of the object without doing any delta
2417 * reconstruction (so non-deltas are true object sizes, but deltas
2418 * return the size of the delta data).
2420 unsigned long oe_get_size_slow(struct packing_data *pack,
2421 const struct object_entry *e)
2423 struct packed_git *p;
2424 struct pack_window *w_curs;
2425 unsigned char *buf;
2426 enum object_type type;
2427 unsigned long used, avail, size;
2429 if (e->type_ != OBJ_OFS_DELTA && e->type_ != OBJ_REF_DELTA) {
2430 packing_data_lock(&to_pack);
2431 if (oid_object_info(the_repository, &e->idx.oid, &size) < 0)
2432 die(_("unable to get size of %s"),
2433 oid_to_hex(&e->idx.oid));
2434 packing_data_unlock(&to_pack);
2435 return size;
2438 p = oe_in_pack(pack, e);
2439 if (!p)
2440 BUG("when e->type is a delta, it must belong to a pack");
2442 packing_data_lock(&to_pack);
2443 w_curs = NULL;
2444 buf = use_pack(p, &w_curs, e->in_pack_offset, &avail);
2445 used = unpack_object_header_buffer(buf, avail, &type, &size);
2446 if (used == 0)
2447 die(_("unable to parse object header of %s"),
2448 oid_to_hex(&e->idx.oid));
2450 unuse_pack(&w_curs);
2451 packing_data_unlock(&to_pack);
2452 return size;
2455 static int try_delta(struct unpacked *trg, struct unpacked *src,
2456 unsigned max_depth, unsigned long *mem_usage)
2458 struct object_entry *trg_entry = trg->entry;
2459 struct object_entry *src_entry = src->entry;
2460 unsigned long trg_size, src_size, delta_size, sizediff, max_size, sz;
2461 unsigned ref_depth;
2462 enum object_type type;
2463 void *delta_buf;
2465 /* Don't bother doing diffs between different types */
2466 if (oe_type(trg_entry) != oe_type(src_entry))
2467 return -1;
2470 * We do not bother to try a delta that we discarded on an
2471 * earlier try, but only when reusing delta data. Note that
2472 * src_entry that is marked as the preferred_base should always
2473 * be considered, as even if we produce a suboptimal delta against
2474 * it, we will still save the transfer cost, as we already know
2475 * the other side has it and we won't send src_entry at all.
2477 if (reuse_delta && IN_PACK(trg_entry) &&
2478 IN_PACK(trg_entry) == IN_PACK(src_entry) &&
2479 !src_entry->preferred_base &&
2480 trg_entry->in_pack_type != OBJ_REF_DELTA &&
2481 trg_entry->in_pack_type != OBJ_OFS_DELTA)
2482 return 0;
2484 /* Let's not bust the allowed depth. */
2485 if (src->depth >= max_depth)
2486 return 0;
2488 /* Now some size filtering heuristics. */
2489 trg_size = SIZE(trg_entry);
2490 if (!DELTA(trg_entry)) {
2491 max_size = trg_size/2 - the_hash_algo->rawsz;
2492 ref_depth = 1;
2493 } else {
2494 max_size = DELTA_SIZE(trg_entry);
2495 ref_depth = trg->depth;
2497 max_size = (uint64_t)max_size * (max_depth - src->depth) /
2498 (max_depth - ref_depth + 1);
2499 if (max_size == 0)
2500 return 0;
2501 src_size = SIZE(src_entry);
2502 sizediff = src_size < trg_size ? trg_size - src_size : 0;
2503 if (sizediff >= max_size)
2504 return 0;
2505 if (trg_size < src_size / 32)
2506 return 0;
2508 if (!in_same_island(&trg->entry->idx.oid, &src->entry->idx.oid))
2509 return 0;
2511 /* Load data if not already done */
2512 if (!trg->data) {
2513 packing_data_lock(&to_pack);
2514 trg->data = read_object_file(&trg_entry->idx.oid, &type, &sz);
2515 packing_data_unlock(&to_pack);
2516 if (!trg->data)
2517 die(_("object %s cannot be read"),
2518 oid_to_hex(&trg_entry->idx.oid));
2519 if (sz != trg_size)
2520 die(_("object %s inconsistent object length (%"PRIuMAX" vs %"PRIuMAX")"),
2521 oid_to_hex(&trg_entry->idx.oid), (uintmax_t)sz,
2522 (uintmax_t)trg_size);
2523 *mem_usage += sz;
2525 if (!src->data) {
2526 packing_data_lock(&to_pack);
2527 src->data = read_object_file(&src_entry->idx.oid, &type, &sz);
2528 packing_data_unlock(&to_pack);
2529 if (!src->data) {
2530 if (src_entry->preferred_base) {
2531 static int warned = 0;
2532 if (!warned++)
2533 warning(_("object %s cannot be read"),
2534 oid_to_hex(&src_entry->idx.oid));
2536 * Those objects are not included in the
2537 * resulting pack. Be resilient and ignore
2538 * them if they can't be read, in case the
2539 * pack could be created nevertheless.
2541 return 0;
2543 die(_("object %s cannot be read"),
2544 oid_to_hex(&src_entry->idx.oid));
2546 if (sz != src_size)
2547 die(_("object %s inconsistent object length (%"PRIuMAX" vs %"PRIuMAX")"),
2548 oid_to_hex(&src_entry->idx.oid), (uintmax_t)sz,
2549 (uintmax_t)src_size);
2550 *mem_usage += sz;
2552 if (!src->index) {
2553 src->index = create_delta_index(src->data, src_size);
2554 if (!src->index) {
2555 static int warned = 0;
2556 if (!warned++)
2557 warning(_("suboptimal pack - out of memory"));
2558 return 0;
2560 *mem_usage += sizeof_delta_index(src->index);
2563 delta_buf = create_delta(src->index, trg->data, trg_size, &delta_size, max_size);
2564 if (!delta_buf)
2565 return 0;
2567 if (DELTA(trg_entry)) {
2568 /* Prefer only shallower same-sized deltas. */
2569 if (delta_size == DELTA_SIZE(trg_entry) &&
2570 src->depth + 1 >= trg->depth) {
2571 free(delta_buf);
2572 return 0;
2577 * Handle memory allocation outside of the cache
2578 * accounting lock. Compiler will optimize the strangeness
2579 * away when NO_PTHREADS is defined.
2581 free(trg_entry->delta_data);
2582 cache_lock();
2583 if (trg_entry->delta_data) {
2584 delta_cache_size -= DELTA_SIZE(trg_entry);
2585 trg_entry->delta_data = NULL;
2587 if (delta_cacheable(src_size, trg_size, delta_size)) {
2588 delta_cache_size += delta_size;
2589 cache_unlock();
2590 trg_entry->delta_data = xrealloc(delta_buf, delta_size);
2591 } else {
2592 cache_unlock();
2593 free(delta_buf);
2596 SET_DELTA(trg_entry, src_entry);
2597 SET_DELTA_SIZE(trg_entry, delta_size);
2598 trg->depth = src->depth + 1;
2600 return 1;
2603 static unsigned int check_delta_limit(struct object_entry *me, unsigned int n)
2605 struct object_entry *child = DELTA_CHILD(me);
2606 unsigned int m = n;
2607 while (child) {
2608 const unsigned int c = check_delta_limit(child, n + 1);
2609 if (m < c)
2610 m = c;
2611 child = DELTA_SIBLING(child);
2613 return m;
2616 static unsigned long free_unpacked(struct unpacked *n)
2618 unsigned long freed_mem = sizeof_delta_index(n->index);
2619 free_delta_index(n->index);
2620 n->index = NULL;
2621 if (n->data) {
2622 freed_mem += SIZE(n->entry);
2623 FREE_AND_NULL(n->data);
2625 n->entry = NULL;
2626 n->depth = 0;
2627 return freed_mem;
2630 static void find_deltas(struct object_entry **list, unsigned *list_size,
2631 int window, int depth, unsigned *processed)
2633 uint32_t i, idx = 0, count = 0;
2634 struct unpacked *array;
2635 unsigned long mem_usage = 0;
2637 CALLOC_ARRAY(array, window);
2639 for (;;) {
2640 struct object_entry *entry;
2641 struct unpacked *n = array + idx;
2642 int j, max_depth, best_base = -1;
2644 progress_lock();
2645 if (!*list_size) {
2646 progress_unlock();
2647 break;
2649 entry = *list++;
2650 (*list_size)--;
2651 if (!entry->preferred_base) {
2652 (*processed)++;
2653 display_progress(progress_state, *processed);
2655 progress_unlock();
2657 mem_usage -= free_unpacked(n);
2658 n->entry = entry;
2660 while (window_memory_limit &&
2661 mem_usage > window_memory_limit &&
2662 count > 1) {
2663 const uint32_t tail = (idx + window - count) % window;
2664 mem_usage -= free_unpacked(array + tail);
2665 count--;
2668 /* We do not compute delta to *create* objects we are not
2669 * going to pack.
2671 if (entry->preferred_base)
2672 goto next;
2675 * If the current object is at pack edge, take the depth the
2676 * objects that depend on the current object into account
2677 * otherwise they would become too deep.
2679 max_depth = depth;
2680 if (DELTA_CHILD(entry)) {
2681 max_depth -= check_delta_limit(entry, 0);
2682 if (max_depth <= 0)
2683 goto next;
2686 j = window;
2687 while (--j > 0) {
2688 int ret;
2689 uint32_t other_idx = idx + j;
2690 struct unpacked *m;
2691 if (other_idx >= window)
2692 other_idx -= window;
2693 m = array + other_idx;
2694 if (!m->entry)
2695 break;
2696 ret = try_delta(n, m, max_depth, &mem_usage);
2697 if (ret < 0)
2698 break;
2699 else if (ret > 0)
2700 best_base = other_idx;
2704 * If we decided to cache the delta data, then it is best
2705 * to compress it right away. First because we have to do
2706 * it anyway, and doing it here while we're threaded will
2707 * save a lot of time in the non threaded write phase,
2708 * as well as allow for caching more deltas within
2709 * the same cache size limit.
2710 * ...
2711 * But only if not writing to stdout, since in that case
2712 * the network is most likely throttling writes anyway,
2713 * and therefore it is best to go to the write phase ASAP
2714 * instead, as we can afford spending more time compressing
2715 * between writes at that moment.
2717 if (entry->delta_data && !pack_to_stdout) {
2718 unsigned long size;
2720 size = do_compress(&entry->delta_data, DELTA_SIZE(entry));
2721 if (size < (1U << OE_Z_DELTA_BITS)) {
2722 entry->z_delta_size = size;
2723 cache_lock();
2724 delta_cache_size -= DELTA_SIZE(entry);
2725 delta_cache_size += entry->z_delta_size;
2726 cache_unlock();
2727 } else {
2728 FREE_AND_NULL(entry->delta_data);
2729 entry->z_delta_size = 0;
2733 /* if we made n a delta, and if n is already at max
2734 * depth, leaving it in the window is pointless. we
2735 * should evict it first.
2737 if (DELTA(entry) && max_depth <= n->depth)
2738 continue;
2741 * Move the best delta base up in the window, after the
2742 * currently deltified object, to keep it longer. It will
2743 * be the first base object to be attempted next.
2745 if (DELTA(entry)) {
2746 struct unpacked swap = array[best_base];
2747 int dist = (window + idx - best_base) % window;
2748 int dst = best_base;
2749 while (dist--) {
2750 int src = (dst + 1) % window;
2751 array[dst] = array[src];
2752 dst = src;
2754 array[dst] = swap;
2757 next:
2758 idx++;
2759 if (count + 1 < window)
2760 count++;
2761 if (idx >= window)
2762 idx = 0;
2765 for (i = 0; i < window; ++i) {
2766 free_delta_index(array[i].index);
2767 free(array[i].data);
2769 free(array);
2773 * The main object list is split into smaller lists, each is handed to
2774 * one worker.
2776 * The main thread waits on the condition that (at least) one of the workers
2777 * has stopped working (which is indicated in the .working member of
2778 * struct thread_params).
2780 * When a work thread has completed its work, it sets .working to 0 and
2781 * signals the main thread and waits on the condition that .data_ready
2782 * becomes 1.
2784 * The main thread steals half of the work from the worker that has
2785 * most work left to hand it to the idle worker.
2788 struct thread_params {
2789 pthread_t thread;
2790 struct object_entry **list;
2791 unsigned list_size;
2792 unsigned remaining;
2793 int window;
2794 int depth;
2795 int working;
2796 int data_ready;
2797 pthread_mutex_t mutex;
2798 pthread_cond_t cond;
2799 unsigned *processed;
2802 static pthread_cond_t progress_cond;
2805 * Mutex and conditional variable can't be statically-initialized on Windows.
2807 static void init_threaded_search(void)
2809 pthread_mutex_init(&cache_mutex, NULL);
2810 pthread_mutex_init(&progress_mutex, NULL);
2811 pthread_cond_init(&progress_cond, NULL);
2814 static void cleanup_threaded_search(void)
2816 pthread_cond_destroy(&progress_cond);
2817 pthread_mutex_destroy(&cache_mutex);
2818 pthread_mutex_destroy(&progress_mutex);
2821 static void *threaded_find_deltas(void *arg)
2823 struct thread_params *me = arg;
2825 progress_lock();
2826 while (me->remaining) {
2827 progress_unlock();
2829 find_deltas(me->list, &me->remaining,
2830 me->window, me->depth, me->processed);
2832 progress_lock();
2833 me->working = 0;
2834 pthread_cond_signal(&progress_cond);
2835 progress_unlock();
2838 * We must not set ->data_ready before we wait on the
2839 * condition because the main thread may have set it to 1
2840 * before we get here. In order to be sure that new
2841 * work is available if we see 1 in ->data_ready, it
2842 * was initialized to 0 before this thread was spawned
2843 * and we reset it to 0 right away.
2845 pthread_mutex_lock(&me->mutex);
2846 while (!me->data_ready)
2847 pthread_cond_wait(&me->cond, &me->mutex);
2848 me->data_ready = 0;
2849 pthread_mutex_unlock(&me->mutex);
2851 progress_lock();
2853 progress_unlock();
2854 /* leave ->working 1 so that this doesn't get more work assigned */
2855 return NULL;
2858 static void ll_find_deltas(struct object_entry **list, unsigned list_size,
2859 int window, int depth, unsigned *processed)
2861 struct thread_params *p;
2862 int i, ret, active_threads = 0;
2864 init_threaded_search();
2866 if (delta_search_threads <= 1) {
2867 find_deltas(list, &list_size, window, depth, processed);
2868 cleanup_threaded_search();
2869 return;
2871 if (progress > pack_to_stdout)
2872 fprintf_ln(stderr, _("Delta compression using up to %d threads"),
2873 delta_search_threads);
2874 CALLOC_ARRAY(p, delta_search_threads);
2876 /* Partition the work amongst work threads. */
2877 for (i = 0; i < delta_search_threads; i++) {
2878 unsigned sub_size = list_size / (delta_search_threads - i);
2880 /* don't use too small segments or no deltas will be found */
2881 if (sub_size < 2*window && i+1 < delta_search_threads)
2882 sub_size = 0;
2884 p[i].window = window;
2885 p[i].depth = depth;
2886 p[i].processed = processed;
2887 p[i].working = 1;
2888 p[i].data_ready = 0;
2890 /* try to split chunks on "path" boundaries */
2891 while (sub_size && sub_size < list_size &&
2892 list[sub_size]->hash &&
2893 list[sub_size]->hash == list[sub_size-1]->hash)
2894 sub_size++;
2896 p[i].list = list;
2897 p[i].list_size = sub_size;
2898 p[i].remaining = sub_size;
2900 list += sub_size;
2901 list_size -= sub_size;
2904 /* Start work threads. */
2905 for (i = 0; i < delta_search_threads; i++) {
2906 if (!p[i].list_size)
2907 continue;
2908 pthread_mutex_init(&p[i].mutex, NULL);
2909 pthread_cond_init(&p[i].cond, NULL);
2910 ret = pthread_create(&p[i].thread, NULL,
2911 threaded_find_deltas, &p[i]);
2912 if (ret)
2913 die(_("unable to create thread: %s"), strerror(ret));
2914 active_threads++;
2918 * Now let's wait for work completion. Each time a thread is done
2919 * with its work, we steal half of the remaining work from the
2920 * thread with the largest number of unprocessed objects and give
2921 * it to that newly idle thread. This ensure good load balancing
2922 * until the remaining object list segments are simply too short
2923 * to be worth splitting anymore.
2925 while (active_threads) {
2926 struct thread_params *target = NULL;
2927 struct thread_params *victim = NULL;
2928 unsigned sub_size = 0;
2930 progress_lock();
2931 for (;;) {
2932 for (i = 0; !target && i < delta_search_threads; i++)
2933 if (!p[i].working)
2934 target = &p[i];
2935 if (target)
2936 break;
2937 pthread_cond_wait(&progress_cond, &progress_mutex);
2940 for (i = 0; i < delta_search_threads; i++)
2941 if (p[i].remaining > 2*window &&
2942 (!victim || victim->remaining < p[i].remaining))
2943 victim = &p[i];
2944 if (victim) {
2945 sub_size = victim->remaining / 2;
2946 list = victim->list + victim->list_size - sub_size;
2947 while (sub_size && list[0]->hash &&
2948 list[0]->hash == list[-1]->hash) {
2949 list++;
2950 sub_size--;
2952 if (!sub_size) {
2954 * It is possible for some "paths" to have
2955 * so many objects that no hash boundary
2956 * might be found. Let's just steal the
2957 * exact half in that case.
2959 sub_size = victim->remaining / 2;
2960 list -= sub_size;
2962 target->list = list;
2963 victim->list_size -= sub_size;
2964 victim->remaining -= sub_size;
2966 target->list_size = sub_size;
2967 target->remaining = sub_size;
2968 target->working = 1;
2969 progress_unlock();
2971 pthread_mutex_lock(&target->mutex);
2972 target->data_ready = 1;
2973 pthread_cond_signal(&target->cond);
2974 pthread_mutex_unlock(&target->mutex);
2976 if (!sub_size) {
2977 pthread_join(target->thread, NULL);
2978 pthread_cond_destroy(&target->cond);
2979 pthread_mutex_destroy(&target->mutex);
2980 active_threads--;
2983 cleanup_threaded_search();
2984 free(p);
2987 static int obj_is_packed(const struct object_id *oid)
2989 return packlist_find(&to_pack, oid) ||
2990 (reuse_packfile_bitmap &&
2991 bitmap_walk_contains(bitmap_git, reuse_packfile_bitmap, oid));
2994 static void add_tag_chain(const struct object_id *oid)
2996 struct tag *tag;
2999 * We catch duplicates already in add_object_entry(), but we'd
3000 * prefer to do this extra check to avoid having to parse the
3001 * tag at all if we already know that it's being packed (e.g., if
3002 * it was included via bitmaps, we would not have parsed it
3003 * previously).
3005 if (obj_is_packed(oid))
3006 return;
3008 tag = lookup_tag(the_repository, oid);
3009 while (1) {
3010 if (!tag || parse_tag(tag) || !tag->tagged)
3011 die(_("unable to pack objects reachable from tag %s"),
3012 oid_to_hex(oid));
3014 add_object_entry(&tag->object.oid, OBJ_TAG, NULL, 0);
3016 if (tag->tagged->type != OBJ_TAG)
3017 return;
3019 tag = (struct tag *)tag->tagged;
3023 static int add_ref_tag(const char *tag, const struct object_id *oid, int flag, void *cb_data)
3025 struct object_id peeled;
3027 if (!peel_iterated_oid(oid, &peeled) && obj_is_packed(&peeled))
3028 add_tag_chain(oid);
3029 return 0;
3032 static void prepare_pack(int window, int depth)
3034 struct object_entry **delta_list;
3035 uint32_t i, nr_deltas;
3036 unsigned n;
3038 if (use_delta_islands)
3039 resolve_tree_islands(the_repository, progress, &to_pack);
3041 get_object_details();
3044 * If we're locally repacking then we need to be doubly careful
3045 * from now on in order to make sure no stealth corruption gets
3046 * propagated to the new pack. Clients receiving streamed packs
3047 * should validate everything they get anyway so no need to incur
3048 * the additional cost here in that case.
3050 if (!pack_to_stdout)
3051 do_check_packed_object_crc = 1;
3053 if (!to_pack.nr_objects || !window || !depth)
3054 return;
3056 ALLOC_ARRAY(delta_list, to_pack.nr_objects);
3057 nr_deltas = n = 0;
3059 for (i = 0; i < to_pack.nr_objects; i++) {
3060 struct object_entry *entry = to_pack.objects + i;
3062 if (DELTA(entry))
3063 /* This happens if we decided to reuse existing
3064 * delta from a pack. "reuse_delta &&" is implied.
3066 continue;
3068 if (!entry->type_valid ||
3069 oe_size_less_than(&to_pack, entry, 50))
3070 continue;
3072 if (entry->no_try_delta)
3073 continue;
3075 if (!entry->preferred_base) {
3076 nr_deltas++;
3077 if (oe_type(entry) < 0)
3078 die(_("unable to get type of object %s"),
3079 oid_to_hex(&entry->idx.oid));
3080 } else {
3081 if (oe_type(entry) < 0) {
3083 * This object is not found, but we
3084 * don't have to include it anyway.
3086 continue;
3090 delta_list[n++] = entry;
3093 if (nr_deltas && n > 1) {
3094 unsigned nr_done = 0;
3096 if (progress)
3097 progress_state = start_progress(_("Compressing objects"),
3098 nr_deltas);
3099 QSORT(delta_list, n, type_size_sort);
3100 ll_find_deltas(delta_list, n, window+1, depth, &nr_done);
3101 stop_progress(&progress_state);
3102 if (nr_done != nr_deltas)
3103 die(_("inconsistency with delta count"));
3105 free(delta_list);
3108 static int git_pack_config(const char *k, const char *v, void *cb)
3110 if (!strcmp(k, "pack.window")) {
3111 window = git_config_int(k, v);
3112 return 0;
3114 if (!strcmp(k, "pack.windowmemory")) {
3115 window_memory_limit = git_config_ulong(k, v);
3116 return 0;
3118 if (!strcmp(k, "pack.depth")) {
3119 depth = git_config_int(k, v);
3120 return 0;
3122 if (!strcmp(k, "pack.deltacachesize")) {
3123 max_delta_cache_size = git_config_int(k, v);
3124 return 0;
3126 if (!strcmp(k, "pack.deltacachelimit")) {
3127 cache_max_small_delta_size = git_config_int(k, v);
3128 return 0;
3130 if (!strcmp(k, "pack.writebitmaphashcache")) {
3131 if (git_config_bool(k, v))
3132 write_bitmap_options |= BITMAP_OPT_HASH_CACHE;
3133 else
3134 write_bitmap_options &= ~BITMAP_OPT_HASH_CACHE;
3136 if (!strcmp(k, "pack.usebitmaps")) {
3137 use_bitmap_index_default = git_config_bool(k, v);
3138 return 0;
3140 if (!strcmp(k, "pack.allowpackreuse")) {
3141 allow_pack_reuse = git_config_bool(k, v);
3142 return 0;
3144 if (!strcmp(k, "pack.threads")) {
3145 delta_search_threads = git_config_int(k, v);
3146 if (delta_search_threads < 0)
3147 die(_("invalid number of threads specified (%d)"),
3148 delta_search_threads);
3149 if (!HAVE_THREADS && delta_search_threads != 1) {
3150 warning(_("no threads support, ignoring %s"), k);
3151 delta_search_threads = 0;
3153 return 0;
3155 if (!strcmp(k, "pack.indexversion")) {
3156 pack_idx_opts.version = git_config_int(k, v);
3157 if (pack_idx_opts.version > 2)
3158 die(_("bad pack.indexversion=%"PRIu32),
3159 pack_idx_opts.version);
3160 return 0;
3162 if (!strcmp(k, "pack.writereverseindex")) {
3163 if (git_config_bool(k, v))
3164 pack_idx_opts.flags |= WRITE_REV;
3165 else
3166 pack_idx_opts.flags &= ~WRITE_REV;
3167 return 0;
3169 if (!strcmp(k, "uploadpack.blobpackfileuri")) {
3170 struct configured_exclusion *ex = xmalloc(sizeof(*ex));
3171 const char *oid_end, *pack_end;
3173 * Stores the pack hash. This is not a true object ID, but is
3174 * of the same form.
3176 struct object_id pack_hash;
3178 if (parse_oid_hex(v, &ex->e.oid, &oid_end) ||
3179 *oid_end != ' ' ||
3180 parse_oid_hex(oid_end + 1, &pack_hash, &pack_end) ||
3181 *pack_end != ' ')
3182 die(_("value of uploadpack.blobpackfileuri must be "
3183 "of the form '<object-hash> <pack-hash> <uri>' (got '%s')"), v);
3184 if (oidmap_get(&configured_exclusions, &ex->e.oid))
3185 die(_("object already configured in another "
3186 "uploadpack.blobpackfileuri (got '%s')"), v);
3187 ex->pack_hash_hex = xcalloc(1, pack_end - oid_end);
3188 memcpy(ex->pack_hash_hex, oid_end + 1, pack_end - oid_end - 1);
3189 ex->uri = xstrdup(pack_end + 1);
3190 oidmap_put(&configured_exclusions, ex);
3192 return git_default_config(k, v, cb);
3195 /* Counters for trace2 output when in --stdin-packs mode. */
3196 static int stdin_packs_found_nr;
3197 static int stdin_packs_hints_nr;
3199 static int add_object_entry_from_pack(const struct object_id *oid,
3200 struct packed_git *p,
3201 uint32_t pos,
3202 void *_data)
3204 struct rev_info *revs = _data;
3205 struct object_info oi = OBJECT_INFO_INIT;
3206 off_t ofs;
3207 enum object_type type;
3209 display_progress(progress_state, ++nr_seen);
3211 if (have_duplicate_entry(oid, 0))
3212 return 0;
3214 ofs = nth_packed_object_offset(p, pos);
3215 if (!want_object_in_pack(oid, 0, &p, &ofs))
3216 return 0;
3218 oi.typep = &type;
3219 if (packed_object_info(the_repository, p, ofs, &oi) < 0)
3220 die(_("could not get type of object %s in pack %s"),
3221 oid_to_hex(oid), p->pack_name);
3222 else if (type == OBJ_COMMIT) {
3224 * commits in included packs are used as starting points for the
3225 * subsequent revision walk
3227 add_pending_oid(revs, NULL, oid, 0);
3230 stdin_packs_found_nr++;
3232 create_object_entry(oid, type, 0, 0, 0, p, ofs);
3234 return 0;
3237 static void show_commit_pack_hint(struct commit *commit, void *_data)
3239 /* nothing to do; commits don't have a namehash */
3242 static void show_object_pack_hint(struct object *object, const char *name,
3243 void *_data)
3245 struct object_entry *oe = packlist_find(&to_pack, &object->oid);
3246 if (!oe)
3247 return;
3250 * Our 'to_pack' list was constructed by iterating all objects packed in
3251 * included packs, and so doesn't have a non-zero hash field that you
3252 * would typically pick up during a reachability traversal.
3254 * Make a best-effort attempt to fill in the ->hash and ->no_try_delta
3255 * here using a now in order to perhaps improve the delta selection
3256 * process.
3258 oe->hash = pack_name_hash(name);
3259 oe->no_try_delta = name && no_try_delta(name);
3261 stdin_packs_hints_nr++;
3264 static int pack_mtime_cmp(const void *_a, const void *_b)
3266 struct packed_git *a = ((const struct string_list_item*)_a)->util;
3267 struct packed_git *b = ((const struct string_list_item*)_b)->util;
3270 * order packs by descending mtime so that objects are laid out
3271 * roughly as newest-to-oldest
3273 if (a->mtime < b->mtime)
3274 return 1;
3275 else if (b->mtime < a->mtime)
3276 return -1;
3277 else
3278 return 0;
3281 static void read_packs_list_from_stdin(void)
3283 struct strbuf buf = STRBUF_INIT;
3284 struct string_list include_packs = STRING_LIST_INIT_DUP;
3285 struct string_list exclude_packs = STRING_LIST_INIT_DUP;
3286 struct string_list_item *item = NULL;
3288 struct packed_git *p;
3289 struct rev_info revs;
3291 repo_init_revisions(the_repository, &revs, NULL);
3293 * Use a revision walk to fill in the namehash of objects in the include
3294 * packs. To save time, we'll avoid traversing through objects that are
3295 * in excluded packs.
3297 * That may cause us to avoid populating all of the namehash fields of
3298 * all included objects, but our goal is best-effort, since this is only
3299 * an optimization during delta selection.
3301 revs.no_kept_objects = 1;
3302 revs.keep_pack_cache_flags |= IN_CORE_KEEP_PACKS;
3303 revs.blob_objects = 1;
3304 revs.tree_objects = 1;
3305 revs.tag_objects = 1;
3306 revs.ignore_missing_links = 1;
3308 while (strbuf_getline(&buf, stdin) != EOF) {
3309 if (!buf.len)
3310 continue;
3312 if (*buf.buf == '^')
3313 string_list_append(&exclude_packs, buf.buf + 1);
3314 else
3315 string_list_append(&include_packs, buf.buf);
3317 strbuf_reset(&buf);
3320 string_list_sort(&include_packs);
3321 string_list_sort(&exclude_packs);
3323 for (p = get_all_packs(the_repository); p; p = p->next) {
3324 const char *pack_name = pack_basename(p);
3326 item = string_list_lookup(&include_packs, pack_name);
3327 if (!item)
3328 item = string_list_lookup(&exclude_packs, pack_name);
3330 if (item)
3331 item->util = p;
3335 * Arguments we got on stdin may not even be packs. First
3336 * check that to avoid segfaulting later on in
3337 * e.g. pack_mtime_cmp(), excluded packs are handled below.
3339 * Since we first parsed our STDIN and then sorted the input
3340 * lines the pack we error on will be whatever line happens to
3341 * sort first. This is lazy, it's enough that we report one
3342 * bad case here, we don't need to report the first/last one,
3343 * or all of them.
3345 for_each_string_list_item(item, &include_packs) {
3346 struct packed_git *p = item->util;
3347 if (!p)
3348 die(_("could not find pack '%s'"), item->string);
3352 * Then, handle all of the excluded packs, marking them as
3353 * kept in-core so that later calls to add_object_entry()
3354 * discards any objects that are also found in excluded packs.
3356 for_each_string_list_item(item, &exclude_packs) {
3357 struct packed_git *p = item->util;
3358 if (!p)
3359 die(_("could not find pack '%s'"), item->string);
3360 p->pack_keep_in_core = 1;
3364 * Order packs by ascending mtime; use QSORT directly to access the
3365 * string_list_item's ->util pointer, which string_list_sort() does not
3366 * provide.
3368 QSORT(include_packs.items, include_packs.nr, pack_mtime_cmp);
3370 for_each_string_list_item(item, &include_packs) {
3371 struct packed_git *p = item->util;
3372 if (!p)
3373 die(_("could not find pack '%s'"), item->string);
3374 for_each_object_in_pack(p,
3375 add_object_entry_from_pack,
3376 &revs,
3377 FOR_EACH_OBJECT_PACK_ORDER);
3380 if (prepare_revision_walk(&revs))
3381 die(_("revision walk setup failed"));
3382 traverse_commit_list(&revs,
3383 show_commit_pack_hint,
3384 show_object_pack_hint,
3385 NULL);
3387 trace2_data_intmax("pack-objects", the_repository, "stdin_packs_found",
3388 stdin_packs_found_nr);
3389 trace2_data_intmax("pack-objects", the_repository, "stdin_packs_hints",
3390 stdin_packs_hints_nr);
3392 strbuf_release(&buf);
3393 string_list_clear(&include_packs, 0);
3394 string_list_clear(&exclude_packs, 0);
3397 static void read_object_list_from_stdin(void)
3399 char line[GIT_MAX_HEXSZ + 1 + PATH_MAX + 2];
3400 struct object_id oid;
3401 const char *p;
3403 for (;;) {
3404 if (!fgets(line, sizeof(line), stdin)) {
3405 if (feof(stdin))
3406 break;
3407 if (!ferror(stdin))
3408 BUG("fgets returned NULL, not EOF, not error!");
3409 if (errno != EINTR)
3410 die_errno("fgets");
3411 clearerr(stdin);
3412 continue;
3414 if (line[0] == '-') {
3415 if (get_oid_hex(line+1, &oid))
3416 die(_("expected edge object ID, got garbage:\n %s"),
3417 line);
3418 add_preferred_base(&oid);
3419 continue;
3421 if (parse_oid_hex(line, &oid, &p))
3422 die(_("expected object ID, got garbage:\n %s"), line);
3424 add_preferred_base_object(p + 1);
3425 add_object_entry(&oid, OBJ_NONE, p + 1, 0);
3429 static void show_commit(struct commit *commit, void *data)
3431 add_object_entry(&commit->object.oid, OBJ_COMMIT, NULL, 0);
3433 if (write_bitmap_index)
3434 index_commit_for_bitmap(commit);
3436 if (use_delta_islands)
3437 propagate_island_marks(commit);
3440 static void show_object(struct object *obj, const char *name, void *data)
3442 add_preferred_base_object(name);
3443 add_object_entry(&obj->oid, obj->type, name, 0);
3445 if (use_delta_islands) {
3446 const char *p;
3447 unsigned depth;
3448 struct object_entry *ent;
3450 /* the empty string is a root tree, which is depth 0 */
3451 depth = *name ? 1 : 0;
3452 for (p = strchr(name, '/'); p; p = strchr(p + 1, '/'))
3453 depth++;
3455 ent = packlist_find(&to_pack, &obj->oid);
3456 if (ent && depth > oe_tree_depth(&to_pack, ent))
3457 oe_set_tree_depth(&to_pack, ent, depth);
3461 static void show_object__ma_allow_any(struct object *obj, const char *name, void *data)
3463 assert(arg_missing_action == MA_ALLOW_ANY);
3466 * Quietly ignore ALL missing objects. This avoids problems with
3467 * staging them now and getting an odd error later.
3469 if (!has_object(the_repository, &obj->oid, 0))
3470 return;
3472 show_object(obj, name, data);
3475 static void show_object__ma_allow_promisor(struct object *obj, const char *name, void *data)
3477 assert(arg_missing_action == MA_ALLOW_PROMISOR);
3480 * Quietly ignore EXPECTED missing objects. This avoids problems with
3481 * staging them now and getting an odd error later.
3483 if (!has_object(the_repository, &obj->oid, 0) && is_promisor_object(&obj->oid))
3484 return;
3486 show_object(obj, name, data);
3489 static int option_parse_missing_action(const struct option *opt,
3490 const char *arg, int unset)
3492 assert(arg);
3493 assert(!unset);
3495 if (!strcmp(arg, "error")) {
3496 arg_missing_action = MA_ERROR;
3497 fn_show_object = show_object;
3498 return 0;
3501 if (!strcmp(arg, "allow-any")) {
3502 arg_missing_action = MA_ALLOW_ANY;
3503 fetch_if_missing = 0;
3504 fn_show_object = show_object__ma_allow_any;
3505 return 0;
3508 if (!strcmp(arg, "allow-promisor")) {
3509 arg_missing_action = MA_ALLOW_PROMISOR;
3510 fetch_if_missing = 0;
3511 fn_show_object = show_object__ma_allow_promisor;
3512 return 0;
3515 die(_("invalid value for '%s': '%s'"), "--missing", arg);
3516 return 0;
3519 static void show_edge(struct commit *commit)
3521 add_preferred_base(&commit->object.oid);
3524 static int add_object_in_unpacked_pack(const struct object_id *oid,
3525 struct packed_git *pack,
3526 uint32_t pos,
3527 void *_data)
3529 add_object_entry(oid, OBJ_NONE, "", 0);
3530 return 0;
3533 static void add_objects_in_unpacked_packs(void)
3535 if (for_each_packed_object(add_object_in_unpacked_pack, NULL,
3536 FOR_EACH_OBJECT_PACK_ORDER |
3537 FOR_EACH_OBJECT_LOCAL_ONLY |
3538 FOR_EACH_OBJECT_SKIP_IN_CORE_KEPT_PACKS |
3539 FOR_EACH_OBJECT_SKIP_ON_DISK_KEPT_PACKS))
3540 die(_("cannot open pack index"));
3543 static int add_loose_object(const struct object_id *oid, const char *path,
3544 void *data)
3546 enum object_type type = oid_object_info(the_repository, oid, NULL);
3548 if (type < 0) {
3549 warning(_("loose object at %s could not be examined"), path);
3550 return 0;
3553 add_object_entry(oid, type, "", 0);
3554 return 0;
3558 * We actually don't even have to worry about reachability here.
3559 * add_object_entry will weed out duplicates, so we just add every
3560 * loose object we find.
3562 static void add_unreachable_loose_objects(void)
3564 for_each_loose_file_in_objdir(get_object_directory(),
3565 add_loose_object,
3566 NULL, NULL, NULL);
3569 static int has_sha1_pack_kept_or_nonlocal(const struct object_id *oid)
3571 static struct packed_git *last_found = (void *)1;
3572 struct packed_git *p;
3574 p = (last_found != (void *)1) ? last_found :
3575 get_all_packs(the_repository);
3577 while (p) {
3578 if ((!p->pack_local || p->pack_keep ||
3579 p->pack_keep_in_core) &&
3580 find_pack_entry_one(oid->hash, p)) {
3581 last_found = p;
3582 return 1;
3584 if (p == last_found)
3585 p = get_all_packs(the_repository);
3586 else
3587 p = p->next;
3588 if (p == last_found)
3589 p = p->next;
3591 return 0;
3595 * Store a list of sha1s that are should not be discarded
3596 * because they are either written too recently, or are
3597 * reachable from another object that was.
3599 * This is filled by get_object_list.
3601 static struct oid_array recent_objects;
3603 static int loosened_object_can_be_discarded(const struct object_id *oid,
3604 timestamp_t mtime)
3606 if (!unpack_unreachable_expiration)
3607 return 0;
3608 if (mtime > unpack_unreachable_expiration)
3609 return 0;
3610 if (oid_array_lookup(&recent_objects, oid) >= 0)
3611 return 0;
3612 return 1;
3615 static void loosen_unused_packed_objects(void)
3617 struct packed_git *p;
3618 uint32_t i;
3619 uint32_t loosened_objects_nr = 0;
3620 struct object_id oid;
3622 for (p = get_all_packs(the_repository); p; p = p->next) {
3623 if (!p->pack_local || p->pack_keep || p->pack_keep_in_core)
3624 continue;
3626 if (open_pack_index(p))
3627 die(_("cannot open pack index"));
3629 for (i = 0; i < p->num_objects; i++) {
3630 nth_packed_object_id(&oid, p, i);
3631 if (!packlist_find(&to_pack, &oid) &&
3632 !has_sha1_pack_kept_or_nonlocal(&oid) &&
3633 !loosened_object_can_be_discarded(&oid, p->mtime)) {
3634 if (force_object_loose(&oid, p->mtime))
3635 die(_("unable to force loose object"));
3636 loosened_objects_nr++;
3641 trace2_data_intmax("pack-objects", the_repository,
3642 "loosen_unused_packed_objects/loosened", loosened_objects_nr);
3646 * This tracks any options which pack-reuse code expects to be on, or which a
3647 * reader of the pack might not understand, and which would therefore prevent
3648 * blind reuse of what we have on disk.
3650 static int pack_options_allow_reuse(void)
3652 return allow_pack_reuse &&
3653 pack_to_stdout &&
3654 !ignore_packed_keep_on_disk &&
3655 !ignore_packed_keep_in_core &&
3656 (!local || !have_non_local_packs) &&
3657 !incremental;
3660 static int get_object_list_from_bitmap(struct rev_info *revs)
3662 if (!(bitmap_git = prepare_bitmap_walk(revs, 0)))
3663 return -1;
3665 if (pack_options_allow_reuse() &&
3666 !reuse_partial_packfile_from_bitmap(
3667 bitmap_git,
3668 &reuse_packfile,
3669 &reuse_packfile_objects,
3670 &reuse_packfile_bitmap)) {
3671 assert(reuse_packfile_objects);
3672 nr_result += reuse_packfile_objects;
3673 nr_seen += reuse_packfile_objects;
3674 display_progress(progress_state, nr_seen);
3677 traverse_bitmap_commit_list(bitmap_git, revs,
3678 &add_object_entry_from_bitmap);
3679 return 0;
3682 static void record_recent_object(struct object *obj,
3683 const char *name,
3684 void *data)
3686 oid_array_append(&recent_objects, &obj->oid);
3689 static void record_recent_commit(struct commit *commit, void *data)
3691 oid_array_append(&recent_objects, &commit->object.oid);
3694 static int mark_bitmap_preferred_tip(const char *refname,
3695 const struct object_id *oid, int flags,
3696 void *_data)
3698 struct object_id peeled;
3699 struct object *object;
3701 if (!peel_iterated_oid(oid, &peeled))
3702 oid = &peeled;
3704 object = parse_object_or_die(oid, refname);
3705 if (object->type == OBJ_COMMIT)
3706 object->flags |= NEEDS_BITMAP;
3708 return 0;
3711 static void mark_bitmap_preferred_tips(void)
3713 struct string_list_item *item;
3714 const struct string_list *preferred_tips;
3716 preferred_tips = bitmap_preferred_tips(the_repository);
3717 if (!preferred_tips)
3718 return;
3720 for_each_string_list_item(item, preferred_tips) {
3721 for_each_ref_in(item->string, mark_bitmap_preferred_tip, NULL);
3725 static void get_object_list(struct rev_info *revs, int ac, const char **av)
3727 struct setup_revision_opt s_r_opt = {
3728 .allow_exclude_promisor_objects = 1,
3730 char line[1000];
3731 int flags = 0;
3732 int save_warning;
3734 save_commit_buffer = 0;
3735 setup_revisions(ac, av, revs, &s_r_opt);
3737 /* make sure shallows are read */
3738 is_repository_shallow(the_repository);
3740 save_warning = warn_on_object_refname_ambiguity;
3741 warn_on_object_refname_ambiguity = 0;
3743 while (fgets(line, sizeof(line), stdin) != NULL) {
3744 int len = strlen(line);
3745 if (len && line[len - 1] == '\n')
3746 line[--len] = 0;
3747 if (!len)
3748 break;
3749 if (*line == '-') {
3750 if (!strcmp(line, "--not")) {
3751 flags ^= UNINTERESTING;
3752 write_bitmap_index = 0;
3753 continue;
3755 if (starts_with(line, "--shallow ")) {
3756 struct object_id oid;
3757 if (get_oid_hex(line + 10, &oid))
3758 die("not an object name '%s'", line + 10);
3759 register_shallow(the_repository, &oid);
3760 use_bitmap_index = 0;
3761 continue;
3763 die(_("not a rev '%s'"), line);
3765 if (handle_revision_arg(line, revs, flags, REVARG_CANNOT_BE_FILENAME))
3766 die(_("bad revision '%s'"), line);
3769 warn_on_object_refname_ambiguity = save_warning;
3771 if (use_bitmap_index && !get_object_list_from_bitmap(revs))
3772 return;
3774 if (use_delta_islands)
3775 load_delta_islands(the_repository, progress);
3777 if (write_bitmap_index)
3778 mark_bitmap_preferred_tips();
3780 if (prepare_revision_walk(revs))
3781 die(_("revision walk setup failed"));
3782 mark_edges_uninteresting(revs, show_edge, sparse);
3784 if (!fn_show_object)
3785 fn_show_object = show_object;
3786 traverse_commit_list(revs,
3787 show_commit, fn_show_object,
3788 NULL);
3790 if (unpack_unreachable_expiration) {
3791 revs->ignore_missing_links = 1;
3792 if (add_unseen_recent_objects_to_traversal(revs,
3793 unpack_unreachable_expiration))
3794 die(_("unable to add recent objects"));
3795 if (prepare_revision_walk(revs))
3796 die(_("revision walk setup failed"));
3797 traverse_commit_list(revs, record_recent_commit,
3798 record_recent_object, NULL);
3801 if (keep_unreachable)
3802 add_objects_in_unpacked_packs();
3803 if (pack_loose_unreachable)
3804 add_unreachable_loose_objects();
3805 if (unpack_unreachable)
3806 loosen_unused_packed_objects();
3808 oid_array_clear(&recent_objects);
3811 static void add_extra_kept_packs(const struct string_list *names)
3813 struct packed_git *p;
3815 if (!names->nr)
3816 return;
3818 for (p = get_all_packs(the_repository); p; p = p->next) {
3819 const char *name = basename(p->pack_name);
3820 int i;
3822 if (!p->pack_local)
3823 continue;
3825 for (i = 0; i < names->nr; i++)
3826 if (!fspathcmp(name, names->items[i].string))
3827 break;
3829 if (i < names->nr) {
3830 p->pack_keep_in_core = 1;
3831 ignore_packed_keep_in_core = 1;
3832 continue;
3837 static int option_parse_index_version(const struct option *opt,
3838 const char *arg, int unset)
3840 char *c;
3841 const char *val = arg;
3843 BUG_ON_OPT_NEG(unset);
3845 pack_idx_opts.version = strtoul(val, &c, 10);
3846 if (pack_idx_opts.version > 2)
3847 die(_("unsupported index version %s"), val);
3848 if (*c == ',' && c[1])
3849 pack_idx_opts.off32_limit = strtoul(c+1, &c, 0);
3850 if (*c || pack_idx_opts.off32_limit & 0x80000000)
3851 die(_("bad index version '%s'"), val);
3852 return 0;
3855 static int option_parse_unpack_unreachable(const struct option *opt,
3856 const char *arg, int unset)
3858 if (unset) {
3859 unpack_unreachable = 0;
3860 unpack_unreachable_expiration = 0;
3862 else {
3863 unpack_unreachable = 1;
3864 if (arg)
3865 unpack_unreachable_expiration = approxidate(arg);
3867 return 0;
3870 struct po_filter_data {
3871 unsigned have_revs:1;
3872 struct rev_info revs;
3875 static struct list_objects_filter_options *po_filter_revs_init(void *value)
3877 struct po_filter_data *data = value;
3879 repo_init_revisions(the_repository, &data->revs, NULL);
3880 data->have_revs = 1;
3882 return &data->revs.filter;
3885 int cmd_pack_objects(int argc, const char **argv, const char *prefix)
3887 int use_internal_rev_list = 0;
3888 int shallow = 0;
3889 int all_progress_implied = 0;
3890 struct strvec rp = STRVEC_INIT;
3891 int rev_list_unpacked = 0, rev_list_all = 0, rev_list_reflog = 0;
3892 int rev_list_index = 0;
3893 int stdin_packs = 0;
3894 struct string_list keep_pack_list = STRING_LIST_INIT_NODUP;
3895 struct po_filter_data pfd = { .have_revs = 0 };
3897 struct option pack_objects_options[] = {
3898 OPT_SET_INT('q', "quiet", &progress,
3899 N_("do not show progress meter"), 0),
3900 OPT_SET_INT(0, "progress", &progress,
3901 N_("show progress meter"), 1),
3902 OPT_SET_INT(0, "all-progress", &progress,
3903 N_("show progress meter during object writing phase"), 2),
3904 OPT_BOOL(0, "all-progress-implied",
3905 &all_progress_implied,
3906 N_("similar to --all-progress when progress meter is shown")),
3907 OPT_CALLBACK_F(0, "index-version", NULL, N_("<version>[,<offset>]"),
3908 N_("write the pack index file in the specified idx format version"),
3909 PARSE_OPT_NONEG, option_parse_index_version),
3910 OPT_MAGNITUDE(0, "max-pack-size", &pack_size_limit,
3911 N_("maximum size of each output pack file")),
3912 OPT_BOOL(0, "local", &local,
3913 N_("ignore borrowed objects from alternate object store")),
3914 OPT_BOOL(0, "incremental", &incremental,
3915 N_("ignore packed objects")),
3916 OPT_INTEGER(0, "window", &window,
3917 N_("limit pack window by objects")),
3918 OPT_MAGNITUDE(0, "window-memory", &window_memory_limit,
3919 N_("limit pack window by memory in addition to object limit")),
3920 OPT_INTEGER(0, "depth", &depth,
3921 N_("maximum length of delta chain allowed in the resulting pack")),
3922 OPT_BOOL(0, "reuse-delta", &reuse_delta,
3923 N_("reuse existing deltas")),
3924 OPT_BOOL(0, "reuse-object", &reuse_object,
3925 N_("reuse existing objects")),
3926 OPT_BOOL(0, "delta-base-offset", &allow_ofs_delta,
3927 N_("use OFS_DELTA objects")),
3928 OPT_INTEGER(0, "threads", &delta_search_threads,
3929 N_("use threads when searching for best delta matches")),
3930 OPT_BOOL(0, "non-empty", &non_empty,
3931 N_("do not create an empty pack output")),
3932 OPT_BOOL(0, "revs", &use_internal_rev_list,
3933 N_("read revision arguments from standard input")),
3934 OPT_SET_INT_F(0, "unpacked", &rev_list_unpacked,
3935 N_("limit the objects to those that are not yet packed"),
3936 1, PARSE_OPT_NONEG),
3937 OPT_SET_INT_F(0, "all", &rev_list_all,
3938 N_("include objects reachable from any reference"),
3939 1, PARSE_OPT_NONEG),
3940 OPT_SET_INT_F(0, "reflog", &rev_list_reflog,
3941 N_("include objects referred by reflog entries"),
3942 1, PARSE_OPT_NONEG),
3943 OPT_SET_INT_F(0, "indexed-objects", &rev_list_index,
3944 N_("include objects referred to by the index"),
3945 1, PARSE_OPT_NONEG),
3946 OPT_BOOL(0, "stdin-packs", &stdin_packs,
3947 N_("read packs from stdin")),
3948 OPT_BOOL(0, "stdout", &pack_to_stdout,
3949 N_("output pack to stdout")),
3950 OPT_BOOL(0, "include-tag", &include_tag,
3951 N_("include tag objects that refer to objects to be packed")),
3952 OPT_BOOL(0, "keep-unreachable", &keep_unreachable,
3953 N_("keep unreachable objects")),
3954 OPT_BOOL(0, "pack-loose-unreachable", &pack_loose_unreachable,
3955 N_("pack loose unreachable objects")),
3956 OPT_CALLBACK_F(0, "unpack-unreachable", NULL, N_("time"),
3957 N_("unpack unreachable objects newer than <time>"),
3958 PARSE_OPT_OPTARG, option_parse_unpack_unreachable),
3959 OPT_BOOL(0, "sparse", &sparse,
3960 N_("use the sparse reachability algorithm")),
3961 OPT_BOOL(0, "thin", &thin,
3962 N_("create thin packs")),
3963 OPT_BOOL(0, "shallow", &shallow,
3964 N_("create packs suitable for shallow fetches")),
3965 OPT_BOOL(0, "honor-pack-keep", &ignore_packed_keep_on_disk,
3966 N_("ignore packs that have companion .keep file")),
3967 OPT_STRING_LIST(0, "keep-pack", &keep_pack_list, N_("name"),
3968 N_("ignore this pack")),
3969 OPT_INTEGER(0, "compression", &pack_compression_level,
3970 N_("pack compression level")),
3971 OPT_SET_INT(0, "keep-true-parents", &grafts_replace_parents,
3972 N_("do not hide commits by grafts"), 0),
3973 OPT_BOOL(0, "use-bitmap-index", &use_bitmap_index,
3974 N_("use a bitmap index if available to speed up counting objects")),
3975 OPT_SET_INT(0, "write-bitmap-index", &write_bitmap_index,
3976 N_("write a bitmap index together with the pack index"),
3977 WRITE_BITMAP_TRUE),
3978 OPT_SET_INT_F(0, "write-bitmap-index-quiet",
3979 &write_bitmap_index,
3980 N_("write a bitmap index if possible"),
3981 WRITE_BITMAP_QUIET, PARSE_OPT_HIDDEN),
3982 OPT_PARSE_LIST_OBJECTS_FILTER_INIT(&pfd, po_filter_revs_init),
3983 OPT_CALLBACK_F(0, "missing", NULL, N_("action"),
3984 N_("handling for missing objects"), PARSE_OPT_NONEG,
3985 option_parse_missing_action),
3986 OPT_BOOL(0, "exclude-promisor-objects", &exclude_promisor_objects,
3987 N_("do not pack objects in promisor packfiles")),
3988 OPT_BOOL(0, "delta-islands", &use_delta_islands,
3989 N_("respect islands during delta compression")),
3990 OPT_STRING_LIST(0, "uri-protocol", &uri_protocols,
3991 N_("protocol"),
3992 N_("exclude any configured uploadpack.blobpackfileuri with this protocol")),
3993 OPT_END(),
3996 if (DFS_NUM_STATES > (1 << OE_DFS_STATE_BITS))
3997 BUG("too many dfs states, increase OE_DFS_STATE_BITS");
3999 read_replace_refs = 0;
4001 sparse = git_env_bool("GIT_TEST_PACK_SPARSE", -1);
4002 if (the_repository->gitdir) {
4003 prepare_repo_settings(the_repository);
4004 if (sparse < 0)
4005 sparse = the_repository->settings.pack_use_sparse;
4008 reset_pack_idx_option(&pack_idx_opts);
4009 git_config(git_pack_config, NULL);
4010 if (git_env_bool(GIT_TEST_WRITE_REV_INDEX, 0))
4011 pack_idx_opts.flags |= WRITE_REV;
4013 progress = isatty(2);
4014 argc = parse_options(argc, argv, prefix, pack_objects_options,
4015 pack_usage, 0);
4017 if (argc) {
4018 base_name = argv[0];
4019 argc--;
4021 if (pack_to_stdout != !base_name || argc)
4022 usage_with_options(pack_usage, pack_objects_options);
4024 if (depth < 0)
4025 depth = 0;
4026 if (depth >= (1 << OE_DEPTH_BITS)) {
4027 warning(_("delta chain depth %d is too deep, forcing %d"),
4028 depth, (1 << OE_DEPTH_BITS) - 1);
4029 depth = (1 << OE_DEPTH_BITS) - 1;
4031 if (cache_max_small_delta_size >= (1U << OE_Z_DELTA_BITS)) {
4032 warning(_("pack.deltaCacheLimit is too high, forcing %d"),
4033 (1U << OE_Z_DELTA_BITS) - 1);
4034 cache_max_small_delta_size = (1U << OE_Z_DELTA_BITS) - 1;
4036 if (window < 0)
4037 window = 0;
4039 strvec_push(&rp, "pack-objects");
4040 if (thin) {
4041 use_internal_rev_list = 1;
4042 strvec_push(&rp, shallow
4043 ? "--objects-edge-aggressive"
4044 : "--objects-edge");
4045 } else
4046 strvec_push(&rp, "--objects");
4048 if (rev_list_all) {
4049 use_internal_rev_list = 1;
4050 strvec_push(&rp, "--all");
4052 if (rev_list_reflog) {
4053 use_internal_rev_list = 1;
4054 strvec_push(&rp, "--reflog");
4056 if (rev_list_index) {
4057 use_internal_rev_list = 1;
4058 strvec_push(&rp, "--indexed-objects");
4060 if (rev_list_unpacked && !stdin_packs) {
4061 use_internal_rev_list = 1;
4062 strvec_push(&rp, "--unpacked");
4065 if (exclude_promisor_objects) {
4066 use_internal_rev_list = 1;
4067 fetch_if_missing = 0;
4068 strvec_push(&rp, "--exclude-promisor-objects");
4070 if (unpack_unreachable || keep_unreachable || pack_loose_unreachable)
4071 use_internal_rev_list = 1;
4073 if (!reuse_object)
4074 reuse_delta = 0;
4075 if (pack_compression_level == -1)
4076 pack_compression_level = Z_DEFAULT_COMPRESSION;
4077 else if (pack_compression_level < 0 || pack_compression_level > Z_BEST_COMPRESSION)
4078 die(_("bad pack compression level %d"), pack_compression_level);
4080 if (!delta_search_threads) /* --threads=0 means autodetect */
4081 delta_search_threads = online_cpus();
4083 if (!HAVE_THREADS && delta_search_threads != 1)
4084 warning(_("no threads support, ignoring --threads"));
4085 if (!pack_to_stdout && !pack_size_limit)
4086 pack_size_limit = pack_size_limit_cfg;
4087 if (pack_to_stdout && pack_size_limit)
4088 die(_("--max-pack-size cannot be used to build a pack for transfer"));
4089 if (pack_size_limit && pack_size_limit < 1024*1024) {
4090 warning(_("minimum pack size limit is 1 MiB"));
4091 pack_size_limit = 1024*1024;
4094 if (!pack_to_stdout && thin)
4095 die(_("--thin cannot be used to build an indexable pack"));
4097 if (keep_unreachable && unpack_unreachable)
4098 die(_("options '%s' and '%s' cannot be used together"), "--keep-unreachable", "--unpack-unreachable");
4099 if (!rev_list_all || !rev_list_reflog || !rev_list_index)
4100 unpack_unreachable_expiration = 0;
4102 if (pfd.have_revs && pfd.revs.filter.choice) {
4103 if (!pack_to_stdout)
4104 die(_("cannot use --filter without --stdout"));
4105 if (stdin_packs)
4106 die(_("cannot use --filter with --stdin-packs"));
4109 if (stdin_packs && use_internal_rev_list)
4110 die(_("cannot use internal rev list with --stdin-packs"));
4113 * "soft" reasons not to use bitmaps - for on-disk repack by default we want
4115 * - to produce good pack (with bitmap index not-yet-packed objects are
4116 * packed in suboptimal order).
4118 * - to use more robust pack-generation codepath (avoiding possible
4119 * bugs in bitmap code and possible bitmap index corruption).
4121 if (!pack_to_stdout)
4122 use_bitmap_index_default = 0;
4124 if (use_bitmap_index < 0)
4125 use_bitmap_index = use_bitmap_index_default;
4127 /* "hard" reasons not to use bitmaps; these just won't work at all */
4128 if (!use_internal_rev_list || (!pack_to_stdout && write_bitmap_index) || is_repository_shallow(the_repository))
4129 use_bitmap_index = 0;
4131 if (pack_to_stdout || !rev_list_all)
4132 write_bitmap_index = 0;
4134 if (use_delta_islands)
4135 strvec_push(&rp, "--topo-order");
4137 if (progress && all_progress_implied)
4138 progress = 2;
4140 add_extra_kept_packs(&keep_pack_list);
4141 if (ignore_packed_keep_on_disk) {
4142 struct packed_git *p;
4143 for (p = get_all_packs(the_repository); p; p = p->next)
4144 if (p->pack_local && p->pack_keep)
4145 break;
4146 if (!p) /* no keep-able packs found */
4147 ignore_packed_keep_on_disk = 0;
4149 if (local) {
4151 * unlike ignore_packed_keep_on_disk above, we do not
4152 * want to unset "local" based on looking at packs, as
4153 * it also covers non-local objects
4155 struct packed_git *p;
4156 for (p = get_all_packs(the_repository); p; p = p->next) {
4157 if (!p->pack_local) {
4158 have_non_local_packs = 1;
4159 break;
4164 trace2_region_enter("pack-objects", "enumerate-objects",
4165 the_repository);
4166 prepare_packing_data(the_repository, &to_pack);
4168 if (progress)
4169 progress_state = start_progress(_("Enumerating objects"), 0);
4170 if (stdin_packs) {
4171 /* avoids adding objects in excluded packs */
4172 ignore_packed_keep_in_core = 1;
4173 read_packs_list_from_stdin();
4174 if (rev_list_unpacked)
4175 add_unreachable_loose_objects();
4176 } else if (!use_internal_rev_list) {
4177 read_object_list_from_stdin();
4178 } else if (pfd.have_revs) {
4179 get_object_list(&pfd.revs, rp.nr, rp.v);
4180 } else {
4181 struct rev_info revs;
4183 repo_init_revisions(the_repository, &revs, NULL);
4184 get_object_list(&revs, rp.nr, rp.v);
4186 cleanup_preferred_base();
4187 if (include_tag && nr_result)
4188 for_each_tag_ref(add_ref_tag, NULL);
4189 stop_progress(&progress_state);
4190 trace2_region_leave("pack-objects", "enumerate-objects",
4191 the_repository);
4193 if (non_empty && !nr_result)
4194 goto cleanup;
4195 if (nr_result) {
4196 trace2_region_enter("pack-objects", "prepare-pack",
4197 the_repository);
4198 prepare_pack(window, depth);
4199 trace2_region_leave("pack-objects", "prepare-pack",
4200 the_repository);
4203 trace2_region_enter("pack-objects", "write-pack-file", the_repository);
4204 write_excluded_by_configs();
4205 write_pack_file();
4206 trace2_region_leave("pack-objects", "write-pack-file", the_repository);
4208 if (progress)
4209 fprintf_ln(stderr,
4210 _("Total %"PRIu32" (delta %"PRIu32"),"
4211 " reused %"PRIu32" (delta %"PRIu32"),"
4212 " pack-reused %"PRIu32),
4213 written, written_delta, reused, reused_delta,
4214 reuse_packfile_objects);
4216 cleanup:
4217 strvec_clear(&rp);
4219 return 0;