Vcproj.pm: urlencode '<' and '>' when generating VC projects
[git/raj.git] / builtin / pack-objects.c
blob000dc4b872b23d555d87f475511ca60d601bc4a1
1 #include "builtin.h"
2 #include "cache.h"
3 #include "repository.h"
4 #include "config.h"
5 #include "attr.h"
6 #include "object.h"
7 #include "blob.h"
8 #include "commit.h"
9 #include "tag.h"
10 #include "tree.h"
11 #include "delta.h"
12 #include "pack.h"
13 #include "pack-revindex.h"
14 #include "csum-file.h"
15 #include "tree-walk.h"
16 #include "diff.h"
17 #include "revision.h"
18 #include "list-objects.h"
19 #include "list-objects-filter.h"
20 #include "list-objects-filter-options.h"
21 #include "pack-objects.h"
22 #include "progress.h"
23 #include "refs.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"
31 #include "list.h"
32 #include "packfile.h"
33 #include "object-store.h"
34 #include "dir.h"
35 #include "midx.h"
36 #include "trace2.h"
38 #define IN_PACK(obj) oe_in_pack(&to_pack, obj)
39 #define SIZE(obj) oe_size(&to_pack, obj)
40 #define SET_SIZE(obj,size) oe_set_size(&to_pack, obj, size)
41 #define DELTA_SIZE(obj) oe_delta_size(&to_pack, obj)
42 #define DELTA(obj) oe_delta(&to_pack, obj)
43 #define DELTA_CHILD(obj) oe_delta_child(&to_pack, obj)
44 #define DELTA_SIBLING(obj) oe_delta_sibling(&to_pack, obj)
45 #define SET_DELTA(obj, val) oe_set_delta(&to_pack, obj, val)
46 #define SET_DELTA_EXT(obj, oid) oe_set_delta_ext(&to_pack, obj, oid)
47 #define SET_DELTA_SIZE(obj, val) oe_set_delta_size(&to_pack, obj, val)
48 #define SET_DELTA_CHILD(obj, val) oe_set_delta_child(&to_pack, obj, val)
49 #define SET_DELTA_SIBLING(obj, val) oe_set_delta_sibling(&to_pack, obj, val)
51 static const char *pack_usage[] = {
52 N_("git pack-objects --stdout [<options>...] [< <ref-list> | < <object-list>]"),
53 N_("git pack-objects [<options>...] <base-name> [< <ref-list> | < <object-list>]"),
54 NULL
58 * Objects we are going to pack are collected in the `to_pack` structure.
59 * It contains an array (dynamically expanded) of the object data, and a map
60 * that can resolve SHA1s to their position in the array.
62 static struct packing_data to_pack;
64 static struct pack_idx_entry **written_list;
65 static uint32_t nr_result, nr_written, nr_seen;
66 static struct bitmap_index *bitmap_git;
67 static uint32_t write_layer;
69 static int non_empty;
70 static int reuse_delta = 1, reuse_object = 1;
71 static int keep_unreachable, unpack_unreachable, include_tag;
72 static timestamp_t unpack_unreachable_expiration;
73 static int pack_loose_unreachable;
74 static int local;
75 static int have_non_local_packs;
76 static int incremental;
77 static int ignore_packed_keep_on_disk;
78 static int ignore_packed_keep_in_core;
79 static int allow_ofs_delta;
80 static struct pack_idx_option pack_idx_opts;
81 static const char *base_name;
82 static int progress = 1;
83 static int window = 10;
84 static unsigned long pack_size_limit;
85 static int depth = 50;
86 static int delta_search_threads;
87 static int pack_to_stdout;
88 static int sparse;
89 static int thin;
90 static int num_preferred_base;
91 static struct progress *progress_state;
93 static struct packed_git *reuse_packfile;
94 static uint32_t reuse_packfile_objects;
95 static off_t reuse_packfile_offset;
97 static int use_bitmap_index_default = 1;
98 static int use_bitmap_index = -1;
99 static int write_bitmap_index;
100 static uint16_t write_bitmap_options = BITMAP_OPT_HASH_CACHE;
102 static int exclude_promisor_objects;
104 static int use_delta_islands;
106 static unsigned long delta_cache_size = 0;
107 static unsigned long max_delta_cache_size = DEFAULT_DELTA_CACHE_SIZE;
108 static unsigned long cache_max_small_delta_size = 1000;
110 static unsigned long window_memory_limit = 0;
112 static struct list_objects_filter_options filter_options;
114 enum missing_action {
115 MA_ERROR = 0, /* fail if any missing objects are encountered */
116 MA_ALLOW_ANY, /* silently allow ALL missing objects */
117 MA_ALLOW_PROMISOR, /* silently allow all missing PROMISOR objects */
119 static enum missing_action arg_missing_action;
120 static show_object_fn fn_show_object;
123 * stats
125 static uint32_t written, written_delta;
126 static uint32_t reused, reused_delta;
129 * Indexed commits
131 static struct commit **indexed_commits;
132 static unsigned int indexed_commits_nr;
133 static unsigned int indexed_commits_alloc;
135 static void index_commit_for_bitmap(struct commit *commit)
137 if (indexed_commits_nr >= indexed_commits_alloc) {
138 indexed_commits_alloc = (indexed_commits_alloc + 32) * 2;
139 REALLOC_ARRAY(indexed_commits, indexed_commits_alloc);
142 indexed_commits[indexed_commits_nr++] = commit;
145 static void *get_delta(struct object_entry *entry)
147 unsigned long size, base_size, delta_size;
148 void *buf, *base_buf, *delta_buf;
149 enum object_type type;
151 buf = read_object_file(&entry->idx.oid, &type, &size);
152 if (!buf)
153 die(_("unable to read %s"), oid_to_hex(&entry->idx.oid));
154 base_buf = read_object_file(&DELTA(entry)->idx.oid, &type,
155 &base_size);
156 if (!base_buf)
157 die("unable to read %s",
158 oid_to_hex(&DELTA(entry)->idx.oid));
159 delta_buf = diff_delta(base_buf, base_size,
160 buf, size, &delta_size, 0);
162 * We succesfully computed this delta once but dropped it for
163 * memory reasons. Something is very wrong if this time we
164 * recompute and create a different delta.
166 if (!delta_buf || delta_size != DELTA_SIZE(entry))
167 BUG("delta size changed");
168 free(buf);
169 free(base_buf);
170 return delta_buf;
173 static unsigned long do_compress(void **pptr, unsigned long size)
175 git_zstream stream;
176 void *in, *out;
177 unsigned long maxsize;
179 git_deflate_init(&stream, pack_compression_level);
180 maxsize = git_deflate_bound(&stream, size);
182 in = *pptr;
183 out = xmalloc(maxsize);
184 *pptr = out;
186 stream.next_in = in;
187 stream.avail_in = size;
188 stream.next_out = out;
189 stream.avail_out = maxsize;
190 while (git_deflate(&stream, Z_FINISH) == Z_OK)
191 ; /* nothing */
192 git_deflate_end(&stream);
194 free(in);
195 return stream.total_out;
198 static unsigned long write_large_blob_data(struct git_istream *st, struct hashfile *f,
199 const struct object_id *oid)
201 git_zstream stream;
202 unsigned char ibuf[1024 * 16];
203 unsigned char obuf[1024 * 16];
204 unsigned long olen = 0;
206 git_deflate_init(&stream, pack_compression_level);
208 for (;;) {
209 ssize_t readlen;
210 int zret = Z_OK;
211 readlen = read_istream(st, ibuf, sizeof(ibuf));
212 if (readlen == -1)
213 die(_("unable to read %s"), oid_to_hex(oid));
215 stream.next_in = ibuf;
216 stream.avail_in = readlen;
217 while ((stream.avail_in || readlen == 0) &&
218 (zret == Z_OK || zret == Z_BUF_ERROR)) {
219 stream.next_out = obuf;
220 stream.avail_out = sizeof(obuf);
221 zret = git_deflate(&stream, readlen ? 0 : Z_FINISH);
222 hashwrite(f, obuf, stream.next_out - obuf);
223 olen += stream.next_out - obuf;
225 if (stream.avail_in)
226 die(_("deflate error (%d)"), zret);
227 if (readlen == 0) {
228 if (zret != Z_STREAM_END)
229 die(_("deflate error (%d)"), zret);
230 break;
233 git_deflate_end(&stream);
234 return olen;
238 * we are going to reuse the existing object data as is. make
239 * sure it is not corrupt.
241 static int check_pack_inflate(struct packed_git *p,
242 struct pack_window **w_curs,
243 off_t offset,
244 off_t len,
245 unsigned long expect)
247 git_zstream stream;
248 unsigned char fakebuf[4096], *in;
249 int st;
251 memset(&stream, 0, sizeof(stream));
252 git_inflate_init(&stream);
253 do {
254 in = use_pack(p, w_curs, offset, &stream.avail_in);
255 stream.next_in = in;
256 stream.next_out = fakebuf;
257 stream.avail_out = sizeof(fakebuf);
258 st = git_inflate(&stream, Z_FINISH);
259 offset += stream.next_in - in;
260 } while (st == Z_OK || st == Z_BUF_ERROR);
261 git_inflate_end(&stream);
262 return (st == Z_STREAM_END &&
263 stream.total_out == expect &&
264 stream.total_in == len) ? 0 : -1;
267 static void copy_pack_data(struct hashfile *f,
268 struct packed_git *p,
269 struct pack_window **w_curs,
270 off_t offset,
271 off_t len)
273 unsigned char *in;
274 unsigned long avail;
276 while (len) {
277 in = use_pack(p, w_curs, offset, &avail);
278 if (avail > len)
279 avail = (unsigned long)len;
280 hashwrite(f, in, avail);
281 offset += avail;
282 len -= avail;
286 /* Return 0 if we will bust the pack-size limit */
287 static unsigned long write_no_reuse_object(struct hashfile *f, struct object_entry *entry,
288 unsigned long limit, int usable_delta)
290 unsigned long size, datalen;
291 unsigned char header[MAX_PACK_OBJECT_HEADER],
292 dheader[MAX_PACK_OBJECT_HEADER];
293 unsigned hdrlen;
294 enum object_type type;
295 void *buf;
296 struct git_istream *st = NULL;
297 const unsigned hashsz = the_hash_algo->rawsz;
299 if (!usable_delta) {
300 if (oe_type(entry) == OBJ_BLOB &&
301 oe_size_greater_than(&to_pack, entry, big_file_threshold) &&
302 (st = open_istream(&entry->idx.oid, &type, &size, NULL)) != NULL)
303 buf = NULL;
304 else {
305 buf = read_object_file(&entry->idx.oid, &type, &size);
306 if (!buf)
307 die(_("unable to read %s"),
308 oid_to_hex(&entry->idx.oid));
311 * make sure no cached delta data remains from a
312 * previous attempt before a pack split occurred.
314 FREE_AND_NULL(entry->delta_data);
315 entry->z_delta_size = 0;
316 } else if (entry->delta_data) {
317 size = DELTA_SIZE(entry);
318 buf = entry->delta_data;
319 entry->delta_data = NULL;
320 type = (allow_ofs_delta && DELTA(entry)->idx.offset) ?
321 OBJ_OFS_DELTA : OBJ_REF_DELTA;
322 } else {
323 buf = get_delta(entry);
324 size = DELTA_SIZE(entry);
325 type = (allow_ofs_delta && DELTA(entry)->idx.offset) ?
326 OBJ_OFS_DELTA : OBJ_REF_DELTA;
329 if (st) /* large blob case, just assume we don't compress well */
330 datalen = size;
331 else if (entry->z_delta_size)
332 datalen = entry->z_delta_size;
333 else
334 datalen = do_compress(&buf, size);
337 * The object header is a byte of 'type' followed by zero or
338 * more bytes of length.
340 hdrlen = encode_in_pack_object_header(header, sizeof(header),
341 type, size);
343 if (type == OBJ_OFS_DELTA) {
345 * Deltas with relative base contain an additional
346 * encoding of the relative offset for the delta
347 * base from this object's position in the pack.
349 off_t ofs = entry->idx.offset - DELTA(entry)->idx.offset;
350 unsigned pos = sizeof(dheader) - 1;
351 dheader[pos] = ofs & 127;
352 while (ofs >>= 7)
353 dheader[--pos] = 128 | (--ofs & 127);
354 if (limit && hdrlen + sizeof(dheader) - pos + datalen + hashsz >= limit) {
355 if (st)
356 close_istream(st);
357 free(buf);
358 return 0;
360 hashwrite(f, header, hdrlen);
361 hashwrite(f, dheader + pos, sizeof(dheader) - pos);
362 hdrlen += sizeof(dheader) - pos;
363 } else if (type == OBJ_REF_DELTA) {
365 * Deltas with a base reference contain
366 * additional bytes for the base object ID.
368 if (limit && hdrlen + hashsz + datalen + hashsz >= limit) {
369 if (st)
370 close_istream(st);
371 free(buf);
372 return 0;
374 hashwrite(f, header, hdrlen);
375 hashwrite(f, DELTA(entry)->idx.oid.hash, hashsz);
376 hdrlen += hashsz;
377 } else {
378 if (limit && hdrlen + datalen + hashsz >= limit) {
379 if (st)
380 close_istream(st);
381 free(buf);
382 return 0;
384 hashwrite(f, header, hdrlen);
386 if (st) {
387 datalen = write_large_blob_data(st, f, &entry->idx.oid);
388 close_istream(st);
389 } else {
390 hashwrite(f, buf, datalen);
391 free(buf);
394 return hdrlen + datalen;
397 /* Return 0 if we will bust the pack-size limit */
398 static off_t write_reuse_object(struct hashfile *f, struct object_entry *entry,
399 unsigned long limit, int usable_delta)
401 struct packed_git *p = IN_PACK(entry);
402 struct pack_window *w_curs = NULL;
403 struct revindex_entry *revidx;
404 off_t offset;
405 enum object_type type = oe_type(entry);
406 off_t datalen;
407 unsigned char header[MAX_PACK_OBJECT_HEADER],
408 dheader[MAX_PACK_OBJECT_HEADER];
409 unsigned hdrlen;
410 const unsigned hashsz = the_hash_algo->rawsz;
411 unsigned long entry_size = SIZE(entry);
413 if (DELTA(entry))
414 type = (allow_ofs_delta && DELTA(entry)->idx.offset) ?
415 OBJ_OFS_DELTA : OBJ_REF_DELTA;
416 hdrlen = encode_in_pack_object_header(header, sizeof(header),
417 type, entry_size);
419 offset = entry->in_pack_offset;
420 revidx = find_pack_revindex(p, offset);
421 datalen = revidx[1].offset - offset;
422 if (!pack_to_stdout && p->index_version > 1 &&
423 check_pack_crc(p, &w_curs, offset, datalen, revidx->nr)) {
424 error(_("bad packed object CRC for %s"),
425 oid_to_hex(&entry->idx.oid));
426 unuse_pack(&w_curs);
427 return write_no_reuse_object(f, entry, limit, usable_delta);
430 offset += entry->in_pack_header_size;
431 datalen -= entry->in_pack_header_size;
433 if (!pack_to_stdout && p->index_version == 1 &&
434 check_pack_inflate(p, &w_curs, offset, datalen, entry_size)) {
435 error(_("corrupt packed object for %s"),
436 oid_to_hex(&entry->idx.oid));
437 unuse_pack(&w_curs);
438 return write_no_reuse_object(f, entry, limit, usable_delta);
441 if (type == OBJ_OFS_DELTA) {
442 off_t ofs = entry->idx.offset - DELTA(entry)->idx.offset;
443 unsigned pos = sizeof(dheader) - 1;
444 dheader[pos] = ofs & 127;
445 while (ofs >>= 7)
446 dheader[--pos] = 128 | (--ofs & 127);
447 if (limit && hdrlen + sizeof(dheader) - pos + datalen + hashsz >= limit) {
448 unuse_pack(&w_curs);
449 return 0;
451 hashwrite(f, header, hdrlen);
452 hashwrite(f, dheader + pos, sizeof(dheader) - pos);
453 hdrlen += sizeof(dheader) - pos;
454 reused_delta++;
455 } else if (type == OBJ_REF_DELTA) {
456 if (limit && hdrlen + hashsz + datalen + hashsz >= limit) {
457 unuse_pack(&w_curs);
458 return 0;
460 hashwrite(f, header, hdrlen);
461 hashwrite(f, DELTA(entry)->idx.oid.hash, hashsz);
462 hdrlen += hashsz;
463 reused_delta++;
464 } else {
465 if (limit && hdrlen + datalen + hashsz >= limit) {
466 unuse_pack(&w_curs);
467 return 0;
469 hashwrite(f, header, hdrlen);
471 copy_pack_data(f, p, &w_curs, offset, datalen);
472 unuse_pack(&w_curs);
473 reused++;
474 return hdrlen + datalen;
477 /* Return 0 if we will bust the pack-size limit */
478 static off_t write_object(struct hashfile *f,
479 struct object_entry *entry,
480 off_t write_offset)
482 unsigned long limit;
483 off_t len;
484 int usable_delta, to_reuse;
486 if (!pack_to_stdout)
487 crc32_begin(f);
489 /* apply size limit if limited packsize and not first object */
490 if (!pack_size_limit || !nr_written)
491 limit = 0;
492 else if (pack_size_limit <= write_offset)
494 * the earlier object did not fit the limit; avoid
495 * mistaking this with unlimited (i.e. limit = 0).
497 limit = 1;
498 else
499 limit = pack_size_limit - write_offset;
501 if (!DELTA(entry))
502 usable_delta = 0; /* no delta */
503 else if (!pack_size_limit)
504 usable_delta = 1; /* unlimited packfile */
505 else if (DELTA(entry)->idx.offset == (off_t)-1)
506 usable_delta = 0; /* base was written to another pack */
507 else if (DELTA(entry)->idx.offset)
508 usable_delta = 1; /* base already exists in this pack */
509 else
510 usable_delta = 0; /* base could end up in another pack */
512 if (!reuse_object)
513 to_reuse = 0; /* explicit */
514 else if (!IN_PACK(entry))
515 to_reuse = 0; /* can't reuse what we don't have */
516 else if (oe_type(entry) == OBJ_REF_DELTA ||
517 oe_type(entry) == OBJ_OFS_DELTA)
518 /* check_object() decided it for us ... */
519 to_reuse = usable_delta;
520 /* ... but pack split may override that */
521 else if (oe_type(entry) != entry->in_pack_type)
522 to_reuse = 0; /* pack has delta which is unusable */
523 else if (DELTA(entry))
524 to_reuse = 0; /* we want to pack afresh */
525 else
526 to_reuse = 1; /* we have it in-pack undeltified,
527 * and we do not need to deltify it.
530 if (!to_reuse)
531 len = write_no_reuse_object(f, entry, limit, usable_delta);
532 else
533 len = write_reuse_object(f, entry, limit, usable_delta);
534 if (!len)
535 return 0;
537 if (usable_delta)
538 written_delta++;
539 written++;
540 if (!pack_to_stdout)
541 entry->idx.crc32 = crc32_end(f);
542 return len;
545 enum write_one_status {
546 WRITE_ONE_SKIP = -1, /* already written */
547 WRITE_ONE_BREAK = 0, /* writing this will bust the limit; not written */
548 WRITE_ONE_WRITTEN = 1, /* normal */
549 WRITE_ONE_RECURSIVE = 2 /* already scheduled to be written */
552 static enum write_one_status write_one(struct hashfile *f,
553 struct object_entry *e,
554 off_t *offset)
556 off_t size;
557 int recursing;
560 * we set offset to 1 (which is an impossible value) to mark
561 * the fact that this object is involved in "write its base
562 * first before writing a deltified object" recursion.
564 recursing = (e->idx.offset == 1);
565 if (recursing) {
566 warning(_("recursive delta detected for object %s"),
567 oid_to_hex(&e->idx.oid));
568 return WRITE_ONE_RECURSIVE;
569 } else if (e->idx.offset || e->preferred_base) {
570 /* offset is non zero if object is written already. */
571 return WRITE_ONE_SKIP;
574 /* if we are deltified, write out base object first. */
575 if (DELTA(e)) {
576 e->idx.offset = 1; /* now recurse */
577 switch (write_one(f, DELTA(e), offset)) {
578 case WRITE_ONE_RECURSIVE:
579 /* we cannot depend on this one */
580 SET_DELTA(e, NULL);
581 break;
582 default:
583 break;
584 case WRITE_ONE_BREAK:
585 e->idx.offset = recursing;
586 return WRITE_ONE_BREAK;
590 e->idx.offset = *offset;
591 size = write_object(f, e, *offset);
592 if (!size) {
593 e->idx.offset = recursing;
594 return WRITE_ONE_BREAK;
596 written_list[nr_written++] = &e->idx;
598 /* make sure off_t is sufficiently large not to wrap */
599 if (signed_add_overflows(*offset, size))
600 die(_("pack too large for current definition of off_t"));
601 *offset += size;
602 return WRITE_ONE_WRITTEN;
605 static int mark_tagged(const char *path, const struct object_id *oid, int flag,
606 void *cb_data)
608 struct object_id peeled;
609 struct object_entry *entry = packlist_find(&to_pack, oid, NULL);
611 if (entry)
612 entry->tagged = 1;
613 if (!peel_ref(path, &peeled)) {
614 entry = packlist_find(&to_pack, &peeled, NULL);
615 if (entry)
616 entry->tagged = 1;
618 return 0;
621 static inline void add_to_write_order(struct object_entry **wo,
622 unsigned int *endp,
623 struct object_entry *e)
625 if (e->filled || oe_layer(&to_pack, e) != write_layer)
626 return;
627 wo[(*endp)++] = e;
628 e->filled = 1;
631 static void add_descendants_to_write_order(struct object_entry **wo,
632 unsigned int *endp,
633 struct object_entry *e)
635 int add_to_order = 1;
636 while (e) {
637 if (add_to_order) {
638 struct object_entry *s;
639 /* add this node... */
640 add_to_write_order(wo, endp, e);
641 /* all its siblings... */
642 for (s = DELTA_SIBLING(e); s; s = DELTA_SIBLING(s)) {
643 add_to_write_order(wo, endp, s);
646 /* drop down a level to add left subtree nodes if possible */
647 if (DELTA_CHILD(e)) {
648 add_to_order = 1;
649 e = DELTA_CHILD(e);
650 } else {
651 add_to_order = 0;
652 /* our sibling might have some children, it is next */
653 if (DELTA_SIBLING(e)) {
654 e = DELTA_SIBLING(e);
655 continue;
657 /* go back to our parent node */
658 e = DELTA(e);
659 while (e && !DELTA_SIBLING(e)) {
660 /* we're on the right side of a subtree, keep
661 * going up until we can go right again */
662 e = DELTA(e);
664 if (!e) {
665 /* done- we hit our original root node */
666 return;
668 /* pass it off to sibling at this level */
669 e = DELTA_SIBLING(e);
674 static void add_family_to_write_order(struct object_entry **wo,
675 unsigned int *endp,
676 struct object_entry *e)
678 struct object_entry *root;
680 for (root = e; DELTA(root); root = DELTA(root))
681 ; /* nothing */
682 add_descendants_to_write_order(wo, endp, root);
685 static void compute_layer_order(struct object_entry **wo, unsigned int *wo_end)
687 unsigned int i, last_untagged;
688 struct object_entry *objects = to_pack.objects;
690 for (i = 0; i < to_pack.nr_objects; i++) {
691 if (objects[i].tagged)
692 break;
693 add_to_write_order(wo, wo_end, &objects[i]);
695 last_untagged = i;
698 * Then fill all the tagged tips.
700 for (; i < to_pack.nr_objects; i++) {
701 if (objects[i].tagged)
702 add_to_write_order(wo, wo_end, &objects[i]);
706 * And then all remaining commits and tags.
708 for (i = last_untagged; i < to_pack.nr_objects; i++) {
709 if (oe_type(&objects[i]) != OBJ_COMMIT &&
710 oe_type(&objects[i]) != OBJ_TAG)
711 continue;
712 add_to_write_order(wo, wo_end, &objects[i]);
716 * And then all the trees.
718 for (i = last_untagged; i < to_pack.nr_objects; i++) {
719 if (oe_type(&objects[i]) != OBJ_TREE)
720 continue;
721 add_to_write_order(wo, wo_end, &objects[i]);
725 * Finally all the rest in really tight order
727 for (i = last_untagged; i < to_pack.nr_objects; i++) {
728 if (!objects[i].filled && oe_layer(&to_pack, &objects[i]) == write_layer)
729 add_family_to_write_order(wo, wo_end, &objects[i]);
733 static struct object_entry **compute_write_order(void)
735 uint32_t max_layers = 1;
736 unsigned int i, wo_end;
738 struct object_entry **wo;
739 struct object_entry *objects = to_pack.objects;
741 for (i = 0; i < to_pack.nr_objects; i++) {
742 objects[i].tagged = 0;
743 objects[i].filled = 0;
744 SET_DELTA_CHILD(&objects[i], NULL);
745 SET_DELTA_SIBLING(&objects[i], NULL);
749 * Fully connect delta_child/delta_sibling network.
750 * Make sure delta_sibling is sorted in the original
751 * recency order.
753 for (i = to_pack.nr_objects; i > 0;) {
754 struct object_entry *e = &objects[--i];
755 if (!DELTA(e))
756 continue;
757 /* Mark me as the first child */
758 e->delta_sibling_idx = DELTA(e)->delta_child_idx;
759 SET_DELTA_CHILD(DELTA(e), e);
763 * Mark objects that are at the tip of tags.
765 for_each_tag_ref(mark_tagged, NULL);
767 if (use_delta_islands)
768 max_layers = compute_pack_layers(&to_pack);
770 ALLOC_ARRAY(wo, to_pack.nr_objects);
771 wo_end = 0;
773 for (; write_layer < max_layers; ++write_layer)
774 compute_layer_order(wo, &wo_end);
776 if (wo_end != to_pack.nr_objects)
777 die(_("ordered %u objects, expected %"PRIu32),
778 wo_end, to_pack.nr_objects);
780 return wo;
783 static off_t write_reused_pack(struct hashfile *f)
785 unsigned char buffer[8192];
786 off_t to_write, total;
787 int fd;
789 if (!is_pack_valid(reuse_packfile))
790 die(_("packfile is invalid: %s"), reuse_packfile->pack_name);
792 fd = git_open(reuse_packfile->pack_name);
793 if (fd < 0)
794 die_errno(_("unable to open packfile for reuse: %s"),
795 reuse_packfile->pack_name);
797 if (lseek(fd, sizeof(struct pack_header), SEEK_SET) == -1)
798 die_errno(_("unable to seek in reused packfile"));
800 if (reuse_packfile_offset < 0)
801 reuse_packfile_offset = reuse_packfile->pack_size - the_hash_algo->rawsz;
803 total = to_write = reuse_packfile_offset - sizeof(struct pack_header);
805 while (to_write) {
806 int read_pack = xread(fd, buffer, sizeof(buffer));
808 if (read_pack <= 0)
809 die_errno(_("unable to read from reused packfile"));
811 if (read_pack > to_write)
812 read_pack = to_write;
814 hashwrite(f, buffer, read_pack);
815 to_write -= read_pack;
818 * We don't know the actual number of objects written,
819 * only how many bytes written, how many bytes total, and
820 * how many objects total. So we can fake it by pretending all
821 * objects we are writing are the same size. This gives us a
822 * smooth progress meter, and at the end it matches the true
823 * answer.
825 written = reuse_packfile_objects *
826 (((double)(total - to_write)) / total);
827 display_progress(progress_state, written);
830 close(fd);
831 written = reuse_packfile_objects;
832 display_progress(progress_state, written);
833 return reuse_packfile_offset - sizeof(struct pack_header);
836 static const char no_split_warning[] = N_(
837 "disabling bitmap writing, packs are split due to pack.packSizeLimit"
840 static void write_pack_file(void)
842 uint32_t i = 0, j;
843 struct hashfile *f;
844 off_t offset;
845 uint32_t nr_remaining = nr_result;
846 time_t last_mtime = 0;
847 struct object_entry **write_order;
849 if (progress > pack_to_stdout)
850 progress_state = start_progress(_("Writing objects"), nr_result);
851 ALLOC_ARRAY(written_list, to_pack.nr_objects);
852 write_order = compute_write_order();
854 do {
855 struct object_id oid;
856 char *pack_tmp_name = NULL;
858 if (pack_to_stdout)
859 f = hashfd_throughput(1, "<stdout>", progress_state);
860 else
861 f = create_tmp_packfile(&pack_tmp_name);
863 offset = write_pack_header(f, nr_remaining);
865 if (reuse_packfile) {
866 off_t packfile_size;
867 assert(pack_to_stdout);
869 packfile_size = write_reused_pack(f);
870 offset += packfile_size;
873 nr_written = 0;
874 for (; i < to_pack.nr_objects; i++) {
875 struct object_entry *e = write_order[i];
876 if (write_one(f, e, &offset) == WRITE_ONE_BREAK)
877 break;
878 display_progress(progress_state, written);
882 * Did we write the wrong # entries in the header?
883 * If so, rewrite it like in fast-import
885 if (pack_to_stdout) {
886 finalize_hashfile(f, oid.hash, CSUM_HASH_IN_STREAM | CSUM_CLOSE);
887 } else if (nr_written == nr_remaining) {
888 finalize_hashfile(f, oid.hash, CSUM_HASH_IN_STREAM | CSUM_FSYNC | CSUM_CLOSE);
889 } else {
890 int fd = finalize_hashfile(f, oid.hash, 0);
891 fixup_pack_header_footer(fd, oid.hash, pack_tmp_name,
892 nr_written, oid.hash, offset);
893 close(fd);
894 if (write_bitmap_index) {
895 warning(_(no_split_warning));
896 write_bitmap_index = 0;
900 if (!pack_to_stdout) {
901 struct stat st;
902 struct strbuf tmpname = STRBUF_INIT;
905 * Packs are runtime accessed in their mtime
906 * order since newer packs are more likely to contain
907 * younger objects. So if we are creating multiple
908 * packs then we should modify the mtime of later ones
909 * to preserve this property.
911 if (stat(pack_tmp_name, &st) < 0) {
912 warning_errno(_("failed to stat %s"), pack_tmp_name);
913 } else if (!last_mtime) {
914 last_mtime = st.st_mtime;
915 } else {
916 struct utimbuf utb;
917 utb.actime = st.st_atime;
918 utb.modtime = --last_mtime;
919 if (utime(pack_tmp_name, &utb) < 0)
920 warning_errno(_("failed utime() on %s"), pack_tmp_name);
923 strbuf_addf(&tmpname, "%s-", base_name);
925 if (write_bitmap_index) {
926 bitmap_writer_set_checksum(oid.hash);
927 bitmap_writer_build_type_index(
928 &to_pack, written_list, nr_written);
931 finish_tmp_packfile(&tmpname, pack_tmp_name,
932 written_list, nr_written,
933 &pack_idx_opts, oid.hash);
935 if (write_bitmap_index) {
936 strbuf_addf(&tmpname, "%s.bitmap", oid_to_hex(&oid));
938 stop_progress(&progress_state);
940 bitmap_writer_show_progress(progress);
941 bitmap_writer_reuse_bitmaps(&to_pack);
942 bitmap_writer_select_commits(indexed_commits, indexed_commits_nr, -1);
943 bitmap_writer_build(&to_pack);
944 bitmap_writer_finish(written_list, nr_written,
945 tmpname.buf, write_bitmap_options);
946 write_bitmap_index = 0;
949 strbuf_release(&tmpname);
950 free(pack_tmp_name);
951 puts(oid_to_hex(&oid));
954 /* mark written objects as written to previous pack */
955 for (j = 0; j < nr_written; j++) {
956 written_list[j]->offset = (off_t)-1;
958 nr_remaining -= nr_written;
959 } while (nr_remaining && i < to_pack.nr_objects);
961 free(written_list);
962 free(write_order);
963 stop_progress(&progress_state);
964 if (written != nr_result)
965 die(_("wrote %"PRIu32" objects while expecting %"PRIu32),
966 written, nr_result);
967 trace2_data_intmax("pack-objects", the_repository,
968 "write_pack_file/wrote", nr_result);
971 static int no_try_delta(const char *path)
973 static struct attr_check *check;
975 if (!check)
976 check = attr_check_initl("delta", NULL);
977 git_check_attr(the_repository->index, path, check);
978 if (ATTR_FALSE(check->items[0].value))
979 return 1;
980 return 0;
984 * When adding an object, check whether we have already added it
985 * to our packing list. If so, we can skip. However, if we are
986 * being asked to excludei t, but the previous mention was to include
987 * it, make sure to adjust its flags and tweak our numbers accordingly.
989 * As an optimization, we pass out the index position where we would have
990 * found the item, since that saves us from having to look it up again a
991 * few lines later when we want to add the new entry.
993 static int have_duplicate_entry(const struct object_id *oid,
994 int exclude,
995 uint32_t *index_pos)
997 struct object_entry *entry;
999 entry = packlist_find(&to_pack, oid, index_pos);
1000 if (!entry)
1001 return 0;
1003 if (exclude) {
1004 if (!entry->preferred_base)
1005 nr_result--;
1006 entry->preferred_base = 1;
1009 return 1;
1012 static int want_found_object(int exclude, struct packed_git *p)
1014 if (exclude)
1015 return 1;
1016 if (incremental)
1017 return 0;
1020 * When asked to do --local (do not include an object that appears in a
1021 * pack we borrow from elsewhere) or --honor-pack-keep (do not include
1022 * an object that appears in a pack marked with .keep), finding a pack
1023 * that matches the criteria is sufficient for us to decide to omit it.
1024 * However, even if this pack does not satisfy the criteria, we need to
1025 * make sure no copy of this object appears in _any_ pack that makes us
1026 * to omit the object, so we need to check all the packs.
1028 * We can however first check whether these options can possible matter;
1029 * if they do not matter we know we want the object in generated pack.
1030 * Otherwise, we signal "-1" at the end to tell the caller that we do
1031 * not know either way, and it needs to check more packs.
1033 if (!ignore_packed_keep_on_disk &&
1034 !ignore_packed_keep_in_core &&
1035 (!local || !have_non_local_packs))
1036 return 1;
1038 if (local && !p->pack_local)
1039 return 0;
1040 if (p->pack_local &&
1041 ((ignore_packed_keep_on_disk && p->pack_keep) ||
1042 (ignore_packed_keep_in_core && p->pack_keep_in_core)))
1043 return 0;
1045 /* we don't know yet; keep looking for more packs */
1046 return -1;
1050 * Check whether we want the object in the pack (e.g., we do not want
1051 * objects found in non-local stores if the "--local" option was used).
1053 * If the caller already knows an existing pack it wants to take the object
1054 * from, that is passed in *found_pack and *found_offset; otherwise this
1055 * function finds if there is any pack that has the object and returns the pack
1056 * and its offset in these variables.
1058 static int want_object_in_pack(const struct object_id *oid,
1059 int exclude,
1060 struct packed_git **found_pack,
1061 off_t *found_offset)
1063 int want;
1064 struct list_head *pos;
1065 struct multi_pack_index *m;
1067 if (!exclude && local && has_loose_object_nonlocal(oid))
1068 return 0;
1071 * If we already know the pack object lives in, start checks from that
1072 * pack - in the usual case when neither --local was given nor .keep files
1073 * are present we will determine the answer right now.
1075 if (*found_pack) {
1076 want = want_found_object(exclude, *found_pack);
1077 if (want != -1)
1078 return want;
1081 for (m = get_multi_pack_index(the_repository); m; m = m->next) {
1082 struct pack_entry e;
1083 if (fill_midx_entry(the_repository, oid, &e, m)) {
1084 struct packed_git *p = e.p;
1085 off_t offset;
1087 if (p == *found_pack)
1088 offset = *found_offset;
1089 else
1090 offset = find_pack_entry_one(oid->hash, p);
1092 if (offset) {
1093 if (!*found_pack) {
1094 if (!is_pack_valid(p))
1095 continue;
1096 *found_offset = offset;
1097 *found_pack = p;
1099 want = want_found_object(exclude, p);
1100 if (want != -1)
1101 return want;
1106 list_for_each(pos, get_packed_git_mru(the_repository)) {
1107 struct packed_git *p = list_entry(pos, struct packed_git, mru);
1108 off_t offset;
1110 if (p == *found_pack)
1111 offset = *found_offset;
1112 else
1113 offset = find_pack_entry_one(oid->hash, p);
1115 if (offset) {
1116 if (!*found_pack) {
1117 if (!is_pack_valid(p))
1118 continue;
1119 *found_offset = offset;
1120 *found_pack = p;
1122 want = want_found_object(exclude, p);
1123 if (!exclude && want > 0)
1124 list_move(&p->mru,
1125 get_packed_git_mru(the_repository));
1126 if (want != -1)
1127 return want;
1131 return 1;
1134 static void create_object_entry(const struct object_id *oid,
1135 enum object_type type,
1136 uint32_t hash,
1137 int exclude,
1138 int no_try_delta,
1139 uint32_t index_pos,
1140 struct packed_git *found_pack,
1141 off_t found_offset)
1143 struct object_entry *entry;
1145 entry = packlist_alloc(&to_pack, oid->hash, index_pos);
1146 entry->hash = hash;
1147 oe_set_type(entry, type);
1148 if (exclude)
1149 entry->preferred_base = 1;
1150 else
1151 nr_result++;
1152 if (found_pack) {
1153 oe_set_in_pack(&to_pack, entry, found_pack);
1154 entry->in_pack_offset = found_offset;
1157 entry->no_try_delta = no_try_delta;
1160 static const char no_closure_warning[] = N_(
1161 "disabling bitmap writing, as some objects are not being packed"
1164 static int add_object_entry(const struct object_id *oid, enum object_type type,
1165 const char *name, int exclude)
1167 struct packed_git *found_pack = NULL;
1168 off_t found_offset = 0;
1169 uint32_t index_pos;
1171 display_progress(progress_state, ++nr_seen);
1173 if (have_duplicate_entry(oid, exclude, &index_pos))
1174 return 0;
1176 if (!want_object_in_pack(oid, exclude, &found_pack, &found_offset)) {
1177 /* The pack is missing an object, so it will not have closure */
1178 if (write_bitmap_index) {
1179 warning(_(no_closure_warning));
1180 write_bitmap_index = 0;
1182 return 0;
1185 create_object_entry(oid, type, pack_name_hash(name),
1186 exclude, name && no_try_delta(name),
1187 index_pos, found_pack, found_offset);
1188 return 1;
1191 static int add_object_entry_from_bitmap(const struct object_id *oid,
1192 enum object_type type,
1193 int flags, uint32_t name_hash,
1194 struct packed_git *pack, off_t offset)
1196 uint32_t index_pos;
1198 display_progress(progress_state, ++nr_seen);
1200 if (have_duplicate_entry(oid, 0, &index_pos))
1201 return 0;
1203 if (!want_object_in_pack(oid, 0, &pack, &offset))
1204 return 0;
1206 create_object_entry(oid, type, name_hash, 0, 0, index_pos, pack, offset);
1207 return 1;
1210 struct pbase_tree_cache {
1211 struct object_id oid;
1212 int ref;
1213 int temporary;
1214 void *tree_data;
1215 unsigned long tree_size;
1218 static struct pbase_tree_cache *(pbase_tree_cache[256]);
1219 static int pbase_tree_cache_ix(const struct object_id *oid)
1221 return oid->hash[0] % ARRAY_SIZE(pbase_tree_cache);
1223 static int pbase_tree_cache_ix_incr(int ix)
1225 return (ix+1) % ARRAY_SIZE(pbase_tree_cache);
1228 static struct pbase_tree {
1229 struct pbase_tree *next;
1230 /* This is a phony "cache" entry; we are not
1231 * going to evict it or find it through _get()
1232 * mechanism -- this is for the toplevel node that
1233 * would almost always change with any commit.
1235 struct pbase_tree_cache pcache;
1236 } *pbase_tree;
1238 static struct pbase_tree_cache *pbase_tree_get(const struct object_id *oid)
1240 struct pbase_tree_cache *ent, *nent;
1241 void *data;
1242 unsigned long size;
1243 enum object_type type;
1244 int neigh;
1245 int my_ix = pbase_tree_cache_ix(oid);
1246 int available_ix = -1;
1248 /* pbase-tree-cache acts as a limited hashtable.
1249 * your object will be found at your index or within a few
1250 * slots after that slot if it is cached.
1252 for (neigh = 0; neigh < 8; neigh++) {
1253 ent = pbase_tree_cache[my_ix];
1254 if (ent && oideq(&ent->oid, oid)) {
1255 ent->ref++;
1256 return ent;
1258 else if (((available_ix < 0) && (!ent || !ent->ref)) ||
1259 ((0 <= available_ix) &&
1260 (!ent && pbase_tree_cache[available_ix])))
1261 available_ix = my_ix;
1262 if (!ent)
1263 break;
1264 my_ix = pbase_tree_cache_ix_incr(my_ix);
1267 /* Did not find one. Either we got a bogus request or
1268 * we need to read and perhaps cache.
1270 data = read_object_file(oid, &type, &size);
1271 if (!data)
1272 return NULL;
1273 if (type != OBJ_TREE) {
1274 free(data);
1275 return NULL;
1278 /* We need to either cache or return a throwaway copy */
1280 if (available_ix < 0)
1281 ent = NULL;
1282 else {
1283 ent = pbase_tree_cache[available_ix];
1284 my_ix = available_ix;
1287 if (!ent) {
1288 nent = xmalloc(sizeof(*nent));
1289 nent->temporary = (available_ix < 0);
1291 else {
1292 /* evict and reuse */
1293 free(ent->tree_data);
1294 nent = ent;
1296 oidcpy(&nent->oid, oid);
1297 nent->tree_data = data;
1298 nent->tree_size = size;
1299 nent->ref = 1;
1300 if (!nent->temporary)
1301 pbase_tree_cache[my_ix] = nent;
1302 return nent;
1305 static void pbase_tree_put(struct pbase_tree_cache *cache)
1307 if (!cache->temporary) {
1308 cache->ref--;
1309 return;
1311 free(cache->tree_data);
1312 free(cache);
1315 static int name_cmp_len(const char *name)
1317 int i;
1318 for (i = 0; name[i] && name[i] != '\n' && name[i] != '/'; i++)
1320 return i;
1323 static void add_pbase_object(struct tree_desc *tree,
1324 const char *name,
1325 int cmplen,
1326 const char *fullname)
1328 struct name_entry entry;
1329 int cmp;
1331 while (tree_entry(tree,&entry)) {
1332 if (S_ISGITLINK(entry.mode))
1333 continue;
1334 cmp = tree_entry_len(&entry) != cmplen ? 1 :
1335 memcmp(name, entry.path, cmplen);
1336 if (cmp > 0)
1337 continue;
1338 if (cmp < 0)
1339 return;
1340 if (name[cmplen] != '/') {
1341 add_object_entry(&entry.oid,
1342 object_type(entry.mode),
1343 fullname, 1);
1344 return;
1346 if (S_ISDIR(entry.mode)) {
1347 struct tree_desc sub;
1348 struct pbase_tree_cache *tree;
1349 const char *down = name+cmplen+1;
1350 int downlen = name_cmp_len(down);
1352 tree = pbase_tree_get(&entry.oid);
1353 if (!tree)
1354 return;
1355 init_tree_desc(&sub, tree->tree_data, tree->tree_size);
1357 add_pbase_object(&sub, down, downlen, fullname);
1358 pbase_tree_put(tree);
1363 static unsigned *done_pbase_paths;
1364 static int done_pbase_paths_num;
1365 static int done_pbase_paths_alloc;
1366 static int done_pbase_path_pos(unsigned hash)
1368 int lo = 0;
1369 int hi = done_pbase_paths_num;
1370 while (lo < hi) {
1371 int mi = lo + (hi - lo) / 2;
1372 if (done_pbase_paths[mi] == hash)
1373 return mi;
1374 if (done_pbase_paths[mi] < hash)
1375 hi = mi;
1376 else
1377 lo = mi + 1;
1379 return -lo-1;
1382 static int check_pbase_path(unsigned hash)
1384 int pos = done_pbase_path_pos(hash);
1385 if (0 <= pos)
1386 return 1;
1387 pos = -pos - 1;
1388 ALLOC_GROW(done_pbase_paths,
1389 done_pbase_paths_num + 1,
1390 done_pbase_paths_alloc);
1391 done_pbase_paths_num++;
1392 if (pos < done_pbase_paths_num)
1393 MOVE_ARRAY(done_pbase_paths + pos + 1, done_pbase_paths + pos,
1394 done_pbase_paths_num - pos - 1);
1395 done_pbase_paths[pos] = hash;
1396 return 0;
1399 static void add_preferred_base_object(const char *name)
1401 struct pbase_tree *it;
1402 int cmplen;
1403 unsigned hash = pack_name_hash(name);
1405 if (!num_preferred_base || check_pbase_path(hash))
1406 return;
1408 cmplen = name_cmp_len(name);
1409 for (it = pbase_tree; it; it = it->next) {
1410 if (cmplen == 0) {
1411 add_object_entry(&it->pcache.oid, OBJ_TREE, NULL, 1);
1413 else {
1414 struct tree_desc tree;
1415 init_tree_desc(&tree, it->pcache.tree_data, it->pcache.tree_size);
1416 add_pbase_object(&tree, name, cmplen, name);
1421 static void add_preferred_base(struct object_id *oid)
1423 struct pbase_tree *it;
1424 void *data;
1425 unsigned long size;
1426 struct object_id tree_oid;
1428 if (window <= num_preferred_base++)
1429 return;
1431 data = read_object_with_reference(oid, tree_type, &size, &tree_oid);
1432 if (!data)
1433 return;
1435 for (it = pbase_tree; it; it = it->next) {
1436 if (oideq(&it->pcache.oid, &tree_oid)) {
1437 free(data);
1438 return;
1442 it = xcalloc(1, sizeof(*it));
1443 it->next = pbase_tree;
1444 pbase_tree = it;
1446 oidcpy(&it->pcache.oid, &tree_oid);
1447 it->pcache.tree_data = data;
1448 it->pcache.tree_size = size;
1451 static void cleanup_preferred_base(void)
1453 struct pbase_tree *it;
1454 unsigned i;
1456 it = pbase_tree;
1457 pbase_tree = NULL;
1458 while (it) {
1459 struct pbase_tree *tmp = it;
1460 it = tmp->next;
1461 free(tmp->pcache.tree_data);
1462 free(tmp);
1465 for (i = 0; i < ARRAY_SIZE(pbase_tree_cache); i++) {
1466 if (!pbase_tree_cache[i])
1467 continue;
1468 free(pbase_tree_cache[i]->tree_data);
1469 FREE_AND_NULL(pbase_tree_cache[i]);
1472 FREE_AND_NULL(done_pbase_paths);
1473 done_pbase_paths_num = done_pbase_paths_alloc = 0;
1477 * Return 1 iff the object specified by "delta" can be sent
1478 * literally as a delta against the base in "base_sha1". If
1479 * so, then *base_out will point to the entry in our packing
1480 * list, or NULL if we must use the external-base list.
1482 * Depth value does not matter - find_deltas() will
1483 * never consider reused delta as the base object to
1484 * deltify other objects against, in order to avoid
1485 * circular deltas.
1487 static int can_reuse_delta(const unsigned char *base_sha1,
1488 struct object_entry *delta,
1489 struct object_entry **base_out)
1491 struct object_entry *base;
1492 struct object_id base_oid;
1494 if (!base_sha1)
1495 return 0;
1497 oidread(&base_oid, base_sha1);
1500 * First see if we're already sending the base (or it's explicitly in
1501 * our "excluded" list).
1503 base = packlist_find(&to_pack, &base_oid, NULL);
1504 if (base) {
1505 if (!in_same_island(&delta->idx.oid, &base->idx.oid))
1506 return 0;
1507 *base_out = base;
1508 return 1;
1512 * Otherwise, reachability bitmaps may tell us if the receiver has it,
1513 * even if it was buried too deep in history to make it into the
1514 * packing list.
1516 if (thin && bitmap_has_oid_in_uninteresting(bitmap_git, &base_oid)) {
1517 if (use_delta_islands) {
1518 if (!in_same_island(&delta->idx.oid, &base_oid))
1519 return 0;
1521 *base_out = NULL;
1522 return 1;
1525 return 0;
1528 static void check_object(struct object_entry *entry)
1530 unsigned long canonical_size;
1532 if (IN_PACK(entry)) {
1533 struct packed_git *p = IN_PACK(entry);
1534 struct pack_window *w_curs = NULL;
1535 const unsigned char *base_ref = NULL;
1536 struct object_entry *base_entry;
1537 unsigned long used, used_0;
1538 unsigned long avail;
1539 off_t ofs;
1540 unsigned char *buf, c;
1541 enum object_type type;
1542 unsigned long in_pack_size;
1544 buf = use_pack(p, &w_curs, entry->in_pack_offset, &avail);
1547 * We want in_pack_type even if we do not reuse delta
1548 * since non-delta representations could still be reused.
1550 used = unpack_object_header_buffer(buf, avail,
1551 &type,
1552 &in_pack_size);
1553 if (used == 0)
1554 goto give_up;
1556 if (type < 0)
1557 BUG("invalid type %d", type);
1558 entry->in_pack_type = type;
1561 * Determine if this is a delta and if so whether we can
1562 * reuse it or not. Otherwise let's find out as cheaply as
1563 * possible what the actual type and size for this object is.
1565 switch (entry->in_pack_type) {
1566 default:
1567 /* Not a delta hence we've already got all we need. */
1568 oe_set_type(entry, entry->in_pack_type);
1569 SET_SIZE(entry, in_pack_size);
1570 entry->in_pack_header_size = used;
1571 if (oe_type(entry) < OBJ_COMMIT || oe_type(entry) > OBJ_BLOB)
1572 goto give_up;
1573 unuse_pack(&w_curs);
1574 return;
1575 case OBJ_REF_DELTA:
1576 if (reuse_delta && !entry->preferred_base)
1577 base_ref = use_pack(p, &w_curs,
1578 entry->in_pack_offset + used, NULL);
1579 entry->in_pack_header_size = used + the_hash_algo->rawsz;
1580 break;
1581 case OBJ_OFS_DELTA:
1582 buf = use_pack(p, &w_curs,
1583 entry->in_pack_offset + used, NULL);
1584 used_0 = 0;
1585 c = buf[used_0++];
1586 ofs = c & 127;
1587 while (c & 128) {
1588 ofs += 1;
1589 if (!ofs || MSB(ofs, 7)) {
1590 error(_("delta base offset overflow in pack for %s"),
1591 oid_to_hex(&entry->idx.oid));
1592 goto give_up;
1594 c = buf[used_0++];
1595 ofs = (ofs << 7) + (c & 127);
1597 ofs = entry->in_pack_offset - ofs;
1598 if (ofs <= 0 || ofs >= entry->in_pack_offset) {
1599 error(_("delta base offset out of bound for %s"),
1600 oid_to_hex(&entry->idx.oid));
1601 goto give_up;
1603 if (reuse_delta && !entry->preferred_base) {
1604 struct revindex_entry *revidx;
1605 revidx = find_pack_revindex(p, ofs);
1606 if (!revidx)
1607 goto give_up;
1608 base_ref = nth_packed_object_sha1(p, revidx->nr);
1610 entry->in_pack_header_size = used + used_0;
1611 break;
1614 if (can_reuse_delta(base_ref, entry, &base_entry)) {
1615 oe_set_type(entry, entry->in_pack_type);
1616 SET_SIZE(entry, in_pack_size); /* delta size */
1617 SET_DELTA_SIZE(entry, in_pack_size);
1619 if (base_entry) {
1620 SET_DELTA(entry, base_entry);
1621 entry->delta_sibling_idx = base_entry->delta_child_idx;
1622 SET_DELTA_CHILD(base_entry, entry);
1623 } else {
1624 SET_DELTA_EXT(entry, base_ref);
1627 unuse_pack(&w_curs);
1628 return;
1631 if (oe_type(entry)) {
1632 off_t delta_pos;
1635 * This must be a delta and we already know what the
1636 * final object type is. Let's extract the actual
1637 * object size from the delta header.
1639 delta_pos = entry->in_pack_offset + entry->in_pack_header_size;
1640 canonical_size = get_size_from_delta(p, &w_curs, delta_pos);
1641 if (canonical_size == 0)
1642 goto give_up;
1643 SET_SIZE(entry, canonical_size);
1644 unuse_pack(&w_curs);
1645 return;
1649 * No choice but to fall back to the recursive delta walk
1650 * with oid_object_info() to find about the object type
1651 * at this point...
1653 give_up:
1654 unuse_pack(&w_curs);
1657 oe_set_type(entry,
1658 oid_object_info(the_repository, &entry->idx.oid, &canonical_size));
1659 if (entry->type_valid) {
1660 SET_SIZE(entry, canonical_size);
1661 } else {
1663 * Bad object type is checked in prepare_pack(). This is
1664 * to permit a missing preferred base object to be ignored
1665 * as a preferred base. Doing so can result in a larger
1666 * pack file, but the transfer will still take place.
1671 static int pack_offset_sort(const void *_a, const void *_b)
1673 const struct object_entry *a = *(struct object_entry **)_a;
1674 const struct object_entry *b = *(struct object_entry **)_b;
1675 const struct packed_git *a_in_pack = IN_PACK(a);
1676 const struct packed_git *b_in_pack = IN_PACK(b);
1678 /* avoid filesystem trashing with loose objects */
1679 if (!a_in_pack && !b_in_pack)
1680 return oidcmp(&a->idx.oid, &b->idx.oid);
1682 if (a_in_pack < b_in_pack)
1683 return -1;
1684 if (a_in_pack > b_in_pack)
1685 return 1;
1686 return a->in_pack_offset < b->in_pack_offset ? -1 :
1687 (a->in_pack_offset > b->in_pack_offset);
1691 * Drop an on-disk delta we were planning to reuse. Naively, this would
1692 * just involve blanking out the "delta" field, but we have to deal
1693 * with some extra book-keeping:
1695 * 1. Removing ourselves from the delta_sibling linked list.
1697 * 2. Updating our size/type to the non-delta representation. These were
1698 * either not recorded initially (size) or overwritten with the delta type
1699 * (type) when check_object() decided to reuse the delta.
1701 * 3. Resetting our delta depth, as we are now a base object.
1703 static void drop_reused_delta(struct object_entry *entry)
1705 unsigned *idx = &to_pack.objects[entry->delta_idx - 1].delta_child_idx;
1706 struct object_info oi = OBJECT_INFO_INIT;
1707 enum object_type type;
1708 unsigned long size;
1710 while (*idx) {
1711 struct object_entry *oe = &to_pack.objects[*idx - 1];
1713 if (oe == entry)
1714 *idx = oe->delta_sibling_idx;
1715 else
1716 idx = &oe->delta_sibling_idx;
1718 SET_DELTA(entry, NULL);
1719 entry->depth = 0;
1721 oi.sizep = &size;
1722 oi.typep = &type;
1723 if (packed_object_info(the_repository, IN_PACK(entry), entry->in_pack_offset, &oi) < 0) {
1725 * We failed to get the info from this pack for some reason;
1726 * fall back to oid_object_info, which may find another copy.
1727 * And if that fails, the error will be recorded in oe_type(entry)
1728 * and dealt with in prepare_pack().
1730 oe_set_type(entry,
1731 oid_object_info(the_repository, &entry->idx.oid, &size));
1732 } else {
1733 oe_set_type(entry, type);
1735 SET_SIZE(entry, size);
1739 * Follow the chain of deltas from this entry onward, throwing away any links
1740 * that cause us to hit a cycle (as determined by the DFS state flags in
1741 * the entries).
1743 * We also detect too-long reused chains that would violate our --depth
1744 * limit.
1746 static void break_delta_chains(struct object_entry *entry)
1749 * The actual depth of each object we will write is stored as an int,
1750 * as it cannot exceed our int "depth" limit. But before we break
1751 * changes based no that limit, we may potentially go as deep as the
1752 * number of objects, which is elsewhere bounded to a uint32_t.
1754 uint32_t total_depth;
1755 struct object_entry *cur, *next;
1757 for (cur = entry, total_depth = 0;
1758 cur;
1759 cur = DELTA(cur), total_depth++) {
1760 if (cur->dfs_state == DFS_DONE) {
1762 * We've already seen this object and know it isn't
1763 * part of a cycle. We do need to append its depth
1764 * to our count.
1766 total_depth += cur->depth;
1767 break;
1771 * We break cycles before looping, so an ACTIVE state (or any
1772 * other cruft which made its way into the state variable)
1773 * is a bug.
1775 if (cur->dfs_state != DFS_NONE)
1776 BUG("confusing delta dfs state in first pass: %d",
1777 cur->dfs_state);
1780 * Now we know this is the first time we've seen the object. If
1781 * it's not a delta, we're done traversing, but we'll mark it
1782 * done to save time on future traversals.
1784 if (!DELTA(cur)) {
1785 cur->dfs_state = DFS_DONE;
1786 break;
1790 * Mark ourselves as active and see if the next step causes
1791 * us to cycle to another active object. It's important to do
1792 * this _before_ we loop, because it impacts where we make the
1793 * cut, and thus how our total_depth counter works.
1794 * E.g., We may see a partial loop like:
1796 * A -> B -> C -> D -> B
1798 * Cutting B->C breaks the cycle. But now the depth of A is
1799 * only 1, and our total_depth counter is at 3. The size of the
1800 * error is always one less than the size of the cycle we
1801 * broke. Commits C and D were "lost" from A's chain.
1803 * If we instead cut D->B, then the depth of A is correct at 3.
1804 * We keep all commits in the chain that we examined.
1806 cur->dfs_state = DFS_ACTIVE;
1807 if (DELTA(cur)->dfs_state == DFS_ACTIVE) {
1808 drop_reused_delta(cur);
1809 cur->dfs_state = DFS_DONE;
1810 break;
1815 * And now that we've gone all the way to the bottom of the chain, we
1816 * need to clear the active flags and set the depth fields as
1817 * appropriate. Unlike the loop above, which can quit when it drops a
1818 * delta, we need to keep going to look for more depth cuts. So we need
1819 * an extra "next" pointer to keep going after we reset cur->delta.
1821 for (cur = entry; cur; cur = next) {
1822 next = DELTA(cur);
1825 * We should have a chain of zero or more ACTIVE states down to
1826 * a final DONE. We can quit after the DONE, because either it
1827 * has no bases, or we've already handled them in a previous
1828 * call.
1830 if (cur->dfs_state == DFS_DONE)
1831 break;
1832 else if (cur->dfs_state != DFS_ACTIVE)
1833 BUG("confusing delta dfs state in second pass: %d",
1834 cur->dfs_state);
1837 * If the total_depth is more than depth, then we need to snip
1838 * the chain into two or more smaller chains that don't exceed
1839 * the maximum depth. Most of the resulting chains will contain
1840 * (depth + 1) entries (i.e., depth deltas plus one base), and
1841 * the last chain (i.e., the one containing entry) will contain
1842 * whatever entries are left over, namely
1843 * (total_depth % (depth + 1)) of them.
1845 * Since we are iterating towards decreasing depth, we need to
1846 * decrement total_depth as we go, and we need to write to the
1847 * entry what its final depth will be after all of the
1848 * snipping. Since we're snipping into chains of length (depth
1849 * + 1) entries, the final depth of an entry will be its
1850 * original depth modulo (depth + 1). Any time we encounter an
1851 * entry whose final depth is supposed to be zero, we snip it
1852 * from its delta base, thereby making it so.
1854 cur->depth = (total_depth--) % (depth + 1);
1855 if (!cur->depth)
1856 drop_reused_delta(cur);
1858 cur->dfs_state = DFS_DONE;
1862 static void get_object_details(void)
1864 uint32_t i;
1865 struct object_entry **sorted_by_offset;
1867 if (progress)
1868 progress_state = start_progress(_("Counting objects"),
1869 to_pack.nr_objects);
1871 sorted_by_offset = xcalloc(to_pack.nr_objects, sizeof(struct object_entry *));
1872 for (i = 0; i < to_pack.nr_objects; i++)
1873 sorted_by_offset[i] = to_pack.objects + i;
1874 QSORT(sorted_by_offset, to_pack.nr_objects, pack_offset_sort);
1876 for (i = 0; i < to_pack.nr_objects; i++) {
1877 struct object_entry *entry = sorted_by_offset[i];
1878 check_object(entry);
1879 if (entry->type_valid &&
1880 oe_size_greater_than(&to_pack, entry, big_file_threshold))
1881 entry->no_try_delta = 1;
1882 display_progress(progress_state, i + 1);
1884 stop_progress(&progress_state);
1887 * This must happen in a second pass, since we rely on the delta
1888 * information for the whole list being completed.
1890 for (i = 0; i < to_pack.nr_objects; i++)
1891 break_delta_chains(&to_pack.objects[i]);
1893 free(sorted_by_offset);
1897 * We search for deltas in a list sorted by type, by filename hash, and then
1898 * by size, so that we see progressively smaller and smaller files.
1899 * That's because we prefer deltas to be from the bigger file
1900 * to the smaller -- deletes are potentially cheaper, but perhaps
1901 * more importantly, the bigger file is likely the more recent
1902 * one. The deepest deltas are therefore the oldest objects which are
1903 * less susceptible to be accessed often.
1905 static int type_size_sort(const void *_a, const void *_b)
1907 const struct object_entry *a = *(struct object_entry **)_a;
1908 const struct object_entry *b = *(struct object_entry **)_b;
1909 const enum object_type a_type = oe_type(a);
1910 const enum object_type b_type = oe_type(b);
1911 const unsigned long a_size = SIZE(a);
1912 const unsigned long b_size = SIZE(b);
1914 if (a_type > b_type)
1915 return -1;
1916 if (a_type < b_type)
1917 return 1;
1918 if (a->hash > b->hash)
1919 return -1;
1920 if (a->hash < b->hash)
1921 return 1;
1922 if (a->preferred_base > b->preferred_base)
1923 return -1;
1924 if (a->preferred_base < b->preferred_base)
1925 return 1;
1926 if (use_delta_islands) {
1927 const int island_cmp = island_delta_cmp(&a->idx.oid, &b->idx.oid);
1928 if (island_cmp)
1929 return island_cmp;
1931 if (a_size > b_size)
1932 return -1;
1933 if (a_size < b_size)
1934 return 1;
1935 return a < b ? -1 : (a > b); /* newest first */
1938 struct unpacked {
1939 struct object_entry *entry;
1940 void *data;
1941 struct delta_index *index;
1942 unsigned depth;
1945 static int delta_cacheable(unsigned long src_size, unsigned long trg_size,
1946 unsigned long delta_size)
1948 if (max_delta_cache_size && delta_cache_size + delta_size > max_delta_cache_size)
1949 return 0;
1951 if (delta_size < cache_max_small_delta_size)
1952 return 1;
1954 /* cache delta, if objects are large enough compared to delta size */
1955 if ((src_size >> 20) + (trg_size >> 21) > (delta_size >> 10))
1956 return 1;
1958 return 0;
1961 /* Protect delta_cache_size */
1962 static pthread_mutex_t cache_mutex;
1963 #define cache_lock() pthread_mutex_lock(&cache_mutex)
1964 #define cache_unlock() pthread_mutex_unlock(&cache_mutex)
1967 * Protect object list partitioning (e.g. struct thread_param) and
1968 * progress_state
1970 static pthread_mutex_t progress_mutex;
1971 #define progress_lock() pthread_mutex_lock(&progress_mutex)
1972 #define progress_unlock() pthread_mutex_unlock(&progress_mutex)
1975 * Access to struct object_entry is unprotected since each thread owns
1976 * a portion of the main object list. Just don't access object entries
1977 * ahead in the list because they can be stolen and would need
1978 * progress_mutex for protection.
1982 * Return the size of the object without doing any delta
1983 * reconstruction (so non-deltas are true object sizes, but deltas
1984 * return the size of the delta data).
1986 unsigned long oe_get_size_slow(struct packing_data *pack,
1987 const struct object_entry *e)
1989 struct packed_git *p;
1990 struct pack_window *w_curs;
1991 unsigned char *buf;
1992 enum object_type type;
1993 unsigned long used, avail, size;
1995 if (e->type_ != OBJ_OFS_DELTA && e->type_ != OBJ_REF_DELTA) {
1996 packing_data_lock(&to_pack);
1997 if (oid_object_info(the_repository, &e->idx.oid, &size) < 0)
1998 die(_("unable to get size of %s"),
1999 oid_to_hex(&e->idx.oid));
2000 packing_data_unlock(&to_pack);
2001 return size;
2004 p = oe_in_pack(pack, e);
2005 if (!p)
2006 BUG("when e->type is a delta, it must belong to a pack");
2008 packing_data_lock(&to_pack);
2009 w_curs = NULL;
2010 buf = use_pack(p, &w_curs, e->in_pack_offset, &avail);
2011 used = unpack_object_header_buffer(buf, avail, &type, &size);
2012 if (used == 0)
2013 die(_("unable to parse object header of %s"),
2014 oid_to_hex(&e->idx.oid));
2016 unuse_pack(&w_curs);
2017 packing_data_unlock(&to_pack);
2018 return size;
2021 static int try_delta(struct unpacked *trg, struct unpacked *src,
2022 unsigned max_depth, unsigned long *mem_usage)
2024 struct object_entry *trg_entry = trg->entry;
2025 struct object_entry *src_entry = src->entry;
2026 unsigned long trg_size, src_size, delta_size, sizediff, max_size, sz;
2027 unsigned ref_depth;
2028 enum object_type type;
2029 void *delta_buf;
2031 /* Don't bother doing diffs between different types */
2032 if (oe_type(trg_entry) != oe_type(src_entry))
2033 return -1;
2036 * We do not bother to try a delta that we discarded on an
2037 * earlier try, but only when reusing delta data. Note that
2038 * src_entry that is marked as the preferred_base should always
2039 * be considered, as even if we produce a suboptimal delta against
2040 * it, we will still save the transfer cost, as we already know
2041 * the other side has it and we won't send src_entry at all.
2043 if (reuse_delta && IN_PACK(trg_entry) &&
2044 IN_PACK(trg_entry) == IN_PACK(src_entry) &&
2045 !src_entry->preferred_base &&
2046 trg_entry->in_pack_type != OBJ_REF_DELTA &&
2047 trg_entry->in_pack_type != OBJ_OFS_DELTA)
2048 return 0;
2050 /* Let's not bust the allowed depth. */
2051 if (src->depth >= max_depth)
2052 return 0;
2054 /* Now some size filtering heuristics. */
2055 trg_size = SIZE(trg_entry);
2056 if (!DELTA(trg_entry)) {
2057 max_size = trg_size/2 - the_hash_algo->rawsz;
2058 ref_depth = 1;
2059 } else {
2060 max_size = DELTA_SIZE(trg_entry);
2061 ref_depth = trg->depth;
2063 max_size = (uint64_t)max_size * (max_depth - src->depth) /
2064 (max_depth - ref_depth + 1);
2065 if (max_size == 0)
2066 return 0;
2067 src_size = SIZE(src_entry);
2068 sizediff = src_size < trg_size ? trg_size - src_size : 0;
2069 if (sizediff >= max_size)
2070 return 0;
2071 if (trg_size < src_size / 32)
2072 return 0;
2074 if (!in_same_island(&trg->entry->idx.oid, &src->entry->idx.oid))
2075 return 0;
2077 /* Load data if not already done */
2078 if (!trg->data) {
2079 packing_data_lock(&to_pack);
2080 trg->data = read_object_file(&trg_entry->idx.oid, &type, &sz);
2081 packing_data_unlock(&to_pack);
2082 if (!trg->data)
2083 die(_("object %s cannot be read"),
2084 oid_to_hex(&trg_entry->idx.oid));
2085 if (sz != trg_size)
2086 die(_("object %s inconsistent object length (%"PRIuMAX" vs %"PRIuMAX")"),
2087 oid_to_hex(&trg_entry->idx.oid), (uintmax_t)sz,
2088 (uintmax_t)trg_size);
2089 *mem_usage += sz;
2091 if (!src->data) {
2092 packing_data_lock(&to_pack);
2093 src->data = read_object_file(&src_entry->idx.oid, &type, &sz);
2094 packing_data_unlock(&to_pack);
2095 if (!src->data) {
2096 if (src_entry->preferred_base) {
2097 static int warned = 0;
2098 if (!warned++)
2099 warning(_("object %s cannot be read"),
2100 oid_to_hex(&src_entry->idx.oid));
2102 * Those objects are not included in the
2103 * resulting pack. Be resilient and ignore
2104 * them if they can't be read, in case the
2105 * pack could be created nevertheless.
2107 return 0;
2109 die(_("object %s cannot be read"),
2110 oid_to_hex(&src_entry->idx.oid));
2112 if (sz != src_size)
2113 die(_("object %s inconsistent object length (%"PRIuMAX" vs %"PRIuMAX")"),
2114 oid_to_hex(&src_entry->idx.oid), (uintmax_t)sz,
2115 (uintmax_t)src_size);
2116 *mem_usage += sz;
2118 if (!src->index) {
2119 src->index = create_delta_index(src->data, src_size);
2120 if (!src->index) {
2121 static int warned = 0;
2122 if (!warned++)
2123 warning(_("suboptimal pack - out of memory"));
2124 return 0;
2126 *mem_usage += sizeof_delta_index(src->index);
2129 delta_buf = create_delta(src->index, trg->data, trg_size, &delta_size, max_size);
2130 if (!delta_buf)
2131 return 0;
2133 if (DELTA(trg_entry)) {
2134 /* Prefer only shallower same-sized deltas. */
2135 if (delta_size == DELTA_SIZE(trg_entry) &&
2136 src->depth + 1 >= trg->depth) {
2137 free(delta_buf);
2138 return 0;
2143 * Handle memory allocation outside of the cache
2144 * accounting lock. Compiler will optimize the strangeness
2145 * away when NO_PTHREADS is defined.
2147 free(trg_entry->delta_data);
2148 cache_lock();
2149 if (trg_entry->delta_data) {
2150 delta_cache_size -= DELTA_SIZE(trg_entry);
2151 trg_entry->delta_data = NULL;
2153 if (delta_cacheable(src_size, trg_size, delta_size)) {
2154 delta_cache_size += delta_size;
2155 cache_unlock();
2156 trg_entry->delta_data = xrealloc(delta_buf, delta_size);
2157 } else {
2158 cache_unlock();
2159 free(delta_buf);
2162 SET_DELTA(trg_entry, src_entry);
2163 SET_DELTA_SIZE(trg_entry, delta_size);
2164 trg->depth = src->depth + 1;
2166 return 1;
2169 static unsigned int check_delta_limit(struct object_entry *me, unsigned int n)
2171 struct object_entry *child = DELTA_CHILD(me);
2172 unsigned int m = n;
2173 while (child) {
2174 const unsigned int c = check_delta_limit(child, n + 1);
2175 if (m < c)
2176 m = c;
2177 child = DELTA_SIBLING(child);
2179 return m;
2182 static unsigned long free_unpacked(struct unpacked *n)
2184 unsigned long freed_mem = sizeof_delta_index(n->index);
2185 free_delta_index(n->index);
2186 n->index = NULL;
2187 if (n->data) {
2188 freed_mem += SIZE(n->entry);
2189 FREE_AND_NULL(n->data);
2191 n->entry = NULL;
2192 n->depth = 0;
2193 return freed_mem;
2196 static void find_deltas(struct object_entry **list, unsigned *list_size,
2197 int window, int depth, unsigned *processed)
2199 uint32_t i, idx = 0, count = 0;
2200 struct unpacked *array;
2201 unsigned long mem_usage = 0;
2203 array = xcalloc(window, sizeof(struct unpacked));
2205 for (;;) {
2206 struct object_entry *entry;
2207 struct unpacked *n = array + idx;
2208 int j, max_depth, best_base = -1;
2210 progress_lock();
2211 if (!*list_size) {
2212 progress_unlock();
2213 break;
2215 entry = *list++;
2216 (*list_size)--;
2217 if (!entry->preferred_base) {
2218 (*processed)++;
2219 display_progress(progress_state, *processed);
2221 progress_unlock();
2223 mem_usage -= free_unpacked(n);
2224 n->entry = entry;
2226 while (window_memory_limit &&
2227 mem_usage > window_memory_limit &&
2228 count > 1) {
2229 const uint32_t tail = (idx + window - count) % window;
2230 mem_usage -= free_unpacked(array + tail);
2231 count--;
2234 /* We do not compute delta to *create* objects we are not
2235 * going to pack.
2237 if (entry->preferred_base)
2238 goto next;
2241 * If the current object is at pack edge, take the depth the
2242 * objects that depend on the current object into account
2243 * otherwise they would become too deep.
2245 max_depth = depth;
2246 if (DELTA_CHILD(entry)) {
2247 max_depth -= check_delta_limit(entry, 0);
2248 if (max_depth <= 0)
2249 goto next;
2252 j = window;
2253 while (--j > 0) {
2254 int ret;
2255 uint32_t other_idx = idx + j;
2256 struct unpacked *m;
2257 if (other_idx >= window)
2258 other_idx -= window;
2259 m = array + other_idx;
2260 if (!m->entry)
2261 break;
2262 ret = try_delta(n, m, max_depth, &mem_usage);
2263 if (ret < 0)
2264 break;
2265 else if (ret > 0)
2266 best_base = other_idx;
2270 * If we decided to cache the delta data, then it is best
2271 * to compress it right away. First because we have to do
2272 * it anyway, and doing it here while we're threaded will
2273 * save a lot of time in the non threaded write phase,
2274 * as well as allow for caching more deltas within
2275 * the same cache size limit.
2276 * ...
2277 * But only if not writing to stdout, since in that case
2278 * the network is most likely throttling writes anyway,
2279 * and therefore it is best to go to the write phase ASAP
2280 * instead, as we can afford spending more time compressing
2281 * between writes at that moment.
2283 if (entry->delta_data && !pack_to_stdout) {
2284 unsigned long size;
2286 size = do_compress(&entry->delta_data, DELTA_SIZE(entry));
2287 if (size < (1U << OE_Z_DELTA_BITS)) {
2288 entry->z_delta_size = size;
2289 cache_lock();
2290 delta_cache_size -= DELTA_SIZE(entry);
2291 delta_cache_size += entry->z_delta_size;
2292 cache_unlock();
2293 } else {
2294 FREE_AND_NULL(entry->delta_data);
2295 entry->z_delta_size = 0;
2299 /* if we made n a delta, and if n is already at max
2300 * depth, leaving it in the window is pointless. we
2301 * should evict it first.
2303 if (DELTA(entry) && max_depth <= n->depth)
2304 continue;
2307 * Move the best delta base up in the window, after the
2308 * currently deltified object, to keep it longer. It will
2309 * be the first base object to be attempted next.
2311 if (DELTA(entry)) {
2312 struct unpacked swap = array[best_base];
2313 int dist = (window + idx - best_base) % window;
2314 int dst = best_base;
2315 while (dist--) {
2316 int src = (dst + 1) % window;
2317 array[dst] = array[src];
2318 dst = src;
2320 array[dst] = swap;
2323 next:
2324 idx++;
2325 if (count + 1 < window)
2326 count++;
2327 if (idx >= window)
2328 idx = 0;
2331 for (i = 0; i < window; ++i) {
2332 free_delta_index(array[i].index);
2333 free(array[i].data);
2335 free(array);
2338 static void try_to_free_from_threads(size_t size)
2340 packing_data_lock(&to_pack);
2341 release_pack_memory(size);
2342 packing_data_unlock(&to_pack);
2345 static try_to_free_t old_try_to_free_routine;
2348 * The main object list is split into smaller lists, each is handed to
2349 * one worker.
2351 * The main thread waits on the condition that (at least) one of the workers
2352 * has stopped working (which is indicated in the .working member of
2353 * struct thread_params).
2355 * When a work thread has completed its work, it sets .working to 0 and
2356 * signals the main thread and waits on the condition that .data_ready
2357 * becomes 1.
2359 * The main thread steals half of the work from the worker that has
2360 * most work left to hand it to the idle worker.
2363 struct thread_params {
2364 pthread_t thread;
2365 struct object_entry **list;
2366 unsigned list_size;
2367 unsigned remaining;
2368 int window;
2369 int depth;
2370 int working;
2371 int data_ready;
2372 pthread_mutex_t mutex;
2373 pthread_cond_t cond;
2374 unsigned *processed;
2377 static pthread_cond_t progress_cond;
2380 * Mutex and conditional variable can't be statically-initialized on Windows.
2382 static void init_threaded_search(void)
2384 pthread_mutex_init(&cache_mutex, NULL);
2385 pthread_mutex_init(&progress_mutex, NULL);
2386 pthread_cond_init(&progress_cond, NULL);
2387 old_try_to_free_routine = set_try_to_free_routine(try_to_free_from_threads);
2390 static void cleanup_threaded_search(void)
2392 set_try_to_free_routine(old_try_to_free_routine);
2393 pthread_cond_destroy(&progress_cond);
2394 pthread_mutex_destroy(&cache_mutex);
2395 pthread_mutex_destroy(&progress_mutex);
2398 static void *threaded_find_deltas(void *arg)
2400 struct thread_params *me = arg;
2402 progress_lock();
2403 while (me->remaining) {
2404 progress_unlock();
2406 find_deltas(me->list, &me->remaining,
2407 me->window, me->depth, me->processed);
2409 progress_lock();
2410 me->working = 0;
2411 pthread_cond_signal(&progress_cond);
2412 progress_unlock();
2415 * We must not set ->data_ready before we wait on the
2416 * condition because the main thread may have set it to 1
2417 * before we get here. In order to be sure that new
2418 * work is available if we see 1 in ->data_ready, it
2419 * was initialized to 0 before this thread was spawned
2420 * and we reset it to 0 right away.
2422 pthread_mutex_lock(&me->mutex);
2423 while (!me->data_ready)
2424 pthread_cond_wait(&me->cond, &me->mutex);
2425 me->data_ready = 0;
2426 pthread_mutex_unlock(&me->mutex);
2428 progress_lock();
2430 progress_unlock();
2431 /* leave ->working 1 so that this doesn't get more work assigned */
2432 return NULL;
2435 static void ll_find_deltas(struct object_entry **list, unsigned list_size,
2436 int window, int depth, unsigned *processed)
2438 struct thread_params *p;
2439 int i, ret, active_threads = 0;
2441 init_threaded_search();
2443 if (delta_search_threads <= 1) {
2444 find_deltas(list, &list_size, window, depth, processed);
2445 cleanup_threaded_search();
2446 return;
2448 if (progress > pack_to_stdout)
2449 fprintf_ln(stderr, _("Delta compression using up to %d threads"),
2450 delta_search_threads);
2451 p = xcalloc(delta_search_threads, sizeof(*p));
2453 /* Partition the work amongst work threads. */
2454 for (i = 0; i < delta_search_threads; i++) {
2455 unsigned sub_size = list_size / (delta_search_threads - i);
2457 /* don't use too small segments or no deltas will be found */
2458 if (sub_size < 2*window && i+1 < delta_search_threads)
2459 sub_size = 0;
2461 p[i].window = window;
2462 p[i].depth = depth;
2463 p[i].processed = processed;
2464 p[i].working = 1;
2465 p[i].data_ready = 0;
2467 /* try to split chunks on "path" boundaries */
2468 while (sub_size && sub_size < list_size &&
2469 list[sub_size]->hash &&
2470 list[sub_size]->hash == list[sub_size-1]->hash)
2471 sub_size++;
2473 p[i].list = list;
2474 p[i].list_size = sub_size;
2475 p[i].remaining = sub_size;
2477 list += sub_size;
2478 list_size -= sub_size;
2481 /* Start work threads. */
2482 for (i = 0; i < delta_search_threads; i++) {
2483 if (!p[i].list_size)
2484 continue;
2485 pthread_mutex_init(&p[i].mutex, NULL);
2486 pthread_cond_init(&p[i].cond, NULL);
2487 ret = pthread_create(&p[i].thread, NULL,
2488 threaded_find_deltas, &p[i]);
2489 if (ret)
2490 die(_("unable to create thread: %s"), strerror(ret));
2491 active_threads++;
2495 * Now let's wait for work completion. Each time a thread is done
2496 * with its work, we steal half of the remaining work from the
2497 * thread with the largest number of unprocessed objects and give
2498 * it to that newly idle thread. This ensure good load balancing
2499 * until the remaining object list segments are simply too short
2500 * to be worth splitting anymore.
2502 while (active_threads) {
2503 struct thread_params *target = NULL;
2504 struct thread_params *victim = NULL;
2505 unsigned sub_size = 0;
2507 progress_lock();
2508 for (;;) {
2509 for (i = 0; !target && i < delta_search_threads; i++)
2510 if (!p[i].working)
2511 target = &p[i];
2512 if (target)
2513 break;
2514 pthread_cond_wait(&progress_cond, &progress_mutex);
2517 for (i = 0; i < delta_search_threads; i++)
2518 if (p[i].remaining > 2*window &&
2519 (!victim || victim->remaining < p[i].remaining))
2520 victim = &p[i];
2521 if (victim) {
2522 sub_size = victim->remaining / 2;
2523 list = victim->list + victim->list_size - sub_size;
2524 while (sub_size && list[0]->hash &&
2525 list[0]->hash == list[-1]->hash) {
2526 list++;
2527 sub_size--;
2529 if (!sub_size) {
2531 * It is possible for some "paths" to have
2532 * so many objects that no hash boundary
2533 * might be found. Let's just steal the
2534 * exact half in that case.
2536 sub_size = victim->remaining / 2;
2537 list -= sub_size;
2539 target->list = list;
2540 victim->list_size -= sub_size;
2541 victim->remaining -= sub_size;
2543 target->list_size = sub_size;
2544 target->remaining = sub_size;
2545 target->working = 1;
2546 progress_unlock();
2548 pthread_mutex_lock(&target->mutex);
2549 target->data_ready = 1;
2550 pthread_cond_signal(&target->cond);
2551 pthread_mutex_unlock(&target->mutex);
2553 if (!sub_size) {
2554 pthread_join(target->thread, NULL);
2555 pthread_cond_destroy(&target->cond);
2556 pthread_mutex_destroy(&target->mutex);
2557 active_threads--;
2560 cleanup_threaded_search();
2561 free(p);
2564 static void add_tag_chain(const struct object_id *oid)
2566 struct tag *tag;
2569 * We catch duplicates already in add_object_entry(), but we'd
2570 * prefer to do this extra check to avoid having to parse the
2571 * tag at all if we already know that it's being packed (e.g., if
2572 * it was included via bitmaps, we would not have parsed it
2573 * previously).
2575 if (packlist_find(&to_pack, oid, NULL))
2576 return;
2578 tag = lookup_tag(the_repository, oid);
2579 while (1) {
2580 if (!tag || parse_tag(tag) || !tag->tagged)
2581 die(_("unable to pack objects reachable from tag %s"),
2582 oid_to_hex(oid));
2584 add_object_entry(&tag->object.oid, OBJ_TAG, NULL, 0);
2586 if (tag->tagged->type != OBJ_TAG)
2587 return;
2589 tag = (struct tag *)tag->tagged;
2593 static int add_ref_tag(const char *path, const struct object_id *oid, int flag, void *cb_data)
2595 struct object_id peeled;
2597 if (starts_with(path, "refs/tags/") && /* is a tag? */
2598 !peel_ref(path, &peeled) && /* peelable? */
2599 packlist_find(&to_pack, &peeled, NULL)) /* object packed? */
2600 add_tag_chain(oid);
2601 return 0;
2604 static void prepare_pack(int window, int depth)
2606 struct object_entry **delta_list;
2607 uint32_t i, nr_deltas;
2608 unsigned n;
2610 if (use_delta_islands)
2611 resolve_tree_islands(the_repository, progress, &to_pack);
2613 get_object_details();
2616 * If we're locally repacking then we need to be doubly careful
2617 * from now on in order to make sure no stealth corruption gets
2618 * propagated to the new pack. Clients receiving streamed packs
2619 * should validate everything they get anyway so no need to incur
2620 * the additional cost here in that case.
2622 if (!pack_to_stdout)
2623 do_check_packed_object_crc = 1;
2625 if (!to_pack.nr_objects || !window || !depth)
2626 return;
2628 ALLOC_ARRAY(delta_list, to_pack.nr_objects);
2629 nr_deltas = n = 0;
2631 for (i = 0; i < to_pack.nr_objects; i++) {
2632 struct object_entry *entry = to_pack.objects + i;
2634 if (DELTA(entry))
2635 /* This happens if we decided to reuse existing
2636 * delta from a pack. "reuse_delta &&" is implied.
2638 continue;
2640 if (!entry->type_valid ||
2641 oe_size_less_than(&to_pack, entry, 50))
2642 continue;
2644 if (entry->no_try_delta)
2645 continue;
2647 if (!entry->preferred_base) {
2648 nr_deltas++;
2649 if (oe_type(entry) < 0)
2650 die(_("unable to get type of object %s"),
2651 oid_to_hex(&entry->idx.oid));
2652 } else {
2653 if (oe_type(entry) < 0) {
2655 * This object is not found, but we
2656 * don't have to include it anyway.
2658 continue;
2662 delta_list[n++] = entry;
2665 if (nr_deltas && n > 1) {
2666 unsigned nr_done = 0;
2667 if (progress)
2668 progress_state = start_progress(_("Compressing objects"),
2669 nr_deltas);
2670 QSORT(delta_list, n, type_size_sort);
2671 ll_find_deltas(delta_list, n, window+1, depth, &nr_done);
2672 stop_progress(&progress_state);
2673 if (nr_done != nr_deltas)
2674 die(_("inconsistency with delta count"));
2676 free(delta_list);
2679 static int git_pack_config(const char *k, const char *v, void *cb)
2681 if (!strcmp(k, "pack.window")) {
2682 window = git_config_int(k, v);
2683 return 0;
2685 if (!strcmp(k, "pack.windowmemory")) {
2686 window_memory_limit = git_config_ulong(k, v);
2687 return 0;
2689 if (!strcmp(k, "pack.depth")) {
2690 depth = git_config_int(k, v);
2691 return 0;
2693 if (!strcmp(k, "pack.deltacachesize")) {
2694 max_delta_cache_size = git_config_int(k, v);
2695 return 0;
2697 if (!strcmp(k, "pack.deltacachelimit")) {
2698 cache_max_small_delta_size = git_config_int(k, v);
2699 return 0;
2701 if (!strcmp(k, "pack.writebitmaphashcache")) {
2702 if (git_config_bool(k, v))
2703 write_bitmap_options |= BITMAP_OPT_HASH_CACHE;
2704 else
2705 write_bitmap_options &= ~BITMAP_OPT_HASH_CACHE;
2707 if (!strcmp(k, "pack.usebitmaps")) {
2708 use_bitmap_index_default = git_config_bool(k, v);
2709 return 0;
2711 if (!strcmp(k, "pack.usesparse")) {
2712 sparse = git_config_bool(k, v);
2713 return 0;
2715 if (!strcmp(k, "pack.threads")) {
2716 delta_search_threads = git_config_int(k, v);
2717 if (delta_search_threads < 0)
2718 die(_("invalid number of threads specified (%d)"),
2719 delta_search_threads);
2720 if (!HAVE_THREADS && delta_search_threads != 1) {
2721 warning(_("no threads support, ignoring %s"), k);
2722 delta_search_threads = 0;
2724 return 0;
2726 if (!strcmp(k, "pack.indexversion")) {
2727 pack_idx_opts.version = git_config_int(k, v);
2728 if (pack_idx_opts.version > 2)
2729 die(_("bad pack.indexversion=%"PRIu32),
2730 pack_idx_opts.version);
2731 return 0;
2733 return git_default_config(k, v, cb);
2736 static void read_object_list_from_stdin(void)
2738 char line[GIT_MAX_HEXSZ + 1 + PATH_MAX + 2];
2739 struct object_id oid;
2740 const char *p;
2742 for (;;) {
2743 if (!fgets(line, sizeof(line), stdin)) {
2744 if (feof(stdin))
2745 break;
2746 if (!ferror(stdin))
2747 die("BUG: fgets returned NULL, not EOF, not error!");
2748 if (errno != EINTR)
2749 die_errno("fgets");
2750 clearerr(stdin);
2751 continue;
2753 if (line[0] == '-') {
2754 if (get_oid_hex(line+1, &oid))
2755 die(_("expected edge object ID, got garbage:\n %s"),
2756 line);
2757 add_preferred_base(&oid);
2758 continue;
2760 if (parse_oid_hex(line, &oid, &p))
2761 die(_("expected object ID, got garbage:\n %s"), line);
2763 add_preferred_base_object(p + 1);
2764 add_object_entry(&oid, OBJ_NONE, p + 1, 0);
2768 /* Remember to update object flag allocation in object.h */
2769 #define OBJECT_ADDED (1u<<20)
2771 static void show_commit(struct commit *commit, void *data)
2773 add_object_entry(&commit->object.oid, OBJ_COMMIT, NULL, 0);
2774 commit->object.flags |= OBJECT_ADDED;
2776 if (write_bitmap_index)
2777 index_commit_for_bitmap(commit);
2779 if (use_delta_islands)
2780 propagate_island_marks(commit);
2783 static void show_object(struct object *obj, const char *name, void *data)
2785 add_preferred_base_object(name);
2786 add_object_entry(&obj->oid, obj->type, name, 0);
2787 obj->flags |= OBJECT_ADDED;
2789 if (use_delta_islands) {
2790 const char *p;
2791 unsigned depth;
2792 struct object_entry *ent;
2794 /* the empty string is a root tree, which is depth 0 */
2795 depth = *name ? 1 : 0;
2796 for (p = strchr(name, '/'); p; p = strchr(p + 1, '/'))
2797 depth++;
2799 ent = packlist_find(&to_pack, &obj->oid, NULL);
2800 if (ent && depth > oe_tree_depth(&to_pack, ent))
2801 oe_set_tree_depth(&to_pack, ent, depth);
2805 static void show_object__ma_allow_any(struct object *obj, const char *name, void *data)
2807 assert(arg_missing_action == MA_ALLOW_ANY);
2810 * Quietly ignore ALL missing objects. This avoids problems with
2811 * staging them now and getting an odd error later.
2813 if (!has_object_file(&obj->oid))
2814 return;
2816 show_object(obj, name, data);
2819 static void show_object__ma_allow_promisor(struct object *obj, const char *name, void *data)
2821 assert(arg_missing_action == MA_ALLOW_PROMISOR);
2824 * Quietly ignore EXPECTED missing objects. This avoids problems with
2825 * staging them now and getting an odd error later.
2827 if (!has_object_file(&obj->oid) && is_promisor_object(&obj->oid))
2828 return;
2830 show_object(obj, name, data);
2833 static int option_parse_missing_action(const struct option *opt,
2834 const char *arg, int unset)
2836 assert(arg);
2837 assert(!unset);
2839 if (!strcmp(arg, "error")) {
2840 arg_missing_action = MA_ERROR;
2841 fn_show_object = show_object;
2842 return 0;
2845 if (!strcmp(arg, "allow-any")) {
2846 arg_missing_action = MA_ALLOW_ANY;
2847 fetch_if_missing = 0;
2848 fn_show_object = show_object__ma_allow_any;
2849 return 0;
2852 if (!strcmp(arg, "allow-promisor")) {
2853 arg_missing_action = MA_ALLOW_PROMISOR;
2854 fetch_if_missing = 0;
2855 fn_show_object = show_object__ma_allow_promisor;
2856 return 0;
2859 die(_("invalid value for --missing"));
2860 return 0;
2863 static void show_edge(struct commit *commit)
2865 add_preferred_base(&commit->object.oid);
2868 struct in_pack_object {
2869 off_t offset;
2870 struct object *object;
2873 struct in_pack {
2874 unsigned int alloc;
2875 unsigned int nr;
2876 struct in_pack_object *array;
2879 static void mark_in_pack_object(struct object *object, struct packed_git *p, struct in_pack *in_pack)
2881 in_pack->array[in_pack->nr].offset = find_pack_entry_one(object->oid.hash, p);
2882 in_pack->array[in_pack->nr].object = object;
2883 in_pack->nr++;
2887 * Compare the objects in the offset order, in order to emulate the
2888 * "git rev-list --objects" output that produced the pack originally.
2890 static int ofscmp(const void *a_, const void *b_)
2892 struct in_pack_object *a = (struct in_pack_object *)a_;
2893 struct in_pack_object *b = (struct in_pack_object *)b_;
2895 if (a->offset < b->offset)
2896 return -1;
2897 else if (a->offset > b->offset)
2898 return 1;
2899 else
2900 return oidcmp(&a->object->oid, &b->object->oid);
2903 static void add_objects_in_unpacked_packs(void)
2905 struct packed_git *p;
2906 struct in_pack in_pack;
2907 uint32_t i;
2909 memset(&in_pack, 0, sizeof(in_pack));
2911 for (p = get_all_packs(the_repository); p; p = p->next) {
2912 struct object_id oid;
2913 struct object *o;
2915 if (!p->pack_local || p->pack_keep || p->pack_keep_in_core)
2916 continue;
2917 if (open_pack_index(p))
2918 die(_("cannot open pack index"));
2920 ALLOC_GROW(in_pack.array,
2921 in_pack.nr + p->num_objects,
2922 in_pack.alloc);
2924 for (i = 0; i < p->num_objects; i++) {
2925 nth_packed_object_oid(&oid, p, i);
2926 o = lookup_unknown_object(&oid);
2927 if (!(o->flags & OBJECT_ADDED))
2928 mark_in_pack_object(o, p, &in_pack);
2929 o->flags |= OBJECT_ADDED;
2933 if (in_pack.nr) {
2934 QSORT(in_pack.array, in_pack.nr, ofscmp);
2935 for (i = 0; i < in_pack.nr; i++) {
2936 struct object *o = in_pack.array[i].object;
2937 add_object_entry(&o->oid, o->type, "", 0);
2940 free(in_pack.array);
2943 static int add_loose_object(const struct object_id *oid, const char *path,
2944 void *data)
2946 enum object_type type = oid_object_info(the_repository, oid, NULL);
2948 if (type < 0) {
2949 warning(_("loose object at %s could not be examined"), path);
2950 return 0;
2953 add_object_entry(oid, type, "", 0);
2954 return 0;
2958 * We actually don't even have to worry about reachability here.
2959 * add_object_entry will weed out duplicates, so we just add every
2960 * loose object we find.
2962 static void add_unreachable_loose_objects(void)
2964 for_each_loose_file_in_objdir(get_object_directory(),
2965 add_loose_object,
2966 NULL, NULL, NULL);
2969 static int has_sha1_pack_kept_or_nonlocal(const struct object_id *oid)
2971 static struct packed_git *last_found = (void *)1;
2972 struct packed_git *p;
2974 p = (last_found != (void *)1) ? last_found :
2975 get_all_packs(the_repository);
2977 while (p) {
2978 if ((!p->pack_local || p->pack_keep ||
2979 p->pack_keep_in_core) &&
2980 find_pack_entry_one(oid->hash, p)) {
2981 last_found = p;
2982 return 1;
2984 if (p == last_found)
2985 p = get_all_packs(the_repository);
2986 else
2987 p = p->next;
2988 if (p == last_found)
2989 p = p->next;
2991 return 0;
2995 * Store a list of sha1s that are should not be discarded
2996 * because they are either written too recently, or are
2997 * reachable from another object that was.
2999 * This is filled by get_object_list.
3001 static struct oid_array recent_objects;
3003 static int loosened_object_can_be_discarded(const struct object_id *oid,
3004 timestamp_t mtime)
3006 if (!unpack_unreachable_expiration)
3007 return 0;
3008 if (mtime > unpack_unreachable_expiration)
3009 return 0;
3010 if (oid_array_lookup(&recent_objects, oid) >= 0)
3011 return 0;
3012 return 1;
3015 static void loosen_unused_packed_objects(void)
3017 struct packed_git *p;
3018 uint32_t i;
3019 struct object_id oid;
3021 for (p = get_all_packs(the_repository); p; p = p->next) {
3022 if (!p->pack_local || p->pack_keep || p->pack_keep_in_core)
3023 continue;
3025 if (open_pack_index(p))
3026 die(_("cannot open pack index"));
3028 for (i = 0; i < p->num_objects; i++) {
3029 nth_packed_object_oid(&oid, p, i);
3030 if (!packlist_find(&to_pack, &oid, NULL) &&
3031 !has_sha1_pack_kept_or_nonlocal(&oid) &&
3032 !loosened_object_can_be_discarded(&oid, p->mtime))
3033 if (force_object_loose(&oid, p->mtime))
3034 die(_("unable to force loose object"));
3040 * This tracks any options which pack-reuse code expects to be on, or which a
3041 * reader of the pack might not understand, and which would therefore prevent
3042 * blind reuse of what we have on disk.
3044 static int pack_options_allow_reuse(void)
3046 return pack_to_stdout &&
3047 allow_ofs_delta &&
3048 !ignore_packed_keep_on_disk &&
3049 !ignore_packed_keep_in_core &&
3050 (!local || !have_non_local_packs) &&
3051 !incremental;
3054 static int get_object_list_from_bitmap(struct rev_info *revs)
3056 if (!(bitmap_git = prepare_bitmap_walk(revs)))
3057 return -1;
3059 if (pack_options_allow_reuse() &&
3060 !reuse_partial_packfile_from_bitmap(
3061 bitmap_git,
3062 &reuse_packfile,
3063 &reuse_packfile_objects,
3064 &reuse_packfile_offset)) {
3065 assert(reuse_packfile_objects);
3066 nr_result += reuse_packfile_objects;
3067 display_progress(progress_state, nr_result);
3070 traverse_bitmap_commit_list(bitmap_git, &add_object_entry_from_bitmap);
3071 return 0;
3074 static void record_recent_object(struct object *obj,
3075 const char *name,
3076 void *data)
3078 oid_array_append(&recent_objects, &obj->oid);
3081 static void record_recent_commit(struct commit *commit, void *data)
3083 oid_array_append(&recent_objects, &commit->object.oid);
3086 static void get_object_list(int ac, const char **av)
3088 struct rev_info revs;
3089 struct setup_revision_opt s_r_opt = {
3090 .allow_exclude_promisor_objects = 1,
3092 char line[1000];
3093 int flags = 0;
3094 int save_warning;
3096 repo_init_revisions(the_repository, &revs, NULL);
3097 save_commit_buffer = 0;
3098 setup_revisions(ac, av, &revs, &s_r_opt);
3100 /* make sure shallows are read */
3101 is_repository_shallow(the_repository);
3103 save_warning = warn_on_object_refname_ambiguity;
3104 warn_on_object_refname_ambiguity = 0;
3106 while (fgets(line, sizeof(line), stdin) != NULL) {
3107 int len = strlen(line);
3108 if (len && line[len - 1] == '\n')
3109 line[--len] = 0;
3110 if (!len)
3111 break;
3112 if (*line == '-') {
3113 if (!strcmp(line, "--not")) {
3114 flags ^= UNINTERESTING;
3115 write_bitmap_index = 0;
3116 continue;
3118 if (starts_with(line, "--shallow ")) {
3119 struct object_id oid;
3120 if (get_oid_hex(line + 10, &oid))
3121 die("not an SHA-1 '%s'", line + 10);
3122 register_shallow(the_repository, &oid);
3123 use_bitmap_index = 0;
3124 continue;
3126 die(_("not a rev '%s'"), line);
3128 if (handle_revision_arg(line, &revs, flags, REVARG_CANNOT_BE_FILENAME))
3129 die(_("bad revision '%s'"), line);
3132 warn_on_object_refname_ambiguity = save_warning;
3134 if (use_bitmap_index && !get_object_list_from_bitmap(&revs))
3135 return;
3137 if (use_delta_islands)
3138 load_delta_islands(the_repository, progress);
3140 if (prepare_revision_walk(&revs))
3141 die(_("revision walk setup failed"));
3142 mark_edges_uninteresting(&revs, show_edge, sparse);
3144 if (!fn_show_object)
3145 fn_show_object = show_object;
3146 traverse_commit_list_filtered(&filter_options, &revs,
3147 show_commit, fn_show_object, NULL,
3148 NULL);
3150 if (unpack_unreachable_expiration) {
3151 revs.ignore_missing_links = 1;
3152 if (add_unseen_recent_objects_to_traversal(&revs,
3153 unpack_unreachable_expiration))
3154 die(_("unable to add recent objects"));
3155 if (prepare_revision_walk(&revs))
3156 die(_("revision walk setup failed"));
3157 traverse_commit_list(&revs, record_recent_commit,
3158 record_recent_object, NULL);
3161 if (keep_unreachable)
3162 add_objects_in_unpacked_packs();
3163 if (pack_loose_unreachable)
3164 add_unreachable_loose_objects();
3165 if (unpack_unreachable)
3166 loosen_unused_packed_objects();
3168 oid_array_clear(&recent_objects);
3171 static void add_extra_kept_packs(const struct string_list *names)
3173 struct packed_git *p;
3175 if (!names->nr)
3176 return;
3178 for (p = get_all_packs(the_repository); p; p = p->next) {
3179 const char *name = basename(p->pack_name);
3180 int i;
3182 if (!p->pack_local)
3183 continue;
3185 for (i = 0; i < names->nr; i++)
3186 if (!fspathcmp(name, names->items[i].string))
3187 break;
3189 if (i < names->nr) {
3190 p->pack_keep_in_core = 1;
3191 ignore_packed_keep_in_core = 1;
3192 continue;
3197 static int option_parse_index_version(const struct option *opt,
3198 const char *arg, int unset)
3200 char *c;
3201 const char *val = arg;
3203 BUG_ON_OPT_NEG(unset);
3205 pack_idx_opts.version = strtoul(val, &c, 10);
3206 if (pack_idx_opts.version > 2)
3207 die(_("unsupported index version %s"), val);
3208 if (*c == ',' && c[1])
3209 pack_idx_opts.off32_limit = strtoul(c+1, &c, 0);
3210 if (*c || pack_idx_opts.off32_limit & 0x80000000)
3211 die(_("bad index version '%s'"), val);
3212 return 0;
3215 static int option_parse_unpack_unreachable(const struct option *opt,
3216 const char *arg, int unset)
3218 if (unset) {
3219 unpack_unreachable = 0;
3220 unpack_unreachable_expiration = 0;
3222 else {
3223 unpack_unreachable = 1;
3224 if (arg)
3225 unpack_unreachable_expiration = approxidate(arg);
3227 return 0;
3230 int cmd_pack_objects(int argc, const char **argv, const char *prefix)
3232 int use_internal_rev_list = 0;
3233 int shallow = 0;
3234 int all_progress_implied = 0;
3235 struct argv_array rp = ARGV_ARRAY_INIT;
3236 int rev_list_unpacked = 0, rev_list_all = 0, rev_list_reflog = 0;
3237 int rev_list_index = 0;
3238 struct string_list keep_pack_list = STRING_LIST_INIT_NODUP;
3239 struct option pack_objects_options[] = {
3240 OPT_SET_INT('q', "quiet", &progress,
3241 N_("do not show progress meter"), 0),
3242 OPT_SET_INT(0, "progress", &progress,
3243 N_("show progress meter"), 1),
3244 OPT_SET_INT(0, "all-progress", &progress,
3245 N_("show progress meter during object writing phase"), 2),
3246 OPT_BOOL(0, "all-progress-implied",
3247 &all_progress_implied,
3248 N_("similar to --all-progress when progress meter is shown")),
3249 { OPTION_CALLBACK, 0, "index-version", NULL, N_("<version>[,<offset>]"),
3250 N_("write the pack index file in the specified idx format version"),
3251 PARSE_OPT_NONEG, option_parse_index_version },
3252 OPT_MAGNITUDE(0, "max-pack-size", &pack_size_limit,
3253 N_("maximum size of each output pack file")),
3254 OPT_BOOL(0, "local", &local,
3255 N_("ignore borrowed objects from alternate object store")),
3256 OPT_BOOL(0, "incremental", &incremental,
3257 N_("ignore packed objects")),
3258 OPT_INTEGER(0, "window", &window,
3259 N_("limit pack window by objects")),
3260 OPT_MAGNITUDE(0, "window-memory", &window_memory_limit,
3261 N_("limit pack window by memory in addition to object limit")),
3262 OPT_INTEGER(0, "depth", &depth,
3263 N_("maximum length of delta chain allowed in the resulting pack")),
3264 OPT_BOOL(0, "reuse-delta", &reuse_delta,
3265 N_("reuse existing deltas")),
3266 OPT_BOOL(0, "reuse-object", &reuse_object,
3267 N_("reuse existing objects")),
3268 OPT_BOOL(0, "delta-base-offset", &allow_ofs_delta,
3269 N_("use OFS_DELTA objects")),
3270 OPT_INTEGER(0, "threads", &delta_search_threads,
3271 N_("use threads when searching for best delta matches")),
3272 OPT_BOOL(0, "non-empty", &non_empty,
3273 N_("do not create an empty pack output")),
3274 OPT_BOOL(0, "revs", &use_internal_rev_list,
3275 N_("read revision arguments from standard input")),
3276 OPT_SET_INT_F(0, "unpacked", &rev_list_unpacked,
3277 N_("limit the objects to those that are not yet packed"),
3278 1, PARSE_OPT_NONEG),
3279 OPT_SET_INT_F(0, "all", &rev_list_all,
3280 N_("include objects reachable from any reference"),
3281 1, PARSE_OPT_NONEG),
3282 OPT_SET_INT_F(0, "reflog", &rev_list_reflog,
3283 N_("include objects referred by reflog entries"),
3284 1, PARSE_OPT_NONEG),
3285 OPT_SET_INT_F(0, "indexed-objects", &rev_list_index,
3286 N_("include objects referred to by the index"),
3287 1, PARSE_OPT_NONEG),
3288 OPT_BOOL(0, "stdout", &pack_to_stdout,
3289 N_("output pack to stdout")),
3290 OPT_BOOL(0, "include-tag", &include_tag,
3291 N_("include tag objects that refer to objects to be packed")),
3292 OPT_BOOL(0, "keep-unreachable", &keep_unreachable,
3293 N_("keep unreachable objects")),
3294 OPT_BOOL(0, "pack-loose-unreachable", &pack_loose_unreachable,
3295 N_("pack loose unreachable objects")),
3296 { OPTION_CALLBACK, 0, "unpack-unreachable", NULL, N_("time"),
3297 N_("unpack unreachable objects newer than <time>"),
3298 PARSE_OPT_OPTARG, option_parse_unpack_unreachable },
3299 OPT_BOOL(0, "sparse", &sparse,
3300 N_("use the sparse reachability algorithm")),
3301 OPT_BOOL(0, "thin", &thin,
3302 N_("create thin packs")),
3303 OPT_BOOL(0, "shallow", &shallow,
3304 N_("create packs suitable for shallow fetches")),
3305 OPT_BOOL(0, "honor-pack-keep", &ignore_packed_keep_on_disk,
3306 N_("ignore packs that have companion .keep file")),
3307 OPT_STRING_LIST(0, "keep-pack", &keep_pack_list, N_("name"),
3308 N_("ignore this pack")),
3309 OPT_INTEGER(0, "compression", &pack_compression_level,
3310 N_("pack compression level")),
3311 OPT_SET_INT(0, "keep-true-parents", &grafts_replace_parents,
3312 N_("do not hide commits by grafts"), 0),
3313 OPT_BOOL(0, "use-bitmap-index", &use_bitmap_index,
3314 N_("use a bitmap index if available to speed up counting objects")),
3315 OPT_BOOL(0, "write-bitmap-index", &write_bitmap_index,
3316 N_("write a bitmap index together with the pack index")),
3317 OPT_PARSE_LIST_OBJECTS_FILTER(&filter_options),
3318 { OPTION_CALLBACK, 0, "missing", NULL, N_("action"),
3319 N_("handling for missing objects"), PARSE_OPT_NONEG,
3320 option_parse_missing_action },
3321 OPT_BOOL(0, "exclude-promisor-objects", &exclude_promisor_objects,
3322 N_("do not pack objects in promisor packfiles")),
3323 OPT_BOOL(0, "delta-islands", &use_delta_islands,
3324 N_("respect islands during delta compression")),
3325 OPT_END(),
3328 if (DFS_NUM_STATES > (1 << OE_DFS_STATE_BITS))
3329 BUG("too many dfs states, increase OE_DFS_STATE_BITS");
3331 read_replace_refs = 0;
3333 sparse = git_env_bool("GIT_TEST_PACK_SPARSE", 0);
3334 reset_pack_idx_option(&pack_idx_opts);
3335 git_config(git_pack_config, NULL);
3337 progress = isatty(2);
3338 argc = parse_options(argc, argv, prefix, pack_objects_options,
3339 pack_usage, 0);
3341 if (argc) {
3342 base_name = argv[0];
3343 argc--;
3345 if (pack_to_stdout != !base_name || argc)
3346 usage_with_options(pack_usage, pack_objects_options);
3348 if (depth >= (1 << OE_DEPTH_BITS)) {
3349 warning(_("delta chain depth %d is too deep, forcing %d"),
3350 depth, (1 << OE_DEPTH_BITS) - 1);
3351 depth = (1 << OE_DEPTH_BITS) - 1;
3353 if (cache_max_small_delta_size >= (1U << OE_Z_DELTA_BITS)) {
3354 warning(_("pack.deltaCacheLimit is too high, forcing %d"),
3355 (1U << OE_Z_DELTA_BITS) - 1);
3356 cache_max_small_delta_size = (1U << OE_Z_DELTA_BITS) - 1;
3359 argv_array_push(&rp, "pack-objects");
3360 if (thin) {
3361 use_internal_rev_list = 1;
3362 argv_array_push(&rp, shallow
3363 ? "--objects-edge-aggressive"
3364 : "--objects-edge");
3365 } else
3366 argv_array_push(&rp, "--objects");
3368 if (rev_list_all) {
3369 use_internal_rev_list = 1;
3370 argv_array_push(&rp, "--all");
3372 if (rev_list_reflog) {
3373 use_internal_rev_list = 1;
3374 argv_array_push(&rp, "--reflog");
3376 if (rev_list_index) {
3377 use_internal_rev_list = 1;
3378 argv_array_push(&rp, "--indexed-objects");
3380 if (rev_list_unpacked) {
3381 use_internal_rev_list = 1;
3382 argv_array_push(&rp, "--unpacked");
3385 if (exclude_promisor_objects) {
3386 use_internal_rev_list = 1;
3387 fetch_if_missing = 0;
3388 argv_array_push(&rp, "--exclude-promisor-objects");
3390 if (unpack_unreachable || keep_unreachable || pack_loose_unreachable)
3391 use_internal_rev_list = 1;
3393 if (!reuse_object)
3394 reuse_delta = 0;
3395 if (pack_compression_level == -1)
3396 pack_compression_level = Z_DEFAULT_COMPRESSION;
3397 else if (pack_compression_level < 0 || pack_compression_level > Z_BEST_COMPRESSION)
3398 die(_("bad pack compression level %d"), pack_compression_level);
3400 if (!delta_search_threads) /* --threads=0 means autodetect */
3401 delta_search_threads = online_cpus();
3403 if (!HAVE_THREADS && delta_search_threads != 1)
3404 warning(_("no threads support, ignoring --threads"));
3405 if (!pack_to_stdout && !pack_size_limit)
3406 pack_size_limit = pack_size_limit_cfg;
3407 if (pack_to_stdout && pack_size_limit)
3408 die(_("--max-pack-size cannot be used to build a pack for transfer"));
3409 if (pack_size_limit && pack_size_limit < 1024*1024) {
3410 warning(_("minimum pack size limit is 1 MiB"));
3411 pack_size_limit = 1024*1024;
3414 if (!pack_to_stdout && thin)
3415 die(_("--thin cannot be used to build an indexable pack"));
3417 if (keep_unreachable && unpack_unreachable)
3418 die(_("--keep-unreachable and --unpack-unreachable are incompatible"));
3419 if (!rev_list_all || !rev_list_reflog || !rev_list_index)
3420 unpack_unreachable_expiration = 0;
3422 if (filter_options.choice) {
3423 if (!pack_to_stdout)
3424 die(_("cannot use --filter without --stdout"));
3425 use_bitmap_index = 0;
3429 * "soft" reasons not to use bitmaps - for on-disk repack by default we want
3431 * - to produce good pack (with bitmap index not-yet-packed objects are
3432 * packed in suboptimal order).
3434 * - to use more robust pack-generation codepath (avoiding possible
3435 * bugs in bitmap code and possible bitmap index corruption).
3437 if (!pack_to_stdout)
3438 use_bitmap_index_default = 0;
3440 if (use_bitmap_index < 0)
3441 use_bitmap_index = use_bitmap_index_default;
3443 /* "hard" reasons not to use bitmaps; these just won't work at all */
3444 if (!use_internal_rev_list || (!pack_to_stdout && write_bitmap_index) || is_repository_shallow(the_repository))
3445 use_bitmap_index = 0;
3447 if (pack_to_stdout || !rev_list_all)
3448 write_bitmap_index = 0;
3450 if (use_delta_islands)
3451 argv_array_push(&rp, "--topo-order");
3453 if (progress && all_progress_implied)
3454 progress = 2;
3456 add_extra_kept_packs(&keep_pack_list);
3457 if (ignore_packed_keep_on_disk) {
3458 struct packed_git *p;
3459 for (p = get_all_packs(the_repository); p; p = p->next)
3460 if (p->pack_local && p->pack_keep)
3461 break;
3462 if (!p) /* no keep-able packs found */
3463 ignore_packed_keep_on_disk = 0;
3465 if (local) {
3467 * unlike ignore_packed_keep_on_disk above, we do not
3468 * want to unset "local" based on looking at packs, as
3469 * it also covers non-local objects
3471 struct packed_git *p;
3472 for (p = get_all_packs(the_repository); p; p = p->next) {
3473 if (!p->pack_local) {
3474 have_non_local_packs = 1;
3475 break;
3480 trace2_region_enter("pack-objects", "enumerate-objects",
3481 the_repository);
3482 prepare_packing_data(the_repository, &to_pack);
3484 if (progress)
3485 progress_state = start_progress(_("Enumerating objects"), 0);
3486 if (!use_internal_rev_list)
3487 read_object_list_from_stdin();
3488 else {
3489 get_object_list(rp.argc, rp.argv);
3490 argv_array_clear(&rp);
3492 cleanup_preferred_base();
3493 if (include_tag && nr_result)
3494 for_each_ref(add_ref_tag, NULL);
3495 stop_progress(&progress_state);
3496 trace2_region_leave("pack-objects", "enumerate-objects",
3497 the_repository);
3499 if (non_empty && !nr_result)
3500 return 0;
3501 if (nr_result) {
3502 trace2_region_enter("pack-objects", "prepare-pack",
3503 the_repository);
3504 prepare_pack(window, depth);
3505 trace2_region_leave("pack-objects", "prepare-pack",
3506 the_repository);
3509 trace2_region_enter("pack-objects", "write-pack-file", the_repository);
3510 write_pack_file();
3511 trace2_region_leave("pack-objects", "write-pack-file", the_repository);
3513 if (progress)
3514 fprintf_ln(stderr,
3515 _("Total %"PRIu32" (delta %"PRIu32"),"
3516 " reused %"PRIu32" (delta %"PRIu32")"),
3517 written, written_delta, reused, reused_delta);
3518 return 0;