3 #include "repository.h"
13 #include "pack-revindex.h"
14 #include "csum-file.h"
15 #include "tree-walk.h"
18 #include "list-objects.h"
19 #include "list-objects-filter.h"
20 #include "list-objects-filter-options.h"
21 #include "pack-objects.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 "sha1-array.h"
30 #include "argv-array.h"
33 #include "object-store.h"
38 #define IN_PACK(obj) oe_in_pack(&to_pack, obj)
39 #define SIZE(obj) oe_size(&to_pack, obj)
40 #define SET_SIZE(obj,size) oe_set_size(&to_pack, obj, size)
41 #define DELTA_SIZE(obj) oe_delta_size(&to_pack, obj)
42 #define DELTA(obj) oe_delta(&to_pack, obj)
43 #define DELTA_CHILD(obj) oe_delta_child(&to_pack, obj)
44 #define DELTA_SIBLING(obj) oe_delta_sibling(&to_pack, obj)
45 #define SET_DELTA(obj, val) oe_set_delta(&to_pack, obj, val)
46 #define SET_DELTA_EXT(obj, oid) oe_set_delta_ext(&to_pack, obj, oid)
47 #define SET_DELTA_SIZE(obj, val) oe_set_delta_size(&to_pack, obj, val)
48 #define SET_DELTA_CHILD(obj, val) oe_set_delta_child(&to_pack, obj, val)
49 #define SET_DELTA_SIBLING(obj, val) oe_set_delta_sibling(&to_pack, obj, val)
51 static const char *pack_usage[] = {
52 N_("git pack-objects --stdout [<options>...] [< <ref-list> | < <object-list>]"),
53 N_("git pack-objects [<options>...] <base-name> [< <ref-list> | < <object-list>]"),
58 * Objects we are going to pack are collected in the `to_pack` structure.
59 * It contains an array (dynamically expanded) of the object data, and a map
60 * that can resolve SHA1s to their position in the array.
62 static struct packing_data to_pack;
64 static struct pack_idx_entry **written_list;
65 static uint32_t nr_result, nr_written, nr_seen;
66 static struct bitmap_index *bitmap_git;
67 static uint32_t write_layer;
70 static int reuse_delta = 1, reuse_object = 1;
71 static int keep_unreachable, unpack_unreachable, include_tag;
72 static timestamp_t unpack_unreachable_expiration;
73 static int pack_loose_unreachable;
75 static int have_non_local_packs;
76 static int incremental;
77 static int ignore_packed_keep_on_disk;
78 static int ignore_packed_keep_in_core;
79 static int allow_ofs_delta;
80 static struct pack_idx_option pack_idx_opts;
81 static const char *base_name;
82 static int progress = 1;
83 static int window = 10;
84 static unsigned long pack_size_limit;
85 static int depth = 50;
86 static int delta_search_threads;
87 static int pack_to_stdout;
90 static int num_preferred_base;
91 static struct progress *progress_state;
93 static struct packed_git *reuse_packfile;
94 static uint32_t reuse_packfile_objects;
95 static off_t reuse_packfile_offset;
97 static int use_bitmap_index_default = 1;
98 static int use_bitmap_index = -1;
100 WRITE_BITMAP_FALSE = 0,
103 } write_bitmap_index;
104 static uint16_t write_bitmap_options = BITMAP_OPT_HASH_CACHE;
106 static int exclude_promisor_objects;
108 static int use_delta_islands;
110 static unsigned long delta_cache_size = 0;
111 static unsigned long max_delta_cache_size = DEFAULT_DELTA_CACHE_SIZE;
112 static unsigned long cache_max_small_delta_size = 1000;
114 static unsigned long window_memory_limit = 0;
116 static struct list_objects_filter_options filter_options;
118 enum missing_action {
119 MA_ERROR = 0, /* fail if any missing objects are encountered */
120 MA_ALLOW_ANY, /* silently allow ALL missing objects */
121 MA_ALLOW_PROMISOR, /* silently allow all missing PROMISOR objects */
123 static enum missing_action arg_missing_action;
124 static show_object_fn fn_show_object;
129 static uint32_t written, written_delta;
130 static uint32_t reused, reused_delta;
135 static struct commit **indexed_commits;
136 static unsigned int indexed_commits_nr;
137 static unsigned int indexed_commits_alloc;
139 static void index_commit_for_bitmap(struct commit *commit)
141 if (indexed_commits_nr >= indexed_commits_alloc) {
142 indexed_commits_alloc = (indexed_commits_alloc + 32) * 2;
143 REALLOC_ARRAY(indexed_commits, indexed_commits_alloc);
146 indexed_commits[indexed_commits_nr++] = commit;
149 static void *get_delta(struct object_entry *entry)
151 unsigned long size, base_size, delta_size;
152 void *buf, *base_buf, *delta_buf;
153 enum object_type type;
155 buf = read_object_file(&entry->idx.oid, &type, &size);
157 die(_("unable to read %s"), oid_to_hex(&entry->idx.oid));
158 base_buf = read_object_file(&DELTA(entry)->idx.oid, &type,
161 die("unable to read %s",
162 oid_to_hex(&DELTA(entry)->idx.oid));
163 delta_buf = diff_delta(base_buf, base_size,
164 buf, size, &delta_size, 0);
166 * We successfully computed this delta once but dropped it for
167 * memory reasons. Something is very wrong if this time we
168 * recompute and create a different delta.
170 if (!delta_buf || delta_size != DELTA_SIZE(entry))
171 BUG("delta size changed");
177 static unsigned long do_compress(void **pptr, unsigned long size)
181 unsigned long maxsize;
183 git_deflate_init(&stream, pack_compression_level);
184 maxsize = git_deflate_bound(&stream, size);
187 out = xmalloc(maxsize);
191 stream.avail_in = size;
192 stream.next_out = out;
193 stream.avail_out = maxsize;
194 while (git_deflate(&stream, Z_FINISH) == Z_OK)
196 git_deflate_end(&stream);
199 return stream.total_out;
202 static unsigned long write_large_blob_data(struct git_istream *st, struct hashfile *f,
203 const struct object_id *oid)
206 unsigned char ibuf[1024 * 16];
207 unsigned char obuf[1024 * 16];
208 unsigned long olen = 0;
210 git_deflate_init(&stream, pack_compression_level);
215 readlen = read_istream(st, ibuf, sizeof(ibuf));
217 die(_("unable to read %s"), oid_to_hex(oid));
219 stream.next_in = ibuf;
220 stream.avail_in = readlen;
221 while ((stream.avail_in || readlen == 0) &&
222 (zret == Z_OK || zret == Z_BUF_ERROR)) {
223 stream.next_out = obuf;
224 stream.avail_out = sizeof(obuf);
225 zret = git_deflate(&stream, readlen ? 0 : Z_FINISH);
226 hashwrite(f, obuf, stream.next_out - obuf);
227 olen += stream.next_out - obuf;
230 die(_("deflate error (%d)"), zret);
232 if (zret != Z_STREAM_END)
233 die(_("deflate error (%d)"), zret);
237 git_deflate_end(&stream);
242 * we are going to reuse the existing object data as is. make
243 * sure it is not corrupt.
245 static int check_pack_inflate(struct packed_git *p,
246 struct pack_window **w_curs,
249 unsigned long expect)
252 unsigned char fakebuf[4096], *in;
255 memset(&stream, 0, sizeof(stream));
256 git_inflate_init(&stream);
258 in = use_pack(p, w_curs, offset, &stream.avail_in);
260 stream.next_out = fakebuf;
261 stream.avail_out = sizeof(fakebuf);
262 st = git_inflate(&stream, Z_FINISH);
263 offset += stream.next_in - in;
264 } while (st == Z_OK || st == Z_BUF_ERROR);
265 git_inflate_end(&stream);
266 return (st == Z_STREAM_END &&
267 stream.total_out == expect &&
268 stream.total_in == len) ? 0 : -1;
271 static void copy_pack_data(struct hashfile *f,
272 struct packed_git *p,
273 struct pack_window **w_curs,
281 in = use_pack(p, w_curs, offset, &avail);
283 avail = (unsigned long)len;
284 hashwrite(f, in, avail);
290 /* Return 0 if we will bust the pack-size limit */
291 static unsigned long write_no_reuse_object(struct hashfile *f, struct object_entry *entry,
292 unsigned long limit, int usable_delta)
294 unsigned long size, datalen;
295 unsigned char header[MAX_PACK_OBJECT_HEADER],
296 dheader[MAX_PACK_OBJECT_HEADER];
298 enum object_type type;
300 struct git_istream *st = NULL;
301 const unsigned hashsz = the_hash_algo->rawsz;
304 if (oe_type(entry) == OBJ_BLOB &&
305 oe_size_greater_than(&to_pack, entry, big_file_threshold) &&
306 (st = open_istream(the_repository, &entry->idx.oid, &type,
307 &size, NULL)) != NULL)
310 buf = read_object_file(&entry->idx.oid, &type, &size);
312 die(_("unable to read %s"),
313 oid_to_hex(&entry->idx.oid));
316 * make sure no cached delta data remains from a
317 * previous attempt before a pack split occurred.
319 FREE_AND_NULL(entry->delta_data);
320 entry->z_delta_size = 0;
321 } else if (entry->delta_data) {
322 size = DELTA_SIZE(entry);
323 buf = entry->delta_data;
324 entry->delta_data = NULL;
325 type = (allow_ofs_delta && DELTA(entry)->idx.offset) ?
326 OBJ_OFS_DELTA : OBJ_REF_DELTA;
328 buf = get_delta(entry);
329 size = DELTA_SIZE(entry);
330 type = (allow_ofs_delta && DELTA(entry)->idx.offset) ?
331 OBJ_OFS_DELTA : OBJ_REF_DELTA;
334 if (st) /* large blob case, just assume we don't compress well */
336 else if (entry->z_delta_size)
337 datalen = entry->z_delta_size;
339 datalen = do_compress(&buf, size);
342 * The object header is a byte of 'type' followed by zero or
343 * more bytes of length.
345 hdrlen = encode_in_pack_object_header(header, sizeof(header),
348 if (type == OBJ_OFS_DELTA) {
350 * Deltas with relative base contain an additional
351 * encoding of the relative offset for the delta
352 * base from this object's position in the pack.
354 off_t ofs = entry->idx.offset - DELTA(entry)->idx.offset;
355 unsigned pos = sizeof(dheader) - 1;
356 dheader[pos] = ofs & 127;
358 dheader[--pos] = 128 | (--ofs & 127);
359 if (limit && hdrlen + sizeof(dheader) - pos + datalen + hashsz >= limit) {
365 hashwrite(f, header, hdrlen);
366 hashwrite(f, dheader + pos, sizeof(dheader) - pos);
367 hdrlen += sizeof(dheader) - pos;
368 } else if (type == OBJ_REF_DELTA) {
370 * Deltas with a base reference contain
371 * additional bytes for the base object ID.
373 if (limit && hdrlen + hashsz + datalen + hashsz >= limit) {
379 hashwrite(f, header, hdrlen);
380 hashwrite(f, DELTA(entry)->idx.oid.hash, hashsz);
383 if (limit && hdrlen + datalen + hashsz >= limit) {
389 hashwrite(f, header, hdrlen);
392 datalen = write_large_blob_data(st, f, &entry->idx.oid);
395 hashwrite(f, buf, datalen);
399 return hdrlen + datalen;
402 /* Return 0 if we will bust the pack-size limit */
403 static off_t write_reuse_object(struct hashfile *f, struct object_entry *entry,
404 unsigned long limit, int usable_delta)
406 struct packed_git *p = IN_PACK(entry);
407 struct pack_window *w_curs = NULL;
408 struct revindex_entry *revidx;
410 enum object_type type = oe_type(entry);
412 unsigned char header[MAX_PACK_OBJECT_HEADER],
413 dheader[MAX_PACK_OBJECT_HEADER];
415 const unsigned hashsz = the_hash_algo->rawsz;
416 unsigned long entry_size = SIZE(entry);
419 type = (allow_ofs_delta && DELTA(entry)->idx.offset) ?
420 OBJ_OFS_DELTA : OBJ_REF_DELTA;
421 hdrlen = encode_in_pack_object_header(header, sizeof(header),
424 offset = entry->in_pack_offset;
425 revidx = find_pack_revindex(p, offset);
426 datalen = revidx[1].offset - offset;
427 if (!pack_to_stdout && p->index_version > 1 &&
428 check_pack_crc(p, &w_curs, offset, datalen, revidx->nr)) {
429 error(_("bad packed object CRC for %s"),
430 oid_to_hex(&entry->idx.oid));
432 return write_no_reuse_object(f, entry, limit, usable_delta);
435 offset += entry->in_pack_header_size;
436 datalen -= entry->in_pack_header_size;
438 if (!pack_to_stdout && p->index_version == 1 &&
439 check_pack_inflate(p, &w_curs, offset, datalen, entry_size)) {
440 error(_("corrupt packed object for %s"),
441 oid_to_hex(&entry->idx.oid));
443 return write_no_reuse_object(f, entry, limit, usable_delta);
446 if (type == OBJ_OFS_DELTA) {
447 off_t ofs = entry->idx.offset - DELTA(entry)->idx.offset;
448 unsigned pos = sizeof(dheader) - 1;
449 dheader[pos] = ofs & 127;
451 dheader[--pos] = 128 | (--ofs & 127);
452 if (limit && hdrlen + sizeof(dheader) - pos + datalen + hashsz >= limit) {
456 hashwrite(f, header, hdrlen);
457 hashwrite(f, dheader + pos, sizeof(dheader) - pos);
458 hdrlen += sizeof(dheader) - pos;
460 } else if (type == OBJ_REF_DELTA) {
461 if (limit && hdrlen + hashsz + datalen + hashsz >= limit) {
465 hashwrite(f, header, hdrlen);
466 hashwrite(f, DELTA(entry)->idx.oid.hash, hashsz);
470 if (limit && hdrlen + datalen + hashsz >= limit) {
474 hashwrite(f, header, hdrlen);
476 copy_pack_data(f, p, &w_curs, offset, datalen);
479 return hdrlen + datalen;
482 /* Return 0 if we will bust the pack-size limit */
483 static off_t write_object(struct hashfile *f,
484 struct object_entry *entry,
489 int usable_delta, to_reuse;
494 /* apply size limit if limited packsize and not first object */
495 if (!pack_size_limit || !nr_written)
497 else if (pack_size_limit <= write_offset)
499 * the earlier object did not fit the limit; avoid
500 * mistaking this with unlimited (i.e. limit = 0).
504 limit = pack_size_limit - write_offset;
507 usable_delta = 0; /* no delta */
508 else if (!pack_size_limit)
509 usable_delta = 1; /* unlimited packfile */
510 else if (DELTA(entry)->idx.offset == (off_t)-1)
511 usable_delta = 0; /* base was written to another pack */
512 else if (DELTA(entry)->idx.offset)
513 usable_delta = 1; /* base already exists in this pack */
515 usable_delta = 0; /* base could end up in another pack */
518 to_reuse = 0; /* explicit */
519 else if (!IN_PACK(entry))
520 to_reuse = 0; /* can't reuse what we don't have */
521 else if (oe_type(entry) == OBJ_REF_DELTA ||
522 oe_type(entry) == OBJ_OFS_DELTA)
523 /* check_object() decided it for us ... */
524 to_reuse = usable_delta;
525 /* ... but pack split may override that */
526 else if (oe_type(entry) != entry->in_pack_type)
527 to_reuse = 0; /* pack has delta which is unusable */
528 else if (DELTA(entry))
529 to_reuse = 0; /* we want to pack afresh */
531 to_reuse = 1; /* we have it in-pack undeltified,
532 * and we do not need to deltify it.
536 len = write_no_reuse_object(f, entry, limit, usable_delta);
538 len = write_reuse_object(f, entry, limit, usable_delta);
546 entry->idx.crc32 = crc32_end(f);
550 enum write_one_status {
551 WRITE_ONE_SKIP = -1, /* already written */
552 WRITE_ONE_BREAK = 0, /* writing this will bust the limit; not written */
553 WRITE_ONE_WRITTEN = 1, /* normal */
554 WRITE_ONE_RECURSIVE = 2 /* already scheduled to be written */
557 static enum write_one_status write_one(struct hashfile *f,
558 struct object_entry *e,
565 * we set offset to 1 (which is an impossible value) to mark
566 * the fact that this object is involved in "write its base
567 * first before writing a deltified object" recursion.
569 recursing = (e->idx.offset == 1);
571 warning(_("recursive delta detected for object %s"),
572 oid_to_hex(&e->idx.oid));
573 return WRITE_ONE_RECURSIVE;
574 } else if (e->idx.offset || e->preferred_base) {
575 /* offset is non zero if object is written already. */
576 return WRITE_ONE_SKIP;
579 /* if we are deltified, write out base object first. */
581 e->idx.offset = 1; /* now recurse */
582 switch (write_one(f, DELTA(e), offset)) {
583 case WRITE_ONE_RECURSIVE:
584 /* we cannot depend on this one */
589 case WRITE_ONE_BREAK:
590 e->idx.offset = recursing;
591 return WRITE_ONE_BREAK;
595 e->idx.offset = *offset;
596 size = write_object(f, e, *offset);
598 e->idx.offset = recursing;
599 return WRITE_ONE_BREAK;
601 written_list[nr_written++] = &e->idx;
603 /* make sure off_t is sufficiently large not to wrap */
604 if (signed_add_overflows(*offset, size))
605 die(_("pack too large for current definition of off_t"));
607 return WRITE_ONE_WRITTEN;
610 static int mark_tagged(const char *path, const struct object_id *oid, int flag,
613 struct object_id peeled;
614 struct object_entry *entry = packlist_find(&to_pack, oid);
618 if (!peel_ref(path, &peeled)) {
619 entry = packlist_find(&to_pack, &peeled);
626 static inline void add_to_write_order(struct object_entry **wo,
628 struct object_entry *e)
630 if (e->filled || oe_layer(&to_pack, e) != write_layer)
636 static void add_descendants_to_write_order(struct object_entry **wo,
638 struct object_entry *e)
640 int add_to_order = 1;
643 struct object_entry *s;
644 /* add this node... */
645 add_to_write_order(wo, endp, e);
646 /* all its siblings... */
647 for (s = DELTA_SIBLING(e); s; s = DELTA_SIBLING(s)) {
648 add_to_write_order(wo, endp, s);
651 /* drop down a level to add left subtree nodes if possible */
652 if (DELTA_CHILD(e)) {
657 /* our sibling might have some children, it is next */
658 if (DELTA_SIBLING(e)) {
659 e = DELTA_SIBLING(e);
662 /* go back to our parent node */
664 while (e && !DELTA_SIBLING(e)) {
665 /* we're on the right side of a subtree, keep
666 * going up until we can go right again */
670 /* done- we hit our original root node */
673 /* pass it off to sibling at this level */
674 e = DELTA_SIBLING(e);
679 static void add_family_to_write_order(struct object_entry **wo,
681 struct object_entry *e)
683 struct object_entry *root;
685 for (root = e; DELTA(root); root = DELTA(root))
687 add_descendants_to_write_order(wo, endp, root);
690 static void compute_layer_order(struct object_entry **wo, unsigned int *wo_end)
692 unsigned int i, last_untagged;
693 struct object_entry *objects = to_pack.objects;
695 for (i = 0; i < to_pack.nr_objects; i++) {
696 if (objects[i].tagged)
698 add_to_write_order(wo, wo_end, &objects[i]);
703 * Then fill all the tagged tips.
705 for (; i < to_pack.nr_objects; i++) {
706 if (objects[i].tagged)
707 add_to_write_order(wo, wo_end, &objects[i]);
711 * And then all remaining commits and tags.
713 for (i = last_untagged; i < to_pack.nr_objects; i++) {
714 if (oe_type(&objects[i]) != OBJ_COMMIT &&
715 oe_type(&objects[i]) != OBJ_TAG)
717 add_to_write_order(wo, wo_end, &objects[i]);
721 * And then all the trees.
723 for (i = last_untagged; i < to_pack.nr_objects; i++) {
724 if (oe_type(&objects[i]) != OBJ_TREE)
726 add_to_write_order(wo, wo_end, &objects[i]);
730 * Finally all the rest in really tight order
732 for (i = last_untagged; i < to_pack.nr_objects; i++) {
733 if (!objects[i].filled && oe_layer(&to_pack, &objects[i]) == write_layer)
734 add_family_to_write_order(wo, wo_end, &objects[i]);
738 static struct object_entry **compute_write_order(void)
740 uint32_t max_layers = 1;
741 unsigned int i, wo_end;
743 struct object_entry **wo;
744 struct object_entry *objects = to_pack.objects;
746 for (i = 0; i < to_pack.nr_objects; i++) {
747 objects[i].tagged = 0;
748 objects[i].filled = 0;
749 SET_DELTA_CHILD(&objects[i], NULL);
750 SET_DELTA_SIBLING(&objects[i], NULL);
754 * Fully connect delta_child/delta_sibling network.
755 * Make sure delta_sibling is sorted in the original
758 for (i = to_pack.nr_objects; i > 0;) {
759 struct object_entry *e = &objects[--i];
762 /* Mark me as the first child */
763 e->delta_sibling_idx = DELTA(e)->delta_child_idx;
764 SET_DELTA_CHILD(DELTA(e), e);
768 * Mark objects that are at the tip of tags.
770 for_each_tag_ref(mark_tagged, NULL);
772 if (use_delta_islands)
773 max_layers = compute_pack_layers(&to_pack);
775 ALLOC_ARRAY(wo, to_pack.nr_objects);
778 for (; write_layer < max_layers; ++write_layer)
779 compute_layer_order(wo, &wo_end);
781 if (wo_end != to_pack.nr_objects)
782 die(_("ordered %u objects, expected %"PRIu32),
783 wo_end, to_pack.nr_objects);
788 static off_t write_reused_pack(struct hashfile *f)
790 unsigned char buffer[8192];
791 off_t to_write, total;
794 if (!is_pack_valid(reuse_packfile))
795 die(_("packfile is invalid: %s"), reuse_packfile->pack_name);
797 fd = git_open(reuse_packfile->pack_name);
799 die_errno(_("unable to open packfile for reuse: %s"),
800 reuse_packfile->pack_name);
802 if (lseek(fd, sizeof(struct pack_header), SEEK_SET) == -1)
803 die_errno(_("unable to seek in reused packfile"));
805 if (reuse_packfile_offset < 0)
806 reuse_packfile_offset = reuse_packfile->pack_size - the_hash_algo->rawsz;
808 total = to_write = reuse_packfile_offset - sizeof(struct pack_header);
811 int read_pack = xread(fd, buffer, sizeof(buffer));
814 die_errno(_("unable to read from reused packfile"));
816 if (read_pack > to_write)
817 read_pack = to_write;
819 hashwrite(f, buffer, read_pack);
820 to_write -= read_pack;
823 * We don't know the actual number of objects written,
824 * only how many bytes written, how many bytes total, and
825 * how many objects total. So we can fake it by pretending all
826 * objects we are writing are the same size. This gives us a
827 * smooth progress meter, and at the end it matches the true
830 written = reuse_packfile_objects *
831 (((double)(total - to_write)) / total);
832 display_progress(progress_state, written);
836 written = reuse_packfile_objects;
837 display_progress(progress_state, written);
838 return reuse_packfile_offset - sizeof(struct pack_header);
841 static const char no_split_warning[] = N_(
842 "disabling bitmap writing, packs are split due to pack.packSizeLimit"
845 static void write_pack_file(void)
850 uint32_t nr_remaining = nr_result;
851 time_t last_mtime = 0;
852 struct object_entry **write_order;
854 if (progress > pack_to_stdout)
855 progress_state = start_progress(_("Writing objects"), nr_result);
856 ALLOC_ARRAY(written_list, to_pack.nr_objects);
857 write_order = compute_write_order();
860 struct object_id oid;
861 char *pack_tmp_name = NULL;
864 f = hashfd_throughput(1, "<stdout>", progress_state);
866 f = create_tmp_packfile(&pack_tmp_name);
868 offset = write_pack_header(f, nr_remaining);
870 if (reuse_packfile) {
872 assert(pack_to_stdout);
874 packfile_size = write_reused_pack(f);
875 offset += packfile_size;
879 for (; i < to_pack.nr_objects; i++) {
880 struct object_entry *e = write_order[i];
881 if (write_one(f, e, &offset) == WRITE_ONE_BREAK)
883 display_progress(progress_state, written);
887 * Did we write the wrong # entries in the header?
888 * If so, rewrite it like in fast-import
890 if (pack_to_stdout) {
891 finalize_hashfile(f, oid.hash, CSUM_HASH_IN_STREAM | CSUM_CLOSE);
892 } else if (nr_written == nr_remaining) {
893 finalize_hashfile(f, oid.hash, CSUM_HASH_IN_STREAM | CSUM_FSYNC | CSUM_CLOSE);
895 int fd = finalize_hashfile(f, oid.hash, 0);
896 fixup_pack_header_footer(fd, oid.hash, pack_tmp_name,
897 nr_written, oid.hash, offset);
899 if (write_bitmap_index) {
900 if (write_bitmap_index != WRITE_BITMAP_QUIET)
901 warning(_(no_split_warning));
902 write_bitmap_index = 0;
906 if (!pack_to_stdout) {
908 struct strbuf tmpname = STRBUF_INIT;
911 * Packs are runtime accessed in their mtime
912 * order since newer packs are more likely to contain
913 * younger objects. So if we are creating multiple
914 * packs then we should modify the mtime of later ones
915 * to preserve this property.
917 if (stat(pack_tmp_name, &st) < 0) {
918 warning_errno(_("failed to stat %s"), pack_tmp_name);
919 } else if (!last_mtime) {
920 last_mtime = st.st_mtime;
923 utb.actime = st.st_atime;
924 utb.modtime = --last_mtime;
925 if (utime(pack_tmp_name, &utb) < 0)
926 warning_errno(_("failed utime() on %s"), pack_tmp_name);
929 strbuf_addf(&tmpname, "%s-", base_name);
931 if (write_bitmap_index) {
932 bitmap_writer_set_checksum(oid.hash);
933 bitmap_writer_build_type_index(
934 &to_pack, written_list, nr_written);
937 finish_tmp_packfile(&tmpname, pack_tmp_name,
938 written_list, nr_written,
939 &pack_idx_opts, oid.hash);
941 if (write_bitmap_index) {
942 strbuf_addf(&tmpname, "%s.bitmap", oid_to_hex(&oid));
944 stop_progress(&progress_state);
946 bitmap_writer_show_progress(progress);
947 bitmap_writer_reuse_bitmaps(&to_pack);
948 bitmap_writer_select_commits(indexed_commits, indexed_commits_nr, -1);
949 bitmap_writer_build(&to_pack);
950 bitmap_writer_finish(written_list, nr_written,
951 tmpname.buf, write_bitmap_options);
952 write_bitmap_index = 0;
955 strbuf_release(&tmpname);
957 puts(oid_to_hex(&oid));
960 /* mark written objects as written to previous pack */
961 for (j = 0; j < nr_written; j++) {
962 written_list[j]->offset = (off_t)-1;
964 nr_remaining -= nr_written;
965 } while (nr_remaining && i < to_pack.nr_objects);
969 stop_progress(&progress_state);
970 if (written != nr_result)
971 die(_("wrote %"PRIu32" objects while expecting %"PRIu32),
973 trace2_data_intmax("pack-objects", the_repository,
974 "write_pack_file/wrote", nr_result);
977 static int no_try_delta(const char *path)
979 static struct attr_check *check;
982 check = attr_check_initl("delta", NULL);
983 git_check_attr(the_repository->index, path, check);
984 if (ATTR_FALSE(check->items[0].value))
990 * When adding an object, check whether we have already added it
991 * to our packing list. If so, we can skip. However, if we are
992 * being asked to excludei t, but the previous mention was to include
993 * it, make sure to adjust its flags and tweak our numbers accordingly.
995 * As an optimization, we pass out the index position where we would have
996 * found the item, since that saves us from having to look it up again a
997 * few lines later when we want to add the new entry.
999 static int have_duplicate_entry(const struct object_id *oid,
1002 struct object_entry *entry;
1004 entry = packlist_find(&to_pack, oid);
1009 if (!entry->preferred_base)
1011 entry->preferred_base = 1;
1017 static int want_found_object(int exclude, struct packed_git *p)
1025 * When asked to do --local (do not include an object that appears in a
1026 * pack we borrow from elsewhere) or --honor-pack-keep (do not include
1027 * an object that appears in a pack marked with .keep), finding a pack
1028 * that matches the criteria is sufficient for us to decide to omit it.
1029 * However, even if this pack does not satisfy the criteria, we need to
1030 * make sure no copy of this object appears in _any_ pack that makes us
1031 * to omit the object, so we need to check all the packs.
1033 * We can however first check whether these options can possible matter;
1034 * if they do not matter we know we want the object in generated pack.
1035 * Otherwise, we signal "-1" at the end to tell the caller that we do
1036 * not know either way, and it needs to check more packs.
1038 if (!ignore_packed_keep_on_disk &&
1039 !ignore_packed_keep_in_core &&
1040 (!local || !have_non_local_packs))
1043 if (local && !p->pack_local)
1045 if (p->pack_local &&
1046 ((ignore_packed_keep_on_disk && p->pack_keep) ||
1047 (ignore_packed_keep_in_core && p->pack_keep_in_core)))
1050 /* we don't know yet; keep looking for more packs */
1055 * Check whether we want the object in the pack (e.g., we do not want
1056 * objects found in non-local stores if the "--local" option was used).
1058 * If the caller already knows an existing pack it wants to take the object
1059 * from, that is passed in *found_pack and *found_offset; otherwise this
1060 * function finds if there is any pack that has the object and returns the pack
1061 * and its offset in these variables.
1063 static int want_object_in_pack(const struct object_id *oid,
1065 struct packed_git **found_pack,
1066 off_t *found_offset)
1069 struct list_head *pos;
1070 struct multi_pack_index *m;
1072 if (!exclude && local && has_loose_object_nonlocal(oid))
1076 * If we already know the pack object lives in, start checks from that
1077 * pack - in the usual case when neither --local was given nor .keep files
1078 * are present we will determine the answer right now.
1081 want = want_found_object(exclude, *found_pack);
1086 for (m = get_multi_pack_index(the_repository); m; m = m->next) {
1087 struct pack_entry e;
1088 if (fill_midx_entry(the_repository, oid, &e, m)) {
1089 struct packed_git *p = e.p;
1092 if (p == *found_pack)
1093 offset = *found_offset;
1095 offset = find_pack_entry_one(oid->hash, p);
1099 if (!is_pack_valid(p))
1101 *found_offset = offset;
1104 want = want_found_object(exclude, p);
1111 list_for_each(pos, get_packed_git_mru(the_repository)) {
1112 struct packed_git *p = list_entry(pos, struct packed_git, mru);
1115 if (p == *found_pack)
1116 offset = *found_offset;
1118 offset = find_pack_entry_one(oid->hash, p);
1122 if (!is_pack_valid(p))
1124 *found_offset = offset;
1127 want = want_found_object(exclude, p);
1128 if (!exclude && want > 0)
1130 get_packed_git_mru(the_repository));
1139 static void create_object_entry(const struct object_id *oid,
1140 enum object_type type,
1144 struct packed_git *found_pack,
1147 struct object_entry *entry;
1149 entry = packlist_alloc(&to_pack, oid);
1151 oe_set_type(entry, type);
1153 entry->preferred_base = 1;
1157 oe_set_in_pack(&to_pack, entry, found_pack);
1158 entry->in_pack_offset = found_offset;
1161 entry->no_try_delta = no_try_delta;
1164 static const char no_closure_warning[] = N_(
1165 "disabling bitmap writing, as some objects are not being packed"
1168 static int add_object_entry(const struct object_id *oid, enum object_type type,
1169 const char *name, int exclude)
1171 struct packed_git *found_pack = NULL;
1172 off_t found_offset = 0;
1174 display_progress(progress_state, ++nr_seen);
1176 if (have_duplicate_entry(oid, exclude))
1179 if (!want_object_in_pack(oid, exclude, &found_pack, &found_offset)) {
1180 /* The pack is missing an object, so it will not have closure */
1181 if (write_bitmap_index) {
1182 if (write_bitmap_index != WRITE_BITMAP_QUIET)
1183 warning(_(no_closure_warning));
1184 write_bitmap_index = 0;
1189 create_object_entry(oid, type, pack_name_hash(name),
1190 exclude, name && no_try_delta(name),
1191 found_pack, found_offset);
1195 static int add_object_entry_from_bitmap(const struct object_id *oid,
1196 enum object_type type,
1197 int flags, uint32_t name_hash,
1198 struct packed_git *pack, off_t offset)
1200 display_progress(progress_state, ++nr_seen);
1202 if (have_duplicate_entry(oid, 0))
1205 if (!want_object_in_pack(oid, 0, &pack, &offset))
1208 create_object_entry(oid, type, name_hash, 0, 0, pack, offset);
1212 struct pbase_tree_cache {
1213 struct object_id oid;
1217 unsigned long tree_size;
1220 static struct pbase_tree_cache *(pbase_tree_cache[256]);
1221 static int pbase_tree_cache_ix(const struct object_id *oid)
1223 return oid->hash[0] % ARRAY_SIZE(pbase_tree_cache);
1225 static int pbase_tree_cache_ix_incr(int ix)
1227 return (ix+1) % ARRAY_SIZE(pbase_tree_cache);
1230 static struct pbase_tree {
1231 struct pbase_tree *next;
1232 /* This is a phony "cache" entry; we are not
1233 * going to evict it or find it through _get()
1234 * mechanism -- this is for the toplevel node that
1235 * would almost always change with any commit.
1237 struct pbase_tree_cache pcache;
1240 static struct pbase_tree_cache *pbase_tree_get(const struct object_id *oid)
1242 struct pbase_tree_cache *ent, *nent;
1245 enum object_type type;
1247 int my_ix = pbase_tree_cache_ix(oid);
1248 int available_ix = -1;
1250 /* pbase-tree-cache acts as a limited hashtable.
1251 * your object will be found at your index or within a few
1252 * slots after that slot if it is cached.
1254 for (neigh = 0; neigh < 8; neigh++) {
1255 ent = pbase_tree_cache[my_ix];
1256 if (ent && oideq(&ent->oid, oid)) {
1260 else if (((available_ix < 0) && (!ent || !ent->ref)) ||
1261 ((0 <= available_ix) &&
1262 (!ent && pbase_tree_cache[available_ix])))
1263 available_ix = my_ix;
1266 my_ix = pbase_tree_cache_ix_incr(my_ix);
1269 /* Did not find one. Either we got a bogus request or
1270 * we need to read and perhaps cache.
1272 data = read_object_file(oid, &type, &size);
1275 if (type != OBJ_TREE) {
1280 /* We need to either cache or return a throwaway copy */
1282 if (available_ix < 0)
1285 ent = pbase_tree_cache[available_ix];
1286 my_ix = available_ix;
1290 nent = xmalloc(sizeof(*nent));
1291 nent->temporary = (available_ix < 0);
1294 /* evict and reuse */
1295 free(ent->tree_data);
1298 oidcpy(&nent->oid, oid);
1299 nent->tree_data = data;
1300 nent->tree_size = size;
1302 if (!nent->temporary)
1303 pbase_tree_cache[my_ix] = nent;
1307 static void pbase_tree_put(struct pbase_tree_cache *cache)
1309 if (!cache->temporary) {
1313 free(cache->tree_data);
1317 static int name_cmp_len(const char *name)
1320 for (i = 0; name[i] && name[i] != '\n' && name[i] != '/'; i++)
1325 static void add_pbase_object(struct tree_desc *tree,
1328 const char *fullname)
1330 struct name_entry entry;
1333 while (tree_entry(tree,&entry)) {
1334 if (S_ISGITLINK(entry.mode))
1336 cmp = tree_entry_len(&entry) != cmplen ? 1 :
1337 memcmp(name, entry.path, cmplen);
1342 if (name[cmplen] != '/') {
1343 add_object_entry(&entry.oid,
1344 object_type(entry.mode),
1348 if (S_ISDIR(entry.mode)) {
1349 struct tree_desc sub;
1350 struct pbase_tree_cache *tree;
1351 const char *down = name+cmplen+1;
1352 int downlen = name_cmp_len(down);
1354 tree = pbase_tree_get(&entry.oid);
1357 init_tree_desc(&sub, tree->tree_data, tree->tree_size);
1359 add_pbase_object(&sub, down, downlen, fullname);
1360 pbase_tree_put(tree);
1365 static unsigned *done_pbase_paths;
1366 static int done_pbase_paths_num;
1367 static int done_pbase_paths_alloc;
1368 static int done_pbase_path_pos(unsigned hash)
1371 int hi = done_pbase_paths_num;
1373 int mi = lo + (hi - lo) / 2;
1374 if (done_pbase_paths[mi] == hash)
1376 if (done_pbase_paths[mi] < hash)
1384 static int check_pbase_path(unsigned hash)
1386 int pos = done_pbase_path_pos(hash);
1390 ALLOC_GROW(done_pbase_paths,
1391 done_pbase_paths_num + 1,
1392 done_pbase_paths_alloc);
1393 done_pbase_paths_num++;
1394 if (pos < done_pbase_paths_num)
1395 MOVE_ARRAY(done_pbase_paths + pos + 1, done_pbase_paths + pos,
1396 done_pbase_paths_num - pos - 1);
1397 done_pbase_paths[pos] = hash;
1401 static void add_preferred_base_object(const char *name)
1403 struct pbase_tree *it;
1405 unsigned hash = pack_name_hash(name);
1407 if (!num_preferred_base || check_pbase_path(hash))
1410 cmplen = name_cmp_len(name);
1411 for (it = pbase_tree; it; it = it->next) {
1413 add_object_entry(&it->pcache.oid, OBJ_TREE, NULL, 1);
1416 struct tree_desc tree;
1417 init_tree_desc(&tree, it->pcache.tree_data, it->pcache.tree_size);
1418 add_pbase_object(&tree, name, cmplen, name);
1423 static void add_preferred_base(struct object_id *oid)
1425 struct pbase_tree *it;
1428 struct object_id tree_oid;
1430 if (window <= num_preferred_base++)
1433 data = read_object_with_reference(the_repository, oid,
1434 tree_type, &size, &tree_oid);
1438 for (it = pbase_tree; it; it = it->next) {
1439 if (oideq(&it->pcache.oid, &tree_oid)) {
1445 it = xcalloc(1, sizeof(*it));
1446 it->next = pbase_tree;
1449 oidcpy(&it->pcache.oid, &tree_oid);
1450 it->pcache.tree_data = data;
1451 it->pcache.tree_size = size;
1454 static void cleanup_preferred_base(void)
1456 struct pbase_tree *it;
1462 struct pbase_tree *tmp = it;
1464 free(tmp->pcache.tree_data);
1468 for (i = 0; i < ARRAY_SIZE(pbase_tree_cache); i++) {
1469 if (!pbase_tree_cache[i])
1471 free(pbase_tree_cache[i]->tree_data);
1472 FREE_AND_NULL(pbase_tree_cache[i]);
1475 FREE_AND_NULL(done_pbase_paths);
1476 done_pbase_paths_num = done_pbase_paths_alloc = 0;
1480 * Return 1 iff the object specified by "delta" can be sent
1481 * literally as a delta against the base in "base_sha1". If
1482 * so, then *base_out will point to the entry in our packing
1483 * list, or NULL if we must use the external-base list.
1485 * Depth value does not matter - find_deltas() will
1486 * never consider reused delta as the base object to
1487 * deltify other objects against, in order to avoid
1490 static int can_reuse_delta(const unsigned char *base_sha1,
1491 struct object_entry *delta,
1492 struct object_entry **base_out)
1494 struct object_entry *base;
1495 struct object_id base_oid;
1500 oidread(&base_oid, base_sha1);
1503 * First see if we're already sending the base (or it's explicitly in
1504 * our "excluded" list).
1506 base = packlist_find(&to_pack, &base_oid);
1508 if (!in_same_island(&delta->idx.oid, &base->idx.oid))
1515 * Otherwise, reachability bitmaps may tell us if the receiver has it,
1516 * even if it was buried too deep in history to make it into the
1519 if (thin && bitmap_has_oid_in_uninteresting(bitmap_git, &base_oid)) {
1520 if (use_delta_islands) {
1521 if (!in_same_island(&delta->idx.oid, &base_oid))
1531 static void check_object(struct object_entry *entry)
1533 unsigned long canonical_size;
1535 if (IN_PACK(entry)) {
1536 struct packed_git *p = IN_PACK(entry);
1537 struct pack_window *w_curs = NULL;
1538 const unsigned char *base_ref = NULL;
1539 struct object_entry *base_entry;
1540 unsigned long used, used_0;
1541 unsigned long avail;
1543 unsigned char *buf, c;
1544 enum object_type type;
1545 unsigned long in_pack_size;
1547 buf = use_pack(p, &w_curs, entry->in_pack_offset, &avail);
1550 * We want in_pack_type even if we do not reuse delta
1551 * since non-delta representations could still be reused.
1553 used = unpack_object_header_buffer(buf, avail,
1560 BUG("invalid type %d", type);
1561 entry->in_pack_type = type;
1564 * Determine if this is a delta and if so whether we can
1565 * reuse it or not. Otherwise let's find out as cheaply as
1566 * possible what the actual type and size for this object is.
1568 switch (entry->in_pack_type) {
1570 /* Not a delta hence we've already got all we need. */
1571 oe_set_type(entry, entry->in_pack_type);
1572 SET_SIZE(entry, in_pack_size);
1573 entry->in_pack_header_size = used;
1574 if (oe_type(entry) < OBJ_COMMIT || oe_type(entry) > OBJ_BLOB)
1576 unuse_pack(&w_curs);
1579 if (reuse_delta && !entry->preferred_base)
1580 base_ref = use_pack(p, &w_curs,
1581 entry->in_pack_offset + used, NULL);
1582 entry->in_pack_header_size = used + the_hash_algo->rawsz;
1585 buf = use_pack(p, &w_curs,
1586 entry->in_pack_offset + used, NULL);
1592 if (!ofs || MSB(ofs, 7)) {
1593 error(_("delta base offset overflow in pack for %s"),
1594 oid_to_hex(&entry->idx.oid));
1598 ofs = (ofs << 7) + (c & 127);
1600 ofs = entry->in_pack_offset - ofs;
1601 if (ofs <= 0 || ofs >= entry->in_pack_offset) {
1602 error(_("delta base offset out of bound for %s"),
1603 oid_to_hex(&entry->idx.oid));
1606 if (reuse_delta && !entry->preferred_base) {
1607 struct revindex_entry *revidx;
1608 revidx = find_pack_revindex(p, ofs);
1611 base_ref = nth_packed_object_sha1(p, revidx->nr);
1613 entry->in_pack_header_size = used + used_0;
1617 if (can_reuse_delta(base_ref, entry, &base_entry)) {
1618 oe_set_type(entry, entry->in_pack_type);
1619 SET_SIZE(entry, in_pack_size); /* delta size */
1620 SET_DELTA_SIZE(entry, in_pack_size);
1623 SET_DELTA(entry, base_entry);
1624 entry->delta_sibling_idx = base_entry->delta_child_idx;
1625 SET_DELTA_CHILD(base_entry, entry);
1627 SET_DELTA_EXT(entry, base_ref);
1630 unuse_pack(&w_curs);
1634 if (oe_type(entry)) {
1638 * This must be a delta and we already know what the
1639 * final object type is. Let's extract the actual
1640 * object size from the delta header.
1642 delta_pos = entry->in_pack_offset + entry->in_pack_header_size;
1643 canonical_size = get_size_from_delta(p, &w_curs, delta_pos);
1644 if (canonical_size == 0)
1646 SET_SIZE(entry, canonical_size);
1647 unuse_pack(&w_curs);
1652 * No choice but to fall back to the recursive delta walk
1653 * with oid_object_info() to find about the object type
1657 unuse_pack(&w_curs);
1661 oid_object_info(the_repository, &entry->idx.oid, &canonical_size));
1662 if (entry->type_valid) {
1663 SET_SIZE(entry, canonical_size);
1666 * Bad object type is checked in prepare_pack(). This is
1667 * to permit a missing preferred base object to be ignored
1668 * as a preferred base. Doing so can result in a larger
1669 * pack file, but the transfer will still take place.
1674 static int pack_offset_sort(const void *_a, const void *_b)
1676 const struct object_entry *a = *(struct object_entry **)_a;
1677 const struct object_entry *b = *(struct object_entry **)_b;
1678 const struct packed_git *a_in_pack = IN_PACK(a);
1679 const struct packed_git *b_in_pack = IN_PACK(b);
1681 /* avoid filesystem trashing with loose objects */
1682 if (!a_in_pack && !b_in_pack)
1683 return oidcmp(&a->idx.oid, &b->idx.oid);
1685 if (a_in_pack < b_in_pack)
1687 if (a_in_pack > b_in_pack)
1689 return a->in_pack_offset < b->in_pack_offset ? -1 :
1690 (a->in_pack_offset > b->in_pack_offset);
1694 * Drop an on-disk delta we were planning to reuse. Naively, this would
1695 * just involve blanking out the "delta" field, but we have to deal
1696 * with some extra book-keeping:
1698 * 1. Removing ourselves from the delta_sibling linked list.
1700 * 2. Updating our size/type to the non-delta representation. These were
1701 * either not recorded initially (size) or overwritten with the delta type
1702 * (type) when check_object() decided to reuse the delta.
1704 * 3. Resetting our delta depth, as we are now a base object.
1706 static void drop_reused_delta(struct object_entry *entry)
1708 unsigned *idx = &to_pack.objects[entry->delta_idx - 1].delta_child_idx;
1709 struct object_info oi = OBJECT_INFO_INIT;
1710 enum object_type type;
1714 struct object_entry *oe = &to_pack.objects[*idx - 1];
1717 *idx = oe->delta_sibling_idx;
1719 idx = &oe->delta_sibling_idx;
1721 SET_DELTA(entry, NULL);
1726 if (packed_object_info(the_repository, IN_PACK(entry), entry->in_pack_offset, &oi) < 0) {
1728 * We failed to get the info from this pack for some reason;
1729 * fall back to oid_object_info, which may find another copy.
1730 * And if that fails, the error will be recorded in oe_type(entry)
1731 * and dealt with in prepare_pack().
1734 oid_object_info(the_repository, &entry->idx.oid, &size));
1736 oe_set_type(entry, type);
1738 SET_SIZE(entry, size);
1742 * Follow the chain of deltas from this entry onward, throwing away any links
1743 * that cause us to hit a cycle (as determined by the DFS state flags in
1746 * We also detect too-long reused chains that would violate our --depth
1749 static void break_delta_chains(struct object_entry *entry)
1752 * The actual depth of each object we will write is stored as an int,
1753 * as it cannot exceed our int "depth" limit. But before we break
1754 * changes based no that limit, we may potentially go as deep as the
1755 * number of objects, which is elsewhere bounded to a uint32_t.
1757 uint32_t total_depth;
1758 struct object_entry *cur, *next;
1760 for (cur = entry, total_depth = 0;
1762 cur = DELTA(cur), total_depth++) {
1763 if (cur->dfs_state == DFS_DONE) {
1765 * We've already seen this object and know it isn't
1766 * part of a cycle. We do need to append its depth
1769 total_depth += cur->depth;
1774 * We break cycles before looping, so an ACTIVE state (or any
1775 * other cruft which made its way into the state variable)
1778 if (cur->dfs_state != DFS_NONE)
1779 BUG("confusing delta dfs state in first pass: %d",
1783 * Now we know this is the first time we've seen the object. If
1784 * it's not a delta, we're done traversing, but we'll mark it
1785 * done to save time on future traversals.
1788 cur->dfs_state = DFS_DONE;
1793 * Mark ourselves as active and see if the next step causes
1794 * us to cycle to another active object. It's important to do
1795 * this _before_ we loop, because it impacts where we make the
1796 * cut, and thus how our total_depth counter works.
1797 * E.g., We may see a partial loop like:
1799 * A -> B -> C -> D -> B
1801 * Cutting B->C breaks the cycle. But now the depth of A is
1802 * only 1, and our total_depth counter is at 3. The size of the
1803 * error is always one less than the size of the cycle we
1804 * broke. Commits C and D were "lost" from A's chain.
1806 * If we instead cut D->B, then the depth of A is correct at 3.
1807 * We keep all commits in the chain that we examined.
1809 cur->dfs_state = DFS_ACTIVE;
1810 if (DELTA(cur)->dfs_state == DFS_ACTIVE) {
1811 drop_reused_delta(cur);
1812 cur->dfs_state = DFS_DONE;
1818 * And now that we've gone all the way to the bottom of the chain, we
1819 * need to clear the active flags and set the depth fields as
1820 * appropriate. Unlike the loop above, which can quit when it drops a
1821 * delta, we need to keep going to look for more depth cuts. So we need
1822 * an extra "next" pointer to keep going after we reset cur->delta.
1824 for (cur = entry; cur; cur = next) {
1828 * We should have a chain of zero or more ACTIVE states down to
1829 * a final DONE. We can quit after the DONE, because either it
1830 * has no bases, or we've already handled them in a previous
1833 if (cur->dfs_state == DFS_DONE)
1835 else if (cur->dfs_state != DFS_ACTIVE)
1836 BUG("confusing delta dfs state in second pass: %d",
1840 * If the total_depth is more than depth, then we need to snip
1841 * the chain into two or more smaller chains that don't exceed
1842 * the maximum depth. Most of the resulting chains will contain
1843 * (depth + 1) entries (i.e., depth deltas plus one base), and
1844 * the last chain (i.e., the one containing entry) will contain
1845 * whatever entries are left over, namely
1846 * (total_depth % (depth + 1)) of them.
1848 * Since we are iterating towards decreasing depth, we need to
1849 * decrement total_depth as we go, and we need to write to the
1850 * entry what its final depth will be after all of the
1851 * snipping. Since we're snipping into chains of length (depth
1852 * + 1) entries, the final depth of an entry will be its
1853 * original depth modulo (depth + 1). Any time we encounter an
1854 * entry whose final depth is supposed to be zero, we snip it
1855 * from its delta base, thereby making it so.
1857 cur->depth = (total_depth--) % (depth + 1);
1859 drop_reused_delta(cur);
1861 cur->dfs_state = DFS_DONE;
1865 static void get_object_details(void)
1868 struct object_entry **sorted_by_offset;
1871 progress_state = start_progress(_("Counting objects"),
1872 to_pack.nr_objects);
1874 sorted_by_offset = xcalloc(to_pack.nr_objects, sizeof(struct object_entry *));
1875 for (i = 0; i < to_pack.nr_objects; i++)
1876 sorted_by_offset[i] = to_pack.objects + i;
1877 QSORT(sorted_by_offset, to_pack.nr_objects, pack_offset_sort);
1879 for (i = 0; i < to_pack.nr_objects; i++) {
1880 struct object_entry *entry = sorted_by_offset[i];
1881 check_object(entry);
1882 if (entry->type_valid &&
1883 oe_size_greater_than(&to_pack, entry, big_file_threshold))
1884 entry->no_try_delta = 1;
1885 display_progress(progress_state, i + 1);
1887 stop_progress(&progress_state);
1890 * This must happen in a second pass, since we rely on the delta
1891 * information for the whole list being completed.
1893 for (i = 0; i < to_pack.nr_objects; i++)
1894 break_delta_chains(&to_pack.objects[i]);
1896 free(sorted_by_offset);
1900 * We search for deltas in a list sorted by type, by filename hash, and then
1901 * by size, so that we see progressively smaller and smaller files.
1902 * That's because we prefer deltas to be from the bigger file
1903 * to the smaller -- deletes are potentially cheaper, but perhaps
1904 * more importantly, the bigger file is likely the more recent
1905 * one. The deepest deltas are therefore the oldest objects which are
1906 * less susceptible to be accessed often.
1908 static int type_size_sort(const void *_a, const void *_b)
1910 const struct object_entry *a = *(struct object_entry **)_a;
1911 const struct object_entry *b = *(struct object_entry **)_b;
1912 const enum object_type a_type = oe_type(a);
1913 const enum object_type b_type = oe_type(b);
1914 const unsigned long a_size = SIZE(a);
1915 const unsigned long b_size = SIZE(b);
1917 if (a_type > b_type)
1919 if (a_type < b_type)
1921 if (a->hash > b->hash)
1923 if (a->hash < b->hash)
1925 if (a->preferred_base > b->preferred_base)
1927 if (a->preferred_base < b->preferred_base)
1929 if (use_delta_islands) {
1930 const int island_cmp = island_delta_cmp(&a->idx.oid, &b->idx.oid);
1934 if (a_size > b_size)
1936 if (a_size < b_size)
1938 return a < b ? -1 : (a > b); /* newest first */
1942 struct object_entry *entry;
1944 struct delta_index *index;
1948 static int delta_cacheable(unsigned long src_size, unsigned long trg_size,
1949 unsigned long delta_size)
1951 if (max_delta_cache_size && delta_cache_size + delta_size > max_delta_cache_size)
1954 if (delta_size < cache_max_small_delta_size)
1957 /* cache delta, if objects are large enough compared to delta size */
1958 if ((src_size >> 20) + (trg_size >> 21) > (delta_size >> 10))
1964 /* Protect delta_cache_size */
1965 static pthread_mutex_t cache_mutex;
1966 #define cache_lock() pthread_mutex_lock(&cache_mutex)
1967 #define cache_unlock() pthread_mutex_unlock(&cache_mutex)
1970 * Protect object list partitioning (e.g. struct thread_param) and
1973 static pthread_mutex_t progress_mutex;
1974 #define progress_lock() pthread_mutex_lock(&progress_mutex)
1975 #define progress_unlock() pthread_mutex_unlock(&progress_mutex)
1978 * Access to struct object_entry is unprotected since each thread owns
1979 * a portion of the main object list. Just don't access object entries
1980 * ahead in the list because they can be stolen and would need
1981 * progress_mutex for protection.
1985 * Return the size of the object without doing any delta
1986 * reconstruction (so non-deltas are true object sizes, but deltas
1987 * return the size of the delta data).
1989 unsigned long oe_get_size_slow(struct packing_data *pack,
1990 const struct object_entry *e)
1992 struct packed_git *p;
1993 struct pack_window *w_curs;
1995 enum object_type type;
1996 unsigned long used, avail, size;
1998 if (e->type_ != OBJ_OFS_DELTA && e->type_ != OBJ_REF_DELTA) {
1999 packing_data_lock(&to_pack);
2000 if (oid_object_info(the_repository, &e->idx.oid, &size) < 0)
2001 die(_("unable to get size of %s"),
2002 oid_to_hex(&e->idx.oid));
2003 packing_data_unlock(&to_pack);
2007 p = oe_in_pack(pack, e);
2009 BUG("when e->type is a delta, it must belong to a pack");
2011 packing_data_lock(&to_pack);
2013 buf = use_pack(p, &w_curs, e->in_pack_offset, &avail);
2014 used = unpack_object_header_buffer(buf, avail, &type, &size);
2016 die(_("unable to parse object header of %s"),
2017 oid_to_hex(&e->idx.oid));
2019 unuse_pack(&w_curs);
2020 packing_data_unlock(&to_pack);
2024 static int try_delta(struct unpacked *trg, struct unpacked *src,
2025 unsigned max_depth, unsigned long *mem_usage)
2027 struct object_entry *trg_entry = trg->entry;
2028 struct object_entry *src_entry = src->entry;
2029 unsigned long trg_size, src_size, delta_size, sizediff, max_size, sz;
2031 enum object_type type;
2034 /* Don't bother doing diffs between different types */
2035 if (oe_type(trg_entry) != oe_type(src_entry))
2039 * We do not bother to try a delta that we discarded on an
2040 * earlier try, but only when reusing delta data. Note that
2041 * src_entry that is marked as the preferred_base should always
2042 * be considered, as even if we produce a suboptimal delta against
2043 * it, we will still save the transfer cost, as we already know
2044 * the other side has it and we won't send src_entry at all.
2046 if (reuse_delta && IN_PACK(trg_entry) &&
2047 IN_PACK(trg_entry) == IN_PACK(src_entry) &&
2048 !src_entry->preferred_base &&
2049 trg_entry->in_pack_type != OBJ_REF_DELTA &&
2050 trg_entry->in_pack_type != OBJ_OFS_DELTA)
2053 /* Let's not bust the allowed depth. */
2054 if (src->depth >= max_depth)
2057 /* Now some size filtering heuristics. */
2058 trg_size = SIZE(trg_entry);
2059 if (!DELTA(trg_entry)) {
2060 max_size = trg_size/2 - the_hash_algo->rawsz;
2063 max_size = DELTA_SIZE(trg_entry);
2064 ref_depth = trg->depth;
2066 max_size = (uint64_t)max_size * (max_depth - src->depth) /
2067 (max_depth - ref_depth + 1);
2070 src_size = SIZE(src_entry);
2071 sizediff = src_size < trg_size ? trg_size - src_size : 0;
2072 if (sizediff >= max_size)
2074 if (trg_size < src_size / 32)
2077 if (!in_same_island(&trg->entry->idx.oid, &src->entry->idx.oid))
2080 /* Load data if not already done */
2082 packing_data_lock(&to_pack);
2083 trg->data = read_object_file(&trg_entry->idx.oid, &type, &sz);
2084 packing_data_unlock(&to_pack);
2086 die(_("object %s cannot be read"),
2087 oid_to_hex(&trg_entry->idx.oid));
2089 die(_("object %s inconsistent object length (%"PRIuMAX" vs %"PRIuMAX")"),
2090 oid_to_hex(&trg_entry->idx.oid), (uintmax_t)sz,
2091 (uintmax_t)trg_size);
2095 packing_data_lock(&to_pack);
2096 src->data = read_object_file(&src_entry->idx.oid, &type, &sz);
2097 packing_data_unlock(&to_pack);
2099 if (src_entry->preferred_base) {
2100 static int warned = 0;
2102 warning(_("object %s cannot be read"),
2103 oid_to_hex(&src_entry->idx.oid));
2105 * Those objects are not included in the
2106 * resulting pack. Be resilient and ignore
2107 * them if they can't be read, in case the
2108 * pack could be created nevertheless.
2112 die(_("object %s cannot be read"),
2113 oid_to_hex(&src_entry->idx.oid));
2116 die(_("object %s inconsistent object length (%"PRIuMAX" vs %"PRIuMAX")"),
2117 oid_to_hex(&src_entry->idx.oid), (uintmax_t)sz,
2118 (uintmax_t)src_size);
2122 src->index = create_delta_index(src->data, src_size);
2124 static int warned = 0;
2126 warning(_("suboptimal pack - out of memory"));
2129 *mem_usage += sizeof_delta_index(src->index);
2132 delta_buf = create_delta(src->index, trg->data, trg_size, &delta_size, max_size);
2136 if (DELTA(trg_entry)) {
2137 /* Prefer only shallower same-sized deltas. */
2138 if (delta_size == DELTA_SIZE(trg_entry) &&
2139 src->depth + 1 >= trg->depth) {
2146 * Handle memory allocation outside of the cache
2147 * accounting lock. Compiler will optimize the strangeness
2148 * away when NO_PTHREADS is defined.
2150 free(trg_entry->delta_data);
2152 if (trg_entry->delta_data) {
2153 delta_cache_size -= DELTA_SIZE(trg_entry);
2154 trg_entry->delta_data = NULL;
2156 if (delta_cacheable(src_size, trg_size, delta_size)) {
2157 delta_cache_size += delta_size;
2159 trg_entry->delta_data = xrealloc(delta_buf, delta_size);
2165 SET_DELTA(trg_entry, src_entry);
2166 SET_DELTA_SIZE(trg_entry, delta_size);
2167 trg->depth = src->depth + 1;
2172 static unsigned int check_delta_limit(struct object_entry *me, unsigned int n)
2174 struct object_entry *child = DELTA_CHILD(me);
2177 const unsigned int c = check_delta_limit(child, n + 1);
2180 child = DELTA_SIBLING(child);
2185 static unsigned long free_unpacked(struct unpacked *n)
2187 unsigned long freed_mem = sizeof_delta_index(n->index);
2188 free_delta_index(n->index);
2191 freed_mem += SIZE(n->entry);
2192 FREE_AND_NULL(n->data);
2199 static void find_deltas(struct object_entry **list, unsigned *list_size,
2200 int window, int depth, unsigned *processed)
2202 uint32_t i, idx = 0, count = 0;
2203 struct unpacked *array;
2204 unsigned long mem_usage = 0;
2206 array = xcalloc(window, sizeof(struct unpacked));
2209 struct object_entry *entry;
2210 struct unpacked *n = array + idx;
2211 int j, max_depth, best_base = -1;
2220 if (!entry->preferred_base) {
2222 display_progress(progress_state, *processed);
2226 mem_usage -= free_unpacked(n);
2229 while (window_memory_limit &&
2230 mem_usage > window_memory_limit &&
2232 const uint32_t tail = (idx + window - count) % window;
2233 mem_usage -= free_unpacked(array + tail);
2237 /* We do not compute delta to *create* objects we are not
2240 if (entry->preferred_base)
2244 * If the current object is at pack edge, take the depth the
2245 * objects that depend on the current object into account
2246 * otherwise they would become too deep.
2249 if (DELTA_CHILD(entry)) {
2250 max_depth -= check_delta_limit(entry, 0);
2258 uint32_t other_idx = idx + j;
2260 if (other_idx >= window)
2261 other_idx -= window;
2262 m = array + other_idx;
2265 ret = try_delta(n, m, max_depth, &mem_usage);
2269 best_base = other_idx;
2273 * If we decided to cache the delta data, then it is best
2274 * to compress it right away. First because we have to do
2275 * it anyway, and doing it here while we're threaded will
2276 * save a lot of time in the non threaded write phase,
2277 * as well as allow for caching more deltas within
2278 * the same cache size limit.
2280 * But only if not writing to stdout, since in that case
2281 * the network is most likely throttling writes anyway,
2282 * and therefore it is best to go to the write phase ASAP
2283 * instead, as we can afford spending more time compressing
2284 * between writes at that moment.
2286 if (entry->delta_data && !pack_to_stdout) {
2289 size = do_compress(&entry->delta_data, DELTA_SIZE(entry));
2290 if (size < (1U << OE_Z_DELTA_BITS)) {
2291 entry->z_delta_size = size;
2293 delta_cache_size -= DELTA_SIZE(entry);
2294 delta_cache_size += entry->z_delta_size;
2297 FREE_AND_NULL(entry->delta_data);
2298 entry->z_delta_size = 0;
2302 /* if we made n a delta, and if n is already at max
2303 * depth, leaving it in the window is pointless. we
2304 * should evict it first.
2306 if (DELTA(entry) && max_depth <= n->depth)
2310 * Move the best delta base up in the window, after the
2311 * currently deltified object, to keep it longer. It will
2312 * be the first base object to be attempted next.
2315 struct unpacked swap = array[best_base];
2316 int dist = (window + idx - best_base) % window;
2317 int dst = best_base;
2319 int src = (dst + 1) % window;
2320 array[dst] = array[src];
2328 if (count + 1 < window)
2334 for (i = 0; i < window; ++i) {
2335 free_delta_index(array[i].index);
2336 free(array[i].data);
2342 * The main object list is split into smaller lists, each is handed to
2345 * The main thread waits on the condition that (at least) one of the workers
2346 * has stopped working (which is indicated in the .working member of
2347 * struct thread_params).
2349 * When a work thread has completed its work, it sets .working to 0 and
2350 * signals the main thread and waits on the condition that .data_ready
2353 * The main thread steals half of the work from the worker that has
2354 * most work left to hand it to the idle worker.
2357 struct thread_params {
2359 struct object_entry **list;
2366 pthread_mutex_t mutex;
2367 pthread_cond_t cond;
2368 unsigned *processed;
2371 static pthread_cond_t progress_cond;
2374 * Mutex and conditional variable can't be statically-initialized on Windows.
2376 static void init_threaded_search(void)
2378 pthread_mutex_init(&cache_mutex, NULL);
2379 pthread_mutex_init(&progress_mutex, NULL);
2380 pthread_cond_init(&progress_cond, NULL);
2383 static void cleanup_threaded_search(void)
2385 pthread_cond_destroy(&progress_cond);
2386 pthread_mutex_destroy(&cache_mutex);
2387 pthread_mutex_destroy(&progress_mutex);
2390 static void *threaded_find_deltas(void *arg)
2392 struct thread_params *me = arg;
2395 while (me->remaining) {
2398 find_deltas(me->list, &me->remaining,
2399 me->window, me->depth, me->processed);
2403 pthread_cond_signal(&progress_cond);
2407 * We must not set ->data_ready before we wait on the
2408 * condition because the main thread may have set it to 1
2409 * before we get here. In order to be sure that new
2410 * work is available if we see 1 in ->data_ready, it
2411 * was initialized to 0 before this thread was spawned
2412 * and we reset it to 0 right away.
2414 pthread_mutex_lock(&me->mutex);
2415 while (!me->data_ready)
2416 pthread_cond_wait(&me->cond, &me->mutex);
2418 pthread_mutex_unlock(&me->mutex);
2423 /* leave ->working 1 so that this doesn't get more work assigned */
2427 static void ll_find_deltas(struct object_entry **list, unsigned list_size,
2428 int window, int depth, unsigned *processed)
2430 struct thread_params *p;
2431 int i, ret, active_threads = 0;
2433 init_threaded_search();
2435 if (delta_search_threads <= 1) {
2436 find_deltas(list, &list_size, window, depth, processed);
2437 cleanup_threaded_search();
2440 if (progress > pack_to_stdout)
2441 fprintf_ln(stderr, _("Delta compression using up to %d threads"),
2442 delta_search_threads);
2443 p = xcalloc(delta_search_threads, sizeof(*p));
2445 /* Partition the work amongst work threads. */
2446 for (i = 0; i < delta_search_threads; i++) {
2447 unsigned sub_size = list_size / (delta_search_threads - i);
2449 /* don't use too small segments or no deltas will be found */
2450 if (sub_size < 2*window && i+1 < delta_search_threads)
2453 p[i].window = window;
2455 p[i].processed = processed;
2457 p[i].data_ready = 0;
2459 /* try to split chunks on "path" boundaries */
2460 while (sub_size && sub_size < list_size &&
2461 list[sub_size]->hash &&
2462 list[sub_size]->hash == list[sub_size-1]->hash)
2466 p[i].list_size = sub_size;
2467 p[i].remaining = sub_size;
2470 list_size -= sub_size;
2473 /* Start work threads. */
2474 for (i = 0; i < delta_search_threads; i++) {
2475 if (!p[i].list_size)
2477 pthread_mutex_init(&p[i].mutex, NULL);
2478 pthread_cond_init(&p[i].cond, NULL);
2479 ret = pthread_create(&p[i].thread, NULL,
2480 threaded_find_deltas, &p[i]);
2482 die(_("unable to create thread: %s"), strerror(ret));
2487 * Now let's wait for work completion. Each time a thread is done
2488 * with its work, we steal half of the remaining work from the
2489 * thread with the largest number of unprocessed objects and give
2490 * it to that newly idle thread. This ensure good load balancing
2491 * until the remaining object list segments are simply too short
2492 * to be worth splitting anymore.
2494 while (active_threads) {
2495 struct thread_params *target = NULL;
2496 struct thread_params *victim = NULL;
2497 unsigned sub_size = 0;
2501 for (i = 0; !target && i < delta_search_threads; i++)
2506 pthread_cond_wait(&progress_cond, &progress_mutex);
2509 for (i = 0; i < delta_search_threads; i++)
2510 if (p[i].remaining > 2*window &&
2511 (!victim || victim->remaining < p[i].remaining))
2514 sub_size = victim->remaining / 2;
2515 list = victim->list + victim->list_size - sub_size;
2516 while (sub_size && list[0]->hash &&
2517 list[0]->hash == list[-1]->hash) {
2523 * It is possible for some "paths" to have
2524 * so many objects that no hash boundary
2525 * might be found. Let's just steal the
2526 * exact half in that case.
2528 sub_size = victim->remaining / 2;
2531 target->list = list;
2532 victim->list_size -= sub_size;
2533 victim->remaining -= sub_size;
2535 target->list_size = sub_size;
2536 target->remaining = sub_size;
2537 target->working = 1;
2540 pthread_mutex_lock(&target->mutex);
2541 target->data_ready = 1;
2542 pthread_cond_signal(&target->cond);
2543 pthread_mutex_unlock(&target->mutex);
2546 pthread_join(target->thread, NULL);
2547 pthread_cond_destroy(&target->cond);
2548 pthread_mutex_destroy(&target->mutex);
2552 cleanup_threaded_search();
2556 static void add_tag_chain(const struct object_id *oid)
2561 * We catch duplicates already in add_object_entry(), but we'd
2562 * prefer to do this extra check to avoid having to parse the
2563 * tag at all if we already know that it's being packed (e.g., if
2564 * it was included via bitmaps, we would not have parsed it
2567 if (packlist_find(&to_pack, oid))
2570 tag = lookup_tag(the_repository, oid);
2572 if (!tag || parse_tag(tag) || !tag->tagged)
2573 die(_("unable to pack objects reachable from tag %s"),
2576 add_object_entry(&tag->object.oid, OBJ_TAG, NULL, 0);
2578 if (tag->tagged->type != OBJ_TAG)
2581 tag = (struct tag *)tag->tagged;
2585 static int add_ref_tag(const char *path, const struct object_id *oid, int flag, void *cb_data)
2587 struct object_id peeled;
2589 if (starts_with(path, "refs/tags/") && /* is a tag? */
2590 !peel_ref(path, &peeled) && /* peelable? */
2591 packlist_find(&to_pack, &peeled)) /* object packed? */
2596 static void prepare_pack(int window, int depth)
2598 struct object_entry **delta_list;
2599 uint32_t i, nr_deltas;
2602 if (use_delta_islands)
2603 resolve_tree_islands(the_repository, progress, &to_pack);
2605 get_object_details();
2608 * If we're locally repacking then we need to be doubly careful
2609 * from now on in order to make sure no stealth corruption gets
2610 * propagated to the new pack. Clients receiving streamed packs
2611 * should validate everything they get anyway so no need to incur
2612 * the additional cost here in that case.
2614 if (!pack_to_stdout)
2615 do_check_packed_object_crc = 1;
2617 if (!to_pack.nr_objects || !window || !depth)
2620 ALLOC_ARRAY(delta_list, to_pack.nr_objects);
2623 for (i = 0; i < to_pack.nr_objects; i++) {
2624 struct object_entry *entry = to_pack.objects + i;
2627 /* This happens if we decided to reuse existing
2628 * delta from a pack. "reuse_delta &&" is implied.
2632 if (!entry->type_valid ||
2633 oe_size_less_than(&to_pack, entry, 50))
2636 if (entry->no_try_delta)
2639 if (!entry->preferred_base) {
2641 if (oe_type(entry) < 0)
2642 die(_("unable to get type of object %s"),
2643 oid_to_hex(&entry->idx.oid));
2645 if (oe_type(entry) < 0) {
2647 * This object is not found, but we
2648 * don't have to include it anyway.
2654 delta_list[n++] = entry;
2657 if (nr_deltas && n > 1) {
2658 unsigned nr_done = 0;
2660 progress_state = start_progress(_("Compressing objects"),
2662 QSORT(delta_list, n, type_size_sort);
2663 ll_find_deltas(delta_list, n, window+1, depth, &nr_done);
2664 stop_progress(&progress_state);
2665 if (nr_done != nr_deltas)
2666 die(_("inconsistency with delta count"));
2671 static int git_pack_config(const char *k, const char *v, void *cb)
2673 if (!strcmp(k, "pack.window")) {
2674 window = git_config_int(k, v);
2677 if (!strcmp(k, "pack.windowmemory")) {
2678 window_memory_limit = git_config_ulong(k, v);
2681 if (!strcmp(k, "pack.depth")) {
2682 depth = git_config_int(k, v);
2685 if (!strcmp(k, "pack.deltacachesize")) {
2686 max_delta_cache_size = git_config_int(k, v);
2689 if (!strcmp(k, "pack.deltacachelimit")) {
2690 cache_max_small_delta_size = git_config_int(k, v);
2693 if (!strcmp(k, "pack.writebitmaphashcache")) {
2694 if (git_config_bool(k, v))
2695 write_bitmap_options |= BITMAP_OPT_HASH_CACHE;
2697 write_bitmap_options &= ~BITMAP_OPT_HASH_CACHE;
2699 if (!strcmp(k, "pack.usebitmaps")) {
2700 use_bitmap_index_default = git_config_bool(k, v);
2703 if (!strcmp(k, "pack.threads")) {
2704 delta_search_threads = git_config_int(k, v);
2705 if (delta_search_threads < 0)
2706 die(_("invalid number of threads specified (%d)"),
2707 delta_search_threads);
2708 if (!HAVE_THREADS && delta_search_threads != 1) {
2709 warning(_("no threads support, ignoring %s"), k);
2710 delta_search_threads = 0;
2714 if (!strcmp(k, "pack.indexversion")) {
2715 pack_idx_opts.version = git_config_int(k, v);
2716 if (pack_idx_opts.version > 2)
2717 die(_("bad pack.indexversion=%"PRIu32),
2718 pack_idx_opts.version);
2721 return git_default_config(k, v, cb);
2724 static void read_object_list_from_stdin(void)
2726 char line[GIT_MAX_HEXSZ + 1 + PATH_MAX + 2];
2727 struct object_id oid;
2731 if (!fgets(line, sizeof(line), stdin)) {
2735 die("BUG: fgets returned NULL, not EOF, not error!");
2741 if (line[0] == '-') {
2742 if (get_oid_hex(line+1, &oid))
2743 die(_("expected edge object ID, got garbage:\n %s"),
2745 add_preferred_base(&oid);
2748 if (parse_oid_hex(line, &oid, &p))
2749 die(_("expected object ID, got garbage:\n %s"), line);
2751 add_preferred_base_object(p + 1);
2752 add_object_entry(&oid, OBJ_NONE, p + 1, 0);
2756 /* Remember to update object flag allocation in object.h */
2757 #define OBJECT_ADDED (1u<<20)
2759 static void show_commit(struct commit *commit, void *data)
2761 add_object_entry(&commit->object.oid, OBJ_COMMIT, NULL, 0);
2762 commit->object.flags |= OBJECT_ADDED;
2764 if (write_bitmap_index)
2765 index_commit_for_bitmap(commit);
2767 if (use_delta_islands)
2768 propagate_island_marks(commit);
2771 static void show_object(struct object *obj, const char *name, void *data)
2773 add_preferred_base_object(name);
2774 add_object_entry(&obj->oid, obj->type, name, 0);
2775 obj->flags |= OBJECT_ADDED;
2777 if (use_delta_islands) {
2780 struct object_entry *ent;
2782 /* the empty string is a root tree, which is depth 0 */
2783 depth = *name ? 1 : 0;
2784 for (p = strchr(name, '/'); p; p = strchr(p + 1, '/'))
2787 ent = packlist_find(&to_pack, &obj->oid);
2788 if (ent && depth > oe_tree_depth(&to_pack, ent))
2789 oe_set_tree_depth(&to_pack, ent, depth);
2793 static void show_object__ma_allow_any(struct object *obj, const char *name, void *data)
2795 assert(arg_missing_action == MA_ALLOW_ANY);
2798 * Quietly ignore ALL missing objects. This avoids problems with
2799 * staging them now and getting an odd error later.
2801 if (!has_object_file(&obj->oid))
2804 show_object(obj, name, data);
2807 static void show_object__ma_allow_promisor(struct object *obj, const char *name, void *data)
2809 assert(arg_missing_action == MA_ALLOW_PROMISOR);
2812 * Quietly ignore EXPECTED missing objects. This avoids problems with
2813 * staging them now and getting an odd error later.
2815 if (!has_object_file(&obj->oid) && is_promisor_object(&obj->oid))
2818 show_object(obj, name, data);
2821 static int option_parse_missing_action(const struct option *opt,
2822 const char *arg, int unset)
2827 if (!strcmp(arg, "error")) {
2828 arg_missing_action = MA_ERROR;
2829 fn_show_object = show_object;
2833 if (!strcmp(arg, "allow-any")) {
2834 arg_missing_action = MA_ALLOW_ANY;
2835 fetch_if_missing = 0;
2836 fn_show_object = show_object__ma_allow_any;
2840 if (!strcmp(arg, "allow-promisor")) {
2841 arg_missing_action = MA_ALLOW_PROMISOR;
2842 fetch_if_missing = 0;
2843 fn_show_object = show_object__ma_allow_promisor;
2847 die(_("invalid value for --missing"));
2851 static void show_edge(struct commit *commit)
2853 add_preferred_base(&commit->object.oid);
2856 struct in_pack_object {
2858 struct object *object;
2864 struct in_pack_object *array;
2867 static void mark_in_pack_object(struct object *object, struct packed_git *p, struct in_pack *in_pack)
2869 in_pack->array[in_pack->nr].offset = find_pack_entry_one(object->oid.hash, p);
2870 in_pack->array[in_pack->nr].object = object;
2875 * Compare the objects in the offset order, in order to emulate the
2876 * "git rev-list --objects" output that produced the pack originally.
2878 static int ofscmp(const void *a_, const void *b_)
2880 struct in_pack_object *a = (struct in_pack_object *)a_;
2881 struct in_pack_object *b = (struct in_pack_object *)b_;
2883 if (a->offset < b->offset)
2885 else if (a->offset > b->offset)
2888 return oidcmp(&a->object->oid, &b->object->oid);
2891 static void add_objects_in_unpacked_packs(void)
2893 struct packed_git *p;
2894 struct in_pack in_pack;
2897 memset(&in_pack, 0, sizeof(in_pack));
2899 for (p = get_all_packs(the_repository); p; p = p->next) {
2900 struct object_id oid;
2903 if (!p->pack_local || p->pack_keep || p->pack_keep_in_core)
2905 if (open_pack_index(p))
2906 die(_("cannot open pack index"));
2908 ALLOC_GROW(in_pack.array,
2909 in_pack.nr + p->num_objects,
2912 for (i = 0; i < p->num_objects; i++) {
2913 nth_packed_object_oid(&oid, p, i);
2914 o = lookup_unknown_object(&oid);
2915 if (!(o->flags & OBJECT_ADDED))
2916 mark_in_pack_object(o, p, &in_pack);
2917 o->flags |= OBJECT_ADDED;
2922 QSORT(in_pack.array, in_pack.nr, ofscmp);
2923 for (i = 0; i < in_pack.nr; i++) {
2924 struct object *o = in_pack.array[i].object;
2925 add_object_entry(&o->oid, o->type, "", 0);
2928 free(in_pack.array);
2931 static int add_loose_object(const struct object_id *oid, const char *path,
2934 enum object_type type = oid_object_info(the_repository, oid, NULL);
2937 warning(_("loose object at %s could not be examined"), path);
2941 add_object_entry(oid, type, "", 0);
2946 * We actually don't even have to worry about reachability here.
2947 * add_object_entry will weed out duplicates, so we just add every
2948 * loose object we find.
2950 static void add_unreachable_loose_objects(void)
2952 for_each_loose_file_in_objdir(get_object_directory(),
2957 static int has_sha1_pack_kept_or_nonlocal(const struct object_id *oid)
2959 static struct packed_git *last_found = (void *)1;
2960 struct packed_git *p;
2962 p = (last_found != (void *)1) ? last_found :
2963 get_all_packs(the_repository);
2966 if ((!p->pack_local || p->pack_keep ||
2967 p->pack_keep_in_core) &&
2968 find_pack_entry_one(oid->hash, p)) {
2972 if (p == last_found)
2973 p = get_all_packs(the_repository);
2976 if (p == last_found)
2983 * Store a list of sha1s that are should not be discarded
2984 * because they are either written too recently, or are
2985 * reachable from another object that was.
2987 * This is filled by get_object_list.
2989 static struct oid_array recent_objects;
2991 static int loosened_object_can_be_discarded(const struct object_id *oid,
2994 if (!unpack_unreachable_expiration)
2996 if (mtime > unpack_unreachable_expiration)
2998 if (oid_array_lookup(&recent_objects, oid) >= 0)
3003 static void loosen_unused_packed_objects(void)
3005 struct packed_git *p;
3007 struct object_id oid;
3009 for (p = get_all_packs(the_repository); p; p = p->next) {
3010 if (!p->pack_local || p->pack_keep || p->pack_keep_in_core)
3013 if (open_pack_index(p))
3014 die(_("cannot open pack index"));
3016 for (i = 0; i < p->num_objects; i++) {
3017 nth_packed_object_oid(&oid, p, i);
3018 if (!packlist_find(&to_pack, &oid) &&
3019 !has_sha1_pack_kept_or_nonlocal(&oid) &&
3020 !loosened_object_can_be_discarded(&oid, p->mtime))
3021 if (force_object_loose(&oid, p->mtime))
3022 die(_("unable to force loose object"));
3028 * This tracks any options which pack-reuse code expects to be on, or which a
3029 * reader of the pack might not understand, and which would therefore prevent
3030 * blind reuse of what we have on disk.
3032 static int pack_options_allow_reuse(void)
3034 return pack_to_stdout &&
3036 !ignore_packed_keep_on_disk &&
3037 !ignore_packed_keep_in_core &&
3038 (!local || !have_non_local_packs) &&
3042 static int get_object_list_from_bitmap(struct rev_info *revs)
3044 if (!(bitmap_git = prepare_bitmap_walk(revs)))
3047 if (pack_options_allow_reuse() &&
3048 !reuse_partial_packfile_from_bitmap(
3051 &reuse_packfile_objects,
3052 &reuse_packfile_offset)) {
3053 assert(reuse_packfile_objects);
3054 nr_result += reuse_packfile_objects;
3055 display_progress(progress_state, nr_result);
3058 traverse_bitmap_commit_list(bitmap_git, &add_object_entry_from_bitmap);
3062 static void record_recent_object(struct object *obj,
3066 oid_array_append(&recent_objects, &obj->oid);
3069 static void record_recent_commit(struct commit *commit, void *data)
3071 oid_array_append(&recent_objects, &commit->object.oid);
3074 static void get_object_list(int ac, const char **av)
3076 struct rev_info revs;
3077 struct setup_revision_opt s_r_opt = {
3078 .allow_exclude_promisor_objects = 1,
3084 repo_init_revisions(the_repository, &revs, NULL);
3085 save_commit_buffer = 0;
3086 setup_revisions(ac, av, &revs, &s_r_opt);
3088 /* make sure shallows are read */
3089 is_repository_shallow(the_repository);
3091 save_warning = warn_on_object_refname_ambiguity;
3092 warn_on_object_refname_ambiguity = 0;
3094 while (fgets(line, sizeof(line), stdin) != NULL) {
3095 int len = strlen(line);
3096 if (len && line[len - 1] == '\n')
3101 if (!strcmp(line, "--not")) {
3102 flags ^= UNINTERESTING;
3103 write_bitmap_index = 0;
3106 if (starts_with(line, "--shallow ")) {
3107 struct object_id oid;
3108 if (get_oid_hex(line + 10, &oid))
3109 die("not an SHA-1 '%s'", line + 10);
3110 register_shallow(the_repository, &oid);
3111 use_bitmap_index = 0;
3114 die(_("not a rev '%s'"), line);
3116 if (handle_revision_arg(line, &revs, flags, REVARG_CANNOT_BE_FILENAME))
3117 die(_("bad revision '%s'"), line);
3120 warn_on_object_refname_ambiguity = save_warning;
3122 if (use_bitmap_index && !get_object_list_from_bitmap(&revs))
3125 if (use_delta_islands)
3126 load_delta_islands(the_repository, progress);
3128 if (prepare_revision_walk(&revs))
3129 die(_("revision walk setup failed"));
3130 mark_edges_uninteresting(&revs, show_edge, sparse);
3132 if (!fn_show_object)
3133 fn_show_object = show_object;
3134 traverse_commit_list_filtered(&filter_options, &revs,
3135 show_commit, fn_show_object, NULL,
3138 if (unpack_unreachable_expiration) {
3139 revs.ignore_missing_links = 1;
3140 if (add_unseen_recent_objects_to_traversal(&revs,
3141 unpack_unreachable_expiration))
3142 die(_("unable to add recent objects"));
3143 if (prepare_revision_walk(&revs))
3144 die(_("revision walk setup failed"));
3145 traverse_commit_list(&revs, record_recent_commit,
3146 record_recent_object, NULL);
3149 if (keep_unreachable)
3150 add_objects_in_unpacked_packs();
3151 if (pack_loose_unreachable)
3152 add_unreachable_loose_objects();
3153 if (unpack_unreachable)
3154 loosen_unused_packed_objects();
3156 oid_array_clear(&recent_objects);
3159 static void add_extra_kept_packs(const struct string_list *names)
3161 struct packed_git *p;
3166 for (p = get_all_packs(the_repository); p; p = p->next) {
3167 const char *name = basename(p->pack_name);
3173 for (i = 0; i < names->nr; i++)
3174 if (!fspathcmp(name, names->items[i].string))
3177 if (i < names->nr) {
3178 p->pack_keep_in_core = 1;
3179 ignore_packed_keep_in_core = 1;
3185 static int option_parse_index_version(const struct option *opt,
3186 const char *arg, int unset)
3189 const char *val = arg;
3191 BUG_ON_OPT_NEG(unset);
3193 pack_idx_opts.version = strtoul(val, &c, 10);
3194 if (pack_idx_opts.version > 2)
3195 die(_("unsupported index version %s"), val);
3196 if (*c == ',' && c[1])
3197 pack_idx_opts.off32_limit = strtoul(c+1, &c, 0);
3198 if (*c || pack_idx_opts.off32_limit & 0x80000000)
3199 die(_("bad index version '%s'"), val);
3203 static int option_parse_unpack_unreachable(const struct option *opt,
3204 const char *arg, int unset)
3207 unpack_unreachable = 0;
3208 unpack_unreachable_expiration = 0;
3211 unpack_unreachable = 1;
3213 unpack_unreachable_expiration = approxidate(arg);
3218 int cmd_pack_objects(int argc, const char **argv, const char *prefix)
3220 int use_internal_rev_list = 0;
3222 int all_progress_implied = 0;
3223 struct argv_array rp = ARGV_ARRAY_INIT;
3224 int rev_list_unpacked = 0, rev_list_all = 0, rev_list_reflog = 0;
3225 int rev_list_index = 0;
3226 struct string_list keep_pack_list = STRING_LIST_INIT_NODUP;
3227 struct option pack_objects_options[] = {
3228 OPT_SET_INT('q', "quiet", &progress,
3229 N_("do not show progress meter"), 0),
3230 OPT_SET_INT(0, "progress", &progress,
3231 N_("show progress meter"), 1),
3232 OPT_SET_INT(0, "all-progress", &progress,
3233 N_("show progress meter during object writing phase"), 2),
3234 OPT_BOOL(0, "all-progress-implied",
3235 &all_progress_implied,
3236 N_("similar to --all-progress when progress meter is shown")),
3237 { OPTION_CALLBACK, 0, "index-version", NULL, N_("<version>[,<offset>]"),
3238 N_("write the pack index file in the specified idx format version"),
3239 PARSE_OPT_NONEG, option_parse_index_version },
3240 OPT_MAGNITUDE(0, "max-pack-size", &pack_size_limit,
3241 N_("maximum size of each output pack file")),
3242 OPT_BOOL(0, "local", &local,
3243 N_("ignore borrowed objects from alternate object store")),
3244 OPT_BOOL(0, "incremental", &incremental,
3245 N_("ignore packed objects")),
3246 OPT_INTEGER(0, "window", &window,
3247 N_("limit pack window by objects")),
3248 OPT_MAGNITUDE(0, "window-memory", &window_memory_limit,
3249 N_("limit pack window by memory in addition to object limit")),
3250 OPT_INTEGER(0, "depth", &depth,
3251 N_("maximum length of delta chain allowed in the resulting pack")),
3252 OPT_BOOL(0, "reuse-delta", &reuse_delta,
3253 N_("reuse existing deltas")),
3254 OPT_BOOL(0, "reuse-object", &reuse_object,
3255 N_("reuse existing objects")),
3256 OPT_BOOL(0, "delta-base-offset", &allow_ofs_delta,
3257 N_("use OFS_DELTA objects")),
3258 OPT_INTEGER(0, "threads", &delta_search_threads,
3259 N_("use threads when searching for best delta matches")),
3260 OPT_BOOL(0, "non-empty", &non_empty,
3261 N_("do not create an empty pack output")),
3262 OPT_BOOL(0, "revs", &use_internal_rev_list,
3263 N_("read revision arguments from standard input")),
3264 OPT_SET_INT_F(0, "unpacked", &rev_list_unpacked,
3265 N_("limit the objects to those that are not yet packed"),
3266 1, PARSE_OPT_NONEG),
3267 OPT_SET_INT_F(0, "all", &rev_list_all,
3268 N_("include objects reachable from any reference"),
3269 1, PARSE_OPT_NONEG),
3270 OPT_SET_INT_F(0, "reflog", &rev_list_reflog,
3271 N_("include objects referred by reflog entries"),
3272 1, PARSE_OPT_NONEG),
3273 OPT_SET_INT_F(0, "indexed-objects", &rev_list_index,
3274 N_("include objects referred to by the index"),
3275 1, PARSE_OPT_NONEG),
3276 OPT_BOOL(0, "stdout", &pack_to_stdout,
3277 N_("output pack to stdout")),
3278 OPT_BOOL(0, "include-tag", &include_tag,
3279 N_("include tag objects that refer to objects to be packed")),
3280 OPT_BOOL(0, "keep-unreachable", &keep_unreachable,
3281 N_("keep unreachable objects")),
3282 OPT_BOOL(0, "pack-loose-unreachable", &pack_loose_unreachable,
3283 N_("pack loose unreachable objects")),
3284 { OPTION_CALLBACK, 0, "unpack-unreachable", NULL, N_("time"),
3285 N_("unpack unreachable objects newer than <time>"),
3286 PARSE_OPT_OPTARG, option_parse_unpack_unreachable },
3287 OPT_BOOL(0, "sparse", &sparse,
3288 N_("use the sparse reachability algorithm")),
3289 OPT_BOOL(0, "thin", &thin,
3290 N_("create thin packs")),
3291 OPT_BOOL(0, "shallow", &shallow,
3292 N_("create packs suitable for shallow fetches")),
3293 OPT_BOOL(0, "honor-pack-keep", &ignore_packed_keep_on_disk,
3294 N_("ignore packs that have companion .keep file")),
3295 OPT_STRING_LIST(0, "keep-pack", &keep_pack_list, N_("name"),
3296 N_("ignore this pack")),
3297 OPT_INTEGER(0, "compression", &pack_compression_level,
3298 N_("pack compression level")),
3299 OPT_SET_INT(0, "keep-true-parents", &grafts_replace_parents,
3300 N_("do not hide commits by grafts"), 0),
3301 OPT_BOOL(0, "use-bitmap-index", &use_bitmap_index,
3302 N_("use a bitmap index if available to speed up counting objects")),
3303 OPT_SET_INT(0, "write-bitmap-index", &write_bitmap_index,
3304 N_("write a bitmap index together with the pack index"),
3306 OPT_SET_INT_F(0, "write-bitmap-index-quiet",
3307 &write_bitmap_index,
3308 N_("write a bitmap index if possible"),
3309 WRITE_BITMAP_QUIET, PARSE_OPT_HIDDEN),
3310 OPT_PARSE_LIST_OBJECTS_FILTER(&filter_options),
3311 { OPTION_CALLBACK, 0, "missing", NULL, N_("action"),
3312 N_("handling for missing objects"), PARSE_OPT_NONEG,
3313 option_parse_missing_action },
3314 OPT_BOOL(0, "exclude-promisor-objects", &exclude_promisor_objects,
3315 N_("do not pack objects in promisor packfiles")),
3316 OPT_BOOL(0, "delta-islands", &use_delta_islands,
3317 N_("respect islands during delta compression")),
3321 if (DFS_NUM_STATES > (1 << OE_DFS_STATE_BITS))
3322 BUG("too many dfs states, increase OE_DFS_STATE_BITS");
3324 read_replace_refs = 0;
3326 sparse = git_env_bool("GIT_TEST_PACK_SPARSE", 0);
3327 prepare_repo_settings(the_repository);
3328 if (!sparse && the_repository->settings.pack_use_sparse != -1)
3329 sparse = the_repository->settings.pack_use_sparse;
3331 reset_pack_idx_option(&pack_idx_opts);
3332 git_config(git_pack_config, NULL);
3334 progress = isatty(2);
3335 argc = parse_options(argc, argv, prefix, pack_objects_options,
3339 base_name = argv[0];
3342 if (pack_to_stdout != !base_name || argc)
3343 usage_with_options(pack_usage, pack_objects_options);
3345 if (depth >= (1 << OE_DEPTH_BITS)) {
3346 warning(_("delta chain depth %d is too deep, forcing %d"),
3347 depth, (1 << OE_DEPTH_BITS) - 1);
3348 depth = (1 << OE_DEPTH_BITS) - 1;
3350 if (cache_max_small_delta_size >= (1U << OE_Z_DELTA_BITS)) {
3351 warning(_("pack.deltaCacheLimit is too high, forcing %d"),
3352 (1U << OE_Z_DELTA_BITS) - 1);
3353 cache_max_small_delta_size = (1U << OE_Z_DELTA_BITS) - 1;
3356 argv_array_push(&rp, "pack-objects");
3358 use_internal_rev_list = 1;
3359 argv_array_push(&rp, shallow
3360 ? "--objects-edge-aggressive"
3361 : "--objects-edge");
3363 argv_array_push(&rp, "--objects");
3366 use_internal_rev_list = 1;
3367 argv_array_push(&rp, "--all");
3369 if (rev_list_reflog) {
3370 use_internal_rev_list = 1;
3371 argv_array_push(&rp, "--reflog");
3373 if (rev_list_index) {
3374 use_internal_rev_list = 1;
3375 argv_array_push(&rp, "--indexed-objects");
3377 if (rev_list_unpacked) {
3378 use_internal_rev_list = 1;
3379 argv_array_push(&rp, "--unpacked");
3382 if (exclude_promisor_objects) {
3383 use_internal_rev_list = 1;
3384 fetch_if_missing = 0;
3385 argv_array_push(&rp, "--exclude-promisor-objects");
3387 if (unpack_unreachable || keep_unreachable || pack_loose_unreachable)
3388 use_internal_rev_list = 1;
3392 if (pack_compression_level == -1)
3393 pack_compression_level = Z_DEFAULT_COMPRESSION;
3394 else if (pack_compression_level < 0 || pack_compression_level > Z_BEST_COMPRESSION)
3395 die(_("bad pack compression level %d"), pack_compression_level);
3397 if (!delta_search_threads) /* --threads=0 means autodetect */
3398 delta_search_threads = online_cpus();
3400 if (!HAVE_THREADS && delta_search_threads != 1)
3401 warning(_("no threads support, ignoring --threads"));
3402 if (!pack_to_stdout && !pack_size_limit)
3403 pack_size_limit = pack_size_limit_cfg;
3404 if (pack_to_stdout && pack_size_limit)
3405 die(_("--max-pack-size cannot be used to build a pack for transfer"));
3406 if (pack_size_limit && pack_size_limit < 1024*1024) {
3407 warning(_("minimum pack size limit is 1 MiB"));
3408 pack_size_limit = 1024*1024;
3411 if (!pack_to_stdout && thin)
3412 die(_("--thin cannot be used to build an indexable pack"));
3414 if (keep_unreachable && unpack_unreachable)
3415 die(_("--keep-unreachable and --unpack-unreachable are incompatible"));
3416 if (!rev_list_all || !rev_list_reflog || !rev_list_index)
3417 unpack_unreachable_expiration = 0;
3419 if (filter_options.choice) {
3420 if (!pack_to_stdout)
3421 die(_("cannot use --filter without --stdout"));
3422 use_bitmap_index = 0;
3426 * "soft" reasons not to use bitmaps - for on-disk repack by default we want
3428 * - to produce good pack (with bitmap index not-yet-packed objects are
3429 * packed in suboptimal order).
3431 * - to use more robust pack-generation codepath (avoiding possible
3432 * bugs in bitmap code and possible bitmap index corruption).
3434 if (!pack_to_stdout)
3435 use_bitmap_index_default = 0;
3437 if (use_bitmap_index < 0)
3438 use_bitmap_index = use_bitmap_index_default;
3440 /* "hard" reasons not to use bitmaps; these just won't work at all */
3441 if (!use_internal_rev_list || (!pack_to_stdout && write_bitmap_index) || is_repository_shallow(the_repository))
3442 use_bitmap_index = 0;
3444 if (pack_to_stdout || !rev_list_all)
3445 write_bitmap_index = 0;
3447 if (use_delta_islands)
3448 argv_array_push(&rp, "--topo-order");
3450 if (progress && all_progress_implied)
3453 add_extra_kept_packs(&keep_pack_list);
3454 if (ignore_packed_keep_on_disk) {
3455 struct packed_git *p;
3456 for (p = get_all_packs(the_repository); p; p = p->next)
3457 if (p->pack_local && p->pack_keep)
3459 if (!p) /* no keep-able packs found */
3460 ignore_packed_keep_on_disk = 0;
3464 * unlike ignore_packed_keep_on_disk above, we do not
3465 * want to unset "local" based on looking at packs, as
3466 * it also covers non-local objects
3468 struct packed_git *p;
3469 for (p = get_all_packs(the_repository); p; p = p->next) {
3470 if (!p->pack_local) {
3471 have_non_local_packs = 1;
3477 trace2_region_enter("pack-objects", "enumerate-objects",
3479 prepare_packing_data(the_repository, &to_pack);
3482 progress_state = start_progress(_("Enumerating objects"), 0);
3483 if (!use_internal_rev_list)
3484 read_object_list_from_stdin();
3486 get_object_list(rp.argc, rp.argv);
3487 argv_array_clear(&rp);
3489 cleanup_preferred_base();
3490 if (include_tag && nr_result)
3491 for_each_ref(add_ref_tag, NULL);
3492 stop_progress(&progress_state);
3493 trace2_region_leave("pack-objects", "enumerate-objects",
3496 if (non_empty && !nr_result)
3499 trace2_region_enter("pack-objects", "prepare-pack",
3501 prepare_pack(window, depth);
3502 trace2_region_leave("pack-objects", "prepare-pack",
3506 trace2_region_enter("pack-objects", "write-pack-file", the_repository);
3508 trace2_region_leave("pack-objects", "write-pack-file", the_repository);
3512 _("Total %"PRIu32" (delta %"PRIu32"),"
3513 " reused %"PRIu32" (delta %"PRIu32")"),
3514 written, written_delta, reused, reused_delta);