3 #include "repository.h"
13 #include "pack-revindex.h"
14 #include "csum-file.h"
15 #include "tree-walk.h"
18 #include "list-objects.h"
19 #include "list-objects-filter.h"
20 #include "list-objects-filter-options.h"
21 #include "pack-objects.h"
24 #include "streaming.h"
25 #include "thread-utils.h"
26 #include "pack-bitmap.h"
27 #include "delta-islands.h"
28 #include "reachable.h"
29 #include "sha1-array.h"
30 #include "argv-array.h"
33 #include "object-store.h"
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;
63 static uint32_t write_layer;
66 static int reuse_delta = 1, reuse_object = 1;
67 static int keep_unreachable, unpack_unreachable, include_tag;
68 static timestamp_t unpack_unreachable_expiration;
69 static int pack_loose_unreachable;
71 static int have_non_local_packs;
72 static int incremental;
73 static int ignore_packed_keep_on_disk;
74 static int ignore_packed_keep_in_core;
75 static int allow_ofs_delta;
76 static struct pack_idx_option pack_idx_opts;
77 static const char *base_name;
78 static int progress = 1;
79 static int window = 10;
80 static unsigned long pack_size_limit;
81 static int depth = 50;
82 static int delta_search_threads;
83 static int pack_to_stdout;
84 static int num_preferred_base;
85 static struct progress *progress_state;
87 static struct packed_git *reuse_packfile;
88 static uint32_t reuse_packfile_objects;
89 static off_t reuse_packfile_offset;
91 static int use_bitmap_index_default = 1;
92 static int use_bitmap_index = -1;
93 static int write_bitmap_index;
94 static uint16_t write_bitmap_options;
96 static int exclude_promisor_objects;
98 static int use_delta_islands;
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);
155 if (!delta_buf || delta_size != DELTA_SIZE(entry))
156 die("delta size changed");
162 static unsigned long do_compress(void **pptr, unsigned long size)
166 unsigned long maxsize;
168 git_deflate_init(&stream, pack_compression_level);
169 maxsize = git_deflate_bound(&stream, size);
172 out = xmalloc(maxsize);
176 stream.avail_in = size;
177 stream.next_out = out;
178 stream.avail_out = maxsize;
179 while (git_deflate(&stream, Z_FINISH) == Z_OK)
181 git_deflate_end(&stream);
184 return stream.total_out;
187 static unsigned long write_large_blob_data(struct git_istream *st, struct hashfile *f,
188 const struct object_id *oid)
191 unsigned char ibuf[1024 * 16];
192 unsigned char obuf[1024 * 16];
193 unsigned long olen = 0;
195 git_deflate_init(&stream, pack_compression_level);
200 readlen = read_istream(st, ibuf, sizeof(ibuf));
202 die(_("unable to read %s"), oid_to_hex(oid));
204 stream.next_in = ibuf;
205 stream.avail_in = readlen;
206 while ((stream.avail_in || readlen == 0) &&
207 (zret == Z_OK || zret == Z_BUF_ERROR)) {
208 stream.next_out = obuf;
209 stream.avail_out = sizeof(obuf);
210 zret = git_deflate(&stream, readlen ? 0 : Z_FINISH);
211 hashwrite(f, obuf, stream.next_out - obuf);
212 olen += stream.next_out - obuf;
215 die(_("deflate error (%d)"), zret);
217 if (zret != Z_STREAM_END)
218 die(_("deflate error (%d)"), zret);
222 git_deflate_end(&stream);
227 * we are going to reuse the existing object data as is. make
228 * sure it is not corrupt.
230 static int check_pack_inflate(struct packed_git *p,
231 struct pack_window **w_curs,
234 unsigned long expect)
237 unsigned char fakebuf[4096], *in;
240 memset(&stream, 0, sizeof(stream));
241 git_inflate_init(&stream);
243 in = use_pack(p, w_curs, offset, &stream.avail_in);
245 stream.next_out = fakebuf;
246 stream.avail_out = sizeof(fakebuf);
247 st = git_inflate(&stream, Z_FINISH);
248 offset += stream.next_in - in;
249 } while (st == Z_OK || st == Z_BUF_ERROR);
250 git_inflate_end(&stream);
251 return (st == Z_STREAM_END &&
252 stream.total_out == expect &&
253 stream.total_in == len) ? 0 : -1;
256 static void copy_pack_data(struct hashfile *f,
257 struct packed_git *p,
258 struct pack_window **w_curs,
266 in = use_pack(p, w_curs, offset, &avail);
268 avail = (unsigned long)len;
269 hashwrite(f, in, avail);
275 /* Return 0 if we will bust the pack-size limit */
276 static unsigned long write_no_reuse_object(struct hashfile *f, struct object_entry *entry,
277 unsigned long limit, int usable_delta)
279 unsigned long size, datalen;
280 unsigned char header[MAX_PACK_OBJECT_HEADER],
281 dheader[MAX_PACK_OBJECT_HEADER];
283 enum object_type type;
285 struct git_istream *st = NULL;
286 const unsigned hashsz = the_hash_algo->rawsz;
289 if (oe_type(entry) == OBJ_BLOB &&
290 oe_size_greater_than(&to_pack, entry, big_file_threshold) &&
291 (st = open_istream(&entry->idx.oid, &type, &size, NULL)) != NULL)
294 buf = read_object_file(&entry->idx.oid, &type, &size);
296 die(_("unable to read %s"),
297 oid_to_hex(&entry->idx.oid));
300 * make sure no cached delta data remains from a
301 * previous attempt before a pack split occurred.
303 FREE_AND_NULL(entry->delta_data);
304 entry->z_delta_size = 0;
305 } else if (entry->delta_data) {
306 size = DELTA_SIZE(entry);
307 buf = entry->delta_data;
308 entry->delta_data = NULL;
309 type = (allow_ofs_delta && DELTA(entry)->idx.offset) ?
310 OBJ_OFS_DELTA : OBJ_REF_DELTA;
312 buf = get_delta(entry);
313 size = DELTA_SIZE(entry);
314 type = (allow_ofs_delta && DELTA(entry)->idx.offset) ?
315 OBJ_OFS_DELTA : OBJ_REF_DELTA;
318 if (st) /* large blob case, just assume we don't compress well */
320 else if (entry->z_delta_size)
321 datalen = entry->z_delta_size;
323 datalen = do_compress(&buf, size);
326 * The object header is a byte of 'type' followed by zero or
327 * more bytes of length.
329 hdrlen = encode_in_pack_object_header(header, sizeof(header),
332 if (type == OBJ_OFS_DELTA) {
334 * Deltas with relative base contain an additional
335 * encoding of the relative offset for the delta
336 * base from this object's position in the pack.
338 off_t ofs = entry->idx.offset - DELTA(entry)->idx.offset;
339 unsigned pos = sizeof(dheader) - 1;
340 dheader[pos] = ofs & 127;
342 dheader[--pos] = 128 | (--ofs & 127);
343 if (limit && hdrlen + sizeof(dheader) - pos + datalen + hashsz >= limit) {
349 hashwrite(f, header, hdrlen);
350 hashwrite(f, dheader + pos, sizeof(dheader) - pos);
351 hdrlen += sizeof(dheader) - pos;
352 } else if (type == OBJ_REF_DELTA) {
354 * Deltas with a base reference contain
355 * additional bytes for the base object ID.
357 if (limit && hdrlen + hashsz + datalen + hashsz >= limit) {
363 hashwrite(f, header, hdrlen);
364 hashwrite(f, DELTA(entry)->idx.oid.hash, hashsz);
367 if (limit && hdrlen + datalen + hashsz >= limit) {
373 hashwrite(f, header, hdrlen);
376 datalen = write_large_blob_data(st, f, &entry->idx.oid);
379 hashwrite(f, buf, datalen);
383 return hdrlen + datalen;
386 /* Return 0 if we will bust the pack-size limit */
387 static off_t write_reuse_object(struct hashfile *f, struct object_entry *entry,
388 unsigned long limit, int usable_delta)
390 struct packed_git *p = IN_PACK(entry);
391 struct pack_window *w_curs = NULL;
392 struct revindex_entry *revidx;
394 enum object_type type = oe_type(entry);
396 unsigned char header[MAX_PACK_OBJECT_HEADER],
397 dheader[MAX_PACK_OBJECT_HEADER];
399 const unsigned hashsz = the_hash_algo->rawsz;
400 unsigned long entry_size = SIZE(entry);
403 type = (allow_ofs_delta && DELTA(entry)->idx.offset) ?
404 OBJ_OFS_DELTA : OBJ_REF_DELTA;
405 hdrlen = encode_in_pack_object_header(header, sizeof(header),
408 offset = entry->in_pack_offset;
409 revidx = find_pack_revindex(p, offset);
410 datalen = revidx[1].offset - offset;
411 if (!pack_to_stdout && p->index_version > 1 &&
412 check_pack_crc(p, &w_curs, offset, datalen, revidx->nr)) {
413 error("bad packed object CRC for %s",
414 oid_to_hex(&entry->idx.oid));
416 return write_no_reuse_object(f, entry, limit, usable_delta);
419 offset += entry->in_pack_header_size;
420 datalen -= entry->in_pack_header_size;
422 if (!pack_to_stdout && p->index_version == 1 &&
423 check_pack_inflate(p, &w_curs, offset, datalen, entry_size)) {
424 error("corrupt packed object for %s",
425 oid_to_hex(&entry->idx.oid));
427 return write_no_reuse_object(f, entry, limit, usable_delta);
430 if (type == OBJ_OFS_DELTA) {
431 off_t ofs = entry->idx.offset - DELTA(entry)->idx.offset;
432 unsigned pos = sizeof(dheader) - 1;
433 dheader[pos] = ofs & 127;
435 dheader[--pos] = 128 | (--ofs & 127);
436 if (limit && hdrlen + sizeof(dheader) - pos + datalen + hashsz >= limit) {
440 hashwrite(f, header, hdrlen);
441 hashwrite(f, dheader + pos, sizeof(dheader) - pos);
442 hdrlen += sizeof(dheader) - pos;
444 } else if (type == OBJ_REF_DELTA) {
445 if (limit && hdrlen + hashsz + datalen + hashsz >= limit) {
449 hashwrite(f, header, hdrlen);
450 hashwrite(f, DELTA(entry)->idx.oid.hash, hashsz);
454 if (limit && hdrlen + datalen + hashsz >= limit) {
458 hashwrite(f, header, hdrlen);
460 copy_pack_data(f, p, &w_curs, offset, datalen);
463 return hdrlen + datalen;
466 /* Return 0 if we will bust the pack-size limit */
467 static off_t write_object(struct hashfile *f,
468 struct object_entry *entry,
473 int usable_delta, to_reuse;
478 /* apply size limit if limited packsize and not first object */
479 if (!pack_size_limit || !nr_written)
481 else if (pack_size_limit <= write_offset)
483 * the earlier object did not fit the limit; avoid
484 * mistaking this with unlimited (i.e. limit = 0).
488 limit = pack_size_limit - write_offset;
491 usable_delta = 0; /* no delta */
492 else if (!pack_size_limit)
493 usable_delta = 1; /* unlimited packfile */
494 else if (DELTA(entry)->idx.offset == (off_t)-1)
495 usable_delta = 0; /* base was written to another pack */
496 else if (DELTA(entry)->idx.offset)
497 usable_delta = 1; /* base already exists in this pack */
499 usable_delta = 0; /* base could end up in another pack */
502 to_reuse = 0; /* explicit */
503 else if (!IN_PACK(entry))
504 to_reuse = 0; /* can't reuse what we don't have */
505 else if (oe_type(entry) == OBJ_REF_DELTA ||
506 oe_type(entry) == OBJ_OFS_DELTA)
507 /* check_object() decided it for us ... */
508 to_reuse = usable_delta;
509 /* ... but pack split may override that */
510 else if (oe_type(entry) != entry->in_pack_type)
511 to_reuse = 0; /* pack has delta which is unusable */
512 else if (DELTA(entry))
513 to_reuse = 0; /* we want to pack afresh */
515 to_reuse = 1; /* we have it in-pack undeltified,
516 * and we do not need to deltify it.
520 len = write_no_reuse_object(f, entry, limit, usable_delta);
522 len = write_reuse_object(f, entry, limit, usable_delta);
530 entry->idx.crc32 = crc32_end(f);
534 enum write_one_status {
535 WRITE_ONE_SKIP = -1, /* already written */
536 WRITE_ONE_BREAK = 0, /* writing this will bust the limit; not written */
537 WRITE_ONE_WRITTEN = 1, /* normal */
538 WRITE_ONE_RECURSIVE = 2 /* already scheduled to be written */
541 static enum write_one_status write_one(struct hashfile *f,
542 struct object_entry *e,
549 * we set offset to 1 (which is an impossible value) to mark
550 * the fact that this object is involved in "write its base
551 * first before writing a deltified object" recursion.
553 recursing = (e->idx.offset == 1);
555 warning("recursive delta detected for object %s",
556 oid_to_hex(&e->idx.oid));
557 return WRITE_ONE_RECURSIVE;
558 } else if (e->idx.offset || e->preferred_base) {
559 /* offset is non zero if object is written already. */
560 return WRITE_ONE_SKIP;
563 /* if we are deltified, write out base object first. */
565 e->idx.offset = 1; /* now recurse */
566 switch (write_one(f, DELTA(e), offset)) {
567 case WRITE_ONE_RECURSIVE:
568 /* we cannot depend on this one */
573 case WRITE_ONE_BREAK:
574 e->idx.offset = recursing;
575 return WRITE_ONE_BREAK;
579 e->idx.offset = *offset;
580 size = write_object(f, e, *offset);
582 e->idx.offset = recursing;
583 return WRITE_ONE_BREAK;
585 written_list[nr_written++] = &e->idx;
587 /* make sure off_t is sufficiently large not to wrap */
588 if (signed_add_overflows(*offset, size))
589 die("pack too large for current definition of off_t");
591 return WRITE_ONE_WRITTEN;
594 static int mark_tagged(const char *path, const struct object_id *oid, int flag,
597 struct object_id peeled;
598 struct object_entry *entry = packlist_find(&to_pack, oid->hash, NULL);
602 if (!peel_ref(path, &peeled)) {
603 entry = packlist_find(&to_pack, peeled.hash, NULL);
610 static inline void add_to_write_order(struct object_entry **wo,
612 struct object_entry *e)
614 if (e->filled || e->layer != write_layer)
620 static void add_descendants_to_write_order(struct object_entry **wo,
622 struct object_entry *e)
624 int add_to_order = 1;
627 struct object_entry *s;
628 /* add this node... */
629 add_to_write_order(wo, endp, e);
630 /* all its siblings... */
631 for (s = DELTA_SIBLING(e); s; s = DELTA_SIBLING(s)) {
632 add_to_write_order(wo, endp, s);
635 /* drop down a level to add left subtree nodes if possible */
636 if (DELTA_CHILD(e)) {
641 /* our sibling might have some children, it is next */
642 if (DELTA_SIBLING(e)) {
643 e = DELTA_SIBLING(e);
646 /* go back to our parent node */
648 while (e && !DELTA_SIBLING(e)) {
649 /* we're on the right side of a subtree, keep
650 * going up until we can go right again */
654 /* done- we hit our original root node */
657 /* pass it off to sibling at this level */
658 e = DELTA_SIBLING(e);
663 static void add_family_to_write_order(struct object_entry **wo,
665 struct object_entry *e)
667 struct object_entry *root;
669 for (root = e; DELTA(root); root = DELTA(root))
671 add_descendants_to_write_order(wo, endp, root);
674 static void compute_layer_order(struct object_entry **wo, unsigned int *wo_end)
676 unsigned int i, last_untagged;
677 struct object_entry *objects = to_pack.objects;
679 for (i = 0; i < to_pack.nr_objects; i++) {
680 if (objects[i].tagged)
682 add_to_write_order(wo, wo_end, &objects[i]);
687 * Then fill all the tagged tips.
689 for (; i < to_pack.nr_objects; i++) {
690 if (objects[i].tagged)
691 add_to_write_order(wo, wo_end, &objects[i]);
695 * And then all remaining commits and tags.
697 for (i = last_untagged; i < to_pack.nr_objects; i++) {
698 if (oe_type(&objects[i]) != OBJ_COMMIT &&
699 oe_type(&objects[i]) != OBJ_TAG)
701 add_to_write_order(wo, wo_end, &objects[i]);
705 * And then all the trees.
707 for (i = last_untagged; i < to_pack.nr_objects; i++) {
708 if (oe_type(&objects[i]) != OBJ_TREE)
710 add_to_write_order(wo, wo_end, &objects[i]);
714 * Finally all the rest in really tight order
716 for (i = last_untagged; i < to_pack.nr_objects; i++) {
717 if (!objects[i].filled && objects[i].layer == write_layer)
718 add_family_to_write_order(wo, wo_end, &objects[i]);
722 static struct object_entry **compute_write_order(void)
724 uint32_t max_layers = 1;
725 unsigned int i, wo_end;
727 struct object_entry **wo;
728 struct object_entry *objects = to_pack.objects;
730 for (i = 0; i < to_pack.nr_objects; i++) {
731 objects[i].tagged = 0;
732 objects[i].filled = 0;
733 SET_DELTA_CHILD(&objects[i], NULL);
734 SET_DELTA_SIBLING(&objects[i], NULL);
738 * Fully connect delta_child/delta_sibling network.
739 * Make sure delta_sibling is sorted in the original
742 for (i = to_pack.nr_objects; i > 0;) {
743 struct object_entry *e = &objects[--i];
746 /* Mark me as the first child */
747 e->delta_sibling_idx = DELTA(e)->delta_child_idx;
748 SET_DELTA_CHILD(DELTA(e), e);
752 * Mark objects that are at the tip of tags.
754 for_each_tag_ref(mark_tagged, NULL);
756 if (use_delta_islands)
757 max_layers = compute_pack_layers(&to_pack);
759 ALLOC_ARRAY(wo, to_pack.nr_objects);
762 for (; write_layer < max_layers; ++write_layer)
763 compute_layer_order(wo, &wo_end);
765 if (wo_end != to_pack.nr_objects)
766 die("ordered %u objects, expected %"PRIu32, wo_end, to_pack.nr_objects);
771 static off_t write_reused_pack(struct hashfile *f)
773 unsigned char buffer[8192];
774 off_t to_write, total;
777 if (!is_pack_valid(reuse_packfile))
778 die("packfile is invalid: %s", reuse_packfile->pack_name);
780 fd = git_open(reuse_packfile->pack_name);
782 die_errno("unable to open packfile for reuse: %s",
783 reuse_packfile->pack_name);
785 if (lseek(fd, sizeof(struct pack_header), SEEK_SET) == -1)
786 die_errno("unable to seek in reused packfile");
788 if (reuse_packfile_offset < 0)
789 reuse_packfile_offset = reuse_packfile->pack_size - the_hash_algo->rawsz;
791 total = to_write = reuse_packfile_offset - sizeof(struct pack_header);
794 int read_pack = xread(fd, buffer, sizeof(buffer));
797 die_errno("unable to read from reused packfile");
799 if (read_pack > to_write)
800 read_pack = to_write;
802 hashwrite(f, buffer, read_pack);
803 to_write -= read_pack;
806 * We don't know the actual number of objects written,
807 * only how many bytes written, how many bytes total, and
808 * how many objects total. So we can fake it by pretending all
809 * objects we are writing are the same size. This gives us a
810 * smooth progress meter, and at the end it matches the true
813 written = reuse_packfile_objects *
814 (((double)(total - to_write)) / total);
815 display_progress(progress_state, written);
819 written = reuse_packfile_objects;
820 display_progress(progress_state, written);
821 return reuse_packfile_offset - sizeof(struct pack_header);
824 static const char no_split_warning[] = N_(
825 "disabling bitmap writing, packs are split due to pack.packSizeLimit"
828 static void write_pack_file(void)
833 uint32_t nr_remaining = nr_result;
834 time_t last_mtime = 0;
835 struct object_entry **write_order;
837 if (progress > pack_to_stdout)
838 progress_state = start_progress(_("Writing objects"), nr_result);
839 ALLOC_ARRAY(written_list, to_pack.nr_objects);
840 write_order = compute_write_order();
843 struct object_id oid;
844 char *pack_tmp_name = NULL;
847 f = hashfd_throughput(1, "<stdout>", progress_state);
849 f = create_tmp_packfile(&pack_tmp_name);
851 offset = write_pack_header(f, nr_remaining);
853 if (reuse_packfile) {
855 assert(pack_to_stdout);
857 packfile_size = write_reused_pack(f);
858 offset += packfile_size;
862 for (; i < to_pack.nr_objects; i++) {
863 struct object_entry *e = write_order[i];
864 if (write_one(f, e, &offset) == WRITE_ONE_BREAK)
866 display_progress(progress_state, written);
870 * Did we write the wrong # entries in the header?
871 * If so, rewrite it like in fast-import
873 if (pack_to_stdout) {
874 finalize_hashfile(f, oid.hash, CSUM_HASH_IN_STREAM | CSUM_CLOSE);
875 } else if (nr_written == nr_remaining) {
876 finalize_hashfile(f, oid.hash, CSUM_HASH_IN_STREAM | CSUM_FSYNC | CSUM_CLOSE);
878 int fd = finalize_hashfile(f, oid.hash, 0);
879 fixup_pack_header_footer(fd, oid.hash, pack_tmp_name,
880 nr_written, oid.hash, offset);
882 if (write_bitmap_index) {
883 warning(_(no_split_warning));
884 write_bitmap_index = 0;
888 if (!pack_to_stdout) {
890 struct strbuf tmpname = STRBUF_INIT;
893 * Packs are runtime accessed in their mtime
894 * order since newer packs are more likely to contain
895 * younger objects. So if we are creating multiple
896 * packs then we should modify the mtime of later ones
897 * to preserve this property.
899 if (stat(pack_tmp_name, &st) < 0) {
900 warning_errno("failed to stat %s", pack_tmp_name);
901 } else if (!last_mtime) {
902 last_mtime = st.st_mtime;
905 utb.actime = st.st_atime;
906 utb.modtime = --last_mtime;
907 if (utime(pack_tmp_name, &utb) < 0)
908 warning_errno("failed utime() on %s", pack_tmp_name);
911 strbuf_addf(&tmpname, "%s-", base_name);
913 if (write_bitmap_index) {
914 bitmap_writer_set_checksum(oid.hash);
915 bitmap_writer_build_type_index(
916 &to_pack, written_list, nr_written);
919 finish_tmp_packfile(&tmpname, pack_tmp_name,
920 written_list, nr_written,
921 &pack_idx_opts, oid.hash);
923 if (write_bitmap_index) {
924 strbuf_addf(&tmpname, "%s.bitmap", oid_to_hex(&oid));
926 stop_progress(&progress_state);
928 bitmap_writer_show_progress(progress);
929 bitmap_writer_reuse_bitmaps(&to_pack);
930 bitmap_writer_select_commits(indexed_commits, indexed_commits_nr, -1);
931 bitmap_writer_build(&to_pack);
932 bitmap_writer_finish(written_list, nr_written,
933 tmpname.buf, write_bitmap_options);
934 write_bitmap_index = 0;
937 strbuf_release(&tmpname);
939 puts(oid_to_hex(&oid));
942 /* mark written objects as written to previous pack */
943 for (j = 0; j < nr_written; j++) {
944 written_list[j]->offset = (off_t)-1;
946 nr_remaining -= nr_written;
947 } while (nr_remaining && i < to_pack.nr_objects);
951 stop_progress(&progress_state);
952 if (written != nr_result)
953 die("wrote %"PRIu32" objects while expecting %"PRIu32,
957 static int no_try_delta(const char *path)
959 static struct attr_check *check;
962 check = attr_check_initl("delta", NULL);
963 if (git_check_attr(path, check))
965 if (ATTR_FALSE(check->items[0].value))
971 * When adding an object, check whether we have already added it
972 * to our packing list. If so, we can skip. However, if we are
973 * being asked to excludei t, but the previous mention was to include
974 * it, make sure to adjust its flags and tweak our numbers accordingly.
976 * As an optimization, we pass out the index position where we would have
977 * found the item, since that saves us from having to look it up again a
978 * few lines later when we want to add the new entry.
980 static int have_duplicate_entry(const struct object_id *oid,
984 struct object_entry *entry;
986 entry = packlist_find(&to_pack, oid->hash, index_pos);
991 if (!entry->preferred_base)
993 entry->preferred_base = 1;
999 static int want_found_object(int exclude, struct packed_git *p)
1007 * When asked to do --local (do not include an object that appears in a
1008 * pack we borrow from elsewhere) or --honor-pack-keep (do not include
1009 * an object that appears in a pack marked with .keep), finding a pack
1010 * that matches the criteria is sufficient for us to decide to omit it.
1011 * However, even if this pack does not satisfy the criteria, we need to
1012 * make sure no copy of this object appears in _any_ pack that makes us
1013 * to omit the object, so we need to check all the packs.
1015 * We can however first check whether these options can possible matter;
1016 * if they do not matter we know we want the object in generated pack.
1017 * Otherwise, we signal "-1" at the end to tell the caller that we do
1018 * not know either way, and it needs to check more packs.
1020 if (!ignore_packed_keep_on_disk &&
1021 !ignore_packed_keep_in_core &&
1022 (!local || !have_non_local_packs))
1025 if (local && !p->pack_local)
1027 if (p->pack_local &&
1028 ((ignore_packed_keep_on_disk && p->pack_keep) ||
1029 (ignore_packed_keep_in_core && p->pack_keep_in_core)))
1032 /* we don't know yet; keep looking for more packs */
1037 * Check whether we want the object in the pack (e.g., we do not want
1038 * objects found in non-local stores if the "--local" option was used).
1040 * If the caller already knows an existing pack it wants to take the object
1041 * from, that is passed in *found_pack and *found_offset; otherwise this
1042 * function finds if there is any pack that has the object and returns the pack
1043 * and its offset in these variables.
1045 static int want_object_in_pack(const struct object_id *oid,
1047 struct packed_git **found_pack,
1048 off_t *found_offset)
1051 struct list_head *pos;
1053 if (!exclude && local && has_loose_object_nonlocal(oid))
1057 * If we already know the pack object lives in, start checks from that
1058 * pack - in the usual case when neither --local was given nor .keep files
1059 * are present we will determine the answer right now.
1062 want = want_found_object(exclude, *found_pack);
1066 list_for_each(pos, get_packed_git_mru(the_repository)) {
1067 struct packed_git *p = list_entry(pos, struct packed_git, mru);
1070 if (p == *found_pack)
1071 offset = *found_offset;
1073 offset = find_pack_entry_one(oid->hash, p);
1077 if (!is_pack_valid(p))
1079 *found_offset = offset;
1082 want = want_found_object(exclude, p);
1083 if (!exclude && want > 0)
1085 get_packed_git_mru(the_repository));
1094 static void create_object_entry(const struct object_id *oid,
1095 enum object_type type,
1100 struct packed_git *found_pack,
1103 struct object_entry *entry;
1105 entry = packlist_alloc(&to_pack, oid->hash, index_pos);
1107 oe_set_type(entry, type);
1109 entry->preferred_base = 1;
1113 oe_set_in_pack(&to_pack, entry, found_pack);
1114 entry->in_pack_offset = found_offset;
1117 entry->no_try_delta = no_try_delta;
1120 static const char no_closure_warning[] = N_(
1121 "disabling bitmap writing, as some objects are not being packed"
1124 static int add_object_entry(const struct object_id *oid, enum object_type type,
1125 const char *name, int exclude)
1127 struct packed_git *found_pack = NULL;
1128 off_t found_offset = 0;
1131 display_progress(progress_state, ++nr_seen);
1133 if (have_duplicate_entry(oid, exclude, &index_pos))
1136 if (!want_object_in_pack(oid, exclude, &found_pack, &found_offset)) {
1137 /* The pack is missing an object, so it will not have closure */
1138 if (write_bitmap_index) {
1139 warning(_(no_closure_warning));
1140 write_bitmap_index = 0;
1145 create_object_entry(oid, type, pack_name_hash(name),
1146 exclude, name && no_try_delta(name),
1147 index_pos, found_pack, found_offset);
1151 static int add_object_entry_from_bitmap(const struct object_id *oid,
1152 enum object_type type,
1153 int flags, uint32_t name_hash,
1154 struct packed_git *pack, off_t offset)
1158 display_progress(progress_state, ++nr_seen);
1160 if (have_duplicate_entry(oid, 0, &index_pos))
1163 if (!want_object_in_pack(oid, 0, &pack, &offset))
1166 create_object_entry(oid, type, name_hash, 0, 0, index_pos, pack, offset);
1170 struct pbase_tree_cache {
1171 struct object_id oid;
1175 unsigned long tree_size;
1178 static struct pbase_tree_cache *(pbase_tree_cache[256]);
1179 static int pbase_tree_cache_ix(const struct object_id *oid)
1181 return oid->hash[0] % ARRAY_SIZE(pbase_tree_cache);
1183 static int pbase_tree_cache_ix_incr(int ix)
1185 return (ix+1) % ARRAY_SIZE(pbase_tree_cache);
1188 static struct pbase_tree {
1189 struct pbase_tree *next;
1190 /* This is a phony "cache" entry; we are not
1191 * going to evict it or find it through _get()
1192 * mechanism -- this is for the toplevel node that
1193 * would almost always change with any commit.
1195 struct pbase_tree_cache pcache;
1198 static struct pbase_tree_cache *pbase_tree_get(const struct object_id *oid)
1200 struct pbase_tree_cache *ent, *nent;
1203 enum object_type type;
1205 int my_ix = pbase_tree_cache_ix(oid);
1206 int available_ix = -1;
1208 /* pbase-tree-cache acts as a limited hashtable.
1209 * your object will be found at your index or within a few
1210 * slots after that slot if it is cached.
1212 for (neigh = 0; neigh < 8; neigh++) {
1213 ent = pbase_tree_cache[my_ix];
1214 if (ent && !oidcmp(&ent->oid, oid)) {
1218 else if (((available_ix < 0) && (!ent || !ent->ref)) ||
1219 ((0 <= available_ix) &&
1220 (!ent && pbase_tree_cache[available_ix])))
1221 available_ix = my_ix;
1224 my_ix = pbase_tree_cache_ix_incr(my_ix);
1227 /* Did not find one. Either we got a bogus request or
1228 * we need to read and perhaps cache.
1230 data = read_object_file(oid, &type, &size);
1233 if (type != OBJ_TREE) {
1238 /* We need to either cache or return a throwaway copy */
1240 if (available_ix < 0)
1243 ent = pbase_tree_cache[available_ix];
1244 my_ix = available_ix;
1248 nent = xmalloc(sizeof(*nent));
1249 nent->temporary = (available_ix < 0);
1252 /* evict and reuse */
1253 free(ent->tree_data);
1256 oidcpy(&nent->oid, oid);
1257 nent->tree_data = data;
1258 nent->tree_size = size;
1260 if (!nent->temporary)
1261 pbase_tree_cache[my_ix] = nent;
1265 static void pbase_tree_put(struct pbase_tree_cache *cache)
1267 if (!cache->temporary) {
1271 free(cache->tree_data);
1275 static int name_cmp_len(const char *name)
1278 for (i = 0; name[i] && name[i] != '\n' && name[i] != '/'; i++)
1283 static void add_pbase_object(struct tree_desc *tree,
1286 const char *fullname)
1288 struct name_entry entry;
1291 while (tree_entry(tree,&entry)) {
1292 if (S_ISGITLINK(entry.mode))
1294 cmp = tree_entry_len(&entry) != cmplen ? 1 :
1295 memcmp(name, entry.path, cmplen);
1300 if (name[cmplen] != '/') {
1301 add_object_entry(entry.oid,
1302 object_type(entry.mode),
1306 if (S_ISDIR(entry.mode)) {
1307 struct tree_desc sub;
1308 struct pbase_tree_cache *tree;
1309 const char *down = name+cmplen+1;
1310 int downlen = name_cmp_len(down);
1312 tree = pbase_tree_get(entry.oid);
1315 init_tree_desc(&sub, tree->tree_data, tree->tree_size);
1317 add_pbase_object(&sub, down, downlen, fullname);
1318 pbase_tree_put(tree);
1323 static unsigned *done_pbase_paths;
1324 static int done_pbase_paths_num;
1325 static int done_pbase_paths_alloc;
1326 static int done_pbase_path_pos(unsigned hash)
1329 int hi = done_pbase_paths_num;
1331 int mi = lo + (hi - lo) / 2;
1332 if (done_pbase_paths[mi] == hash)
1334 if (done_pbase_paths[mi] < hash)
1342 static int check_pbase_path(unsigned hash)
1344 int pos = done_pbase_path_pos(hash);
1348 ALLOC_GROW(done_pbase_paths,
1349 done_pbase_paths_num + 1,
1350 done_pbase_paths_alloc);
1351 done_pbase_paths_num++;
1352 if (pos < done_pbase_paths_num)
1353 MOVE_ARRAY(done_pbase_paths + pos + 1, done_pbase_paths + pos,
1354 done_pbase_paths_num - pos - 1);
1355 done_pbase_paths[pos] = hash;
1359 static void add_preferred_base_object(const char *name)
1361 struct pbase_tree *it;
1363 unsigned hash = pack_name_hash(name);
1365 if (!num_preferred_base || check_pbase_path(hash))
1368 cmplen = name_cmp_len(name);
1369 for (it = pbase_tree; it; it = it->next) {
1371 add_object_entry(&it->pcache.oid, OBJ_TREE, NULL, 1);
1374 struct tree_desc tree;
1375 init_tree_desc(&tree, it->pcache.tree_data, it->pcache.tree_size);
1376 add_pbase_object(&tree, name, cmplen, name);
1381 static void add_preferred_base(struct object_id *oid)
1383 struct pbase_tree *it;
1386 struct object_id tree_oid;
1388 if (window <= num_preferred_base++)
1391 data = read_object_with_reference(oid, tree_type, &size, &tree_oid);
1395 for (it = pbase_tree; it; it = it->next) {
1396 if (!oidcmp(&it->pcache.oid, &tree_oid)) {
1402 it = xcalloc(1, sizeof(*it));
1403 it->next = pbase_tree;
1406 oidcpy(&it->pcache.oid, &tree_oid);
1407 it->pcache.tree_data = data;
1408 it->pcache.tree_size = size;
1411 static void cleanup_preferred_base(void)
1413 struct pbase_tree *it;
1419 struct pbase_tree *tmp = it;
1421 free(tmp->pcache.tree_data);
1425 for (i = 0; i < ARRAY_SIZE(pbase_tree_cache); i++) {
1426 if (!pbase_tree_cache[i])
1428 free(pbase_tree_cache[i]->tree_data);
1429 FREE_AND_NULL(pbase_tree_cache[i]);
1432 FREE_AND_NULL(done_pbase_paths);
1433 done_pbase_paths_num = done_pbase_paths_alloc = 0;
1436 static void check_object(struct object_entry *entry)
1438 unsigned long canonical_size;
1440 if (IN_PACK(entry)) {
1441 struct packed_git *p = IN_PACK(entry);
1442 struct pack_window *w_curs = NULL;
1443 const unsigned char *base_ref = NULL;
1444 struct object_entry *base_entry;
1445 unsigned long used, used_0;
1446 unsigned long avail;
1448 unsigned char *buf, c;
1449 enum object_type type;
1450 unsigned long in_pack_size;
1452 buf = use_pack(p, &w_curs, entry->in_pack_offset, &avail);
1455 * We want in_pack_type even if we do not reuse delta
1456 * since non-delta representations could still be reused.
1458 used = unpack_object_header_buffer(buf, avail,
1465 BUG("invalid type %d", type);
1466 entry->in_pack_type = type;
1469 * Determine if this is a delta and if so whether we can
1470 * reuse it or not. Otherwise let's find out as cheaply as
1471 * possible what the actual type and size for this object is.
1473 switch (entry->in_pack_type) {
1475 /* Not a delta hence we've already got all we need. */
1476 oe_set_type(entry, entry->in_pack_type);
1477 SET_SIZE(entry, in_pack_size);
1478 entry->in_pack_header_size = used;
1479 if (oe_type(entry) < OBJ_COMMIT || oe_type(entry) > OBJ_BLOB)
1481 unuse_pack(&w_curs);
1484 if (reuse_delta && !entry->preferred_base)
1485 base_ref = use_pack(p, &w_curs,
1486 entry->in_pack_offset + used, NULL);
1487 entry->in_pack_header_size = used + the_hash_algo->rawsz;
1490 buf = use_pack(p, &w_curs,
1491 entry->in_pack_offset + used, NULL);
1497 if (!ofs || MSB(ofs, 7)) {
1498 error("delta base offset overflow in pack for %s",
1499 oid_to_hex(&entry->idx.oid));
1503 ofs = (ofs << 7) + (c & 127);
1505 ofs = entry->in_pack_offset - ofs;
1506 if (ofs <= 0 || ofs >= entry->in_pack_offset) {
1507 error("delta base offset out of bound for %s",
1508 oid_to_hex(&entry->idx.oid));
1511 if (reuse_delta && !entry->preferred_base) {
1512 struct revindex_entry *revidx;
1513 revidx = find_pack_revindex(p, ofs);
1516 base_ref = nth_packed_object_sha1(p, revidx->nr);
1518 entry->in_pack_header_size = used + used_0;
1522 if (base_ref && (base_entry = packlist_find(&to_pack, base_ref, NULL)) &&
1523 in_same_island(&entry->idx.oid, &base_entry->idx.oid)) {
1525 * If base_ref was set above that means we wish to
1526 * reuse delta data, and we even found that base
1527 * in the list of objects we want to pack. Goodie!
1529 * Depth value does not matter - find_deltas() will
1530 * never consider reused delta as the base object to
1531 * deltify other objects against, in order to avoid
1534 oe_set_type(entry, entry->in_pack_type);
1535 SET_SIZE(entry, in_pack_size); /* delta size */
1536 SET_DELTA(entry, base_entry);
1537 SET_DELTA_SIZE(entry, in_pack_size);
1538 entry->delta_sibling_idx = base_entry->delta_child_idx;
1539 SET_DELTA_CHILD(base_entry, entry);
1540 unuse_pack(&w_curs);
1544 if (oe_type(entry)) {
1548 * This must be a delta and we already know what the
1549 * final object type is. Let's extract the actual
1550 * object size from the delta header.
1552 delta_pos = entry->in_pack_offset + entry->in_pack_header_size;
1553 canonical_size = get_size_from_delta(p, &w_curs, delta_pos);
1554 if (canonical_size == 0)
1556 SET_SIZE(entry, canonical_size);
1557 unuse_pack(&w_curs);
1562 * No choice but to fall back to the recursive delta walk
1563 * with sha1_object_info() to find about the object type
1567 unuse_pack(&w_curs);
1571 oid_object_info(the_repository, &entry->idx.oid, &canonical_size));
1572 if (entry->type_valid) {
1573 SET_SIZE(entry, canonical_size);
1576 * Bad object type is checked in prepare_pack(). This is
1577 * to permit a missing preferred base object to be ignored
1578 * as a preferred base. Doing so can result in a larger
1579 * pack file, but the transfer will still take place.
1584 static int pack_offset_sort(const void *_a, const void *_b)
1586 const struct object_entry *a = *(struct object_entry **)_a;
1587 const struct object_entry *b = *(struct object_entry **)_b;
1588 const struct packed_git *a_in_pack = IN_PACK(a);
1589 const struct packed_git *b_in_pack = IN_PACK(b);
1591 /* avoid filesystem trashing with loose objects */
1592 if (!a_in_pack && !b_in_pack)
1593 return oidcmp(&a->idx.oid, &b->idx.oid);
1595 if (a_in_pack < b_in_pack)
1597 if (a_in_pack > b_in_pack)
1599 return a->in_pack_offset < b->in_pack_offset ? -1 :
1600 (a->in_pack_offset > b->in_pack_offset);
1604 * Drop an on-disk delta we were planning to reuse. Naively, this would
1605 * just involve blanking out the "delta" field, but we have to deal
1606 * with some extra book-keeping:
1608 * 1. Removing ourselves from the delta_sibling linked list.
1610 * 2. Updating our size/type to the non-delta representation. These were
1611 * either not recorded initially (size) or overwritten with the delta type
1612 * (type) when check_object() decided to reuse the delta.
1614 * 3. Resetting our delta depth, as we are now a base object.
1616 static void drop_reused_delta(struct object_entry *entry)
1618 unsigned *idx = &to_pack.objects[entry->delta_idx - 1].delta_child_idx;
1619 struct object_info oi = OBJECT_INFO_INIT;
1620 enum object_type type;
1624 struct object_entry *oe = &to_pack.objects[*idx - 1];
1627 *idx = oe->delta_sibling_idx;
1629 idx = &oe->delta_sibling_idx;
1631 SET_DELTA(entry, NULL);
1636 if (packed_object_info(the_repository, IN_PACK(entry), entry->in_pack_offset, &oi) < 0) {
1638 * We failed to get the info from this pack for some reason;
1639 * fall back to sha1_object_info, which may find another copy.
1640 * And if that fails, the error will be recorded in oe_type(entry)
1641 * and dealt with in prepare_pack().
1644 oid_object_info(the_repository, &entry->idx.oid, &size));
1646 oe_set_type(entry, type);
1648 SET_SIZE(entry, size);
1652 * Follow the chain of deltas from this entry onward, throwing away any links
1653 * that cause us to hit a cycle (as determined by the DFS state flags in
1656 * We also detect too-long reused chains that would violate our --depth
1659 static void break_delta_chains(struct object_entry *entry)
1662 * The actual depth of each object we will write is stored as an int,
1663 * as it cannot exceed our int "depth" limit. But before we break
1664 * changes based no that limit, we may potentially go as deep as the
1665 * number of objects, which is elsewhere bounded to a uint32_t.
1667 uint32_t total_depth;
1668 struct object_entry *cur, *next;
1670 for (cur = entry, total_depth = 0;
1672 cur = DELTA(cur), total_depth++) {
1673 if (cur->dfs_state == DFS_DONE) {
1675 * We've already seen this object and know it isn't
1676 * part of a cycle. We do need to append its depth
1679 total_depth += cur->depth;
1684 * We break cycles before looping, so an ACTIVE state (or any
1685 * other cruft which made its way into the state variable)
1688 if (cur->dfs_state != DFS_NONE)
1689 BUG("confusing delta dfs state in first pass: %d",
1693 * Now we know this is the first time we've seen the object. If
1694 * it's not a delta, we're done traversing, but we'll mark it
1695 * done to save time on future traversals.
1698 cur->dfs_state = DFS_DONE;
1703 * Mark ourselves as active and see if the next step causes
1704 * us to cycle to another active object. It's important to do
1705 * this _before_ we loop, because it impacts where we make the
1706 * cut, and thus how our total_depth counter works.
1707 * E.g., We may see a partial loop like:
1709 * A -> B -> C -> D -> B
1711 * Cutting B->C breaks the cycle. But now the depth of A is
1712 * only 1, and our total_depth counter is at 3. The size of the
1713 * error is always one less than the size of the cycle we
1714 * broke. Commits C and D were "lost" from A's chain.
1716 * If we instead cut D->B, then the depth of A is correct at 3.
1717 * We keep all commits in the chain that we examined.
1719 cur->dfs_state = DFS_ACTIVE;
1720 if (DELTA(cur)->dfs_state == DFS_ACTIVE) {
1721 drop_reused_delta(cur);
1722 cur->dfs_state = DFS_DONE;
1728 * And now that we've gone all the way to the bottom of the chain, we
1729 * need to clear the active flags and set the depth fields as
1730 * appropriate. Unlike the loop above, which can quit when it drops a
1731 * delta, we need to keep going to look for more depth cuts. So we need
1732 * an extra "next" pointer to keep going after we reset cur->delta.
1734 for (cur = entry; cur; cur = next) {
1738 * We should have a chain of zero or more ACTIVE states down to
1739 * a final DONE. We can quit after the DONE, because either it
1740 * has no bases, or we've already handled them in a previous
1743 if (cur->dfs_state == DFS_DONE)
1745 else if (cur->dfs_state != DFS_ACTIVE)
1746 BUG("confusing delta dfs state in second pass: %d",
1750 * If the total_depth is more than depth, then we need to snip
1751 * the chain into two or more smaller chains that don't exceed
1752 * the maximum depth. Most of the resulting chains will contain
1753 * (depth + 1) entries (i.e., depth deltas plus one base), and
1754 * the last chain (i.e., the one containing entry) will contain
1755 * whatever entries are left over, namely
1756 * (total_depth % (depth + 1)) of them.
1758 * Since we are iterating towards decreasing depth, we need to
1759 * decrement total_depth as we go, and we need to write to the
1760 * entry what its final depth will be after all of the
1761 * snipping. Since we're snipping into chains of length (depth
1762 * + 1) entries, the final depth of an entry will be its
1763 * original depth modulo (depth + 1). Any time we encounter an
1764 * entry whose final depth is supposed to be zero, we snip it
1765 * from its delta base, thereby making it so.
1767 cur->depth = (total_depth--) % (depth + 1);
1769 drop_reused_delta(cur);
1771 cur->dfs_state = DFS_DONE;
1775 static void get_object_details(void)
1778 struct object_entry **sorted_by_offset;
1781 progress_state = start_progress(_("Counting objects"),
1782 to_pack.nr_objects);
1784 sorted_by_offset = xcalloc(to_pack.nr_objects, sizeof(struct object_entry *));
1785 for (i = 0; i < to_pack.nr_objects; i++)
1786 sorted_by_offset[i] = to_pack.objects + i;
1787 QSORT(sorted_by_offset, to_pack.nr_objects, pack_offset_sort);
1789 for (i = 0; i < to_pack.nr_objects; i++) {
1790 struct object_entry *entry = sorted_by_offset[i];
1791 check_object(entry);
1792 if (entry->type_valid &&
1793 oe_size_greater_than(&to_pack, entry, big_file_threshold))
1794 entry->no_try_delta = 1;
1795 display_progress(progress_state, i + 1);
1797 stop_progress(&progress_state);
1800 * This must happen in a second pass, since we rely on the delta
1801 * information for the whole list being completed.
1803 for (i = 0; i < to_pack.nr_objects; i++)
1804 break_delta_chains(&to_pack.objects[i]);
1806 free(sorted_by_offset);
1810 * We search for deltas in a list sorted by type, by filename hash, and then
1811 * by size, so that we see progressively smaller and smaller files.
1812 * That's because we prefer deltas to be from the bigger file
1813 * to the smaller -- deletes are potentially cheaper, but perhaps
1814 * more importantly, the bigger file is likely the more recent
1815 * one. The deepest deltas are therefore the oldest objects which are
1816 * less susceptible to be accessed often.
1818 static int type_size_sort(const void *_a, const void *_b)
1820 const struct object_entry *a = *(struct object_entry **)_a;
1821 const struct object_entry *b = *(struct object_entry **)_b;
1822 enum object_type a_type = oe_type(a);
1823 enum object_type b_type = oe_type(b);
1824 unsigned long a_size = SIZE(a);
1825 unsigned long b_size = SIZE(b);
1827 if (a_type > b_type)
1829 if (a_type < b_type)
1831 if (a->hash > b->hash)
1833 if (a->hash < b->hash)
1835 if (a->preferred_base > b->preferred_base)
1837 if (a->preferred_base < b->preferred_base)
1839 if (use_delta_islands) {
1840 int island_cmp = island_delta_cmp(&a->idx.oid, &b->idx.oid);
1844 if (a_size > b_size)
1846 if (a_size < b_size)
1848 return a < b ? -1 : (a > b); /* newest first */
1852 struct object_entry *entry;
1854 struct delta_index *index;
1858 static int delta_cacheable(unsigned long src_size, unsigned long trg_size,
1859 unsigned long delta_size)
1861 if (max_delta_cache_size && delta_cache_size + delta_size > max_delta_cache_size)
1864 if (delta_size < cache_max_small_delta_size)
1867 /* cache delta, if objects are large enough compared to delta size */
1868 if ((src_size >> 20) + (trg_size >> 21) > (delta_size >> 10))
1876 static pthread_mutex_t read_mutex;
1877 #define read_lock() pthread_mutex_lock(&read_mutex)
1878 #define read_unlock() pthread_mutex_unlock(&read_mutex)
1880 static pthread_mutex_t cache_mutex;
1881 #define cache_lock() pthread_mutex_lock(&cache_mutex)
1882 #define cache_unlock() pthread_mutex_unlock(&cache_mutex)
1884 static pthread_mutex_t progress_mutex;
1885 #define progress_lock() pthread_mutex_lock(&progress_mutex)
1886 #define progress_unlock() pthread_mutex_unlock(&progress_mutex)
1890 #define read_lock() (void)0
1891 #define read_unlock() (void)0
1892 #define cache_lock() (void)0
1893 #define cache_unlock() (void)0
1894 #define progress_lock() (void)0
1895 #define progress_unlock() (void)0
1900 * Return the size of the object without doing any delta
1901 * reconstruction (so non-deltas are true object sizes, but deltas
1902 * return the size of the delta data).
1904 unsigned long oe_get_size_slow(struct packing_data *pack,
1905 const struct object_entry *e)
1907 struct packed_git *p;
1908 struct pack_window *w_curs;
1910 enum object_type type;
1911 unsigned long used, avail, size;
1913 if (e->type_ != OBJ_OFS_DELTA && e->type_ != OBJ_REF_DELTA) {
1915 if (oid_object_info(the_repository, &e->idx.oid, &size) < 0)
1916 die(_("unable to get size of %s"),
1917 oid_to_hex(&e->idx.oid));
1922 p = oe_in_pack(pack, e);
1924 BUG("when e->type is a delta, it must belong to a pack");
1928 buf = use_pack(p, &w_curs, e->in_pack_offset, &avail);
1929 used = unpack_object_header_buffer(buf, avail, &type, &size);
1931 die(_("unable to parse object header of %s"),
1932 oid_to_hex(&e->idx.oid));
1934 unuse_pack(&w_curs);
1939 static int try_delta(struct unpacked *trg, struct unpacked *src,
1940 unsigned max_depth, unsigned long *mem_usage)
1942 struct object_entry *trg_entry = trg->entry;
1943 struct object_entry *src_entry = src->entry;
1944 unsigned long trg_size, src_size, delta_size, sizediff, max_size, sz;
1946 enum object_type type;
1949 /* Don't bother doing diffs between different types */
1950 if (oe_type(trg_entry) != oe_type(src_entry))
1954 * We do not bother to try a delta that we discarded on an
1955 * earlier try, but only when reusing delta data. Note that
1956 * src_entry that is marked as the preferred_base should always
1957 * be considered, as even if we produce a suboptimal delta against
1958 * it, we will still save the transfer cost, as we already know
1959 * the other side has it and we won't send src_entry at all.
1961 if (reuse_delta && IN_PACK(trg_entry) &&
1962 IN_PACK(trg_entry) == IN_PACK(src_entry) &&
1963 !src_entry->preferred_base &&
1964 trg_entry->in_pack_type != OBJ_REF_DELTA &&
1965 trg_entry->in_pack_type != OBJ_OFS_DELTA)
1968 /* Let's not bust the allowed depth. */
1969 if (src->depth >= max_depth)
1972 /* Now some size filtering heuristics. */
1973 trg_size = SIZE(trg_entry);
1974 if (!DELTA(trg_entry)) {
1975 max_size = trg_size/2 - the_hash_algo->rawsz;
1978 max_size = DELTA_SIZE(trg_entry);
1979 ref_depth = trg->depth;
1981 max_size = (uint64_t)max_size * (max_depth - src->depth) /
1982 (max_depth - ref_depth + 1);
1985 src_size = SIZE(src_entry);
1986 sizediff = src_size < trg_size ? trg_size - src_size : 0;
1987 if (sizediff >= max_size)
1989 if (trg_size < src_size / 32)
1992 if (!in_same_island(&trg->entry->idx.oid, &src->entry->idx.oid))
1995 /* Load data if not already done */
1998 trg->data = read_object_file(&trg_entry->idx.oid, &type, &sz);
2001 die("object %s cannot be read",
2002 oid_to_hex(&trg_entry->idx.oid));
2004 die("object %s inconsistent object length (%lu vs %lu)",
2005 oid_to_hex(&trg_entry->idx.oid), sz,
2011 src->data = read_object_file(&src_entry->idx.oid, &type, &sz);
2014 if (src_entry->preferred_base) {
2015 static int warned = 0;
2017 warning("object %s cannot be read",
2018 oid_to_hex(&src_entry->idx.oid));
2020 * Those objects are not included in the
2021 * resulting pack. Be resilient and ignore
2022 * them if they can't be read, in case the
2023 * pack could be created nevertheless.
2027 die("object %s cannot be read",
2028 oid_to_hex(&src_entry->idx.oid));
2031 die("object %s inconsistent object length (%lu vs %lu)",
2032 oid_to_hex(&src_entry->idx.oid), sz,
2037 src->index = create_delta_index(src->data, src_size);
2039 static int warned = 0;
2041 warning("suboptimal pack - out of memory");
2044 *mem_usage += sizeof_delta_index(src->index);
2047 delta_buf = create_delta(src->index, trg->data, trg_size, &delta_size, max_size);
2050 if (delta_size >= (1U << OE_DELTA_SIZE_BITS)) {
2055 if (DELTA(trg_entry)) {
2056 /* Prefer only shallower same-sized deltas. */
2057 if (delta_size == DELTA_SIZE(trg_entry) &&
2058 src->depth + 1 >= trg->depth) {
2065 * Handle memory allocation outside of the cache
2066 * accounting lock. Compiler will optimize the strangeness
2067 * away when NO_PTHREADS is defined.
2069 free(trg_entry->delta_data);
2071 if (trg_entry->delta_data) {
2072 delta_cache_size -= DELTA_SIZE(trg_entry);
2073 trg_entry->delta_data = NULL;
2075 if (delta_cacheable(src_size, trg_size, delta_size)) {
2076 delta_cache_size += delta_size;
2078 trg_entry->delta_data = xrealloc(delta_buf, delta_size);
2084 SET_DELTA(trg_entry, src_entry);
2085 SET_DELTA_SIZE(trg_entry, delta_size);
2086 trg->depth = src->depth + 1;
2091 static unsigned int check_delta_limit(struct object_entry *me, unsigned int n)
2093 struct object_entry *child = DELTA_CHILD(me);
2096 unsigned int c = check_delta_limit(child, n + 1);
2099 child = DELTA_SIBLING(child);
2104 static unsigned long free_unpacked(struct unpacked *n)
2106 unsigned long freed_mem = sizeof_delta_index(n->index);
2107 free_delta_index(n->index);
2110 freed_mem += SIZE(n->entry);
2111 FREE_AND_NULL(n->data);
2118 static void find_deltas(struct object_entry **list, unsigned *list_size,
2119 int window, int depth, unsigned *processed)
2121 uint32_t i, idx = 0, count = 0;
2122 struct unpacked *array;
2123 unsigned long mem_usage = 0;
2125 array = xcalloc(window, sizeof(struct unpacked));
2128 struct object_entry *entry;
2129 struct unpacked *n = array + idx;
2130 int j, max_depth, best_base = -1;
2139 if (!entry->preferred_base) {
2141 display_progress(progress_state, *processed);
2145 mem_usage -= free_unpacked(n);
2148 while (window_memory_limit &&
2149 mem_usage > window_memory_limit &&
2151 uint32_t tail = (idx + window - count) % window;
2152 mem_usage -= free_unpacked(array + tail);
2156 /* We do not compute delta to *create* objects we are not
2159 if (entry->preferred_base)
2163 * If the current object is at pack edge, take the depth the
2164 * objects that depend on the current object into account
2165 * otherwise they would become too deep.
2168 if (DELTA_CHILD(entry)) {
2169 max_depth -= check_delta_limit(entry, 0);
2177 uint32_t other_idx = idx + j;
2179 if (other_idx >= window)
2180 other_idx -= window;
2181 m = array + other_idx;
2184 ret = try_delta(n, m, max_depth, &mem_usage);
2188 best_base = other_idx;
2192 * If we decided to cache the delta data, then it is best
2193 * to compress it right away. First because we have to do
2194 * it anyway, and doing it here while we're threaded will
2195 * save a lot of time in the non threaded write phase,
2196 * as well as allow for caching more deltas within
2197 * the same cache size limit.
2199 * But only if not writing to stdout, since in that case
2200 * the network is most likely throttling writes anyway,
2201 * and therefore it is best to go to the write phase ASAP
2202 * instead, as we can afford spending more time compressing
2203 * between writes at that moment.
2205 if (entry->delta_data && !pack_to_stdout) {
2208 size = do_compress(&entry->delta_data, DELTA_SIZE(entry));
2209 if (size < (1U << OE_Z_DELTA_BITS)) {
2210 entry->z_delta_size = size;
2212 delta_cache_size -= DELTA_SIZE(entry);
2213 delta_cache_size += entry->z_delta_size;
2216 FREE_AND_NULL(entry->delta_data);
2217 entry->z_delta_size = 0;
2221 /* if we made n a delta, and if n is already at max
2222 * depth, leaving it in the window is pointless. we
2223 * should evict it first.
2225 if (DELTA(entry) && max_depth <= n->depth)
2229 * Move the best delta base up in the window, after the
2230 * currently deltified object, to keep it longer. It will
2231 * be the first base object to be attempted next.
2234 struct unpacked swap = array[best_base];
2235 int dist = (window + idx - best_base) % window;
2236 int dst = best_base;
2238 int src = (dst + 1) % window;
2239 array[dst] = array[src];
2247 if (count + 1 < window)
2253 for (i = 0; i < window; ++i) {
2254 free_delta_index(array[i].index);
2255 free(array[i].data);
2262 static void try_to_free_from_threads(size_t size)
2265 release_pack_memory(size);
2269 static try_to_free_t old_try_to_free_routine;
2272 * The main thread waits on the condition that (at least) one of the workers
2273 * has stopped working (which is indicated in the .working member of
2274 * struct thread_params).
2275 * When a work thread has completed its work, it sets .working to 0 and
2276 * signals the main thread and waits on the condition that .data_ready
2280 struct thread_params {
2282 struct object_entry **list;
2289 pthread_mutex_t mutex;
2290 pthread_cond_t cond;
2291 unsigned *processed;
2294 static pthread_cond_t progress_cond;
2297 * Mutex and conditional variable can't be statically-initialized on Windows.
2299 static void init_threaded_search(void)
2301 init_recursive_mutex(&read_mutex);
2302 pthread_mutex_init(&cache_mutex, NULL);
2303 pthread_mutex_init(&progress_mutex, NULL);
2304 pthread_cond_init(&progress_cond, NULL);
2305 old_try_to_free_routine = set_try_to_free_routine(try_to_free_from_threads);
2308 static void cleanup_threaded_search(void)
2310 set_try_to_free_routine(old_try_to_free_routine);
2311 pthread_cond_destroy(&progress_cond);
2312 pthread_mutex_destroy(&read_mutex);
2313 pthread_mutex_destroy(&cache_mutex);
2314 pthread_mutex_destroy(&progress_mutex);
2317 static void *threaded_find_deltas(void *arg)
2319 struct thread_params *me = arg;
2322 while (me->remaining) {
2325 find_deltas(me->list, &me->remaining,
2326 me->window, me->depth, me->processed);
2330 pthread_cond_signal(&progress_cond);
2334 * We must not set ->data_ready before we wait on the
2335 * condition because the main thread may have set it to 1
2336 * before we get here. In order to be sure that new
2337 * work is available if we see 1 in ->data_ready, it
2338 * was initialized to 0 before this thread was spawned
2339 * and we reset it to 0 right away.
2341 pthread_mutex_lock(&me->mutex);
2342 while (!me->data_ready)
2343 pthread_cond_wait(&me->cond, &me->mutex);
2345 pthread_mutex_unlock(&me->mutex);
2350 /* leave ->working 1 so that this doesn't get more work assigned */
2354 static void ll_find_deltas(struct object_entry **list, unsigned list_size,
2355 int window, int depth, unsigned *processed)
2357 struct thread_params *p;
2358 int i, ret, active_threads = 0;
2360 init_threaded_search();
2362 if (delta_search_threads <= 1) {
2363 find_deltas(list, &list_size, window, depth, processed);
2364 cleanup_threaded_search();
2367 if (progress > pack_to_stdout)
2368 fprintf(stderr, "Delta compression using up to %d threads.\n",
2369 delta_search_threads);
2370 p = xcalloc(delta_search_threads, sizeof(*p));
2372 /* Partition the work amongst work threads. */
2373 for (i = 0; i < delta_search_threads; i++) {
2374 unsigned sub_size = list_size / (delta_search_threads - i);
2376 /* don't use too small segments or no deltas will be found */
2377 if (sub_size < 2*window && i+1 < delta_search_threads)
2380 p[i].window = window;
2382 p[i].processed = processed;
2384 p[i].data_ready = 0;
2386 /* try to split chunks on "path" boundaries */
2387 while (sub_size && sub_size < list_size &&
2388 list[sub_size]->hash &&
2389 list[sub_size]->hash == list[sub_size-1]->hash)
2393 p[i].list_size = sub_size;
2394 p[i].remaining = sub_size;
2397 list_size -= sub_size;
2400 /* Start work threads. */
2401 for (i = 0; i < delta_search_threads; i++) {
2402 if (!p[i].list_size)
2404 pthread_mutex_init(&p[i].mutex, NULL);
2405 pthread_cond_init(&p[i].cond, NULL);
2406 ret = pthread_create(&p[i].thread, NULL,
2407 threaded_find_deltas, &p[i]);
2409 die("unable to create thread: %s", strerror(ret));
2414 * Now let's wait for work completion. Each time a thread is done
2415 * with its work, we steal half of the remaining work from the
2416 * thread with the largest number of unprocessed objects and give
2417 * it to that newly idle thread. This ensure good load balancing
2418 * until the remaining object list segments are simply too short
2419 * to be worth splitting anymore.
2421 while (active_threads) {
2422 struct thread_params *target = NULL;
2423 struct thread_params *victim = NULL;
2424 unsigned sub_size = 0;
2428 for (i = 0; !target && i < delta_search_threads; i++)
2433 pthread_cond_wait(&progress_cond, &progress_mutex);
2436 for (i = 0; i < delta_search_threads; i++)
2437 if (p[i].remaining > 2*window &&
2438 (!victim || victim->remaining < p[i].remaining))
2441 sub_size = victim->remaining / 2;
2442 list = victim->list + victim->list_size - sub_size;
2443 while (sub_size && list[0]->hash &&
2444 list[0]->hash == list[-1]->hash) {
2450 * It is possible for some "paths" to have
2451 * so many objects that no hash boundary
2452 * might be found. Let's just steal the
2453 * exact half in that case.
2455 sub_size = victim->remaining / 2;
2458 target->list = list;
2459 victim->list_size -= sub_size;
2460 victim->remaining -= sub_size;
2462 target->list_size = sub_size;
2463 target->remaining = sub_size;
2464 target->working = 1;
2467 pthread_mutex_lock(&target->mutex);
2468 target->data_ready = 1;
2469 pthread_cond_signal(&target->cond);
2470 pthread_mutex_unlock(&target->mutex);
2473 pthread_join(target->thread, NULL);
2474 pthread_cond_destroy(&target->cond);
2475 pthread_mutex_destroy(&target->mutex);
2479 cleanup_threaded_search();
2484 #define ll_find_deltas(l, s, w, d, p) find_deltas(l, &s, w, d, p)
2487 static void add_tag_chain(const struct object_id *oid)
2492 * We catch duplicates already in add_object_entry(), but we'd
2493 * prefer to do this extra check to avoid having to parse the
2494 * tag at all if we already know that it's being packed (e.g., if
2495 * it was included via bitmaps, we would not have parsed it
2498 if (packlist_find(&to_pack, oid->hash, NULL))
2501 tag = lookup_tag(the_repository, oid);
2503 if (!tag || parse_tag(tag) || !tag->tagged)
2504 die("unable to pack objects reachable from tag %s",
2507 add_object_entry(&tag->object.oid, OBJ_TAG, NULL, 0);
2509 if (tag->tagged->type != OBJ_TAG)
2512 tag = (struct tag *)tag->tagged;
2516 static int add_ref_tag(const char *path, const struct object_id *oid, int flag, void *cb_data)
2518 struct object_id peeled;
2520 if (starts_with(path, "refs/tags/") && /* is a tag? */
2521 !peel_ref(path, &peeled) && /* peelable? */
2522 packlist_find(&to_pack, peeled.hash, NULL)) /* object packed? */
2527 static void prepare_pack(int window, int depth)
2529 struct object_entry **delta_list;
2530 uint32_t i, nr_deltas;
2533 if (use_delta_islands)
2534 resolve_tree_islands(progress, &to_pack);
2536 get_object_details();
2539 * If we're locally repacking then we need to be doubly careful
2540 * from now on in order to make sure no stealth corruption gets
2541 * propagated to the new pack. Clients receiving streamed packs
2542 * should validate everything they get anyway so no need to incur
2543 * the additional cost here in that case.
2545 if (!pack_to_stdout)
2546 do_check_packed_object_crc = 1;
2548 if (!to_pack.nr_objects || !window || !depth)
2551 ALLOC_ARRAY(delta_list, to_pack.nr_objects);
2554 for (i = 0; i < to_pack.nr_objects; i++) {
2555 struct object_entry *entry = to_pack.objects + i;
2558 /* This happens if we decided to reuse existing
2559 * delta from a pack. "reuse_delta &&" is implied.
2563 if (!entry->type_valid ||
2564 oe_size_less_than(&to_pack, entry, 50))
2567 if (entry->no_try_delta)
2570 if (!entry->preferred_base) {
2572 if (oe_type(entry) < 0)
2573 die("unable to get type of object %s",
2574 oid_to_hex(&entry->idx.oid));
2576 if (oe_type(entry) < 0) {
2578 * This object is not found, but we
2579 * don't have to include it anyway.
2585 delta_list[n++] = entry;
2588 if (nr_deltas && n > 1) {
2589 unsigned nr_done = 0;
2591 progress_state = start_progress(_("Compressing objects"),
2593 QSORT(delta_list, n, type_size_sort);
2594 ll_find_deltas(delta_list, n, window+1, depth, &nr_done);
2595 stop_progress(&progress_state);
2596 if (nr_done != nr_deltas)
2597 die("inconsistency with delta count");
2602 static int git_pack_config(const char *k, const char *v, void *cb)
2604 if (!strcmp(k, "pack.window")) {
2605 window = git_config_int(k, v);
2608 if (!strcmp(k, "pack.windowmemory")) {
2609 window_memory_limit = git_config_ulong(k, v);
2612 if (!strcmp(k, "pack.depth")) {
2613 depth = git_config_int(k, v);
2616 if (!strcmp(k, "pack.deltacachesize")) {
2617 max_delta_cache_size = git_config_int(k, v);
2620 if (!strcmp(k, "pack.deltacachelimit")) {
2621 cache_max_small_delta_size = git_config_int(k, v);
2624 if (!strcmp(k, "pack.writebitmaphashcache")) {
2625 if (git_config_bool(k, v))
2626 write_bitmap_options |= BITMAP_OPT_HASH_CACHE;
2628 write_bitmap_options &= ~BITMAP_OPT_HASH_CACHE;
2630 if (!strcmp(k, "pack.usebitmaps")) {
2631 use_bitmap_index_default = git_config_bool(k, v);
2634 if (!strcmp(k, "pack.threads")) {
2635 delta_search_threads = git_config_int(k, v);
2636 if (delta_search_threads < 0)
2637 die("invalid number of threads specified (%d)",
2638 delta_search_threads);
2640 if (delta_search_threads != 1) {
2641 warning("no threads support, ignoring %s", k);
2642 delta_search_threads = 0;
2647 if (!strcmp(k, "pack.indexversion")) {
2648 pack_idx_opts.version = git_config_int(k, v);
2649 if (pack_idx_opts.version > 2)
2650 die("bad pack.indexversion=%"PRIu32,
2651 pack_idx_opts.version);
2654 return git_default_config(k, v, cb);
2657 static void read_object_list_from_stdin(void)
2659 char line[GIT_MAX_HEXSZ + 1 + PATH_MAX + 2];
2660 struct object_id oid;
2664 if (!fgets(line, sizeof(line), stdin)) {
2668 die("fgets returned NULL, not EOF, not error!");
2674 if (line[0] == '-') {
2675 if (get_oid_hex(line+1, &oid))
2676 die("expected edge object ID, got garbage:\n %s",
2678 add_preferred_base(&oid);
2681 if (parse_oid_hex(line, &oid, &p))
2682 die("expected object ID, got garbage:\n %s", line);
2684 add_preferred_base_object(p + 1);
2685 add_object_entry(&oid, OBJ_NONE, p + 1, 0);
2689 /* Remember to update object flag allocation in object.h */
2690 #define OBJECT_ADDED (1u<<20)
2692 static void show_commit(struct commit *commit, void *data)
2694 add_object_entry(&commit->object.oid, OBJ_COMMIT, NULL, 0);
2695 commit->object.flags |= OBJECT_ADDED;
2697 if (write_bitmap_index)
2698 index_commit_for_bitmap(commit);
2700 if (use_delta_islands)
2701 propagate_island_marks(commit);
2704 static void show_object(struct object *obj, const char *name, void *data)
2706 add_preferred_base_object(name);
2707 add_object_entry(&obj->oid, obj->type, name, 0);
2708 obj->flags |= OBJECT_ADDED;
2710 if (use_delta_islands) {
2713 struct object_entry *ent;
2715 for (p = strchr(name, '/'); p; p = strchr(p + 1, '/'))
2718 ent = packlist_find(&to_pack, obj->oid.hash, NULL);
2719 if (ent && depth > oe_tree_depth(&to_pack, ent))
2720 oe_set_tree_depth(&to_pack, ent, depth);
2724 static void show_object__ma_allow_any(struct object *obj, const char *name, void *data)
2726 assert(arg_missing_action == MA_ALLOW_ANY);
2729 * Quietly ignore ALL missing objects. This avoids problems with
2730 * staging them now and getting an odd error later.
2732 if (!has_object_file(&obj->oid))
2735 show_object(obj, name, data);
2738 static void show_object__ma_allow_promisor(struct object *obj, const char *name, void *data)
2740 assert(arg_missing_action == MA_ALLOW_PROMISOR);
2743 * Quietly ignore EXPECTED missing objects. This avoids problems with
2744 * staging them now and getting an odd error later.
2746 if (!has_object_file(&obj->oid) && is_promisor_object(&obj->oid))
2749 show_object(obj, name, data);
2752 static int option_parse_missing_action(const struct option *opt,
2753 const char *arg, int unset)
2758 if (!strcmp(arg, "error")) {
2759 arg_missing_action = MA_ERROR;
2760 fn_show_object = show_object;
2764 if (!strcmp(arg, "allow-any")) {
2765 arg_missing_action = MA_ALLOW_ANY;
2766 fetch_if_missing = 0;
2767 fn_show_object = show_object__ma_allow_any;
2771 if (!strcmp(arg, "allow-promisor")) {
2772 arg_missing_action = MA_ALLOW_PROMISOR;
2773 fetch_if_missing = 0;
2774 fn_show_object = show_object__ma_allow_promisor;
2778 die(_("invalid value for --missing"));
2782 static void show_edge(struct commit *commit)
2784 add_preferred_base(&commit->object.oid);
2787 struct in_pack_object {
2789 struct object *object;
2795 struct in_pack_object *array;
2798 static void mark_in_pack_object(struct object *object, struct packed_git *p, struct in_pack *in_pack)
2800 in_pack->array[in_pack->nr].offset = find_pack_entry_one(object->oid.hash, p);
2801 in_pack->array[in_pack->nr].object = object;
2806 * Compare the objects in the offset order, in order to emulate the
2807 * "git rev-list --objects" output that produced the pack originally.
2809 static int ofscmp(const void *a_, const void *b_)
2811 struct in_pack_object *a = (struct in_pack_object *)a_;
2812 struct in_pack_object *b = (struct in_pack_object *)b_;
2814 if (a->offset < b->offset)
2816 else if (a->offset > b->offset)
2819 return oidcmp(&a->object->oid, &b->object->oid);
2822 static void add_objects_in_unpacked_packs(struct rev_info *revs)
2824 struct packed_git *p;
2825 struct in_pack in_pack;
2828 memset(&in_pack, 0, sizeof(in_pack));
2830 for (p = get_packed_git(the_repository); p; p = p->next) {
2831 struct object_id oid;
2834 if (!p->pack_local || p->pack_keep || p->pack_keep_in_core)
2836 if (open_pack_index(p))
2837 die("cannot open pack index");
2839 ALLOC_GROW(in_pack.array,
2840 in_pack.nr + p->num_objects,
2843 for (i = 0; i < p->num_objects; i++) {
2844 nth_packed_object_oid(&oid, p, i);
2845 o = lookup_unknown_object(oid.hash);
2846 if (!(o->flags & OBJECT_ADDED))
2847 mark_in_pack_object(o, p, &in_pack);
2848 o->flags |= OBJECT_ADDED;
2853 QSORT(in_pack.array, in_pack.nr, ofscmp);
2854 for (i = 0; i < in_pack.nr; i++) {
2855 struct object *o = in_pack.array[i].object;
2856 add_object_entry(&o->oid, o->type, "", 0);
2859 free(in_pack.array);
2862 static int add_loose_object(const struct object_id *oid, const char *path,
2865 enum object_type type = oid_object_info(the_repository, oid, NULL);
2868 warning("loose object at %s could not be examined", path);
2872 add_object_entry(oid, type, "", 0);
2877 * We actually don't even have to worry about reachability here.
2878 * add_object_entry will weed out duplicates, so we just add every
2879 * loose object we find.
2881 static void add_unreachable_loose_objects(void)
2883 for_each_loose_file_in_objdir(get_object_directory(),
2888 static int has_sha1_pack_kept_or_nonlocal(const struct object_id *oid)
2890 static struct packed_git *last_found = (void *)1;
2891 struct packed_git *p;
2893 p = (last_found != (void *)1) ? last_found :
2894 get_packed_git(the_repository);
2897 if ((!p->pack_local || p->pack_keep ||
2898 p->pack_keep_in_core) &&
2899 find_pack_entry_one(oid->hash, p)) {
2903 if (p == last_found)
2904 p = get_packed_git(the_repository);
2907 if (p == last_found)
2914 * Store a list of sha1s that are should not be discarded
2915 * because they are either written too recently, or are
2916 * reachable from another object that was.
2918 * This is filled by get_object_list.
2920 static struct oid_array recent_objects;
2922 static int loosened_object_can_be_discarded(const struct object_id *oid,
2925 if (!unpack_unreachable_expiration)
2927 if (mtime > unpack_unreachable_expiration)
2929 if (oid_array_lookup(&recent_objects, oid) >= 0)
2934 static void loosen_unused_packed_objects(struct rev_info *revs)
2936 struct packed_git *p;
2938 struct object_id oid;
2940 for (p = get_packed_git(the_repository); p; p = p->next) {
2941 if (!p->pack_local || p->pack_keep || p->pack_keep_in_core)
2944 if (open_pack_index(p))
2945 die("cannot open pack index");
2947 for (i = 0; i < p->num_objects; i++) {
2948 nth_packed_object_oid(&oid, p, i);
2949 if (!packlist_find(&to_pack, oid.hash, NULL) &&
2950 !has_sha1_pack_kept_or_nonlocal(&oid) &&
2951 !loosened_object_can_be_discarded(&oid, p->mtime))
2952 if (force_object_loose(&oid, p->mtime))
2953 die("unable to force loose object");
2959 * This tracks any options which pack-reuse code expects to be on, or which a
2960 * reader of the pack might not understand, and which would therefore prevent
2961 * blind reuse of what we have on disk.
2963 static int pack_options_allow_reuse(void)
2965 return pack_to_stdout &&
2967 !ignore_packed_keep_on_disk &&
2968 !ignore_packed_keep_in_core &&
2969 (!local || !have_non_local_packs) &&
2973 static int get_object_list_from_bitmap(struct rev_info *revs)
2975 struct bitmap_index *bitmap_git;
2976 if (!(bitmap_git = prepare_bitmap_walk(revs)))
2979 if (pack_options_allow_reuse() &&
2980 !reuse_partial_packfile_from_bitmap(
2983 &reuse_packfile_objects,
2984 &reuse_packfile_offset)) {
2985 assert(reuse_packfile_objects);
2986 nr_result += reuse_packfile_objects;
2987 display_progress(progress_state, nr_result);
2990 traverse_bitmap_commit_list(bitmap_git, &add_object_entry_from_bitmap);
2991 free_bitmap_index(bitmap_git);
2995 static void record_recent_object(struct object *obj,
2999 oid_array_append(&recent_objects, &obj->oid);
3002 static void record_recent_commit(struct commit *commit, void *data)
3004 oid_array_append(&recent_objects, &commit->object.oid);
3007 static void get_object_list(int ac, const char **av)
3009 struct rev_info revs;
3013 init_revisions(&revs, NULL);
3014 save_commit_buffer = 0;
3015 setup_revisions(ac, av, &revs, NULL);
3017 /* make sure shallows are read */
3018 is_repository_shallow(the_repository);
3020 while (fgets(line, sizeof(line), stdin) != NULL) {
3021 int len = strlen(line);
3022 if (len && line[len - 1] == '\n')
3027 if (!strcmp(line, "--not")) {
3028 flags ^= UNINTERESTING;
3029 write_bitmap_index = 0;
3032 if (starts_with(line, "--shallow ")) {
3033 struct object_id oid;
3034 if (get_oid_hex(line + 10, &oid))
3035 die("not an SHA-1 '%s'", line + 10);
3036 register_shallow(the_repository, &oid);
3037 use_bitmap_index = 0;
3040 die("not a rev '%s'", line);
3042 if (handle_revision_arg(line, &revs, flags, REVARG_CANNOT_BE_FILENAME))
3043 die("bad revision '%s'", line);
3046 if (use_bitmap_index && !get_object_list_from_bitmap(&revs))
3049 if (use_delta_islands)
3050 load_delta_islands();
3052 if (prepare_revision_walk(&revs))
3053 die("revision walk setup failed");
3054 mark_edges_uninteresting(&revs, show_edge);
3056 if (!fn_show_object)
3057 fn_show_object = show_object;
3058 traverse_commit_list_filtered(&filter_options, &revs,
3059 show_commit, fn_show_object, NULL,
3062 if (unpack_unreachable_expiration) {
3063 revs.ignore_missing_links = 1;
3064 if (add_unseen_recent_objects_to_traversal(&revs,
3065 unpack_unreachable_expiration))
3066 die("unable to add recent objects");
3067 if (prepare_revision_walk(&revs))
3068 die("revision walk setup failed");
3069 traverse_commit_list(&revs, record_recent_commit,
3070 record_recent_object, NULL);
3073 if (keep_unreachable)
3074 add_objects_in_unpacked_packs(&revs);
3075 if (pack_loose_unreachable)
3076 add_unreachable_loose_objects();
3077 if (unpack_unreachable)
3078 loosen_unused_packed_objects(&revs);
3080 oid_array_clear(&recent_objects);
3083 static void add_extra_kept_packs(const struct string_list *names)
3085 struct packed_git *p;
3090 for (p = get_packed_git(the_repository); p; p = p->next) {
3091 const char *name = basename(p->pack_name);
3097 for (i = 0; i < names->nr; i++)
3098 if (!fspathcmp(name, names->items[i].string))
3101 if (i < names->nr) {
3102 p->pack_keep_in_core = 1;
3103 ignore_packed_keep_in_core = 1;
3109 static int option_parse_index_version(const struct option *opt,
3110 const char *arg, int unset)
3113 const char *val = arg;
3114 pack_idx_opts.version = strtoul(val, &c, 10);
3115 if (pack_idx_opts.version > 2)
3116 die(_("unsupported index version %s"), val);
3117 if (*c == ',' && c[1])
3118 pack_idx_opts.off32_limit = strtoul(c+1, &c, 0);
3119 if (*c || pack_idx_opts.off32_limit & 0x80000000)
3120 die(_("bad index version '%s'"), val);
3124 static int option_parse_unpack_unreachable(const struct option *opt,
3125 const char *arg, int unset)
3128 unpack_unreachable = 0;
3129 unpack_unreachable_expiration = 0;
3132 unpack_unreachable = 1;
3134 unpack_unreachable_expiration = approxidate(arg);
3139 int cmd_pack_objects(int argc, const char **argv, const char *prefix)
3141 int use_internal_rev_list = 0;
3144 int all_progress_implied = 0;
3145 struct argv_array rp = ARGV_ARRAY_INIT;
3146 int rev_list_unpacked = 0, rev_list_all = 0, rev_list_reflog = 0;
3147 int rev_list_index = 0;
3148 struct string_list keep_pack_list = STRING_LIST_INIT_NODUP;
3149 struct option pack_objects_options[] = {
3150 OPT_SET_INT('q', "quiet", &progress,
3151 N_("do not show progress meter"), 0),
3152 OPT_SET_INT(0, "progress", &progress,
3153 N_("show progress meter"), 1),
3154 OPT_SET_INT(0, "all-progress", &progress,
3155 N_("show progress meter during object writing phase"), 2),
3156 OPT_BOOL(0, "all-progress-implied",
3157 &all_progress_implied,
3158 N_("similar to --all-progress when progress meter is shown")),
3159 { OPTION_CALLBACK, 0, "index-version", NULL, N_("version[,offset]"),
3160 N_("write the pack index file in the specified idx format version"),
3161 0, option_parse_index_version },
3162 OPT_MAGNITUDE(0, "max-pack-size", &pack_size_limit,
3163 N_("maximum size of each output pack file")),
3164 OPT_BOOL(0, "local", &local,
3165 N_("ignore borrowed objects from alternate object store")),
3166 OPT_BOOL(0, "incremental", &incremental,
3167 N_("ignore packed objects")),
3168 OPT_INTEGER(0, "window", &window,
3169 N_("limit pack window by objects")),
3170 OPT_MAGNITUDE(0, "window-memory", &window_memory_limit,
3171 N_("limit pack window by memory in addition to object limit")),
3172 OPT_INTEGER(0, "depth", &depth,
3173 N_("maximum length of delta chain allowed in the resulting pack")),
3174 OPT_BOOL(0, "reuse-delta", &reuse_delta,
3175 N_("reuse existing deltas")),
3176 OPT_BOOL(0, "reuse-object", &reuse_object,
3177 N_("reuse existing objects")),
3178 OPT_BOOL(0, "delta-base-offset", &allow_ofs_delta,
3179 N_("use OFS_DELTA objects")),
3180 OPT_INTEGER(0, "threads", &delta_search_threads,
3181 N_("use threads when searching for best delta matches")),
3182 OPT_BOOL(0, "non-empty", &non_empty,
3183 N_("do not create an empty pack output")),
3184 OPT_BOOL(0, "revs", &use_internal_rev_list,
3185 N_("read revision arguments from standard input")),
3186 OPT_SET_INT_F(0, "unpacked", &rev_list_unpacked,
3187 N_("limit the objects to those that are not yet packed"),
3188 1, PARSE_OPT_NONEG),
3189 OPT_SET_INT_F(0, "all", &rev_list_all,
3190 N_("include objects reachable from any reference"),
3191 1, PARSE_OPT_NONEG),
3192 OPT_SET_INT_F(0, "reflog", &rev_list_reflog,
3193 N_("include objects referred by reflog entries"),
3194 1, PARSE_OPT_NONEG),
3195 OPT_SET_INT_F(0, "indexed-objects", &rev_list_index,
3196 N_("include objects referred to by the index"),
3197 1, PARSE_OPT_NONEG),
3198 OPT_BOOL(0, "stdout", &pack_to_stdout,
3199 N_("output pack to stdout")),
3200 OPT_BOOL(0, "include-tag", &include_tag,
3201 N_("include tag objects that refer to objects to be packed")),
3202 OPT_BOOL(0, "keep-unreachable", &keep_unreachable,
3203 N_("keep unreachable objects")),
3204 OPT_BOOL(0, "pack-loose-unreachable", &pack_loose_unreachable,
3205 N_("pack loose unreachable objects")),
3206 { OPTION_CALLBACK, 0, "unpack-unreachable", NULL, N_("time"),
3207 N_("unpack unreachable objects newer than <time>"),
3208 PARSE_OPT_OPTARG, option_parse_unpack_unreachable },
3209 OPT_BOOL(0, "thin", &thin,
3210 N_("create thin packs")),
3211 OPT_BOOL(0, "shallow", &shallow,
3212 N_("create packs suitable for shallow fetches")),
3213 OPT_BOOL(0, "honor-pack-keep", &ignore_packed_keep_on_disk,
3214 N_("ignore packs that have companion .keep file")),
3215 OPT_STRING_LIST(0, "keep-pack", &keep_pack_list, N_("name"),
3216 N_("ignore this pack")),
3217 OPT_INTEGER(0, "compression", &pack_compression_level,
3218 N_("pack compression level")),
3219 OPT_SET_INT(0, "keep-true-parents", &grafts_replace_parents,
3220 N_("do not hide commits by grafts"), 0),
3221 OPT_BOOL(0, "use-bitmap-index", &use_bitmap_index,
3222 N_("use a bitmap index if available to speed up counting objects")),
3223 OPT_BOOL(0, "write-bitmap-index", &write_bitmap_index,
3224 N_("write a bitmap index together with the pack index")),
3225 OPT_PARSE_LIST_OBJECTS_FILTER(&filter_options),
3226 { OPTION_CALLBACK, 0, "missing", NULL, N_("action"),
3227 N_("handling for missing objects"), PARSE_OPT_NONEG,
3228 option_parse_missing_action },
3229 OPT_BOOL(0, "exclude-promisor-objects", &exclude_promisor_objects,
3230 N_("do not pack objects in promisor packfiles")),
3231 OPT_BOOL(0, "delta-islands", &use_delta_islands,
3232 N_("respect islands during delta compression")),
3236 if (DFS_NUM_STATES > (1 << OE_DFS_STATE_BITS))
3237 BUG("too many dfs states, increase OE_DFS_STATE_BITS");
3239 check_replace_refs = 0;
3241 reset_pack_idx_option(&pack_idx_opts);
3242 git_config(git_pack_config, NULL);
3244 progress = isatty(2);
3245 argc = parse_options(argc, argv, prefix, pack_objects_options,
3249 base_name = argv[0];
3252 if (pack_to_stdout != !base_name || argc)
3253 usage_with_options(pack_usage, pack_objects_options);
3255 if (depth >= (1 << OE_DEPTH_BITS)) {
3256 warning(_("delta chain depth %d is too deep, forcing %d"),
3257 depth, (1 << OE_DEPTH_BITS) - 1);
3258 depth = (1 << OE_DEPTH_BITS) - 1;
3260 if (cache_max_small_delta_size >= (1U << OE_Z_DELTA_BITS)) {
3261 warning(_("pack.deltaCacheLimit is too high, forcing %d"),
3262 (1U << OE_Z_DELTA_BITS) - 1);
3263 cache_max_small_delta_size = (1U << OE_Z_DELTA_BITS) - 1;
3266 argv_array_push(&rp, "pack-objects");
3268 use_internal_rev_list = 1;
3269 argv_array_push(&rp, shallow
3270 ? "--objects-edge-aggressive"
3271 : "--objects-edge");
3273 argv_array_push(&rp, "--objects");
3276 use_internal_rev_list = 1;
3277 argv_array_push(&rp, "--all");
3279 if (rev_list_reflog) {
3280 use_internal_rev_list = 1;
3281 argv_array_push(&rp, "--reflog");
3283 if (rev_list_index) {
3284 use_internal_rev_list = 1;
3285 argv_array_push(&rp, "--indexed-objects");
3287 if (rev_list_unpacked) {
3288 use_internal_rev_list = 1;
3289 argv_array_push(&rp, "--unpacked");
3292 if (exclude_promisor_objects) {
3293 use_internal_rev_list = 1;
3294 fetch_if_missing = 0;
3295 argv_array_push(&rp, "--exclude-promisor-objects");
3297 if (unpack_unreachable || keep_unreachable || pack_loose_unreachable)
3298 use_internal_rev_list = 1;
3302 if (pack_compression_level == -1)
3303 pack_compression_level = Z_DEFAULT_COMPRESSION;
3304 else if (pack_compression_level < 0 || pack_compression_level > Z_BEST_COMPRESSION)
3305 die("bad pack compression level %d", pack_compression_level);
3307 if (!delta_search_threads) /* --threads=0 means autodetect */
3308 delta_search_threads = online_cpus();
3311 if (delta_search_threads != 1)
3312 warning("no threads support, ignoring --threads");
3314 if (!pack_to_stdout && !pack_size_limit)
3315 pack_size_limit = pack_size_limit_cfg;
3316 if (pack_to_stdout && pack_size_limit)
3317 die("--max-pack-size cannot be used to build a pack for transfer.");
3318 if (pack_size_limit && pack_size_limit < 1024*1024) {
3319 warning("minimum pack size limit is 1 MiB");
3320 pack_size_limit = 1024*1024;
3323 if (!pack_to_stdout && thin)
3324 die("--thin cannot be used to build an indexable pack.");
3326 if (keep_unreachable && unpack_unreachable)
3327 die("--keep-unreachable and --unpack-unreachable are incompatible.");
3328 if (!rev_list_all || !rev_list_reflog || !rev_list_index)
3329 unpack_unreachable_expiration = 0;
3331 if (filter_options.choice) {
3332 if (!pack_to_stdout)
3333 die("cannot use --filter without --stdout.");
3334 use_bitmap_index = 0;
3338 * "soft" reasons not to use bitmaps - for on-disk repack by default we want
3340 * - to produce good pack (with bitmap index not-yet-packed objects are
3341 * packed in suboptimal order).
3343 * - to use more robust pack-generation codepath (avoiding possible
3344 * bugs in bitmap code and possible bitmap index corruption).
3346 if (!pack_to_stdout)
3347 use_bitmap_index_default = 0;
3349 if (use_bitmap_index < 0)
3350 use_bitmap_index = use_bitmap_index_default;
3352 /* "hard" reasons not to use bitmaps; these just won't work at all */
3353 if (!use_internal_rev_list || (!pack_to_stdout && write_bitmap_index) || is_repository_shallow(the_repository))
3354 use_bitmap_index = 0;
3356 if (pack_to_stdout || !rev_list_all)
3357 write_bitmap_index = 0;
3359 if (use_delta_islands)
3360 argv_array_push(&rp, "--topo-order");
3362 if (progress && all_progress_implied)
3365 add_extra_kept_packs(&keep_pack_list);
3366 if (ignore_packed_keep_on_disk) {
3367 struct packed_git *p;
3368 for (p = get_packed_git(the_repository); p; p = p->next)
3369 if (p->pack_local && p->pack_keep)
3371 if (!p) /* no keep-able packs found */
3372 ignore_packed_keep_on_disk = 0;
3376 * unlike ignore_packed_keep_on_disk above, we do not
3377 * want to unset "local" based on looking at packs, as
3378 * it also covers non-local objects
3380 struct packed_git *p;
3381 for (p = get_packed_git(the_repository); p; p = p->next) {
3382 if (!p->pack_local) {
3383 have_non_local_packs = 1;
3389 prepare_packing_data(&to_pack);
3392 progress_state = start_progress(_("Enumerating objects"), 0);
3393 if (!use_internal_rev_list)
3394 read_object_list_from_stdin();
3396 get_object_list(rp.argc, rp.argv);
3397 argv_array_clear(&rp);
3399 cleanup_preferred_base();
3400 if (include_tag && nr_result)
3401 for_each_ref(add_ref_tag, NULL);
3402 stop_progress(&progress_state);
3404 if (non_empty && !nr_result)
3407 prepare_pack(window, depth);
3410 fprintf(stderr, "Total %"PRIu32" (delta %"PRIu32"),"
3411 " reused %"PRIu32" (delta %"PRIu32")\n",
3412 written, written_delta, reused, reused_delta);