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"
35 #define IN_PACK(obj) oe_in_pack(&to_pack, obj)
36 #define SIZE(obj) oe_size(&to_pack, obj)
37 #define SET_SIZE(obj,size) oe_set_size(&to_pack, obj, size)
38 #define DELTA_SIZE(obj) oe_delta_size(&to_pack, obj)
39 #define DELTA(obj) oe_delta(&to_pack, obj)
40 #define DELTA_CHILD(obj) oe_delta_child(&to_pack, obj)
41 #define DELTA_SIBLING(obj) oe_delta_sibling(&to_pack, obj)
42 #define SET_DELTA(obj, val) oe_set_delta(&to_pack, obj, val)
43 #define SET_DELTA_SIZE(obj, val) oe_set_delta_size(&to_pack, obj, val)
44 #define SET_DELTA_CHILD(obj, val) oe_set_delta_child(&to_pack, obj, val)
45 #define SET_DELTA_SIBLING(obj, val) oe_set_delta_sibling(&to_pack, obj, val)
47 static const char *pack_usage[] = {
48 N_("git pack-objects --stdout [<options>...] [< <ref-list> | < <object-list>]"),
49 N_("git pack-objects [<options>...] <base-name> [< <ref-list> | < <object-list>]"),
54 * Objects we are going to pack are collected in the `to_pack` structure.
55 * It contains an array (dynamically expanded) of the object data, and a map
56 * that can resolve SHA1s to their position in the array.
58 static struct packing_data to_pack;
60 static struct pack_idx_entry **written_list;
61 static uint32_t nr_result, nr_written, nr_seen;
64 static int reuse_delta = 1, reuse_object = 1;
65 static int keep_unreachable, unpack_unreachable, include_tag;
66 static timestamp_t unpack_unreachable_expiration;
67 static int pack_loose_unreachable;
69 static int have_non_local_packs;
70 static int incremental;
71 static int ignore_packed_keep_on_disk;
72 static int ignore_packed_keep_in_core;
73 static int allow_ofs_delta;
74 static struct pack_idx_option pack_idx_opts;
75 static const char *base_name;
76 static int progress = 1;
77 static int window = 10;
78 static unsigned long pack_size_limit;
79 static int depth = 50;
80 static int delta_search_threads;
81 static int pack_to_stdout;
82 static int num_preferred_base;
83 static struct progress *progress_state;
85 static struct packed_git *reuse_packfile;
86 static uint32_t reuse_packfile_objects;
87 static off_t reuse_packfile_offset;
89 static int use_bitmap_index_default = 1;
90 static int use_bitmap_index = -1;
91 static int write_bitmap_index;
92 static uint16_t write_bitmap_options;
94 static int exclude_promisor_objects;
96 static unsigned long delta_cache_size = 0;
97 static unsigned long max_delta_cache_size = DEFAULT_DELTA_CACHE_SIZE;
98 static unsigned long cache_max_small_delta_size = 1000;
100 static unsigned long window_memory_limit = 0;
102 static struct list_objects_filter_options filter_options;
104 enum missing_action {
105 MA_ERROR = 0, /* fail if any missing objects are encountered */
106 MA_ALLOW_ANY, /* silently allow ALL missing objects */
107 MA_ALLOW_PROMISOR, /* silently allow all missing PROMISOR objects */
109 static enum missing_action arg_missing_action;
110 static show_object_fn fn_show_object;
115 static uint32_t written, written_delta;
116 static uint32_t reused, reused_delta;
121 static struct commit **indexed_commits;
122 static unsigned int indexed_commits_nr;
123 static unsigned int indexed_commits_alloc;
125 static void index_commit_for_bitmap(struct commit *commit)
127 if (indexed_commits_nr >= indexed_commits_alloc) {
128 indexed_commits_alloc = (indexed_commits_alloc + 32) * 2;
129 REALLOC_ARRAY(indexed_commits, indexed_commits_alloc);
132 indexed_commits[indexed_commits_nr++] = commit;
135 static void *get_delta(struct object_entry *entry)
137 unsigned long size, base_size, delta_size;
138 void *buf, *base_buf, *delta_buf;
139 enum object_type type;
141 buf = read_object_file(&entry->idx.oid, &type, &size);
143 die("unable to read %s", oid_to_hex(&entry->idx.oid));
144 base_buf = read_object_file(&DELTA(entry)->idx.oid, &type,
147 die("unable to read %s",
148 oid_to_hex(&DELTA(entry)->idx.oid));
149 delta_buf = diff_delta(base_buf, base_size,
150 buf, size, &delta_size, 0);
151 if (!delta_buf || delta_size != DELTA_SIZE(entry))
152 die("delta size changed");
158 static unsigned long do_compress(void **pptr, unsigned long size)
162 unsigned long maxsize;
164 git_deflate_init(&stream, pack_compression_level);
165 maxsize = git_deflate_bound(&stream, size);
168 out = xmalloc(maxsize);
172 stream.avail_in = size;
173 stream.next_out = out;
174 stream.avail_out = maxsize;
175 while (git_deflate(&stream, Z_FINISH) == Z_OK)
177 git_deflate_end(&stream);
180 return stream.total_out;
183 static unsigned long write_large_blob_data(struct git_istream *st, struct hashfile *f,
184 const struct object_id *oid)
187 unsigned char ibuf[1024 * 16];
188 unsigned char obuf[1024 * 16];
189 unsigned long olen = 0;
191 git_deflate_init(&stream, pack_compression_level);
196 readlen = read_istream(st, ibuf, sizeof(ibuf));
198 die(_("unable to read %s"), oid_to_hex(oid));
200 stream.next_in = ibuf;
201 stream.avail_in = readlen;
202 while ((stream.avail_in || readlen == 0) &&
203 (zret == Z_OK || zret == Z_BUF_ERROR)) {
204 stream.next_out = obuf;
205 stream.avail_out = sizeof(obuf);
206 zret = git_deflate(&stream, readlen ? 0 : Z_FINISH);
207 hashwrite(f, obuf, stream.next_out - obuf);
208 olen += stream.next_out - obuf;
211 die(_("deflate error (%d)"), zret);
213 if (zret != Z_STREAM_END)
214 die(_("deflate error (%d)"), zret);
218 git_deflate_end(&stream);
223 * we are going to reuse the existing object data as is. make
224 * sure it is not corrupt.
226 static int check_pack_inflate(struct packed_git *p,
227 struct pack_window **w_curs,
230 unsigned long expect)
233 unsigned char fakebuf[4096], *in;
236 memset(&stream, 0, sizeof(stream));
237 git_inflate_init(&stream);
239 in = use_pack(p, w_curs, offset, &stream.avail_in);
241 stream.next_out = fakebuf;
242 stream.avail_out = sizeof(fakebuf);
243 st = git_inflate(&stream, Z_FINISH);
244 offset += stream.next_in - in;
245 } while (st == Z_OK || st == Z_BUF_ERROR);
246 git_inflate_end(&stream);
247 return (st == Z_STREAM_END &&
248 stream.total_out == expect &&
249 stream.total_in == len) ? 0 : -1;
252 static void copy_pack_data(struct hashfile *f,
253 struct packed_git *p,
254 struct pack_window **w_curs,
262 in = use_pack(p, w_curs, offset, &avail);
264 avail = (unsigned long)len;
265 hashwrite(f, in, avail);
271 /* Return 0 if we will bust the pack-size limit */
272 static unsigned long write_no_reuse_object(struct hashfile *f, struct object_entry *entry,
273 unsigned long limit, int usable_delta)
275 unsigned long size, datalen;
276 unsigned char header[MAX_PACK_OBJECT_HEADER],
277 dheader[MAX_PACK_OBJECT_HEADER];
279 enum object_type type;
281 struct git_istream *st = NULL;
282 const unsigned hashsz = the_hash_algo->rawsz;
285 if (oe_type(entry) == OBJ_BLOB &&
286 oe_size_greater_than(&to_pack, entry, big_file_threshold) &&
287 (st = open_istream(&entry->idx.oid, &type, &size, NULL)) != NULL)
290 buf = read_object_file(&entry->idx.oid, &type, &size);
292 die(_("unable to read %s"),
293 oid_to_hex(&entry->idx.oid));
296 * make sure no cached delta data remains from a
297 * previous attempt before a pack split occurred.
299 FREE_AND_NULL(entry->delta_data);
300 entry->z_delta_size = 0;
301 } else if (entry->delta_data) {
302 size = DELTA_SIZE(entry);
303 buf = entry->delta_data;
304 entry->delta_data = NULL;
305 type = (allow_ofs_delta && DELTA(entry)->idx.offset) ?
306 OBJ_OFS_DELTA : OBJ_REF_DELTA;
308 buf = get_delta(entry);
309 size = DELTA_SIZE(entry);
310 type = (allow_ofs_delta && DELTA(entry)->idx.offset) ?
311 OBJ_OFS_DELTA : OBJ_REF_DELTA;
314 if (st) /* large blob case, just assume we don't compress well */
316 else if (entry->z_delta_size)
317 datalen = entry->z_delta_size;
319 datalen = do_compress(&buf, size);
322 * The object header is a byte of 'type' followed by zero or
323 * more bytes of length.
325 hdrlen = encode_in_pack_object_header(header, sizeof(header),
328 if (type == OBJ_OFS_DELTA) {
330 * Deltas with relative base contain an additional
331 * encoding of the relative offset for the delta
332 * base from this object's position in the pack.
334 off_t ofs = entry->idx.offset - DELTA(entry)->idx.offset;
335 unsigned pos = sizeof(dheader) - 1;
336 dheader[pos] = ofs & 127;
338 dheader[--pos] = 128 | (--ofs & 127);
339 if (limit && hdrlen + sizeof(dheader) - pos + datalen + hashsz >= limit) {
345 hashwrite(f, header, hdrlen);
346 hashwrite(f, dheader + pos, sizeof(dheader) - pos);
347 hdrlen += sizeof(dheader) - pos;
348 } else if (type == OBJ_REF_DELTA) {
350 * Deltas with a base reference contain
351 * additional bytes for the base object ID.
353 if (limit && hdrlen + hashsz + datalen + hashsz >= limit) {
359 hashwrite(f, header, hdrlen);
360 hashwrite(f, DELTA(entry)->idx.oid.hash, hashsz);
363 if (limit && hdrlen + datalen + hashsz >= limit) {
369 hashwrite(f, header, hdrlen);
372 datalen = write_large_blob_data(st, f, &entry->idx.oid);
375 hashwrite(f, buf, datalen);
379 return hdrlen + datalen;
382 /* Return 0 if we will bust the pack-size limit */
383 static off_t write_reuse_object(struct hashfile *f, struct object_entry *entry,
384 unsigned long limit, int usable_delta)
386 struct packed_git *p = IN_PACK(entry);
387 struct pack_window *w_curs = NULL;
388 struct revindex_entry *revidx;
390 enum object_type type = oe_type(entry);
392 unsigned char header[MAX_PACK_OBJECT_HEADER],
393 dheader[MAX_PACK_OBJECT_HEADER];
395 const unsigned hashsz = the_hash_algo->rawsz;
396 unsigned long entry_size = SIZE(entry);
399 type = (allow_ofs_delta && DELTA(entry)->idx.offset) ?
400 OBJ_OFS_DELTA : OBJ_REF_DELTA;
401 hdrlen = encode_in_pack_object_header(header, sizeof(header),
404 offset = entry->in_pack_offset;
405 revidx = find_pack_revindex(p, offset);
406 datalen = revidx[1].offset - offset;
407 if (!pack_to_stdout && p->index_version > 1 &&
408 check_pack_crc(p, &w_curs, offset, datalen, revidx->nr)) {
409 error("bad packed object CRC for %s",
410 oid_to_hex(&entry->idx.oid));
412 return write_no_reuse_object(f, entry, limit, usable_delta);
415 offset += entry->in_pack_header_size;
416 datalen -= entry->in_pack_header_size;
418 if (!pack_to_stdout && p->index_version == 1 &&
419 check_pack_inflate(p, &w_curs, offset, datalen, entry_size)) {
420 error("corrupt packed object for %s",
421 oid_to_hex(&entry->idx.oid));
423 return write_no_reuse_object(f, entry, limit, usable_delta);
426 if (type == OBJ_OFS_DELTA) {
427 off_t ofs = entry->idx.offset - DELTA(entry)->idx.offset;
428 unsigned pos = sizeof(dheader) - 1;
429 dheader[pos] = ofs & 127;
431 dheader[--pos] = 128 | (--ofs & 127);
432 if (limit && hdrlen + sizeof(dheader) - pos + datalen + hashsz >= limit) {
436 hashwrite(f, header, hdrlen);
437 hashwrite(f, dheader + pos, sizeof(dheader) - pos);
438 hdrlen += sizeof(dheader) - pos;
440 } else if (type == OBJ_REF_DELTA) {
441 if (limit && hdrlen + hashsz + datalen + hashsz >= limit) {
445 hashwrite(f, header, hdrlen);
446 hashwrite(f, DELTA(entry)->idx.oid.hash, hashsz);
450 if (limit && hdrlen + datalen + hashsz >= limit) {
454 hashwrite(f, header, hdrlen);
456 copy_pack_data(f, p, &w_curs, offset, datalen);
459 return hdrlen + datalen;
462 /* Return 0 if we will bust the pack-size limit */
463 static off_t write_object(struct hashfile *f,
464 struct object_entry *entry,
469 int usable_delta, to_reuse;
474 /* apply size limit if limited packsize and not first object */
475 if (!pack_size_limit || !nr_written)
477 else if (pack_size_limit <= write_offset)
479 * the earlier object did not fit the limit; avoid
480 * mistaking this with unlimited (i.e. limit = 0).
484 limit = pack_size_limit - write_offset;
487 usable_delta = 0; /* no delta */
488 else if (!pack_size_limit)
489 usable_delta = 1; /* unlimited packfile */
490 else if (DELTA(entry)->idx.offset == (off_t)-1)
491 usable_delta = 0; /* base was written to another pack */
492 else if (DELTA(entry)->idx.offset)
493 usable_delta = 1; /* base already exists in this pack */
495 usable_delta = 0; /* base could end up in another pack */
498 to_reuse = 0; /* explicit */
499 else if (!IN_PACK(entry))
500 to_reuse = 0; /* can't reuse what we don't have */
501 else if (oe_type(entry) == OBJ_REF_DELTA ||
502 oe_type(entry) == OBJ_OFS_DELTA)
503 /* check_object() decided it for us ... */
504 to_reuse = usable_delta;
505 /* ... but pack split may override that */
506 else if (oe_type(entry) != entry->in_pack_type)
507 to_reuse = 0; /* pack has delta which is unusable */
508 else if (DELTA(entry))
509 to_reuse = 0; /* we want to pack afresh */
511 to_reuse = 1; /* we have it in-pack undeltified,
512 * and we do not need to deltify it.
516 len = write_no_reuse_object(f, entry, limit, usable_delta);
518 len = write_reuse_object(f, entry, limit, usable_delta);
526 entry->idx.crc32 = crc32_end(f);
530 enum write_one_status {
531 WRITE_ONE_SKIP = -1, /* already written */
532 WRITE_ONE_BREAK = 0, /* writing this will bust the limit; not written */
533 WRITE_ONE_WRITTEN = 1, /* normal */
534 WRITE_ONE_RECURSIVE = 2 /* already scheduled to be written */
537 static enum write_one_status write_one(struct hashfile *f,
538 struct object_entry *e,
545 * we set offset to 1 (which is an impossible value) to mark
546 * the fact that this object is involved in "write its base
547 * first before writing a deltified object" recursion.
549 recursing = (e->idx.offset == 1);
551 warning("recursive delta detected for object %s",
552 oid_to_hex(&e->idx.oid));
553 return WRITE_ONE_RECURSIVE;
554 } else if (e->idx.offset || e->preferred_base) {
555 /* offset is non zero if object is written already. */
556 return WRITE_ONE_SKIP;
559 /* if we are deltified, write out base object first. */
561 e->idx.offset = 1; /* now recurse */
562 switch (write_one(f, DELTA(e), offset)) {
563 case WRITE_ONE_RECURSIVE:
564 /* we cannot depend on this one */
569 case WRITE_ONE_BREAK:
570 e->idx.offset = recursing;
571 return WRITE_ONE_BREAK;
575 e->idx.offset = *offset;
576 size = write_object(f, e, *offset);
578 e->idx.offset = recursing;
579 return WRITE_ONE_BREAK;
581 written_list[nr_written++] = &e->idx;
583 /* make sure off_t is sufficiently large not to wrap */
584 if (signed_add_overflows(*offset, size))
585 die("pack too large for current definition of off_t");
587 return WRITE_ONE_WRITTEN;
590 static int mark_tagged(const char *path, const struct object_id *oid, int flag,
593 struct object_id peeled;
594 struct object_entry *entry = packlist_find(&to_pack, oid->hash, NULL);
598 if (!peel_ref(path, &peeled)) {
599 entry = packlist_find(&to_pack, peeled.hash, NULL);
606 static inline void add_to_write_order(struct object_entry **wo,
608 struct object_entry *e)
616 static void add_descendants_to_write_order(struct object_entry **wo,
618 struct object_entry *e)
620 int add_to_order = 1;
623 struct object_entry *s;
624 /* add this node... */
625 add_to_write_order(wo, endp, e);
626 /* all its siblings... */
627 for (s = DELTA_SIBLING(e); s; s = DELTA_SIBLING(s)) {
628 add_to_write_order(wo, endp, s);
631 /* drop down a level to add left subtree nodes if possible */
632 if (DELTA_CHILD(e)) {
637 /* our sibling might have some children, it is next */
638 if (DELTA_SIBLING(e)) {
639 e = DELTA_SIBLING(e);
642 /* go back to our parent node */
644 while (e && !DELTA_SIBLING(e)) {
645 /* we're on the right side of a subtree, keep
646 * going up until we can go right again */
650 /* done- we hit our original root node */
653 /* pass it off to sibling at this level */
654 e = DELTA_SIBLING(e);
659 static void add_family_to_write_order(struct object_entry **wo,
661 struct object_entry *e)
663 struct object_entry *root;
665 for (root = e; DELTA(root); root = DELTA(root))
667 add_descendants_to_write_order(wo, endp, root);
670 static struct object_entry **compute_write_order(void)
672 unsigned int i, wo_end, last_untagged;
674 struct object_entry **wo;
675 struct object_entry *objects = to_pack.objects;
677 for (i = 0; i < to_pack.nr_objects; i++) {
678 objects[i].tagged = 0;
679 objects[i].filled = 0;
680 SET_DELTA_CHILD(&objects[i], NULL);
681 SET_DELTA_SIBLING(&objects[i], NULL);
685 * Fully connect delta_child/delta_sibling network.
686 * Make sure delta_sibling is sorted in the original
689 for (i = to_pack.nr_objects; i > 0;) {
690 struct object_entry *e = &objects[--i];
693 /* Mark me as the first child */
694 e->delta_sibling_idx = DELTA(e)->delta_child_idx;
695 SET_DELTA_CHILD(DELTA(e), e);
699 * Mark objects that are at the tip of tags.
701 for_each_tag_ref(mark_tagged, NULL);
704 * Give the objects in the original recency order until
705 * we see a tagged tip.
707 ALLOC_ARRAY(wo, to_pack.nr_objects);
708 for (i = wo_end = 0; i < to_pack.nr_objects; i++) {
709 if (objects[i].tagged)
711 add_to_write_order(wo, &wo_end, &objects[i]);
716 * Then fill all the tagged tips.
718 for (; i < to_pack.nr_objects; i++) {
719 if (objects[i].tagged)
720 add_to_write_order(wo, &wo_end, &objects[i]);
724 * And then all remaining commits and tags.
726 for (i = last_untagged; i < to_pack.nr_objects; i++) {
727 if (oe_type(&objects[i]) != OBJ_COMMIT &&
728 oe_type(&objects[i]) != OBJ_TAG)
730 add_to_write_order(wo, &wo_end, &objects[i]);
734 * And then all the trees.
736 for (i = last_untagged; i < to_pack.nr_objects; i++) {
737 if (oe_type(&objects[i]) != OBJ_TREE)
739 add_to_write_order(wo, &wo_end, &objects[i]);
743 * Finally all the rest in really tight order
745 for (i = last_untagged; i < to_pack.nr_objects; i++) {
746 if (!objects[i].filled)
747 add_family_to_write_order(wo, &wo_end, &objects[i]);
750 if (wo_end != to_pack.nr_objects)
751 die("ordered %u objects, expected %"PRIu32, wo_end, to_pack.nr_objects);
756 static off_t write_reused_pack(struct hashfile *f)
758 unsigned char buffer[8192];
759 off_t to_write, total;
762 if (!is_pack_valid(reuse_packfile))
763 die("packfile is invalid: %s", reuse_packfile->pack_name);
765 fd = git_open(reuse_packfile->pack_name);
767 die_errno("unable to open packfile for reuse: %s",
768 reuse_packfile->pack_name);
770 if (lseek(fd, sizeof(struct pack_header), SEEK_SET) == -1)
771 die_errno("unable to seek in reused packfile");
773 if (reuse_packfile_offset < 0)
774 reuse_packfile_offset = reuse_packfile->pack_size - the_hash_algo->rawsz;
776 total = to_write = reuse_packfile_offset - sizeof(struct pack_header);
779 int read_pack = xread(fd, buffer, sizeof(buffer));
782 die_errno("unable to read from reused packfile");
784 if (read_pack > to_write)
785 read_pack = to_write;
787 hashwrite(f, buffer, read_pack);
788 to_write -= read_pack;
791 * We don't know the actual number of objects written,
792 * only how many bytes written, how many bytes total, and
793 * how many objects total. So we can fake it by pretending all
794 * objects we are writing are the same size. This gives us a
795 * smooth progress meter, and at the end it matches the true
798 written = reuse_packfile_objects *
799 (((double)(total - to_write)) / total);
800 display_progress(progress_state, written);
804 written = reuse_packfile_objects;
805 display_progress(progress_state, written);
806 return reuse_packfile_offset - sizeof(struct pack_header);
809 static const char no_split_warning[] = N_(
810 "disabling bitmap writing, packs are split due to pack.packSizeLimit"
813 static void write_pack_file(void)
818 uint32_t nr_remaining = nr_result;
819 time_t last_mtime = 0;
820 struct object_entry **write_order;
822 if (progress > pack_to_stdout)
823 progress_state = start_progress(_("Writing objects"), nr_result);
824 ALLOC_ARRAY(written_list, to_pack.nr_objects);
825 write_order = compute_write_order();
828 struct object_id oid;
829 char *pack_tmp_name = NULL;
832 f = hashfd_throughput(1, "<stdout>", progress_state);
834 f = create_tmp_packfile(&pack_tmp_name);
836 offset = write_pack_header(f, nr_remaining);
838 if (reuse_packfile) {
840 assert(pack_to_stdout);
842 packfile_size = write_reused_pack(f);
843 offset += packfile_size;
847 for (; i < to_pack.nr_objects; i++) {
848 struct object_entry *e = write_order[i];
849 if (write_one(f, e, &offset) == WRITE_ONE_BREAK)
851 display_progress(progress_state, written);
855 * Did we write the wrong # entries in the header?
856 * If so, rewrite it like in fast-import
858 if (pack_to_stdout) {
859 finalize_hashfile(f, oid.hash, CSUM_HASH_IN_STREAM | CSUM_CLOSE);
860 } else if (nr_written == nr_remaining) {
861 finalize_hashfile(f, oid.hash, CSUM_HASH_IN_STREAM | CSUM_FSYNC | CSUM_CLOSE);
863 int fd = finalize_hashfile(f, oid.hash, 0);
864 fixup_pack_header_footer(fd, oid.hash, pack_tmp_name,
865 nr_written, oid.hash, offset);
867 if (write_bitmap_index) {
868 warning(_(no_split_warning));
869 write_bitmap_index = 0;
873 if (!pack_to_stdout) {
875 struct strbuf tmpname = STRBUF_INIT;
878 * Packs are runtime accessed in their mtime
879 * order since newer packs are more likely to contain
880 * younger objects. So if we are creating multiple
881 * packs then we should modify the mtime of later ones
882 * to preserve this property.
884 if (stat(pack_tmp_name, &st) < 0) {
885 warning_errno("failed to stat %s", pack_tmp_name);
886 } else if (!last_mtime) {
887 last_mtime = st.st_mtime;
890 utb.actime = st.st_atime;
891 utb.modtime = --last_mtime;
892 if (utime(pack_tmp_name, &utb) < 0)
893 warning_errno("failed utime() on %s", pack_tmp_name);
896 strbuf_addf(&tmpname, "%s-", base_name);
898 if (write_bitmap_index) {
899 bitmap_writer_set_checksum(oid.hash);
900 bitmap_writer_build_type_index(
901 &to_pack, written_list, nr_written);
904 finish_tmp_packfile(&tmpname, pack_tmp_name,
905 written_list, nr_written,
906 &pack_idx_opts, oid.hash);
908 if (write_bitmap_index) {
909 strbuf_addf(&tmpname, "%s.bitmap", oid_to_hex(&oid));
911 stop_progress(&progress_state);
913 bitmap_writer_show_progress(progress);
914 bitmap_writer_reuse_bitmaps(&to_pack);
915 bitmap_writer_select_commits(indexed_commits, indexed_commits_nr, -1);
916 bitmap_writer_build(&to_pack);
917 bitmap_writer_finish(written_list, nr_written,
918 tmpname.buf, write_bitmap_options);
919 write_bitmap_index = 0;
922 strbuf_release(&tmpname);
924 puts(oid_to_hex(&oid));
927 /* mark written objects as written to previous pack */
928 for (j = 0; j < nr_written; j++) {
929 written_list[j]->offset = (off_t)-1;
931 nr_remaining -= nr_written;
932 } while (nr_remaining && i < to_pack.nr_objects);
936 stop_progress(&progress_state);
937 if (written != nr_result)
938 die("wrote %"PRIu32" objects while expecting %"PRIu32,
942 static int no_try_delta(const char *path)
944 static struct attr_check *check;
947 check = attr_check_initl("delta", NULL);
948 if (git_check_attr(path, check))
950 if (ATTR_FALSE(check->items[0].value))
956 * When adding an object, check whether we have already added it
957 * to our packing list. If so, we can skip. However, if we are
958 * being asked to excludei t, but the previous mention was to include
959 * it, make sure to adjust its flags and tweak our numbers accordingly.
961 * As an optimization, we pass out the index position where we would have
962 * found the item, since that saves us from having to look it up again a
963 * few lines later when we want to add the new entry.
965 static int have_duplicate_entry(const struct object_id *oid,
969 struct object_entry *entry;
971 entry = packlist_find(&to_pack, oid->hash, index_pos);
976 if (!entry->preferred_base)
978 entry->preferred_base = 1;
984 static int want_found_object(int exclude, struct packed_git *p)
992 * When asked to do --local (do not include an object that appears in a
993 * pack we borrow from elsewhere) or --honor-pack-keep (do not include
994 * an object that appears in a pack marked with .keep), finding a pack
995 * that matches the criteria is sufficient for us to decide to omit it.
996 * However, even if this pack does not satisfy the criteria, we need to
997 * make sure no copy of this object appears in _any_ pack that makes us
998 * to omit the object, so we need to check all the packs.
1000 * We can however first check whether these options can possible matter;
1001 * if they do not matter we know we want the object in generated pack.
1002 * Otherwise, we signal "-1" at the end to tell the caller that we do
1003 * not know either way, and it needs to check more packs.
1005 if (!ignore_packed_keep_on_disk &&
1006 !ignore_packed_keep_in_core &&
1007 (!local || !have_non_local_packs))
1010 if (local && !p->pack_local)
1012 if (p->pack_local &&
1013 ((ignore_packed_keep_on_disk && p->pack_keep) ||
1014 (ignore_packed_keep_in_core && p->pack_keep_in_core)))
1017 /* we don't know yet; keep looking for more packs */
1022 * Check whether we want the object in the pack (e.g., we do not want
1023 * objects found in non-local stores if the "--local" option was used).
1025 * If the caller already knows an existing pack it wants to take the object
1026 * from, that is passed in *found_pack and *found_offset; otherwise this
1027 * function finds if there is any pack that has the object and returns the pack
1028 * and its offset in these variables.
1030 static int want_object_in_pack(const struct object_id *oid,
1032 struct packed_git **found_pack,
1033 off_t *found_offset)
1036 struct list_head *pos;
1038 if (!exclude && local && has_loose_object_nonlocal(oid))
1042 * If we already know the pack object lives in, start checks from that
1043 * pack - in the usual case when neither --local was given nor .keep files
1044 * are present we will determine the answer right now.
1047 want = want_found_object(exclude, *found_pack);
1051 list_for_each(pos, get_packed_git_mru(the_repository)) {
1052 struct packed_git *p = list_entry(pos, struct packed_git, mru);
1055 if (p == *found_pack)
1056 offset = *found_offset;
1058 offset = find_pack_entry_one(oid->hash, p);
1062 if (!is_pack_valid(p))
1064 *found_offset = offset;
1067 want = want_found_object(exclude, p);
1068 if (!exclude && want > 0)
1070 get_packed_git_mru(the_repository));
1079 static void create_object_entry(const struct object_id *oid,
1080 enum object_type type,
1085 struct packed_git *found_pack,
1088 struct object_entry *entry;
1090 entry = packlist_alloc(&to_pack, oid->hash, index_pos);
1092 oe_set_type(entry, type);
1094 entry->preferred_base = 1;
1098 oe_set_in_pack(&to_pack, entry, found_pack);
1099 entry->in_pack_offset = found_offset;
1102 entry->no_try_delta = no_try_delta;
1105 static const char no_closure_warning[] = N_(
1106 "disabling bitmap writing, as some objects are not being packed"
1109 static int add_object_entry(const struct object_id *oid, enum object_type type,
1110 const char *name, int exclude)
1112 struct packed_git *found_pack = NULL;
1113 off_t found_offset = 0;
1116 display_progress(progress_state, ++nr_seen);
1118 if (have_duplicate_entry(oid, exclude, &index_pos))
1121 if (!want_object_in_pack(oid, exclude, &found_pack, &found_offset)) {
1122 /* The pack is missing an object, so it will not have closure */
1123 if (write_bitmap_index) {
1124 warning(_(no_closure_warning));
1125 write_bitmap_index = 0;
1130 create_object_entry(oid, type, pack_name_hash(name),
1131 exclude, name && no_try_delta(name),
1132 index_pos, found_pack, found_offset);
1136 static int add_object_entry_from_bitmap(const struct object_id *oid,
1137 enum object_type type,
1138 int flags, uint32_t name_hash,
1139 struct packed_git *pack, off_t offset)
1143 display_progress(progress_state, ++nr_seen);
1145 if (have_duplicate_entry(oid, 0, &index_pos))
1148 if (!want_object_in_pack(oid, 0, &pack, &offset))
1151 create_object_entry(oid, type, name_hash, 0, 0, index_pos, pack, offset);
1155 struct pbase_tree_cache {
1156 struct object_id oid;
1160 unsigned long tree_size;
1163 static struct pbase_tree_cache *(pbase_tree_cache[256]);
1164 static int pbase_tree_cache_ix(const struct object_id *oid)
1166 return oid->hash[0] % ARRAY_SIZE(pbase_tree_cache);
1168 static int pbase_tree_cache_ix_incr(int ix)
1170 return (ix+1) % ARRAY_SIZE(pbase_tree_cache);
1173 static struct pbase_tree {
1174 struct pbase_tree *next;
1175 /* This is a phony "cache" entry; we are not
1176 * going to evict it or find it through _get()
1177 * mechanism -- this is for the toplevel node that
1178 * would almost always change with any commit.
1180 struct pbase_tree_cache pcache;
1183 static struct pbase_tree_cache *pbase_tree_get(const struct object_id *oid)
1185 struct pbase_tree_cache *ent, *nent;
1188 enum object_type type;
1190 int my_ix = pbase_tree_cache_ix(oid);
1191 int available_ix = -1;
1193 /* pbase-tree-cache acts as a limited hashtable.
1194 * your object will be found at your index or within a few
1195 * slots after that slot if it is cached.
1197 for (neigh = 0; neigh < 8; neigh++) {
1198 ent = pbase_tree_cache[my_ix];
1199 if (ent && !oidcmp(&ent->oid, oid)) {
1203 else if (((available_ix < 0) && (!ent || !ent->ref)) ||
1204 ((0 <= available_ix) &&
1205 (!ent && pbase_tree_cache[available_ix])))
1206 available_ix = my_ix;
1209 my_ix = pbase_tree_cache_ix_incr(my_ix);
1212 /* Did not find one. Either we got a bogus request or
1213 * we need to read and perhaps cache.
1215 data = read_object_file(oid, &type, &size);
1218 if (type != OBJ_TREE) {
1223 /* We need to either cache or return a throwaway copy */
1225 if (available_ix < 0)
1228 ent = pbase_tree_cache[available_ix];
1229 my_ix = available_ix;
1233 nent = xmalloc(sizeof(*nent));
1234 nent->temporary = (available_ix < 0);
1237 /* evict and reuse */
1238 free(ent->tree_data);
1241 oidcpy(&nent->oid, oid);
1242 nent->tree_data = data;
1243 nent->tree_size = size;
1245 if (!nent->temporary)
1246 pbase_tree_cache[my_ix] = nent;
1250 static void pbase_tree_put(struct pbase_tree_cache *cache)
1252 if (!cache->temporary) {
1256 free(cache->tree_data);
1260 static int name_cmp_len(const char *name)
1263 for (i = 0; name[i] && name[i] != '\n' && name[i] != '/'; i++)
1268 static void add_pbase_object(struct tree_desc *tree,
1271 const char *fullname)
1273 struct name_entry entry;
1276 while (tree_entry(tree,&entry)) {
1277 if (S_ISGITLINK(entry.mode))
1279 cmp = tree_entry_len(&entry) != cmplen ? 1 :
1280 memcmp(name, entry.path, cmplen);
1285 if (name[cmplen] != '/') {
1286 add_object_entry(entry.oid,
1287 object_type(entry.mode),
1291 if (S_ISDIR(entry.mode)) {
1292 struct tree_desc sub;
1293 struct pbase_tree_cache *tree;
1294 const char *down = name+cmplen+1;
1295 int downlen = name_cmp_len(down);
1297 tree = pbase_tree_get(entry.oid);
1300 init_tree_desc(&sub, tree->tree_data, tree->tree_size);
1302 add_pbase_object(&sub, down, downlen, fullname);
1303 pbase_tree_put(tree);
1308 static unsigned *done_pbase_paths;
1309 static int done_pbase_paths_num;
1310 static int done_pbase_paths_alloc;
1311 static int done_pbase_path_pos(unsigned hash)
1314 int hi = done_pbase_paths_num;
1316 int mi = lo + (hi - lo) / 2;
1317 if (done_pbase_paths[mi] == hash)
1319 if (done_pbase_paths[mi] < hash)
1327 static int check_pbase_path(unsigned hash)
1329 int pos = done_pbase_path_pos(hash);
1333 ALLOC_GROW(done_pbase_paths,
1334 done_pbase_paths_num + 1,
1335 done_pbase_paths_alloc);
1336 done_pbase_paths_num++;
1337 if (pos < done_pbase_paths_num)
1338 MOVE_ARRAY(done_pbase_paths + pos + 1, done_pbase_paths + pos,
1339 done_pbase_paths_num - pos - 1);
1340 done_pbase_paths[pos] = hash;
1344 static void add_preferred_base_object(const char *name)
1346 struct pbase_tree *it;
1348 unsigned hash = pack_name_hash(name);
1350 if (!num_preferred_base || check_pbase_path(hash))
1353 cmplen = name_cmp_len(name);
1354 for (it = pbase_tree; it; it = it->next) {
1356 add_object_entry(&it->pcache.oid, OBJ_TREE, NULL, 1);
1359 struct tree_desc tree;
1360 init_tree_desc(&tree, it->pcache.tree_data, it->pcache.tree_size);
1361 add_pbase_object(&tree, name, cmplen, name);
1366 static void add_preferred_base(struct object_id *oid)
1368 struct pbase_tree *it;
1371 struct object_id tree_oid;
1373 if (window <= num_preferred_base++)
1376 data = read_object_with_reference(oid, tree_type, &size, &tree_oid);
1380 for (it = pbase_tree; it; it = it->next) {
1381 if (!oidcmp(&it->pcache.oid, &tree_oid)) {
1387 it = xcalloc(1, sizeof(*it));
1388 it->next = pbase_tree;
1391 oidcpy(&it->pcache.oid, &tree_oid);
1392 it->pcache.tree_data = data;
1393 it->pcache.tree_size = size;
1396 static void cleanup_preferred_base(void)
1398 struct pbase_tree *it;
1404 struct pbase_tree *tmp = it;
1406 free(tmp->pcache.tree_data);
1410 for (i = 0; i < ARRAY_SIZE(pbase_tree_cache); i++) {
1411 if (!pbase_tree_cache[i])
1413 free(pbase_tree_cache[i]->tree_data);
1414 FREE_AND_NULL(pbase_tree_cache[i]);
1417 FREE_AND_NULL(done_pbase_paths);
1418 done_pbase_paths_num = done_pbase_paths_alloc = 0;
1421 static void check_object(struct object_entry *entry)
1423 unsigned long canonical_size;
1425 if (IN_PACK(entry)) {
1426 struct packed_git *p = IN_PACK(entry);
1427 struct pack_window *w_curs = NULL;
1428 const unsigned char *base_ref = NULL;
1429 struct object_entry *base_entry;
1430 unsigned long used, used_0;
1431 unsigned long avail;
1433 unsigned char *buf, c;
1434 enum object_type type;
1435 unsigned long in_pack_size;
1437 buf = use_pack(p, &w_curs, entry->in_pack_offset, &avail);
1440 * We want in_pack_type even if we do not reuse delta
1441 * since non-delta representations could still be reused.
1443 used = unpack_object_header_buffer(buf, avail,
1450 BUG("invalid type %d", type);
1451 entry->in_pack_type = type;
1454 * Determine if this is a delta and if so whether we can
1455 * reuse it or not. Otherwise let's find out as cheaply as
1456 * possible what the actual type and size for this object is.
1458 switch (entry->in_pack_type) {
1460 /* Not a delta hence we've already got all we need. */
1461 oe_set_type(entry, entry->in_pack_type);
1462 SET_SIZE(entry, in_pack_size);
1463 entry->in_pack_header_size = used;
1464 if (oe_type(entry) < OBJ_COMMIT || oe_type(entry) > OBJ_BLOB)
1466 unuse_pack(&w_curs);
1469 if (reuse_delta && !entry->preferred_base)
1470 base_ref = use_pack(p, &w_curs,
1471 entry->in_pack_offset + used, NULL);
1472 entry->in_pack_header_size = used + the_hash_algo->rawsz;
1475 buf = use_pack(p, &w_curs,
1476 entry->in_pack_offset + used, NULL);
1482 if (!ofs || MSB(ofs, 7)) {
1483 error("delta base offset overflow in pack for %s",
1484 oid_to_hex(&entry->idx.oid));
1488 ofs = (ofs << 7) + (c & 127);
1490 ofs = entry->in_pack_offset - ofs;
1491 if (ofs <= 0 || ofs >= entry->in_pack_offset) {
1492 error("delta base offset out of bound for %s",
1493 oid_to_hex(&entry->idx.oid));
1496 if (reuse_delta && !entry->preferred_base) {
1497 struct revindex_entry *revidx;
1498 revidx = find_pack_revindex(p, ofs);
1501 base_ref = nth_packed_object_sha1(p, revidx->nr);
1503 entry->in_pack_header_size = used + used_0;
1507 if (base_ref && (base_entry = packlist_find(&to_pack, base_ref, NULL))) {
1509 * If base_ref was set above that means we wish to
1510 * reuse delta data, and we even found that base
1511 * in the list of objects we want to pack. Goodie!
1513 * Depth value does not matter - find_deltas() will
1514 * never consider reused delta as the base object to
1515 * deltify other objects against, in order to avoid
1518 oe_set_type(entry, entry->in_pack_type);
1519 SET_SIZE(entry, in_pack_size); /* delta size */
1520 SET_DELTA(entry, base_entry);
1521 SET_DELTA_SIZE(entry, in_pack_size);
1522 entry->delta_sibling_idx = base_entry->delta_child_idx;
1523 SET_DELTA_CHILD(base_entry, entry);
1524 unuse_pack(&w_curs);
1528 if (oe_type(entry)) {
1532 * This must be a delta and we already know what the
1533 * final object type is. Let's extract the actual
1534 * object size from the delta header.
1536 delta_pos = entry->in_pack_offset + entry->in_pack_header_size;
1537 canonical_size = get_size_from_delta(p, &w_curs, delta_pos);
1538 if (canonical_size == 0)
1540 SET_SIZE(entry, canonical_size);
1541 unuse_pack(&w_curs);
1546 * No choice but to fall back to the recursive delta walk
1547 * with sha1_object_info() to find about the object type
1551 unuse_pack(&w_curs);
1555 oid_object_info(the_repository, &entry->idx.oid, &canonical_size));
1556 if (entry->type_valid) {
1557 SET_SIZE(entry, canonical_size);
1560 * Bad object type is checked in prepare_pack(). This is
1561 * to permit a missing preferred base object to be ignored
1562 * as a preferred base. Doing so can result in a larger
1563 * pack file, but the transfer will still take place.
1568 static int pack_offset_sort(const void *_a, const void *_b)
1570 const struct object_entry *a = *(struct object_entry **)_a;
1571 const struct object_entry *b = *(struct object_entry **)_b;
1572 const struct packed_git *a_in_pack = IN_PACK(a);
1573 const struct packed_git *b_in_pack = IN_PACK(b);
1575 /* avoid filesystem trashing with loose objects */
1576 if (!a_in_pack && !b_in_pack)
1577 return oidcmp(&a->idx.oid, &b->idx.oid);
1579 if (a_in_pack < b_in_pack)
1581 if (a_in_pack > b_in_pack)
1583 return a->in_pack_offset < b->in_pack_offset ? -1 :
1584 (a->in_pack_offset > b->in_pack_offset);
1588 * Drop an on-disk delta we were planning to reuse. Naively, this would
1589 * just involve blanking out the "delta" field, but we have to deal
1590 * with some extra book-keeping:
1592 * 1. Removing ourselves from the delta_sibling linked list.
1594 * 2. Updating our size/type to the non-delta representation. These were
1595 * either not recorded initially (size) or overwritten with the delta type
1596 * (type) when check_object() decided to reuse the delta.
1598 * 3. Resetting our delta depth, as we are now a base object.
1600 static void drop_reused_delta(struct object_entry *entry)
1602 unsigned *idx = &to_pack.objects[entry->delta_idx - 1].delta_child_idx;
1603 struct object_info oi = OBJECT_INFO_INIT;
1604 enum object_type type;
1608 struct object_entry *oe = &to_pack.objects[*idx - 1];
1611 *idx = oe->delta_sibling_idx;
1613 idx = &oe->delta_sibling_idx;
1615 SET_DELTA(entry, NULL);
1620 if (packed_object_info(the_repository, IN_PACK(entry), entry->in_pack_offset, &oi) < 0) {
1622 * We failed to get the info from this pack for some reason;
1623 * fall back to sha1_object_info, which may find another copy.
1624 * And if that fails, the error will be recorded in oe_type(entry)
1625 * and dealt with in prepare_pack().
1628 oid_object_info(the_repository, &entry->idx.oid, &size));
1630 oe_set_type(entry, type);
1632 SET_SIZE(entry, size);
1636 * Follow the chain of deltas from this entry onward, throwing away any links
1637 * that cause us to hit a cycle (as determined by the DFS state flags in
1640 * We also detect too-long reused chains that would violate our --depth
1643 static void break_delta_chains(struct object_entry *entry)
1646 * The actual depth of each object we will write is stored as an int,
1647 * as it cannot exceed our int "depth" limit. But before we break
1648 * changes based no that limit, we may potentially go as deep as the
1649 * number of objects, which is elsewhere bounded to a uint32_t.
1651 uint32_t total_depth;
1652 struct object_entry *cur, *next;
1654 for (cur = entry, total_depth = 0;
1656 cur = DELTA(cur), total_depth++) {
1657 if (cur->dfs_state == DFS_DONE) {
1659 * We've already seen this object and know it isn't
1660 * part of a cycle. We do need to append its depth
1663 total_depth += cur->depth;
1668 * We break cycles before looping, so an ACTIVE state (or any
1669 * other cruft which made its way into the state variable)
1672 if (cur->dfs_state != DFS_NONE)
1673 BUG("confusing delta dfs state in first pass: %d",
1677 * Now we know this is the first time we've seen the object. If
1678 * it's not a delta, we're done traversing, but we'll mark it
1679 * done to save time on future traversals.
1682 cur->dfs_state = DFS_DONE;
1687 * Mark ourselves as active and see if the next step causes
1688 * us to cycle to another active object. It's important to do
1689 * this _before_ we loop, because it impacts where we make the
1690 * cut, and thus how our total_depth counter works.
1691 * E.g., We may see a partial loop like:
1693 * A -> B -> C -> D -> B
1695 * Cutting B->C breaks the cycle. But now the depth of A is
1696 * only 1, and our total_depth counter is at 3. The size of the
1697 * error is always one less than the size of the cycle we
1698 * broke. Commits C and D were "lost" from A's chain.
1700 * If we instead cut D->B, then the depth of A is correct at 3.
1701 * We keep all commits in the chain that we examined.
1703 cur->dfs_state = DFS_ACTIVE;
1704 if (DELTA(cur)->dfs_state == DFS_ACTIVE) {
1705 drop_reused_delta(cur);
1706 cur->dfs_state = DFS_DONE;
1712 * And now that we've gone all the way to the bottom of the chain, we
1713 * need to clear the active flags and set the depth fields as
1714 * appropriate. Unlike the loop above, which can quit when it drops a
1715 * delta, we need to keep going to look for more depth cuts. So we need
1716 * an extra "next" pointer to keep going after we reset cur->delta.
1718 for (cur = entry; cur; cur = next) {
1722 * We should have a chain of zero or more ACTIVE states down to
1723 * a final DONE. We can quit after the DONE, because either it
1724 * has no bases, or we've already handled them in a previous
1727 if (cur->dfs_state == DFS_DONE)
1729 else if (cur->dfs_state != DFS_ACTIVE)
1730 BUG("confusing delta dfs state in second pass: %d",
1734 * If the total_depth is more than depth, then we need to snip
1735 * the chain into two or more smaller chains that don't exceed
1736 * the maximum depth. Most of the resulting chains will contain
1737 * (depth + 1) entries (i.e., depth deltas plus one base), and
1738 * the last chain (i.e., the one containing entry) will contain
1739 * whatever entries are left over, namely
1740 * (total_depth % (depth + 1)) of them.
1742 * Since we are iterating towards decreasing depth, we need to
1743 * decrement total_depth as we go, and we need to write to the
1744 * entry what its final depth will be after all of the
1745 * snipping. Since we're snipping into chains of length (depth
1746 * + 1) entries, the final depth of an entry will be its
1747 * original depth modulo (depth + 1). Any time we encounter an
1748 * entry whose final depth is supposed to be zero, we snip it
1749 * from its delta base, thereby making it so.
1751 cur->depth = (total_depth--) % (depth + 1);
1753 drop_reused_delta(cur);
1755 cur->dfs_state = DFS_DONE;
1759 static void get_object_details(void)
1762 struct object_entry **sorted_by_offset;
1765 progress_state = start_progress(_("Counting objects"),
1766 to_pack.nr_objects);
1768 sorted_by_offset = xcalloc(to_pack.nr_objects, sizeof(struct object_entry *));
1769 for (i = 0; i < to_pack.nr_objects; i++)
1770 sorted_by_offset[i] = to_pack.objects + i;
1771 QSORT(sorted_by_offset, to_pack.nr_objects, pack_offset_sort);
1773 for (i = 0; i < to_pack.nr_objects; i++) {
1774 struct object_entry *entry = sorted_by_offset[i];
1775 check_object(entry);
1776 if (entry->type_valid &&
1777 oe_size_greater_than(&to_pack, entry, big_file_threshold))
1778 entry->no_try_delta = 1;
1779 display_progress(progress_state, i + 1);
1781 stop_progress(&progress_state);
1784 * This must happen in a second pass, since we rely on the delta
1785 * information for the whole list being completed.
1787 for (i = 0; i < to_pack.nr_objects; i++)
1788 break_delta_chains(&to_pack.objects[i]);
1790 free(sorted_by_offset);
1794 * We search for deltas in a list sorted by type, by filename hash, and then
1795 * by size, so that we see progressively smaller and smaller files.
1796 * That's because we prefer deltas to be from the bigger file
1797 * to the smaller -- deletes are potentially cheaper, but perhaps
1798 * more importantly, the bigger file is likely the more recent
1799 * one. The deepest deltas are therefore the oldest objects which are
1800 * less susceptible to be accessed often.
1802 static int type_size_sort(const void *_a, const void *_b)
1804 const struct object_entry *a = *(struct object_entry **)_a;
1805 const struct object_entry *b = *(struct object_entry **)_b;
1806 enum object_type a_type = oe_type(a);
1807 enum object_type b_type = oe_type(b);
1808 unsigned long a_size = SIZE(a);
1809 unsigned long b_size = SIZE(b);
1811 if (a_type > b_type)
1813 if (a_type < b_type)
1815 if (a->hash > b->hash)
1817 if (a->hash < b->hash)
1819 if (a->preferred_base > b->preferred_base)
1821 if (a->preferred_base < b->preferred_base)
1823 if (a_size > b_size)
1825 if (a_size < b_size)
1827 return a < b ? -1 : (a > b); /* newest first */
1831 struct object_entry *entry;
1833 struct delta_index *index;
1837 static int delta_cacheable(unsigned long src_size, unsigned long trg_size,
1838 unsigned long delta_size)
1840 if (max_delta_cache_size && delta_cache_size + delta_size > max_delta_cache_size)
1843 if (delta_size < cache_max_small_delta_size)
1846 /* cache delta, if objects are large enough compared to delta size */
1847 if ((src_size >> 20) + (trg_size >> 21) > (delta_size >> 10))
1855 static pthread_mutex_t read_mutex;
1856 #define read_lock() pthread_mutex_lock(&read_mutex)
1857 #define read_unlock() pthread_mutex_unlock(&read_mutex)
1859 static pthread_mutex_t cache_mutex;
1860 #define cache_lock() pthread_mutex_lock(&cache_mutex)
1861 #define cache_unlock() pthread_mutex_unlock(&cache_mutex)
1863 static pthread_mutex_t progress_mutex;
1864 #define progress_lock() pthread_mutex_lock(&progress_mutex)
1865 #define progress_unlock() pthread_mutex_unlock(&progress_mutex)
1869 #define read_lock() (void)0
1870 #define read_unlock() (void)0
1871 #define cache_lock() (void)0
1872 #define cache_unlock() (void)0
1873 #define progress_lock() (void)0
1874 #define progress_unlock() (void)0
1879 * Return the size of the object without doing any delta
1880 * reconstruction (so non-deltas are true object sizes, but deltas
1881 * return the size of the delta data).
1883 unsigned long oe_get_size_slow(struct packing_data *pack,
1884 const struct object_entry *e)
1886 struct packed_git *p;
1887 struct pack_window *w_curs;
1889 enum object_type type;
1890 unsigned long used, avail, size;
1892 if (e->type_ != OBJ_OFS_DELTA && e->type_ != OBJ_REF_DELTA) {
1894 if (oid_object_info(the_repository, &e->idx.oid, &size) < 0)
1895 die(_("unable to get size of %s"),
1896 oid_to_hex(&e->idx.oid));
1901 p = oe_in_pack(pack, e);
1903 BUG("when e->type is a delta, it must belong to a pack");
1907 buf = use_pack(p, &w_curs, e->in_pack_offset, &avail);
1908 used = unpack_object_header_buffer(buf, avail, &type, &size);
1910 die(_("unable to parse object header of %s"),
1911 oid_to_hex(&e->idx.oid));
1913 unuse_pack(&w_curs);
1918 static int try_delta(struct unpacked *trg, struct unpacked *src,
1919 unsigned max_depth, unsigned long *mem_usage)
1921 struct object_entry *trg_entry = trg->entry;
1922 struct object_entry *src_entry = src->entry;
1923 unsigned long trg_size, src_size, delta_size, sizediff, max_size, sz;
1925 enum object_type type;
1928 /* Don't bother doing diffs between different types */
1929 if (oe_type(trg_entry) != oe_type(src_entry))
1933 * We do not bother to try a delta that we discarded on an
1934 * earlier try, but only when reusing delta data. Note that
1935 * src_entry that is marked as the preferred_base should always
1936 * be considered, as even if we produce a suboptimal delta against
1937 * it, we will still save the transfer cost, as we already know
1938 * the other side has it and we won't send src_entry at all.
1940 if (reuse_delta && IN_PACK(trg_entry) &&
1941 IN_PACK(trg_entry) == IN_PACK(src_entry) &&
1942 !src_entry->preferred_base &&
1943 trg_entry->in_pack_type != OBJ_REF_DELTA &&
1944 trg_entry->in_pack_type != OBJ_OFS_DELTA)
1947 /* Let's not bust the allowed depth. */
1948 if (src->depth >= max_depth)
1951 /* Now some size filtering heuristics. */
1952 trg_size = SIZE(trg_entry);
1953 if (!DELTA(trg_entry)) {
1954 max_size = trg_size/2 - the_hash_algo->rawsz;
1957 max_size = DELTA_SIZE(trg_entry);
1958 ref_depth = trg->depth;
1960 max_size = (uint64_t)max_size * (max_depth - src->depth) /
1961 (max_depth - ref_depth + 1);
1964 src_size = SIZE(src_entry);
1965 sizediff = src_size < trg_size ? trg_size - src_size : 0;
1966 if (sizediff >= max_size)
1968 if (trg_size < src_size / 32)
1971 /* Load data if not already done */
1974 trg->data = read_object_file(&trg_entry->idx.oid, &type, &sz);
1977 die("object %s cannot be read",
1978 oid_to_hex(&trg_entry->idx.oid));
1980 die("object %s inconsistent object length (%lu vs %lu)",
1981 oid_to_hex(&trg_entry->idx.oid), sz,
1987 src->data = read_object_file(&src_entry->idx.oid, &type, &sz);
1990 if (src_entry->preferred_base) {
1991 static int warned = 0;
1993 warning("object %s cannot be read",
1994 oid_to_hex(&src_entry->idx.oid));
1996 * Those objects are not included in the
1997 * resulting pack. Be resilient and ignore
1998 * them if they can't be read, in case the
1999 * pack could be created nevertheless.
2003 die("object %s cannot be read",
2004 oid_to_hex(&src_entry->idx.oid));
2007 die("object %s inconsistent object length (%lu vs %lu)",
2008 oid_to_hex(&src_entry->idx.oid), sz,
2013 src->index = create_delta_index(src->data, src_size);
2015 static int warned = 0;
2017 warning("suboptimal pack - out of memory");
2020 *mem_usage += sizeof_delta_index(src->index);
2023 delta_buf = create_delta(src->index, trg->data, trg_size, &delta_size, max_size);
2026 if (delta_size >= (1U << OE_DELTA_SIZE_BITS)) {
2031 if (DELTA(trg_entry)) {
2032 /* Prefer only shallower same-sized deltas. */
2033 if (delta_size == DELTA_SIZE(trg_entry) &&
2034 src->depth + 1 >= trg->depth) {
2041 * Handle memory allocation outside of the cache
2042 * accounting lock. Compiler will optimize the strangeness
2043 * away when NO_PTHREADS is defined.
2045 free(trg_entry->delta_data);
2047 if (trg_entry->delta_data) {
2048 delta_cache_size -= DELTA_SIZE(trg_entry);
2049 trg_entry->delta_data = NULL;
2051 if (delta_cacheable(src_size, trg_size, delta_size)) {
2052 delta_cache_size += delta_size;
2054 trg_entry->delta_data = xrealloc(delta_buf, delta_size);
2060 SET_DELTA(trg_entry, src_entry);
2061 SET_DELTA_SIZE(trg_entry, delta_size);
2062 trg->depth = src->depth + 1;
2067 static unsigned int check_delta_limit(struct object_entry *me, unsigned int n)
2069 struct object_entry *child = DELTA_CHILD(me);
2072 unsigned int c = check_delta_limit(child, n + 1);
2075 child = DELTA_SIBLING(child);
2080 static unsigned long free_unpacked(struct unpacked *n)
2082 unsigned long freed_mem = sizeof_delta_index(n->index);
2083 free_delta_index(n->index);
2086 freed_mem += SIZE(n->entry);
2087 FREE_AND_NULL(n->data);
2094 static void find_deltas(struct object_entry **list, unsigned *list_size,
2095 int window, int depth, unsigned *processed)
2097 uint32_t i, idx = 0, count = 0;
2098 struct unpacked *array;
2099 unsigned long mem_usage = 0;
2101 array = xcalloc(window, sizeof(struct unpacked));
2104 struct object_entry *entry;
2105 struct unpacked *n = array + idx;
2106 int j, max_depth, best_base = -1;
2115 if (!entry->preferred_base) {
2117 display_progress(progress_state, *processed);
2121 mem_usage -= free_unpacked(n);
2124 while (window_memory_limit &&
2125 mem_usage > window_memory_limit &&
2127 uint32_t tail = (idx + window - count) % window;
2128 mem_usage -= free_unpacked(array + tail);
2132 /* We do not compute delta to *create* objects we are not
2135 if (entry->preferred_base)
2139 * If the current object is at pack edge, take the depth the
2140 * objects that depend on the current object into account
2141 * otherwise they would become too deep.
2144 if (DELTA_CHILD(entry)) {
2145 max_depth -= check_delta_limit(entry, 0);
2153 uint32_t other_idx = idx + j;
2155 if (other_idx >= window)
2156 other_idx -= window;
2157 m = array + other_idx;
2160 ret = try_delta(n, m, max_depth, &mem_usage);
2164 best_base = other_idx;
2168 * If we decided to cache the delta data, then it is best
2169 * to compress it right away. First because we have to do
2170 * it anyway, and doing it here while we're threaded will
2171 * save a lot of time in the non threaded write phase,
2172 * as well as allow for caching more deltas within
2173 * the same cache size limit.
2175 * But only if not writing to stdout, since in that case
2176 * the network is most likely throttling writes anyway,
2177 * and therefore it is best to go to the write phase ASAP
2178 * instead, as we can afford spending more time compressing
2179 * between writes at that moment.
2181 if (entry->delta_data && !pack_to_stdout) {
2184 size = do_compress(&entry->delta_data, DELTA_SIZE(entry));
2185 if (size < (1U << OE_Z_DELTA_BITS)) {
2186 entry->z_delta_size = size;
2188 delta_cache_size -= DELTA_SIZE(entry);
2189 delta_cache_size += entry->z_delta_size;
2192 FREE_AND_NULL(entry->delta_data);
2193 entry->z_delta_size = 0;
2197 /* if we made n a delta, and if n is already at max
2198 * depth, leaving it in the window is pointless. we
2199 * should evict it first.
2201 if (DELTA(entry) && max_depth <= n->depth)
2205 * Move the best delta base up in the window, after the
2206 * currently deltified object, to keep it longer. It will
2207 * be the first base object to be attempted next.
2210 struct unpacked swap = array[best_base];
2211 int dist = (window + idx - best_base) % window;
2212 int dst = best_base;
2214 int src = (dst + 1) % window;
2215 array[dst] = array[src];
2223 if (count + 1 < window)
2229 for (i = 0; i < window; ++i) {
2230 free_delta_index(array[i].index);
2231 free(array[i].data);
2238 static void try_to_free_from_threads(size_t size)
2241 release_pack_memory(size);
2245 static try_to_free_t old_try_to_free_routine;
2248 * The main thread waits on the condition that (at least) one of the workers
2249 * has stopped working (which is indicated in the .working member of
2250 * struct thread_params).
2251 * When a work thread has completed its work, it sets .working to 0 and
2252 * signals the main thread and waits on the condition that .data_ready
2256 struct thread_params {
2258 struct object_entry **list;
2265 pthread_mutex_t mutex;
2266 pthread_cond_t cond;
2267 unsigned *processed;
2270 static pthread_cond_t progress_cond;
2273 * Mutex and conditional variable can't be statically-initialized on Windows.
2275 static void init_threaded_search(void)
2277 init_recursive_mutex(&read_mutex);
2278 pthread_mutex_init(&cache_mutex, NULL);
2279 pthread_mutex_init(&progress_mutex, NULL);
2280 pthread_cond_init(&progress_cond, NULL);
2281 old_try_to_free_routine = set_try_to_free_routine(try_to_free_from_threads);
2284 static void cleanup_threaded_search(void)
2286 set_try_to_free_routine(old_try_to_free_routine);
2287 pthread_cond_destroy(&progress_cond);
2288 pthread_mutex_destroy(&read_mutex);
2289 pthread_mutex_destroy(&cache_mutex);
2290 pthread_mutex_destroy(&progress_mutex);
2293 static void *threaded_find_deltas(void *arg)
2295 struct thread_params *me = arg;
2298 while (me->remaining) {
2301 find_deltas(me->list, &me->remaining,
2302 me->window, me->depth, me->processed);
2306 pthread_cond_signal(&progress_cond);
2310 * We must not set ->data_ready before we wait on the
2311 * condition because the main thread may have set it to 1
2312 * before we get here. In order to be sure that new
2313 * work is available if we see 1 in ->data_ready, it
2314 * was initialized to 0 before this thread was spawned
2315 * and we reset it to 0 right away.
2317 pthread_mutex_lock(&me->mutex);
2318 while (!me->data_ready)
2319 pthread_cond_wait(&me->cond, &me->mutex);
2321 pthread_mutex_unlock(&me->mutex);
2326 /* leave ->working 1 so that this doesn't get more work assigned */
2330 static void ll_find_deltas(struct object_entry **list, unsigned list_size,
2331 int window, int depth, unsigned *processed)
2333 struct thread_params *p;
2334 int i, ret, active_threads = 0;
2336 init_threaded_search();
2338 if (delta_search_threads <= 1) {
2339 find_deltas(list, &list_size, window, depth, processed);
2340 cleanup_threaded_search();
2343 if (progress > pack_to_stdout)
2344 fprintf(stderr, "Delta compression using up to %d threads.\n",
2345 delta_search_threads);
2346 p = xcalloc(delta_search_threads, sizeof(*p));
2348 /* Partition the work amongst work threads. */
2349 for (i = 0; i < delta_search_threads; i++) {
2350 unsigned sub_size = list_size / (delta_search_threads - i);
2352 /* don't use too small segments or no deltas will be found */
2353 if (sub_size < 2*window && i+1 < delta_search_threads)
2356 p[i].window = window;
2358 p[i].processed = processed;
2360 p[i].data_ready = 0;
2362 /* try to split chunks on "path" boundaries */
2363 while (sub_size && sub_size < list_size &&
2364 list[sub_size]->hash &&
2365 list[sub_size]->hash == list[sub_size-1]->hash)
2369 p[i].list_size = sub_size;
2370 p[i].remaining = sub_size;
2373 list_size -= sub_size;
2376 /* Start work threads. */
2377 for (i = 0; i < delta_search_threads; i++) {
2378 if (!p[i].list_size)
2380 pthread_mutex_init(&p[i].mutex, NULL);
2381 pthread_cond_init(&p[i].cond, NULL);
2382 ret = pthread_create(&p[i].thread, NULL,
2383 threaded_find_deltas, &p[i]);
2385 die("unable to create thread: %s", strerror(ret));
2390 * Now let's wait for work completion. Each time a thread is done
2391 * with its work, we steal half of the remaining work from the
2392 * thread with the largest number of unprocessed objects and give
2393 * it to that newly idle thread. This ensure good load balancing
2394 * until the remaining object list segments are simply too short
2395 * to be worth splitting anymore.
2397 while (active_threads) {
2398 struct thread_params *target = NULL;
2399 struct thread_params *victim = NULL;
2400 unsigned sub_size = 0;
2404 for (i = 0; !target && i < delta_search_threads; i++)
2409 pthread_cond_wait(&progress_cond, &progress_mutex);
2412 for (i = 0; i < delta_search_threads; i++)
2413 if (p[i].remaining > 2*window &&
2414 (!victim || victim->remaining < p[i].remaining))
2417 sub_size = victim->remaining / 2;
2418 list = victim->list + victim->list_size - sub_size;
2419 while (sub_size && list[0]->hash &&
2420 list[0]->hash == list[-1]->hash) {
2426 * It is possible for some "paths" to have
2427 * so many objects that no hash boundary
2428 * might be found. Let's just steal the
2429 * exact half in that case.
2431 sub_size = victim->remaining / 2;
2434 target->list = list;
2435 victim->list_size -= sub_size;
2436 victim->remaining -= sub_size;
2438 target->list_size = sub_size;
2439 target->remaining = sub_size;
2440 target->working = 1;
2443 pthread_mutex_lock(&target->mutex);
2444 target->data_ready = 1;
2445 pthread_cond_signal(&target->cond);
2446 pthread_mutex_unlock(&target->mutex);
2449 pthread_join(target->thread, NULL);
2450 pthread_cond_destroy(&target->cond);
2451 pthread_mutex_destroy(&target->mutex);
2455 cleanup_threaded_search();
2460 #define ll_find_deltas(l, s, w, d, p) find_deltas(l, &s, w, d, p)
2463 static void add_tag_chain(const struct object_id *oid)
2468 * We catch duplicates already in add_object_entry(), but we'd
2469 * prefer to do this extra check to avoid having to parse the
2470 * tag at all if we already know that it's being packed (e.g., if
2471 * it was included via bitmaps, we would not have parsed it
2474 if (packlist_find(&to_pack, oid->hash, NULL))
2477 tag = lookup_tag(oid);
2479 if (!tag || parse_tag(tag) || !tag->tagged)
2480 die("unable to pack objects reachable from tag %s",
2483 add_object_entry(&tag->object.oid, OBJ_TAG, NULL, 0);
2485 if (tag->tagged->type != OBJ_TAG)
2488 tag = (struct tag *)tag->tagged;
2492 static int add_ref_tag(const char *path, const struct object_id *oid, int flag, void *cb_data)
2494 struct object_id peeled;
2496 if (starts_with(path, "refs/tags/") && /* is a tag? */
2497 !peel_ref(path, &peeled) && /* peelable? */
2498 packlist_find(&to_pack, peeled.hash, NULL)) /* object packed? */
2503 static void prepare_pack(int window, int depth)
2505 struct object_entry **delta_list;
2506 uint32_t i, nr_deltas;
2509 get_object_details();
2512 * If we're locally repacking then we need to be doubly careful
2513 * from now on in order to make sure no stealth corruption gets
2514 * propagated to the new pack. Clients receiving streamed packs
2515 * should validate everything they get anyway so no need to incur
2516 * the additional cost here in that case.
2518 if (!pack_to_stdout)
2519 do_check_packed_object_crc = 1;
2521 if (!to_pack.nr_objects || !window || !depth)
2524 ALLOC_ARRAY(delta_list, to_pack.nr_objects);
2527 for (i = 0; i < to_pack.nr_objects; i++) {
2528 struct object_entry *entry = to_pack.objects + i;
2531 /* This happens if we decided to reuse existing
2532 * delta from a pack. "reuse_delta &&" is implied.
2536 if (!entry->type_valid ||
2537 oe_size_less_than(&to_pack, entry, 50))
2540 if (entry->no_try_delta)
2543 if (!entry->preferred_base) {
2545 if (oe_type(entry) < 0)
2546 die("unable to get type of object %s",
2547 oid_to_hex(&entry->idx.oid));
2549 if (oe_type(entry) < 0) {
2551 * This object is not found, but we
2552 * don't have to include it anyway.
2558 delta_list[n++] = entry;
2561 if (nr_deltas && n > 1) {
2562 unsigned nr_done = 0;
2564 progress_state = start_progress(_("Compressing objects"),
2566 QSORT(delta_list, n, type_size_sort);
2567 ll_find_deltas(delta_list, n, window+1, depth, &nr_done);
2568 stop_progress(&progress_state);
2569 if (nr_done != nr_deltas)
2570 die("inconsistency with delta count");
2575 static int git_pack_config(const char *k, const char *v, void *cb)
2577 if (!strcmp(k, "pack.window")) {
2578 window = git_config_int(k, v);
2581 if (!strcmp(k, "pack.windowmemory")) {
2582 window_memory_limit = git_config_ulong(k, v);
2585 if (!strcmp(k, "pack.depth")) {
2586 depth = git_config_int(k, v);
2589 if (!strcmp(k, "pack.deltacachesize")) {
2590 max_delta_cache_size = git_config_int(k, v);
2593 if (!strcmp(k, "pack.deltacachelimit")) {
2594 cache_max_small_delta_size = git_config_int(k, v);
2597 if (!strcmp(k, "pack.writebitmaphashcache")) {
2598 if (git_config_bool(k, v))
2599 write_bitmap_options |= BITMAP_OPT_HASH_CACHE;
2601 write_bitmap_options &= ~BITMAP_OPT_HASH_CACHE;
2603 if (!strcmp(k, "pack.usebitmaps")) {
2604 use_bitmap_index_default = git_config_bool(k, v);
2607 if (!strcmp(k, "pack.threads")) {
2608 delta_search_threads = git_config_int(k, v);
2609 if (delta_search_threads < 0)
2610 die("invalid number of threads specified (%d)",
2611 delta_search_threads);
2613 if (delta_search_threads != 1) {
2614 warning("no threads support, ignoring %s", k);
2615 delta_search_threads = 0;
2620 if (!strcmp(k, "pack.indexversion")) {
2621 pack_idx_opts.version = git_config_int(k, v);
2622 if (pack_idx_opts.version > 2)
2623 die("bad pack.indexversion=%"PRIu32,
2624 pack_idx_opts.version);
2627 return git_default_config(k, v, cb);
2630 static void read_object_list_from_stdin(void)
2632 char line[GIT_MAX_HEXSZ + 1 + PATH_MAX + 2];
2633 struct object_id oid;
2637 if (!fgets(line, sizeof(line), stdin)) {
2641 die("fgets returned NULL, not EOF, not error!");
2647 if (line[0] == '-') {
2648 if (get_oid_hex(line+1, &oid))
2649 die("expected edge object ID, got garbage:\n %s",
2651 add_preferred_base(&oid);
2654 if (parse_oid_hex(line, &oid, &p))
2655 die("expected object ID, got garbage:\n %s", line);
2657 add_preferred_base_object(p + 1);
2658 add_object_entry(&oid, OBJ_NONE, p + 1, 0);
2662 /* Remember to update object flag allocation in object.h */
2663 #define OBJECT_ADDED (1u<<20)
2665 static void show_commit(struct commit *commit, void *data)
2667 add_object_entry(&commit->object.oid, OBJ_COMMIT, NULL, 0);
2668 commit->object.flags |= OBJECT_ADDED;
2670 if (write_bitmap_index)
2671 index_commit_for_bitmap(commit);
2674 static void show_object(struct object *obj, const char *name, void *data)
2676 add_preferred_base_object(name);
2677 add_object_entry(&obj->oid, obj->type, name, 0);
2678 obj->flags |= OBJECT_ADDED;
2681 static void show_object__ma_allow_any(struct object *obj, const char *name, void *data)
2683 assert(arg_missing_action == MA_ALLOW_ANY);
2686 * Quietly ignore ALL missing objects. This avoids problems with
2687 * staging them now and getting an odd error later.
2689 if (!has_object_file(&obj->oid))
2692 show_object(obj, name, data);
2695 static void show_object__ma_allow_promisor(struct object *obj, const char *name, void *data)
2697 assert(arg_missing_action == MA_ALLOW_PROMISOR);
2700 * Quietly ignore EXPECTED missing objects. This avoids problems with
2701 * staging them now and getting an odd error later.
2703 if (!has_object_file(&obj->oid) && is_promisor_object(&obj->oid))
2706 show_object(obj, name, data);
2709 static int option_parse_missing_action(const struct option *opt,
2710 const char *arg, int unset)
2715 if (!strcmp(arg, "error")) {
2716 arg_missing_action = MA_ERROR;
2717 fn_show_object = show_object;
2721 if (!strcmp(arg, "allow-any")) {
2722 arg_missing_action = MA_ALLOW_ANY;
2723 fetch_if_missing = 0;
2724 fn_show_object = show_object__ma_allow_any;
2728 if (!strcmp(arg, "allow-promisor")) {
2729 arg_missing_action = MA_ALLOW_PROMISOR;
2730 fetch_if_missing = 0;
2731 fn_show_object = show_object__ma_allow_promisor;
2735 die(_("invalid value for --missing"));
2739 static void show_edge(struct commit *commit)
2741 add_preferred_base(&commit->object.oid);
2744 struct in_pack_object {
2746 struct object *object;
2752 struct in_pack_object *array;
2755 static void mark_in_pack_object(struct object *object, struct packed_git *p, struct in_pack *in_pack)
2757 in_pack->array[in_pack->nr].offset = find_pack_entry_one(object->oid.hash, p);
2758 in_pack->array[in_pack->nr].object = object;
2763 * Compare the objects in the offset order, in order to emulate the
2764 * "git rev-list --objects" output that produced the pack originally.
2766 static int ofscmp(const void *a_, const void *b_)
2768 struct in_pack_object *a = (struct in_pack_object *)a_;
2769 struct in_pack_object *b = (struct in_pack_object *)b_;
2771 if (a->offset < b->offset)
2773 else if (a->offset > b->offset)
2776 return oidcmp(&a->object->oid, &b->object->oid);
2779 static void add_objects_in_unpacked_packs(struct rev_info *revs)
2781 struct packed_git *p;
2782 struct in_pack in_pack;
2785 memset(&in_pack, 0, sizeof(in_pack));
2787 for (p = get_packed_git(the_repository); p; p = p->next) {
2788 struct object_id oid;
2791 if (!p->pack_local || p->pack_keep || p->pack_keep_in_core)
2793 if (open_pack_index(p))
2794 die("cannot open pack index");
2796 ALLOC_GROW(in_pack.array,
2797 in_pack.nr + p->num_objects,
2800 for (i = 0; i < p->num_objects; i++) {
2801 nth_packed_object_oid(&oid, p, i);
2802 o = lookup_unknown_object(oid.hash);
2803 if (!(o->flags & OBJECT_ADDED))
2804 mark_in_pack_object(o, p, &in_pack);
2805 o->flags |= OBJECT_ADDED;
2810 QSORT(in_pack.array, in_pack.nr, ofscmp);
2811 for (i = 0; i < in_pack.nr; i++) {
2812 struct object *o = in_pack.array[i].object;
2813 add_object_entry(&o->oid, o->type, "", 0);
2816 free(in_pack.array);
2819 static int add_loose_object(const struct object_id *oid, const char *path,
2822 enum object_type type = oid_object_info(the_repository, oid, NULL);
2825 warning("loose object at %s could not be examined", path);
2829 add_object_entry(oid, type, "", 0);
2834 * We actually don't even have to worry about reachability here.
2835 * add_object_entry will weed out duplicates, so we just add every
2836 * loose object we find.
2838 static void add_unreachable_loose_objects(void)
2840 for_each_loose_file_in_objdir(get_object_directory(),
2845 static int has_sha1_pack_kept_or_nonlocal(const struct object_id *oid)
2847 static struct packed_git *last_found = (void *)1;
2848 struct packed_git *p;
2850 p = (last_found != (void *)1) ? last_found :
2851 get_packed_git(the_repository);
2854 if ((!p->pack_local || p->pack_keep ||
2855 p->pack_keep_in_core) &&
2856 find_pack_entry_one(oid->hash, p)) {
2860 if (p == last_found)
2861 p = get_packed_git(the_repository);
2864 if (p == last_found)
2871 * Store a list of sha1s that are should not be discarded
2872 * because they are either written too recently, or are
2873 * reachable from another object that was.
2875 * This is filled by get_object_list.
2877 static struct oid_array recent_objects;
2879 static int loosened_object_can_be_discarded(const struct object_id *oid,
2882 if (!unpack_unreachable_expiration)
2884 if (mtime > unpack_unreachable_expiration)
2886 if (oid_array_lookup(&recent_objects, oid) >= 0)
2891 static void loosen_unused_packed_objects(struct rev_info *revs)
2893 struct packed_git *p;
2895 struct object_id oid;
2897 for (p = get_packed_git(the_repository); p; p = p->next) {
2898 if (!p->pack_local || p->pack_keep || p->pack_keep_in_core)
2901 if (open_pack_index(p))
2902 die("cannot open pack index");
2904 for (i = 0; i < p->num_objects; i++) {
2905 nth_packed_object_oid(&oid, p, i);
2906 if (!packlist_find(&to_pack, oid.hash, NULL) &&
2907 !has_sha1_pack_kept_or_nonlocal(&oid) &&
2908 !loosened_object_can_be_discarded(&oid, p->mtime))
2909 if (force_object_loose(&oid, p->mtime))
2910 die("unable to force loose object");
2916 * This tracks any options which pack-reuse code expects to be on, or which a
2917 * reader of the pack might not understand, and which would therefore prevent
2918 * blind reuse of what we have on disk.
2920 static int pack_options_allow_reuse(void)
2922 return pack_to_stdout &&
2924 !ignore_packed_keep_on_disk &&
2925 !ignore_packed_keep_in_core &&
2926 (!local || !have_non_local_packs) &&
2930 static int get_object_list_from_bitmap(struct rev_info *revs)
2932 struct bitmap_index *bitmap_git;
2933 if (!(bitmap_git = prepare_bitmap_walk(revs)))
2936 if (pack_options_allow_reuse() &&
2937 !reuse_partial_packfile_from_bitmap(
2940 &reuse_packfile_objects,
2941 &reuse_packfile_offset)) {
2942 assert(reuse_packfile_objects);
2943 nr_result += reuse_packfile_objects;
2944 display_progress(progress_state, nr_result);
2947 traverse_bitmap_commit_list(bitmap_git, &add_object_entry_from_bitmap);
2948 free_bitmap_index(bitmap_git);
2952 static void record_recent_object(struct object *obj,
2956 oid_array_append(&recent_objects, &obj->oid);
2959 static void record_recent_commit(struct commit *commit, void *data)
2961 oid_array_append(&recent_objects, &commit->object.oid);
2964 static void get_object_list(int ac, const char **av)
2966 struct rev_info revs;
2970 init_revisions(&revs, NULL);
2971 save_commit_buffer = 0;
2972 setup_revisions(ac, av, &revs, NULL);
2974 /* make sure shallows are read */
2975 is_repository_shallow(the_repository);
2977 while (fgets(line, sizeof(line), stdin) != NULL) {
2978 int len = strlen(line);
2979 if (len && line[len - 1] == '\n')
2984 if (!strcmp(line, "--not")) {
2985 flags ^= UNINTERESTING;
2986 write_bitmap_index = 0;
2989 if (starts_with(line, "--shallow ")) {
2990 struct object_id oid;
2991 if (get_oid_hex(line + 10, &oid))
2992 die("not an SHA-1 '%s'", line + 10);
2993 register_shallow(the_repository, &oid);
2994 use_bitmap_index = 0;
2997 die("not a rev '%s'", line);
2999 if (handle_revision_arg(line, &revs, flags, REVARG_CANNOT_BE_FILENAME))
3000 die("bad revision '%s'", line);
3003 if (use_bitmap_index && !get_object_list_from_bitmap(&revs))
3006 if (prepare_revision_walk(&revs))
3007 die("revision walk setup failed");
3008 mark_edges_uninteresting(&revs, show_edge);
3010 if (!fn_show_object)
3011 fn_show_object = show_object;
3012 traverse_commit_list_filtered(&filter_options, &revs,
3013 show_commit, fn_show_object, NULL,
3016 if (unpack_unreachable_expiration) {
3017 revs.ignore_missing_links = 1;
3018 if (add_unseen_recent_objects_to_traversal(&revs,
3019 unpack_unreachable_expiration))
3020 die("unable to add recent objects");
3021 if (prepare_revision_walk(&revs))
3022 die("revision walk setup failed");
3023 traverse_commit_list(&revs, record_recent_commit,
3024 record_recent_object, NULL);
3027 if (keep_unreachable)
3028 add_objects_in_unpacked_packs(&revs);
3029 if (pack_loose_unreachable)
3030 add_unreachable_loose_objects();
3031 if (unpack_unreachable)
3032 loosen_unused_packed_objects(&revs);
3034 oid_array_clear(&recent_objects);
3037 static void add_extra_kept_packs(const struct string_list *names)
3039 struct packed_git *p;
3044 for (p = get_packed_git(the_repository); p; p = p->next) {
3045 const char *name = basename(p->pack_name);
3051 for (i = 0; i < names->nr; i++)
3052 if (!fspathcmp(name, names->items[i].string))
3055 if (i < names->nr) {
3056 p->pack_keep_in_core = 1;
3057 ignore_packed_keep_in_core = 1;
3063 static int option_parse_index_version(const struct option *opt,
3064 const char *arg, int unset)
3067 const char *val = arg;
3068 pack_idx_opts.version = strtoul(val, &c, 10);
3069 if (pack_idx_opts.version > 2)
3070 die(_("unsupported index version %s"), val);
3071 if (*c == ',' && c[1])
3072 pack_idx_opts.off32_limit = strtoul(c+1, &c, 0);
3073 if (*c || pack_idx_opts.off32_limit & 0x80000000)
3074 die(_("bad index version '%s'"), val);
3078 static int option_parse_unpack_unreachable(const struct option *opt,
3079 const char *arg, int unset)
3082 unpack_unreachable = 0;
3083 unpack_unreachable_expiration = 0;
3086 unpack_unreachable = 1;
3088 unpack_unreachable_expiration = approxidate(arg);
3093 int cmd_pack_objects(int argc, const char **argv, const char *prefix)
3095 int use_internal_rev_list = 0;
3098 int all_progress_implied = 0;
3099 struct argv_array rp = ARGV_ARRAY_INIT;
3100 int rev_list_unpacked = 0, rev_list_all = 0, rev_list_reflog = 0;
3101 int rev_list_index = 0;
3102 struct string_list keep_pack_list = STRING_LIST_INIT_NODUP;
3103 struct option pack_objects_options[] = {
3104 OPT_SET_INT('q', "quiet", &progress,
3105 N_("do not show progress meter"), 0),
3106 OPT_SET_INT(0, "progress", &progress,
3107 N_("show progress meter"), 1),
3108 OPT_SET_INT(0, "all-progress", &progress,
3109 N_("show progress meter during object writing phase"), 2),
3110 OPT_BOOL(0, "all-progress-implied",
3111 &all_progress_implied,
3112 N_("similar to --all-progress when progress meter is shown")),
3113 { OPTION_CALLBACK, 0, "index-version", NULL, N_("version[,offset]"),
3114 N_("write the pack index file in the specified idx format version"),
3115 0, option_parse_index_version },
3116 OPT_MAGNITUDE(0, "max-pack-size", &pack_size_limit,
3117 N_("maximum size of each output pack file")),
3118 OPT_BOOL(0, "local", &local,
3119 N_("ignore borrowed objects from alternate object store")),
3120 OPT_BOOL(0, "incremental", &incremental,
3121 N_("ignore packed objects")),
3122 OPT_INTEGER(0, "window", &window,
3123 N_("limit pack window by objects")),
3124 OPT_MAGNITUDE(0, "window-memory", &window_memory_limit,
3125 N_("limit pack window by memory in addition to object limit")),
3126 OPT_INTEGER(0, "depth", &depth,
3127 N_("maximum length of delta chain allowed in the resulting pack")),
3128 OPT_BOOL(0, "reuse-delta", &reuse_delta,
3129 N_("reuse existing deltas")),
3130 OPT_BOOL(0, "reuse-object", &reuse_object,
3131 N_("reuse existing objects")),
3132 OPT_BOOL(0, "delta-base-offset", &allow_ofs_delta,
3133 N_("use OFS_DELTA objects")),
3134 OPT_INTEGER(0, "threads", &delta_search_threads,
3135 N_("use threads when searching for best delta matches")),
3136 OPT_BOOL(0, "non-empty", &non_empty,
3137 N_("do not create an empty pack output")),
3138 OPT_BOOL(0, "revs", &use_internal_rev_list,
3139 N_("read revision arguments from standard input")),
3140 OPT_SET_INT_F(0, "unpacked", &rev_list_unpacked,
3141 N_("limit the objects to those that are not yet packed"),
3142 1, PARSE_OPT_NONEG),
3143 OPT_SET_INT_F(0, "all", &rev_list_all,
3144 N_("include objects reachable from any reference"),
3145 1, PARSE_OPT_NONEG),
3146 OPT_SET_INT_F(0, "reflog", &rev_list_reflog,
3147 N_("include objects referred by reflog entries"),
3148 1, PARSE_OPT_NONEG),
3149 OPT_SET_INT_F(0, "indexed-objects", &rev_list_index,
3150 N_("include objects referred to by the index"),
3151 1, PARSE_OPT_NONEG),
3152 OPT_BOOL(0, "stdout", &pack_to_stdout,
3153 N_("output pack to stdout")),
3154 OPT_BOOL(0, "include-tag", &include_tag,
3155 N_("include tag objects that refer to objects to be packed")),
3156 OPT_BOOL(0, "keep-unreachable", &keep_unreachable,
3157 N_("keep unreachable objects")),
3158 OPT_BOOL(0, "pack-loose-unreachable", &pack_loose_unreachable,
3159 N_("pack loose unreachable objects")),
3160 { OPTION_CALLBACK, 0, "unpack-unreachable", NULL, N_("time"),
3161 N_("unpack unreachable objects newer than <time>"),
3162 PARSE_OPT_OPTARG, option_parse_unpack_unreachable },
3163 OPT_BOOL(0, "thin", &thin,
3164 N_("create thin packs")),
3165 OPT_BOOL(0, "shallow", &shallow,
3166 N_("create packs suitable for shallow fetches")),
3167 OPT_BOOL(0, "honor-pack-keep", &ignore_packed_keep_on_disk,
3168 N_("ignore packs that have companion .keep file")),
3169 OPT_STRING_LIST(0, "keep-pack", &keep_pack_list, N_("name"),
3170 N_("ignore this pack")),
3171 OPT_INTEGER(0, "compression", &pack_compression_level,
3172 N_("pack compression level")),
3173 OPT_SET_INT(0, "keep-true-parents", &grafts_replace_parents,
3174 N_("do not hide commits by grafts"), 0),
3175 OPT_BOOL(0, "use-bitmap-index", &use_bitmap_index,
3176 N_("use a bitmap index if available to speed up counting objects")),
3177 OPT_BOOL(0, "write-bitmap-index", &write_bitmap_index,
3178 N_("write a bitmap index together with the pack index")),
3179 OPT_PARSE_LIST_OBJECTS_FILTER(&filter_options),
3180 { OPTION_CALLBACK, 0, "missing", NULL, N_("action"),
3181 N_("handling for missing objects"), PARSE_OPT_NONEG,
3182 option_parse_missing_action },
3183 OPT_BOOL(0, "exclude-promisor-objects", &exclude_promisor_objects,
3184 N_("do not pack objects in promisor packfiles")),
3188 if (DFS_NUM_STATES > (1 << OE_DFS_STATE_BITS))
3189 BUG("too many dfs states, increase OE_DFS_STATE_BITS");
3191 check_replace_refs = 0;
3193 reset_pack_idx_option(&pack_idx_opts);
3194 git_config(git_pack_config, NULL);
3196 progress = isatty(2);
3197 argc = parse_options(argc, argv, prefix, pack_objects_options,
3201 base_name = argv[0];
3204 if (pack_to_stdout != !base_name || argc)
3205 usage_with_options(pack_usage, pack_objects_options);
3207 if (depth >= (1 << OE_DEPTH_BITS)) {
3208 warning(_("delta chain depth %d is too deep, forcing %d"),
3209 depth, (1 << OE_DEPTH_BITS) - 1);
3210 depth = (1 << OE_DEPTH_BITS) - 1;
3212 if (cache_max_small_delta_size >= (1U << OE_Z_DELTA_BITS)) {
3213 warning(_("pack.deltaCacheLimit is too high, forcing %d"),
3214 (1U << OE_Z_DELTA_BITS) - 1);
3215 cache_max_small_delta_size = (1U << OE_Z_DELTA_BITS) - 1;
3218 argv_array_push(&rp, "pack-objects");
3220 use_internal_rev_list = 1;
3221 argv_array_push(&rp, shallow
3222 ? "--objects-edge-aggressive"
3223 : "--objects-edge");
3225 argv_array_push(&rp, "--objects");
3228 use_internal_rev_list = 1;
3229 argv_array_push(&rp, "--all");
3231 if (rev_list_reflog) {
3232 use_internal_rev_list = 1;
3233 argv_array_push(&rp, "--reflog");
3235 if (rev_list_index) {
3236 use_internal_rev_list = 1;
3237 argv_array_push(&rp, "--indexed-objects");
3239 if (rev_list_unpacked) {
3240 use_internal_rev_list = 1;
3241 argv_array_push(&rp, "--unpacked");
3244 if (exclude_promisor_objects) {
3245 use_internal_rev_list = 1;
3246 fetch_if_missing = 0;
3247 argv_array_push(&rp, "--exclude-promisor-objects");
3249 if (unpack_unreachable || keep_unreachable || pack_loose_unreachable)
3250 use_internal_rev_list = 1;
3254 if (pack_compression_level == -1)
3255 pack_compression_level = Z_DEFAULT_COMPRESSION;
3256 else if (pack_compression_level < 0 || pack_compression_level > Z_BEST_COMPRESSION)
3257 die("bad pack compression level %d", pack_compression_level);
3259 if (!delta_search_threads) /* --threads=0 means autodetect */
3260 delta_search_threads = online_cpus();
3263 if (delta_search_threads != 1)
3264 warning("no threads support, ignoring --threads");
3266 if (!pack_to_stdout && !pack_size_limit)
3267 pack_size_limit = pack_size_limit_cfg;
3268 if (pack_to_stdout && pack_size_limit)
3269 die("--max-pack-size cannot be used to build a pack for transfer.");
3270 if (pack_size_limit && pack_size_limit < 1024*1024) {
3271 warning("minimum pack size limit is 1 MiB");
3272 pack_size_limit = 1024*1024;
3275 if (!pack_to_stdout && thin)
3276 die("--thin cannot be used to build an indexable pack.");
3278 if (keep_unreachable && unpack_unreachable)
3279 die("--keep-unreachable and --unpack-unreachable are incompatible.");
3280 if (!rev_list_all || !rev_list_reflog || !rev_list_index)
3281 unpack_unreachable_expiration = 0;
3283 if (filter_options.choice) {
3284 if (!pack_to_stdout)
3285 die("cannot use --filter without --stdout.");
3286 use_bitmap_index = 0;
3290 * "soft" reasons not to use bitmaps - for on-disk repack by default we want
3292 * - to produce good pack (with bitmap index not-yet-packed objects are
3293 * packed in suboptimal order).
3295 * - to use more robust pack-generation codepath (avoiding possible
3296 * bugs in bitmap code and possible bitmap index corruption).
3298 if (!pack_to_stdout)
3299 use_bitmap_index_default = 0;
3301 if (use_bitmap_index < 0)
3302 use_bitmap_index = use_bitmap_index_default;
3304 /* "hard" reasons not to use bitmaps; these just won't work at all */
3305 if (!use_internal_rev_list || (!pack_to_stdout && write_bitmap_index) || is_repository_shallow(the_repository))
3306 use_bitmap_index = 0;
3308 if (pack_to_stdout || !rev_list_all)
3309 write_bitmap_index = 0;
3311 if (progress && all_progress_implied)
3314 add_extra_kept_packs(&keep_pack_list);
3315 if (ignore_packed_keep_on_disk) {
3316 struct packed_git *p;
3317 for (p = get_packed_git(the_repository); p; p = p->next)
3318 if (p->pack_local && p->pack_keep)
3320 if (!p) /* no keep-able packs found */
3321 ignore_packed_keep_on_disk = 0;
3325 * unlike ignore_packed_keep_on_disk above, we do not
3326 * want to unset "local" based on looking at packs, as
3327 * it also covers non-local objects
3329 struct packed_git *p;
3330 for (p = get_packed_git(the_repository); p; p = p->next) {
3331 if (!p->pack_local) {
3332 have_non_local_packs = 1;
3338 prepare_packing_data(&to_pack);
3341 progress_state = start_progress(_("Enumerating objects"), 0);
3342 if (!use_internal_rev_list)
3343 read_object_list_from_stdin();
3345 get_object_list(rp.argc, rp.argv);
3346 argv_array_clear(&rp);
3348 cleanup_preferred_base();
3349 if (include_tag && nr_result)
3350 for_each_ref(add_ref_tag, NULL);
3351 stop_progress(&progress_state);
3353 if (non_empty && !nr_result)
3356 prepare_pack(window, depth);
3359 fprintf(stderr, "Total %"PRIu32" (delta %"PRIu32"),"
3360 " reused %"PRIu32" (delta %"PRIu32")\n",
3361 written, written_delta, reused, reused_delta);