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 "reachable.h"
28 #include "sha1-array.h"
29 #include "argv-array.h"
32 #include "object-store.h"
36 #define IN_PACK(obj) oe_in_pack(&to_pack, obj)
37 #define SIZE(obj) oe_size(&to_pack, obj)
38 #define SET_SIZE(obj,size) oe_set_size(&to_pack, obj, size)
39 #define DELTA_SIZE(obj) oe_delta_size(&to_pack, obj)
40 #define DELTA(obj) oe_delta(&to_pack, obj)
41 #define DELTA_CHILD(obj) oe_delta_child(&to_pack, obj)
42 #define DELTA_SIBLING(obj) oe_delta_sibling(&to_pack, obj)
43 #define SET_DELTA(obj, val) oe_set_delta(&to_pack, obj, val)
44 #define SET_DELTA_EXT(obj, oid) oe_set_delta_ext(&to_pack, obj, oid)
45 #define SET_DELTA_SIZE(obj, val) oe_set_delta_size(&to_pack, obj, val)
46 #define SET_DELTA_CHILD(obj, val) oe_set_delta_child(&to_pack, obj, val)
47 #define SET_DELTA_SIBLING(obj, val) oe_set_delta_sibling(&to_pack, obj, val)
49 static const char *pack_usage[] = {
50 N_("git pack-objects --stdout [<options>...] [< <ref-list> | < <object-list>]"),
51 N_("git pack-objects [<options>...] <base-name> [< <ref-list> | < <object-list>]"),
56 * Objects we are going to pack are collected in the `to_pack` structure.
57 * It contains an array (dynamically expanded) of the object data, and a map
58 * that can resolve SHA1s to their position in the array.
60 static struct packing_data to_pack;
62 static struct pack_idx_entry **written_list;
63 static uint32_t nr_result, nr_written, nr_seen;
64 static struct bitmap_index *bitmap_git;
67 static int reuse_delta = 1, reuse_object = 1;
68 static int keep_unreachable, unpack_unreachable, include_tag;
69 static timestamp_t unpack_unreachable_expiration;
70 static int pack_loose_unreachable;
72 static int have_non_local_packs;
73 static int incremental;
74 static int ignore_packed_keep_on_disk;
75 static int ignore_packed_keep_in_core;
76 static int allow_ofs_delta;
77 static struct pack_idx_option pack_idx_opts;
78 static const char *base_name;
79 static int progress = 1;
80 static int window = 10;
81 static unsigned long pack_size_limit;
82 static int depth = 50;
83 static int delta_search_threads;
84 static int pack_to_stdout;
86 static int num_preferred_base;
87 static struct progress *progress_state;
89 static struct packed_git *reuse_packfile;
90 static uint32_t reuse_packfile_objects;
91 static off_t reuse_packfile_offset;
93 static int use_bitmap_index_default = 1;
94 static int use_bitmap_index = -1;
95 static int write_bitmap_index;
96 static uint16_t write_bitmap_options;
98 static int exclude_promisor_objects;
100 static unsigned long delta_cache_size = 0;
101 static unsigned long max_delta_cache_size = DEFAULT_DELTA_CACHE_SIZE;
102 static unsigned long cache_max_small_delta_size = 1000;
104 static unsigned long window_memory_limit = 0;
106 static struct list_objects_filter_options filter_options;
108 enum missing_action {
109 MA_ERROR = 0, /* fail if any missing objects are encountered */
110 MA_ALLOW_ANY, /* silently allow ALL missing objects */
111 MA_ALLOW_PROMISOR, /* silently allow all missing PROMISOR objects */
113 static enum missing_action arg_missing_action;
114 static show_object_fn fn_show_object;
119 static uint32_t written, written_delta;
120 static uint32_t reused, reused_delta;
125 static struct commit **indexed_commits;
126 static unsigned int indexed_commits_nr;
127 static unsigned int indexed_commits_alloc;
129 static void index_commit_for_bitmap(struct commit *commit)
131 if (indexed_commits_nr >= indexed_commits_alloc) {
132 indexed_commits_alloc = (indexed_commits_alloc + 32) * 2;
133 REALLOC_ARRAY(indexed_commits, indexed_commits_alloc);
136 indexed_commits[indexed_commits_nr++] = commit;
139 static void *get_delta(struct object_entry *entry)
141 unsigned long size, base_size, delta_size;
142 void *buf, *base_buf, *delta_buf;
143 enum object_type type;
145 buf = read_object_file(&entry->idx.oid, &type, &size);
147 die(_("unable to read %s"), oid_to_hex(&entry->idx.oid));
148 base_buf = read_object_file(&DELTA(entry)->idx.oid, &type,
151 die("unable to read %s",
152 oid_to_hex(&DELTA(entry)->idx.oid));
153 delta_buf = diff_delta(base_buf, base_size,
154 buf, size, &delta_size, 0);
156 * We succesfully computed this delta once but dropped it for
157 * memory reasons. Something is very wrong if this time we
158 * recompute and create a different delta.
160 if (!delta_buf || delta_size != DELTA_SIZE(entry))
161 BUG("delta size changed");
167 static unsigned long do_compress(void **pptr, unsigned long size)
171 unsigned long maxsize;
173 git_deflate_init(&stream, pack_compression_level);
174 maxsize = git_deflate_bound(&stream, size);
177 out = xmalloc(maxsize);
181 stream.avail_in = size;
182 stream.next_out = out;
183 stream.avail_out = maxsize;
184 while (git_deflate(&stream, Z_FINISH) == Z_OK)
186 git_deflate_end(&stream);
189 return stream.total_out;
192 static unsigned long write_large_blob_data(struct git_istream *st, struct hashfile *f,
193 const struct object_id *oid)
196 unsigned char ibuf[1024 * 16];
197 unsigned char obuf[1024 * 16];
198 unsigned long olen = 0;
200 git_deflate_init(&stream, pack_compression_level);
205 readlen = read_istream(st, ibuf, sizeof(ibuf));
207 die(_("unable to read %s"), oid_to_hex(oid));
209 stream.next_in = ibuf;
210 stream.avail_in = readlen;
211 while ((stream.avail_in || readlen == 0) &&
212 (zret == Z_OK || zret == Z_BUF_ERROR)) {
213 stream.next_out = obuf;
214 stream.avail_out = sizeof(obuf);
215 zret = git_deflate(&stream, readlen ? 0 : Z_FINISH);
216 hashwrite(f, obuf, stream.next_out - obuf);
217 olen += stream.next_out - obuf;
220 die(_("deflate error (%d)"), zret);
222 if (zret != Z_STREAM_END)
223 die(_("deflate error (%d)"), zret);
227 git_deflate_end(&stream);
232 * we are going to reuse the existing object data as is. make
233 * sure it is not corrupt.
235 static int check_pack_inflate(struct packed_git *p,
236 struct pack_window **w_curs,
239 unsigned long expect)
242 unsigned char fakebuf[4096], *in;
245 memset(&stream, 0, sizeof(stream));
246 git_inflate_init(&stream);
248 in = use_pack(p, w_curs, offset, &stream.avail_in);
250 stream.next_out = fakebuf;
251 stream.avail_out = sizeof(fakebuf);
252 st = git_inflate(&stream, Z_FINISH);
253 offset += stream.next_in - in;
254 } while (st == Z_OK || st == Z_BUF_ERROR);
255 git_inflate_end(&stream);
256 return (st == Z_STREAM_END &&
257 stream.total_out == expect &&
258 stream.total_in == len) ? 0 : -1;
261 static void copy_pack_data(struct hashfile *f,
262 struct packed_git *p,
263 struct pack_window **w_curs,
271 in = use_pack(p, w_curs, offset, &avail);
273 avail = (unsigned long)len;
274 hashwrite(f, in, avail);
280 /* Return 0 if we will bust the pack-size limit */
281 static unsigned long write_no_reuse_object(struct hashfile *f, struct object_entry *entry,
282 unsigned long limit, int usable_delta)
284 unsigned long size, datalen;
285 unsigned char header[MAX_PACK_OBJECT_HEADER],
286 dheader[MAX_PACK_OBJECT_HEADER];
288 enum object_type type;
290 struct git_istream *st = NULL;
291 const unsigned hashsz = the_hash_algo->rawsz;
294 if (oe_type(entry) == OBJ_BLOB &&
295 oe_size_greater_than(&to_pack, entry, big_file_threshold) &&
296 (st = open_istream(&entry->idx.oid, &type, &size, NULL)) != NULL)
299 buf = read_object_file(&entry->idx.oid, &type, &size);
301 die(_("unable to read %s"),
302 oid_to_hex(&entry->idx.oid));
305 * make sure no cached delta data remains from a
306 * previous attempt before a pack split occurred.
308 FREE_AND_NULL(entry->delta_data);
309 entry->z_delta_size = 0;
310 } else if (entry->delta_data) {
311 size = DELTA_SIZE(entry);
312 buf = entry->delta_data;
313 entry->delta_data = NULL;
314 type = (allow_ofs_delta && DELTA(entry)->idx.offset) ?
315 OBJ_OFS_DELTA : OBJ_REF_DELTA;
317 buf = get_delta(entry);
318 size = DELTA_SIZE(entry);
319 type = (allow_ofs_delta && DELTA(entry)->idx.offset) ?
320 OBJ_OFS_DELTA : OBJ_REF_DELTA;
323 if (st) /* large blob case, just assume we don't compress well */
325 else if (entry->z_delta_size)
326 datalen = entry->z_delta_size;
328 datalen = do_compress(&buf, size);
331 * The object header is a byte of 'type' followed by zero or
332 * more bytes of length.
334 hdrlen = encode_in_pack_object_header(header, sizeof(header),
337 if (type == OBJ_OFS_DELTA) {
339 * Deltas with relative base contain an additional
340 * encoding of the relative offset for the delta
341 * base from this object's position in the pack.
343 off_t ofs = entry->idx.offset - DELTA(entry)->idx.offset;
344 unsigned pos = sizeof(dheader) - 1;
345 dheader[pos] = ofs & 127;
347 dheader[--pos] = 128 | (--ofs & 127);
348 if (limit && hdrlen + sizeof(dheader) - pos + datalen + hashsz >= limit) {
354 hashwrite(f, header, hdrlen);
355 hashwrite(f, dheader + pos, sizeof(dheader) - pos);
356 hdrlen += sizeof(dheader) - pos;
357 } else if (type == OBJ_REF_DELTA) {
359 * Deltas with a base reference contain
360 * additional bytes for the base object ID.
362 if (limit && hdrlen + hashsz + datalen + hashsz >= limit) {
368 hashwrite(f, header, hdrlen);
369 hashwrite(f, DELTA(entry)->idx.oid.hash, hashsz);
372 if (limit && hdrlen + datalen + hashsz >= limit) {
378 hashwrite(f, header, hdrlen);
381 datalen = write_large_blob_data(st, f, &entry->idx.oid);
384 hashwrite(f, buf, datalen);
388 return hdrlen + datalen;
391 /* Return 0 if we will bust the pack-size limit */
392 static off_t write_reuse_object(struct hashfile *f, struct object_entry *entry,
393 unsigned long limit, int usable_delta)
395 struct packed_git *p = IN_PACK(entry);
396 struct pack_window *w_curs = NULL;
397 struct revindex_entry *revidx;
399 enum object_type type = oe_type(entry);
401 unsigned char header[MAX_PACK_OBJECT_HEADER],
402 dheader[MAX_PACK_OBJECT_HEADER];
404 const unsigned hashsz = the_hash_algo->rawsz;
405 unsigned long entry_size = SIZE(entry);
408 type = (allow_ofs_delta && DELTA(entry)->idx.offset) ?
409 OBJ_OFS_DELTA : OBJ_REF_DELTA;
410 hdrlen = encode_in_pack_object_header(header, sizeof(header),
413 offset = entry->in_pack_offset;
414 revidx = find_pack_revindex(p, offset);
415 datalen = revidx[1].offset - offset;
416 if (!pack_to_stdout && p->index_version > 1 &&
417 check_pack_crc(p, &w_curs, offset, datalen, revidx->nr)) {
418 error(_("bad packed object CRC for %s"),
419 oid_to_hex(&entry->idx.oid));
421 return write_no_reuse_object(f, entry, limit, usable_delta);
424 offset += entry->in_pack_header_size;
425 datalen -= entry->in_pack_header_size;
427 if (!pack_to_stdout && p->index_version == 1 &&
428 check_pack_inflate(p, &w_curs, offset, datalen, entry_size)) {
429 error(_("corrupt packed object for %s"),
430 oid_to_hex(&entry->idx.oid));
432 return write_no_reuse_object(f, entry, limit, usable_delta);
435 if (type == OBJ_OFS_DELTA) {
436 off_t ofs = entry->idx.offset - DELTA(entry)->idx.offset;
437 unsigned pos = sizeof(dheader) - 1;
438 dheader[pos] = ofs & 127;
440 dheader[--pos] = 128 | (--ofs & 127);
441 if (limit && hdrlen + sizeof(dheader) - pos + datalen + hashsz >= limit) {
445 hashwrite(f, header, hdrlen);
446 hashwrite(f, dheader + pos, sizeof(dheader) - pos);
447 hdrlen += sizeof(dheader) - pos;
449 } else if (type == OBJ_REF_DELTA) {
450 if (limit && hdrlen + hashsz + datalen + hashsz >= limit) {
454 hashwrite(f, header, hdrlen);
455 hashwrite(f, DELTA(entry)->idx.oid.hash, hashsz);
459 if (limit && hdrlen + datalen + hashsz >= limit) {
463 hashwrite(f, header, hdrlen);
465 copy_pack_data(f, p, &w_curs, offset, datalen);
468 return hdrlen + datalen;
471 /* Return 0 if we will bust the pack-size limit */
472 static off_t write_object(struct hashfile *f,
473 struct object_entry *entry,
478 int usable_delta, to_reuse;
483 /* apply size limit if limited packsize and not first object */
484 if (!pack_size_limit || !nr_written)
486 else if (pack_size_limit <= write_offset)
488 * the earlier object did not fit the limit; avoid
489 * mistaking this with unlimited (i.e. limit = 0).
493 limit = pack_size_limit - write_offset;
496 usable_delta = 0; /* no delta */
497 else if (!pack_size_limit)
498 usable_delta = 1; /* unlimited packfile */
499 else if (DELTA(entry)->idx.offset == (off_t)-1)
500 usable_delta = 0; /* base was written to another pack */
501 else if (DELTA(entry)->idx.offset)
502 usable_delta = 1; /* base already exists in this pack */
504 usable_delta = 0; /* base could end up in another pack */
507 to_reuse = 0; /* explicit */
508 else if (!IN_PACK(entry))
509 to_reuse = 0; /* can't reuse what we don't have */
510 else if (oe_type(entry) == OBJ_REF_DELTA ||
511 oe_type(entry) == OBJ_OFS_DELTA)
512 /* check_object() decided it for us ... */
513 to_reuse = usable_delta;
514 /* ... but pack split may override that */
515 else if (oe_type(entry) != entry->in_pack_type)
516 to_reuse = 0; /* pack has delta which is unusable */
517 else if (DELTA(entry))
518 to_reuse = 0; /* we want to pack afresh */
520 to_reuse = 1; /* we have it in-pack undeltified,
521 * and we do not need to deltify it.
525 len = write_no_reuse_object(f, entry, limit, usable_delta);
527 len = write_reuse_object(f, entry, limit, usable_delta);
535 entry->idx.crc32 = crc32_end(f);
539 enum write_one_status {
540 WRITE_ONE_SKIP = -1, /* already written */
541 WRITE_ONE_BREAK = 0, /* writing this will bust the limit; not written */
542 WRITE_ONE_WRITTEN = 1, /* normal */
543 WRITE_ONE_RECURSIVE = 2 /* already scheduled to be written */
546 static enum write_one_status write_one(struct hashfile *f,
547 struct object_entry *e,
554 * we set offset to 1 (which is an impossible value) to mark
555 * the fact that this object is involved in "write its base
556 * first before writing a deltified object" recursion.
558 recursing = (e->idx.offset == 1);
560 warning(_("recursive delta detected for object %s"),
561 oid_to_hex(&e->idx.oid));
562 return WRITE_ONE_RECURSIVE;
563 } else if (e->idx.offset || e->preferred_base) {
564 /* offset is non zero if object is written already. */
565 return WRITE_ONE_SKIP;
568 /* if we are deltified, write out base object first. */
570 e->idx.offset = 1; /* now recurse */
571 switch (write_one(f, DELTA(e), offset)) {
572 case WRITE_ONE_RECURSIVE:
573 /* we cannot depend on this one */
578 case WRITE_ONE_BREAK:
579 e->idx.offset = recursing;
580 return WRITE_ONE_BREAK;
584 e->idx.offset = *offset;
585 size = write_object(f, e, *offset);
587 e->idx.offset = recursing;
588 return WRITE_ONE_BREAK;
590 written_list[nr_written++] = &e->idx;
592 /* make sure off_t is sufficiently large not to wrap */
593 if (signed_add_overflows(*offset, size))
594 die(_("pack too large for current definition of off_t"));
596 return WRITE_ONE_WRITTEN;
599 static int mark_tagged(const char *path, const struct object_id *oid, int flag,
602 struct object_id peeled;
603 struct object_entry *entry = packlist_find(&to_pack, oid->hash, NULL);
607 if (!peel_ref(path, &peeled)) {
608 entry = packlist_find(&to_pack, peeled.hash, NULL);
615 static inline void add_to_write_order(struct object_entry **wo,
617 struct object_entry *e)
625 static void add_descendants_to_write_order(struct object_entry **wo,
627 struct object_entry *e)
629 int add_to_order = 1;
632 struct object_entry *s;
633 /* add this node... */
634 add_to_write_order(wo, endp, e);
635 /* all its siblings... */
636 for (s = DELTA_SIBLING(e); s; s = DELTA_SIBLING(s)) {
637 add_to_write_order(wo, endp, s);
640 /* drop down a level to add left subtree nodes if possible */
641 if (DELTA_CHILD(e)) {
646 /* our sibling might have some children, it is next */
647 if (DELTA_SIBLING(e)) {
648 e = DELTA_SIBLING(e);
651 /* go back to our parent node */
653 while (e && !DELTA_SIBLING(e)) {
654 /* we're on the right side of a subtree, keep
655 * going up until we can go right again */
659 /* done- we hit our original root node */
662 /* pass it off to sibling at this level */
663 e = DELTA_SIBLING(e);
668 static void add_family_to_write_order(struct object_entry **wo,
670 struct object_entry *e)
672 struct object_entry *root;
674 for (root = e; DELTA(root); root = DELTA(root))
676 add_descendants_to_write_order(wo, endp, root);
679 static struct object_entry **compute_write_order(void)
681 unsigned int i, wo_end, last_untagged;
683 struct object_entry **wo;
684 struct object_entry *objects = to_pack.objects;
686 for (i = 0; i < to_pack.nr_objects; i++) {
687 objects[i].tagged = 0;
688 objects[i].filled = 0;
689 SET_DELTA_CHILD(&objects[i], NULL);
690 SET_DELTA_SIBLING(&objects[i], NULL);
694 * Fully connect delta_child/delta_sibling network.
695 * Make sure delta_sibling is sorted in the original
698 for (i = to_pack.nr_objects; i > 0;) {
699 struct object_entry *e = &objects[--i];
702 /* Mark me as the first child */
703 e->delta_sibling_idx = DELTA(e)->delta_child_idx;
704 SET_DELTA_CHILD(DELTA(e), e);
708 * Mark objects that are at the tip of tags.
710 for_each_tag_ref(mark_tagged, NULL);
713 * Give the objects in the original recency order until
714 * we see a tagged tip.
716 ALLOC_ARRAY(wo, to_pack.nr_objects);
717 for (i = wo_end = 0; i < to_pack.nr_objects; i++) {
718 if (objects[i].tagged)
720 add_to_write_order(wo, &wo_end, &objects[i]);
725 * Then fill all the tagged tips.
727 for (; i < to_pack.nr_objects; i++) {
728 if (objects[i].tagged)
729 add_to_write_order(wo, &wo_end, &objects[i]);
733 * And then all remaining commits and tags.
735 for (i = last_untagged; i < to_pack.nr_objects; i++) {
736 if (oe_type(&objects[i]) != OBJ_COMMIT &&
737 oe_type(&objects[i]) != OBJ_TAG)
739 add_to_write_order(wo, &wo_end, &objects[i]);
743 * And then all the trees.
745 for (i = last_untagged; i < to_pack.nr_objects; i++) {
746 if (oe_type(&objects[i]) != OBJ_TREE)
748 add_to_write_order(wo, &wo_end, &objects[i]);
752 * Finally all the rest in really tight order
754 for (i = last_untagged; i < to_pack.nr_objects; i++) {
755 if (!objects[i].filled)
756 add_family_to_write_order(wo, &wo_end, &objects[i]);
759 if (wo_end != to_pack.nr_objects)
760 die(_("ordered %u objects, expected %"PRIu32),
761 wo_end, to_pack.nr_objects);
766 static off_t write_reused_pack(struct hashfile *f)
768 unsigned char buffer[8192];
769 off_t to_write, total;
772 if (!is_pack_valid(reuse_packfile))
773 die(_("packfile is invalid: %s"), reuse_packfile->pack_name);
775 fd = git_open(reuse_packfile->pack_name);
777 die_errno(_("unable to open packfile for reuse: %s"),
778 reuse_packfile->pack_name);
780 if (lseek(fd, sizeof(struct pack_header), SEEK_SET) == -1)
781 die_errno(_("unable to seek in reused packfile"));
783 if (reuse_packfile_offset < 0)
784 reuse_packfile_offset = reuse_packfile->pack_size - the_hash_algo->rawsz;
786 total = to_write = reuse_packfile_offset - sizeof(struct pack_header);
789 int read_pack = xread(fd, buffer, sizeof(buffer));
792 die_errno(_("unable to read from reused packfile"));
794 if (read_pack > to_write)
795 read_pack = to_write;
797 hashwrite(f, buffer, read_pack);
798 to_write -= read_pack;
801 * We don't know the actual number of objects written,
802 * only how many bytes written, how many bytes total, and
803 * how many objects total. So we can fake it by pretending all
804 * objects we are writing are the same size. This gives us a
805 * smooth progress meter, and at the end it matches the true
808 written = reuse_packfile_objects *
809 (((double)(total - to_write)) / total);
810 display_progress(progress_state, written);
814 written = reuse_packfile_objects;
815 display_progress(progress_state, written);
816 return reuse_packfile_offset - sizeof(struct pack_header);
819 static const char no_split_warning[] = N_(
820 "disabling bitmap writing, packs are split due to pack.packSizeLimit"
823 static void write_pack_file(void)
828 uint32_t nr_remaining = nr_result;
829 time_t last_mtime = 0;
830 struct object_entry **write_order;
832 if (progress > pack_to_stdout)
833 progress_state = start_progress(_("Writing objects"), nr_result);
834 ALLOC_ARRAY(written_list, to_pack.nr_objects);
835 write_order = compute_write_order();
838 struct object_id oid;
839 char *pack_tmp_name = NULL;
842 f = hashfd_throughput(1, "<stdout>", progress_state);
844 f = create_tmp_packfile(&pack_tmp_name);
846 offset = write_pack_header(f, nr_remaining);
848 if (reuse_packfile) {
850 assert(pack_to_stdout);
852 packfile_size = write_reused_pack(f);
853 offset += packfile_size;
857 for (; i < to_pack.nr_objects; i++) {
858 struct object_entry *e = write_order[i];
859 if (write_one(f, e, &offset) == WRITE_ONE_BREAK)
861 display_progress(progress_state, written);
865 * Did we write the wrong # entries in the header?
866 * If so, rewrite it like in fast-import
868 if (pack_to_stdout) {
869 finalize_hashfile(f, oid.hash, CSUM_HASH_IN_STREAM | CSUM_CLOSE);
870 } else if (nr_written == nr_remaining) {
871 finalize_hashfile(f, oid.hash, CSUM_HASH_IN_STREAM | CSUM_FSYNC | CSUM_CLOSE);
873 int fd = finalize_hashfile(f, oid.hash, 0);
874 fixup_pack_header_footer(fd, oid.hash, pack_tmp_name,
875 nr_written, oid.hash, offset);
877 if (write_bitmap_index) {
878 warning(_(no_split_warning));
879 write_bitmap_index = 0;
883 if (!pack_to_stdout) {
885 struct strbuf tmpname = STRBUF_INIT;
888 * Packs are runtime accessed in their mtime
889 * order since newer packs are more likely to contain
890 * younger objects. So if we are creating multiple
891 * packs then we should modify the mtime of later ones
892 * to preserve this property.
894 if (stat(pack_tmp_name, &st) < 0) {
895 warning_errno(_("failed to stat %s"), pack_tmp_name);
896 } else if (!last_mtime) {
897 last_mtime = st.st_mtime;
900 utb.actime = st.st_atime;
901 utb.modtime = --last_mtime;
902 if (utime(pack_tmp_name, &utb) < 0)
903 warning_errno(_("failed utime() on %s"), pack_tmp_name);
906 strbuf_addf(&tmpname, "%s-", base_name);
908 if (write_bitmap_index) {
909 bitmap_writer_set_checksum(oid.hash);
910 bitmap_writer_build_type_index(
911 &to_pack, written_list, nr_written);
914 finish_tmp_packfile(&tmpname, pack_tmp_name,
915 written_list, nr_written,
916 &pack_idx_opts, oid.hash);
918 if (write_bitmap_index) {
919 strbuf_addf(&tmpname, "%s.bitmap", oid_to_hex(&oid));
921 stop_progress(&progress_state);
923 bitmap_writer_show_progress(progress);
924 bitmap_writer_reuse_bitmaps(&to_pack);
925 bitmap_writer_select_commits(indexed_commits, indexed_commits_nr, -1);
926 bitmap_writer_build(&to_pack);
927 bitmap_writer_finish(written_list, nr_written,
928 tmpname.buf, write_bitmap_options);
929 write_bitmap_index = 0;
932 strbuf_release(&tmpname);
934 puts(oid_to_hex(&oid));
937 /* mark written objects as written to previous pack */
938 for (j = 0; j < nr_written; j++) {
939 written_list[j]->offset = (off_t)-1;
941 nr_remaining -= nr_written;
942 } while (nr_remaining && i < to_pack.nr_objects);
946 stop_progress(&progress_state);
947 if (written != nr_result)
948 die(_("wrote %"PRIu32" objects while expecting %"PRIu32),
952 static int no_try_delta(const char *path)
954 static struct attr_check *check;
957 check = attr_check_initl("delta", NULL);
958 if (git_check_attr(&the_index, path, check))
960 if (ATTR_FALSE(check->items[0].value))
966 * When adding an object, check whether we have already added it
967 * to our packing list. If so, we can skip. However, if we are
968 * being asked to excludei t, but the previous mention was to include
969 * it, make sure to adjust its flags and tweak our numbers accordingly.
971 * As an optimization, we pass out the index position where we would have
972 * found the item, since that saves us from having to look it up again a
973 * few lines later when we want to add the new entry.
975 static int have_duplicate_entry(const struct object_id *oid,
979 struct object_entry *entry;
981 entry = packlist_find(&to_pack, oid->hash, index_pos);
986 if (!entry->preferred_base)
988 entry->preferred_base = 1;
994 static int want_found_object(int exclude, struct packed_git *p)
1002 * When asked to do --local (do not include an object that appears in a
1003 * pack we borrow from elsewhere) or --honor-pack-keep (do not include
1004 * an object that appears in a pack marked with .keep), finding a pack
1005 * that matches the criteria is sufficient for us to decide to omit it.
1006 * However, even if this pack does not satisfy the criteria, we need to
1007 * make sure no copy of this object appears in _any_ pack that makes us
1008 * to omit the object, so we need to check all the packs.
1010 * We can however first check whether these options can possible matter;
1011 * if they do not matter we know we want the object in generated pack.
1012 * Otherwise, we signal "-1" at the end to tell the caller that we do
1013 * not know either way, and it needs to check more packs.
1015 if (!ignore_packed_keep_on_disk &&
1016 !ignore_packed_keep_in_core &&
1017 (!local || !have_non_local_packs))
1020 if (local && !p->pack_local)
1022 if (p->pack_local &&
1023 ((ignore_packed_keep_on_disk && p->pack_keep) ||
1024 (ignore_packed_keep_in_core && p->pack_keep_in_core)))
1027 /* we don't know yet; keep looking for more packs */
1032 * Check whether we want the object in the pack (e.g., we do not want
1033 * objects found in non-local stores if the "--local" option was used).
1035 * If the caller already knows an existing pack it wants to take the object
1036 * from, that is passed in *found_pack and *found_offset; otherwise this
1037 * function finds if there is any pack that has the object and returns the pack
1038 * and its offset in these variables.
1040 static int want_object_in_pack(const struct object_id *oid,
1042 struct packed_git **found_pack,
1043 off_t *found_offset)
1046 struct list_head *pos;
1047 struct multi_pack_index *m;
1049 if (!exclude && local && has_loose_object_nonlocal(oid))
1053 * If we already know the pack object lives in, start checks from that
1054 * pack - in the usual case when neither --local was given nor .keep files
1055 * are present we will determine the answer right now.
1058 want = want_found_object(exclude, *found_pack);
1063 for (m = get_multi_pack_index(the_repository); m; m = m->next) {
1064 struct pack_entry e;
1065 if (fill_midx_entry(oid, &e, m)) {
1066 struct packed_git *p = e.p;
1069 if (p == *found_pack)
1070 offset = *found_offset;
1072 offset = find_pack_entry_one(oid->hash, p);
1076 if (!is_pack_valid(p))
1078 *found_offset = offset;
1081 want = want_found_object(exclude, p);
1088 list_for_each(pos, get_packed_git_mru(the_repository)) {
1089 struct packed_git *p = list_entry(pos, struct packed_git, mru);
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);
1105 if (!exclude && want > 0)
1107 get_packed_git_mru(the_repository));
1116 static void create_object_entry(const struct object_id *oid,
1117 enum object_type type,
1122 struct packed_git *found_pack,
1125 struct object_entry *entry;
1127 entry = packlist_alloc(&to_pack, oid->hash, index_pos);
1129 oe_set_type(entry, type);
1131 entry->preferred_base = 1;
1135 oe_set_in_pack(&to_pack, entry, found_pack);
1136 entry->in_pack_offset = found_offset;
1139 entry->no_try_delta = no_try_delta;
1142 static const char no_closure_warning[] = N_(
1143 "disabling bitmap writing, as some objects are not being packed"
1146 static int add_object_entry(const struct object_id *oid, enum object_type type,
1147 const char *name, int exclude)
1149 struct packed_git *found_pack = NULL;
1150 off_t found_offset = 0;
1153 display_progress(progress_state, ++nr_seen);
1155 if (have_duplicate_entry(oid, exclude, &index_pos))
1158 if (!want_object_in_pack(oid, exclude, &found_pack, &found_offset)) {
1159 /* The pack is missing an object, so it will not have closure */
1160 if (write_bitmap_index) {
1161 warning(_(no_closure_warning));
1162 write_bitmap_index = 0;
1167 create_object_entry(oid, type, pack_name_hash(name),
1168 exclude, name && no_try_delta(name),
1169 index_pos, found_pack, found_offset);
1173 static int add_object_entry_from_bitmap(const struct object_id *oid,
1174 enum object_type type,
1175 int flags, uint32_t name_hash,
1176 struct packed_git *pack, off_t offset)
1180 display_progress(progress_state, ++nr_seen);
1182 if (have_duplicate_entry(oid, 0, &index_pos))
1185 if (!want_object_in_pack(oid, 0, &pack, &offset))
1188 create_object_entry(oid, type, name_hash, 0, 0, index_pos, pack, offset);
1192 struct pbase_tree_cache {
1193 struct object_id oid;
1197 unsigned long tree_size;
1200 static struct pbase_tree_cache *(pbase_tree_cache[256]);
1201 static int pbase_tree_cache_ix(const struct object_id *oid)
1203 return oid->hash[0] % ARRAY_SIZE(pbase_tree_cache);
1205 static int pbase_tree_cache_ix_incr(int ix)
1207 return (ix+1) % ARRAY_SIZE(pbase_tree_cache);
1210 static struct pbase_tree {
1211 struct pbase_tree *next;
1212 /* This is a phony "cache" entry; we are not
1213 * going to evict it or find it through _get()
1214 * mechanism -- this is for the toplevel node that
1215 * would almost always change with any commit.
1217 struct pbase_tree_cache pcache;
1220 static struct pbase_tree_cache *pbase_tree_get(const struct object_id *oid)
1222 struct pbase_tree_cache *ent, *nent;
1225 enum object_type type;
1227 int my_ix = pbase_tree_cache_ix(oid);
1228 int available_ix = -1;
1230 /* pbase-tree-cache acts as a limited hashtable.
1231 * your object will be found at your index or within a few
1232 * slots after that slot if it is cached.
1234 for (neigh = 0; neigh < 8; neigh++) {
1235 ent = pbase_tree_cache[my_ix];
1236 if (ent && !oidcmp(&ent->oid, oid)) {
1240 else if (((available_ix < 0) && (!ent || !ent->ref)) ||
1241 ((0 <= available_ix) &&
1242 (!ent && pbase_tree_cache[available_ix])))
1243 available_ix = my_ix;
1246 my_ix = pbase_tree_cache_ix_incr(my_ix);
1249 /* Did not find one. Either we got a bogus request or
1250 * we need to read and perhaps cache.
1252 data = read_object_file(oid, &type, &size);
1255 if (type != OBJ_TREE) {
1260 /* We need to either cache or return a throwaway copy */
1262 if (available_ix < 0)
1265 ent = pbase_tree_cache[available_ix];
1266 my_ix = available_ix;
1270 nent = xmalloc(sizeof(*nent));
1271 nent->temporary = (available_ix < 0);
1274 /* evict and reuse */
1275 free(ent->tree_data);
1278 oidcpy(&nent->oid, oid);
1279 nent->tree_data = data;
1280 nent->tree_size = size;
1282 if (!nent->temporary)
1283 pbase_tree_cache[my_ix] = nent;
1287 static void pbase_tree_put(struct pbase_tree_cache *cache)
1289 if (!cache->temporary) {
1293 free(cache->tree_data);
1297 static int name_cmp_len(const char *name)
1300 for (i = 0; name[i] && name[i] != '\n' && name[i] != '/'; i++)
1305 static void add_pbase_object(struct tree_desc *tree,
1308 const char *fullname)
1310 struct name_entry entry;
1313 while (tree_entry(tree,&entry)) {
1314 if (S_ISGITLINK(entry.mode))
1316 cmp = tree_entry_len(&entry) != cmplen ? 1 :
1317 memcmp(name, entry.path, cmplen);
1322 if (name[cmplen] != '/') {
1323 add_object_entry(entry.oid,
1324 object_type(entry.mode),
1328 if (S_ISDIR(entry.mode)) {
1329 struct tree_desc sub;
1330 struct pbase_tree_cache *tree;
1331 const char *down = name+cmplen+1;
1332 int downlen = name_cmp_len(down);
1334 tree = pbase_tree_get(entry.oid);
1337 init_tree_desc(&sub, tree->tree_data, tree->tree_size);
1339 add_pbase_object(&sub, down, downlen, fullname);
1340 pbase_tree_put(tree);
1345 static unsigned *done_pbase_paths;
1346 static int done_pbase_paths_num;
1347 static int done_pbase_paths_alloc;
1348 static int done_pbase_path_pos(unsigned hash)
1351 int hi = done_pbase_paths_num;
1353 int mi = lo + (hi - lo) / 2;
1354 if (done_pbase_paths[mi] == hash)
1356 if (done_pbase_paths[mi] < hash)
1364 static int check_pbase_path(unsigned hash)
1366 int pos = done_pbase_path_pos(hash);
1370 ALLOC_GROW(done_pbase_paths,
1371 done_pbase_paths_num + 1,
1372 done_pbase_paths_alloc);
1373 done_pbase_paths_num++;
1374 if (pos < done_pbase_paths_num)
1375 MOVE_ARRAY(done_pbase_paths + pos + 1, done_pbase_paths + pos,
1376 done_pbase_paths_num - pos - 1);
1377 done_pbase_paths[pos] = hash;
1381 static void add_preferred_base_object(const char *name)
1383 struct pbase_tree *it;
1385 unsigned hash = pack_name_hash(name);
1387 if (!num_preferred_base || check_pbase_path(hash))
1390 cmplen = name_cmp_len(name);
1391 for (it = pbase_tree; it; it = it->next) {
1393 add_object_entry(&it->pcache.oid, OBJ_TREE, NULL, 1);
1396 struct tree_desc tree;
1397 init_tree_desc(&tree, it->pcache.tree_data, it->pcache.tree_size);
1398 add_pbase_object(&tree, name, cmplen, name);
1403 static void add_preferred_base(struct object_id *oid)
1405 struct pbase_tree *it;
1408 struct object_id tree_oid;
1410 if (window <= num_preferred_base++)
1413 data = read_object_with_reference(oid, tree_type, &size, &tree_oid);
1417 for (it = pbase_tree; it; it = it->next) {
1418 if (!oidcmp(&it->pcache.oid, &tree_oid)) {
1424 it = xcalloc(1, sizeof(*it));
1425 it->next = pbase_tree;
1428 oidcpy(&it->pcache.oid, &tree_oid);
1429 it->pcache.tree_data = data;
1430 it->pcache.tree_size = size;
1433 static void cleanup_preferred_base(void)
1435 struct pbase_tree *it;
1441 struct pbase_tree *tmp = it;
1443 free(tmp->pcache.tree_data);
1447 for (i = 0; i < ARRAY_SIZE(pbase_tree_cache); i++) {
1448 if (!pbase_tree_cache[i])
1450 free(pbase_tree_cache[i]->tree_data);
1451 FREE_AND_NULL(pbase_tree_cache[i]);
1454 FREE_AND_NULL(done_pbase_paths);
1455 done_pbase_paths_num = done_pbase_paths_alloc = 0;
1458 static void check_object(struct object_entry *entry)
1460 unsigned long canonical_size;
1462 if (IN_PACK(entry)) {
1463 struct packed_git *p = IN_PACK(entry);
1464 struct pack_window *w_curs = NULL;
1465 const unsigned char *base_ref = NULL;
1466 struct object_entry *base_entry;
1467 unsigned long used, used_0;
1468 unsigned long avail;
1470 unsigned char *buf, c;
1471 enum object_type type;
1472 unsigned long in_pack_size;
1474 buf = use_pack(p, &w_curs, entry->in_pack_offset, &avail);
1477 * We want in_pack_type even if we do not reuse delta
1478 * since non-delta representations could still be reused.
1480 used = unpack_object_header_buffer(buf, avail,
1487 BUG("invalid type %d", type);
1488 entry->in_pack_type = type;
1491 * Determine if this is a delta and if so whether we can
1492 * reuse it or not. Otherwise let's find out as cheaply as
1493 * possible what the actual type and size for this object is.
1495 switch (entry->in_pack_type) {
1497 /* Not a delta hence we've already got all we need. */
1498 oe_set_type(entry, entry->in_pack_type);
1499 SET_SIZE(entry, in_pack_size);
1500 entry->in_pack_header_size = used;
1501 if (oe_type(entry) < OBJ_COMMIT || oe_type(entry) > OBJ_BLOB)
1503 unuse_pack(&w_curs);
1506 if (reuse_delta && !entry->preferred_base)
1507 base_ref = use_pack(p, &w_curs,
1508 entry->in_pack_offset + used, NULL);
1509 entry->in_pack_header_size = used + the_hash_algo->rawsz;
1512 buf = use_pack(p, &w_curs,
1513 entry->in_pack_offset + used, NULL);
1519 if (!ofs || MSB(ofs, 7)) {
1520 error(_("delta base offset overflow in pack for %s"),
1521 oid_to_hex(&entry->idx.oid));
1525 ofs = (ofs << 7) + (c & 127);
1527 ofs = entry->in_pack_offset - ofs;
1528 if (ofs <= 0 || ofs >= entry->in_pack_offset) {
1529 error(_("delta base offset out of bound for %s"),
1530 oid_to_hex(&entry->idx.oid));
1533 if (reuse_delta && !entry->preferred_base) {
1534 struct revindex_entry *revidx;
1535 revidx = find_pack_revindex(p, ofs);
1538 base_ref = nth_packed_object_sha1(p, revidx->nr);
1540 entry->in_pack_header_size = used + used_0;
1545 (base_entry = packlist_find(&to_pack, base_ref, NULL)) ||
1547 bitmap_has_sha1_in_uninteresting(bitmap_git, base_ref)))) {
1549 * If base_ref was set above that means we wish to
1550 * reuse delta data, and either we found that object in
1551 * the list of objects we want to pack, or it's one we
1552 * know the receiver has.
1554 * Depth value does not matter - find_deltas() will
1555 * never consider reused delta as the base object to
1556 * deltify other objects against, in order to avoid
1559 oe_set_type(entry, entry->in_pack_type);
1560 SET_SIZE(entry, in_pack_size); /* delta size */
1561 SET_DELTA_SIZE(entry, in_pack_size);
1564 SET_DELTA(entry, base_entry);
1565 entry->delta_sibling_idx = base_entry->delta_child_idx;
1566 SET_DELTA_CHILD(base_entry, entry);
1568 SET_DELTA_EXT(entry, base_ref);
1571 unuse_pack(&w_curs);
1575 if (oe_type(entry)) {
1579 * This must be a delta and we already know what the
1580 * final object type is. Let's extract the actual
1581 * object size from the delta header.
1583 delta_pos = entry->in_pack_offset + entry->in_pack_header_size;
1584 canonical_size = get_size_from_delta(p, &w_curs, delta_pos);
1585 if (canonical_size == 0)
1587 SET_SIZE(entry, canonical_size);
1588 unuse_pack(&w_curs);
1593 * No choice but to fall back to the recursive delta walk
1594 * with sha1_object_info() to find about the object type
1598 unuse_pack(&w_curs);
1602 oid_object_info(the_repository, &entry->idx.oid, &canonical_size));
1603 if (entry->type_valid) {
1604 SET_SIZE(entry, canonical_size);
1607 * Bad object type is checked in prepare_pack(). This is
1608 * to permit a missing preferred base object to be ignored
1609 * as a preferred base. Doing so can result in a larger
1610 * pack file, but the transfer will still take place.
1615 static int pack_offset_sort(const void *_a, const void *_b)
1617 const struct object_entry *a = *(struct object_entry **)_a;
1618 const struct object_entry *b = *(struct object_entry **)_b;
1619 const struct packed_git *a_in_pack = IN_PACK(a);
1620 const struct packed_git *b_in_pack = IN_PACK(b);
1622 /* avoid filesystem trashing with loose objects */
1623 if (!a_in_pack && !b_in_pack)
1624 return oidcmp(&a->idx.oid, &b->idx.oid);
1626 if (a_in_pack < b_in_pack)
1628 if (a_in_pack > b_in_pack)
1630 return a->in_pack_offset < b->in_pack_offset ? -1 :
1631 (a->in_pack_offset > b->in_pack_offset);
1635 * Drop an on-disk delta we were planning to reuse. Naively, this would
1636 * just involve blanking out the "delta" field, but we have to deal
1637 * with some extra book-keeping:
1639 * 1. Removing ourselves from the delta_sibling linked list.
1641 * 2. Updating our size/type to the non-delta representation. These were
1642 * either not recorded initially (size) or overwritten with the delta type
1643 * (type) when check_object() decided to reuse the delta.
1645 * 3. Resetting our delta depth, as we are now a base object.
1647 static void drop_reused_delta(struct object_entry *entry)
1649 unsigned *idx = &to_pack.objects[entry->delta_idx - 1].delta_child_idx;
1650 struct object_info oi = OBJECT_INFO_INIT;
1651 enum object_type type;
1655 struct object_entry *oe = &to_pack.objects[*idx - 1];
1658 *idx = oe->delta_sibling_idx;
1660 idx = &oe->delta_sibling_idx;
1662 SET_DELTA(entry, NULL);
1667 if (packed_object_info(the_repository, IN_PACK(entry), entry->in_pack_offset, &oi) < 0) {
1669 * We failed to get the info from this pack for some reason;
1670 * fall back to sha1_object_info, which may find another copy.
1671 * And if that fails, the error will be recorded in oe_type(entry)
1672 * and dealt with in prepare_pack().
1675 oid_object_info(the_repository, &entry->idx.oid, &size));
1677 oe_set_type(entry, type);
1679 SET_SIZE(entry, size);
1683 * Follow the chain of deltas from this entry onward, throwing away any links
1684 * that cause us to hit a cycle (as determined by the DFS state flags in
1687 * We also detect too-long reused chains that would violate our --depth
1690 static void break_delta_chains(struct object_entry *entry)
1693 * The actual depth of each object we will write is stored as an int,
1694 * as it cannot exceed our int "depth" limit. But before we break
1695 * changes based no that limit, we may potentially go as deep as the
1696 * number of objects, which is elsewhere bounded to a uint32_t.
1698 uint32_t total_depth;
1699 struct object_entry *cur, *next;
1701 for (cur = entry, total_depth = 0;
1703 cur = DELTA(cur), total_depth++) {
1704 if (cur->dfs_state == DFS_DONE) {
1706 * We've already seen this object and know it isn't
1707 * part of a cycle. We do need to append its depth
1710 total_depth += cur->depth;
1715 * We break cycles before looping, so an ACTIVE state (or any
1716 * other cruft which made its way into the state variable)
1719 if (cur->dfs_state != DFS_NONE)
1720 BUG("confusing delta dfs state in first pass: %d",
1724 * Now we know this is the first time we've seen the object. If
1725 * it's not a delta, we're done traversing, but we'll mark it
1726 * done to save time on future traversals.
1729 cur->dfs_state = DFS_DONE;
1734 * Mark ourselves as active and see if the next step causes
1735 * us to cycle to another active object. It's important to do
1736 * this _before_ we loop, because it impacts where we make the
1737 * cut, and thus how our total_depth counter works.
1738 * E.g., We may see a partial loop like:
1740 * A -> B -> C -> D -> B
1742 * Cutting B->C breaks the cycle. But now the depth of A is
1743 * only 1, and our total_depth counter is at 3. The size of the
1744 * error is always one less than the size of the cycle we
1745 * broke. Commits C and D were "lost" from A's chain.
1747 * If we instead cut D->B, then the depth of A is correct at 3.
1748 * We keep all commits in the chain that we examined.
1750 cur->dfs_state = DFS_ACTIVE;
1751 if (DELTA(cur)->dfs_state == DFS_ACTIVE) {
1752 drop_reused_delta(cur);
1753 cur->dfs_state = DFS_DONE;
1759 * And now that we've gone all the way to the bottom of the chain, we
1760 * need to clear the active flags and set the depth fields as
1761 * appropriate. Unlike the loop above, which can quit when it drops a
1762 * delta, we need to keep going to look for more depth cuts. So we need
1763 * an extra "next" pointer to keep going after we reset cur->delta.
1765 for (cur = entry; cur; cur = next) {
1769 * We should have a chain of zero or more ACTIVE states down to
1770 * a final DONE. We can quit after the DONE, because either it
1771 * has no bases, or we've already handled them in a previous
1774 if (cur->dfs_state == DFS_DONE)
1776 else if (cur->dfs_state != DFS_ACTIVE)
1777 BUG("confusing delta dfs state in second pass: %d",
1781 * If the total_depth is more than depth, then we need to snip
1782 * the chain into two or more smaller chains that don't exceed
1783 * the maximum depth. Most of the resulting chains will contain
1784 * (depth + 1) entries (i.e., depth deltas plus one base), and
1785 * the last chain (i.e., the one containing entry) will contain
1786 * whatever entries are left over, namely
1787 * (total_depth % (depth + 1)) of them.
1789 * Since we are iterating towards decreasing depth, we need to
1790 * decrement total_depth as we go, and we need to write to the
1791 * entry what its final depth will be after all of the
1792 * snipping. Since we're snipping into chains of length (depth
1793 * + 1) entries, the final depth of an entry will be its
1794 * original depth modulo (depth + 1). Any time we encounter an
1795 * entry whose final depth is supposed to be zero, we snip it
1796 * from its delta base, thereby making it so.
1798 cur->depth = (total_depth--) % (depth + 1);
1800 drop_reused_delta(cur);
1802 cur->dfs_state = DFS_DONE;
1806 static void get_object_details(void)
1809 struct object_entry **sorted_by_offset;
1812 progress_state = start_progress(_("Counting objects"),
1813 to_pack.nr_objects);
1815 sorted_by_offset = xcalloc(to_pack.nr_objects, sizeof(struct object_entry *));
1816 for (i = 0; i < to_pack.nr_objects; i++)
1817 sorted_by_offset[i] = to_pack.objects + i;
1818 QSORT(sorted_by_offset, to_pack.nr_objects, pack_offset_sort);
1820 for (i = 0; i < to_pack.nr_objects; i++) {
1821 struct object_entry *entry = sorted_by_offset[i];
1822 check_object(entry);
1823 if (entry->type_valid &&
1824 oe_size_greater_than(&to_pack, entry, big_file_threshold))
1825 entry->no_try_delta = 1;
1826 display_progress(progress_state, i + 1);
1828 stop_progress(&progress_state);
1831 * This must happen in a second pass, since we rely on the delta
1832 * information for the whole list being completed.
1834 for (i = 0; i < to_pack.nr_objects; i++)
1835 break_delta_chains(&to_pack.objects[i]);
1837 free(sorted_by_offset);
1841 * We search for deltas in a list sorted by type, by filename hash, and then
1842 * by size, so that we see progressively smaller and smaller files.
1843 * That's because we prefer deltas to be from the bigger file
1844 * to the smaller -- deletes are potentially cheaper, but perhaps
1845 * more importantly, the bigger file is likely the more recent
1846 * one. The deepest deltas are therefore the oldest objects which are
1847 * less susceptible to be accessed often.
1849 static int type_size_sort(const void *_a, const void *_b)
1851 const struct object_entry *a = *(struct object_entry **)_a;
1852 const struct object_entry *b = *(struct object_entry **)_b;
1853 enum object_type a_type = oe_type(a);
1854 enum object_type b_type = oe_type(b);
1855 unsigned long a_size = SIZE(a);
1856 unsigned long b_size = SIZE(b);
1858 if (a_type > b_type)
1860 if (a_type < b_type)
1862 if (a->hash > b->hash)
1864 if (a->hash < b->hash)
1866 if (a->preferred_base > b->preferred_base)
1868 if (a->preferred_base < b->preferred_base)
1870 if (a_size > b_size)
1872 if (a_size < b_size)
1874 return a < b ? -1 : (a > b); /* newest first */
1878 struct object_entry *entry;
1880 struct delta_index *index;
1884 static int delta_cacheable(unsigned long src_size, unsigned long trg_size,
1885 unsigned long delta_size)
1887 if (max_delta_cache_size && delta_cache_size + delta_size > max_delta_cache_size)
1890 if (delta_size < cache_max_small_delta_size)
1893 /* cache delta, if objects are large enough compared to delta size */
1894 if ((src_size >> 20) + (trg_size >> 21) > (delta_size >> 10))
1902 /* Protect access to object database */
1903 static pthread_mutex_t read_mutex;
1904 #define read_lock() pthread_mutex_lock(&read_mutex)
1905 #define read_unlock() pthread_mutex_unlock(&read_mutex)
1907 /* Protect delta_cache_size */
1908 static pthread_mutex_t cache_mutex;
1909 #define cache_lock() pthread_mutex_lock(&cache_mutex)
1910 #define cache_unlock() pthread_mutex_unlock(&cache_mutex)
1913 * Protect object list partitioning (e.g. struct thread_param) and
1916 static pthread_mutex_t progress_mutex;
1917 #define progress_lock() pthread_mutex_lock(&progress_mutex)
1918 #define progress_unlock() pthread_mutex_unlock(&progress_mutex)
1921 * Access to struct object_entry is unprotected since each thread owns
1922 * a portion of the main object list. Just don't access object entries
1923 * ahead in the list because they can be stolen and would need
1924 * progress_mutex for protection.
1928 #define read_lock() (void)0
1929 #define read_unlock() (void)0
1930 #define cache_lock() (void)0
1931 #define cache_unlock() (void)0
1932 #define progress_lock() (void)0
1933 #define progress_unlock() (void)0
1938 * Return the size of the object without doing any delta
1939 * reconstruction (so non-deltas are true object sizes, but deltas
1940 * return the size of the delta data).
1942 unsigned long oe_get_size_slow(struct packing_data *pack,
1943 const struct object_entry *e)
1945 struct packed_git *p;
1946 struct pack_window *w_curs;
1948 enum object_type type;
1949 unsigned long used, avail, size;
1951 if (e->type_ != OBJ_OFS_DELTA && e->type_ != OBJ_REF_DELTA) {
1953 if (oid_object_info(the_repository, &e->idx.oid, &size) < 0)
1954 die(_("unable to get size of %s"),
1955 oid_to_hex(&e->idx.oid));
1960 p = oe_in_pack(pack, e);
1962 BUG("when e->type is a delta, it must belong to a pack");
1966 buf = use_pack(p, &w_curs, e->in_pack_offset, &avail);
1967 used = unpack_object_header_buffer(buf, avail, &type, &size);
1969 die(_("unable to parse object header of %s"),
1970 oid_to_hex(&e->idx.oid));
1972 unuse_pack(&w_curs);
1977 static int try_delta(struct unpacked *trg, struct unpacked *src,
1978 unsigned max_depth, unsigned long *mem_usage)
1980 struct object_entry *trg_entry = trg->entry;
1981 struct object_entry *src_entry = src->entry;
1982 unsigned long trg_size, src_size, delta_size, sizediff, max_size, sz;
1984 enum object_type type;
1987 /* Don't bother doing diffs between different types */
1988 if (oe_type(trg_entry) != oe_type(src_entry))
1992 * We do not bother to try a delta that we discarded on an
1993 * earlier try, but only when reusing delta data. Note that
1994 * src_entry that is marked as the preferred_base should always
1995 * be considered, as even if we produce a suboptimal delta against
1996 * it, we will still save the transfer cost, as we already know
1997 * the other side has it and we won't send src_entry at all.
1999 if (reuse_delta && IN_PACK(trg_entry) &&
2000 IN_PACK(trg_entry) == IN_PACK(src_entry) &&
2001 !src_entry->preferred_base &&
2002 trg_entry->in_pack_type != OBJ_REF_DELTA &&
2003 trg_entry->in_pack_type != OBJ_OFS_DELTA)
2006 /* Let's not bust the allowed depth. */
2007 if (src->depth >= max_depth)
2010 /* Now some size filtering heuristics. */
2011 trg_size = SIZE(trg_entry);
2012 if (!DELTA(trg_entry)) {
2013 max_size = trg_size/2 - the_hash_algo->rawsz;
2016 max_size = DELTA_SIZE(trg_entry);
2017 ref_depth = trg->depth;
2019 max_size = (uint64_t)max_size * (max_depth - src->depth) /
2020 (max_depth - ref_depth + 1);
2023 src_size = SIZE(src_entry);
2024 sizediff = src_size < trg_size ? trg_size - src_size : 0;
2025 if (sizediff >= max_size)
2027 if (trg_size < src_size / 32)
2030 /* Load data if not already done */
2033 trg->data = read_object_file(&trg_entry->idx.oid, &type, &sz);
2036 die(_("object %s cannot be read"),
2037 oid_to_hex(&trg_entry->idx.oid));
2039 die(_("object %s inconsistent object length (%lu vs %lu)"),
2040 oid_to_hex(&trg_entry->idx.oid), sz,
2046 src->data = read_object_file(&src_entry->idx.oid, &type, &sz);
2049 if (src_entry->preferred_base) {
2050 static int warned = 0;
2052 warning(_("object %s cannot be read"),
2053 oid_to_hex(&src_entry->idx.oid));
2055 * Those objects are not included in the
2056 * resulting pack. Be resilient and ignore
2057 * them if they can't be read, in case the
2058 * pack could be created nevertheless.
2062 die(_("object %s cannot be read"),
2063 oid_to_hex(&src_entry->idx.oid));
2066 die(_("object %s inconsistent object length (%lu vs %lu)"),
2067 oid_to_hex(&src_entry->idx.oid), sz,
2072 src->index = create_delta_index(src->data, src_size);
2074 static int warned = 0;
2076 warning(_("suboptimal pack - out of memory"));
2079 *mem_usage += sizeof_delta_index(src->index);
2082 delta_buf = create_delta(src->index, trg->data, trg_size, &delta_size, max_size);
2086 if (DELTA(trg_entry)) {
2087 /* Prefer only shallower same-sized deltas. */
2088 if (delta_size == DELTA_SIZE(trg_entry) &&
2089 src->depth + 1 >= trg->depth) {
2096 * Handle memory allocation outside of the cache
2097 * accounting lock. Compiler will optimize the strangeness
2098 * away when NO_PTHREADS is defined.
2100 free(trg_entry->delta_data);
2102 if (trg_entry->delta_data) {
2103 delta_cache_size -= DELTA_SIZE(trg_entry);
2104 trg_entry->delta_data = NULL;
2106 if (delta_cacheable(src_size, trg_size, delta_size)) {
2107 delta_cache_size += delta_size;
2109 trg_entry->delta_data = xrealloc(delta_buf, delta_size);
2115 SET_DELTA(trg_entry, src_entry);
2116 SET_DELTA_SIZE(trg_entry, delta_size);
2117 trg->depth = src->depth + 1;
2122 static unsigned int check_delta_limit(struct object_entry *me, unsigned int n)
2124 struct object_entry *child = DELTA_CHILD(me);
2127 unsigned int c = check_delta_limit(child, n + 1);
2130 child = DELTA_SIBLING(child);
2135 static unsigned long free_unpacked(struct unpacked *n)
2137 unsigned long freed_mem = sizeof_delta_index(n->index);
2138 free_delta_index(n->index);
2141 freed_mem += SIZE(n->entry);
2142 FREE_AND_NULL(n->data);
2149 static void find_deltas(struct object_entry **list, unsigned *list_size,
2150 int window, int depth, unsigned *processed)
2152 uint32_t i, idx = 0, count = 0;
2153 struct unpacked *array;
2154 unsigned long mem_usage = 0;
2156 array = xcalloc(window, sizeof(struct unpacked));
2159 struct object_entry *entry;
2160 struct unpacked *n = array + idx;
2161 int j, max_depth, best_base = -1;
2170 if (!entry->preferred_base) {
2172 display_progress(progress_state, *processed);
2176 mem_usage -= free_unpacked(n);
2179 while (window_memory_limit &&
2180 mem_usage > window_memory_limit &&
2182 uint32_t tail = (idx + window - count) % window;
2183 mem_usage -= free_unpacked(array + tail);
2187 /* We do not compute delta to *create* objects we are not
2190 if (entry->preferred_base)
2194 * If the current object is at pack edge, take the depth the
2195 * objects that depend on the current object into account
2196 * otherwise they would become too deep.
2199 if (DELTA_CHILD(entry)) {
2200 max_depth -= check_delta_limit(entry, 0);
2208 uint32_t other_idx = idx + j;
2210 if (other_idx >= window)
2211 other_idx -= window;
2212 m = array + other_idx;
2215 ret = try_delta(n, m, max_depth, &mem_usage);
2219 best_base = other_idx;
2223 * If we decided to cache the delta data, then it is best
2224 * to compress it right away. First because we have to do
2225 * it anyway, and doing it here while we're threaded will
2226 * save a lot of time in the non threaded write phase,
2227 * as well as allow for caching more deltas within
2228 * the same cache size limit.
2230 * But only if not writing to stdout, since in that case
2231 * the network is most likely throttling writes anyway,
2232 * and therefore it is best to go to the write phase ASAP
2233 * instead, as we can afford spending more time compressing
2234 * between writes at that moment.
2236 if (entry->delta_data && !pack_to_stdout) {
2239 size = do_compress(&entry->delta_data, DELTA_SIZE(entry));
2240 if (size < (1U << OE_Z_DELTA_BITS)) {
2241 entry->z_delta_size = size;
2243 delta_cache_size -= DELTA_SIZE(entry);
2244 delta_cache_size += entry->z_delta_size;
2247 FREE_AND_NULL(entry->delta_data);
2248 entry->z_delta_size = 0;
2252 /* if we made n a delta, and if n is already at max
2253 * depth, leaving it in the window is pointless. we
2254 * should evict it first.
2256 if (DELTA(entry) && max_depth <= n->depth)
2260 * Move the best delta base up in the window, after the
2261 * currently deltified object, to keep it longer. It will
2262 * be the first base object to be attempted next.
2265 struct unpacked swap = array[best_base];
2266 int dist = (window + idx - best_base) % window;
2267 int dst = best_base;
2269 int src = (dst + 1) % window;
2270 array[dst] = array[src];
2278 if (count + 1 < window)
2284 for (i = 0; i < window; ++i) {
2285 free_delta_index(array[i].index);
2286 free(array[i].data);
2293 static void try_to_free_from_threads(size_t size)
2296 release_pack_memory(size);
2300 static try_to_free_t old_try_to_free_routine;
2303 * The main object list is split into smaller lists, each is handed to
2306 * The main thread waits on the condition that (at least) one of the workers
2307 * has stopped working (which is indicated in the .working member of
2308 * struct thread_params).
2310 * When a work thread has completed its work, it sets .working to 0 and
2311 * signals the main thread and waits on the condition that .data_ready
2314 * The main thread steals half of the work from the worker that has
2315 * most work left to hand it to the idle worker.
2318 struct thread_params {
2320 struct object_entry **list;
2327 pthread_mutex_t mutex;
2328 pthread_cond_t cond;
2329 unsigned *processed;
2332 static pthread_cond_t progress_cond;
2335 * Mutex and conditional variable can't be statically-initialized on Windows.
2337 static void init_threaded_search(void)
2339 init_recursive_mutex(&read_mutex);
2340 pthread_mutex_init(&cache_mutex, NULL);
2341 pthread_mutex_init(&progress_mutex, NULL);
2342 pthread_cond_init(&progress_cond, NULL);
2343 pthread_mutex_init(&to_pack.lock, NULL);
2344 old_try_to_free_routine = set_try_to_free_routine(try_to_free_from_threads);
2347 static void cleanup_threaded_search(void)
2349 set_try_to_free_routine(old_try_to_free_routine);
2350 pthread_cond_destroy(&progress_cond);
2351 pthread_mutex_destroy(&read_mutex);
2352 pthread_mutex_destroy(&cache_mutex);
2353 pthread_mutex_destroy(&progress_mutex);
2356 static void *threaded_find_deltas(void *arg)
2358 struct thread_params *me = arg;
2361 while (me->remaining) {
2364 find_deltas(me->list, &me->remaining,
2365 me->window, me->depth, me->processed);
2369 pthread_cond_signal(&progress_cond);
2373 * We must not set ->data_ready before we wait on the
2374 * condition because the main thread may have set it to 1
2375 * before we get here. In order to be sure that new
2376 * work is available if we see 1 in ->data_ready, it
2377 * was initialized to 0 before this thread was spawned
2378 * and we reset it to 0 right away.
2380 pthread_mutex_lock(&me->mutex);
2381 while (!me->data_ready)
2382 pthread_cond_wait(&me->cond, &me->mutex);
2384 pthread_mutex_unlock(&me->mutex);
2389 /* leave ->working 1 so that this doesn't get more work assigned */
2393 static void ll_find_deltas(struct object_entry **list, unsigned list_size,
2394 int window, int depth, unsigned *processed)
2396 struct thread_params *p;
2397 int i, ret, active_threads = 0;
2399 init_threaded_search();
2401 if (delta_search_threads <= 1) {
2402 find_deltas(list, &list_size, window, depth, processed);
2403 cleanup_threaded_search();
2406 if (progress > pack_to_stdout)
2407 fprintf_ln(stderr, _("Delta compression using up to %d threads"),
2408 delta_search_threads);
2409 p = xcalloc(delta_search_threads, sizeof(*p));
2411 /* Partition the work amongst work threads. */
2412 for (i = 0; i < delta_search_threads; i++) {
2413 unsigned sub_size = list_size / (delta_search_threads - i);
2415 /* don't use too small segments or no deltas will be found */
2416 if (sub_size < 2*window && i+1 < delta_search_threads)
2419 p[i].window = window;
2421 p[i].processed = processed;
2423 p[i].data_ready = 0;
2425 /* try to split chunks on "path" boundaries */
2426 while (sub_size && sub_size < list_size &&
2427 list[sub_size]->hash &&
2428 list[sub_size]->hash == list[sub_size-1]->hash)
2432 p[i].list_size = sub_size;
2433 p[i].remaining = sub_size;
2436 list_size -= sub_size;
2439 /* Start work threads. */
2440 for (i = 0; i < delta_search_threads; i++) {
2441 if (!p[i].list_size)
2443 pthread_mutex_init(&p[i].mutex, NULL);
2444 pthread_cond_init(&p[i].cond, NULL);
2445 ret = pthread_create(&p[i].thread, NULL,
2446 threaded_find_deltas, &p[i]);
2448 die(_("unable to create thread: %s"), strerror(ret));
2453 * Now let's wait for work completion. Each time a thread is done
2454 * with its work, we steal half of the remaining work from the
2455 * thread with the largest number of unprocessed objects and give
2456 * it to that newly idle thread. This ensure good load balancing
2457 * until the remaining object list segments are simply too short
2458 * to be worth splitting anymore.
2460 while (active_threads) {
2461 struct thread_params *target = NULL;
2462 struct thread_params *victim = NULL;
2463 unsigned sub_size = 0;
2467 for (i = 0; !target && i < delta_search_threads; i++)
2472 pthread_cond_wait(&progress_cond, &progress_mutex);
2475 for (i = 0; i < delta_search_threads; i++)
2476 if (p[i].remaining > 2*window &&
2477 (!victim || victim->remaining < p[i].remaining))
2480 sub_size = victim->remaining / 2;
2481 list = victim->list + victim->list_size - sub_size;
2482 while (sub_size && list[0]->hash &&
2483 list[0]->hash == list[-1]->hash) {
2489 * It is possible for some "paths" to have
2490 * so many objects that no hash boundary
2491 * might be found. Let's just steal the
2492 * exact half in that case.
2494 sub_size = victim->remaining / 2;
2497 target->list = list;
2498 victim->list_size -= sub_size;
2499 victim->remaining -= sub_size;
2501 target->list_size = sub_size;
2502 target->remaining = sub_size;
2503 target->working = 1;
2506 pthread_mutex_lock(&target->mutex);
2507 target->data_ready = 1;
2508 pthread_cond_signal(&target->cond);
2509 pthread_mutex_unlock(&target->mutex);
2512 pthread_join(target->thread, NULL);
2513 pthread_cond_destroy(&target->cond);
2514 pthread_mutex_destroy(&target->mutex);
2518 cleanup_threaded_search();
2523 #define ll_find_deltas(l, s, w, d, p) find_deltas(l, &s, w, d, p)
2526 static void add_tag_chain(const struct object_id *oid)
2531 * We catch duplicates already in add_object_entry(), but we'd
2532 * prefer to do this extra check to avoid having to parse the
2533 * tag at all if we already know that it's being packed (e.g., if
2534 * it was included via bitmaps, we would not have parsed it
2537 if (packlist_find(&to_pack, oid->hash, NULL))
2540 tag = lookup_tag(the_repository, oid);
2542 if (!tag || parse_tag(tag) || !tag->tagged)
2543 die(_("unable to pack objects reachable from tag %s"),
2546 add_object_entry(&tag->object.oid, OBJ_TAG, NULL, 0);
2548 if (tag->tagged->type != OBJ_TAG)
2551 tag = (struct tag *)tag->tagged;
2555 static int add_ref_tag(const char *path, const struct object_id *oid, int flag, void *cb_data)
2557 struct object_id peeled;
2559 if (starts_with(path, "refs/tags/") && /* is a tag? */
2560 !peel_ref(path, &peeled) && /* peelable? */
2561 packlist_find(&to_pack, peeled.hash, NULL)) /* object packed? */
2566 static void prepare_pack(int window, int depth)
2568 struct object_entry **delta_list;
2569 uint32_t i, nr_deltas;
2572 get_object_details();
2575 * If we're locally repacking then we need to be doubly careful
2576 * from now on in order to make sure no stealth corruption gets
2577 * propagated to the new pack. Clients receiving streamed packs
2578 * should validate everything they get anyway so no need to incur
2579 * the additional cost here in that case.
2581 if (!pack_to_stdout)
2582 do_check_packed_object_crc = 1;
2584 if (!to_pack.nr_objects || !window || !depth)
2587 ALLOC_ARRAY(delta_list, to_pack.nr_objects);
2590 for (i = 0; i < to_pack.nr_objects; i++) {
2591 struct object_entry *entry = to_pack.objects + i;
2594 /* This happens if we decided to reuse existing
2595 * delta from a pack. "reuse_delta &&" is implied.
2599 if (!entry->type_valid ||
2600 oe_size_less_than(&to_pack, entry, 50))
2603 if (entry->no_try_delta)
2606 if (!entry->preferred_base) {
2608 if (oe_type(entry) < 0)
2609 die(_("unable to get type of object %s"),
2610 oid_to_hex(&entry->idx.oid));
2612 if (oe_type(entry) < 0) {
2614 * This object is not found, but we
2615 * don't have to include it anyway.
2621 delta_list[n++] = entry;
2624 if (nr_deltas && n > 1) {
2625 unsigned nr_done = 0;
2627 progress_state = start_progress(_("Compressing objects"),
2629 QSORT(delta_list, n, type_size_sort);
2630 ll_find_deltas(delta_list, n, window+1, depth, &nr_done);
2631 stop_progress(&progress_state);
2632 if (nr_done != nr_deltas)
2633 die(_("inconsistency with delta count"));
2638 static int git_pack_config(const char *k, const char *v, void *cb)
2640 if (!strcmp(k, "pack.window")) {
2641 window = git_config_int(k, v);
2644 if (!strcmp(k, "pack.windowmemory")) {
2645 window_memory_limit = git_config_ulong(k, v);
2648 if (!strcmp(k, "pack.depth")) {
2649 depth = git_config_int(k, v);
2652 if (!strcmp(k, "pack.deltacachesize")) {
2653 max_delta_cache_size = git_config_int(k, v);
2656 if (!strcmp(k, "pack.deltacachelimit")) {
2657 cache_max_small_delta_size = git_config_int(k, v);
2660 if (!strcmp(k, "pack.writebitmaphashcache")) {
2661 if (git_config_bool(k, v))
2662 write_bitmap_options |= BITMAP_OPT_HASH_CACHE;
2664 write_bitmap_options &= ~BITMAP_OPT_HASH_CACHE;
2666 if (!strcmp(k, "pack.usebitmaps")) {
2667 use_bitmap_index_default = git_config_bool(k, v);
2670 if (!strcmp(k, "pack.threads")) {
2671 delta_search_threads = git_config_int(k, v);
2672 if (delta_search_threads < 0)
2673 die(_("invalid number of threads specified (%d)"),
2674 delta_search_threads);
2676 if (delta_search_threads != 1) {
2677 warning(_("no threads support, ignoring %s"), k);
2678 delta_search_threads = 0;
2683 if (!strcmp(k, "pack.indexversion")) {
2684 pack_idx_opts.version = git_config_int(k, v);
2685 if (pack_idx_opts.version > 2)
2686 die(_("bad pack.indexversion=%"PRIu32),
2687 pack_idx_opts.version);
2690 return git_default_config(k, v, cb);
2693 static void read_object_list_from_stdin(void)
2695 char line[GIT_MAX_HEXSZ + 1 + PATH_MAX + 2];
2696 struct object_id oid;
2700 if (!fgets(line, sizeof(line), stdin)) {
2704 die("BUG: fgets returned NULL, not EOF, not error!");
2710 if (line[0] == '-') {
2711 if (get_oid_hex(line+1, &oid))
2712 die(_("expected edge object ID, got garbage:\n %s"),
2714 add_preferred_base(&oid);
2717 if (parse_oid_hex(line, &oid, &p))
2718 die(_("expected object ID, got garbage:\n %s"), line);
2720 add_preferred_base_object(p + 1);
2721 add_object_entry(&oid, OBJ_NONE, p + 1, 0);
2725 /* Remember to update object flag allocation in object.h */
2726 #define OBJECT_ADDED (1u<<20)
2728 static void show_commit(struct commit *commit, void *data)
2730 add_object_entry(&commit->object.oid, OBJ_COMMIT, NULL, 0);
2731 commit->object.flags |= OBJECT_ADDED;
2733 if (write_bitmap_index)
2734 index_commit_for_bitmap(commit);
2737 static void show_object(struct object *obj, const char *name, void *data)
2739 add_preferred_base_object(name);
2740 add_object_entry(&obj->oid, obj->type, name, 0);
2741 obj->flags |= OBJECT_ADDED;
2744 static void show_object__ma_allow_any(struct object *obj, const char *name, void *data)
2746 assert(arg_missing_action == MA_ALLOW_ANY);
2749 * Quietly ignore ALL missing objects. This avoids problems with
2750 * staging them now and getting an odd error later.
2752 if (!has_object_file(&obj->oid))
2755 show_object(obj, name, data);
2758 static void show_object__ma_allow_promisor(struct object *obj, const char *name, void *data)
2760 assert(arg_missing_action == MA_ALLOW_PROMISOR);
2763 * Quietly ignore EXPECTED missing objects. This avoids problems with
2764 * staging them now and getting an odd error later.
2766 if (!has_object_file(&obj->oid) && is_promisor_object(&obj->oid))
2769 show_object(obj, name, data);
2772 static int option_parse_missing_action(const struct option *opt,
2773 const char *arg, int unset)
2778 if (!strcmp(arg, "error")) {
2779 arg_missing_action = MA_ERROR;
2780 fn_show_object = show_object;
2784 if (!strcmp(arg, "allow-any")) {
2785 arg_missing_action = MA_ALLOW_ANY;
2786 fetch_if_missing = 0;
2787 fn_show_object = show_object__ma_allow_any;
2791 if (!strcmp(arg, "allow-promisor")) {
2792 arg_missing_action = MA_ALLOW_PROMISOR;
2793 fetch_if_missing = 0;
2794 fn_show_object = show_object__ma_allow_promisor;
2798 die(_("invalid value for --missing"));
2802 static void show_edge(struct commit *commit)
2804 add_preferred_base(&commit->object.oid);
2807 struct in_pack_object {
2809 struct object *object;
2815 struct in_pack_object *array;
2818 static void mark_in_pack_object(struct object *object, struct packed_git *p, struct in_pack *in_pack)
2820 in_pack->array[in_pack->nr].offset = find_pack_entry_one(object->oid.hash, p);
2821 in_pack->array[in_pack->nr].object = object;
2826 * Compare the objects in the offset order, in order to emulate the
2827 * "git rev-list --objects" output that produced the pack originally.
2829 static int ofscmp(const void *a_, const void *b_)
2831 struct in_pack_object *a = (struct in_pack_object *)a_;
2832 struct in_pack_object *b = (struct in_pack_object *)b_;
2834 if (a->offset < b->offset)
2836 else if (a->offset > b->offset)
2839 return oidcmp(&a->object->oid, &b->object->oid);
2842 static void add_objects_in_unpacked_packs(struct rev_info *revs)
2844 struct packed_git *p;
2845 struct in_pack in_pack;
2848 memset(&in_pack, 0, sizeof(in_pack));
2850 for (p = get_all_packs(the_repository); p; p = p->next) {
2851 struct object_id oid;
2854 if (!p->pack_local || p->pack_keep || p->pack_keep_in_core)
2856 if (open_pack_index(p))
2857 die(_("cannot open pack index"));
2859 ALLOC_GROW(in_pack.array,
2860 in_pack.nr + p->num_objects,
2863 for (i = 0; i < p->num_objects; i++) {
2864 nth_packed_object_oid(&oid, p, i);
2865 o = lookup_unknown_object(oid.hash);
2866 if (!(o->flags & OBJECT_ADDED))
2867 mark_in_pack_object(o, p, &in_pack);
2868 o->flags |= OBJECT_ADDED;
2873 QSORT(in_pack.array, in_pack.nr, ofscmp);
2874 for (i = 0; i < in_pack.nr; i++) {
2875 struct object *o = in_pack.array[i].object;
2876 add_object_entry(&o->oid, o->type, "", 0);
2879 free(in_pack.array);
2882 static int add_loose_object(const struct object_id *oid, const char *path,
2885 enum object_type type = oid_object_info(the_repository, oid, NULL);
2888 warning(_("loose object at %s could not be examined"), path);
2892 add_object_entry(oid, type, "", 0);
2897 * We actually don't even have to worry about reachability here.
2898 * add_object_entry will weed out duplicates, so we just add every
2899 * loose object we find.
2901 static void add_unreachable_loose_objects(void)
2903 for_each_loose_file_in_objdir(get_object_directory(),
2908 static int has_sha1_pack_kept_or_nonlocal(const struct object_id *oid)
2910 static struct packed_git *last_found = (void *)1;
2911 struct packed_git *p;
2913 p = (last_found != (void *)1) ? last_found :
2914 get_all_packs(the_repository);
2917 if ((!p->pack_local || p->pack_keep ||
2918 p->pack_keep_in_core) &&
2919 find_pack_entry_one(oid->hash, p)) {
2923 if (p == last_found)
2924 p = get_all_packs(the_repository);
2927 if (p == last_found)
2934 * Store a list of sha1s that are should not be discarded
2935 * because they are either written too recently, or are
2936 * reachable from another object that was.
2938 * This is filled by get_object_list.
2940 static struct oid_array recent_objects;
2942 static int loosened_object_can_be_discarded(const struct object_id *oid,
2945 if (!unpack_unreachable_expiration)
2947 if (mtime > unpack_unreachable_expiration)
2949 if (oid_array_lookup(&recent_objects, oid) >= 0)
2954 static void loosen_unused_packed_objects(struct rev_info *revs)
2956 struct packed_git *p;
2958 struct object_id oid;
2960 for (p = get_all_packs(the_repository); p; p = p->next) {
2961 if (!p->pack_local || p->pack_keep || p->pack_keep_in_core)
2964 if (open_pack_index(p))
2965 die(_("cannot open pack index"));
2967 for (i = 0; i < p->num_objects; i++) {
2968 nth_packed_object_oid(&oid, p, i);
2969 if (!packlist_find(&to_pack, oid.hash, NULL) &&
2970 !has_sha1_pack_kept_or_nonlocal(&oid) &&
2971 !loosened_object_can_be_discarded(&oid, p->mtime))
2972 if (force_object_loose(&oid, p->mtime))
2973 die(_("unable to force loose object"));
2979 * This tracks any options which pack-reuse code expects to be on, or which a
2980 * reader of the pack might not understand, and which would therefore prevent
2981 * blind reuse of what we have on disk.
2983 static int pack_options_allow_reuse(void)
2985 return pack_to_stdout &&
2987 !ignore_packed_keep_on_disk &&
2988 !ignore_packed_keep_in_core &&
2989 (!local || !have_non_local_packs) &&
2993 static int get_object_list_from_bitmap(struct rev_info *revs)
2995 if (!(bitmap_git = prepare_bitmap_walk(revs)))
2998 if (pack_options_allow_reuse() &&
2999 !reuse_partial_packfile_from_bitmap(
3002 &reuse_packfile_objects,
3003 &reuse_packfile_offset)) {
3004 assert(reuse_packfile_objects);
3005 nr_result += reuse_packfile_objects;
3006 display_progress(progress_state, nr_result);
3009 traverse_bitmap_commit_list(bitmap_git, &add_object_entry_from_bitmap);
3013 static void record_recent_object(struct object *obj,
3017 oid_array_append(&recent_objects, &obj->oid);
3020 static void record_recent_commit(struct commit *commit, void *data)
3022 oid_array_append(&recent_objects, &commit->object.oid);
3025 static void get_object_list(int ac, const char **av)
3027 struct rev_info revs;
3031 init_revisions(&revs, NULL);
3032 save_commit_buffer = 0;
3033 setup_revisions(ac, av, &revs, NULL);
3035 /* make sure shallows are read */
3036 is_repository_shallow(the_repository);
3038 while (fgets(line, sizeof(line), stdin) != NULL) {
3039 int len = strlen(line);
3040 if (len && line[len - 1] == '\n')
3045 if (!strcmp(line, "--not")) {
3046 flags ^= UNINTERESTING;
3047 write_bitmap_index = 0;
3050 if (starts_with(line, "--shallow ")) {
3051 struct object_id oid;
3052 if (get_oid_hex(line + 10, &oid))
3053 die("not an SHA-1 '%s'", line + 10);
3054 register_shallow(the_repository, &oid);
3055 use_bitmap_index = 0;
3058 die(_("not a rev '%s'"), line);
3060 if (handle_revision_arg(line, &revs, flags, REVARG_CANNOT_BE_FILENAME))
3061 die(_("bad revision '%s'"), line);
3064 if (use_bitmap_index && !get_object_list_from_bitmap(&revs))
3067 if (prepare_revision_walk(&revs))
3068 die(_("revision walk setup failed"));
3069 mark_edges_uninteresting(&revs, show_edge);
3071 if (!fn_show_object)
3072 fn_show_object = show_object;
3073 traverse_commit_list_filtered(&filter_options, &revs,
3074 show_commit, fn_show_object, NULL,
3077 if (unpack_unreachable_expiration) {
3078 revs.ignore_missing_links = 1;
3079 if (add_unseen_recent_objects_to_traversal(&revs,
3080 unpack_unreachable_expiration))
3081 die(_("unable to add recent objects"));
3082 if (prepare_revision_walk(&revs))
3083 die(_("revision walk setup failed"));
3084 traverse_commit_list(&revs, record_recent_commit,
3085 record_recent_object, NULL);
3088 if (keep_unreachable)
3089 add_objects_in_unpacked_packs(&revs);
3090 if (pack_loose_unreachable)
3091 add_unreachable_loose_objects();
3092 if (unpack_unreachable)
3093 loosen_unused_packed_objects(&revs);
3095 oid_array_clear(&recent_objects);
3098 static void add_extra_kept_packs(const struct string_list *names)
3100 struct packed_git *p;
3105 for (p = get_all_packs(the_repository); p; p = p->next) {
3106 const char *name = basename(p->pack_name);
3112 for (i = 0; i < names->nr; i++)
3113 if (!fspathcmp(name, names->items[i].string))
3116 if (i < names->nr) {
3117 p->pack_keep_in_core = 1;
3118 ignore_packed_keep_in_core = 1;
3124 static int option_parse_index_version(const struct option *opt,
3125 const char *arg, int unset)
3128 const char *val = arg;
3129 pack_idx_opts.version = strtoul(val, &c, 10);
3130 if (pack_idx_opts.version > 2)
3131 die(_("unsupported index version %s"), val);
3132 if (*c == ',' && c[1])
3133 pack_idx_opts.off32_limit = strtoul(c+1, &c, 0);
3134 if (*c || pack_idx_opts.off32_limit & 0x80000000)
3135 die(_("bad index version '%s'"), val);
3139 static int option_parse_unpack_unreachable(const struct option *opt,
3140 const char *arg, int unset)
3143 unpack_unreachable = 0;
3144 unpack_unreachable_expiration = 0;
3147 unpack_unreachable = 1;
3149 unpack_unreachable_expiration = approxidate(arg);
3154 int cmd_pack_objects(int argc, const char **argv, const char *prefix)
3156 int use_internal_rev_list = 0;
3158 int all_progress_implied = 0;
3159 struct argv_array rp = ARGV_ARRAY_INIT;
3160 int rev_list_unpacked = 0, rev_list_all = 0, rev_list_reflog = 0;
3161 int rev_list_index = 0;
3162 struct string_list keep_pack_list = STRING_LIST_INIT_NODUP;
3163 struct option pack_objects_options[] = {
3164 OPT_SET_INT('q', "quiet", &progress,
3165 N_("do not show progress meter"), 0),
3166 OPT_SET_INT(0, "progress", &progress,
3167 N_("show progress meter"), 1),
3168 OPT_SET_INT(0, "all-progress", &progress,
3169 N_("show progress meter during object writing phase"), 2),
3170 OPT_BOOL(0, "all-progress-implied",
3171 &all_progress_implied,
3172 N_("similar to --all-progress when progress meter is shown")),
3173 { OPTION_CALLBACK, 0, "index-version", NULL, N_("<version>[,<offset>]"),
3174 N_("write the pack index file in the specified idx format version"),
3175 0, option_parse_index_version },
3176 OPT_MAGNITUDE(0, "max-pack-size", &pack_size_limit,
3177 N_("maximum size of each output pack file")),
3178 OPT_BOOL(0, "local", &local,
3179 N_("ignore borrowed objects from alternate object store")),
3180 OPT_BOOL(0, "incremental", &incremental,
3181 N_("ignore packed objects")),
3182 OPT_INTEGER(0, "window", &window,
3183 N_("limit pack window by objects")),
3184 OPT_MAGNITUDE(0, "window-memory", &window_memory_limit,
3185 N_("limit pack window by memory in addition to object limit")),
3186 OPT_INTEGER(0, "depth", &depth,
3187 N_("maximum length of delta chain allowed in the resulting pack")),
3188 OPT_BOOL(0, "reuse-delta", &reuse_delta,
3189 N_("reuse existing deltas")),
3190 OPT_BOOL(0, "reuse-object", &reuse_object,
3191 N_("reuse existing objects")),
3192 OPT_BOOL(0, "delta-base-offset", &allow_ofs_delta,
3193 N_("use OFS_DELTA objects")),
3194 OPT_INTEGER(0, "threads", &delta_search_threads,
3195 N_("use threads when searching for best delta matches")),
3196 OPT_BOOL(0, "non-empty", &non_empty,
3197 N_("do not create an empty pack output")),
3198 OPT_BOOL(0, "revs", &use_internal_rev_list,
3199 N_("read revision arguments from standard input")),
3200 OPT_SET_INT_F(0, "unpacked", &rev_list_unpacked,
3201 N_("limit the objects to those that are not yet packed"),
3202 1, PARSE_OPT_NONEG),
3203 OPT_SET_INT_F(0, "all", &rev_list_all,
3204 N_("include objects reachable from any reference"),
3205 1, PARSE_OPT_NONEG),
3206 OPT_SET_INT_F(0, "reflog", &rev_list_reflog,
3207 N_("include objects referred by reflog entries"),
3208 1, PARSE_OPT_NONEG),
3209 OPT_SET_INT_F(0, "indexed-objects", &rev_list_index,
3210 N_("include objects referred to by the index"),
3211 1, PARSE_OPT_NONEG),
3212 OPT_BOOL(0, "stdout", &pack_to_stdout,
3213 N_("output pack to stdout")),
3214 OPT_BOOL(0, "include-tag", &include_tag,
3215 N_("include tag objects that refer to objects to be packed")),
3216 OPT_BOOL(0, "keep-unreachable", &keep_unreachable,
3217 N_("keep unreachable objects")),
3218 OPT_BOOL(0, "pack-loose-unreachable", &pack_loose_unreachable,
3219 N_("pack loose unreachable objects")),
3220 { OPTION_CALLBACK, 0, "unpack-unreachable", NULL, N_("time"),
3221 N_("unpack unreachable objects newer than <time>"),
3222 PARSE_OPT_OPTARG, option_parse_unpack_unreachable },
3223 OPT_BOOL(0, "thin", &thin,
3224 N_("create thin packs")),
3225 OPT_BOOL(0, "shallow", &shallow,
3226 N_("create packs suitable for shallow fetches")),
3227 OPT_BOOL(0, "honor-pack-keep", &ignore_packed_keep_on_disk,
3228 N_("ignore packs that have companion .keep file")),
3229 OPT_STRING_LIST(0, "keep-pack", &keep_pack_list, N_("name"),
3230 N_("ignore this pack")),
3231 OPT_INTEGER(0, "compression", &pack_compression_level,
3232 N_("pack compression level")),
3233 OPT_SET_INT(0, "keep-true-parents", &grafts_replace_parents,
3234 N_("do not hide commits by grafts"), 0),
3235 OPT_BOOL(0, "use-bitmap-index", &use_bitmap_index,
3236 N_("use a bitmap index if available to speed up counting objects")),
3237 OPT_BOOL(0, "write-bitmap-index", &write_bitmap_index,
3238 N_("write a bitmap index together with the pack index")),
3239 OPT_PARSE_LIST_OBJECTS_FILTER(&filter_options),
3240 { OPTION_CALLBACK, 0, "missing", NULL, N_("action"),
3241 N_("handling for missing objects"), PARSE_OPT_NONEG,
3242 option_parse_missing_action },
3243 OPT_BOOL(0, "exclude-promisor-objects", &exclude_promisor_objects,
3244 N_("do not pack objects in promisor packfiles")),
3248 if (DFS_NUM_STATES > (1 << OE_DFS_STATE_BITS))
3249 BUG("too many dfs states, increase OE_DFS_STATE_BITS");
3251 read_replace_refs = 0;
3253 reset_pack_idx_option(&pack_idx_opts);
3254 git_config(git_pack_config, NULL);
3256 progress = isatty(2);
3257 argc = parse_options(argc, argv, prefix, pack_objects_options,
3261 base_name = argv[0];
3264 if (pack_to_stdout != !base_name || argc)
3265 usage_with_options(pack_usage, pack_objects_options);
3267 if (depth >= (1 << OE_DEPTH_BITS)) {
3268 warning(_("delta chain depth %d is too deep, forcing %d"),
3269 depth, (1 << OE_DEPTH_BITS) - 1);
3270 depth = (1 << OE_DEPTH_BITS) - 1;
3272 if (cache_max_small_delta_size >= (1U << OE_Z_DELTA_BITS)) {
3273 warning(_("pack.deltaCacheLimit is too high, forcing %d"),
3274 (1U << OE_Z_DELTA_BITS) - 1);
3275 cache_max_small_delta_size = (1U << OE_Z_DELTA_BITS) - 1;
3278 argv_array_push(&rp, "pack-objects");
3280 use_internal_rev_list = 1;
3281 argv_array_push(&rp, shallow
3282 ? "--objects-edge-aggressive"
3283 : "--objects-edge");
3285 argv_array_push(&rp, "--objects");
3288 use_internal_rev_list = 1;
3289 argv_array_push(&rp, "--all");
3291 if (rev_list_reflog) {
3292 use_internal_rev_list = 1;
3293 argv_array_push(&rp, "--reflog");
3295 if (rev_list_index) {
3296 use_internal_rev_list = 1;
3297 argv_array_push(&rp, "--indexed-objects");
3299 if (rev_list_unpacked) {
3300 use_internal_rev_list = 1;
3301 argv_array_push(&rp, "--unpacked");
3304 if (exclude_promisor_objects) {
3305 use_internal_rev_list = 1;
3306 fetch_if_missing = 0;
3307 argv_array_push(&rp, "--exclude-promisor-objects");
3309 if (unpack_unreachable || keep_unreachable || pack_loose_unreachable)
3310 use_internal_rev_list = 1;
3314 if (pack_compression_level == -1)
3315 pack_compression_level = Z_DEFAULT_COMPRESSION;
3316 else if (pack_compression_level < 0 || pack_compression_level > Z_BEST_COMPRESSION)
3317 die(_("bad pack compression level %d"), pack_compression_level);
3319 if (!delta_search_threads) /* --threads=0 means autodetect */
3320 delta_search_threads = online_cpus();
3323 if (delta_search_threads != 1)
3324 warning(_("no threads support, ignoring --threads"));
3326 if (!pack_to_stdout && !pack_size_limit)
3327 pack_size_limit = pack_size_limit_cfg;
3328 if (pack_to_stdout && pack_size_limit)
3329 die(_("--max-pack-size cannot be used to build a pack for transfer"));
3330 if (pack_size_limit && pack_size_limit < 1024*1024) {
3331 warning(_("minimum pack size limit is 1 MiB"));
3332 pack_size_limit = 1024*1024;
3335 if (!pack_to_stdout && thin)
3336 die(_("--thin cannot be used to build an indexable pack"));
3338 if (keep_unreachable && unpack_unreachable)
3339 die(_("--keep-unreachable and --unpack-unreachable are incompatible"));
3340 if (!rev_list_all || !rev_list_reflog || !rev_list_index)
3341 unpack_unreachable_expiration = 0;
3343 if (filter_options.choice) {
3344 if (!pack_to_stdout)
3345 die(_("cannot use --filter without --stdout"));
3346 use_bitmap_index = 0;
3350 * "soft" reasons not to use bitmaps - for on-disk repack by default we want
3352 * - to produce good pack (with bitmap index not-yet-packed objects are
3353 * packed in suboptimal order).
3355 * - to use more robust pack-generation codepath (avoiding possible
3356 * bugs in bitmap code and possible bitmap index corruption).
3358 if (!pack_to_stdout)
3359 use_bitmap_index_default = 0;
3361 if (use_bitmap_index < 0)
3362 use_bitmap_index = use_bitmap_index_default;
3364 /* "hard" reasons not to use bitmaps; these just won't work at all */
3365 if (!use_internal_rev_list || (!pack_to_stdout && write_bitmap_index) || is_repository_shallow(the_repository))
3366 use_bitmap_index = 0;
3368 if (pack_to_stdout || !rev_list_all)
3369 write_bitmap_index = 0;
3371 if (progress && all_progress_implied)
3374 add_extra_kept_packs(&keep_pack_list);
3375 if (ignore_packed_keep_on_disk) {
3376 struct packed_git *p;
3377 for (p = get_all_packs(the_repository); p; p = p->next)
3378 if (p->pack_local && p->pack_keep)
3380 if (!p) /* no keep-able packs found */
3381 ignore_packed_keep_on_disk = 0;
3385 * unlike ignore_packed_keep_on_disk above, we do not
3386 * want to unset "local" based on looking at packs, as
3387 * it also covers non-local objects
3389 struct packed_git *p;
3390 for (p = get_all_packs(the_repository); p; p = p->next) {
3391 if (!p->pack_local) {
3392 have_non_local_packs = 1;
3398 prepare_packing_data(&to_pack);
3401 progress_state = start_progress(_("Enumerating objects"), 0);
3402 if (!use_internal_rev_list)
3403 read_object_list_from_stdin();
3405 get_object_list(rp.argc, rp.argv);
3406 argv_array_clear(&rp);
3408 cleanup_preferred_base();
3409 if (include_tag && nr_result)
3410 for_each_ref(add_ref_tag, NULL);
3411 stop_progress(&progress_state);
3413 if (non_empty && !nr_result)
3416 prepare_pack(window, depth);
3420 _("Total %"PRIu32" (delta %"PRIu32"),"
3421 " reused %"PRIu32" (delta %"PRIu32")"),
3422 written, written_delta, reused, reused_delta);