3 #include "repository.h"
13 #include "pack-revindex.h"
14 #include "csum-file.h"
15 #include "tree-walk.h"
18 #include "list-objects.h"
19 #include "list-objects-filter.h"
20 #include "list-objects-filter-options.h"
21 #include "pack-objects.h"
24 #include "streaming.h"
25 #include "thread-utils.h"
26 #include "pack-bitmap.h"
27 #include "delta-islands.h"
28 #include "reachable.h"
29 #include "sha1-array.h"
30 #include "argv-array.h"
33 #include "object-store.h"
37 #define IN_PACK(obj) oe_in_pack(&to_pack, obj)
38 #define SIZE(obj) oe_size(&to_pack, obj)
39 #define SET_SIZE(obj,size) oe_set_size(&to_pack, obj, size)
40 #define DELTA_SIZE(obj) oe_delta_size(&to_pack, obj)
41 #define DELTA(obj) oe_delta(&to_pack, obj)
42 #define DELTA_CHILD(obj) oe_delta_child(&to_pack, obj)
43 #define DELTA_SIBLING(obj) oe_delta_sibling(&to_pack, obj)
44 #define SET_DELTA(obj, val) oe_set_delta(&to_pack, obj, val)
45 #define SET_DELTA_EXT(obj, oid) oe_set_delta_ext(&to_pack, obj, oid)
46 #define SET_DELTA_SIZE(obj, val) oe_set_delta_size(&to_pack, obj, val)
47 #define SET_DELTA_CHILD(obj, val) oe_set_delta_child(&to_pack, obj, val)
48 #define SET_DELTA_SIBLING(obj, val) oe_set_delta_sibling(&to_pack, obj, val)
50 static const char *pack_usage[] = {
51 N_("git pack-objects --stdout [<options>...] [< <ref-list> | < <object-list>]"),
52 N_("git pack-objects [<options>...] <base-name> [< <ref-list> | < <object-list>]"),
57 * Objects we are going to pack are collected in the `to_pack` structure.
58 * It contains an array (dynamically expanded) of the object data, and a map
59 * that can resolve SHA1s to their position in the array.
61 static struct packing_data to_pack;
63 static struct pack_idx_entry **written_list;
64 static uint32_t nr_result, nr_written, nr_seen;
65 static struct bitmap_index *bitmap_git;
66 static uint32_t write_layer;
69 static int reuse_delta = 1, reuse_object = 1;
70 static int keep_unreachable, unpack_unreachable, include_tag;
71 static timestamp_t unpack_unreachable_expiration;
72 static int pack_loose_unreachable;
74 static int have_non_local_packs;
75 static int incremental;
76 static int ignore_packed_keep_on_disk;
77 static int ignore_packed_keep_in_core;
78 static int allow_ofs_delta;
79 static struct pack_idx_option pack_idx_opts;
80 static const char *base_name;
81 static int progress = 1;
82 static int window = 10;
83 static unsigned long pack_size_limit;
84 static int depth = 50;
85 static int delta_search_threads;
86 static int pack_to_stdout;
89 static int num_preferred_base;
90 static struct progress *progress_state;
92 static struct packed_git *reuse_packfile;
93 static uint32_t reuse_packfile_objects;
94 static off_t reuse_packfile_offset;
96 static int use_bitmap_index_default = 1;
97 static int use_bitmap_index = -1;
98 static int write_bitmap_index;
99 static uint16_t write_bitmap_options;
101 static int exclude_promisor_objects;
103 static int use_delta_islands;
105 static unsigned long delta_cache_size = 0;
106 static unsigned long max_delta_cache_size = DEFAULT_DELTA_CACHE_SIZE;
107 static unsigned long cache_max_small_delta_size = 1000;
109 static unsigned long window_memory_limit = 0;
111 static struct list_objects_filter_options filter_options;
113 enum missing_action {
114 MA_ERROR = 0, /* fail if any missing objects are encountered */
115 MA_ALLOW_ANY, /* silently allow ALL missing objects */
116 MA_ALLOW_PROMISOR, /* silently allow all missing PROMISOR objects */
118 static enum missing_action arg_missing_action;
119 static show_object_fn fn_show_object;
124 static uint32_t written, written_delta;
125 static uint32_t reused, reused_delta;
130 static struct commit **indexed_commits;
131 static unsigned int indexed_commits_nr;
132 static unsigned int indexed_commits_alloc;
134 static void index_commit_for_bitmap(struct commit *commit)
136 if (indexed_commits_nr >= indexed_commits_alloc) {
137 indexed_commits_alloc = (indexed_commits_alloc + 32) * 2;
138 REALLOC_ARRAY(indexed_commits, indexed_commits_alloc);
141 indexed_commits[indexed_commits_nr++] = commit;
144 static void *get_delta(struct object_entry *entry)
146 unsigned long size, base_size, delta_size;
147 void *buf, *base_buf, *delta_buf;
148 enum object_type type;
150 buf = read_object_file(&entry->idx.oid, &type, &size);
152 die(_("unable to read %s"), oid_to_hex(&entry->idx.oid));
153 base_buf = read_object_file(&DELTA(entry)->idx.oid, &type,
156 die("unable to read %s",
157 oid_to_hex(&DELTA(entry)->idx.oid));
158 delta_buf = diff_delta(base_buf, base_size,
159 buf, size, &delta_size, 0);
161 * We succesfully computed this delta once but dropped it for
162 * memory reasons. Something is very wrong if this time we
163 * recompute and create a different delta.
165 if (!delta_buf || delta_size != DELTA_SIZE(entry))
166 BUG("delta size changed");
172 static unsigned long do_compress(void **pptr, unsigned long size)
176 unsigned long maxsize;
178 git_deflate_init(&stream, pack_compression_level);
179 maxsize = git_deflate_bound(&stream, size);
182 out = xmalloc(maxsize);
186 stream.avail_in = size;
187 stream.next_out = out;
188 stream.avail_out = maxsize;
189 while (git_deflate(&stream, Z_FINISH) == Z_OK)
191 git_deflate_end(&stream);
194 return stream.total_out;
197 static unsigned long write_large_blob_data(struct git_istream *st, struct hashfile *f,
198 const struct object_id *oid)
201 unsigned char ibuf[1024 * 16];
202 unsigned char obuf[1024 * 16];
203 unsigned long olen = 0;
205 git_deflate_init(&stream, pack_compression_level);
210 readlen = read_istream(st, ibuf, sizeof(ibuf));
212 die(_("unable to read %s"), oid_to_hex(oid));
214 stream.next_in = ibuf;
215 stream.avail_in = readlen;
216 while ((stream.avail_in || readlen == 0) &&
217 (zret == Z_OK || zret == Z_BUF_ERROR)) {
218 stream.next_out = obuf;
219 stream.avail_out = sizeof(obuf);
220 zret = git_deflate(&stream, readlen ? 0 : Z_FINISH);
221 hashwrite(f, obuf, stream.next_out - obuf);
222 olen += stream.next_out - obuf;
225 die(_("deflate error (%d)"), zret);
227 if (zret != Z_STREAM_END)
228 die(_("deflate error (%d)"), zret);
232 git_deflate_end(&stream);
237 * we are going to reuse the existing object data as is. make
238 * sure it is not corrupt.
240 static int check_pack_inflate(struct packed_git *p,
241 struct pack_window **w_curs,
244 unsigned long expect)
247 unsigned char fakebuf[4096], *in;
250 memset(&stream, 0, sizeof(stream));
251 git_inflate_init(&stream);
253 in = use_pack(p, w_curs, offset, &stream.avail_in);
255 stream.next_out = fakebuf;
256 stream.avail_out = sizeof(fakebuf);
257 st = git_inflate(&stream, Z_FINISH);
258 offset += stream.next_in - in;
259 } while (st == Z_OK || st == Z_BUF_ERROR);
260 git_inflate_end(&stream);
261 return (st == Z_STREAM_END &&
262 stream.total_out == expect &&
263 stream.total_in == len) ? 0 : -1;
266 static void copy_pack_data(struct hashfile *f,
267 struct packed_git *p,
268 struct pack_window **w_curs,
276 in = use_pack(p, w_curs, offset, &avail);
278 avail = (unsigned long)len;
279 hashwrite(f, in, avail);
285 /* Return 0 if we will bust the pack-size limit */
286 static unsigned long write_no_reuse_object(struct hashfile *f, struct object_entry *entry,
287 unsigned long limit, int usable_delta)
289 unsigned long size, datalen;
290 unsigned char header[MAX_PACK_OBJECT_HEADER],
291 dheader[MAX_PACK_OBJECT_HEADER];
293 enum object_type type;
295 struct git_istream *st = NULL;
296 const unsigned hashsz = the_hash_algo->rawsz;
299 if (oe_type(entry) == OBJ_BLOB &&
300 oe_size_greater_than(&to_pack, entry, big_file_threshold) &&
301 (st = open_istream(&entry->idx.oid, &type, &size, NULL)) != NULL)
304 buf = read_object_file(&entry->idx.oid, &type, &size);
306 die(_("unable to read %s"),
307 oid_to_hex(&entry->idx.oid));
310 * make sure no cached delta data remains from a
311 * previous attempt before a pack split occurred.
313 FREE_AND_NULL(entry->delta_data);
314 entry->z_delta_size = 0;
315 } else if (entry->delta_data) {
316 size = DELTA_SIZE(entry);
317 buf = entry->delta_data;
318 entry->delta_data = NULL;
319 type = (allow_ofs_delta && DELTA(entry)->idx.offset) ?
320 OBJ_OFS_DELTA : OBJ_REF_DELTA;
322 buf = get_delta(entry);
323 size = DELTA_SIZE(entry);
324 type = (allow_ofs_delta && DELTA(entry)->idx.offset) ?
325 OBJ_OFS_DELTA : OBJ_REF_DELTA;
328 if (st) /* large blob case, just assume we don't compress well */
330 else if (entry->z_delta_size)
331 datalen = entry->z_delta_size;
333 datalen = do_compress(&buf, size);
336 * The object header is a byte of 'type' followed by zero or
337 * more bytes of length.
339 hdrlen = encode_in_pack_object_header(header, sizeof(header),
342 if (type == OBJ_OFS_DELTA) {
344 * Deltas with relative base contain an additional
345 * encoding of the relative offset for the delta
346 * base from this object's position in the pack.
348 off_t ofs = entry->idx.offset - DELTA(entry)->idx.offset;
349 unsigned pos = sizeof(dheader) - 1;
350 dheader[pos] = ofs & 127;
352 dheader[--pos] = 128 | (--ofs & 127);
353 if (limit && hdrlen + sizeof(dheader) - pos + datalen + hashsz >= limit) {
359 hashwrite(f, header, hdrlen);
360 hashwrite(f, dheader + pos, sizeof(dheader) - pos);
361 hdrlen += sizeof(dheader) - pos;
362 } else if (type == OBJ_REF_DELTA) {
364 * Deltas with a base reference contain
365 * additional bytes for the base object ID.
367 if (limit && hdrlen + hashsz + datalen + hashsz >= limit) {
373 hashwrite(f, header, hdrlen);
374 hashwrite(f, DELTA(entry)->idx.oid.hash, hashsz);
377 if (limit && hdrlen + datalen + hashsz >= limit) {
383 hashwrite(f, header, hdrlen);
386 datalen = write_large_blob_data(st, f, &entry->idx.oid);
389 hashwrite(f, buf, datalen);
393 return hdrlen + datalen;
396 /* Return 0 if we will bust the pack-size limit */
397 static off_t write_reuse_object(struct hashfile *f, struct object_entry *entry,
398 unsigned long limit, int usable_delta)
400 struct packed_git *p = IN_PACK(entry);
401 struct pack_window *w_curs = NULL;
402 struct revindex_entry *revidx;
404 enum object_type type = oe_type(entry);
406 unsigned char header[MAX_PACK_OBJECT_HEADER],
407 dheader[MAX_PACK_OBJECT_HEADER];
409 const unsigned hashsz = the_hash_algo->rawsz;
410 unsigned long entry_size = SIZE(entry);
413 type = (allow_ofs_delta && DELTA(entry)->idx.offset) ?
414 OBJ_OFS_DELTA : OBJ_REF_DELTA;
415 hdrlen = encode_in_pack_object_header(header, sizeof(header),
418 offset = entry->in_pack_offset;
419 revidx = find_pack_revindex(p, offset);
420 datalen = revidx[1].offset - offset;
421 if (!pack_to_stdout && p->index_version > 1 &&
422 check_pack_crc(p, &w_curs, offset, datalen, revidx->nr)) {
423 error(_("bad packed object CRC for %s"),
424 oid_to_hex(&entry->idx.oid));
426 return write_no_reuse_object(f, entry, limit, usable_delta);
429 offset += entry->in_pack_header_size;
430 datalen -= entry->in_pack_header_size;
432 if (!pack_to_stdout && p->index_version == 1 &&
433 check_pack_inflate(p, &w_curs, offset, datalen, entry_size)) {
434 error(_("corrupt packed object for %s"),
435 oid_to_hex(&entry->idx.oid));
437 return write_no_reuse_object(f, entry, limit, usable_delta);
440 if (type == OBJ_OFS_DELTA) {
441 off_t ofs = entry->idx.offset - DELTA(entry)->idx.offset;
442 unsigned pos = sizeof(dheader) - 1;
443 dheader[pos] = ofs & 127;
445 dheader[--pos] = 128 | (--ofs & 127);
446 if (limit && hdrlen + sizeof(dheader) - pos + datalen + hashsz >= limit) {
450 hashwrite(f, header, hdrlen);
451 hashwrite(f, dheader + pos, sizeof(dheader) - pos);
452 hdrlen += sizeof(dheader) - pos;
454 } else if (type == OBJ_REF_DELTA) {
455 if (limit && hdrlen + hashsz + datalen + hashsz >= limit) {
459 hashwrite(f, header, hdrlen);
460 hashwrite(f, DELTA(entry)->idx.oid.hash, hashsz);
464 if (limit && hdrlen + datalen + hashsz >= limit) {
468 hashwrite(f, header, hdrlen);
470 copy_pack_data(f, p, &w_curs, offset, datalen);
473 return hdrlen + datalen;
476 /* Return 0 if we will bust the pack-size limit */
477 static off_t write_object(struct hashfile *f,
478 struct object_entry *entry,
483 int usable_delta, to_reuse;
488 /* apply size limit if limited packsize and not first object */
489 if (!pack_size_limit || !nr_written)
491 else if (pack_size_limit <= write_offset)
493 * the earlier object did not fit the limit; avoid
494 * mistaking this with unlimited (i.e. limit = 0).
498 limit = pack_size_limit - write_offset;
501 usable_delta = 0; /* no delta */
502 else if (!pack_size_limit)
503 usable_delta = 1; /* unlimited packfile */
504 else if (DELTA(entry)->idx.offset == (off_t)-1)
505 usable_delta = 0; /* base was written to another pack */
506 else if (DELTA(entry)->idx.offset)
507 usable_delta = 1; /* base already exists in this pack */
509 usable_delta = 0; /* base could end up in another pack */
512 to_reuse = 0; /* explicit */
513 else if (!IN_PACK(entry))
514 to_reuse = 0; /* can't reuse what we don't have */
515 else if (oe_type(entry) == OBJ_REF_DELTA ||
516 oe_type(entry) == OBJ_OFS_DELTA)
517 /* check_object() decided it for us ... */
518 to_reuse = usable_delta;
519 /* ... but pack split may override that */
520 else if (oe_type(entry) != entry->in_pack_type)
521 to_reuse = 0; /* pack has delta which is unusable */
522 else if (DELTA(entry))
523 to_reuse = 0; /* we want to pack afresh */
525 to_reuse = 1; /* we have it in-pack undeltified,
526 * and we do not need to deltify it.
530 len = write_no_reuse_object(f, entry, limit, usable_delta);
532 len = write_reuse_object(f, entry, limit, usable_delta);
540 entry->idx.crc32 = crc32_end(f);
544 enum write_one_status {
545 WRITE_ONE_SKIP = -1, /* already written */
546 WRITE_ONE_BREAK = 0, /* writing this will bust the limit; not written */
547 WRITE_ONE_WRITTEN = 1, /* normal */
548 WRITE_ONE_RECURSIVE = 2 /* already scheduled to be written */
551 static enum write_one_status write_one(struct hashfile *f,
552 struct object_entry *e,
559 * we set offset to 1 (which is an impossible value) to mark
560 * the fact that this object is involved in "write its base
561 * first before writing a deltified object" recursion.
563 recursing = (e->idx.offset == 1);
565 warning(_("recursive delta detected for object %s"),
566 oid_to_hex(&e->idx.oid));
567 return WRITE_ONE_RECURSIVE;
568 } else if (e->idx.offset || e->preferred_base) {
569 /* offset is non zero if object is written already. */
570 return WRITE_ONE_SKIP;
573 /* if we are deltified, write out base object first. */
575 e->idx.offset = 1; /* now recurse */
576 switch (write_one(f, DELTA(e), offset)) {
577 case WRITE_ONE_RECURSIVE:
578 /* we cannot depend on this one */
583 case WRITE_ONE_BREAK:
584 e->idx.offset = recursing;
585 return WRITE_ONE_BREAK;
589 e->idx.offset = *offset;
590 size = write_object(f, e, *offset);
592 e->idx.offset = recursing;
593 return WRITE_ONE_BREAK;
595 written_list[nr_written++] = &e->idx;
597 /* make sure off_t is sufficiently large not to wrap */
598 if (signed_add_overflows(*offset, size))
599 die(_("pack too large for current definition of off_t"));
601 return WRITE_ONE_WRITTEN;
604 static int mark_tagged(const char *path, const struct object_id *oid, int flag,
607 struct object_id peeled;
608 struct object_entry *entry = packlist_find(&to_pack, oid->hash, NULL);
612 if (!peel_ref(path, &peeled)) {
613 entry = packlist_find(&to_pack, peeled.hash, NULL);
620 static inline void add_to_write_order(struct object_entry **wo,
622 struct object_entry *e)
624 if (e->filled || oe_layer(&to_pack, e) != write_layer)
630 static void add_descendants_to_write_order(struct object_entry **wo,
632 struct object_entry *e)
634 int add_to_order = 1;
637 struct object_entry *s;
638 /* add this node... */
639 add_to_write_order(wo, endp, e);
640 /* all its siblings... */
641 for (s = DELTA_SIBLING(e); s; s = DELTA_SIBLING(s)) {
642 add_to_write_order(wo, endp, s);
645 /* drop down a level to add left subtree nodes if possible */
646 if (DELTA_CHILD(e)) {
651 /* our sibling might have some children, it is next */
652 if (DELTA_SIBLING(e)) {
653 e = DELTA_SIBLING(e);
656 /* go back to our parent node */
658 while (e && !DELTA_SIBLING(e)) {
659 /* we're on the right side of a subtree, keep
660 * going up until we can go right again */
664 /* done- we hit our original root node */
667 /* pass it off to sibling at this level */
668 e = DELTA_SIBLING(e);
673 static void add_family_to_write_order(struct object_entry **wo,
675 struct object_entry *e)
677 struct object_entry *root;
679 for (root = e; DELTA(root); root = DELTA(root))
681 add_descendants_to_write_order(wo, endp, root);
684 static void compute_layer_order(struct object_entry **wo, unsigned int *wo_end)
686 unsigned int i, last_untagged;
687 struct object_entry *objects = to_pack.objects;
689 for (i = 0; i < to_pack.nr_objects; i++) {
690 if (objects[i].tagged)
692 add_to_write_order(wo, wo_end, &objects[i]);
697 * Then fill all the tagged tips.
699 for (; i < to_pack.nr_objects; i++) {
700 if (objects[i].tagged)
701 add_to_write_order(wo, wo_end, &objects[i]);
705 * And then all remaining commits and tags.
707 for (i = last_untagged; i < to_pack.nr_objects; i++) {
708 if (oe_type(&objects[i]) != OBJ_COMMIT &&
709 oe_type(&objects[i]) != OBJ_TAG)
711 add_to_write_order(wo, wo_end, &objects[i]);
715 * And then all the trees.
717 for (i = last_untagged; i < to_pack.nr_objects; i++) {
718 if (oe_type(&objects[i]) != OBJ_TREE)
720 add_to_write_order(wo, wo_end, &objects[i]);
724 * Finally all the rest in really tight order
726 for (i = last_untagged; i < to_pack.nr_objects; i++) {
727 if (!objects[i].filled && oe_layer(&to_pack, &objects[i]) == write_layer)
728 add_family_to_write_order(wo, wo_end, &objects[i]);
732 static struct object_entry **compute_write_order(void)
734 uint32_t max_layers = 1;
735 unsigned int i, wo_end;
737 struct object_entry **wo;
738 struct object_entry *objects = to_pack.objects;
740 for (i = 0; i < to_pack.nr_objects; i++) {
741 objects[i].tagged = 0;
742 objects[i].filled = 0;
743 SET_DELTA_CHILD(&objects[i], NULL);
744 SET_DELTA_SIBLING(&objects[i], NULL);
748 * Fully connect delta_child/delta_sibling network.
749 * Make sure delta_sibling is sorted in the original
752 for (i = to_pack.nr_objects; i > 0;) {
753 struct object_entry *e = &objects[--i];
756 /* Mark me as the first child */
757 e->delta_sibling_idx = DELTA(e)->delta_child_idx;
758 SET_DELTA_CHILD(DELTA(e), e);
762 * Mark objects that are at the tip of tags.
764 for_each_tag_ref(mark_tagged, NULL);
766 if (use_delta_islands)
767 max_layers = compute_pack_layers(&to_pack);
769 ALLOC_ARRAY(wo, to_pack.nr_objects);
772 for (; write_layer < max_layers; ++write_layer)
773 compute_layer_order(wo, &wo_end);
775 if (wo_end != to_pack.nr_objects)
776 die(_("ordered %u objects, expected %"PRIu32),
777 wo_end, to_pack.nr_objects);
782 static off_t write_reused_pack(struct hashfile *f)
784 unsigned char buffer[8192];
785 off_t to_write, total;
788 if (!is_pack_valid(reuse_packfile))
789 die(_("packfile is invalid: %s"), reuse_packfile->pack_name);
791 fd = git_open(reuse_packfile->pack_name);
793 die_errno(_("unable to open packfile for reuse: %s"),
794 reuse_packfile->pack_name);
796 if (lseek(fd, sizeof(struct pack_header), SEEK_SET) == -1)
797 die_errno(_("unable to seek in reused packfile"));
799 if (reuse_packfile_offset < 0)
800 reuse_packfile_offset = reuse_packfile->pack_size - the_hash_algo->rawsz;
802 total = to_write = reuse_packfile_offset - sizeof(struct pack_header);
805 int read_pack = xread(fd, buffer, sizeof(buffer));
808 die_errno(_("unable to read from reused packfile"));
810 if (read_pack > to_write)
811 read_pack = to_write;
813 hashwrite(f, buffer, read_pack);
814 to_write -= read_pack;
817 * We don't know the actual number of objects written,
818 * only how many bytes written, how many bytes total, and
819 * how many objects total. So we can fake it by pretending all
820 * objects we are writing are the same size. This gives us a
821 * smooth progress meter, and at the end it matches the true
824 written = reuse_packfile_objects *
825 (((double)(total - to_write)) / total);
826 display_progress(progress_state, written);
830 written = reuse_packfile_objects;
831 display_progress(progress_state, written);
832 return reuse_packfile_offset - sizeof(struct pack_header);
835 static const char no_split_warning[] = N_(
836 "disabling bitmap writing, packs are split due to pack.packSizeLimit"
839 static void write_pack_file(void)
844 uint32_t nr_remaining = nr_result;
845 time_t last_mtime = 0;
846 struct object_entry **write_order;
848 if (progress > pack_to_stdout)
849 progress_state = start_progress(_("Writing objects"), nr_result);
850 ALLOC_ARRAY(written_list, to_pack.nr_objects);
851 write_order = compute_write_order();
854 struct object_id oid;
855 char *pack_tmp_name = NULL;
858 f = hashfd_throughput(1, "<stdout>", progress_state);
860 f = create_tmp_packfile(&pack_tmp_name);
862 offset = write_pack_header(f, nr_remaining);
864 if (reuse_packfile) {
866 assert(pack_to_stdout);
868 packfile_size = write_reused_pack(f);
869 offset += packfile_size;
873 for (; i < to_pack.nr_objects; i++) {
874 struct object_entry *e = write_order[i];
875 if (write_one(f, e, &offset) == WRITE_ONE_BREAK)
877 display_progress(progress_state, written);
881 * Did we write the wrong # entries in the header?
882 * If so, rewrite it like in fast-import
884 if (pack_to_stdout) {
885 finalize_hashfile(f, oid.hash, CSUM_HASH_IN_STREAM | CSUM_CLOSE);
886 } else if (nr_written == nr_remaining) {
887 finalize_hashfile(f, oid.hash, CSUM_HASH_IN_STREAM | CSUM_FSYNC | CSUM_CLOSE);
889 int fd = finalize_hashfile(f, oid.hash, 0);
890 fixup_pack_header_footer(fd, oid.hash, pack_tmp_name,
891 nr_written, oid.hash, offset);
893 if (write_bitmap_index) {
894 warning(_(no_split_warning));
895 write_bitmap_index = 0;
899 if (!pack_to_stdout) {
901 struct strbuf tmpname = STRBUF_INIT;
904 * Packs are runtime accessed in their mtime
905 * order since newer packs are more likely to contain
906 * younger objects. So if we are creating multiple
907 * packs then we should modify the mtime of later ones
908 * to preserve this property.
910 if (stat(pack_tmp_name, &st) < 0) {
911 warning_errno(_("failed to stat %s"), pack_tmp_name);
912 } else if (!last_mtime) {
913 last_mtime = st.st_mtime;
916 utb.actime = st.st_atime;
917 utb.modtime = --last_mtime;
918 if (utime(pack_tmp_name, &utb) < 0)
919 warning_errno(_("failed utime() on %s"), pack_tmp_name);
922 strbuf_addf(&tmpname, "%s-", base_name);
924 if (write_bitmap_index) {
925 bitmap_writer_set_checksum(oid.hash);
926 bitmap_writer_build_type_index(
927 &to_pack, written_list, nr_written);
930 finish_tmp_packfile(&tmpname, pack_tmp_name,
931 written_list, nr_written,
932 &pack_idx_opts, oid.hash);
934 if (write_bitmap_index) {
935 strbuf_addf(&tmpname, "%s.bitmap", oid_to_hex(&oid));
937 stop_progress(&progress_state);
939 bitmap_writer_show_progress(progress);
940 bitmap_writer_reuse_bitmaps(&to_pack);
941 bitmap_writer_select_commits(indexed_commits, indexed_commits_nr, -1);
942 bitmap_writer_build(&to_pack);
943 bitmap_writer_finish(written_list, nr_written,
944 tmpname.buf, write_bitmap_options);
945 write_bitmap_index = 0;
948 strbuf_release(&tmpname);
950 puts(oid_to_hex(&oid));
953 /* mark written objects as written to previous pack */
954 for (j = 0; j < nr_written; j++) {
955 written_list[j]->offset = (off_t)-1;
957 nr_remaining -= nr_written;
958 } while (nr_remaining && i < to_pack.nr_objects);
962 stop_progress(&progress_state);
963 if (written != nr_result)
964 die(_("wrote %"PRIu32" objects while expecting %"PRIu32),
968 static int no_try_delta(const char *path)
970 static struct attr_check *check;
973 check = attr_check_initl("delta", NULL);
974 git_check_attr(the_repository->index, path, check);
975 if (ATTR_FALSE(check->items[0].value))
981 * When adding an object, check whether we have already added it
982 * to our packing list. If so, we can skip. However, if we are
983 * being asked to excludei t, but the previous mention was to include
984 * it, make sure to adjust its flags and tweak our numbers accordingly.
986 * As an optimization, we pass out the index position where we would have
987 * found the item, since that saves us from having to look it up again a
988 * few lines later when we want to add the new entry.
990 static int have_duplicate_entry(const struct object_id *oid,
994 struct object_entry *entry;
996 entry = packlist_find(&to_pack, oid->hash, index_pos);
1001 if (!entry->preferred_base)
1003 entry->preferred_base = 1;
1009 static int want_found_object(int exclude, struct packed_git *p)
1017 * When asked to do --local (do not include an object that appears in a
1018 * pack we borrow from elsewhere) or --honor-pack-keep (do not include
1019 * an object that appears in a pack marked with .keep), finding a pack
1020 * that matches the criteria is sufficient for us to decide to omit it.
1021 * However, even if this pack does not satisfy the criteria, we need to
1022 * make sure no copy of this object appears in _any_ pack that makes us
1023 * to omit the object, so we need to check all the packs.
1025 * We can however first check whether these options can possible matter;
1026 * if they do not matter we know we want the object in generated pack.
1027 * Otherwise, we signal "-1" at the end to tell the caller that we do
1028 * not know either way, and it needs to check more packs.
1030 if (!ignore_packed_keep_on_disk &&
1031 !ignore_packed_keep_in_core &&
1032 (!local || !have_non_local_packs))
1035 if (local && !p->pack_local)
1037 if (p->pack_local &&
1038 ((ignore_packed_keep_on_disk && p->pack_keep) ||
1039 (ignore_packed_keep_in_core && p->pack_keep_in_core)))
1042 /* we don't know yet; keep looking for more packs */
1047 * Check whether we want the object in the pack (e.g., we do not want
1048 * objects found in non-local stores if the "--local" option was used).
1050 * If the caller already knows an existing pack it wants to take the object
1051 * from, that is passed in *found_pack and *found_offset; otherwise this
1052 * function finds if there is any pack that has the object and returns the pack
1053 * and its offset in these variables.
1055 static int want_object_in_pack(const struct object_id *oid,
1057 struct packed_git **found_pack,
1058 off_t *found_offset)
1061 struct list_head *pos;
1062 struct multi_pack_index *m;
1064 if (!exclude && local && has_loose_object_nonlocal(oid))
1068 * If we already know the pack object lives in, start checks from that
1069 * pack - in the usual case when neither --local was given nor .keep files
1070 * are present we will determine the answer right now.
1073 want = want_found_object(exclude, *found_pack);
1078 for (m = get_multi_pack_index(the_repository); m; m = m->next) {
1079 struct pack_entry e;
1080 if (fill_midx_entry(oid, &e, m)) {
1081 struct packed_git *p = e.p;
1084 if (p == *found_pack)
1085 offset = *found_offset;
1087 offset = find_pack_entry_one(oid->hash, p);
1091 if (!is_pack_valid(p))
1093 *found_offset = offset;
1096 want = want_found_object(exclude, p);
1103 list_for_each(pos, get_packed_git_mru(the_repository)) {
1104 struct packed_git *p = list_entry(pos, struct packed_git, mru);
1107 if (p == *found_pack)
1108 offset = *found_offset;
1110 offset = find_pack_entry_one(oid->hash, p);
1114 if (!is_pack_valid(p))
1116 *found_offset = offset;
1119 want = want_found_object(exclude, p);
1120 if (!exclude && want > 0)
1122 get_packed_git_mru(the_repository));
1131 static void create_object_entry(const struct object_id *oid,
1132 enum object_type type,
1137 struct packed_git *found_pack,
1140 struct object_entry *entry;
1142 entry = packlist_alloc(&to_pack, oid->hash, index_pos);
1144 oe_set_type(entry, type);
1146 entry->preferred_base = 1;
1150 oe_set_in_pack(&to_pack, entry, found_pack);
1151 entry->in_pack_offset = found_offset;
1154 entry->no_try_delta = no_try_delta;
1157 static const char no_closure_warning[] = N_(
1158 "disabling bitmap writing, as some objects are not being packed"
1161 static int add_object_entry(const struct object_id *oid, enum object_type type,
1162 const char *name, int exclude)
1164 struct packed_git *found_pack = NULL;
1165 off_t found_offset = 0;
1168 display_progress(progress_state, ++nr_seen);
1170 if (have_duplicate_entry(oid, exclude, &index_pos))
1173 if (!want_object_in_pack(oid, exclude, &found_pack, &found_offset)) {
1174 /* The pack is missing an object, so it will not have closure */
1175 if (write_bitmap_index) {
1176 warning(_(no_closure_warning));
1177 write_bitmap_index = 0;
1182 create_object_entry(oid, type, pack_name_hash(name),
1183 exclude, name && no_try_delta(name),
1184 index_pos, found_pack, found_offset);
1188 static int add_object_entry_from_bitmap(const struct object_id *oid,
1189 enum object_type type,
1190 int flags, uint32_t name_hash,
1191 struct packed_git *pack, off_t offset)
1195 display_progress(progress_state, ++nr_seen);
1197 if (have_duplicate_entry(oid, 0, &index_pos))
1200 if (!want_object_in_pack(oid, 0, &pack, &offset))
1203 create_object_entry(oid, type, name_hash, 0, 0, index_pos, pack, offset);
1207 struct pbase_tree_cache {
1208 struct object_id oid;
1212 unsigned long tree_size;
1215 static struct pbase_tree_cache *(pbase_tree_cache[256]);
1216 static int pbase_tree_cache_ix(const struct object_id *oid)
1218 return oid->hash[0] % ARRAY_SIZE(pbase_tree_cache);
1220 static int pbase_tree_cache_ix_incr(int ix)
1222 return (ix+1) % ARRAY_SIZE(pbase_tree_cache);
1225 static struct pbase_tree {
1226 struct pbase_tree *next;
1227 /* This is a phony "cache" entry; we are not
1228 * going to evict it or find it through _get()
1229 * mechanism -- this is for the toplevel node that
1230 * would almost always change with any commit.
1232 struct pbase_tree_cache pcache;
1235 static struct pbase_tree_cache *pbase_tree_get(const struct object_id *oid)
1237 struct pbase_tree_cache *ent, *nent;
1240 enum object_type type;
1242 int my_ix = pbase_tree_cache_ix(oid);
1243 int available_ix = -1;
1245 /* pbase-tree-cache acts as a limited hashtable.
1246 * your object will be found at your index or within a few
1247 * slots after that slot if it is cached.
1249 for (neigh = 0; neigh < 8; neigh++) {
1250 ent = pbase_tree_cache[my_ix];
1251 if (ent && oideq(&ent->oid, oid)) {
1255 else if (((available_ix < 0) && (!ent || !ent->ref)) ||
1256 ((0 <= available_ix) &&
1257 (!ent && pbase_tree_cache[available_ix])))
1258 available_ix = my_ix;
1261 my_ix = pbase_tree_cache_ix_incr(my_ix);
1264 /* Did not find one. Either we got a bogus request or
1265 * we need to read and perhaps cache.
1267 data = read_object_file(oid, &type, &size);
1270 if (type != OBJ_TREE) {
1275 /* We need to either cache or return a throwaway copy */
1277 if (available_ix < 0)
1280 ent = pbase_tree_cache[available_ix];
1281 my_ix = available_ix;
1285 nent = xmalloc(sizeof(*nent));
1286 nent->temporary = (available_ix < 0);
1289 /* evict and reuse */
1290 free(ent->tree_data);
1293 oidcpy(&nent->oid, oid);
1294 nent->tree_data = data;
1295 nent->tree_size = size;
1297 if (!nent->temporary)
1298 pbase_tree_cache[my_ix] = nent;
1302 static void pbase_tree_put(struct pbase_tree_cache *cache)
1304 if (!cache->temporary) {
1308 free(cache->tree_data);
1312 static int name_cmp_len(const char *name)
1315 for (i = 0; name[i] && name[i] != '\n' && name[i] != '/'; i++)
1320 static void add_pbase_object(struct tree_desc *tree,
1323 const char *fullname)
1325 struct name_entry entry;
1328 while (tree_entry(tree,&entry)) {
1329 if (S_ISGITLINK(entry.mode))
1331 cmp = tree_entry_len(&entry) != cmplen ? 1 :
1332 memcmp(name, entry.path, cmplen);
1337 if (name[cmplen] != '/') {
1338 add_object_entry(&entry.oid,
1339 object_type(entry.mode),
1343 if (S_ISDIR(entry.mode)) {
1344 struct tree_desc sub;
1345 struct pbase_tree_cache *tree;
1346 const char *down = name+cmplen+1;
1347 int downlen = name_cmp_len(down);
1349 tree = pbase_tree_get(&entry.oid);
1352 init_tree_desc(&sub, tree->tree_data, tree->tree_size);
1354 add_pbase_object(&sub, down, downlen, fullname);
1355 pbase_tree_put(tree);
1360 static unsigned *done_pbase_paths;
1361 static int done_pbase_paths_num;
1362 static int done_pbase_paths_alloc;
1363 static int done_pbase_path_pos(unsigned hash)
1366 int hi = done_pbase_paths_num;
1368 int mi = lo + (hi - lo) / 2;
1369 if (done_pbase_paths[mi] == hash)
1371 if (done_pbase_paths[mi] < hash)
1379 static int check_pbase_path(unsigned hash)
1381 int pos = done_pbase_path_pos(hash);
1385 ALLOC_GROW(done_pbase_paths,
1386 done_pbase_paths_num + 1,
1387 done_pbase_paths_alloc);
1388 done_pbase_paths_num++;
1389 if (pos < done_pbase_paths_num)
1390 MOVE_ARRAY(done_pbase_paths + pos + 1, done_pbase_paths + pos,
1391 done_pbase_paths_num - pos - 1);
1392 done_pbase_paths[pos] = hash;
1396 static void add_preferred_base_object(const char *name)
1398 struct pbase_tree *it;
1400 unsigned hash = pack_name_hash(name);
1402 if (!num_preferred_base || check_pbase_path(hash))
1405 cmplen = name_cmp_len(name);
1406 for (it = pbase_tree; it; it = it->next) {
1408 add_object_entry(&it->pcache.oid, OBJ_TREE, NULL, 1);
1411 struct tree_desc tree;
1412 init_tree_desc(&tree, it->pcache.tree_data, it->pcache.tree_size);
1413 add_pbase_object(&tree, name, cmplen, name);
1418 static void add_preferred_base(struct object_id *oid)
1420 struct pbase_tree *it;
1423 struct object_id tree_oid;
1425 if (window <= num_preferred_base++)
1428 data = read_object_with_reference(oid, tree_type, &size, &tree_oid);
1432 for (it = pbase_tree; it; it = it->next) {
1433 if (oideq(&it->pcache.oid, &tree_oid)) {
1439 it = xcalloc(1, sizeof(*it));
1440 it->next = pbase_tree;
1443 oidcpy(&it->pcache.oid, &tree_oid);
1444 it->pcache.tree_data = data;
1445 it->pcache.tree_size = size;
1448 static void cleanup_preferred_base(void)
1450 struct pbase_tree *it;
1456 struct pbase_tree *tmp = it;
1458 free(tmp->pcache.tree_data);
1462 for (i = 0; i < ARRAY_SIZE(pbase_tree_cache); i++) {
1463 if (!pbase_tree_cache[i])
1465 free(pbase_tree_cache[i]->tree_data);
1466 FREE_AND_NULL(pbase_tree_cache[i]);
1469 FREE_AND_NULL(done_pbase_paths);
1470 done_pbase_paths_num = done_pbase_paths_alloc = 0;
1474 * Return 1 iff the object specified by "delta" can be sent
1475 * literally as a delta against the base in "base_sha1". If
1476 * so, then *base_out will point to the entry in our packing
1477 * list, or NULL if we must use the external-base list.
1479 * Depth value does not matter - find_deltas() will
1480 * never consider reused delta as the base object to
1481 * deltify other objects against, in order to avoid
1484 static int can_reuse_delta(const unsigned char *base_sha1,
1485 struct object_entry *delta,
1486 struct object_entry **base_out)
1488 struct object_entry *base;
1494 * First see if we're already sending the base (or it's explicitly in
1495 * our "excluded" list).
1497 base = packlist_find(&to_pack, base_sha1, NULL);
1499 if (!in_same_island(&delta->idx.oid, &base->idx.oid))
1506 * Otherwise, reachability bitmaps may tell us if the receiver has it,
1507 * even if it was buried too deep in history to make it into the
1510 if (thin && bitmap_has_sha1_in_uninteresting(bitmap_git, base_sha1)) {
1511 if (use_delta_islands) {
1512 struct object_id base_oid;
1513 hashcpy(base_oid.hash, base_sha1);
1514 if (!in_same_island(&delta->idx.oid, &base_oid))
1524 static void check_object(struct object_entry *entry)
1526 unsigned long canonical_size;
1528 if (IN_PACK(entry)) {
1529 struct packed_git *p = IN_PACK(entry);
1530 struct pack_window *w_curs = NULL;
1531 const unsigned char *base_ref = NULL;
1532 struct object_entry *base_entry;
1533 unsigned long used, used_0;
1534 unsigned long avail;
1536 unsigned char *buf, c;
1537 enum object_type type;
1538 unsigned long in_pack_size;
1540 buf = use_pack(p, &w_curs, entry->in_pack_offset, &avail);
1543 * We want in_pack_type even if we do not reuse delta
1544 * since non-delta representations could still be reused.
1546 used = unpack_object_header_buffer(buf, avail,
1553 BUG("invalid type %d", type);
1554 entry->in_pack_type = type;
1557 * Determine if this is a delta and if so whether we can
1558 * reuse it or not. Otherwise let's find out as cheaply as
1559 * possible what the actual type and size for this object is.
1561 switch (entry->in_pack_type) {
1563 /* Not a delta hence we've already got all we need. */
1564 oe_set_type(entry, entry->in_pack_type);
1565 SET_SIZE(entry, in_pack_size);
1566 entry->in_pack_header_size = used;
1567 if (oe_type(entry) < OBJ_COMMIT || oe_type(entry) > OBJ_BLOB)
1569 unuse_pack(&w_curs);
1572 if (reuse_delta && !entry->preferred_base)
1573 base_ref = use_pack(p, &w_curs,
1574 entry->in_pack_offset + used, NULL);
1575 entry->in_pack_header_size = used + the_hash_algo->rawsz;
1578 buf = use_pack(p, &w_curs,
1579 entry->in_pack_offset + used, NULL);
1585 if (!ofs || MSB(ofs, 7)) {
1586 error(_("delta base offset overflow in pack for %s"),
1587 oid_to_hex(&entry->idx.oid));
1591 ofs = (ofs << 7) + (c & 127);
1593 ofs = entry->in_pack_offset - ofs;
1594 if (ofs <= 0 || ofs >= entry->in_pack_offset) {
1595 error(_("delta base offset out of bound for %s"),
1596 oid_to_hex(&entry->idx.oid));
1599 if (reuse_delta && !entry->preferred_base) {
1600 struct revindex_entry *revidx;
1601 revidx = find_pack_revindex(p, ofs);
1604 base_ref = nth_packed_object_sha1(p, revidx->nr);
1606 entry->in_pack_header_size = used + used_0;
1610 if (can_reuse_delta(base_ref, entry, &base_entry)) {
1611 oe_set_type(entry, entry->in_pack_type);
1612 SET_SIZE(entry, in_pack_size); /* delta size */
1613 SET_DELTA_SIZE(entry, in_pack_size);
1616 SET_DELTA(entry, base_entry);
1617 entry->delta_sibling_idx = base_entry->delta_child_idx;
1618 SET_DELTA_CHILD(base_entry, entry);
1620 SET_DELTA_EXT(entry, base_ref);
1623 unuse_pack(&w_curs);
1627 if (oe_type(entry)) {
1631 * This must be a delta and we already know what the
1632 * final object type is. Let's extract the actual
1633 * object size from the delta header.
1635 delta_pos = entry->in_pack_offset + entry->in_pack_header_size;
1636 canonical_size = get_size_from_delta(p, &w_curs, delta_pos);
1637 if (canonical_size == 0)
1639 SET_SIZE(entry, canonical_size);
1640 unuse_pack(&w_curs);
1645 * No choice but to fall back to the recursive delta walk
1646 * with oid_object_info() to find about the object type
1650 unuse_pack(&w_curs);
1654 oid_object_info(the_repository, &entry->idx.oid, &canonical_size));
1655 if (entry->type_valid) {
1656 SET_SIZE(entry, canonical_size);
1659 * Bad object type is checked in prepare_pack(). This is
1660 * to permit a missing preferred base object to be ignored
1661 * as a preferred base. Doing so can result in a larger
1662 * pack file, but the transfer will still take place.
1667 static int pack_offset_sort(const void *_a, const void *_b)
1669 const struct object_entry *a = *(struct object_entry **)_a;
1670 const struct object_entry *b = *(struct object_entry **)_b;
1671 const struct packed_git *a_in_pack = IN_PACK(a);
1672 const struct packed_git *b_in_pack = IN_PACK(b);
1674 /* avoid filesystem trashing with loose objects */
1675 if (!a_in_pack && !b_in_pack)
1676 return oidcmp(&a->idx.oid, &b->idx.oid);
1678 if (a_in_pack < b_in_pack)
1680 if (a_in_pack > b_in_pack)
1682 return a->in_pack_offset < b->in_pack_offset ? -1 :
1683 (a->in_pack_offset > b->in_pack_offset);
1687 * Drop an on-disk delta we were planning to reuse. Naively, this would
1688 * just involve blanking out the "delta" field, but we have to deal
1689 * with some extra book-keeping:
1691 * 1. Removing ourselves from the delta_sibling linked list.
1693 * 2. Updating our size/type to the non-delta representation. These were
1694 * either not recorded initially (size) or overwritten with the delta type
1695 * (type) when check_object() decided to reuse the delta.
1697 * 3. Resetting our delta depth, as we are now a base object.
1699 static void drop_reused_delta(struct object_entry *entry)
1701 unsigned *idx = &to_pack.objects[entry->delta_idx - 1].delta_child_idx;
1702 struct object_info oi = OBJECT_INFO_INIT;
1703 enum object_type type;
1707 struct object_entry *oe = &to_pack.objects[*idx - 1];
1710 *idx = oe->delta_sibling_idx;
1712 idx = &oe->delta_sibling_idx;
1714 SET_DELTA(entry, NULL);
1719 if (packed_object_info(the_repository, IN_PACK(entry), entry->in_pack_offset, &oi) < 0) {
1721 * We failed to get the info from this pack for some reason;
1722 * fall back to oid_object_info, which may find another copy.
1723 * And if that fails, the error will be recorded in oe_type(entry)
1724 * and dealt with in prepare_pack().
1727 oid_object_info(the_repository, &entry->idx.oid, &size));
1729 oe_set_type(entry, type);
1731 SET_SIZE(entry, size);
1735 * Follow the chain of deltas from this entry onward, throwing away any links
1736 * that cause us to hit a cycle (as determined by the DFS state flags in
1739 * We also detect too-long reused chains that would violate our --depth
1742 static void break_delta_chains(struct object_entry *entry)
1745 * The actual depth of each object we will write is stored as an int,
1746 * as it cannot exceed our int "depth" limit. But before we break
1747 * changes based no that limit, we may potentially go as deep as the
1748 * number of objects, which is elsewhere bounded to a uint32_t.
1750 uint32_t total_depth;
1751 struct object_entry *cur, *next;
1753 for (cur = entry, total_depth = 0;
1755 cur = DELTA(cur), total_depth++) {
1756 if (cur->dfs_state == DFS_DONE) {
1758 * We've already seen this object and know it isn't
1759 * part of a cycle. We do need to append its depth
1762 total_depth += cur->depth;
1767 * We break cycles before looping, so an ACTIVE state (or any
1768 * other cruft which made its way into the state variable)
1771 if (cur->dfs_state != DFS_NONE)
1772 BUG("confusing delta dfs state in first pass: %d",
1776 * Now we know this is the first time we've seen the object. If
1777 * it's not a delta, we're done traversing, but we'll mark it
1778 * done to save time on future traversals.
1781 cur->dfs_state = DFS_DONE;
1786 * Mark ourselves as active and see if the next step causes
1787 * us to cycle to another active object. It's important to do
1788 * this _before_ we loop, because it impacts where we make the
1789 * cut, and thus how our total_depth counter works.
1790 * E.g., We may see a partial loop like:
1792 * A -> B -> C -> D -> B
1794 * Cutting B->C breaks the cycle. But now the depth of A is
1795 * only 1, and our total_depth counter is at 3. The size of the
1796 * error is always one less than the size of the cycle we
1797 * broke. Commits C and D were "lost" from A's chain.
1799 * If we instead cut D->B, then the depth of A is correct at 3.
1800 * We keep all commits in the chain that we examined.
1802 cur->dfs_state = DFS_ACTIVE;
1803 if (DELTA(cur)->dfs_state == DFS_ACTIVE) {
1804 drop_reused_delta(cur);
1805 cur->dfs_state = DFS_DONE;
1811 * And now that we've gone all the way to the bottom of the chain, we
1812 * need to clear the active flags and set the depth fields as
1813 * appropriate. Unlike the loop above, which can quit when it drops a
1814 * delta, we need to keep going to look for more depth cuts. So we need
1815 * an extra "next" pointer to keep going after we reset cur->delta.
1817 for (cur = entry; cur; cur = next) {
1821 * We should have a chain of zero or more ACTIVE states down to
1822 * a final DONE. We can quit after the DONE, because either it
1823 * has no bases, or we've already handled them in a previous
1826 if (cur->dfs_state == DFS_DONE)
1828 else if (cur->dfs_state != DFS_ACTIVE)
1829 BUG("confusing delta dfs state in second pass: %d",
1833 * If the total_depth is more than depth, then we need to snip
1834 * the chain into two or more smaller chains that don't exceed
1835 * the maximum depth. Most of the resulting chains will contain
1836 * (depth + 1) entries (i.e., depth deltas plus one base), and
1837 * the last chain (i.e., the one containing entry) will contain
1838 * whatever entries are left over, namely
1839 * (total_depth % (depth + 1)) of them.
1841 * Since we are iterating towards decreasing depth, we need to
1842 * decrement total_depth as we go, and we need to write to the
1843 * entry what its final depth will be after all of the
1844 * snipping. Since we're snipping into chains of length (depth
1845 * + 1) entries, the final depth of an entry will be its
1846 * original depth modulo (depth + 1). Any time we encounter an
1847 * entry whose final depth is supposed to be zero, we snip it
1848 * from its delta base, thereby making it so.
1850 cur->depth = (total_depth--) % (depth + 1);
1852 drop_reused_delta(cur);
1854 cur->dfs_state = DFS_DONE;
1858 static void get_object_details(void)
1861 struct object_entry **sorted_by_offset;
1864 progress_state = start_progress(_("Counting objects"),
1865 to_pack.nr_objects);
1867 sorted_by_offset = xcalloc(to_pack.nr_objects, sizeof(struct object_entry *));
1868 for (i = 0; i < to_pack.nr_objects; i++)
1869 sorted_by_offset[i] = to_pack.objects + i;
1870 QSORT(sorted_by_offset, to_pack.nr_objects, pack_offset_sort);
1872 for (i = 0; i < to_pack.nr_objects; i++) {
1873 struct object_entry *entry = sorted_by_offset[i];
1874 check_object(entry);
1875 if (entry->type_valid &&
1876 oe_size_greater_than(&to_pack, entry, big_file_threshold))
1877 entry->no_try_delta = 1;
1878 display_progress(progress_state, i + 1);
1880 stop_progress(&progress_state);
1883 * This must happen in a second pass, since we rely on the delta
1884 * information for the whole list being completed.
1886 for (i = 0; i < to_pack.nr_objects; i++)
1887 break_delta_chains(&to_pack.objects[i]);
1889 free(sorted_by_offset);
1893 * We search for deltas in a list sorted by type, by filename hash, and then
1894 * by size, so that we see progressively smaller and smaller files.
1895 * That's because we prefer deltas to be from the bigger file
1896 * to the smaller -- deletes are potentially cheaper, but perhaps
1897 * more importantly, the bigger file is likely the more recent
1898 * one. The deepest deltas are therefore the oldest objects which are
1899 * less susceptible to be accessed often.
1901 static int type_size_sort(const void *_a, const void *_b)
1903 const struct object_entry *a = *(struct object_entry **)_a;
1904 const struct object_entry *b = *(struct object_entry **)_b;
1905 const enum object_type a_type = oe_type(a);
1906 const enum object_type b_type = oe_type(b);
1907 const unsigned long a_size = SIZE(a);
1908 const unsigned long b_size = SIZE(b);
1910 if (a_type > b_type)
1912 if (a_type < b_type)
1914 if (a->hash > b->hash)
1916 if (a->hash < b->hash)
1918 if (a->preferred_base > b->preferred_base)
1920 if (a->preferred_base < b->preferred_base)
1922 if (use_delta_islands) {
1923 const int island_cmp = island_delta_cmp(&a->idx.oid, &b->idx.oid);
1927 if (a_size > b_size)
1929 if (a_size < b_size)
1931 return a < b ? -1 : (a > b); /* newest first */
1935 struct object_entry *entry;
1937 struct delta_index *index;
1941 static int delta_cacheable(unsigned long src_size, unsigned long trg_size,
1942 unsigned long delta_size)
1944 if (max_delta_cache_size && delta_cache_size + delta_size > max_delta_cache_size)
1947 if (delta_size < cache_max_small_delta_size)
1950 /* cache delta, if objects are large enough compared to delta size */
1951 if ((src_size >> 20) + (trg_size >> 21) > (delta_size >> 10))
1957 /* Protect delta_cache_size */
1958 static pthread_mutex_t cache_mutex;
1959 #define cache_lock() pthread_mutex_lock(&cache_mutex)
1960 #define cache_unlock() pthread_mutex_unlock(&cache_mutex)
1963 * Protect object list partitioning (e.g. struct thread_param) and
1966 static pthread_mutex_t progress_mutex;
1967 #define progress_lock() pthread_mutex_lock(&progress_mutex)
1968 #define progress_unlock() pthread_mutex_unlock(&progress_mutex)
1971 * Access to struct object_entry is unprotected since each thread owns
1972 * a portion of the main object list. Just don't access object entries
1973 * ahead in the list because they can be stolen and would need
1974 * progress_mutex for protection.
1978 * Return the size of the object without doing any delta
1979 * reconstruction (so non-deltas are true object sizes, but deltas
1980 * return the size of the delta data).
1982 unsigned long oe_get_size_slow(struct packing_data *pack,
1983 const struct object_entry *e)
1985 struct packed_git *p;
1986 struct pack_window *w_curs;
1988 enum object_type type;
1989 unsigned long used, avail, size;
1991 if (e->type_ != OBJ_OFS_DELTA && e->type_ != OBJ_REF_DELTA) {
1992 packing_data_lock(&to_pack);
1993 if (oid_object_info(the_repository, &e->idx.oid, &size) < 0)
1994 die(_("unable to get size of %s"),
1995 oid_to_hex(&e->idx.oid));
1996 packing_data_unlock(&to_pack);
2000 p = oe_in_pack(pack, e);
2002 BUG("when e->type is a delta, it must belong to a pack");
2004 packing_data_lock(&to_pack);
2006 buf = use_pack(p, &w_curs, e->in_pack_offset, &avail);
2007 used = unpack_object_header_buffer(buf, avail, &type, &size);
2009 die(_("unable to parse object header of %s"),
2010 oid_to_hex(&e->idx.oid));
2012 unuse_pack(&w_curs);
2013 packing_data_unlock(&to_pack);
2017 static int try_delta(struct unpacked *trg, struct unpacked *src,
2018 unsigned max_depth, unsigned long *mem_usage)
2020 struct object_entry *trg_entry = trg->entry;
2021 struct object_entry *src_entry = src->entry;
2022 unsigned long trg_size, src_size, delta_size, sizediff, max_size, sz;
2024 enum object_type type;
2027 /* Don't bother doing diffs between different types */
2028 if (oe_type(trg_entry) != oe_type(src_entry))
2032 * We do not bother to try a delta that we discarded on an
2033 * earlier try, but only when reusing delta data. Note that
2034 * src_entry that is marked as the preferred_base should always
2035 * be considered, as even if we produce a suboptimal delta against
2036 * it, we will still save the transfer cost, as we already know
2037 * the other side has it and we won't send src_entry at all.
2039 if (reuse_delta && IN_PACK(trg_entry) &&
2040 IN_PACK(trg_entry) == IN_PACK(src_entry) &&
2041 !src_entry->preferred_base &&
2042 trg_entry->in_pack_type != OBJ_REF_DELTA &&
2043 trg_entry->in_pack_type != OBJ_OFS_DELTA)
2046 /* Let's not bust the allowed depth. */
2047 if (src->depth >= max_depth)
2050 /* Now some size filtering heuristics. */
2051 trg_size = SIZE(trg_entry);
2052 if (!DELTA(trg_entry)) {
2053 max_size = trg_size/2 - the_hash_algo->rawsz;
2056 max_size = DELTA_SIZE(trg_entry);
2057 ref_depth = trg->depth;
2059 max_size = (uint64_t)max_size * (max_depth - src->depth) /
2060 (max_depth - ref_depth + 1);
2063 src_size = SIZE(src_entry);
2064 sizediff = src_size < trg_size ? trg_size - src_size : 0;
2065 if (sizediff >= max_size)
2067 if (trg_size < src_size / 32)
2070 if (!in_same_island(&trg->entry->idx.oid, &src->entry->idx.oid))
2073 /* Load data if not already done */
2075 packing_data_lock(&to_pack);
2076 trg->data = read_object_file(&trg_entry->idx.oid, &type, &sz);
2077 packing_data_unlock(&to_pack);
2079 die(_("object %s cannot be read"),
2080 oid_to_hex(&trg_entry->idx.oid));
2082 die(_("object %s inconsistent object length (%"PRIuMAX" vs %"PRIuMAX")"),
2083 oid_to_hex(&trg_entry->idx.oid), (uintmax_t)sz,
2084 (uintmax_t)trg_size);
2088 packing_data_lock(&to_pack);
2089 src->data = read_object_file(&src_entry->idx.oid, &type, &sz);
2090 packing_data_unlock(&to_pack);
2092 if (src_entry->preferred_base) {
2093 static int warned = 0;
2095 warning(_("object %s cannot be read"),
2096 oid_to_hex(&src_entry->idx.oid));
2098 * Those objects are not included in the
2099 * resulting pack. Be resilient and ignore
2100 * them if they can't be read, in case the
2101 * pack could be created nevertheless.
2105 die(_("object %s cannot be read"),
2106 oid_to_hex(&src_entry->idx.oid));
2109 die(_("object %s inconsistent object length (%"PRIuMAX" vs %"PRIuMAX")"),
2110 oid_to_hex(&src_entry->idx.oid), (uintmax_t)sz,
2111 (uintmax_t)src_size);
2115 src->index = create_delta_index(src->data, src_size);
2117 static int warned = 0;
2119 warning(_("suboptimal pack - out of memory"));
2122 *mem_usage += sizeof_delta_index(src->index);
2125 delta_buf = create_delta(src->index, trg->data, trg_size, &delta_size, max_size);
2129 if (DELTA(trg_entry)) {
2130 /* Prefer only shallower same-sized deltas. */
2131 if (delta_size == DELTA_SIZE(trg_entry) &&
2132 src->depth + 1 >= trg->depth) {
2139 * Handle memory allocation outside of the cache
2140 * accounting lock. Compiler will optimize the strangeness
2141 * away when NO_PTHREADS is defined.
2143 free(trg_entry->delta_data);
2145 if (trg_entry->delta_data) {
2146 delta_cache_size -= DELTA_SIZE(trg_entry);
2147 trg_entry->delta_data = NULL;
2149 if (delta_cacheable(src_size, trg_size, delta_size)) {
2150 delta_cache_size += delta_size;
2152 trg_entry->delta_data = xrealloc(delta_buf, delta_size);
2158 SET_DELTA(trg_entry, src_entry);
2159 SET_DELTA_SIZE(trg_entry, delta_size);
2160 trg->depth = src->depth + 1;
2165 static unsigned int check_delta_limit(struct object_entry *me, unsigned int n)
2167 struct object_entry *child = DELTA_CHILD(me);
2170 const unsigned int c = check_delta_limit(child, n + 1);
2173 child = DELTA_SIBLING(child);
2178 static unsigned long free_unpacked(struct unpacked *n)
2180 unsigned long freed_mem = sizeof_delta_index(n->index);
2181 free_delta_index(n->index);
2184 freed_mem += SIZE(n->entry);
2185 FREE_AND_NULL(n->data);
2192 static void find_deltas(struct object_entry **list, unsigned *list_size,
2193 int window, int depth, unsigned *processed)
2195 uint32_t i, idx = 0, count = 0;
2196 struct unpacked *array;
2197 unsigned long mem_usage = 0;
2199 array = xcalloc(window, sizeof(struct unpacked));
2202 struct object_entry *entry;
2203 struct unpacked *n = array + idx;
2204 int j, max_depth, best_base = -1;
2213 if (!entry->preferred_base) {
2215 display_progress(progress_state, *processed);
2219 mem_usage -= free_unpacked(n);
2222 while (window_memory_limit &&
2223 mem_usage > window_memory_limit &&
2225 const uint32_t tail = (idx + window - count) % window;
2226 mem_usage -= free_unpacked(array + tail);
2230 /* We do not compute delta to *create* objects we are not
2233 if (entry->preferred_base)
2237 * If the current object is at pack edge, take the depth the
2238 * objects that depend on the current object into account
2239 * otherwise they would become too deep.
2242 if (DELTA_CHILD(entry)) {
2243 max_depth -= check_delta_limit(entry, 0);
2251 uint32_t other_idx = idx + j;
2253 if (other_idx >= window)
2254 other_idx -= window;
2255 m = array + other_idx;
2258 ret = try_delta(n, m, max_depth, &mem_usage);
2262 best_base = other_idx;
2266 * If we decided to cache the delta data, then it is best
2267 * to compress it right away. First because we have to do
2268 * it anyway, and doing it here while we're threaded will
2269 * save a lot of time in the non threaded write phase,
2270 * as well as allow for caching more deltas within
2271 * the same cache size limit.
2273 * But only if not writing to stdout, since in that case
2274 * the network is most likely throttling writes anyway,
2275 * and therefore it is best to go to the write phase ASAP
2276 * instead, as we can afford spending more time compressing
2277 * between writes at that moment.
2279 if (entry->delta_data && !pack_to_stdout) {
2282 size = do_compress(&entry->delta_data, DELTA_SIZE(entry));
2283 if (size < (1U << OE_Z_DELTA_BITS)) {
2284 entry->z_delta_size = size;
2286 delta_cache_size -= DELTA_SIZE(entry);
2287 delta_cache_size += entry->z_delta_size;
2290 FREE_AND_NULL(entry->delta_data);
2291 entry->z_delta_size = 0;
2295 /* if we made n a delta, and if n is already at max
2296 * depth, leaving it in the window is pointless. we
2297 * should evict it first.
2299 if (DELTA(entry) && max_depth <= n->depth)
2303 * Move the best delta base up in the window, after the
2304 * currently deltified object, to keep it longer. It will
2305 * be the first base object to be attempted next.
2308 struct unpacked swap = array[best_base];
2309 int dist = (window + idx - best_base) % window;
2310 int dst = best_base;
2312 int src = (dst + 1) % window;
2313 array[dst] = array[src];
2321 if (count + 1 < window)
2327 for (i = 0; i < window; ++i) {
2328 free_delta_index(array[i].index);
2329 free(array[i].data);
2334 static void try_to_free_from_threads(size_t size)
2336 packing_data_lock(&to_pack);
2337 release_pack_memory(size);
2338 packing_data_unlock(&to_pack);
2341 static try_to_free_t old_try_to_free_routine;
2344 * The main object list is split into smaller lists, each is handed to
2347 * The main thread waits on the condition that (at least) one of the workers
2348 * has stopped working (which is indicated in the .working member of
2349 * struct thread_params).
2351 * When a work thread has completed its work, it sets .working to 0 and
2352 * signals the main thread and waits on the condition that .data_ready
2355 * The main thread steals half of the work from the worker that has
2356 * most work left to hand it to the idle worker.
2359 struct thread_params {
2361 struct object_entry **list;
2368 pthread_mutex_t mutex;
2369 pthread_cond_t cond;
2370 unsigned *processed;
2373 static pthread_cond_t progress_cond;
2376 * Mutex and conditional variable can't be statically-initialized on Windows.
2378 static void init_threaded_search(void)
2380 pthread_mutex_init(&cache_mutex, NULL);
2381 pthread_mutex_init(&progress_mutex, NULL);
2382 pthread_cond_init(&progress_cond, NULL);
2383 old_try_to_free_routine = set_try_to_free_routine(try_to_free_from_threads);
2386 static void cleanup_threaded_search(void)
2388 set_try_to_free_routine(old_try_to_free_routine);
2389 pthread_cond_destroy(&progress_cond);
2390 pthread_mutex_destroy(&cache_mutex);
2391 pthread_mutex_destroy(&progress_mutex);
2394 static void *threaded_find_deltas(void *arg)
2396 struct thread_params *me = arg;
2399 while (me->remaining) {
2402 find_deltas(me->list, &me->remaining,
2403 me->window, me->depth, me->processed);
2407 pthread_cond_signal(&progress_cond);
2411 * We must not set ->data_ready before we wait on the
2412 * condition because the main thread may have set it to 1
2413 * before we get here. In order to be sure that new
2414 * work is available if we see 1 in ->data_ready, it
2415 * was initialized to 0 before this thread was spawned
2416 * and we reset it to 0 right away.
2418 pthread_mutex_lock(&me->mutex);
2419 while (!me->data_ready)
2420 pthread_cond_wait(&me->cond, &me->mutex);
2422 pthread_mutex_unlock(&me->mutex);
2427 /* leave ->working 1 so that this doesn't get more work assigned */
2431 static void ll_find_deltas(struct object_entry **list, unsigned list_size,
2432 int window, int depth, unsigned *processed)
2434 struct thread_params *p;
2435 int i, ret, active_threads = 0;
2437 init_threaded_search();
2439 if (delta_search_threads <= 1) {
2440 find_deltas(list, &list_size, window, depth, processed);
2441 cleanup_threaded_search();
2444 if (progress > pack_to_stdout)
2445 fprintf_ln(stderr, _("Delta compression using up to %d threads"),
2446 delta_search_threads);
2447 p = xcalloc(delta_search_threads, sizeof(*p));
2449 /* Partition the work amongst work threads. */
2450 for (i = 0; i < delta_search_threads; i++) {
2451 unsigned sub_size = list_size / (delta_search_threads - i);
2453 /* don't use too small segments or no deltas will be found */
2454 if (sub_size < 2*window && i+1 < delta_search_threads)
2457 p[i].window = window;
2459 p[i].processed = processed;
2461 p[i].data_ready = 0;
2463 /* try to split chunks on "path" boundaries */
2464 while (sub_size && sub_size < list_size &&
2465 list[sub_size]->hash &&
2466 list[sub_size]->hash == list[sub_size-1]->hash)
2470 p[i].list_size = sub_size;
2471 p[i].remaining = sub_size;
2474 list_size -= sub_size;
2477 /* Start work threads. */
2478 for (i = 0; i < delta_search_threads; i++) {
2479 if (!p[i].list_size)
2481 pthread_mutex_init(&p[i].mutex, NULL);
2482 pthread_cond_init(&p[i].cond, NULL);
2483 ret = pthread_create(&p[i].thread, NULL,
2484 threaded_find_deltas, &p[i]);
2486 die(_("unable to create thread: %s"), strerror(ret));
2491 * Now let's wait for work completion. Each time a thread is done
2492 * with its work, we steal half of the remaining work from the
2493 * thread with the largest number of unprocessed objects and give
2494 * it to that newly idle thread. This ensure good load balancing
2495 * until the remaining object list segments are simply too short
2496 * to be worth splitting anymore.
2498 while (active_threads) {
2499 struct thread_params *target = NULL;
2500 struct thread_params *victim = NULL;
2501 unsigned sub_size = 0;
2505 for (i = 0; !target && i < delta_search_threads; i++)
2510 pthread_cond_wait(&progress_cond, &progress_mutex);
2513 for (i = 0; i < delta_search_threads; i++)
2514 if (p[i].remaining > 2*window &&
2515 (!victim || victim->remaining < p[i].remaining))
2518 sub_size = victim->remaining / 2;
2519 list = victim->list + victim->list_size - sub_size;
2520 while (sub_size && list[0]->hash &&
2521 list[0]->hash == list[-1]->hash) {
2527 * It is possible for some "paths" to have
2528 * so many objects that no hash boundary
2529 * might be found. Let's just steal the
2530 * exact half in that case.
2532 sub_size = victim->remaining / 2;
2535 target->list = list;
2536 victim->list_size -= sub_size;
2537 victim->remaining -= sub_size;
2539 target->list_size = sub_size;
2540 target->remaining = sub_size;
2541 target->working = 1;
2544 pthread_mutex_lock(&target->mutex);
2545 target->data_ready = 1;
2546 pthread_cond_signal(&target->cond);
2547 pthread_mutex_unlock(&target->mutex);
2550 pthread_join(target->thread, NULL);
2551 pthread_cond_destroy(&target->cond);
2552 pthread_mutex_destroy(&target->mutex);
2556 cleanup_threaded_search();
2560 static void add_tag_chain(const struct object_id *oid)
2565 * We catch duplicates already in add_object_entry(), but we'd
2566 * prefer to do this extra check to avoid having to parse the
2567 * tag at all if we already know that it's being packed (e.g., if
2568 * it was included via bitmaps, we would not have parsed it
2571 if (packlist_find(&to_pack, oid->hash, NULL))
2574 tag = lookup_tag(the_repository, oid);
2576 if (!tag || parse_tag(tag) || !tag->tagged)
2577 die(_("unable to pack objects reachable from tag %s"),
2580 add_object_entry(&tag->object.oid, OBJ_TAG, NULL, 0);
2582 if (tag->tagged->type != OBJ_TAG)
2585 tag = (struct tag *)tag->tagged;
2589 static int add_ref_tag(const char *path, const struct object_id *oid, int flag, void *cb_data)
2591 struct object_id peeled;
2593 if (starts_with(path, "refs/tags/") && /* is a tag? */
2594 !peel_ref(path, &peeled) && /* peelable? */
2595 packlist_find(&to_pack, peeled.hash, NULL)) /* object packed? */
2600 static void prepare_pack(int window, int depth)
2602 struct object_entry **delta_list;
2603 uint32_t i, nr_deltas;
2606 if (use_delta_islands)
2607 resolve_tree_islands(the_repository, progress, &to_pack);
2609 get_object_details();
2612 * If we're locally repacking then we need to be doubly careful
2613 * from now on in order to make sure no stealth corruption gets
2614 * propagated to the new pack. Clients receiving streamed packs
2615 * should validate everything they get anyway so no need to incur
2616 * the additional cost here in that case.
2618 if (!pack_to_stdout)
2619 do_check_packed_object_crc = 1;
2621 if (!to_pack.nr_objects || !window || !depth)
2624 ALLOC_ARRAY(delta_list, to_pack.nr_objects);
2627 for (i = 0; i < to_pack.nr_objects; i++) {
2628 struct object_entry *entry = to_pack.objects + i;
2631 /* This happens if we decided to reuse existing
2632 * delta from a pack. "reuse_delta &&" is implied.
2636 if (!entry->type_valid ||
2637 oe_size_less_than(&to_pack, entry, 50))
2640 if (entry->no_try_delta)
2643 if (!entry->preferred_base) {
2645 if (oe_type(entry) < 0)
2646 die(_("unable to get type of object %s"),
2647 oid_to_hex(&entry->idx.oid));
2649 if (oe_type(entry) < 0) {
2651 * This object is not found, but we
2652 * don't have to include it anyway.
2658 delta_list[n++] = entry;
2661 if (nr_deltas && n > 1) {
2662 unsigned nr_done = 0;
2664 progress_state = start_progress(_("Compressing objects"),
2666 QSORT(delta_list, n, type_size_sort);
2667 ll_find_deltas(delta_list, n, window+1, depth, &nr_done);
2668 stop_progress(&progress_state);
2669 if (nr_done != nr_deltas)
2670 die(_("inconsistency with delta count"));
2675 static int git_pack_config(const char *k, const char *v, void *cb)
2677 if (!strcmp(k, "pack.window")) {
2678 window = git_config_int(k, v);
2681 if (!strcmp(k, "pack.windowmemory")) {
2682 window_memory_limit = git_config_ulong(k, v);
2685 if (!strcmp(k, "pack.depth")) {
2686 depth = git_config_int(k, v);
2689 if (!strcmp(k, "pack.deltacachesize")) {
2690 max_delta_cache_size = git_config_int(k, v);
2693 if (!strcmp(k, "pack.deltacachelimit")) {
2694 cache_max_small_delta_size = git_config_int(k, v);
2697 if (!strcmp(k, "pack.writebitmaphashcache")) {
2698 if (git_config_bool(k, v))
2699 write_bitmap_options |= BITMAP_OPT_HASH_CACHE;
2701 write_bitmap_options &= ~BITMAP_OPT_HASH_CACHE;
2703 if (!strcmp(k, "pack.usebitmaps")) {
2704 use_bitmap_index_default = git_config_bool(k, v);
2707 if (!strcmp(k, "pack.usesparse")) {
2708 sparse = git_config_bool(k, v);
2711 if (!strcmp(k, "pack.threads")) {
2712 delta_search_threads = git_config_int(k, v);
2713 if (delta_search_threads < 0)
2714 die(_("invalid number of threads specified (%d)"),
2715 delta_search_threads);
2716 if (!HAVE_THREADS && delta_search_threads != 1) {
2717 warning(_("no threads support, ignoring %s"), k);
2718 delta_search_threads = 0;
2722 if (!strcmp(k, "pack.indexversion")) {
2723 pack_idx_opts.version = git_config_int(k, v);
2724 if (pack_idx_opts.version > 2)
2725 die(_("bad pack.indexversion=%"PRIu32),
2726 pack_idx_opts.version);
2729 return git_default_config(k, v, cb);
2732 static void read_object_list_from_stdin(void)
2734 char line[GIT_MAX_HEXSZ + 1 + PATH_MAX + 2];
2735 struct object_id oid;
2739 if (!fgets(line, sizeof(line), stdin)) {
2743 die("BUG: fgets returned NULL, not EOF, not error!");
2749 if (line[0] == '-') {
2750 if (get_oid_hex(line+1, &oid))
2751 die(_("expected edge object ID, got garbage:\n %s"),
2753 add_preferred_base(&oid);
2756 if (parse_oid_hex(line, &oid, &p))
2757 die(_("expected object ID, got garbage:\n %s"), line);
2759 add_preferred_base_object(p + 1);
2760 add_object_entry(&oid, OBJ_NONE, p + 1, 0);
2764 /* Remember to update object flag allocation in object.h */
2765 #define OBJECT_ADDED (1u<<20)
2767 static void show_commit(struct commit *commit, void *data)
2769 add_object_entry(&commit->object.oid, OBJ_COMMIT, NULL, 0);
2770 commit->object.flags |= OBJECT_ADDED;
2772 if (write_bitmap_index)
2773 index_commit_for_bitmap(commit);
2775 if (use_delta_islands)
2776 propagate_island_marks(commit);
2779 static void show_object(struct object *obj, const char *name, void *data)
2781 add_preferred_base_object(name);
2782 add_object_entry(&obj->oid, obj->type, name, 0);
2783 obj->flags |= OBJECT_ADDED;
2785 if (use_delta_islands) {
2788 struct object_entry *ent;
2790 /* the empty string is a root tree, which is depth 0 */
2791 depth = *name ? 1 : 0;
2792 for (p = strchr(name, '/'); p; p = strchr(p + 1, '/'))
2795 ent = packlist_find(&to_pack, obj->oid.hash, NULL);
2796 if (ent && depth > oe_tree_depth(&to_pack, ent))
2797 oe_set_tree_depth(&to_pack, ent, depth);
2801 static void show_object__ma_allow_any(struct object *obj, const char *name, void *data)
2803 assert(arg_missing_action == MA_ALLOW_ANY);
2806 * Quietly ignore ALL missing objects. This avoids problems with
2807 * staging them now and getting an odd error later.
2809 if (!has_object_file(&obj->oid))
2812 show_object(obj, name, data);
2815 static void show_object__ma_allow_promisor(struct object *obj, const char *name, void *data)
2817 assert(arg_missing_action == MA_ALLOW_PROMISOR);
2820 * Quietly ignore EXPECTED missing objects. This avoids problems with
2821 * staging them now and getting an odd error later.
2823 if (!has_object_file(&obj->oid) && is_promisor_object(&obj->oid))
2826 show_object(obj, name, data);
2829 static int option_parse_missing_action(const struct option *opt,
2830 const char *arg, int unset)
2835 if (!strcmp(arg, "error")) {
2836 arg_missing_action = MA_ERROR;
2837 fn_show_object = show_object;
2841 if (!strcmp(arg, "allow-any")) {
2842 arg_missing_action = MA_ALLOW_ANY;
2843 fetch_if_missing = 0;
2844 fn_show_object = show_object__ma_allow_any;
2848 if (!strcmp(arg, "allow-promisor")) {
2849 arg_missing_action = MA_ALLOW_PROMISOR;
2850 fetch_if_missing = 0;
2851 fn_show_object = show_object__ma_allow_promisor;
2855 die(_("invalid value for --missing"));
2859 static void show_edge(struct commit *commit)
2861 add_preferred_base(&commit->object.oid);
2864 struct in_pack_object {
2866 struct object *object;
2872 struct in_pack_object *array;
2875 static void mark_in_pack_object(struct object *object, struct packed_git *p, struct in_pack *in_pack)
2877 in_pack->array[in_pack->nr].offset = find_pack_entry_one(object->oid.hash, p);
2878 in_pack->array[in_pack->nr].object = object;
2883 * Compare the objects in the offset order, in order to emulate the
2884 * "git rev-list --objects" output that produced the pack originally.
2886 static int ofscmp(const void *a_, const void *b_)
2888 struct in_pack_object *a = (struct in_pack_object *)a_;
2889 struct in_pack_object *b = (struct in_pack_object *)b_;
2891 if (a->offset < b->offset)
2893 else if (a->offset > b->offset)
2896 return oidcmp(&a->object->oid, &b->object->oid);
2899 static void add_objects_in_unpacked_packs(struct rev_info *revs)
2901 struct packed_git *p;
2902 struct in_pack in_pack;
2905 memset(&in_pack, 0, sizeof(in_pack));
2907 for (p = get_all_packs(the_repository); p; p = p->next) {
2908 struct object_id oid;
2911 if (!p->pack_local || p->pack_keep || p->pack_keep_in_core)
2913 if (open_pack_index(p))
2914 die(_("cannot open pack index"));
2916 ALLOC_GROW(in_pack.array,
2917 in_pack.nr + p->num_objects,
2920 for (i = 0; i < p->num_objects; i++) {
2921 nth_packed_object_oid(&oid, p, i);
2922 o = lookup_unknown_object(oid.hash);
2923 if (!(o->flags & OBJECT_ADDED))
2924 mark_in_pack_object(o, p, &in_pack);
2925 o->flags |= OBJECT_ADDED;
2930 QSORT(in_pack.array, in_pack.nr, ofscmp);
2931 for (i = 0; i < in_pack.nr; i++) {
2932 struct object *o = in_pack.array[i].object;
2933 add_object_entry(&o->oid, o->type, "", 0);
2936 free(in_pack.array);
2939 static int add_loose_object(const struct object_id *oid, const char *path,
2942 enum object_type type = oid_object_info(the_repository, oid, NULL);
2945 warning(_("loose object at %s could not be examined"), path);
2949 add_object_entry(oid, type, "", 0);
2954 * We actually don't even have to worry about reachability here.
2955 * add_object_entry will weed out duplicates, so we just add every
2956 * loose object we find.
2958 static void add_unreachable_loose_objects(void)
2960 for_each_loose_file_in_objdir(get_object_directory(),
2965 static int has_sha1_pack_kept_or_nonlocal(const struct object_id *oid)
2967 static struct packed_git *last_found = (void *)1;
2968 struct packed_git *p;
2970 p = (last_found != (void *)1) ? last_found :
2971 get_all_packs(the_repository);
2974 if ((!p->pack_local || p->pack_keep ||
2975 p->pack_keep_in_core) &&
2976 find_pack_entry_one(oid->hash, p)) {
2980 if (p == last_found)
2981 p = get_all_packs(the_repository);
2984 if (p == last_found)
2991 * Store a list of sha1s that are should not be discarded
2992 * because they are either written too recently, or are
2993 * reachable from another object that was.
2995 * This is filled by get_object_list.
2997 static struct oid_array recent_objects;
2999 static int loosened_object_can_be_discarded(const struct object_id *oid,
3002 if (!unpack_unreachable_expiration)
3004 if (mtime > unpack_unreachable_expiration)
3006 if (oid_array_lookup(&recent_objects, oid) >= 0)
3011 static void loosen_unused_packed_objects(struct rev_info *revs)
3013 struct packed_git *p;
3015 struct object_id oid;
3017 for (p = get_all_packs(the_repository); p; p = p->next) {
3018 if (!p->pack_local || p->pack_keep || p->pack_keep_in_core)
3021 if (open_pack_index(p))
3022 die(_("cannot open pack index"));
3024 for (i = 0; i < p->num_objects; i++) {
3025 nth_packed_object_oid(&oid, p, i);
3026 if (!packlist_find(&to_pack, oid.hash, NULL) &&
3027 !has_sha1_pack_kept_or_nonlocal(&oid) &&
3028 !loosened_object_can_be_discarded(&oid, p->mtime))
3029 if (force_object_loose(&oid, p->mtime))
3030 die(_("unable to force loose object"));
3036 * This tracks any options which pack-reuse code expects to be on, or which a
3037 * reader of the pack might not understand, and which would therefore prevent
3038 * blind reuse of what we have on disk.
3040 static int pack_options_allow_reuse(void)
3042 return pack_to_stdout &&
3044 !ignore_packed_keep_on_disk &&
3045 !ignore_packed_keep_in_core &&
3046 (!local || !have_non_local_packs) &&
3050 static int get_object_list_from_bitmap(struct rev_info *revs)
3052 if (!(bitmap_git = prepare_bitmap_walk(revs)))
3055 if (pack_options_allow_reuse() &&
3056 !reuse_partial_packfile_from_bitmap(
3059 &reuse_packfile_objects,
3060 &reuse_packfile_offset)) {
3061 assert(reuse_packfile_objects);
3062 nr_result += reuse_packfile_objects;
3063 display_progress(progress_state, nr_result);
3066 traverse_bitmap_commit_list(bitmap_git, &add_object_entry_from_bitmap);
3070 static void record_recent_object(struct object *obj,
3074 oid_array_append(&recent_objects, &obj->oid);
3077 static void record_recent_commit(struct commit *commit, void *data)
3079 oid_array_append(&recent_objects, &commit->object.oid);
3082 static void get_object_list(int ac, const char **av)
3084 struct rev_info revs;
3085 struct setup_revision_opt s_r_opt = {
3086 .allow_exclude_promisor_objects = 1,
3092 repo_init_revisions(the_repository, &revs, NULL);
3093 save_commit_buffer = 0;
3094 setup_revisions(ac, av, &revs, &s_r_opt);
3096 /* make sure shallows are read */
3097 is_repository_shallow(the_repository);
3099 save_warning = warn_on_object_refname_ambiguity;
3100 warn_on_object_refname_ambiguity = 0;
3102 while (fgets(line, sizeof(line), stdin) != NULL) {
3103 int len = strlen(line);
3104 if (len && line[len - 1] == '\n')
3109 if (!strcmp(line, "--not")) {
3110 flags ^= UNINTERESTING;
3111 write_bitmap_index = 0;
3114 if (starts_with(line, "--shallow ")) {
3115 struct object_id oid;
3116 if (get_oid_hex(line + 10, &oid))
3117 die("not an SHA-1 '%s'", line + 10);
3118 register_shallow(the_repository, &oid);
3119 use_bitmap_index = 0;
3122 die(_("not a rev '%s'"), line);
3124 if (handle_revision_arg(line, &revs, flags, REVARG_CANNOT_BE_FILENAME))
3125 die(_("bad revision '%s'"), line);
3128 warn_on_object_refname_ambiguity = save_warning;
3130 if (use_bitmap_index && !get_object_list_from_bitmap(&revs))
3133 if (use_delta_islands)
3134 load_delta_islands(the_repository);
3136 if (prepare_revision_walk(&revs))
3137 die(_("revision walk setup failed"));
3138 mark_edges_uninteresting(&revs, show_edge, sparse);
3140 if (!fn_show_object)
3141 fn_show_object = show_object;
3142 traverse_commit_list_filtered(&filter_options, &revs,
3143 show_commit, fn_show_object, NULL,
3146 if (unpack_unreachable_expiration) {
3147 revs.ignore_missing_links = 1;
3148 if (add_unseen_recent_objects_to_traversal(&revs,
3149 unpack_unreachable_expiration))
3150 die(_("unable to add recent objects"));
3151 if (prepare_revision_walk(&revs))
3152 die(_("revision walk setup failed"));
3153 traverse_commit_list(&revs, record_recent_commit,
3154 record_recent_object, NULL);
3157 if (keep_unreachable)
3158 add_objects_in_unpacked_packs(&revs);
3159 if (pack_loose_unreachable)
3160 add_unreachable_loose_objects();
3161 if (unpack_unreachable)
3162 loosen_unused_packed_objects(&revs);
3164 oid_array_clear(&recent_objects);
3167 static void add_extra_kept_packs(const struct string_list *names)
3169 struct packed_git *p;
3174 for (p = get_all_packs(the_repository); p; p = p->next) {
3175 const char *name = basename(p->pack_name);
3181 for (i = 0; i < names->nr; i++)
3182 if (!fspathcmp(name, names->items[i].string))
3185 if (i < names->nr) {
3186 p->pack_keep_in_core = 1;
3187 ignore_packed_keep_in_core = 1;
3193 static int option_parse_index_version(const struct option *opt,
3194 const char *arg, int unset)
3197 const char *val = arg;
3199 BUG_ON_OPT_NEG(unset);
3201 pack_idx_opts.version = strtoul(val, &c, 10);
3202 if (pack_idx_opts.version > 2)
3203 die(_("unsupported index version %s"), val);
3204 if (*c == ',' && c[1])
3205 pack_idx_opts.off32_limit = strtoul(c+1, &c, 0);
3206 if (*c || pack_idx_opts.off32_limit & 0x80000000)
3207 die(_("bad index version '%s'"), val);
3211 static int option_parse_unpack_unreachable(const struct option *opt,
3212 const char *arg, int unset)
3215 unpack_unreachable = 0;
3216 unpack_unreachable_expiration = 0;
3219 unpack_unreachable = 1;
3221 unpack_unreachable_expiration = approxidate(arg);
3226 int cmd_pack_objects(int argc, const char **argv, const char *prefix)
3228 int use_internal_rev_list = 0;
3230 int all_progress_implied = 0;
3231 struct argv_array rp = ARGV_ARRAY_INIT;
3232 int rev_list_unpacked = 0, rev_list_all = 0, rev_list_reflog = 0;
3233 int rev_list_index = 0;
3234 struct string_list keep_pack_list = STRING_LIST_INIT_NODUP;
3235 struct option pack_objects_options[] = {
3236 OPT_SET_INT('q', "quiet", &progress,
3237 N_("do not show progress meter"), 0),
3238 OPT_SET_INT(0, "progress", &progress,
3239 N_("show progress meter"), 1),
3240 OPT_SET_INT(0, "all-progress", &progress,
3241 N_("show progress meter during object writing phase"), 2),
3242 OPT_BOOL(0, "all-progress-implied",
3243 &all_progress_implied,
3244 N_("similar to --all-progress when progress meter is shown")),
3245 { OPTION_CALLBACK, 0, "index-version", NULL, N_("<version>[,<offset>]"),
3246 N_("write the pack index file in the specified idx format version"),
3247 PARSE_OPT_NONEG, option_parse_index_version },
3248 OPT_MAGNITUDE(0, "max-pack-size", &pack_size_limit,
3249 N_("maximum size of each output pack file")),
3250 OPT_BOOL(0, "local", &local,
3251 N_("ignore borrowed objects from alternate object store")),
3252 OPT_BOOL(0, "incremental", &incremental,
3253 N_("ignore packed objects")),
3254 OPT_INTEGER(0, "window", &window,
3255 N_("limit pack window by objects")),
3256 OPT_MAGNITUDE(0, "window-memory", &window_memory_limit,
3257 N_("limit pack window by memory in addition to object limit")),
3258 OPT_INTEGER(0, "depth", &depth,
3259 N_("maximum length of delta chain allowed in the resulting pack")),
3260 OPT_BOOL(0, "reuse-delta", &reuse_delta,
3261 N_("reuse existing deltas")),
3262 OPT_BOOL(0, "reuse-object", &reuse_object,
3263 N_("reuse existing objects")),
3264 OPT_BOOL(0, "delta-base-offset", &allow_ofs_delta,
3265 N_("use OFS_DELTA objects")),
3266 OPT_INTEGER(0, "threads", &delta_search_threads,
3267 N_("use threads when searching for best delta matches")),
3268 OPT_BOOL(0, "non-empty", &non_empty,
3269 N_("do not create an empty pack output")),
3270 OPT_BOOL(0, "revs", &use_internal_rev_list,
3271 N_("read revision arguments from standard input")),
3272 OPT_SET_INT_F(0, "unpacked", &rev_list_unpacked,
3273 N_("limit the objects to those that are not yet packed"),
3274 1, PARSE_OPT_NONEG),
3275 OPT_SET_INT_F(0, "all", &rev_list_all,
3276 N_("include objects reachable from any reference"),
3277 1, PARSE_OPT_NONEG),
3278 OPT_SET_INT_F(0, "reflog", &rev_list_reflog,
3279 N_("include objects referred by reflog entries"),
3280 1, PARSE_OPT_NONEG),
3281 OPT_SET_INT_F(0, "indexed-objects", &rev_list_index,
3282 N_("include objects referred to by the index"),
3283 1, PARSE_OPT_NONEG),
3284 OPT_BOOL(0, "stdout", &pack_to_stdout,
3285 N_("output pack to stdout")),
3286 OPT_BOOL(0, "include-tag", &include_tag,
3287 N_("include tag objects that refer to objects to be packed")),
3288 OPT_BOOL(0, "keep-unreachable", &keep_unreachable,
3289 N_("keep unreachable objects")),
3290 OPT_BOOL(0, "pack-loose-unreachable", &pack_loose_unreachable,
3291 N_("pack loose unreachable objects")),
3292 { OPTION_CALLBACK, 0, "unpack-unreachable", NULL, N_("time"),
3293 N_("unpack unreachable objects newer than <time>"),
3294 PARSE_OPT_OPTARG, option_parse_unpack_unreachable },
3295 OPT_BOOL(0, "sparse", &sparse,
3296 N_("use the sparse reachability algorithm")),
3297 OPT_BOOL(0, "thin", &thin,
3298 N_("create thin packs")),
3299 OPT_BOOL(0, "shallow", &shallow,
3300 N_("create packs suitable for shallow fetches")),
3301 OPT_BOOL(0, "honor-pack-keep", &ignore_packed_keep_on_disk,
3302 N_("ignore packs that have companion .keep file")),
3303 OPT_STRING_LIST(0, "keep-pack", &keep_pack_list, N_("name"),
3304 N_("ignore this pack")),
3305 OPT_INTEGER(0, "compression", &pack_compression_level,
3306 N_("pack compression level")),
3307 OPT_SET_INT(0, "keep-true-parents", &grafts_replace_parents,
3308 N_("do not hide commits by grafts"), 0),
3309 OPT_BOOL(0, "use-bitmap-index", &use_bitmap_index,
3310 N_("use a bitmap index if available to speed up counting objects")),
3311 OPT_BOOL(0, "write-bitmap-index", &write_bitmap_index,
3312 N_("write a bitmap index together with the pack index")),
3313 OPT_PARSE_LIST_OBJECTS_FILTER(&filter_options),
3314 { OPTION_CALLBACK, 0, "missing", NULL, N_("action"),
3315 N_("handling for missing objects"), PARSE_OPT_NONEG,
3316 option_parse_missing_action },
3317 OPT_BOOL(0, "exclude-promisor-objects", &exclude_promisor_objects,
3318 N_("do not pack objects in promisor packfiles")),
3319 OPT_BOOL(0, "delta-islands", &use_delta_islands,
3320 N_("respect islands during delta compression")),
3324 if (DFS_NUM_STATES > (1 << OE_DFS_STATE_BITS))
3325 BUG("too many dfs states, increase OE_DFS_STATE_BITS");
3327 read_replace_refs = 0;
3329 sparse = git_env_bool("GIT_TEST_PACK_SPARSE", 0);
3330 reset_pack_idx_option(&pack_idx_opts);
3331 git_config(git_pack_config, NULL);
3333 progress = isatty(2);
3334 argc = parse_options(argc, argv, prefix, pack_objects_options,
3338 base_name = argv[0];
3341 if (pack_to_stdout != !base_name || argc)
3342 usage_with_options(pack_usage, pack_objects_options);
3344 if (depth >= (1 << OE_DEPTH_BITS)) {
3345 warning(_("delta chain depth %d is too deep, forcing %d"),
3346 depth, (1 << OE_DEPTH_BITS) - 1);
3347 depth = (1 << OE_DEPTH_BITS) - 1;
3349 if (cache_max_small_delta_size >= (1U << OE_Z_DELTA_BITS)) {
3350 warning(_("pack.deltaCacheLimit is too high, forcing %d"),
3351 (1U << OE_Z_DELTA_BITS) - 1);
3352 cache_max_small_delta_size = (1U << OE_Z_DELTA_BITS) - 1;
3355 argv_array_push(&rp, "pack-objects");
3357 use_internal_rev_list = 1;
3358 argv_array_push(&rp, shallow
3359 ? "--objects-edge-aggressive"
3360 : "--objects-edge");
3362 argv_array_push(&rp, "--objects");
3365 use_internal_rev_list = 1;
3366 argv_array_push(&rp, "--all");
3368 if (rev_list_reflog) {
3369 use_internal_rev_list = 1;
3370 argv_array_push(&rp, "--reflog");
3372 if (rev_list_index) {
3373 use_internal_rev_list = 1;
3374 argv_array_push(&rp, "--indexed-objects");
3376 if (rev_list_unpacked) {
3377 use_internal_rev_list = 1;
3378 argv_array_push(&rp, "--unpacked");
3381 if (exclude_promisor_objects) {
3382 use_internal_rev_list = 1;
3383 fetch_if_missing = 0;
3384 argv_array_push(&rp, "--exclude-promisor-objects");
3386 if (unpack_unreachable || keep_unreachable || pack_loose_unreachable)
3387 use_internal_rev_list = 1;
3391 if (pack_compression_level == -1)
3392 pack_compression_level = Z_DEFAULT_COMPRESSION;
3393 else if (pack_compression_level < 0 || pack_compression_level > Z_BEST_COMPRESSION)
3394 die(_("bad pack compression level %d"), pack_compression_level);
3396 if (!delta_search_threads) /* --threads=0 means autodetect */
3397 delta_search_threads = online_cpus();
3399 if (!HAVE_THREADS && delta_search_threads != 1)
3400 warning(_("no threads support, ignoring --threads"));
3401 if (!pack_to_stdout && !pack_size_limit)
3402 pack_size_limit = pack_size_limit_cfg;
3403 if (pack_to_stdout && pack_size_limit)
3404 die(_("--max-pack-size cannot be used to build a pack for transfer"));
3405 if (pack_size_limit && pack_size_limit < 1024*1024) {
3406 warning(_("minimum pack size limit is 1 MiB"));
3407 pack_size_limit = 1024*1024;
3410 if (!pack_to_stdout && thin)
3411 die(_("--thin cannot be used to build an indexable pack"));
3413 if (keep_unreachable && unpack_unreachable)
3414 die(_("--keep-unreachable and --unpack-unreachable are incompatible"));
3415 if (!rev_list_all || !rev_list_reflog || !rev_list_index)
3416 unpack_unreachable_expiration = 0;
3418 if (filter_options.choice) {
3419 if (!pack_to_stdout)
3420 die(_("cannot use --filter without --stdout"));
3421 use_bitmap_index = 0;
3425 * "soft" reasons not to use bitmaps - for on-disk repack by default we want
3427 * - to produce good pack (with bitmap index not-yet-packed objects are
3428 * packed in suboptimal order).
3430 * - to use more robust pack-generation codepath (avoiding possible
3431 * bugs in bitmap code and possible bitmap index corruption).
3433 if (!pack_to_stdout)
3434 use_bitmap_index_default = 0;
3436 if (use_bitmap_index < 0)
3437 use_bitmap_index = use_bitmap_index_default;
3439 /* "hard" reasons not to use bitmaps; these just won't work at all */
3440 if (!use_internal_rev_list || (!pack_to_stdout && write_bitmap_index) || is_repository_shallow(the_repository))
3441 use_bitmap_index = 0;
3443 if (pack_to_stdout || !rev_list_all)
3444 write_bitmap_index = 0;
3446 if (use_delta_islands)
3447 argv_array_push(&rp, "--topo-order");
3449 if (progress && all_progress_implied)
3452 add_extra_kept_packs(&keep_pack_list);
3453 if (ignore_packed_keep_on_disk) {
3454 struct packed_git *p;
3455 for (p = get_all_packs(the_repository); p; p = p->next)
3456 if (p->pack_local && p->pack_keep)
3458 if (!p) /* no keep-able packs found */
3459 ignore_packed_keep_on_disk = 0;
3463 * unlike ignore_packed_keep_on_disk above, we do not
3464 * want to unset "local" based on looking at packs, as
3465 * it also covers non-local objects
3467 struct packed_git *p;
3468 for (p = get_all_packs(the_repository); p; p = p->next) {
3469 if (!p->pack_local) {
3470 have_non_local_packs = 1;
3476 prepare_packing_data(the_repository, &to_pack);
3479 progress_state = start_progress(_("Enumerating objects"), 0);
3480 if (!use_internal_rev_list)
3481 read_object_list_from_stdin();
3483 get_object_list(rp.argc, rp.argv);
3484 argv_array_clear(&rp);
3486 cleanup_preferred_base();
3487 if (include_tag && nr_result)
3488 for_each_ref(add_ref_tag, NULL);
3489 stop_progress(&progress_state);
3491 if (non_empty && !nr_result)
3494 prepare_pack(window, depth);
3498 _("Total %"PRIu32" (delta %"PRIu32"),"
3499 " reused %"PRIu32" (delta %"PRIu32")"),
3500 written, written_delta, reused, reused_delta);