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_SIZE(obj, val) oe_set_delta_size(&to_pack, obj, val)
45 #define SET_DELTA_CHILD(obj, val) oe_set_delta_child(&to_pack, obj, val)
46 #define SET_DELTA_SIBLING(obj, val) oe_set_delta_sibling(&to_pack, obj, val)
48 static const char *pack_usage[] = {
49 N_("git pack-objects --stdout [<options>...] [< <ref-list> | < <object-list>]"),
50 N_("git pack-objects [<options>...] <base-name> [< <ref-list> | < <object-list>]"),
55 * Objects we are going to pack are collected in the `to_pack` structure.
56 * It contains an array (dynamically expanded) of the object data, and a map
57 * that can resolve SHA1s to their position in the array.
59 static struct packing_data to_pack;
61 static struct pack_idx_entry **written_list;
62 static uint32_t nr_result, nr_written, nr_seen;
65 static int reuse_delta = 1, reuse_object = 1;
66 static int keep_unreachable, unpack_unreachable, include_tag;
67 static timestamp_t unpack_unreachable_expiration;
68 static int pack_loose_unreachable;
70 static int have_non_local_packs;
71 static int incremental;
72 static int ignore_packed_keep_on_disk;
73 static int ignore_packed_keep_in_core;
74 static int allow_ofs_delta;
75 static struct pack_idx_option pack_idx_opts;
76 static const char *base_name;
77 static int progress = 1;
78 static int window = 10;
79 static unsigned long pack_size_limit;
80 static int depth = 50;
81 static int delta_search_threads;
82 static int pack_to_stdout;
83 static int num_preferred_base;
84 static struct progress *progress_state;
86 static struct packed_git *reuse_packfile;
87 static uint32_t reuse_packfile_objects;
88 static off_t reuse_packfile_offset;
90 static int use_bitmap_index_default = 1;
91 static int use_bitmap_index = -1;
92 static int write_bitmap_index;
93 static uint16_t write_bitmap_options;
95 static int exclude_promisor_objects;
97 static unsigned long delta_cache_size = 0;
98 static unsigned long max_delta_cache_size = DEFAULT_DELTA_CACHE_SIZE;
99 static unsigned long cache_max_small_delta_size = 1000;
101 static unsigned long window_memory_limit = 0;
103 static struct list_objects_filter_options filter_options;
105 enum missing_action {
106 MA_ERROR = 0, /* fail if any missing objects are encountered */
107 MA_ALLOW_ANY, /* silently allow ALL missing objects */
108 MA_ALLOW_PROMISOR, /* silently allow all missing PROMISOR objects */
110 static enum missing_action arg_missing_action;
111 static show_object_fn fn_show_object;
116 static uint32_t written, written_delta;
117 static uint32_t reused, reused_delta;
122 static struct commit **indexed_commits;
123 static unsigned int indexed_commits_nr;
124 static unsigned int indexed_commits_alloc;
126 static void index_commit_for_bitmap(struct commit *commit)
128 if (indexed_commits_nr >= indexed_commits_alloc) {
129 indexed_commits_alloc = (indexed_commits_alloc + 32) * 2;
130 REALLOC_ARRAY(indexed_commits, indexed_commits_alloc);
133 indexed_commits[indexed_commits_nr++] = commit;
136 static void *get_delta(struct object_entry *entry)
138 unsigned long size, base_size, delta_size;
139 void *buf, *base_buf, *delta_buf;
140 enum object_type type;
142 buf = read_object_file(&entry->idx.oid, &type, &size);
144 die(_("unable to read %s"), oid_to_hex(&entry->idx.oid));
145 base_buf = read_object_file(&DELTA(entry)->idx.oid, &type,
148 die("unable to read %s",
149 oid_to_hex(&DELTA(entry)->idx.oid));
150 delta_buf = diff_delta(base_buf, base_size,
151 buf, size, &delta_size, 0);
153 * We succesfully computed this delta once but dropped it for
154 * memory reasons. Something is very wrong if this time we
155 * recompute and create a different delta.
157 if (!delta_buf || delta_size != DELTA_SIZE(entry))
158 BUG("delta size changed");
164 static unsigned long do_compress(void **pptr, unsigned long size)
168 unsigned long maxsize;
170 git_deflate_init(&stream, pack_compression_level);
171 maxsize = git_deflate_bound(&stream, size);
174 out = xmalloc(maxsize);
178 stream.avail_in = size;
179 stream.next_out = out;
180 stream.avail_out = maxsize;
181 while (git_deflate(&stream, Z_FINISH) == Z_OK)
183 git_deflate_end(&stream);
186 return stream.total_out;
189 static unsigned long write_large_blob_data(struct git_istream *st, struct hashfile *f,
190 const struct object_id *oid)
193 unsigned char ibuf[1024 * 16];
194 unsigned char obuf[1024 * 16];
195 unsigned long olen = 0;
197 git_deflate_init(&stream, pack_compression_level);
202 readlen = read_istream(st, ibuf, sizeof(ibuf));
204 die(_("unable to read %s"), oid_to_hex(oid));
206 stream.next_in = ibuf;
207 stream.avail_in = readlen;
208 while ((stream.avail_in || readlen == 0) &&
209 (zret == Z_OK || zret == Z_BUF_ERROR)) {
210 stream.next_out = obuf;
211 stream.avail_out = sizeof(obuf);
212 zret = git_deflate(&stream, readlen ? 0 : Z_FINISH);
213 hashwrite(f, obuf, stream.next_out - obuf);
214 olen += stream.next_out - obuf;
217 die(_("deflate error (%d)"), zret);
219 if (zret != Z_STREAM_END)
220 die(_("deflate error (%d)"), zret);
224 git_deflate_end(&stream);
229 * we are going to reuse the existing object data as is. make
230 * sure it is not corrupt.
232 static int check_pack_inflate(struct packed_git *p,
233 struct pack_window **w_curs,
236 unsigned long expect)
239 unsigned char fakebuf[4096], *in;
242 memset(&stream, 0, sizeof(stream));
243 git_inflate_init(&stream);
245 in = use_pack(p, w_curs, offset, &stream.avail_in);
247 stream.next_out = fakebuf;
248 stream.avail_out = sizeof(fakebuf);
249 st = git_inflate(&stream, Z_FINISH);
250 offset += stream.next_in - in;
251 } while (st == Z_OK || st == Z_BUF_ERROR);
252 git_inflate_end(&stream);
253 return (st == Z_STREAM_END &&
254 stream.total_out == expect &&
255 stream.total_in == len) ? 0 : -1;
258 static void copy_pack_data(struct hashfile *f,
259 struct packed_git *p,
260 struct pack_window **w_curs,
268 in = use_pack(p, w_curs, offset, &avail);
270 avail = (unsigned long)len;
271 hashwrite(f, in, avail);
277 /* Return 0 if we will bust the pack-size limit */
278 static unsigned long write_no_reuse_object(struct hashfile *f, struct object_entry *entry,
279 unsigned long limit, int usable_delta)
281 unsigned long size, datalen;
282 unsigned char header[MAX_PACK_OBJECT_HEADER],
283 dheader[MAX_PACK_OBJECT_HEADER];
285 enum object_type type;
287 struct git_istream *st = NULL;
288 const unsigned hashsz = the_hash_algo->rawsz;
291 if (oe_type(entry) == OBJ_BLOB &&
292 oe_size_greater_than(&to_pack, entry, big_file_threshold) &&
293 (st = open_istream(&entry->idx.oid, &type, &size, NULL)) != NULL)
296 buf = read_object_file(&entry->idx.oid, &type, &size);
298 die(_("unable to read %s"),
299 oid_to_hex(&entry->idx.oid));
302 * make sure no cached delta data remains from a
303 * previous attempt before a pack split occurred.
305 FREE_AND_NULL(entry->delta_data);
306 entry->z_delta_size = 0;
307 } else if (entry->delta_data) {
308 size = DELTA_SIZE(entry);
309 buf = entry->delta_data;
310 entry->delta_data = NULL;
311 type = (allow_ofs_delta && DELTA(entry)->idx.offset) ?
312 OBJ_OFS_DELTA : OBJ_REF_DELTA;
314 buf = get_delta(entry);
315 size = DELTA_SIZE(entry);
316 type = (allow_ofs_delta && DELTA(entry)->idx.offset) ?
317 OBJ_OFS_DELTA : OBJ_REF_DELTA;
320 if (st) /* large blob case, just assume we don't compress well */
322 else if (entry->z_delta_size)
323 datalen = entry->z_delta_size;
325 datalen = do_compress(&buf, size);
328 * The object header is a byte of 'type' followed by zero or
329 * more bytes of length.
331 hdrlen = encode_in_pack_object_header(header, sizeof(header),
334 if (type == OBJ_OFS_DELTA) {
336 * Deltas with relative base contain an additional
337 * encoding of the relative offset for the delta
338 * base from this object's position in the pack.
340 off_t ofs = entry->idx.offset - DELTA(entry)->idx.offset;
341 unsigned pos = sizeof(dheader) - 1;
342 dheader[pos] = ofs & 127;
344 dheader[--pos] = 128 | (--ofs & 127);
345 if (limit && hdrlen + sizeof(dheader) - pos + datalen + hashsz >= limit) {
351 hashwrite(f, header, hdrlen);
352 hashwrite(f, dheader + pos, sizeof(dheader) - pos);
353 hdrlen += sizeof(dheader) - pos;
354 } else if (type == OBJ_REF_DELTA) {
356 * Deltas with a base reference contain
357 * additional bytes for the base object ID.
359 if (limit && hdrlen + hashsz + datalen + hashsz >= limit) {
365 hashwrite(f, header, hdrlen);
366 hashwrite(f, DELTA(entry)->idx.oid.hash, hashsz);
369 if (limit && hdrlen + datalen + hashsz >= limit) {
375 hashwrite(f, header, hdrlen);
378 datalen = write_large_blob_data(st, f, &entry->idx.oid);
381 hashwrite(f, buf, datalen);
385 return hdrlen + datalen;
388 /* Return 0 if we will bust the pack-size limit */
389 static off_t write_reuse_object(struct hashfile *f, struct object_entry *entry,
390 unsigned long limit, int usable_delta)
392 struct packed_git *p = IN_PACK(entry);
393 struct pack_window *w_curs = NULL;
394 struct revindex_entry *revidx;
396 enum object_type type = oe_type(entry);
398 unsigned char header[MAX_PACK_OBJECT_HEADER],
399 dheader[MAX_PACK_OBJECT_HEADER];
401 const unsigned hashsz = the_hash_algo->rawsz;
402 unsigned long entry_size = SIZE(entry);
405 type = (allow_ofs_delta && DELTA(entry)->idx.offset) ?
406 OBJ_OFS_DELTA : OBJ_REF_DELTA;
407 hdrlen = encode_in_pack_object_header(header, sizeof(header),
410 offset = entry->in_pack_offset;
411 revidx = find_pack_revindex(p, offset);
412 datalen = revidx[1].offset - offset;
413 if (!pack_to_stdout && p->index_version > 1 &&
414 check_pack_crc(p, &w_curs, offset, datalen, revidx->nr)) {
415 error(_("bad packed object CRC for %s"),
416 oid_to_hex(&entry->idx.oid));
418 return write_no_reuse_object(f, entry, limit, usable_delta);
421 offset += entry->in_pack_header_size;
422 datalen -= entry->in_pack_header_size;
424 if (!pack_to_stdout && p->index_version == 1 &&
425 check_pack_inflate(p, &w_curs, offset, datalen, entry_size)) {
426 error(_("corrupt packed object for %s"),
427 oid_to_hex(&entry->idx.oid));
429 return write_no_reuse_object(f, entry, limit, usable_delta);
432 if (type == OBJ_OFS_DELTA) {
433 off_t ofs = entry->idx.offset - DELTA(entry)->idx.offset;
434 unsigned pos = sizeof(dheader) - 1;
435 dheader[pos] = ofs & 127;
437 dheader[--pos] = 128 | (--ofs & 127);
438 if (limit && hdrlen + sizeof(dheader) - pos + datalen + hashsz >= limit) {
442 hashwrite(f, header, hdrlen);
443 hashwrite(f, dheader + pos, sizeof(dheader) - pos);
444 hdrlen += sizeof(dheader) - pos;
446 } else if (type == OBJ_REF_DELTA) {
447 if (limit && hdrlen + hashsz + datalen + hashsz >= limit) {
451 hashwrite(f, header, hdrlen);
452 hashwrite(f, DELTA(entry)->idx.oid.hash, hashsz);
456 if (limit && hdrlen + datalen + hashsz >= limit) {
460 hashwrite(f, header, hdrlen);
462 copy_pack_data(f, p, &w_curs, offset, datalen);
465 return hdrlen + datalen;
468 /* Return 0 if we will bust the pack-size limit */
469 static off_t write_object(struct hashfile *f,
470 struct object_entry *entry,
475 int usable_delta, to_reuse;
480 /* apply size limit if limited packsize and not first object */
481 if (!pack_size_limit || !nr_written)
483 else if (pack_size_limit <= write_offset)
485 * the earlier object did not fit the limit; avoid
486 * mistaking this with unlimited (i.e. limit = 0).
490 limit = pack_size_limit - write_offset;
493 usable_delta = 0; /* no delta */
494 else if (!pack_size_limit)
495 usable_delta = 1; /* unlimited packfile */
496 else if (DELTA(entry)->idx.offset == (off_t)-1)
497 usable_delta = 0; /* base was written to another pack */
498 else if (DELTA(entry)->idx.offset)
499 usable_delta = 1; /* base already exists in this pack */
501 usable_delta = 0; /* base could end up in another pack */
504 to_reuse = 0; /* explicit */
505 else if (!IN_PACK(entry))
506 to_reuse = 0; /* can't reuse what we don't have */
507 else if (oe_type(entry) == OBJ_REF_DELTA ||
508 oe_type(entry) == OBJ_OFS_DELTA)
509 /* check_object() decided it for us ... */
510 to_reuse = usable_delta;
511 /* ... but pack split may override that */
512 else if (oe_type(entry) != entry->in_pack_type)
513 to_reuse = 0; /* pack has delta which is unusable */
514 else if (DELTA(entry))
515 to_reuse = 0; /* we want to pack afresh */
517 to_reuse = 1; /* we have it in-pack undeltified,
518 * and we do not need to deltify it.
522 len = write_no_reuse_object(f, entry, limit, usable_delta);
524 len = write_reuse_object(f, entry, limit, usable_delta);
532 entry->idx.crc32 = crc32_end(f);
536 enum write_one_status {
537 WRITE_ONE_SKIP = -1, /* already written */
538 WRITE_ONE_BREAK = 0, /* writing this will bust the limit; not written */
539 WRITE_ONE_WRITTEN = 1, /* normal */
540 WRITE_ONE_RECURSIVE = 2 /* already scheduled to be written */
543 static enum write_one_status write_one(struct hashfile *f,
544 struct object_entry *e,
551 * we set offset to 1 (which is an impossible value) to mark
552 * the fact that this object is involved in "write its base
553 * first before writing a deltified object" recursion.
555 recursing = (e->idx.offset == 1);
557 warning(_("recursive delta detected for object %s"),
558 oid_to_hex(&e->idx.oid));
559 return WRITE_ONE_RECURSIVE;
560 } else if (e->idx.offset || e->preferred_base) {
561 /* offset is non zero if object is written already. */
562 return WRITE_ONE_SKIP;
565 /* if we are deltified, write out base object first. */
567 e->idx.offset = 1; /* now recurse */
568 switch (write_one(f, DELTA(e), offset)) {
569 case WRITE_ONE_RECURSIVE:
570 /* we cannot depend on this one */
575 case WRITE_ONE_BREAK:
576 e->idx.offset = recursing;
577 return WRITE_ONE_BREAK;
581 e->idx.offset = *offset;
582 size = write_object(f, e, *offset);
584 e->idx.offset = recursing;
585 return WRITE_ONE_BREAK;
587 written_list[nr_written++] = &e->idx;
589 /* make sure off_t is sufficiently large not to wrap */
590 if (signed_add_overflows(*offset, size))
591 die(_("pack too large for current definition of off_t"));
593 return WRITE_ONE_WRITTEN;
596 static int mark_tagged(const char *path, const struct object_id *oid, int flag,
599 struct object_id peeled;
600 struct object_entry *entry = packlist_find(&to_pack, oid->hash, NULL);
604 if (!peel_ref(path, &peeled)) {
605 entry = packlist_find(&to_pack, peeled.hash, NULL);
612 static inline void add_to_write_order(struct object_entry **wo,
614 struct object_entry *e)
622 static void add_descendants_to_write_order(struct object_entry **wo,
624 struct object_entry *e)
626 int add_to_order = 1;
629 struct object_entry *s;
630 /* add this node... */
631 add_to_write_order(wo, endp, e);
632 /* all its siblings... */
633 for (s = DELTA_SIBLING(e); s; s = DELTA_SIBLING(s)) {
634 add_to_write_order(wo, endp, s);
637 /* drop down a level to add left subtree nodes if possible */
638 if (DELTA_CHILD(e)) {
643 /* our sibling might have some children, it is next */
644 if (DELTA_SIBLING(e)) {
645 e = DELTA_SIBLING(e);
648 /* go back to our parent node */
650 while (e && !DELTA_SIBLING(e)) {
651 /* we're on the right side of a subtree, keep
652 * going up until we can go right again */
656 /* done- we hit our original root node */
659 /* pass it off to sibling at this level */
660 e = DELTA_SIBLING(e);
665 static void add_family_to_write_order(struct object_entry **wo,
667 struct object_entry *e)
669 struct object_entry *root;
671 for (root = e; DELTA(root); root = DELTA(root))
673 add_descendants_to_write_order(wo, endp, root);
676 static struct object_entry **compute_write_order(void)
678 unsigned int i, wo_end, last_untagged;
680 struct object_entry **wo;
681 struct object_entry *objects = to_pack.objects;
683 for (i = 0; i < to_pack.nr_objects; i++) {
684 objects[i].tagged = 0;
685 objects[i].filled = 0;
686 SET_DELTA_CHILD(&objects[i], NULL);
687 SET_DELTA_SIBLING(&objects[i], NULL);
691 * Fully connect delta_child/delta_sibling network.
692 * Make sure delta_sibling is sorted in the original
695 for (i = to_pack.nr_objects; i > 0;) {
696 struct object_entry *e = &objects[--i];
699 /* Mark me as the first child */
700 e->delta_sibling_idx = DELTA(e)->delta_child_idx;
701 SET_DELTA_CHILD(DELTA(e), e);
705 * Mark objects that are at the tip of tags.
707 for_each_tag_ref(mark_tagged, NULL);
710 * Give the objects in the original recency order until
711 * we see a tagged tip.
713 ALLOC_ARRAY(wo, to_pack.nr_objects);
714 for (i = wo_end = 0; i < to_pack.nr_objects; i++) {
715 if (objects[i].tagged)
717 add_to_write_order(wo, &wo_end, &objects[i]);
722 * Then fill all the tagged tips.
724 for (; i < to_pack.nr_objects; i++) {
725 if (objects[i].tagged)
726 add_to_write_order(wo, &wo_end, &objects[i]);
730 * And then all remaining commits and tags.
732 for (i = last_untagged; i < to_pack.nr_objects; i++) {
733 if (oe_type(&objects[i]) != OBJ_COMMIT &&
734 oe_type(&objects[i]) != OBJ_TAG)
736 add_to_write_order(wo, &wo_end, &objects[i]);
740 * And then all the trees.
742 for (i = last_untagged; i < to_pack.nr_objects; i++) {
743 if (oe_type(&objects[i]) != OBJ_TREE)
745 add_to_write_order(wo, &wo_end, &objects[i]);
749 * Finally all the rest in really tight order
751 for (i = last_untagged; i < to_pack.nr_objects; i++) {
752 if (!objects[i].filled)
753 add_family_to_write_order(wo, &wo_end, &objects[i]);
756 if (wo_end != to_pack.nr_objects)
757 die(_("ordered %u objects, expected %"PRIu32),
758 wo_end, to_pack.nr_objects);
763 static off_t write_reused_pack(struct hashfile *f)
765 unsigned char buffer[8192];
766 off_t to_write, total;
769 if (!is_pack_valid(reuse_packfile))
770 die(_("packfile is invalid: %s"), reuse_packfile->pack_name);
772 fd = git_open(reuse_packfile->pack_name);
774 die_errno(_("unable to open packfile for reuse: %s"),
775 reuse_packfile->pack_name);
777 if (lseek(fd, sizeof(struct pack_header), SEEK_SET) == -1)
778 die_errno(_("unable to seek in reused packfile"));
780 if (reuse_packfile_offset < 0)
781 reuse_packfile_offset = reuse_packfile->pack_size - the_hash_algo->rawsz;
783 total = to_write = reuse_packfile_offset - sizeof(struct pack_header);
786 int read_pack = xread(fd, buffer, sizeof(buffer));
789 die_errno(_("unable to read from reused packfile"));
791 if (read_pack > to_write)
792 read_pack = to_write;
794 hashwrite(f, buffer, read_pack);
795 to_write -= read_pack;
798 * We don't know the actual number of objects written,
799 * only how many bytes written, how many bytes total, and
800 * how many objects total. So we can fake it by pretending all
801 * objects we are writing are the same size. This gives us a
802 * smooth progress meter, and at the end it matches the true
805 written = reuse_packfile_objects *
806 (((double)(total - to_write)) / total);
807 display_progress(progress_state, written);
811 written = reuse_packfile_objects;
812 display_progress(progress_state, written);
813 return reuse_packfile_offset - sizeof(struct pack_header);
816 static const char no_split_warning[] = N_(
817 "disabling bitmap writing, packs are split due to pack.packSizeLimit"
820 static void write_pack_file(void)
825 uint32_t nr_remaining = nr_result;
826 time_t last_mtime = 0;
827 struct object_entry **write_order;
829 if (progress > pack_to_stdout)
830 progress_state = start_progress(_("Writing objects"), nr_result);
831 ALLOC_ARRAY(written_list, to_pack.nr_objects);
832 write_order = compute_write_order();
835 struct object_id oid;
836 char *pack_tmp_name = NULL;
839 f = hashfd_throughput(1, "<stdout>", progress_state);
841 f = create_tmp_packfile(&pack_tmp_name);
843 offset = write_pack_header(f, nr_remaining);
845 if (reuse_packfile) {
847 assert(pack_to_stdout);
849 packfile_size = write_reused_pack(f);
850 offset += packfile_size;
854 for (; i < to_pack.nr_objects; i++) {
855 struct object_entry *e = write_order[i];
856 if (write_one(f, e, &offset) == WRITE_ONE_BREAK)
858 display_progress(progress_state, written);
862 * Did we write the wrong # entries in the header?
863 * If so, rewrite it like in fast-import
865 if (pack_to_stdout) {
866 finalize_hashfile(f, oid.hash, CSUM_HASH_IN_STREAM | CSUM_CLOSE);
867 } else if (nr_written == nr_remaining) {
868 finalize_hashfile(f, oid.hash, CSUM_HASH_IN_STREAM | CSUM_FSYNC | CSUM_CLOSE);
870 int fd = finalize_hashfile(f, oid.hash, 0);
871 fixup_pack_header_footer(fd, oid.hash, pack_tmp_name,
872 nr_written, oid.hash, offset);
874 if (write_bitmap_index) {
875 warning(_(no_split_warning));
876 write_bitmap_index = 0;
880 if (!pack_to_stdout) {
882 struct strbuf tmpname = STRBUF_INIT;
885 * Packs are runtime accessed in their mtime
886 * order since newer packs are more likely to contain
887 * younger objects. So if we are creating multiple
888 * packs then we should modify the mtime of later ones
889 * to preserve this property.
891 if (stat(pack_tmp_name, &st) < 0) {
892 warning_errno(_("failed to stat %s"), pack_tmp_name);
893 } else if (!last_mtime) {
894 last_mtime = st.st_mtime;
897 utb.actime = st.st_atime;
898 utb.modtime = --last_mtime;
899 if (utime(pack_tmp_name, &utb) < 0)
900 warning_errno(_("failed utime() on %s"), pack_tmp_name);
903 strbuf_addf(&tmpname, "%s-", base_name);
905 if (write_bitmap_index) {
906 bitmap_writer_set_checksum(oid.hash);
907 bitmap_writer_build_type_index(
908 &to_pack, written_list, nr_written);
911 finish_tmp_packfile(&tmpname, pack_tmp_name,
912 written_list, nr_written,
913 &pack_idx_opts, oid.hash);
915 if (write_bitmap_index) {
916 strbuf_addf(&tmpname, "%s.bitmap", oid_to_hex(&oid));
918 stop_progress(&progress_state);
920 bitmap_writer_show_progress(progress);
921 bitmap_writer_reuse_bitmaps(&to_pack);
922 bitmap_writer_select_commits(indexed_commits, indexed_commits_nr, -1);
923 bitmap_writer_build(&to_pack);
924 bitmap_writer_finish(written_list, nr_written,
925 tmpname.buf, write_bitmap_options);
926 write_bitmap_index = 0;
929 strbuf_release(&tmpname);
931 puts(oid_to_hex(&oid));
934 /* mark written objects as written to previous pack */
935 for (j = 0; j < nr_written; j++) {
936 written_list[j]->offset = (off_t)-1;
938 nr_remaining -= nr_written;
939 } while (nr_remaining && i < to_pack.nr_objects);
943 stop_progress(&progress_state);
944 if (written != nr_result)
945 die(_("wrote %"PRIu32" objects while expecting %"PRIu32),
949 static int no_try_delta(const char *path)
951 static struct attr_check *check;
954 check = attr_check_initl("delta", NULL);
955 if (git_check_attr(&the_index, path, check))
957 if (ATTR_FALSE(check->items[0].value))
963 * When adding an object, check whether we have already added it
964 * to our packing list. If so, we can skip. However, if we are
965 * being asked to excludei t, but the previous mention was to include
966 * it, make sure to adjust its flags and tweak our numbers accordingly.
968 * As an optimization, we pass out the index position where we would have
969 * found the item, since that saves us from having to look it up again a
970 * few lines later when we want to add the new entry.
972 static int have_duplicate_entry(const struct object_id *oid,
976 struct object_entry *entry;
978 entry = packlist_find(&to_pack, oid->hash, index_pos);
983 if (!entry->preferred_base)
985 entry->preferred_base = 1;
991 static int want_found_object(int exclude, struct packed_git *p)
999 * When asked to do --local (do not include an object that appears in a
1000 * pack we borrow from elsewhere) or --honor-pack-keep (do not include
1001 * an object that appears in a pack marked with .keep), finding a pack
1002 * that matches the criteria is sufficient for us to decide to omit it.
1003 * However, even if this pack does not satisfy the criteria, we need to
1004 * make sure no copy of this object appears in _any_ pack that makes us
1005 * to omit the object, so we need to check all the packs.
1007 * We can however first check whether these options can possible matter;
1008 * if they do not matter we know we want the object in generated pack.
1009 * Otherwise, we signal "-1" at the end to tell the caller that we do
1010 * not know either way, and it needs to check more packs.
1012 if (!ignore_packed_keep_on_disk &&
1013 !ignore_packed_keep_in_core &&
1014 (!local || !have_non_local_packs))
1017 if (local && !p->pack_local)
1019 if (p->pack_local &&
1020 ((ignore_packed_keep_on_disk && p->pack_keep) ||
1021 (ignore_packed_keep_in_core && p->pack_keep_in_core)))
1024 /* we don't know yet; keep looking for more packs */
1029 * Check whether we want the object in the pack (e.g., we do not want
1030 * objects found in non-local stores if the "--local" option was used).
1032 * If the caller already knows an existing pack it wants to take the object
1033 * from, that is passed in *found_pack and *found_offset; otherwise this
1034 * function finds if there is any pack that has the object and returns the pack
1035 * and its offset in these variables.
1037 static int want_object_in_pack(const struct object_id *oid,
1039 struct packed_git **found_pack,
1040 off_t *found_offset)
1043 struct list_head *pos;
1044 struct multi_pack_index *m;
1046 if (!exclude && local && has_loose_object_nonlocal(oid))
1050 * If we already know the pack object lives in, start checks from that
1051 * pack - in the usual case when neither --local was given nor .keep files
1052 * are present we will determine the answer right now.
1055 want = want_found_object(exclude, *found_pack);
1060 for (m = get_multi_pack_index(the_repository); m; m = m->next) {
1061 struct pack_entry e;
1062 if (fill_midx_entry(oid, &e, m)) {
1063 struct packed_git *p = e.p;
1066 if (p == *found_pack)
1067 offset = *found_offset;
1069 offset = find_pack_entry_one(oid->hash, p);
1073 if (!is_pack_valid(p))
1075 *found_offset = offset;
1078 want = want_found_object(exclude, p);
1085 list_for_each(pos, get_packed_git_mru(the_repository)) {
1086 struct packed_git *p = list_entry(pos, struct packed_git, mru);
1089 if (p == *found_pack)
1090 offset = *found_offset;
1092 offset = find_pack_entry_one(oid->hash, p);
1096 if (!is_pack_valid(p))
1098 *found_offset = offset;
1101 want = want_found_object(exclude, p);
1102 if (!exclude && want > 0)
1104 get_packed_git_mru(the_repository));
1113 static void create_object_entry(const struct object_id *oid,
1114 enum object_type type,
1119 struct packed_git *found_pack,
1122 struct object_entry *entry;
1124 entry = packlist_alloc(&to_pack, oid->hash, index_pos);
1126 oe_set_type(entry, type);
1128 entry->preferred_base = 1;
1132 oe_set_in_pack(&to_pack, entry, found_pack);
1133 entry->in_pack_offset = found_offset;
1136 entry->no_try_delta = no_try_delta;
1139 static const char no_closure_warning[] = N_(
1140 "disabling bitmap writing, as some objects are not being packed"
1143 static int add_object_entry(const struct object_id *oid, enum object_type type,
1144 const char *name, int exclude)
1146 struct packed_git *found_pack = NULL;
1147 off_t found_offset = 0;
1150 display_progress(progress_state, ++nr_seen);
1152 if (have_duplicate_entry(oid, exclude, &index_pos))
1155 if (!want_object_in_pack(oid, exclude, &found_pack, &found_offset)) {
1156 /* The pack is missing an object, so it will not have closure */
1157 if (write_bitmap_index) {
1158 warning(_(no_closure_warning));
1159 write_bitmap_index = 0;
1164 create_object_entry(oid, type, pack_name_hash(name),
1165 exclude, name && no_try_delta(name),
1166 index_pos, found_pack, found_offset);
1170 static int add_object_entry_from_bitmap(const struct object_id *oid,
1171 enum object_type type,
1172 int flags, uint32_t name_hash,
1173 struct packed_git *pack, off_t offset)
1177 display_progress(progress_state, ++nr_seen);
1179 if (have_duplicate_entry(oid, 0, &index_pos))
1182 if (!want_object_in_pack(oid, 0, &pack, &offset))
1185 create_object_entry(oid, type, name_hash, 0, 0, index_pos, pack, offset);
1189 struct pbase_tree_cache {
1190 struct object_id oid;
1194 unsigned long tree_size;
1197 static struct pbase_tree_cache *(pbase_tree_cache[256]);
1198 static int pbase_tree_cache_ix(const struct object_id *oid)
1200 return oid->hash[0] % ARRAY_SIZE(pbase_tree_cache);
1202 static int pbase_tree_cache_ix_incr(int ix)
1204 return (ix+1) % ARRAY_SIZE(pbase_tree_cache);
1207 static struct pbase_tree {
1208 struct pbase_tree *next;
1209 /* This is a phony "cache" entry; we are not
1210 * going to evict it or find it through _get()
1211 * mechanism -- this is for the toplevel node that
1212 * would almost always change with any commit.
1214 struct pbase_tree_cache pcache;
1217 static struct pbase_tree_cache *pbase_tree_get(const struct object_id *oid)
1219 struct pbase_tree_cache *ent, *nent;
1222 enum object_type type;
1224 int my_ix = pbase_tree_cache_ix(oid);
1225 int available_ix = -1;
1227 /* pbase-tree-cache acts as a limited hashtable.
1228 * your object will be found at your index or within a few
1229 * slots after that slot if it is cached.
1231 for (neigh = 0; neigh < 8; neigh++) {
1232 ent = pbase_tree_cache[my_ix];
1233 if (ent && !oidcmp(&ent->oid, oid)) {
1237 else if (((available_ix < 0) && (!ent || !ent->ref)) ||
1238 ((0 <= available_ix) &&
1239 (!ent && pbase_tree_cache[available_ix])))
1240 available_ix = my_ix;
1243 my_ix = pbase_tree_cache_ix_incr(my_ix);
1246 /* Did not find one. Either we got a bogus request or
1247 * we need to read and perhaps cache.
1249 data = read_object_file(oid, &type, &size);
1252 if (type != OBJ_TREE) {
1257 /* We need to either cache or return a throwaway copy */
1259 if (available_ix < 0)
1262 ent = pbase_tree_cache[available_ix];
1263 my_ix = available_ix;
1267 nent = xmalloc(sizeof(*nent));
1268 nent->temporary = (available_ix < 0);
1271 /* evict and reuse */
1272 free(ent->tree_data);
1275 oidcpy(&nent->oid, oid);
1276 nent->tree_data = data;
1277 nent->tree_size = size;
1279 if (!nent->temporary)
1280 pbase_tree_cache[my_ix] = nent;
1284 static void pbase_tree_put(struct pbase_tree_cache *cache)
1286 if (!cache->temporary) {
1290 free(cache->tree_data);
1294 static int name_cmp_len(const char *name)
1297 for (i = 0; name[i] && name[i] != '\n' && name[i] != '/'; i++)
1302 static void add_pbase_object(struct tree_desc *tree,
1305 const char *fullname)
1307 struct name_entry entry;
1310 while (tree_entry(tree,&entry)) {
1311 if (S_ISGITLINK(entry.mode))
1313 cmp = tree_entry_len(&entry) != cmplen ? 1 :
1314 memcmp(name, entry.path, cmplen);
1319 if (name[cmplen] != '/') {
1320 add_object_entry(entry.oid,
1321 object_type(entry.mode),
1325 if (S_ISDIR(entry.mode)) {
1326 struct tree_desc sub;
1327 struct pbase_tree_cache *tree;
1328 const char *down = name+cmplen+1;
1329 int downlen = name_cmp_len(down);
1331 tree = pbase_tree_get(entry.oid);
1334 init_tree_desc(&sub, tree->tree_data, tree->tree_size);
1336 add_pbase_object(&sub, down, downlen, fullname);
1337 pbase_tree_put(tree);
1342 static unsigned *done_pbase_paths;
1343 static int done_pbase_paths_num;
1344 static int done_pbase_paths_alloc;
1345 static int done_pbase_path_pos(unsigned hash)
1348 int hi = done_pbase_paths_num;
1350 int mi = lo + (hi - lo) / 2;
1351 if (done_pbase_paths[mi] == hash)
1353 if (done_pbase_paths[mi] < hash)
1361 static int check_pbase_path(unsigned hash)
1363 int pos = done_pbase_path_pos(hash);
1367 ALLOC_GROW(done_pbase_paths,
1368 done_pbase_paths_num + 1,
1369 done_pbase_paths_alloc);
1370 done_pbase_paths_num++;
1371 if (pos < done_pbase_paths_num)
1372 MOVE_ARRAY(done_pbase_paths + pos + 1, done_pbase_paths + pos,
1373 done_pbase_paths_num - pos - 1);
1374 done_pbase_paths[pos] = hash;
1378 static void add_preferred_base_object(const char *name)
1380 struct pbase_tree *it;
1382 unsigned hash = pack_name_hash(name);
1384 if (!num_preferred_base || check_pbase_path(hash))
1387 cmplen = name_cmp_len(name);
1388 for (it = pbase_tree; it; it = it->next) {
1390 add_object_entry(&it->pcache.oid, OBJ_TREE, NULL, 1);
1393 struct tree_desc tree;
1394 init_tree_desc(&tree, it->pcache.tree_data, it->pcache.tree_size);
1395 add_pbase_object(&tree, name, cmplen, name);
1400 static void add_preferred_base(struct object_id *oid)
1402 struct pbase_tree *it;
1405 struct object_id tree_oid;
1407 if (window <= num_preferred_base++)
1410 data = read_object_with_reference(oid, tree_type, &size, &tree_oid);
1414 for (it = pbase_tree; it; it = it->next) {
1415 if (!oidcmp(&it->pcache.oid, &tree_oid)) {
1421 it = xcalloc(1, sizeof(*it));
1422 it->next = pbase_tree;
1425 oidcpy(&it->pcache.oid, &tree_oid);
1426 it->pcache.tree_data = data;
1427 it->pcache.tree_size = size;
1430 static void cleanup_preferred_base(void)
1432 struct pbase_tree *it;
1438 struct pbase_tree *tmp = it;
1440 free(tmp->pcache.tree_data);
1444 for (i = 0; i < ARRAY_SIZE(pbase_tree_cache); i++) {
1445 if (!pbase_tree_cache[i])
1447 free(pbase_tree_cache[i]->tree_data);
1448 FREE_AND_NULL(pbase_tree_cache[i]);
1451 FREE_AND_NULL(done_pbase_paths);
1452 done_pbase_paths_num = done_pbase_paths_alloc = 0;
1455 static void check_object(struct object_entry *entry)
1457 unsigned long canonical_size;
1459 if (IN_PACK(entry)) {
1460 struct packed_git *p = IN_PACK(entry);
1461 struct pack_window *w_curs = NULL;
1462 const unsigned char *base_ref = NULL;
1463 struct object_entry *base_entry;
1464 unsigned long used, used_0;
1465 unsigned long avail;
1467 unsigned char *buf, c;
1468 enum object_type type;
1469 unsigned long in_pack_size;
1471 buf = use_pack(p, &w_curs, entry->in_pack_offset, &avail);
1474 * We want in_pack_type even if we do not reuse delta
1475 * since non-delta representations could still be reused.
1477 used = unpack_object_header_buffer(buf, avail,
1484 BUG("invalid type %d", type);
1485 entry->in_pack_type = type;
1488 * Determine if this is a delta and if so whether we can
1489 * reuse it or not. Otherwise let's find out as cheaply as
1490 * possible what the actual type and size for this object is.
1492 switch (entry->in_pack_type) {
1494 /* Not a delta hence we've already got all we need. */
1495 oe_set_type(entry, entry->in_pack_type);
1496 SET_SIZE(entry, in_pack_size);
1497 entry->in_pack_header_size = used;
1498 if (oe_type(entry) < OBJ_COMMIT || oe_type(entry) > OBJ_BLOB)
1500 unuse_pack(&w_curs);
1503 if (reuse_delta && !entry->preferred_base)
1504 base_ref = use_pack(p, &w_curs,
1505 entry->in_pack_offset + used, NULL);
1506 entry->in_pack_header_size = used + the_hash_algo->rawsz;
1509 buf = use_pack(p, &w_curs,
1510 entry->in_pack_offset + used, NULL);
1516 if (!ofs || MSB(ofs, 7)) {
1517 error(_("delta base offset overflow in pack for %s"),
1518 oid_to_hex(&entry->idx.oid));
1522 ofs = (ofs << 7) + (c & 127);
1524 ofs = entry->in_pack_offset - ofs;
1525 if (ofs <= 0 || ofs >= entry->in_pack_offset) {
1526 error(_("delta base offset out of bound for %s"),
1527 oid_to_hex(&entry->idx.oid));
1530 if (reuse_delta && !entry->preferred_base) {
1531 struct revindex_entry *revidx;
1532 revidx = find_pack_revindex(p, ofs);
1535 base_ref = nth_packed_object_sha1(p, revidx->nr);
1537 entry->in_pack_header_size = used + used_0;
1541 if (base_ref && (base_entry = packlist_find(&to_pack, base_ref, NULL))) {
1543 * If base_ref was set above that means we wish to
1544 * reuse delta data, and we even found that base
1545 * in the list of objects we want to pack. Goodie!
1547 * Depth value does not matter - find_deltas() will
1548 * never consider reused delta as the base object to
1549 * deltify other objects against, in order to avoid
1552 oe_set_type(entry, entry->in_pack_type);
1553 SET_SIZE(entry, in_pack_size); /* delta size */
1554 SET_DELTA(entry, base_entry);
1555 SET_DELTA_SIZE(entry, in_pack_size);
1556 entry->delta_sibling_idx = base_entry->delta_child_idx;
1557 SET_DELTA_CHILD(base_entry, entry);
1558 unuse_pack(&w_curs);
1562 if (oe_type(entry)) {
1566 * This must be a delta and we already know what the
1567 * final object type is. Let's extract the actual
1568 * object size from the delta header.
1570 delta_pos = entry->in_pack_offset + entry->in_pack_header_size;
1571 canonical_size = get_size_from_delta(p, &w_curs, delta_pos);
1572 if (canonical_size == 0)
1574 SET_SIZE(entry, canonical_size);
1575 unuse_pack(&w_curs);
1580 * No choice but to fall back to the recursive delta walk
1581 * with sha1_object_info() to find about the object type
1585 unuse_pack(&w_curs);
1589 oid_object_info(the_repository, &entry->idx.oid, &canonical_size));
1590 if (entry->type_valid) {
1591 SET_SIZE(entry, canonical_size);
1594 * Bad object type is checked in prepare_pack(). This is
1595 * to permit a missing preferred base object to be ignored
1596 * as a preferred base. Doing so can result in a larger
1597 * pack file, but the transfer will still take place.
1602 static int pack_offset_sort(const void *_a, const void *_b)
1604 const struct object_entry *a = *(struct object_entry **)_a;
1605 const struct object_entry *b = *(struct object_entry **)_b;
1606 const struct packed_git *a_in_pack = IN_PACK(a);
1607 const struct packed_git *b_in_pack = IN_PACK(b);
1609 /* avoid filesystem trashing with loose objects */
1610 if (!a_in_pack && !b_in_pack)
1611 return oidcmp(&a->idx.oid, &b->idx.oid);
1613 if (a_in_pack < b_in_pack)
1615 if (a_in_pack > b_in_pack)
1617 return a->in_pack_offset < b->in_pack_offset ? -1 :
1618 (a->in_pack_offset > b->in_pack_offset);
1622 * Drop an on-disk delta we were planning to reuse. Naively, this would
1623 * just involve blanking out the "delta" field, but we have to deal
1624 * with some extra book-keeping:
1626 * 1. Removing ourselves from the delta_sibling linked list.
1628 * 2. Updating our size/type to the non-delta representation. These were
1629 * either not recorded initially (size) or overwritten with the delta type
1630 * (type) when check_object() decided to reuse the delta.
1632 * 3. Resetting our delta depth, as we are now a base object.
1634 static void drop_reused_delta(struct object_entry *entry)
1636 unsigned *idx = &to_pack.objects[entry->delta_idx - 1].delta_child_idx;
1637 struct object_info oi = OBJECT_INFO_INIT;
1638 enum object_type type;
1642 struct object_entry *oe = &to_pack.objects[*idx - 1];
1645 *idx = oe->delta_sibling_idx;
1647 idx = &oe->delta_sibling_idx;
1649 SET_DELTA(entry, NULL);
1654 if (packed_object_info(the_repository, IN_PACK(entry), entry->in_pack_offset, &oi) < 0) {
1656 * We failed to get the info from this pack for some reason;
1657 * fall back to sha1_object_info, which may find another copy.
1658 * And if that fails, the error will be recorded in oe_type(entry)
1659 * and dealt with in prepare_pack().
1662 oid_object_info(the_repository, &entry->idx.oid, &size));
1664 oe_set_type(entry, type);
1666 SET_SIZE(entry, size);
1670 * Follow the chain of deltas from this entry onward, throwing away any links
1671 * that cause us to hit a cycle (as determined by the DFS state flags in
1674 * We also detect too-long reused chains that would violate our --depth
1677 static void break_delta_chains(struct object_entry *entry)
1680 * The actual depth of each object we will write is stored as an int,
1681 * as it cannot exceed our int "depth" limit. But before we break
1682 * changes based no that limit, we may potentially go as deep as the
1683 * number of objects, which is elsewhere bounded to a uint32_t.
1685 uint32_t total_depth;
1686 struct object_entry *cur, *next;
1688 for (cur = entry, total_depth = 0;
1690 cur = DELTA(cur), total_depth++) {
1691 if (cur->dfs_state == DFS_DONE) {
1693 * We've already seen this object and know it isn't
1694 * part of a cycle. We do need to append its depth
1697 total_depth += cur->depth;
1702 * We break cycles before looping, so an ACTIVE state (or any
1703 * other cruft which made its way into the state variable)
1706 if (cur->dfs_state != DFS_NONE)
1707 BUG("confusing delta dfs state in first pass: %d",
1711 * Now we know this is the first time we've seen the object. If
1712 * it's not a delta, we're done traversing, but we'll mark it
1713 * done to save time on future traversals.
1716 cur->dfs_state = DFS_DONE;
1721 * Mark ourselves as active and see if the next step causes
1722 * us to cycle to another active object. It's important to do
1723 * this _before_ we loop, because it impacts where we make the
1724 * cut, and thus how our total_depth counter works.
1725 * E.g., We may see a partial loop like:
1727 * A -> B -> C -> D -> B
1729 * Cutting B->C breaks the cycle. But now the depth of A is
1730 * only 1, and our total_depth counter is at 3. The size of the
1731 * error is always one less than the size of the cycle we
1732 * broke. Commits C and D were "lost" from A's chain.
1734 * If we instead cut D->B, then the depth of A is correct at 3.
1735 * We keep all commits in the chain that we examined.
1737 cur->dfs_state = DFS_ACTIVE;
1738 if (DELTA(cur)->dfs_state == DFS_ACTIVE) {
1739 drop_reused_delta(cur);
1740 cur->dfs_state = DFS_DONE;
1746 * And now that we've gone all the way to the bottom of the chain, we
1747 * need to clear the active flags and set the depth fields as
1748 * appropriate. Unlike the loop above, which can quit when it drops a
1749 * delta, we need to keep going to look for more depth cuts. So we need
1750 * an extra "next" pointer to keep going after we reset cur->delta.
1752 for (cur = entry; cur; cur = next) {
1756 * We should have a chain of zero or more ACTIVE states down to
1757 * a final DONE. We can quit after the DONE, because either it
1758 * has no bases, or we've already handled them in a previous
1761 if (cur->dfs_state == DFS_DONE)
1763 else if (cur->dfs_state != DFS_ACTIVE)
1764 BUG("confusing delta dfs state in second pass: %d",
1768 * If the total_depth is more than depth, then we need to snip
1769 * the chain into two or more smaller chains that don't exceed
1770 * the maximum depth. Most of the resulting chains will contain
1771 * (depth + 1) entries (i.e., depth deltas plus one base), and
1772 * the last chain (i.e., the one containing entry) will contain
1773 * whatever entries are left over, namely
1774 * (total_depth % (depth + 1)) of them.
1776 * Since we are iterating towards decreasing depth, we need to
1777 * decrement total_depth as we go, and we need to write to the
1778 * entry what its final depth will be after all of the
1779 * snipping. Since we're snipping into chains of length (depth
1780 * + 1) entries, the final depth of an entry will be its
1781 * original depth modulo (depth + 1). Any time we encounter an
1782 * entry whose final depth is supposed to be zero, we snip it
1783 * from its delta base, thereby making it so.
1785 cur->depth = (total_depth--) % (depth + 1);
1787 drop_reused_delta(cur);
1789 cur->dfs_state = DFS_DONE;
1793 static void get_object_details(void)
1796 struct object_entry **sorted_by_offset;
1799 progress_state = start_progress(_("Counting objects"),
1800 to_pack.nr_objects);
1802 sorted_by_offset = xcalloc(to_pack.nr_objects, sizeof(struct object_entry *));
1803 for (i = 0; i < to_pack.nr_objects; i++)
1804 sorted_by_offset[i] = to_pack.objects + i;
1805 QSORT(sorted_by_offset, to_pack.nr_objects, pack_offset_sort);
1807 for (i = 0; i < to_pack.nr_objects; i++) {
1808 struct object_entry *entry = sorted_by_offset[i];
1809 check_object(entry);
1810 if (entry->type_valid &&
1811 oe_size_greater_than(&to_pack, entry, big_file_threshold))
1812 entry->no_try_delta = 1;
1813 display_progress(progress_state, i + 1);
1815 stop_progress(&progress_state);
1818 * This must happen in a second pass, since we rely on the delta
1819 * information for the whole list being completed.
1821 for (i = 0; i < to_pack.nr_objects; i++)
1822 break_delta_chains(&to_pack.objects[i]);
1824 free(sorted_by_offset);
1828 * We search for deltas in a list sorted by type, by filename hash, and then
1829 * by size, so that we see progressively smaller and smaller files.
1830 * That's because we prefer deltas to be from the bigger file
1831 * to the smaller -- deletes are potentially cheaper, but perhaps
1832 * more importantly, the bigger file is likely the more recent
1833 * one. The deepest deltas are therefore the oldest objects which are
1834 * less susceptible to be accessed often.
1836 static int type_size_sort(const void *_a, const void *_b)
1838 const struct object_entry *a = *(struct object_entry **)_a;
1839 const struct object_entry *b = *(struct object_entry **)_b;
1840 enum object_type a_type = oe_type(a);
1841 enum object_type b_type = oe_type(b);
1842 unsigned long a_size = SIZE(a);
1843 unsigned long b_size = SIZE(b);
1845 if (a_type > b_type)
1847 if (a_type < b_type)
1849 if (a->hash > b->hash)
1851 if (a->hash < b->hash)
1853 if (a->preferred_base > b->preferred_base)
1855 if (a->preferred_base < b->preferred_base)
1857 if (a_size > b_size)
1859 if (a_size < b_size)
1861 return a < b ? -1 : (a > b); /* newest first */
1865 struct object_entry *entry;
1867 struct delta_index *index;
1871 static int delta_cacheable(unsigned long src_size, unsigned long trg_size,
1872 unsigned long delta_size)
1874 if (max_delta_cache_size && delta_cache_size + delta_size > max_delta_cache_size)
1877 if (delta_size < cache_max_small_delta_size)
1880 /* cache delta, if objects are large enough compared to delta size */
1881 if ((src_size >> 20) + (trg_size >> 21) > (delta_size >> 10))
1889 /* Protect access to object database */
1890 static pthread_mutex_t read_mutex;
1891 #define read_lock() pthread_mutex_lock(&read_mutex)
1892 #define read_unlock() pthread_mutex_unlock(&read_mutex)
1894 /* Protect delta_cache_size */
1895 static pthread_mutex_t cache_mutex;
1896 #define cache_lock() pthread_mutex_lock(&cache_mutex)
1897 #define cache_unlock() pthread_mutex_unlock(&cache_mutex)
1900 * Protect object list partitioning (e.g. struct thread_param) and
1903 static pthread_mutex_t progress_mutex;
1904 #define progress_lock() pthread_mutex_lock(&progress_mutex)
1905 #define progress_unlock() pthread_mutex_unlock(&progress_mutex)
1908 * Access to struct object_entry is unprotected since each thread owns
1909 * a portion of the main object list. Just don't access object entries
1910 * ahead in the list because they can be stolen and would need
1911 * progress_mutex for protection.
1915 #define read_lock() (void)0
1916 #define read_unlock() (void)0
1917 #define cache_lock() (void)0
1918 #define cache_unlock() (void)0
1919 #define progress_lock() (void)0
1920 #define progress_unlock() (void)0
1925 * Return the size of the object without doing any delta
1926 * reconstruction (so non-deltas are true object sizes, but deltas
1927 * return the size of the delta data).
1929 unsigned long oe_get_size_slow(struct packing_data *pack,
1930 const struct object_entry *e)
1932 struct packed_git *p;
1933 struct pack_window *w_curs;
1935 enum object_type type;
1936 unsigned long used, avail, size;
1938 if (e->type_ != OBJ_OFS_DELTA && e->type_ != OBJ_REF_DELTA) {
1940 if (oid_object_info(the_repository, &e->idx.oid, &size) < 0)
1941 die(_("unable to get size of %s"),
1942 oid_to_hex(&e->idx.oid));
1947 p = oe_in_pack(pack, e);
1949 BUG("when e->type is a delta, it must belong to a pack");
1953 buf = use_pack(p, &w_curs, e->in_pack_offset, &avail);
1954 used = unpack_object_header_buffer(buf, avail, &type, &size);
1956 die(_("unable to parse object header of %s"),
1957 oid_to_hex(&e->idx.oid));
1959 unuse_pack(&w_curs);
1964 static int try_delta(struct unpacked *trg, struct unpacked *src,
1965 unsigned max_depth, unsigned long *mem_usage)
1967 struct object_entry *trg_entry = trg->entry;
1968 struct object_entry *src_entry = src->entry;
1969 unsigned long trg_size, src_size, delta_size, sizediff, max_size, sz;
1971 enum object_type type;
1974 /* Don't bother doing diffs between different types */
1975 if (oe_type(trg_entry) != oe_type(src_entry))
1979 * We do not bother to try a delta that we discarded on an
1980 * earlier try, but only when reusing delta data. Note that
1981 * src_entry that is marked as the preferred_base should always
1982 * be considered, as even if we produce a suboptimal delta against
1983 * it, we will still save the transfer cost, as we already know
1984 * the other side has it and we won't send src_entry at all.
1986 if (reuse_delta && IN_PACK(trg_entry) &&
1987 IN_PACK(trg_entry) == IN_PACK(src_entry) &&
1988 !src_entry->preferred_base &&
1989 trg_entry->in_pack_type != OBJ_REF_DELTA &&
1990 trg_entry->in_pack_type != OBJ_OFS_DELTA)
1993 /* Let's not bust the allowed depth. */
1994 if (src->depth >= max_depth)
1997 /* Now some size filtering heuristics. */
1998 trg_size = SIZE(trg_entry);
1999 if (!DELTA(trg_entry)) {
2000 max_size = trg_size/2 - the_hash_algo->rawsz;
2003 max_size = DELTA_SIZE(trg_entry);
2004 ref_depth = trg->depth;
2006 max_size = (uint64_t)max_size * (max_depth - src->depth) /
2007 (max_depth - ref_depth + 1);
2010 src_size = SIZE(src_entry);
2011 sizediff = src_size < trg_size ? trg_size - src_size : 0;
2012 if (sizediff >= max_size)
2014 if (trg_size < src_size / 32)
2017 /* Load data if not already done */
2020 trg->data = read_object_file(&trg_entry->idx.oid, &type, &sz);
2023 die(_("object %s cannot be read"),
2024 oid_to_hex(&trg_entry->idx.oid));
2026 die(_("object %s inconsistent object length (%lu vs %lu)"),
2027 oid_to_hex(&trg_entry->idx.oid), sz,
2033 src->data = read_object_file(&src_entry->idx.oid, &type, &sz);
2036 if (src_entry->preferred_base) {
2037 static int warned = 0;
2039 warning(_("object %s cannot be read"),
2040 oid_to_hex(&src_entry->idx.oid));
2042 * Those objects are not included in the
2043 * resulting pack. Be resilient and ignore
2044 * them if they can't be read, in case the
2045 * pack could be created nevertheless.
2049 die(_("object %s cannot be read"),
2050 oid_to_hex(&src_entry->idx.oid));
2053 die(_("object %s inconsistent object length (%lu vs %lu)"),
2054 oid_to_hex(&src_entry->idx.oid), sz,
2059 src->index = create_delta_index(src->data, src_size);
2061 static int warned = 0;
2063 warning(_("suboptimal pack - out of memory"));
2066 *mem_usage += sizeof_delta_index(src->index);
2069 delta_buf = create_delta(src->index, trg->data, trg_size, &delta_size, max_size);
2073 if (DELTA(trg_entry)) {
2074 /* Prefer only shallower same-sized deltas. */
2075 if (delta_size == DELTA_SIZE(trg_entry) &&
2076 src->depth + 1 >= trg->depth) {
2083 * Handle memory allocation outside of the cache
2084 * accounting lock. Compiler will optimize the strangeness
2085 * away when NO_PTHREADS is defined.
2087 free(trg_entry->delta_data);
2089 if (trg_entry->delta_data) {
2090 delta_cache_size -= DELTA_SIZE(trg_entry);
2091 trg_entry->delta_data = NULL;
2093 if (delta_cacheable(src_size, trg_size, delta_size)) {
2094 delta_cache_size += delta_size;
2096 trg_entry->delta_data = xrealloc(delta_buf, delta_size);
2102 SET_DELTA(trg_entry, src_entry);
2103 SET_DELTA_SIZE(trg_entry, delta_size);
2104 trg->depth = src->depth + 1;
2109 static unsigned int check_delta_limit(struct object_entry *me, unsigned int n)
2111 struct object_entry *child = DELTA_CHILD(me);
2114 unsigned int c = check_delta_limit(child, n + 1);
2117 child = DELTA_SIBLING(child);
2122 static unsigned long free_unpacked(struct unpacked *n)
2124 unsigned long freed_mem = sizeof_delta_index(n->index);
2125 free_delta_index(n->index);
2128 freed_mem += SIZE(n->entry);
2129 FREE_AND_NULL(n->data);
2136 static void find_deltas(struct object_entry **list, unsigned *list_size,
2137 int window, int depth, unsigned *processed)
2139 uint32_t i, idx = 0, count = 0;
2140 struct unpacked *array;
2141 unsigned long mem_usage = 0;
2143 array = xcalloc(window, sizeof(struct unpacked));
2146 struct object_entry *entry;
2147 struct unpacked *n = array + idx;
2148 int j, max_depth, best_base = -1;
2157 if (!entry->preferred_base) {
2159 display_progress(progress_state, *processed);
2163 mem_usage -= free_unpacked(n);
2166 while (window_memory_limit &&
2167 mem_usage > window_memory_limit &&
2169 uint32_t tail = (idx + window - count) % window;
2170 mem_usage -= free_unpacked(array + tail);
2174 /* We do not compute delta to *create* objects we are not
2177 if (entry->preferred_base)
2181 * If the current object is at pack edge, take the depth the
2182 * objects that depend on the current object into account
2183 * otherwise they would become too deep.
2186 if (DELTA_CHILD(entry)) {
2187 max_depth -= check_delta_limit(entry, 0);
2195 uint32_t other_idx = idx + j;
2197 if (other_idx >= window)
2198 other_idx -= window;
2199 m = array + other_idx;
2202 ret = try_delta(n, m, max_depth, &mem_usage);
2206 best_base = other_idx;
2210 * If we decided to cache the delta data, then it is best
2211 * to compress it right away. First because we have to do
2212 * it anyway, and doing it here while we're threaded will
2213 * save a lot of time in the non threaded write phase,
2214 * as well as allow for caching more deltas within
2215 * the same cache size limit.
2217 * But only if not writing to stdout, since in that case
2218 * the network is most likely throttling writes anyway,
2219 * and therefore it is best to go to the write phase ASAP
2220 * instead, as we can afford spending more time compressing
2221 * between writes at that moment.
2223 if (entry->delta_data && !pack_to_stdout) {
2226 size = do_compress(&entry->delta_data, DELTA_SIZE(entry));
2227 if (size < (1U << OE_Z_DELTA_BITS)) {
2228 entry->z_delta_size = size;
2230 delta_cache_size -= DELTA_SIZE(entry);
2231 delta_cache_size += entry->z_delta_size;
2234 FREE_AND_NULL(entry->delta_data);
2235 entry->z_delta_size = 0;
2239 /* if we made n a delta, and if n is already at max
2240 * depth, leaving it in the window is pointless. we
2241 * should evict it first.
2243 if (DELTA(entry) && max_depth <= n->depth)
2247 * Move the best delta base up in the window, after the
2248 * currently deltified object, to keep it longer. It will
2249 * be the first base object to be attempted next.
2252 struct unpacked swap = array[best_base];
2253 int dist = (window + idx - best_base) % window;
2254 int dst = best_base;
2256 int src = (dst + 1) % window;
2257 array[dst] = array[src];
2265 if (count + 1 < window)
2271 for (i = 0; i < window; ++i) {
2272 free_delta_index(array[i].index);
2273 free(array[i].data);
2280 static void try_to_free_from_threads(size_t size)
2283 release_pack_memory(size);
2287 static try_to_free_t old_try_to_free_routine;
2290 * The main object list is split into smaller lists, each is handed to
2293 * The main thread waits on the condition that (at least) one of the workers
2294 * has stopped working (which is indicated in the .working member of
2295 * struct thread_params).
2297 * When a work thread has completed its work, it sets .working to 0 and
2298 * signals the main thread and waits on the condition that .data_ready
2301 * The main thread steals half of the work from the worker that has
2302 * most work left to hand it to the idle worker.
2305 struct thread_params {
2307 struct object_entry **list;
2314 pthread_mutex_t mutex;
2315 pthread_cond_t cond;
2316 unsigned *processed;
2319 static pthread_cond_t progress_cond;
2322 * Mutex and conditional variable can't be statically-initialized on Windows.
2324 static void init_threaded_search(void)
2326 init_recursive_mutex(&read_mutex);
2327 pthread_mutex_init(&cache_mutex, NULL);
2328 pthread_mutex_init(&progress_mutex, NULL);
2329 pthread_cond_init(&progress_cond, NULL);
2330 pthread_mutex_init(&to_pack.lock, NULL);
2331 old_try_to_free_routine = set_try_to_free_routine(try_to_free_from_threads);
2334 static void cleanup_threaded_search(void)
2336 set_try_to_free_routine(old_try_to_free_routine);
2337 pthread_cond_destroy(&progress_cond);
2338 pthread_mutex_destroy(&read_mutex);
2339 pthread_mutex_destroy(&cache_mutex);
2340 pthread_mutex_destroy(&progress_mutex);
2343 static void *threaded_find_deltas(void *arg)
2345 struct thread_params *me = arg;
2348 while (me->remaining) {
2351 find_deltas(me->list, &me->remaining,
2352 me->window, me->depth, me->processed);
2356 pthread_cond_signal(&progress_cond);
2360 * We must not set ->data_ready before we wait on the
2361 * condition because the main thread may have set it to 1
2362 * before we get here. In order to be sure that new
2363 * work is available if we see 1 in ->data_ready, it
2364 * was initialized to 0 before this thread was spawned
2365 * and we reset it to 0 right away.
2367 pthread_mutex_lock(&me->mutex);
2368 while (!me->data_ready)
2369 pthread_cond_wait(&me->cond, &me->mutex);
2371 pthread_mutex_unlock(&me->mutex);
2376 /* leave ->working 1 so that this doesn't get more work assigned */
2380 static void ll_find_deltas(struct object_entry **list, unsigned list_size,
2381 int window, int depth, unsigned *processed)
2383 struct thread_params *p;
2384 int i, ret, active_threads = 0;
2386 init_threaded_search();
2388 if (delta_search_threads <= 1) {
2389 find_deltas(list, &list_size, window, depth, processed);
2390 cleanup_threaded_search();
2393 if (progress > pack_to_stdout)
2394 fprintf_ln(stderr, _("Delta compression using up to %d threads"),
2395 delta_search_threads);
2396 p = xcalloc(delta_search_threads, sizeof(*p));
2398 /* Partition the work amongst work threads. */
2399 for (i = 0; i < delta_search_threads; i++) {
2400 unsigned sub_size = list_size / (delta_search_threads - i);
2402 /* don't use too small segments or no deltas will be found */
2403 if (sub_size < 2*window && i+1 < delta_search_threads)
2406 p[i].window = window;
2408 p[i].processed = processed;
2410 p[i].data_ready = 0;
2412 /* try to split chunks on "path" boundaries */
2413 while (sub_size && sub_size < list_size &&
2414 list[sub_size]->hash &&
2415 list[sub_size]->hash == list[sub_size-1]->hash)
2419 p[i].list_size = sub_size;
2420 p[i].remaining = sub_size;
2423 list_size -= sub_size;
2426 /* Start work threads. */
2427 for (i = 0; i < delta_search_threads; i++) {
2428 if (!p[i].list_size)
2430 pthread_mutex_init(&p[i].mutex, NULL);
2431 pthread_cond_init(&p[i].cond, NULL);
2432 ret = pthread_create(&p[i].thread, NULL,
2433 threaded_find_deltas, &p[i]);
2435 die(_("unable to create thread: %s"), strerror(ret));
2440 * Now let's wait for work completion. Each time a thread is done
2441 * with its work, we steal half of the remaining work from the
2442 * thread with the largest number of unprocessed objects and give
2443 * it to that newly idle thread. This ensure good load balancing
2444 * until the remaining object list segments are simply too short
2445 * to be worth splitting anymore.
2447 while (active_threads) {
2448 struct thread_params *target = NULL;
2449 struct thread_params *victim = NULL;
2450 unsigned sub_size = 0;
2454 for (i = 0; !target && i < delta_search_threads; i++)
2459 pthread_cond_wait(&progress_cond, &progress_mutex);
2462 for (i = 0; i < delta_search_threads; i++)
2463 if (p[i].remaining > 2*window &&
2464 (!victim || victim->remaining < p[i].remaining))
2467 sub_size = victim->remaining / 2;
2468 list = victim->list + victim->list_size - sub_size;
2469 while (sub_size && list[0]->hash &&
2470 list[0]->hash == list[-1]->hash) {
2476 * It is possible for some "paths" to have
2477 * so many objects that no hash boundary
2478 * might be found. Let's just steal the
2479 * exact half in that case.
2481 sub_size = victim->remaining / 2;
2484 target->list = list;
2485 victim->list_size -= sub_size;
2486 victim->remaining -= sub_size;
2488 target->list_size = sub_size;
2489 target->remaining = sub_size;
2490 target->working = 1;
2493 pthread_mutex_lock(&target->mutex);
2494 target->data_ready = 1;
2495 pthread_cond_signal(&target->cond);
2496 pthread_mutex_unlock(&target->mutex);
2499 pthread_join(target->thread, NULL);
2500 pthread_cond_destroy(&target->cond);
2501 pthread_mutex_destroy(&target->mutex);
2505 cleanup_threaded_search();
2510 #define ll_find_deltas(l, s, w, d, p) find_deltas(l, &s, w, d, p)
2513 static void add_tag_chain(const struct object_id *oid)
2518 * We catch duplicates already in add_object_entry(), but we'd
2519 * prefer to do this extra check to avoid having to parse the
2520 * tag at all if we already know that it's being packed (e.g., if
2521 * it was included via bitmaps, we would not have parsed it
2524 if (packlist_find(&to_pack, oid->hash, NULL))
2527 tag = lookup_tag(the_repository, oid);
2529 if (!tag || parse_tag(tag) || !tag->tagged)
2530 die(_("unable to pack objects reachable from tag %s"),
2533 add_object_entry(&tag->object.oid, OBJ_TAG, NULL, 0);
2535 if (tag->tagged->type != OBJ_TAG)
2538 tag = (struct tag *)tag->tagged;
2542 static int add_ref_tag(const char *path, const struct object_id *oid, int flag, void *cb_data)
2544 struct object_id peeled;
2546 if (starts_with(path, "refs/tags/") && /* is a tag? */
2547 !peel_ref(path, &peeled) && /* peelable? */
2548 packlist_find(&to_pack, peeled.hash, NULL)) /* object packed? */
2553 static void prepare_pack(int window, int depth)
2555 struct object_entry **delta_list;
2556 uint32_t i, nr_deltas;
2559 get_object_details();
2562 * If we're locally repacking then we need to be doubly careful
2563 * from now on in order to make sure no stealth corruption gets
2564 * propagated to the new pack. Clients receiving streamed packs
2565 * should validate everything they get anyway so no need to incur
2566 * the additional cost here in that case.
2568 if (!pack_to_stdout)
2569 do_check_packed_object_crc = 1;
2571 if (!to_pack.nr_objects || !window || !depth)
2574 ALLOC_ARRAY(delta_list, to_pack.nr_objects);
2577 for (i = 0; i < to_pack.nr_objects; i++) {
2578 struct object_entry *entry = to_pack.objects + i;
2581 /* This happens if we decided to reuse existing
2582 * delta from a pack. "reuse_delta &&" is implied.
2586 if (!entry->type_valid ||
2587 oe_size_less_than(&to_pack, entry, 50))
2590 if (entry->no_try_delta)
2593 if (!entry->preferred_base) {
2595 if (oe_type(entry) < 0)
2596 die(_("unable to get type of object %s"),
2597 oid_to_hex(&entry->idx.oid));
2599 if (oe_type(entry) < 0) {
2601 * This object is not found, but we
2602 * don't have to include it anyway.
2608 delta_list[n++] = entry;
2611 if (nr_deltas && n > 1) {
2612 unsigned nr_done = 0;
2614 progress_state = start_progress(_("Compressing objects"),
2616 QSORT(delta_list, n, type_size_sort);
2617 ll_find_deltas(delta_list, n, window+1, depth, &nr_done);
2618 stop_progress(&progress_state);
2619 if (nr_done != nr_deltas)
2620 die(_("inconsistency with delta count"));
2625 static int git_pack_config(const char *k, const char *v, void *cb)
2627 if (!strcmp(k, "pack.window")) {
2628 window = git_config_int(k, v);
2631 if (!strcmp(k, "pack.windowmemory")) {
2632 window_memory_limit = git_config_ulong(k, v);
2635 if (!strcmp(k, "pack.depth")) {
2636 depth = git_config_int(k, v);
2639 if (!strcmp(k, "pack.deltacachesize")) {
2640 max_delta_cache_size = git_config_int(k, v);
2643 if (!strcmp(k, "pack.deltacachelimit")) {
2644 cache_max_small_delta_size = git_config_int(k, v);
2647 if (!strcmp(k, "pack.writebitmaphashcache")) {
2648 if (git_config_bool(k, v))
2649 write_bitmap_options |= BITMAP_OPT_HASH_CACHE;
2651 write_bitmap_options &= ~BITMAP_OPT_HASH_CACHE;
2653 if (!strcmp(k, "pack.usebitmaps")) {
2654 use_bitmap_index_default = git_config_bool(k, v);
2657 if (!strcmp(k, "pack.threads")) {
2658 delta_search_threads = git_config_int(k, v);
2659 if (delta_search_threads < 0)
2660 die(_("invalid number of threads specified (%d)"),
2661 delta_search_threads);
2663 if (delta_search_threads != 1) {
2664 warning(_("no threads support, ignoring %s"), k);
2665 delta_search_threads = 0;
2670 if (!strcmp(k, "pack.indexversion")) {
2671 pack_idx_opts.version = git_config_int(k, v);
2672 if (pack_idx_opts.version > 2)
2673 die(_("bad pack.indexversion=%"PRIu32),
2674 pack_idx_opts.version);
2677 return git_default_config(k, v, cb);
2680 static void read_object_list_from_stdin(void)
2682 char line[GIT_MAX_HEXSZ + 1 + PATH_MAX + 2];
2683 struct object_id oid;
2687 if (!fgets(line, sizeof(line), stdin)) {
2691 die("BUG: fgets returned NULL, not EOF, not error!");
2697 if (line[0] == '-') {
2698 if (get_oid_hex(line+1, &oid))
2699 die(_("expected edge object ID, got garbage:\n %s"),
2701 add_preferred_base(&oid);
2704 if (parse_oid_hex(line, &oid, &p))
2705 die(_("expected object ID, got garbage:\n %s"), line);
2707 add_preferred_base_object(p + 1);
2708 add_object_entry(&oid, OBJ_NONE, p + 1, 0);
2712 /* Remember to update object flag allocation in object.h */
2713 #define OBJECT_ADDED (1u<<20)
2715 static void show_commit(struct commit *commit, void *data)
2717 add_object_entry(&commit->object.oid, OBJ_COMMIT, NULL, 0);
2718 commit->object.flags |= OBJECT_ADDED;
2720 if (write_bitmap_index)
2721 index_commit_for_bitmap(commit);
2724 static void show_object(struct object *obj, const char *name, void *data)
2726 add_preferred_base_object(name);
2727 add_object_entry(&obj->oid, obj->type, name, 0);
2728 obj->flags |= OBJECT_ADDED;
2731 static void show_object__ma_allow_any(struct object *obj, const char *name, void *data)
2733 assert(arg_missing_action == MA_ALLOW_ANY);
2736 * Quietly ignore ALL missing objects. This avoids problems with
2737 * staging them now and getting an odd error later.
2739 if (!has_object_file(&obj->oid))
2742 show_object(obj, name, data);
2745 static void show_object__ma_allow_promisor(struct object *obj, const char *name, void *data)
2747 assert(arg_missing_action == MA_ALLOW_PROMISOR);
2750 * Quietly ignore EXPECTED missing objects. This avoids problems with
2751 * staging them now and getting an odd error later.
2753 if (!has_object_file(&obj->oid) && is_promisor_object(&obj->oid))
2756 show_object(obj, name, data);
2759 static int option_parse_missing_action(const struct option *opt,
2760 const char *arg, int unset)
2765 if (!strcmp(arg, "error")) {
2766 arg_missing_action = MA_ERROR;
2767 fn_show_object = show_object;
2771 if (!strcmp(arg, "allow-any")) {
2772 arg_missing_action = MA_ALLOW_ANY;
2773 fetch_if_missing = 0;
2774 fn_show_object = show_object__ma_allow_any;
2778 if (!strcmp(arg, "allow-promisor")) {
2779 arg_missing_action = MA_ALLOW_PROMISOR;
2780 fetch_if_missing = 0;
2781 fn_show_object = show_object__ma_allow_promisor;
2785 die(_("invalid value for --missing"));
2789 static void show_edge(struct commit *commit)
2791 add_preferred_base(&commit->object.oid);
2794 struct in_pack_object {
2796 struct object *object;
2802 struct in_pack_object *array;
2805 static void mark_in_pack_object(struct object *object, struct packed_git *p, struct in_pack *in_pack)
2807 in_pack->array[in_pack->nr].offset = find_pack_entry_one(object->oid.hash, p);
2808 in_pack->array[in_pack->nr].object = object;
2813 * Compare the objects in the offset order, in order to emulate the
2814 * "git rev-list --objects" output that produced the pack originally.
2816 static int ofscmp(const void *a_, const void *b_)
2818 struct in_pack_object *a = (struct in_pack_object *)a_;
2819 struct in_pack_object *b = (struct in_pack_object *)b_;
2821 if (a->offset < b->offset)
2823 else if (a->offset > b->offset)
2826 return oidcmp(&a->object->oid, &b->object->oid);
2829 static void add_objects_in_unpacked_packs(struct rev_info *revs)
2831 struct packed_git *p;
2832 struct in_pack in_pack;
2835 memset(&in_pack, 0, sizeof(in_pack));
2837 for (p = get_all_packs(the_repository); p; p = p->next) {
2838 struct object_id oid;
2841 if (!p->pack_local || p->pack_keep || p->pack_keep_in_core)
2843 if (open_pack_index(p))
2844 die(_("cannot open pack index"));
2846 ALLOC_GROW(in_pack.array,
2847 in_pack.nr + p->num_objects,
2850 for (i = 0; i < p->num_objects; i++) {
2851 nth_packed_object_oid(&oid, p, i);
2852 o = lookup_unknown_object(oid.hash);
2853 if (!(o->flags & OBJECT_ADDED))
2854 mark_in_pack_object(o, p, &in_pack);
2855 o->flags |= OBJECT_ADDED;
2860 QSORT(in_pack.array, in_pack.nr, ofscmp);
2861 for (i = 0; i < in_pack.nr; i++) {
2862 struct object *o = in_pack.array[i].object;
2863 add_object_entry(&o->oid, o->type, "", 0);
2866 free(in_pack.array);
2869 static int add_loose_object(const struct object_id *oid, const char *path,
2872 enum object_type type = oid_object_info(the_repository, oid, NULL);
2875 warning(_("loose object at %s could not be examined"), path);
2879 add_object_entry(oid, type, "", 0);
2884 * We actually don't even have to worry about reachability here.
2885 * add_object_entry will weed out duplicates, so we just add every
2886 * loose object we find.
2888 static void add_unreachable_loose_objects(void)
2890 for_each_loose_file_in_objdir(get_object_directory(),
2895 static int has_sha1_pack_kept_or_nonlocal(const struct object_id *oid)
2897 static struct packed_git *last_found = (void *)1;
2898 struct packed_git *p;
2900 p = (last_found != (void *)1) ? last_found :
2901 get_all_packs(the_repository);
2904 if ((!p->pack_local || p->pack_keep ||
2905 p->pack_keep_in_core) &&
2906 find_pack_entry_one(oid->hash, p)) {
2910 if (p == last_found)
2911 p = get_all_packs(the_repository);
2914 if (p == last_found)
2921 * Store a list of sha1s that are should not be discarded
2922 * because they are either written too recently, or are
2923 * reachable from another object that was.
2925 * This is filled by get_object_list.
2927 static struct oid_array recent_objects;
2929 static int loosened_object_can_be_discarded(const struct object_id *oid,
2932 if (!unpack_unreachable_expiration)
2934 if (mtime > unpack_unreachable_expiration)
2936 if (oid_array_lookup(&recent_objects, oid) >= 0)
2941 static void loosen_unused_packed_objects(struct rev_info *revs)
2943 struct packed_git *p;
2945 struct object_id oid;
2947 for (p = get_all_packs(the_repository); p; p = p->next) {
2948 if (!p->pack_local || p->pack_keep || p->pack_keep_in_core)
2951 if (open_pack_index(p))
2952 die(_("cannot open pack index"));
2954 for (i = 0; i < p->num_objects; i++) {
2955 nth_packed_object_oid(&oid, p, i);
2956 if (!packlist_find(&to_pack, oid.hash, NULL) &&
2957 !has_sha1_pack_kept_or_nonlocal(&oid) &&
2958 !loosened_object_can_be_discarded(&oid, p->mtime))
2959 if (force_object_loose(&oid, p->mtime))
2960 die(_("unable to force loose object"));
2966 * This tracks any options which pack-reuse code expects to be on, or which a
2967 * reader of the pack might not understand, and which would therefore prevent
2968 * blind reuse of what we have on disk.
2970 static int pack_options_allow_reuse(void)
2972 return pack_to_stdout &&
2974 !ignore_packed_keep_on_disk &&
2975 !ignore_packed_keep_in_core &&
2976 (!local || !have_non_local_packs) &&
2980 static int get_object_list_from_bitmap(struct rev_info *revs)
2982 struct bitmap_index *bitmap_git;
2983 if (!(bitmap_git = prepare_bitmap_walk(revs)))
2986 if (pack_options_allow_reuse() &&
2987 !reuse_partial_packfile_from_bitmap(
2990 &reuse_packfile_objects,
2991 &reuse_packfile_offset)) {
2992 assert(reuse_packfile_objects);
2993 nr_result += reuse_packfile_objects;
2994 display_progress(progress_state, nr_result);
2997 traverse_bitmap_commit_list(bitmap_git, &add_object_entry_from_bitmap);
2998 free_bitmap_index(bitmap_git);
3002 static void record_recent_object(struct object *obj,
3006 oid_array_append(&recent_objects, &obj->oid);
3009 static void record_recent_commit(struct commit *commit, void *data)
3011 oid_array_append(&recent_objects, &commit->object.oid);
3014 static void get_object_list(int ac, const char **av)
3016 struct rev_info revs;
3020 init_revisions(&revs, NULL);
3021 save_commit_buffer = 0;
3022 setup_revisions(ac, av, &revs, NULL);
3024 /* make sure shallows are read */
3025 is_repository_shallow(the_repository);
3027 while (fgets(line, sizeof(line), stdin) != NULL) {
3028 int len = strlen(line);
3029 if (len && line[len - 1] == '\n')
3034 if (!strcmp(line, "--not")) {
3035 flags ^= UNINTERESTING;
3036 write_bitmap_index = 0;
3039 if (starts_with(line, "--shallow ")) {
3040 struct object_id oid;
3041 if (get_oid_hex(line + 10, &oid))
3042 die("not an SHA-1 '%s'", line + 10);
3043 register_shallow(the_repository, &oid);
3044 use_bitmap_index = 0;
3047 die(_("not a rev '%s'"), line);
3049 if (handle_revision_arg(line, &revs, flags, REVARG_CANNOT_BE_FILENAME))
3050 die(_("bad revision '%s'"), line);
3053 if (use_bitmap_index && !get_object_list_from_bitmap(&revs))
3056 if (prepare_revision_walk(&revs))
3057 die(_("revision walk setup failed"));
3058 mark_edges_uninteresting(&revs, show_edge);
3060 if (!fn_show_object)
3061 fn_show_object = show_object;
3062 traverse_commit_list_filtered(&filter_options, &revs,
3063 show_commit, fn_show_object, NULL,
3066 if (unpack_unreachable_expiration) {
3067 revs.ignore_missing_links = 1;
3068 if (add_unseen_recent_objects_to_traversal(&revs,
3069 unpack_unreachable_expiration))
3070 die(_("unable to add recent objects"));
3071 if (prepare_revision_walk(&revs))
3072 die(_("revision walk setup failed"));
3073 traverse_commit_list(&revs, record_recent_commit,
3074 record_recent_object, NULL);
3077 if (keep_unreachable)
3078 add_objects_in_unpacked_packs(&revs);
3079 if (pack_loose_unreachable)
3080 add_unreachable_loose_objects();
3081 if (unpack_unreachable)
3082 loosen_unused_packed_objects(&revs);
3084 oid_array_clear(&recent_objects);
3087 static void add_extra_kept_packs(const struct string_list *names)
3089 struct packed_git *p;
3094 for (p = get_all_packs(the_repository); p; p = p->next) {
3095 const char *name = basename(p->pack_name);
3101 for (i = 0; i < names->nr; i++)
3102 if (!fspathcmp(name, names->items[i].string))
3105 if (i < names->nr) {
3106 p->pack_keep_in_core = 1;
3107 ignore_packed_keep_in_core = 1;
3113 static int option_parse_index_version(const struct option *opt,
3114 const char *arg, int unset)
3117 const char *val = arg;
3118 pack_idx_opts.version = strtoul(val, &c, 10);
3119 if (pack_idx_opts.version > 2)
3120 die(_("unsupported index version %s"), val);
3121 if (*c == ',' && c[1])
3122 pack_idx_opts.off32_limit = strtoul(c+1, &c, 0);
3123 if (*c || pack_idx_opts.off32_limit & 0x80000000)
3124 die(_("bad index version '%s'"), val);
3128 static int option_parse_unpack_unreachable(const struct option *opt,
3129 const char *arg, int unset)
3132 unpack_unreachable = 0;
3133 unpack_unreachable_expiration = 0;
3136 unpack_unreachable = 1;
3138 unpack_unreachable_expiration = approxidate(arg);
3143 int cmd_pack_objects(int argc, const char **argv, const char *prefix)
3145 int use_internal_rev_list = 0;
3148 int all_progress_implied = 0;
3149 struct argv_array rp = ARGV_ARRAY_INIT;
3150 int rev_list_unpacked = 0, rev_list_all = 0, rev_list_reflog = 0;
3151 int rev_list_index = 0;
3152 struct string_list keep_pack_list = STRING_LIST_INIT_NODUP;
3153 struct option pack_objects_options[] = {
3154 OPT_SET_INT('q', "quiet", &progress,
3155 N_("do not show progress meter"), 0),
3156 OPT_SET_INT(0, "progress", &progress,
3157 N_("show progress meter"), 1),
3158 OPT_SET_INT(0, "all-progress", &progress,
3159 N_("show progress meter during object writing phase"), 2),
3160 OPT_BOOL(0, "all-progress-implied",
3161 &all_progress_implied,
3162 N_("similar to --all-progress when progress meter is shown")),
3163 { OPTION_CALLBACK, 0, "index-version", NULL, N_("<version>[,<offset>]"),
3164 N_("write the pack index file in the specified idx format version"),
3165 0, option_parse_index_version },
3166 OPT_MAGNITUDE(0, "max-pack-size", &pack_size_limit,
3167 N_("maximum size of each output pack file")),
3168 OPT_BOOL(0, "local", &local,
3169 N_("ignore borrowed objects from alternate object store")),
3170 OPT_BOOL(0, "incremental", &incremental,
3171 N_("ignore packed objects")),
3172 OPT_INTEGER(0, "window", &window,
3173 N_("limit pack window by objects")),
3174 OPT_MAGNITUDE(0, "window-memory", &window_memory_limit,
3175 N_("limit pack window by memory in addition to object limit")),
3176 OPT_INTEGER(0, "depth", &depth,
3177 N_("maximum length of delta chain allowed in the resulting pack")),
3178 OPT_BOOL(0, "reuse-delta", &reuse_delta,
3179 N_("reuse existing deltas")),
3180 OPT_BOOL(0, "reuse-object", &reuse_object,
3181 N_("reuse existing objects")),
3182 OPT_BOOL(0, "delta-base-offset", &allow_ofs_delta,
3183 N_("use OFS_DELTA objects")),
3184 OPT_INTEGER(0, "threads", &delta_search_threads,
3185 N_("use threads when searching for best delta matches")),
3186 OPT_BOOL(0, "non-empty", &non_empty,
3187 N_("do not create an empty pack output")),
3188 OPT_BOOL(0, "revs", &use_internal_rev_list,
3189 N_("read revision arguments from standard input")),
3190 OPT_SET_INT_F(0, "unpacked", &rev_list_unpacked,
3191 N_("limit the objects to those that are not yet packed"),
3192 1, PARSE_OPT_NONEG),
3193 OPT_SET_INT_F(0, "all", &rev_list_all,
3194 N_("include objects reachable from any reference"),
3195 1, PARSE_OPT_NONEG),
3196 OPT_SET_INT_F(0, "reflog", &rev_list_reflog,
3197 N_("include objects referred by reflog entries"),
3198 1, PARSE_OPT_NONEG),
3199 OPT_SET_INT_F(0, "indexed-objects", &rev_list_index,
3200 N_("include objects referred to by the index"),
3201 1, PARSE_OPT_NONEG),
3202 OPT_BOOL(0, "stdout", &pack_to_stdout,
3203 N_("output pack to stdout")),
3204 OPT_BOOL(0, "include-tag", &include_tag,
3205 N_("include tag objects that refer to objects to be packed")),
3206 OPT_BOOL(0, "keep-unreachable", &keep_unreachable,
3207 N_("keep unreachable objects")),
3208 OPT_BOOL(0, "pack-loose-unreachable", &pack_loose_unreachable,
3209 N_("pack loose unreachable objects")),
3210 { OPTION_CALLBACK, 0, "unpack-unreachable", NULL, N_("time"),
3211 N_("unpack unreachable objects newer than <time>"),
3212 PARSE_OPT_OPTARG, option_parse_unpack_unreachable },
3213 OPT_BOOL(0, "thin", &thin,
3214 N_("create thin packs")),
3215 OPT_BOOL(0, "shallow", &shallow,
3216 N_("create packs suitable for shallow fetches")),
3217 OPT_BOOL(0, "honor-pack-keep", &ignore_packed_keep_on_disk,
3218 N_("ignore packs that have companion .keep file")),
3219 OPT_STRING_LIST(0, "keep-pack", &keep_pack_list, N_("name"),
3220 N_("ignore this pack")),
3221 OPT_INTEGER(0, "compression", &pack_compression_level,
3222 N_("pack compression level")),
3223 OPT_SET_INT(0, "keep-true-parents", &grafts_replace_parents,
3224 N_("do not hide commits by grafts"), 0),
3225 OPT_BOOL(0, "use-bitmap-index", &use_bitmap_index,
3226 N_("use a bitmap index if available to speed up counting objects")),
3227 OPT_BOOL(0, "write-bitmap-index", &write_bitmap_index,
3228 N_("write a bitmap index together with the pack index")),
3229 OPT_PARSE_LIST_OBJECTS_FILTER(&filter_options),
3230 { OPTION_CALLBACK, 0, "missing", NULL, N_("action"),
3231 N_("handling for missing objects"), PARSE_OPT_NONEG,
3232 option_parse_missing_action },
3233 OPT_BOOL(0, "exclude-promisor-objects", &exclude_promisor_objects,
3234 N_("do not pack objects in promisor packfiles")),
3238 if (DFS_NUM_STATES > (1 << OE_DFS_STATE_BITS))
3239 BUG("too many dfs states, increase OE_DFS_STATE_BITS");
3241 read_replace_refs = 0;
3243 reset_pack_idx_option(&pack_idx_opts);
3244 git_config(git_pack_config, NULL);
3246 progress = isatty(2);
3247 argc = parse_options(argc, argv, prefix, pack_objects_options,
3251 base_name = argv[0];
3254 if (pack_to_stdout != !base_name || argc)
3255 usage_with_options(pack_usage, pack_objects_options);
3257 if (depth >= (1 << OE_DEPTH_BITS)) {
3258 warning(_("delta chain depth %d is too deep, forcing %d"),
3259 depth, (1 << OE_DEPTH_BITS) - 1);
3260 depth = (1 << OE_DEPTH_BITS) - 1;
3262 if (cache_max_small_delta_size >= (1U << OE_Z_DELTA_BITS)) {
3263 warning(_("pack.deltaCacheLimit is too high, forcing %d"),
3264 (1U << OE_Z_DELTA_BITS) - 1);
3265 cache_max_small_delta_size = (1U << OE_Z_DELTA_BITS) - 1;
3268 argv_array_push(&rp, "pack-objects");
3270 use_internal_rev_list = 1;
3271 argv_array_push(&rp, shallow
3272 ? "--objects-edge-aggressive"
3273 : "--objects-edge");
3275 argv_array_push(&rp, "--objects");
3278 use_internal_rev_list = 1;
3279 argv_array_push(&rp, "--all");
3281 if (rev_list_reflog) {
3282 use_internal_rev_list = 1;
3283 argv_array_push(&rp, "--reflog");
3285 if (rev_list_index) {
3286 use_internal_rev_list = 1;
3287 argv_array_push(&rp, "--indexed-objects");
3289 if (rev_list_unpacked) {
3290 use_internal_rev_list = 1;
3291 argv_array_push(&rp, "--unpacked");
3294 if (exclude_promisor_objects) {
3295 use_internal_rev_list = 1;
3296 fetch_if_missing = 0;
3297 argv_array_push(&rp, "--exclude-promisor-objects");
3299 if (unpack_unreachable || keep_unreachable || pack_loose_unreachable)
3300 use_internal_rev_list = 1;
3304 if (pack_compression_level == -1)
3305 pack_compression_level = Z_DEFAULT_COMPRESSION;
3306 else if (pack_compression_level < 0 || pack_compression_level > Z_BEST_COMPRESSION)
3307 die(_("bad pack compression level %d"), pack_compression_level);
3309 if (!delta_search_threads) /* --threads=0 means autodetect */
3310 delta_search_threads = online_cpus();
3313 if (delta_search_threads != 1)
3314 warning(_("no threads support, ignoring --threads"));
3316 if (!pack_to_stdout && !pack_size_limit)
3317 pack_size_limit = pack_size_limit_cfg;
3318 if (pack_to_stdout && pack_size_limit)
3319 die(_("--max-pack-size cannot be used to build a pack for transfer"));
3320 if (pack_size_limit && pack_size_limit < 1024*1024) {
3321 warning(_("minimum pack size limit is 1 MiB"));
3322 pack_size_limit = 1024*1024;
3325 if (!pack_to_stdout && thin)
3326 die(_("--thin cannot be used to build an indexable pack"));
3328 if (keep_unreachable && unpack_unreachable)
3329 die(_("--keep-unreachable and --unpack-unreachable are incompatible"));
3330 if (!rev_list_all || !rev_list_reflog || !rev_list_index)
3331 unpack_unreachable_expiration = 0;
3333 if (filter_options.choice) {
3334 if (!pack_to_stdout)
3335 die(_("cannot use --filter without --stdout"));
3336 use_bitmap_index = 0;
3340 * "soft" reasons not to use bitmaps - for on-disk repack by default we want
3342 * - to produce good pack (with bitmap index not-yet-packed objects are
3343 * packed in suboptimal order).
3345 * - to use more robust pack-generation codepath (avoiding possible
3346 * bugs in bitmap code and possible bitmap index corruption).
3348 if (!pack_to_stdout)
3349 use_bitmap_index_default = 0;
3351 if (use_bitmap_index < 0)
3352 use_bitmap_index = use_bitmap_index_default;
3354 /* "hard" reasons not to use bitmaps; these just won't work at all */
3355 if (!use_internal_rev_list || (!pack_to_stdout && write_bitmap_index) || is_repository_shallow(the_repository))
3356 use_bitmap_index = 0;
3358 if (pack_to_stdout || !rev_list_all)
3359 write_bitmap_index = 0;
3361 if (progress && all_progress_implied)
3364 add_extra_kept_packs(&keep_pack_list);
3365 if (ignore_packed_keep_on_disk) {
3366 struct packed_git *p;
3367 for (p = get_all_packs(the_repository); p; p = p->next)
3368 if (p->pack_local && p->pack_keep)
3370 if (!p) /* no keep-able packs found */
3371 ignore_packed_keep_on_disk = 0;
3375 * unlike ignore_packed_keep_on_disk above, we do not
3376 * want to unset "local" based on looking at packs, as
3377 * it also covers non-local objects
3379 struct packed_git *p;
3380 for (p = get_all_packs(the_repository); p; p = p->next) {
3381 if (!p->pack_local) {
3382 have_non_local_packs = 1;
3388 prepare_packing_data(&to_pack);
3391 progress_state = start_progress(_("Enumerating objects"), 0);
3392 if (!use_internal_rev_list)
3393 read_object_list_from_stdin();
3395 get_object_list(rp.argc, rp.argv);
3396 argv_array_clear(&rp);
3398 cleanup_preferred_base();
3399 if (include_tag && nr_result)
3400 for_each_ref(add_ref_tag, NULL);
3401 stop_progress(&progress_state);
3403 if (non_empty && !nr_result)
3406 prepare_pack(window, depth);
3410 _("Total %"PRIu32" (delta %"PRIu32"),"
3411 " reused %"PRIu32" (delta %"PRIu32")"),
3412 written, written_delta, reused, reused_delta);