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"
34 #define IN_PACK(obj) oe_in_pack(&to_pack, obj)
36 static const char *pack_usage[] = {
37 N_("git pack-objects --stdout [<options>...] [< <ref-list> | < <object-list>]"),
38 N_("git pack-objects [<options>...] <base-name> [< <ref-list> | < <object-list>]"),
43 * Objects we are going to pack are collected in the `to_pack` structure.
44 * It contains an array (dynamically expanded) of the object data, and a map
45 * that can resolve SHA1s to their position in the array.
47 static struct packing_data to_pack;
49 static struct pack_idx_entry **written_list;
50 static uint32_t nr_result, nr_written;
53 static int reuse_delta = 1, reuse_object = 1;
54 static int keep_unreachable, unpack_unreachable, include_tag;
55 static timestamp_t unpack_unreachable_expiration;
56 static int pack_loose_unreachable;
58 static int have_non_local_packs;
59 static int incremental;
60 static int ignore_packed_keep;
61 static int allow_ofs_delta;
62 static struct pack_idx_option pack_idx_opts;
63 static const char *base_name;
64 static int progress = 1;
65 static int window = 10;
66 static unsigned long pack_size_limit;
67 static int depth = 50;
68 static int delta_search_threads;
69 static int pack_to_stdout;
70 static int num_preferred_base;
71 static struct progress *progress_state;
73 static struct packed_git *reuse_packfile;
74 static uint32_t reuse_packfile_objects;
75 static off_t reuse_packfile_offset;
77 static int use_bitmap_index_default = 1;
78 static int use_bitmap_index = -1;
79 static int write_bitmap_index;
80 static uint16_t write_bitmap_options;
82 static int exclude_promisor_objects;
84 static unsigned long delta_cache_size = 0;
85 static unsigned long max_delta_cache_size = 256 * 1024 * 1024;
86 static unsigned long cache_max_small_delta_size = 1000;
88 static unsigned long window_memory_limit = 0;
90 static struct list_objects_filter_options filter_options;
93 MA_ERROR = 0, /* fail if any missing objects are encountered */
94 MA_ALLOW_ANY, /* silently allow ALL missing objects */
95 MA_ALLOW_PROMISOR, /* silently allow all missing PROMISOR objects */
97 static enum missing_action arg_missing_action;
98 static show_object_fn fn_show_object;
103 static uint32_t written, written_delta;
104 static uint32_t reused, reused_delta;
109 static struct commit **indexed_commits;
110 static unsigned int indexed_commits_nr;
111 static unsigned int indexed_commits_alloc;
113 static void index_commit_for_bitmap(struct commit *commit)
115 if (indexed_commits_nr >= indexed_commits_alloc) {
116 indexed_commits_alloc = (indexed_commits_alloc + 32) * 2;
117 REALLOC_ARRAY(indexed_commits, indexed_commits_alloc);
120 indexed_commits[indexed_commits_nr++] = commit;
123 static void *get_delta(struct object_entry *entry)
125 unsigned long size, base_size, delta_size;
126 void *buf, *base_buf, *delta_buf;
127 enum object_type type;
129 buf = read_object_file(&entry->idx.oid, &type, &size);
131 die("unable to read %s", oid_to_hex(&entry->idx.oid));
132 base_buf = read_object_file(&entry->delta->idx.oid, &type, &base_size);
134 die("unable to read %s",
135 oid_to_hex(&entry->delta->idx.oid));
136 delta_buf = diff_delta(base_buf, base_size,
137 buf, size, &delta_size, 0);
138 if (!delta_buf || delta_size != entry->delta_size)
139 die("delta size changed");
145 static unsigned long do_compress(void **pptr, unsigned long size)
149 unsigned long maxsize;
151 git_deflate_init(&stream, pack_compression_level);
152 maxsize = git_deflate_bound(&stream, size);
155 out = xmalloc(maxsize);
159 stream.avail_in = size;
160 stream.next_out = out;
161 stream.avail_out = maxsize;
162 while (git_deflate(&stream, Z_FINISH) == Z_OK)
164 git_deflate_end(&stream);
167 return stream.total_out;
170 static unsigned long write_large_blob_data(struct git_istream *st, struct hashfile *f,
171 const struct object_id *oid)
174 unsigned char ibuf[1024 * 16];
175 unsigned char obuf[1024 * 16];
176 unsigned long olen = 0;
178 git_deflate_init(&stream, pack_compression_level);
183 readlen = read_istream(st, ibuf, sizeof(ibuf));
185 die(_("unable to read %s"), oid_to_hex(oid));
187 stream.next_in = ibuf;
188 stream.avail_in = readlen;
189 while ((stream.avail_in || readlen == 0) &&
190 (zret == Z_OK || zret == Z_BUF_ERROR)) {
191 stream.next_out = obuf;
192 stream.avail_out = sizeof(obuf);
193 zret = git_deflate(&stream, readlen ? 0 : Z_FINISH);
194 hashwrite(f, obuf, stream.next_out - obuf);
195 olen += stream.next_out - obuf;
198 die(_("deflate error (%d)"), zret);
200 if (zret != Z_STREAM_END)
201 die(_("deflate error (%d)"), zret);
205 git_deflate_end(&stream);
210 * we are going to reuse the existing object data as is. make
211 * sure it is not corrupt.
213 static int check_pack_inflate(struct packed_git *p,
214 struct pack_window **w_curs,
217 unsigned long expect)
220 unsigned char fakebuf[4096], *in;
223 memset(&stream, 0, sizeof(stream));
224 git_inflate_init(&stream);
226 in = use_pack(p, w_curs, offset, &stream.avail_in);
228 stream.next_out = fakebuf;
229 stream.avail_out = sizeof(fakebuf);
230 st = git_inflate(&stream, Z_FINISH);
231 offset += stream.next_in - in;
232 } while (st == Z_OK || st == Z_BUF_ERROR);
233 git_inflate_end(&stream);
234 return (st == Z_STREAM_END &&
235 stream.total_out == expect &&
236 stream.total_in == len) ? 0 : -1;
239 static void copy_pack_data(struct hashfile *f,
240 struct packed_git *p,
241 struct pack_window **w_curs,
249 in = use_pack(p, w_curs, offset, &avail);
251 avail = (unsigned long)len;
252 hashwrite(f, in, avail);
258 /* Return 0 if we will bust the pack-size limit */
259 static unsigned long write_no_reuse_object(struct hashfile *f, struct object_entry *entry,
260 unsigned long limit, int usable_delta)
262 unsigned long size, datalen;
263 unsigned char header[MAX_PACK_OBJECT_HEADER],
264 dheader[MAX_PACK_OBJECT_HEADER];
266 enum object_type type;
268 struct git_istream *st = NULL;
271 if (oe_type(entry) == OBJ_BLOB &&
272 entry->size > big_file_threshold &&
273 (st = open_istream(&entry->idx.oid, &type, &size, NULL)) != NULL)
276 buf = read_object_file(&entry->idx.oid, &type, &size);
278 die(_("unable to read %s"),
279 oid_to_hex(&entry->idx.oid));
282 * make sure no cached delta data remains from a
283 * previous attempt before a pack split occurred.
285 FREE_AND_NULL(entry->delta_data);
286 entry->z_delta_size = 0;
287 } else if (entry->delta_data) {
288 size = entry->delta_size;
289 buf = entry->delta_data;
290 entry->delta_data = NULL;
291 type = (allow_ofs_delta && entry->delta->idx.offset) ?
292 OBJ_OFS_DELTA : OBJ_REF_DELTA;
294 buf = get_delta(entry);
295 size = entry->delta_size;
296 type = (allow_ofs_delta && entry->delta->idx.offset) ?
297 OBJ_OFS_DELTA : OBJ_REF_DELTA;
300 if (st) /* large blob case, just assume we don't compress well */
302 else if (entry->z_delta_size)
303 datalen = entry->z_delta_size;
305 datalen = do_compress(&buf, size);
308 * The object header is a byte of 'type' followed by zero or
309 * more bytes of length.
311 hdrlen = encode_in_pack_object_header(header, sizeof(header),
314 if (type == OBJ_OFS_DELTA) {
316 * Deltas with relative base contain an additional
317 * encoding of the relative offset for the delta
318 * base from this object's position in the pack.
320 off_t ofs = entry->idx.offset - entry->delta->idx.offset;
321 unsigned pos = sizeof(dheader) - 1;
322 dheader[pos] = ofs & 127;
324 dheader[--pos] = 128 | (--ofs & 127);
325 if (limit && hdrlen + sizeof(dheader) - pos + datalen + 20 >= limit) {
331 hashwrite(f, header, hdrlen);
332 hashwrite(f, dheader + pos, sizeof(dheader) - pos);
333 hdrlen += sizeof(dheader) - pos;
334 } else if (type == OBJ_REF_DELTA) {
336 * Deltas with a base reference contain
337 * an additional 20 bytes for the base sha1.
339 if (limit && hdrlen + 20 + datalen + 20 >= limit) {
345 hashwrite(f, header, hdrlen);
346 hashwrite(f, entry->delta->idx.oid.hash, 20);
349 if (limit && hdrlen + datalen + 20 >= limit) {
355 hashwrite(f, header, hdrlen);
358 datalen = write_large_blob_data(st, f, &entry->idx.oid);
361 hashwrite(f, buf, datalen);
365 return hdrlen + datalen;
368 /* Return 0 if we will bust the pack-size limit */
369 static off_t write_reuse_object(struct hashfile *f, struct object_entry *entry,
370 unsigned long limit, int usable_delta)
372 struct packed_git *p = IN_PACK(entry);
373 struct pack_window *w_curs = NULL;
374 struct revindex_entry *revidx;
376 enum object_type type = oe_type(entry);
378 unsigned char header[MAX_PACK_OBJECT_HEADER],
379 dheader[MAX_PACK_OBJECT_HEADER];
383 type = (allow_ofs_delta && entry->delta->idx.offset) ?
384 OBJ_OFS_DELTA : OBJ_REF_DELTA;
385 hdrlen = encode_in_pack_object_header(header, sizeof(header),
388 offset = entry->in_pack_offset;
389 revidx = find_pack_revindex(p, offset);
390 datalen = revidx[1].offset - offset;
391 if (!pack_to_stdout && p->index_version > 1 &&
392 check_pack_crc(p, &w_curs, offset, datalen, revidx->nr)) {
393 error("bad packed object CRC for %s",
394 oid_to_hex(&entry->idx.oid));
396 return write_no_reuse_object(f, entry, limit, usable_delta);
399 offset += entry->in_pack_header_size;
400 datalen -= entry->in_pack_header_size;
402 if (!pack_to_stdout && p->index_version == 1 &&
403 check_pack_inflate(p, &w_curs, offset, datalen, entry->size)) {
404 error("corrupt packed object for %s",
405 oid_to_hex(&entry->idx.oid));
407 return write_no_reuse_object(f, entry, limit, usable_delta);
410 if (type == OBJ_OFS_DELTA) {
411 off_t ofs = entry->idx.offset - entry->delta->idx.offset;
412 unsigned pos = sizeof(dheader) - 1;
413 dheader[pos] = ofs & 127;
415 dheader[--pos] = 128 | (--ofs & 127);
416 if (limit && hdrlen + sizeof(dheader) - pos + datalen + 20 >= limit) {
420 hashwrite(f, header, hdrlen);
421 hashwrite(f, dheader + pos, sizeof(dheader) - pos);
422 hdrlen += sizeof(dheader) - pos;
424 } else if (type == OBJ_REF_DELTA) {
425 if (limit && hdrlen + 20 + datalen + 20 >= limit) {
429 hashwrite(f, header, hdrlen);
430 hashwrite(f, entry->delta->idx.oid.hash, 20);
434 if (limit && hdrlen + datalen + 20 >= limit) {
438 hashwrite(f, header, hdrlen);
440 copy_pack_data(f, p, &w_curs, offset, datalen);
443 return hdrlen + datalen;
446 /* Return 0 if we will bust the pack-size limit */
447 static off_t write_object(struct hashfile *f,
448 struct object_entry *entry,
453 int usable_delta, to_reuse;
458 /* apply size limit if limited packsize and not first object */
459 if (!pack_size_limit || !nr_written)
461 else if (pack_size_limit <= write_offset)
463 * the earlier object did not fit the limit; avoid
464 * mistaking this with unlimited (i.e. limit = 0).
468 limit = pack_size_limit - write_offset;
471 usable_delta = 0; /* no delta */
472 else if (!pack_size_limit)
473 usable_delta = 1; /* unlimited packfile */
474 else if (entry->delta->idx.offset == (off_t)-1)
475 usable_delta = 0; /* base was written to another pack */
476 else if (entry->delta->idx.offset)
477 usable_delta = 1; /* base already exists in this pack */
479 usable_delta = 0; /* base could end up in another pack */
482 to_reuse = 0; /* explicit */
483 else if (!IN_PACK(entry))
484 to_reuse = 0; /* can't reuse what we don't have */
485 else if (oe_type(entry) == OBJ_REF_DELTA ||
486 oe_type(entry) == OBJ_OFS_DELTA)
487 /* check_object() decided it for us ... */
488 to_reuse = usable_delta;
489 /* ... but pack split may override that */
490 else if (oe_type(entry) != entry->in_pack_type)
491 to_reuse = 0; /* pack has delta which is unusable */
492 else if (entry->delta)
493 to_reuse = 0; /* we want to pack afresh */
495 to_reuse = 1; /* we have it in-pack undeltified,
496 * and we do not need to deltify it.
500 len = write_no_reuse_object(f, entry, limit, usable_delta);
502 len = write_reuse_object(f, entry, limit, usable_delta);
510 entry->idx.crc32 = crc32_end(f);
514 enum write_one_status {
515 WRITE_ONE_SKIP = -1, /* already written */
516 WRITE_ONE_BREAK = 0, /* writing this will bust the limit; not written */
517 WRITE_ONE_WRITTEN = 1, /* normal */
518 WRITE_ONE_RECURSIVE = 2 /* already scheduled to be written */
521 static enum write_one_status write_one(struct hashfile *f,
522 struct object_entry *e,
529 * we set offset to 1 (which is an impossible value) to mark
530 * the fact that this object is involved in "write its base
531 * first before writing a deltified object" recursion.
533 recursing = (e->idx.offset == 1);
535 warning("recursive delta detected for object %s",
536 oid_to_hex(&e->idx.oid));
537 return WRITE_ONE_RECURSIVE;
538 } else if (e->idx.offset || e->preferred_base) {
539 /* offset is non zero if object is written already. */
540 return WRITE_ONE_SKIP;
543 /* if we are deltified, write out base object first. */
545 e->idx.offset = 1; /* now recurse */
546 switch (write_one(f, e->delta, offset)) {
547 case WRITE_ONE_RECURSIVE:
548 /* we cannot depend on this one */
553 case WRITE_ONE_BREAK:
554 e->idx.offset = recursing;
555 return WRITE_ONE_BREAK;
559 e->idx.offset = *offset;
560 size = write_object(f, e, *offset);
562 e->idx.offset = recursing;
563 return WRITE_ONE_BREAK;
565 written_list[nr_written++] = &e->idx;
567 /* make sure off_t is sufficiently large not to wrap */
568 if (signed_add_overflows(*offset, size))
569 die("pack too large for current definition of off_t");
571 return WRITE_ONE_WRITTEN;
574 static int mark_tagged(const char *path, const struct object_id *oid, int flag,
577 struct object_id peeled;
578 struct object_entry *entry = packlist_find(&to_pack, oid->hash, NULL);
582 if (!peel_ref(path, &peeled)) {
583 entry = packlist_find(&to_pack, peeled.hash, NULL);
590 static inline void add_to_write_order(struct object_entry **wo,
592 struct object_entry *e)
600 static void add_descendants_to_write_order(struct object_entry **wo,
602 struct object_entry *e)
604 int add_to_order = 1;
607 struct object_entry *s;
608 /* add this node... */
609 add_to_write_order(wo, endp, e);
610 /* all its siblings... */
611 for (s = e->delta_sibling; s; s = s->delta_sibling) {
612 add_to_write_order(wo, endp, s);
615 /* drop down a level to add left subtree nodes if possible */
616 if (e->delta_child) {
621 /* our sibling might have some children, it is next */
622 if (e->delta_sibling) {
623 e = e->delta_sibling;
626 /* go back to our parent node */
628 while (e && !e->delta_sibling) {
629 /* we're on the right side of a subtree, keep
630 * going up until we can go right again */
634 /* done- we hit our original root node */
637 /* pass it off to sibling at this level */
638 e = e->delta_sibling;
643 static void add_family_to_write_order(struct object_entry **wo,
645 struct object_entry *e)
647 struct object_entry *root;
649 for (root = e; root->delta; root = root->delta)
651 add_descendants_to_write_order(wo, endp, root);
654 static struct object_entry **compute_write_order(void)
656 unsigned int i, wo_end, last_untagged;
658 struct object_entry **wo;
659 struct object_entry *objects = to_pack.objects;
661 for (i = 0; i < to_pack.nr_objects; i++) {
662 objects[i].tagged = 0;
663 objects[i].filled = 0;
664 objects[i].delta_child = NULL;
665 objects[i].delta_sibling = NULL;
669 * Fully connect delta_child/delta_sibling network.
670 * Make sure delta_sibling is sorted in the original
673 for (i = to_pack.nr_objects; i > 0;) {
674 struct object_entry *e = &objects[--i];
677 /* Mark me as the first child */
678 e->delta_sibling = e->delta->delta_child;
679 e->delta->delta_child = e;
683 * Mark objects that are at the tip of tags.
685 for_each_tag_ref(mark_tagged, NULL);
688 * Give the objects in the original recency order until
689 * we see a tagged tip.
691 ALLOC_ARRAY(wo, to_pack.nr_objects);
692 for (i = wo_end = 0; i < to_pack.nr_objects; i++) {
693 if (objects[i].tagged)
695 add_to_write_order(wo, &wo_end, &objects[i]);
700 * Then fill all the tagged tips.
702 for (; i < to_pack.nr_objects; i++) {
703 if (objects[i].tagged)
704 add_to_write_order(wo, &wo_end, &objects[i]);
708 * And then all remaining commits and tags.
710 for (i = last_untagged; i < to_pack.nr_objects; i++) {
711 if (oe_type(&objects[i]) != OBJ_COMMIT &&
712 oe_type(&objects[i]) != OBJ_TAG)
714 add_to_write_order(wo, &wo_end, &objects[i]);
718 * And then all the trees.
720 for (i = last_untagged; i < to_pack.nr_objects; i++) {
721 if (oe_type(&objects[i]) != OBJ_TREE)
723 add_to_write_order(wo, &wo_end, &objects[i]);
727 * Finally all the rest in really tight order
729 for (i = last_untagged; i < to_pack.nr_objects; i++) {
730 if (!objects[i].filled)
731 add_family_to_write_order(wo, &wo_end, &objects[i]);
734 if (wo_end != to_pack.nr_objects)
735 die("ordered %u objects, expected %"PRIu32, wo_end, to_pack.nr_objects);
740 static off_t write_reused_pack(struct hashfile *f)
742 unsigned char buffer[8192];
743 off_t to_write, total;
746 if (!is_pack_valid(reuse_packfile))
747 die("packfile is invalid: %s", reuse_packfile->pack_name);
749 fd = git_open(reuse_packfile->pack_name);
751 die_errno("unable to open packfile for reuse: %s",
752 reuse_packfile->pack_name);
754 if (lseek(fd, sizeof(struct pack_header), SEEK_SET) == -1)
755 die_errno("unable to seek in reused packfile");
757 if (reuse_packfile_offset < 0)
758 reuse_packfile_offset = reuse_packfile->pack_size - 20;
760 total = to_write = reuse_packfile_offset - sizeof(struct pack_header);
763 int read_pack = xread(fd, buffer, sizeof(buffer));
766 die_errno("unable to read from reused packfile");
768 if (read_pack > to_write)
769 read_pack = to_write;
771 hashwrite(f, buffer, read_pack);
772 to_write -= read_pack;
775 * We don't know the actual number of objects written,
776 * only how many bytes written, how many bytes total, and
777 * how many objects total. So we can fake it by pretending all
778 * objects we are writing are the same size. This gives us a
779 * smooth progress meter, and at the end it matches the true
782 written = reuse_packfile_objects *
783 (((double)(total - to_write)) / total);
784 display_progress(progress_state, written);
788 written = reuse_packfile_objects;
789 display_progress(progress_state, written);
790 return reuse_packfile_offset - sizeof(struct pack_header);
793 static const char no_split_warning[] = N_(
794 "disabling bitmap writing, packs are split due to pack.packSizeLimit"
797 static void write_pack_file(void)
802 uint32_t nr_remaining = nr_result;
803 time_t last_mtime = 0;
804 struct object_entry **write_order;
806 if (progress > pack_to_stdout)
807 progress_state = start_progress(_("Writing objects"), nr_result);
808 ALLOC_ARRAY(written_list, to_pack.nr_objects);
809 write_order = compute_write_order();
812 struct object_id oid;
813 char *pack_tmp_name = NULL;
816 f = hashfd_throughput(1, "<stdout>", progress_state);
818 f = create_tmp_packfile(&pack_tmp_name);
820 offset = write_pack_header(f, nr_remaining);
822 if (reuse_packfile) {
824 assert(pack_to_stdout);
826 packfile_size = write_reused_pack(f);
827 offset += packfile_size;
831 for (; i < to_pack.nr_objects; i++) {
832 struct object_entry *e = write_order[i];
833 if (write_one(f, e, &offset) == WRITE_ONE_BREAK)
835 display_progress(progress_state, written);
839 * Did we write the wrong # entries in the header?
840 * If so, rewrite it like in fast-import
842 if (pack_to_stdout) {
843 hashclose(f, oid.hash, CSUM_CLOSE);
844 } else if (nr_written == nr_remaining) {
845 hashclose(f, oid.hash, CSUM_FSYNC);
847 int fd = hashclose(f, oid.hash, 0);
848 fixup_pack_header_footer(fd, oid.hash, pack_tmp_name,
849 nr_written, oid.hash, offset);
851 if (write_bitmap_index) {
852 warning(_(no_split_warning));
853 write_bitmap_index = 0;
857 if (!pack_to_stdout) {
859 struct strbuf tmpname = STRBUF_INIT;
862 * Packs are runtime accessed in their mtime
863 * order since newer packs are more likely to contain
864 * younger objects. So if we are creating multiple
865 * packs then we should modify the mtime of later ones
866 * to preserve this property.
868 if (stat(pack_tmp_name, &st) < 0) {
869 warning_errno("failed to stat %s", pack_tmp_name);
870 } else if (!last_mtime) {
871 last_mtime = st.st_mtime;
874 utb.actime = st.st_atime;
875 utb.modtime = --last_mtime;
876 if (utime(pack_tmp_name, &utb) < 0)
877 warning_errno("failed utime() on %s", pack_tmp_name);
880 strbuf_addf(&tmpname, "%s-", base_name);
882 if (write_bitmap_index) {
883 bitmap_writer_set_checksum(oid.hash);
884 bitmap_writer_build_type_index(
885 &to_pack, written_list, nr_written);
888 finish_tmp_packfile(&tmpname, pack_tmp_name,
889 written_list, nr_written,
890 &pack_idx_opts, oid.hash);
892 if (write_bitmap_index) {
893 strbuf_addf(&tmpname, "%s.bitmap", oid_to_hex(&oid));
895 stop_progress(&progress_state);
897 bitmap_writer_show_progress(progress);
898 bitmap_writer_reuse_bitmaps(&to_pack);
899 bitmap_writer_select_commits(indexed_commits, indexed_commits_nr, -1);
900 bitmap_writer_build(&to_pack);
901 bitmap_writer_finish(written_list, nr_written,
902 tmpname.buf, write_bitmap_options);
903 write_bitmap_index = 0;
906 strbuf_release(&tmpname);
908 puts(oid_to_hex(&oid));
911 /* mark written objects as written to previous pack */
912 for (j = 0; j < nr_written; j++) {
913 written_list[j]->offset = (off_t)-1;
915 nr_remaining -= nr_written;
916 } while (nr_remaining && i < to_pack.nr_objects);
920 stop_progress(&progress_state);
921 if (written != nr_result)
922 die("wrote %"PRIu32" objects while expecting %"PRIu32,
926 static int no_try_delta(const char *path)
928 static struct attr_check *check;
931 check = attr_check_initl("delta", NULL);
932 if (git_check_attr(path, check))
934 if (ATTR_FALSE(check->items[0].value))
940 * When adding an object, check whether we have already added it
941 * to our packing list. If so, we can skip. However, if we are
942 * being asked to excludei t, but the previous mention was to include
943 * it, make sure to adjust its flags and tweak our numbers accordingly.
945 * As an optimization, we pass out the index position where we would have
946 * found the item, since that saves us from having to look it up again a
947 * few lines later when we want to add the new entry.
949 static int have_duplicate_entry(const struct object_id *oid,
953 struct object_entry *entry;
955 entry = packlist_find(&to_pack, oid->hash, index_pos);
960 if (!entry->preferred_base)
962 entry->preferred_base = 1;
968 static int want_found_object(int exclude, struct packed_git *p)
976 * When asked to do --local (do not include an object that appears in a
977 * pack we borrow from elsewhere) or --honor-pack-keep (do not include
978 * an object that appears in a pack marked with .keep), finding a pack
979 * that matches the criteria is sufficient for us to decide to omit it.
980 * However, even if this pack does not satisfy the criteria, we need to
981 * make sure no copy of this object appears in _any_ pack that makes us
982 * to omit the object, so we need to check all the packs.
984 * We can however first check whether these options can possible matter;
985 * if they do not matter we know we want the object in generated pack.
986 * Otherwise, we signal "-1" at the end to tell the caller that we do
987 * not know either way, and it needs to check more packs.
989 if (!ignore_packed_keep &&
990 (!local || !have_non_local_packs))
993 if (local && !p->pack_local)
995 if (ignore_packed_keep && p->pack_local && p->pack_keep)
998 /* we don't know yet; keep looking for more packs */
1003 * Check whether we want the object in the pack (e.g., we do not want
1004 * objects found in non-local stores if the "--local" option was used).
1006 * If the caller already knows an existing pack it wants to take the object
1007 * from, that is passed in *found_pack and *found_offset; otherwise this
1008 * function finds if there is any pack that has the object and returns the pack
1009 * and its offset in these variables.
1011 static int want_object_in_pack(const struct object_id *oid,
1013 struct packed_git **found_pack,
1014 off_t *found_offset)
1017 struct list_head *pos;
1019 if (!exclude && local && has_loose_object_nonlocal(oid->hash))
1023 * If we already know the pack object lives in, start checks from that
1024 * pack - in the usual case when neither --local was given nor .keep files
1025 * are present we will determine the answer right now.
1028 want = want_found_object(exclude, *found_pack);
1032 list_for_each(pos, get_packed_git_mru(the_repository)) {
1033 struct packed_git *p = list_entry(pos, struct packed_git, mru);
1036 if (p == *found_pack)
1037 offset = *found_offset;
1039 offset = find_pack_entry_one(oid->hash, p);
1043 if (!is_pack_valid(p))
1045 *found_offset = offset;
1048 want = want_found_object(exclude, p);
1049 if (!exclude && want > 0)
1051 get_packed_git_mru(the_repository));
1060 static void create_object_entry(const struct object_id *oid,
1061 enum object_type type,
1066 struct packed_git *found_pack,
1069 struct object_entry *entry;
1071 entry = packlist_alloc(&to_pack, oid->hash, index_pos);
1073 oe_set_type(entry, type);
1075 entry->preferred_base = 1;
1079 oe_set_in_pack(&to_pack, entry, found_pack);
1080 entry->in_pack_offset = found_offset;
1083 entry->no_try_delta = no_try_delta;
1086 static const char no_closure_warning[] = N_(
1087 "disabling bitmap writing, as some objects are not being packed"
1090 static int add_object_entry(const struct object_id *oid, enum object_type type,
1091 const char *name, int exclude)
1093 struct packed_git *found_pack = NULL;
1094 off_t found_offset = 0;
1097 if (have_duplicate_entry(oid, exclude, &index_pos))
1100 if (!want_object_in_pack(oid, exclude, &found_pack, &found_offset)) {
1101 /* The pack is missing an object, so it will not have closure */
1102 if (write_bitmap_index) {
1103 warning(_(no_closure_warning));
1104 write_bitmap_index = 0;
1109 create_object_entry(oid, type, pack_name_hash(name),
1110 exclude, name && no_try_delta(name),
1111 index_pos, found_pack, found_offset);
1113 display_progress(progress_state, nr_result);
1117 static int add_object_entry_from_bitmap(const struct object_id *oid,
1118 enum object_type type,
1119 int flags, uint32_t name_hash,
1120 struct packed_git *pack, off_t offset)
1124 if (have_duplicate_entry(oid, 0, &index_pos))
1127 if (!want_object_in_pack(oid, 0, &pack, &offset))
1130 create_object_entry(oid, type, name_hash, 0, 0, index_pos, pack, offset);
1132 display_progress(progress_state, nr_result);
1136 struct pbase_tree_cache {
1137 struct object_id oid;
1141 unsigned long tree_size;
1144 static struct pbase_tree_cache *(pbase_tree_cache[256]);
1145 static int pbase_tree_cache_ix(const struct object_id *oid)
1147 return oid->hash[0] % ARRAY_SIZE(pbase_tree_cache);
1149 static int pbase_tree_cache_ix_incr(int ix)
1151 return (ix+1) % ARRAY_SIZE(pbase_tree_cache);
1154 static struct pbase_tree {
1155 struct pbase_tree *next;
1156 /* This is a phony "cache" entry; we are not
1157 * going to evict it or find it through _get()
1158 * mechanism -- this is for the toplevel node that
1159 * would almost always change with any commit.
1161 struct pbase_tree_cache pcache;
1164 static struct pbase_tree_cache *pbase_tree_get(const struct object_id *oid)
1166 struct pbase_tree_cache *ent, *nent;
1169 enum object_type type;
1171 int my_ix = pbase_tree_cache_ix(oid);
1172 int available_ix = -1;
1174 /* pbase-tree-cache acts as a limited hashtable.
1175 * your object will be found at your index or within a few
1176 * slots after that slot if it is cached.
1178 for (neigh = 0; neigh < 8; neigh++) {
1179 ent = pbase_tree_cache[my_ix];
1180 if (ent && !oidcmp(&ent->oid, oid)) {
1184 else if (((available_ix < 0) && (!ent || !ent->ref)) ||
1185 ((0 <= available_ix) &&
1186 (!ent && pbase_tree_cache[available_ix])))
1187 available_ix = my_ix;
1190 my_ix = pbase_tree_cache_ix_incr(my_ix);
1193 /* Did not find one. Either we got a bogus request or
1194 * we need to read and perhaps cache.
1196 data = read_object_file(oid, &type, &size);
1199 if (type != OBJ_TREE) {
1204 /* We need to either cache or return a throwaway copy */
1206 if (available_ix < 0)
1209 ent = pbase_tree_cache[available_ix];
1210 my_ix = available_ix;
1214 nent = xmalloc(sizeof(*nent));
1215 nent->temporary = (available_ix < 0);
1218 /* evict and reuse */
1219 free(ent->tree_data);
1222 oidcpy(&nent->oid, oid);
1223 nent->tree_data = data;
1224 nent->tree_size = size;
1226 if (!nent->temporary)
1227 pbase_tree_cache[my_ix] = nent;
1231 static void pbase_tree_put(struct pbase_tree_cache *cache)
1233 if (!cache->temporary) {
1237 free(cache->tree_data);
1241 static int name_cmp_len(const char *name)
1244 for (i = 0; name[i] && name[i] != '\n' && name[i] != '/'; i++)
1249 static void add_pbase_object(struct tree_desc *tree,
1252 const char *fullname)
1254 struct name_entry entry;
1257 while (tree_entry(tree,&entry)) {
1258 if (S_ISGITLINK(entry.mode))
1260 cmp = tree_entry_len(&entry) != cmplen ? 1 :
1261 memcmp(name, entry.path, cmplen);
1266 if (name[cmplen] != '/') {
1267 add_object_entry(entry.oid,
1268 object_type(entry.mode),
1272 if (S_ISDIR(entry.mode)) {
1273 struct tree_desc sub;
1274 struct pbase_tree_cache *tree;
1275 const char *down = name+cmplen+1;
1276 int downlen = name_cmp_len(down);
1278 tree = pbase_tree_get(entry.oid);
1281 init_tree_desc(&sub, tree->tree_data, tree->tree_size);
1283 add_pbase_object(&sub, down, downlen, fullname);
1284 pbase_tree_put(tree);
1289 static unsigned *done_pbase_paths;
1290 static int done_pbase_paths_num;
1291 static int done_pbase_paths_alloc;
1292 static int done_pbase_path_pos(unsigned hash)
1295 int hi = done_pbase_paths_num;
1297 int mi = lo + (hi - lo) / 2;
1298 if (done_pbase_paths[mi] == hash)
1300 if (done_pbase_paths[mi] < hash)
1308 static int check_pbase_path(unsigned hash)
1310 int pos = done_pbase_path_pos(hash);
1314 ALLOC_GROW(done_pbase_paths,
1315 done_pbase_paths_num + 1,
1316 done_pbase_paths_alloc);
1317 done_pbase_paths_num++;
1318 if (pos < done_pbase_paths_num)
1319 MOVE_ARRAY(done_pbase_paths + pos + 1, done_pbase_paths + pos,
1320 done_pbase_paths_num - pos - 1);
1321 done_pbase_paths[pos] = hash;
1325 static void add_preferred_base_object(const char *name)
1327 struct pbase_tree *it;
1329 unsigned hash = pack_name_hash(name);
1331 if (!num_preferred_base || check_pbase_path(hash))
1334 cmplen = name_cmp_len(name);
1335 for (it = pbase_tree; it; it = it->next) {
1337 add_object_entry(&it->pcache.oid, OBJ_TREE, NULL, 1);
1340 struct tree_desc tree;
1341 init_tree_desc(&tree, it->pcache.tree_data, it->pcache.tree_size);
1342 add_pbase_object(&tree, name, cmplen, name);
1347 static void add_preferred_base(struct object_id *oid)
1349 struct pbase_tree *it;
1352 struct object_id tree_oid;
1354 if (window <= num_preferred_base++)
1357 data = read_object_with_reference(oid, tree_type, &size, &tree_oid);
1361 for (it = pbase_tree; it; it = it->next) {
1362 if (!oidcmp(&it->pcache.oid, &tree_oid)) {
1368 it = xcalloc(1, sizeof(*it));
1369 it->next = pbase_tree;
1372 oidcpy(&it->pcache.oid, &tree_oid);
1373 it->pcache.tree_data = data;
1374 it->pcache.tree_size = size;
1377 static void cleanup_preferred_base(void)
1379 struct pbase_tree *it;
1385 struct pbase_tree *tmp = it;
1387 free(tmp->pcache.tree_data);
1391 for (i = 0; i < ARRAY_SIZE(pbase_tree_cache); i++) {
1392 if (!pbase_tree_cache[i])
1394 free(pbase_tree_cache[i]->tree_data);
1395 FREE_AND_NULL(pbase_tree_cache[i]);
1398 FREE_AND_NULL(done_pbase_paths);
1399 done_pbase_paths_num = done_pbase_paths_alloc = 0;
1402 static void check_object(struct object_entry *entry)
1404 if (IN_PACK(entry)) {
1405 struct packed_git *p = IN_PACK(entry);
1406 struct pack_window *w_curs = NULL;
1407 const unsigned char *base_ref = NULL;
1408 struct object_entry *base_entry;
1409 unsigned long used, used_0;
1410 unsigned long avail;
1412 unsigned char *buf, c;
1413 enum object_type type;
1415 buf = use_pack(p, &w_curs, entry->in_pack_offset, &avail);
1418 * We want in_pack_type even if we do not reuse delta
1419 * since non-delta representations could still be reused.
1421 used = unpack_object_header_buffer(buf, avail,
1428 BUG("invalid type %d", type);
1429 entry->in_pack_type = type;
1432 * Determine if this is a delta and if so whether we can
1433 * reuse it or not. Otherwise let's find out as cheaply as
1434 * possible what the actual type and size for this object is.
1436 switch (entry->in_pack_type) {
1438 /* Not a delta hence we've already got all we need. */
1439 oe_set_type(entry, entry->in_pack_type);
1440 entry->in_pack_header_size = used;
1441 if (oe_type(entry) < OBJ_COMMIT || oe_type(entry) > OBJ_BLOB)
1443 unuse_pack(&w_curs);
1446 if (reuse_delta && !entry->preferred_base)
1447 base_ref = use_pack(p, &w_curs,
1448 entry->in_pack_offset + used, NULL);
1449 entry->in_pack_header_size = used + 20;
1452 buf = use_pack(p, &w_curs,
1453 entry->in_pack_offset + used, NULL);
1459 if (!ofs || MSB(ofs, 7)) {
1460 error("delta base offset overflow in pack for %s",
1461 oid_to_hex(&entry->idx.oid));
1465 ofs = (ofs << 7) + (c & 127);
1467 ofs = entry->in_pack_offset - ofs;
1468 if (ofs <= 0 || ofs >= entry->in_pack_offset) {
1469 error("delta base offset out of bound for %s",
1470 oid_to_hex(&entry->idx.oid));
1473 if (reuse_delta && !entry->preferred_base) {
1474 struct revindex_entry *revidx;
1475 revidx = find_pack_revindex(p, ofs);
1478 base_ref = nth_packed_object_sha1(p, revidx->nr);
1480 entry->in_pack_header_size = used + used_0;
1484 if (base_ref && (base_entry = packlist_find(&to_pack, base_ref, NULL))) {
1486 * If base_ref was set above that means we wish to
1487 * reuse delta data, and we even found that base
1488 * in the list of objects we want to pack. Goodie!
1490 * Depth value does not matter - find_deltas() will
1491 * never consider reused delta as the base object to
1492 * deltify other objects against, in order to avoid
1495 oe_set_type(entry, entry->in_pack_type);
1496 entry->delta = base_entry;
1497 entry->delta_size = entry->size;
1498 entry->delta_sibling = base_entry->delta_child;
1499 base_entry->delta_child = entry;
1500 unuse_pack(&w_curs);
1504 if (oe_type(entry)) {
1506 * This must be a delta and we already know what the
1507 * final object type is. Let's extract the actual
1508 * object size from the delta header.
1510 entry->size = get_size_from_delta(p, &w_curs,
1511 entry->in_pack_offset + entry->in_pack_header_size);
1512 if (entry->size == 0)
1514 unuse_pack(&w_curs);
1519 * No choice but to fall back to the recursive delta walk
1520 * with sha1_object_info() to find about the object type
1524 unuse_pack(&w_curs);
1527 oe_set_type(entry, oid_object_info(&entry->idx.oid, &entry->size));
1529 * The error condition is checked in prepare_pack(). This is
1530 * to permit a missing preferred base object to be ignored
1531 * as a preferred base. Doing so can result in a larger
1532 * pack file, but the transfer will still take place.
1536 static int pack_offset_sort(const void *_a, const void *_b)
1538 const struct object_entry *a = *(struct object_entry **)_a;
1539 const struct object_entry *b = *(struct object_entry **)_b;
1540 const struct packed_git *a_in_pack = IN_PACK(a);
1541 const struct packed_git *b_in_pack = IN_PACK(b);
1543 /* avoid filesystem trashing with loose objects */
1544 if (!a_in_pack && !b_in_pack)
1545 return oidcmp(&a->idx.oid, &b->idx.oid);
1547 if (a_in_pack < b_in_pack)
1549 if (a_in_pack > b_in_pack)
1551 return a->in_pack_offset < b->in_pack_offset ? -1 :
1552 (a->in_pack_offset > b->in_pack_offset);
1556 * Drop an on-disk delta we were planning to reuse. Naively, this would
1557 * just involve blanking out the "delta" field, but we have to deal
1558 * with some extra book-keeping:
1560 * 1. Removing ourselves from the delta_sibling linked list.
1562 * 2. Updating our size/type to the non-delta representation. These were
1563 * either not recorded initially (size) or overwritten with the delta type
1564 * (type) when check_object() decided to reuse the delta.
1566 * 3. Resetting our delta depth, as we are now a base object.
1568 static void drop_reused_delta(struct object_entry *entry)
1570 struct object_entry **p = &entry->delta->delta_child;
1571 struct object_info oi = OBJECT_INFO_INIT;
1572 enum object_type type;
1576 *p = (*p)->delta_sibling;
1578 p = &(*p)->delta_sibling;
1580 entry->delta = NULL;
1583 oi.sizep = &entry->size;
1585 if (packed_object_info(IN_PACK(entry), entry->in_pack_offset, &oi) < 0) {
1587 * We failed to get the info from this pack for some reason;
1588 * fall back to sha1_object_info, which may find another copy.
1589 * And if that fails, the error will be recorded in oe_type(entry)
1590 * and dealt with in prepare_pack().
1592 oe_set_type(entry, oid_object_info(&entry->idx.oid,
1595 oe_set_type(entry, type);
1600 * Follow the chain of deltas from this entry onward, throwing away any links
1601 * that cause us to hit a cycle (as determined by the DFS state flags in
1604 * We also detect too-long reused chains that would violate our --depth
1607 static void break_delta_chains(struct object_entry *entry)
1610 * The actual depth of each object we will write is stored as an int,
1611 * as it cannot exceed our int "depth" limit. But before we break
1612 * changes based no that limit, we may potentially go as deep as the
1613 * number of objects, which is elsewhere bounded to a uint32_t.
1615 uint32_t total_depth;
1616 struct object_entry *cur, *next;
1618 for (cur = entry, total_depth = 0;
1620 cur = cur->delta, total_depth++) {
1621 if (cur->dfs_state == DFS_DONE) {
1623 * We've already seen this object and know it isn't
1624 * part of a cycle. We do need to append its depth
1627 total_depth += cur->depth;
1632 * We break cycles before looping, so an ACTIVE state (or any
1633 * other cruft which made its way into the state variable)
1636 if (cur->dfs_state != DFS_NONE)
1637 die("BUG: confusing delta dfs state in first pass: %d",
1641 * Now we know this is the first time we've seen the object. If
1642 * it's not a delta, we're done traversing, but we'll mark it
1643 * done to save time on future traversals.
1646 cur->dfs_state = DFS_DONE;
1651 * Mark ourselves as active and see if the next step causes
1652 * us to cycle to another active object. It's important to do
1653 * this _before_ we loop, because it impacts where we make the
1654 * cut, and thus how our total_depth counter works.
1655 * E.g., We may see a partial loop like:
1657 * A -> B -> C -> D -> B
1659 * Cutting B->C breaks the cycle. But now the depth of A is
1660 * only 1, and our total_depth counter is at 3. The size of the
1661 * error is always one less than the size of the cycle we
1662 * broke. Commits C and D were "lost" from A's chain.
1664 * If we instead cut D->B, then the depth of A is correct at 3.
1665 * We keep all commits in the chain that we examined.
1667 cur->dfs_state = DFS_ACTIVE;
1668 if (cur->delta->dfs_state == DFS_ACTIVE) {
1669 drop_reused_delta(cur);
1670 cur->dfs_state = DFS_DONE;
1676 * And now that we've gone all the way to the bottom of the chain, we
1677 * need to clear the active flags and set the depth fields as
1678 * appropriate. Unlike the loop above, which can quit when it drops a
1679 * delta, we need to keep going to look for more depth cuts. So we need
1680 * an extra "next" pointer to keep going after we reset cur->delta.
1682 for (cur = entry; cur; cur = next) {
1686 * We should have a chain of zero or more ACTIVE states down to
1687 * a final DONE. We can quit after the DONE, because either it
1688 * has no bases, or we've already handled them in a previous
1691 if (cur->dfs_state == DFS_DONE)
1693 else if (cur->dfs_state != DFS_ACTIVE)
1694 die("BUG: confusing delta dfs state in second pass: %d",
1698 * If the total_depth is more than depth, then we need to snip
1699 * the chain into two or more smaller chains that don't exceed
1700 * the maximum depth. Most of the resulting chains will contain
1701 * (depth + 1) entries (i.e., depth deltas plus one base), and
1702 * the last chain (i.e., the one containing entry) will contain
1703 * whatever entries are left over, namely
1704 * (total_depth % (depth + 1)) of them.
1706 * Since we are iterating towards decreasing depth, we need to
1707 * decrement total_depth as we go, and we need to write to the
1708 * entry what its final depth will be after all of the
1709 * snipping. Since we're snipping into chains of length (depth
1710 * + 1) entries, the final depth of an entry will be its
1711 * original depth modulo (depth + 1). Any time we encounter an
1712 * entry whose final depth is supposed to be zero, we snip it
1713 * from its delta base, thereby making it so.
1715 cur->depth = (total_depth--) % (depth + 1);
1717 drop_reused_delta(cur);
1719 cur->dfs_state = DFS_DONE;
1723 static void get_object_details(void)
1726 struct object_entry **sorted_by_offset;
1728 sorted_by_offset = xcalloc(to_pack.nr_objects, sizeof(struct object_entry *));
1729 for (i = 0; i < to_pack.nr_objects; i++)
1730 sorted_by_offset[i] = to_pack.objects + i;
1731 QSORT(sorted_by_offset, to_pack.nr_objects, pack_offset_sort);
1733 for (i = 0; i < to_pack.nr_objects; i++) {
1734 struct object_entry *entry = sorted_by_offset[i];
1735 check_object(entry);
1736 if (big_file_threshold < entry->size)
1737 entry->no_try_delta = 1;
1741 * This must happen in a second pass, since we rely on the delta
1742 * information for the whole list being completed.
1744 for (i = 0; i < to_pack.nr_objects; i++)
1745 break_delta_chains(&to_pack.objects[i]);
1747 free(sorted_by_offset);
1751 * We search for deltas in a list sorted by type, by filename hash, and then
1752 * by size, so that we see progressively smaller and smaller files.
1753 * That's because we prefer deltas to be from the bigger file
1754 * to the smaller -- deletes are potentially cheaper, but perhaps
1755 * more importantly, the bigger file is likely the more recent
1756 * one. The deepest deltas are therefore the oldest objects which are
1757 * less susceptible to be accessed often.
1759 static int type_size_sort(const void *_a, const void *_b)
1761 const struct object_entry *a = *(struct object_entry **)_a;
1762 const struct object_entry *b = *(struct object_entry **)_b;
1763 enum object_type a_type = oe_type(a);
1764 enum object_type b_type = oe_type(b);
1766 if (a_type > b_type)
1768 if (a_type < b_type)
1770 if (a->hash > b->hash)
1772 if (a->hash < b->hash)
1774 if (a->preferred_base > b->preferred_base)
1776 if (a->preferred_base < b->preferred_base)
1778 if (a->size > b->size)
1780 if (a->size < b->size)
1782 return a < b ? -1 : (a > b); /* newest first */
1786 struct object_entry *entry;
1788 struct delta_index *index;
1792 static int delta_cacheable(unsigned long src_size, unsigned long trg_size,
1793 unsigned long delta_size)
1795 if (max_delta_cache_size && delta_cache_size + delta_size > max_delta_cache_size)
1798 if (delta_size < cache_max_small_delta_size)
1801 /* cache delta, if objects are large enough compared to delta size */
1802 if ((src_size >> 20) + (trg_size >> 21) > (delta_size >> 10))
1810 static pthread_mutex_t read_mutex;
1811 #define read_lock() pthread_mutex_lock(&read_mutex)
1812 #define read_unlock() pthread_mutex_unlock(&read_mutex)
1814 static pthread_mutex_t cache_mutex;
1815 #define cache_lock() pthread_mutex_lock(&cache_mutex)
1816 #define cache_unlock() pthread_mutex_unlock(&cache_mutex)
1818 static pthread_mutex_t progress_mutex;
1819 #define progress_lock() pthread_mutex_lock(&progress_mutex)
1820 #define progress_unlock() pthread_mutex_unlock(&progress_mutex)
1824 #define read_lock() (void)0
1825 #define read_unlock() (void)0
1826 #define cache_lock() (void)0
1827 #define cache_unlock() (void)0
1828 #define progress_lock() (void)0
1829 #define progress_unlock() (void)0
1833 static int try_delta(struct unpacked *trg, struct unpacked *src,
1834 unsigned max_depth, unsigned long *mem_usage)
1836 struct object_entry *trg_entry = trg->entry;
1837 struct object_entry *src_entry = src->entry;
1838 unsigned long trg_size, src_size, delta_size, sizediff, max_size, sz;
1840 enum object_type type;
1843 /* Don't bother doing diffs between different types */
1844 if (oe_type(trg_entry) != oe_type(src_entry))
1848 * We do not bother to try a delta that we discarded on an
1849 * earlier try, but only when reusing delta data. Note that
1850 * src_entry that is marked as the preferred_base should always
1851 * be considered, as even if we produce a suboptimal delta against
1852 * it, we will still save the transfer cost, as we already know
1853 * the other side has it and we won't send src_entry at all.
1855 if (reuse_delta && IN_PACK(trg_entry) &&
1856 IN_PACK(trg_entry) == IN_PACK(src_entry) &&
1857 !src_entry->preferred_base &&
1858 trg_entry->in_pack_type != OBJ_REF_DELTA &&
1859 trg_entry->in_pack_type != OBJ_OFS_DELTA)
1862 /* Let's not bust the allowed depth. */
1863 if (src->depth >= max_depth)
1866 /* Now some size filtering heuristics. */
1867 trg_size = trg_entry->size;
1868 if (!trg_entry->delta) {
1869 max_size = trg_size/2 - 20;
1872 max_size = trg_entry->delta_size;
1873 ref_depth = trg->depth;
1875 max_size = (uint64_t)max_size * (max_depth - src->depth) /
1876 (max_depth - ref_depth + 1);
1879 src_size = src_entry->size;
1880 sizediff = src_size < trg_size ? trg_size - src_size : 0;
1881 if (sizediff >= max_size)
1883 if (trg_size < src_size / 32)
1886 /* Load data if not already done */
1889 trg->data = read_object_file(&trg_entry->idx.oid, &type, &sz);
1892 die("object %s cannot be read",
1893 oid_to_hex(&trg_entry->idx.oid));
1895 die("object %s inconsistent object length (%lu vs %lu)",
1896 oid_to_hex(&trg_entry->idx.oid), sz,
1902 src->data = read_object_file(&src_entry->idx.oid, &type, &sz);
1905 if (src_entry->preferred_base) {
1906 static int warned = 0;
1908 warning("object %s cannot be read",
1909 oid_to_hex(&src_entry->idx.oid));
1911 * Those objects are not included in the
1912 * resulting pack. Be resilient and ignore
1913 * them if they can't be read, in case the
1914 * pack could be created nevertheless.
1918 die("object %s cannot be read",
1919 oid_to_hex(&src_entry->idx.oid));
1922 die("object %s inconsistent object length (%lu vs %lu)",
1923 oid_to_hex(&src_entry->idx.oid), sz,
1928 src->index = create_delta_index(src->data, src_size);
1930 static int warned = 0;
1932 warning("suboptimal pack - out of memory");
1935 *mem_usage += sizeof_delta_index(src->index);
1938 delta_buf = create_delta(src->index, trg->data, trg_size, &delta_size, max_size);
1942 if (trg_entry->delta) {
1943 /* Prefer only shallower same-sized deltas. */
1944 if (delta_size == trg_entry->delta_size &&
1945 src->depth + 1 >= trg->depth) {
1952 * Handle memory allocation outside of the cache
1953 * accounting lock. Compiler will optimize the strangeness
1954 * away when NO_PTHREADS is defined.
1956 free(trg_entry->delta_data);
1958 if (trg_entry->delta_data) {
1959 delta_cache_size -= trg_entry->delta_size;
1960 trg_entry->delta_data = NULL;
1962 if (delta_cacheable(src_size, trg_size, delta_size)) {
1963 delta_cache_size += delta_size;
1965 trg_entry->delta_data = xrealloc(delta_buf, delta_size);
1971 trg_entry->delta = src_entry;
1972 trg_entry->delta_size = delta_size;
1973 trg->depth = src->depth + 1;
1978 static unsigned int check_delta_limit(struct object_entry *me, unsigned int n)
1980 struct object_entry *child = me->delta_child;
1983 unsigned int c = check_delta_limit(child, n + 1);
1986 child = child->delta_sibling;
1991 static unsigned long free_unpacked(struct unpacked *n)
1993 unsigned long freed_mem = sizeof_delta_index(n->index);
1994 free_delta_index(n->index);
1997 freed_mem += n->entry->size;
1998 FREE_AND_NULL(n->data);
2005 static void find_deltas(struct object_entry **list, unsigned *list_size,
2006 int window, int depth, unsigned *processed)
2008 uint32_t i, idx = 0, count = 0;
2009 struct unpacked *array;
2010 unsigned long mem_usage = 0;
2012 array = xcalloc(window, sizeof(struct unpacked));
2015 struct object_entry *entry;
2016 struct unpacked *n = array + idx;
2017 int j, max_depth, best_base = -1;
2026 if (!entry->preferred_base) {
2028 display_progress(progress_state, *processed);
2032 mem_usage -= free_unpacked(n);
2035 while (window_memory_limit &&
2036 mem_usage > window_memory_limit &&
2038 uint32_t tail = (idx + window - count) % window;
2039 mem_usage -= free_unpacked(array + tail);
2043 /* We do not compute delta to *create* objects we are not
2046 if (entry->preferred_base)
2050 * If the current object is at pack edge, take the depth the
2051 * objects that depend on the current object into account
2052 * otherwise they would become too deep.
2055 if (entry->delta_child) {
2056 max_depth -= check_delta_limit(entry, 0);
2064 uint32_t other_idx = idx + j;
2066 if (other_idx >= window)
2067 other_idx -= window;
2068 m = array + other_idx;
2071 ret = try_delta(n, m, max_depth, &mem_usage);
2075 best_base = other_idx;
2079 * If we decided to cache the delta data, then it is best
2080 * to compress it right away. First because we have to do
2081 * it anyway, and doing it here while we're threaded will
2082 * save a lot of time in the non threaded write phase,
2083 * as well as allow for caching more deltas within
2084 * the same cache size limit.
2086 * But only if not writing to stdout, since in that case
2087 * the network is most likely throttling writes anyway,
2088 * and therefore it is best to go to the write phase ASAP
2089 * instead, as we can afford spending more time compressing
2090 * between writes at that moment.
2092 if (entry->delta_data && !pack_to_stdout) {
2093 entry->z_delta_size = do_compress(&entry->delta_data,
2096 delta_cache_size -= entry->delta_size;
2097 delta_cache_size += entry->z_delta_size;
2101 /* if we made n a delta, and if n is already at max
2102 * depth, leaving it in the window is pointless. we
2103 * should evict it first.
2105 if (entry->delta && max_depth <= n->depth)
2109 * Move the best delta base up in the window, after the
2110 * currently deltified object, to keep it longer. It will
2111 * be the first base object to be attempted next.
2114 struct unpacked swap = array[best_base];
2115 int dist = (window + idx - best_base) % window;
2116 int dst = best_base;
2118 int src = (dst + 1) % window;
2119 array[dst] = array[src];
2127 if (count + 1 < window)
2133 for (i = 0; i < window; ++i) {
2134 free_delta_index(array[i].index);
2135 free(array[i].data);
2142 static void try_to_free_from_threads(size_t size)
2145 release_pack_memory(size);
2149 static try_to_free_t old_try_to_free_routine;
2152 * The main thread waits on the condition that (at least) one of the workers
2153 * has stopped working (which is indicated in the .working member of
2154 * struct thread_params).
2155 * When a work thread has completed its work, it sets .working to 0 and
2156 * signals the main thread and waits on the condition that .data_ready
2160 struct thread_params {
2162 struct object_entry **list;
2169 pthread_mutex_t mutex;
2170 pthread_cond_t cond;
2171 unsigned *processed;
2174 static pthread_cond_t progress_cond;
2177 * Mutex and conditional variable can't be statically-initialized on Windows.
2179 static void init_threaded_search(void)
2181 init_recursive_mutex(&read_mutex);
2182 pthread_mutex_init(&cache_mutex, NULL);
2183 pthread_mutex_init(&progress_mutex, NULL);
2184 pthread_cond_init(&progress_cond, NULL);
2185 old_try_to_free_routine = set_try_to_free_routine(try_to_free_from_threads);
2188 static void cleanup_threaded_search(void)
2190 set_try_to_free_routine(old_try_to_free_routine);
2191 pthread_cond_destroy(&progress_cond);
2192 pthread_mutex_destroy(&read_mutex);
2193 pthread_mutex_destroy(&cache_mutex);
2194 pthread_mutex_destroy(&progress_mutex);
2197 static void *threaded_find_deltas(void *arg)
2199 struct thread_params *me = arg;
2202 while (me->remaining) {
2205 find_deltas(me->list, &me->remaining,
2206 me->window, me->depth, me->processed);
2210 pthread_cond_signal(&progress_cond);
2214 * We must not set ->data_ready before we wait on the
2215 * condition because the main thread may have set it to 1
2216 * before we get here. In order to be sure that new
2217 * work is available if we see 1 in ->data_ready, it
2218 * was initialized to 0 before this thread was spawned
2219 * and we reset it to 0 right away.
2221 pthread_mutex_lock(&me->mutex);
2222 while (!me->data_ready)
2223 pthread_cond_wait(&me->cond, &me->mutex);
2225 pthread_mutex_unlock(&me->mutex);
2230 /* leave ->working 1 so that this doesn't get more work assigned */
2234 static void ll_find_deltas(struct object_entry **list, unsigned list_size,
2235 int window, int depth, unsigned *processed)
2237 struct thread_params *p;
2238 int i, ret, active_threads = 0;
2240 init_threaded_search();
2242 if (delta_search_threads <= 1) {
2243 find_deltas(list, &list_size, window, depth, processed);
2244 cleanup_threaded_search();
2247 if (progress > pack_to_stdout)
2248 fprintf(stderr, "Delta compression using up to %d threads.\n",
2249 delta_search_threads);
2250 p = xcalloc(delta_search_threads, sizeof(*p));
2252 /* Partition the work amongst work threads. */
2253 for (i = 0; i < delta_search_threads; i++) {
2254 unsigned sub_size = list_size / (delta_search_threads - i);
2256 /* don't use too small segments or no deltas will be found */
2257 if (sub_size < 2*window && i+1 < delta_search_threads)
2260 p[i].window = window;
2262 p[i].processed = processed;
2264 p[i].data_ready = 0;
2266 /* try to split chunks on "path" boundaries */
2267 while (sub_size && sub_size < list_size &&
2268 list[sub_size]->hash &&
2269 list[sub_size]->hash == list[sub_size-1]->hash)
2273 p[i].list_size = sub_size;
2274 p[i].remaining = sub_size;
2277 list_size -= sub_size;
2280 /* Start work threads. */
2281 for (i = 0; i < delta_search_threads; i++) {
2282 if (!p[i].list_size)
2284 pthread_mutex_init(&p[i].mutex, NULL);
2285 pthread_cond_init(&p[i].cond, NULL);
2286 ret = pthread_create(&p[i].thread, NULL,
2287 threaded_find_deltas, &p[i]);
2289 die("unable to create thread: %s", strerror(ret));
2294 * Now let's wait for work completion. Each time a thread is done
2295 * with its work, we steal half of the remaining work from the
2296 * thread with the largest number of unprocessed objects and give
2297 * it to that newly idle thread. This ensure good load balancing
2298 * until the remaining object list segments are simply too short
2299 * to be worth splitting anymore.
2301 while (active_threads) {
2302 struct thread_params *target = NULL;
2303 struct thread_params *victim = NULL;
2304 unsigned sub_size = 0;
2308 for (i = 0; !target && i < delta_search_threads; i++)
2313 pthread_cond_wait(&progress_cond, &progress_mutex);
2316 for (i = 0; i < delta_search_threads; i++)
2317 if (p[i].remaining > 2*window &&
2318 (!victim || victim->remaining < p[i].remaining))
2321 sub_size = victim->remaining / 2;
2322 list = victim->list + victim->list_size - sub_size;
2323 while (sub_size && list[0]->hash &&
2324 list[0]->hash == list[-1]->hash) {
2330 * It is possible for some "paths" to have
2331 * so many objects that no hash boundary
2332 * might be found. Let's just steal the
2333 * exact half in that case.
2335 sub_size = victim->remaining / 2;
2338 target->list = list;
2339 victim->list_size -= sub_size;
2340 victim->remaining -= sub_size;
2342 target->list_size = sub_size;
2343 target->remaining = sub_size;
2344 target->working = 1;
2347 pthread_mutex_lock(&target->mutex);
2348 target->data_ready = 1;
2349 pthread_cond_signal(&target->cond);
2350 pthread_mutex_unlock(&target->mutex);
2353 pthread_join(target->thread, NULL);
2354 pthread_cond_destroy(&target->cond);
2355 pthread_mutex_destroy(&target->mutex);
2359 cleanup_threaded_search();
2364 #define ll_find_deltas(l, s, w, d, p) find_deltas(l, &s, w, d, p)
2367 static void add_tag_chain(const struct object_id *oid)
2372 * We catch duplicates already in add_object_entry(), but we'd
2373 * prefer to do this extra check to avoid having to parse the
2374 * tag at all if we already know that it's being packed (e.g., if
2375 * it was included via bitmaps, we would not have parsed it
2378 if (packlist_find(&to_pack, oid->hash, NULL))
2381 tag = lookup_tag(oid);
2383 if (!tag || parse_tag(tag) || !tag->tagged)
2384 die("unable to pack objects reachable from tag %s",
2387 add_object_entry(&tag->object.oid, OBJ_TAG, NULL, 0);
2389 if (tag->tagged->type != OBJ_TAG)
2392 tag = (struct tag *)tag->tagged;
2396 static int add_ref_tag(const char *path, const struct object_id *oid, int flag, void *cb_data)
2398 struct object_id peeled;
2400 if (starts_with(path, "refs/tags/") && /* is a tag? */
2401 !peel_ref(path, &peeled) && /* peelable? */
2402 packlist_find(&to_pack, peeled.hash, NULL)) /* object packed? */
2407 static void prepare_pack(int window, int depth)
2409 struct object_entry **delta_list;
2410 uint32_t i, nr_deltas;
2413 get_object_details();
2416 * If we're locally repacking then we need to be doubly careful
2417 * from now on in order to make sure no stealth corruption gets
2418 * propagated to the new pack. Clients receiving streamed packs
2419 * should validate everything they get anyway so no need to incur
2420 * the additional cost here in that case.
2422 if (!pack_to_stdout)
2423 do_check_packed_object_crc = 1;
2425 if (!to_pack.nr_objects || !window || !depth)
2428 ALLOC_ARRAY(delta_list, to_pack.nr_objects);
2431 for (i = 0; i < to_pack.nr_objects; i++) {
2432 struct object_entry *entry = to_pack.objects + i;
2435 /* This happens if we decided to reuse existing
2436 * delta from a pack. "reuse_delta &&" is implied.
2440 if (entry->size < 50)
2443 if (entry->no_try_delta)
2446 if (!entry->preferred_base) {
2448 if (oe_type(entry) < 0)
2449 die("unable to get type of object %s",
2450 oid_to_hex(&entry->idx.oid));
2452 if (oe_type(entry) < 0) {
2454 * This object is not found, but we
2455 * don't have to include it anyway.
2461 delta_list[n++] = entry;
2464 if (nr_deltas && n > 1) {
2465 unsigned nr_done = 0;
2467 progress_state = start_progress(_("Compressing objects"),
2469 QSORT(delta_list, n, type_size_sort);
2470 ll_find_deltas(delta_list, n, window+1, depth, &nr_done);
2471 stop_progress(&progress_state);
2472 if (nr_done != nr_deltas)
2473 die("inconsistency with delta count");
2478 static int git_pack_config(const char *k, const char *v, void *cb)
2480 if (!strcmp(k, "pack.window")) {
2481 window = git_config_int(k, v);
2484 if (!strcmp(k, "pack.windowmemory")) {
2485 window_memory_limit = git_config_ulong(k, v);
2488 if (!strcmp(k, "pack.depth")) {
2489 depth = git_config_int(k, v);
2492 if (!strcmp(k, "pack.deltacachesize")) {
2493 max_delta_cache_size = git_config_int(k, v);
2496 if (!strcmp(k, "pack.deltacachelimit")) {
2497 cache_max_small_delta_size = git_config_int(k, v);
2500 if (!strcmp(k, "pack.writebitmaphashcache")) {
2501 if (git_config_bool(k, v))
2502 write_bitmap_options |= BITMAP_OPT_HASH_CACHE;
2504 write_bitmap_options &= ~BITMAP_OPT_HASH_CACHE;
2506 if (!strcmp(k, "pack.usebitmaps")) {
2507 use_bitmap_index_default = git_config_bool(k, v);
2510 if (!strcmp(k, "pack.threads")) {
2511 delta_search_threads = git_config_int(k, v);
2512 if (delta_search_threads < 0)
2513 die("invalid number of threads specified (%d)",
2514 delta_search_threads);
2516 if (delta_search_threads != 1) {
2517 warning("no threads support, ignoring %s", k);
2518 delta_search_threads = 0;
2523 if (!strcmp(k, "pack.indexversion")) {
2524 pack_idx_opts.version = git_config_int(k, v);
2525 if (pack_idx_opts.version > 2)
2526 die("bad pack.indexversion=%"PRIu32,
2527 pack_idx_opts.version);
2530 return git_default_config(k, v, cb);
2533 static void read_object_list_from_stdin(void)
2535 char line[GIT_MAX_HEXSZ + 1 + PATH_MAX + 2];
2536 struct object_id oid;
2540 if (!fgets(line, sizeof(line), stdin)) {
2544 die("fgets returned NULL, not EOF, not error!");
2550 if (line[0] == '-') {
2551 if (get_oid_hex(line+1, &oid))
2552 die("expected edge object ID, got garbage:\n %s",
2554 add_preferred_base(&oid);
2557 if (parse_oid_hex(line, &oid, &p))
2558 die("expected object ID, got garbage:\n %s", line);
2560 add_preferred_base_object(p + 1);
2561 add_object_entry(&oid, OBJ_NONE, p + 1, 0);
2565 /* Remember to update object flag allocation in object.h */
2566 #define OBJECT_ADDED (1u<<20)
2568 static void show_commit(struct commit *commit, void *data)
2570 add_object_entry(&commit->object.oid, OBJ_COMMIT, NULL, 0);
2571 commit->object.flags |= OBJECT_ADDED;
2573 if (write_bitmap_index)
2574 index_commit_for_bitmap(commit);
2577 static void show_object(struct object *obj, const char *name, void *data)
2579 add_preferred_base_object(name);
2580 add_object_entry(&obj->oid, obj->type, name, 0);
2581 obj->flags |= OBJECT_ADDED;
2584 static void show_object__ma_allow_any(struct object *obj, const char *name, void *data)
2586 assert(arg_missing_action == MA_ALLOW_ANY);
2589 * Quietly ignore ALL missing objects. This avoids problems with
2590 * staging them now and getting an odd error later.
2592 if (!has_object_file(&obj->oid))
2595 show_object(obj, name, data);
2598 static void show_object__ma_allow_promisor(struct object *obj, const char *name, void *data)
2600 assert(arg_missing_action == MA_ALLOW_PROMISOR);
2603 * Quietly ignore EXPECTED missing objects. This avoids problems with
2604 * staging them now and getting an odd error later.
2606 if (!has_object_file(&obj->oid) && is_promisor_object(&obj->oid))
2609 show_object(obj, name, data);
2612 static int option_parse_missing_action(const struct option *opt,
2613 const char *arg, int unset)
2618 if (!strcmp(arg, "error")) {
2619 arg_missing_action = MA_ERROR;
2620 fn_show_object = show_object;
2624 if (!strcmp(arg, "allow-any")) {
2625 arg_missing_action = MA_ALLOW_ANY;
2626 fetch_if_missing = 0;
2627 fn_show_object = show_object__ma_allow_any;
2631 if (!strcmp(arg, "allow-promisor")) {
2632 arg_missing_action = MA_ALLOW_PROMISOR;
2633 fetch_if_missing = 0;
2634 fn_show_object = show_object__ma_allow_promisor;
2638 die(_("invalid value for --missing"));
2642 static void show_edge(struct commit *commit)
2644 add_preferred_base(&commit->object.oid);
2647 struct in_pack_object {
2649 struct object *object;
2655 struct in_pack_object *array;
2658 static void mark_in_pack_object(struct object *object, struct packed_git *p, struct in_pack *in_pack)
2660 in_pack->array[in_pack->nr].offset = find_pack_entry_one(object->oid.hash, p);
2661 in_pack->array[in_pack->nr].object = object;
2666 * Compare the objects in the offset order, in order to emulate the
2667 * "git rev-list --objects" output that produced the pack originally.
2669 static int ofscmp(const void *a_, const void *b_)
2671 struct in_pack_object *a = (struct in_pack_object *)a_;
2672 struct in_pack_object *b = (struct in_pack_object *)b_;
2674 if (a->offset < b->offset)
2676 else if (a->offset > b->offset)
2679 return oidcmp(&a->object->oid, &b->object->oid);
2682 static void add_objects_in_unpacked_packs(struct rev_info *revs)
2684 struct packed_git *p;
2685 struct in_pack in_pack;
2688 memset(&in_pack, 0, sizeof(in_pack));
2690 for (p = get_packed_git(the_repository); p; p = p->next) {
2691 struct object_id oid;
2694 if (!p->pack_local || p->pack_keep)
2696 if (open_pack_index(p))
2697 die("cannot open pack index");
2699 ALLOC_GROW(in_pack.array,
2700 in_pack.nr + p->num_objects,
2703 for (i = 0; i < p->num_objects; i++) {
2704 nth_packed_object_oid(&oid, p, i);
2705 o = lookup_unknown_object(oid.hash);
2706 if (!(o->flags & OBJECT_ADDED))
2707 mark_in_pack_object(o, p, &in_pack);
2708 o->flags |= OBJECT_ADDED;
2713 QSORT(in_pack.array, in_pack.nr, ofscmp);
2714 for (i = 0; i < in_pack.nr; i++) {
2715 struct object *o = in_pack.array[i].object;
2716 add_object_entry(&o->oid, o->type, "", 0);
2719 free(in_pack.array);
2722 static int add_loose_object(const struct object_id *oid, const char *path,
2725 enum object_type type = oid_object_info(oid, NULL);
2728 warning("loose object at %s could not be examined", path);
2732 add_object_entry(oid, type, "", 0);
2737 * We actually don't even have to worry about reachability here.
2738 * add_object_entry will weed out duplicates, so we just add every
2739 * loose object we find.
2741 static void add_unreachable_loose_objects(void)
2743 for_each_loose_file_in_objdir(get_object_directory(),
2748 static int has_sha1_pack_kept_or_nonlocal(const struct object_id *oid)
2750 static struct packed_git *last_found = (void *)1;
2751 struct packed_git *p;
2753 p = (last_found != (void *)1) ? last_found :
2754 get_packed_git(the_repository);
2757 if ((!p->pack_local || p->pack_keep) &&
2758 find_pack_entry_one(oid->hash, p)) {
2762 if (p == last_found)
2763 p = get_packed_git(the_repository);
2766 if (p == last_found)
2773 * Store a list of sha1s that are should not be discarded
2774 * because they are either written too recently, or are
2775 * reachable from another object that was.
2777 * This is filled by get_object_list.
2779 static struct oid_array recent_objects;
2781 static int loosened_object_can_be_discarded(const struct object_id *oid,
2784 if (!unpack_unreachable_expiration)
2786 if (mtime > unpack_unreachable_expiration)
2788 if (oid_array_lookup(&recent_objects, oid) >= 0)
2793 static void loosen_unused_packed_objects(struct rev_info *revs)
2795 struct packed_git *p;
2797 struct object_id oid;
2799 for (p = get_packed_git(the_repository); p; p = p->next) {
2800 if (!p->pack_local || p->pack_keep)
2803 if (open_pack_index(p))
2804 die("cannot open pack index");
2806 for (i = 0; i < p->num_objects; i++) {
2807 nth_packed_object_oid(&oid, p, i);
2808 if (!packlist_find(&to_pack, oid.hash, NULL) &&
2809 !has_sha1_pack_kept_or_nonlocal(&oid) &&
2810 !loosened_object_can_be_discarded(&oid, p->mtime))
2811 if (force_object_loose(&oid, p->mtime))
2812 die("unable to force loose object");
2818 * This tracks any options which pack-reuse code expects to be on, or which a
2819 * reader of the pack might not understand, and which would therefore prevent
2820 * blind reuse of what we have on disk.
2822 static int pack_options_allow_reuse(void)
2824 return pack_to_stdout &&
2826 !ignore_packed_keep &&
2827 (!local || !have_non_local_packs) &&
2831 static int get_object_list_from_bitmap(struct rev_info *revs)
2833 if (prepare_bitmap_walk(revs) < 0)
2836 if (pack_options_allow_reuse() &&
2837 !reuse_partial_packfile_from_bitmap(
2839 &reuse_packfile_objects,
2840 &reuse_packfile_offset)) {
2841 assert(reuse_packfile_objects);
2842 nr_result += reuse_packfile_objects;
2843 display_progress(progress_state, nr_result);
2846 traverse_bitmap_commit_list(&add_object_entry_from_bitmap);
2850 static void record_recent_object(struct object *obj,
2854 oid_array_append(&recent_objects, &obj->oid);
2857 static void record_recent_commit(struct commit *commit, void *data)
2859 oid_array_append(&recent_objects, &commit->object.oid);
2862 static void get_object_list(int ac, const char **av)
2864 struct rev_info revs;
2868 init_revisions(&revs, NULL);
2869 save_commit_buffer = 0;
2870 setup_revisions(ac, av, &revs, NULL);
2872 /* make sure shallows are read */
2873 is_repository_shallow();
2875 while (fgets(line, sizeof(line), stdin) != NULL) {
2876 int len = strlen(line);
2877 if (len && line[len - 1] == '\n')
2882 if (!strcmp(line, "--not")) {
2883 flags ^= UNINTERESTING;
2884 write_bitmap_index = 0;
2887 if (starts_with(line, "--shallow ")) {
2888 struct object_id oid;
2889 if (get_oid_hex(line + 10, &oid))
2890 die("not an SHA-1 '%s'", line + 10);
2891 register_shallow(&oid);
2892 use_bitmap_index = 0;
2895 die("not a rev '%s'", line);
2897 if (handle_revision_arg(line, &revs, flags, REVARG_CANNOT_BE_FILENAME))
2898 die("bad revision '%s'", line);
2901 if (use_bitmap_index && !get_object_list_from_bitmap(&revs))
2904 if (prepare_revision_walk(&revs))
2905 die("revision walk setup failed");
2906 mark_edges_uninteresting(&revs, show_edge);
2908 if (!fn_show_object)
2909 fn_show_object = show_object;
2910 traverse_commit_list_filtered(&filter_options, &revs,
2911 show_commit, fn_show_object, NULL,
2914 if (unpack_unreachable_expiration) {
2915 revs.ignore_missing_links = 1;
2916 if (add_unseen_recent_objects_to_traversal(&revs,
2917 unpack_unreachable_expiration))
2918 die("unable to add recent objects");
2919 if (prepare_revision_walk(&revs))
2920 die("revision walk setup failed");
2921 traverse_commit_list(&revs, record_recent_commit,
2922 record_recent_object, NULL);
2925 if (keep_unreachable)
2926 add_objects_in_unpacked_packs(&revs);
2927 if (pack_loose_unreachable)
2928 add_unreachable_loose_objects();
2929 if (unpack_unreachable)
2930 loosen_unused_packed_objects(&revs);
2932 oid_array_clear(&recent_objects);
2935 static int option_parse_index_version(const struct option *opt,
2936 const char *arg, int unset)
2939 const char *val = arg;
2940 pack_idx_opts.version = strtoul(val, &c, 10);
2941 if (pack_idx_opts.version > 2)
2942 die(_("unsupported index version %s"), val);
2943 if (*c == ',' && c[1])
2944 pack_idx_opts.off32_limit = strtoul(c+1, &c, 0);
2945 if (*c || pack_idx_opts.off32_limit & 0x80000000)
2946 die(_("bad index version '%s'"), val);
2950 static int option_parse_unpack_unreachable(const struct option *opt,
2951 const char *arg, int unset)
2954 unpack_unreachable = 0;
2955 unpack_unreachable_expiration = 0;
2958 unpack_unreachable = 1;
2960 unpack_unreachable_expiration = approxidate(arg);
2965 int cmd_pack_objects(int argc, const char **argv, const char *prefix)
2967 int use_internal_rev_list = 0;
2970 int all_progress_implied = 0;
2971 struct argv_array rp = ARGV_ARRAY_INIT;
2972 int rev_list_unpacked = 0, rev_list_all = 0, rev_list_reflog = 0;
2973 int rev_list_index = 0;
2974 struct option pack_objects_options[] = {
2975 OPT_SET_INT('q', "quiet", &progress,
2976 N_("do not show progress meter"), 0),
2977 OPT_SET_INT(0, "progress", &progress,
2978 N_("show progress meter"), 1),
2979 OPT_SET_INT(0, "all-progress", &progress,
2980 N_("show progress meter during object writing phase"), 2),
2981 OPT_BOOL(0, "all-progress-implied",
2982 &all_progress_implied,
2983 N_("similar to --all-progress when progress meter is shown")),
2984 { OPTION_CALLBACK, 0, "index-version", NULL, N_("version[,offset]"),
2985 N_("write the pack index file in the specified idx format version"),
2986 0, option_parse_index_version },
2987 OPT_MAGNITUDE(0, "max-pack-size", &pack_size_limit,
2988 N_("maximum size of each output pack file")),
2989 OPT_BOOL(0, "local", &local,
2990 N_("ignore borrowed objects from alternate object store")),
2991 OPT_BOOL(0, "incremental", &incremental,
2992 N_("ignore packed objects")),
2993 OPT_INTEGER(0, "window", &window,
2994 N_("limit pack window by objects")),
2995 OPT_MAGNITUDE(0, "window-memory", &window_memory_limit,
2996 N_("limit pack window by memory in addition to object limit")),
2997 OPT_INTEGER(0, "depth", &depth,
2998 N_("maximum length of delta chain allowed in the resulting pack")),
2999 OPT_BOOL(0, "reuse-delta", &reuse_delta,
3000 N_("reuse existing deltas")),
3001 OPT_BOOL(0, "reuse-object", &reuse_object,
3002 N_("reuse existing objects")),
3003 OPT_BOOL(0, "delta-base-offset", &allow_ofs_delta,
3004 N_("use OFS_DELTA objects")),
3005 OPT_INTEGER(0, "threads", &delta_search_threads,
3006 N_("use threads when searching for best delta matches")),
3007 OPT_BOOL(0, "non-empty", &non_empty,
3008 N_("do not create an empty pack output")),
3009 OPT_BOOL(0, "revs", &use_internal_rev_list,
3010 N_("read revision arguments from standard input")),
3011 { OPTION_SET_INT, 0, "unpacked", &rev_list_unpacked, NULL,
3012 N_("limit the objects to those that are not yet packed"),
3013 PARSE_OPT_NOARG | PARSE_OPT_NONEG, NULL, 1 },
3014 { OPTION_SET_INT, 0, "all", &rev_list_all, NULL,
3015 N_("include objects reachable from any reference"),
3016 PARSE_OPT_NOARG | PARSE_OPT_NONEG, NULL, 1 },
3017 { OPTION_SET_INT, 0, "reflog", &rev_list_reflog, NULL,
3018 N_("include objects referred by reflog entries"),
3019 PARSE_OPT_NOARG | PARSE_OPT_NONEG, NULL, 1 },
3020 { OPTION_SET_INT, 0, "indexed-objects", &rev_list_index, NULL,
3021 N_("include objects referred to by the index"),
3022 PARSE_OPT_NOARG | PARSE_OPT_NONEG, NULL, 1 },
3023 OPT_BOOL(0, "stdout", &pack_to_stdout,
3024 N_("output pack to stdout")),
3025 OPT_BOOL(0, "include-tag", &include_tag,
3026 N_("include tag objects that refer to objects to be packed")),
3027 OPT_BOOL(0, "keep-unreachable", &keep_unreachable,
3028 N_("keep unreachable objects")),
3029 OPT_BOOL(0, "pack-loose-unreachable", &pack_loose_unreachable,
3030 N_("pack loose unreachable objects")),
3031 { OPTION_CALLBACK, 0, "unpack-unreachable", NULL, N_("time"),
3032 N_("unpack unreachable objects newer than <time>"),
3033 PARSE_OPT_OPTARG, option_parse_unpack_unreachable },
3034 OPT_BOOL(0, "thin", &thin,
3035 N_("create thin packs")),
3036 OPT_BOOL(0, "shallow", &shallow,
3037 N_("create packs suitable for shallow fetches")),
3038 OPT_BOOL(0, "honor-pack-keep", &ignore_packed_keep,
3039 N_("ignore packs that have companion .keep file")),
3040 OPT_INTEGER(0, "compression", &pack_compression_level,
3041 N_("pack compression level")),
3042 OPT_SET_INT(0, "keep-true-parents", &grafts_replace_parents,
3043 N_("do not hide commits by grafts"), 0),
3044 OPT_BOOL(0, "use-bitmap-index", &use_bitmap_index,
3045 N_("use a bitmap index if available to speed up counting objects")),
3046 OPT_BOOL(0, "write-bitmap-index", &write_bitmap_index,
3047 N_("write a bitmap index together with the pack index")),
3048 OPT_PARSE_LIST_OBJECTS_FILTER(&filter_options),
3049 { OPTION_CALLBACK, 0, "missing", NULL, N_("action"),
3050 N_("handling for missing objects"), PARSE_OPT_NONEG,
3051 option_parse_missing_action },
3052 OPT_BOOL(0, "exclude-promisor-objects", &exclude_promisor_objects,
3053 N_("do not pack objects in promisor packfiles")),
3057 if (DFS_NUM_STATES > (1 << OE_DFS_STATE_BITS))
3058 BUG("too many dfs states, increase OE_DFS_STATE_BITS");
3060 check_replace_refs = 0;
3062 reset_pack_idx_option(&pack_idx_opts);
3063 git_config(git_pack_config, NULL);
3065 progress = isatty(2);
3066 argc = parse_options(argc, argv, prefix, pack_objects_options,
3070 base_name = argv[0];
3073 if (pack_to_stdout != !base_name || argc)
3074 usage_with_options(pack_usage, pack_objects_options);
3076 if (depth >= (1 << OE_DEPTH_BITS)) {
3077 warning(_("delta chain depth %d is too deep, forcing %d"),
3078 depth, (1 << OE_DEPTH_BITS) - 1);
3079 depth = (1 << OE_DEPTH_BITS) - 1;
3082 argv_array_push(&rp, "pack-objects");
3084 use_internal_rev_list = 1;
3085 argv_array_push(&rp, shallow
3086 ? "--objects-edge-aggressive"
3087 : "--objects-edge");
3089 argv_array_push(&rp, "--objects");
3092 use_internal_rev_list = 1;
3093 argv_array_push(&rp, "--all");
3095 if (rev_list_reflog) {
3096 use_internal_rev_list = 1;
3097 argv_array_push(&rp, "--reflog");
3099 if (rev_list_index) {
3100 use_internal_rev_list = 1;
3101 argv_array_push(&rp, "--indexed-objects");
3103 if (rev_list_unpacked) {
3104 use_internal_rev_list = 1;
3105 argv_array_push(&rp, "--unpacked");
3108 if (exclude_promisor_objects) {
3109 use_internal_rev_list = 1;
3110 fetch_if_missing = 0;
3111 argv_array_push(&rp, "--exclude-promisor-objects");
3116 if (pack_compression_level == -1)
3117 pack_compression_level = Z_DEFAULT_COMPRESSION;
3118 else if (pack_compression_level < 0 || pack_compression_level > Z_BEST_COMPRESSION)
3119 die("bad pack compression level %d", pack_compression_level);
3121 if (!delta_search_threads) /* --threads=0 means autodetect */
3122 delta_search_threads = online_cpus();
3125 if (delta_search_threads != 1)
3126 warning("no threads support, ignoring --threads");
3128 if (!pack_to_stdout && !pack_size_limit)
3129 pack_size_limit = pack_size_limit_cfg;
3130 if (pack_to_stdout && pack_size_limit)
3131 die("--max-pack-size cannot be used to build a pack for transfer.");
3132 if (pack_size_limit && pack_size_limit < 1024*1024) {
3133 warning("minimum pack size limit is 1 MiB");
3134 pack_size_limit = 1024*1024;
3137 if (!pack_to_stdout && thin)
3138 die("--thin cannot be used to build an indexable pack.");
3140 if (keep_unreachable && unpack_unreachable)
3141 die("--keep-unreachable and --unpack-unreachable are incompatible.");
3142 if (!rev_list_all || !rev_list_reflog || !rev_list_index)
3143 unpack_unreachable_expiration = 0;
3145 if (filter_options.choice) {
3146 if (!pack_to_stdout)
3147 die("cannot use --filter without --stdout.");
3148 use_bitmap_index = 0;
3152 * "soft" reasons not to use bitmaps - for on-disk repack by default we want
3154 * - to produce good pack (with bitmap index not-yet-packed objects are
3155 * packed in suboptimal order).
3157 * - to use more robust pack-generation codepath (avoiding possible
3158 * bugs in bitmap code and possible bitmap index corruption).
3160 if (!pack_to_stdout)
3161 use_bitmap_index_default = 0;
3163 if (use_bitmap_index < 0)
3164 use_bitmap_index = use_bitmap_index_default;
3166 /* "hard" reasons not to use bitmaps; these just won't work at all */
3167 if (!use_internal_rev_list || (!pack_to_stdout && write_bitmap_index) || is_repository_shallow())
3168 use_bitmap_index = 0;
3170 if (pack_to_stdout || !rev_list_all)
3171 write_bitmap_index = 0;
3173 if (progress && all_progress_implied)
3176 if (ignore_packed_keep) {
3177 struct packed_git *p;
3178 for (p = get_packed_git(the_repository); p; p = p->next)
3179 if (p->pack_local && p->pack_keep)
3181 if (!p) /* no keep-able packs found */
3182 ignore_packed_keep = 0;
3186 * unlike ignore_packed_keep above, we do not want to
3187 * unset "local" based on looking at packs, as it
3188 * also covers non-local objects
3190 struct packed_git *p;
3191 for (p = get_packed_git(the_repository); p; p = p->next) {
3192 if (!p->pack_local) {
3193 have_non_local_packs = 1;
3199 prepare_packing_data(&to_pack);
3202 progress_state = start_progress(_("Counting objects"), 0);
3203 if (!use_internal_rev_list)
3204 read_object_list_from_stdin();
3206 get_object_list(rp.argc, rp.argv);
3207 argv_array_clear(&rp);
3209 cleanup_preferred_base();
3210 if (include_tag && nr_result)
3211 for_each_ref(add_ref_tag, NULL);
3212 stop_progress(&progress_state);
3214 if (non_empty && !nr_result)
3217 prepare_pack(window, depth);
3220 fprintf(stderr, "Total %"PRIu32" (delta %"PRIu32"),"
3221 " reused %"PRIu32" (delta %"PRIu32")\n",
3222 written, written_delta, reused, reused_delta);