pack-objects: fix off-by-one in delta-island tree-depth computation
[git.git] / builtin / pack-objects.c
blob3d70ab1f427fd846195997be27f0d2d31f349e5c
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"
36 #define IN_PACK(obj) oe_in_pack(&to_pack, obj)
37 #define SIZE(obj) oe_size(&to_pack, obj)
38 #define SET_SIZE(obj,size) oe_set_size(&to_pack, obj, size)
39 #define DELTA_SIZE(obj) oe_delta_size(&to_pack, obj)
40 #define DELTA(obj) oe_delta(&to_pack, obj)
41 #define DELTA_CHILD(obj) oe_delta_child(&to_pack, obj)
42 #define DELTA_SIBLING(obj) oe_delta_sibling(&to_pack, obj)
43 #define SET_DELTA(obj, val) oe_set_delta(&to_pack, obj, val)
44 #define SET_DELTA_SIZE(obj, val) oe_set_delta_size(&to_pack, obj, val)
45 #define SET_DELTA_CHILD(obj, val) oe_set_delta_child(&to_pack, obj, val)
46 #define SET_DELTA_SIBLING(obj, val) oe_set_delta_sibling(&to_pack, obj, val)
48 static const char *pack_usage[] = {
49 N_("git pack-objects --stdout [<options>...] [< <ref-list> | < <object-list>]"),
50 N_("git pack-objects [<options>...] <base-name> [< <ref-list> | < <object-list>]"),
51 NULL
55 * Objects we are going to pack are collected in the `to_pack` structure.
56 * It contains an array (dynamically expanded) of the object data, and a map
57 * that can resolve SHA1s to their position in the array.
59 static struct packing_data to_pack;
61 static struct pack_idx_entry **written_list;
62 static uint32_t nr_result, nr_written, nr_seen;
63 static uint32_t write_layer;
65 static int non_empty;
66 static int reuse_delta = 1, reuse_object = 1;
67 static int keep_unreachable, unpack_unreachable, include_tag;
68 static timestamp_t unpack_unreachable_expiration;
69 static int pack_loose_unreachable;
70 static int local;
71 static int have_non_local_packs;
72 static int incremental;
73 static int ignore_packed_keep_on_disk;
74 static int ignore_packed_keep_in_core;
75 static int allow_ofs_delta;
76 static struct pack_idx_option pack_idx_opts;
77 static const char *base_name;
78 static int progress = 1;
79 static int window = 10;
80 static unsigned long pack_size_limit;
81 static int depth = 50;
82 static int delta_search_threads;
83 static int pack_to_stdout;
84 static int num_preferred_base;
85 static struct progress *progress_state;
87 static struct packed_git *reuse_packfile;
88 static uint32_t reuse_packfile_objects;
89 static off_t reuse_packfile_offset;
91 static int use_bitmap_index_default = 1;
92 static int use_bitmap_index = -1;
93 static int write_bitmap_index;
94 static uint16_t write_bitmap_options;
96 static int exclude_promisor_objects;
98 static int use_delta_islands;
100 static unsigned long delta_cache_size = 0;
101 static unsigned long max_delta_cache_size = DEFAULT_DELTA_CACHE_SIZE;
102 static unsigned long cache_max_small_delta_size = 1000;
104 static unsigned long window_memory_limit = 0;
106 static struct list_objects_filter_options filter_options;
108 enum missing_action {
109 MA_ERROR = 0, /* fail if any missing objects are encountered */
110 MA_ALLOW_ANY, /* silently allow ALL missing objects */
111 MA_ALLOW_PROMISOR, /* silently allow all missing PROMISOR objects */
113 static enum missing_action arg_missing_action;
114 static show_object_fn fn_show_object;
117 * stats
119 static uint32_t written, written_delta;
120 static uint32_t reused, reused_delta;
123 * Indexed commits
125 static struct commit **indexed_commits;
126 static unsigned int indexed_commits_nr;
127 static unsigned int indexed_commits_alloc;
129 static void index_commit_for_bitmap(struct commit *commit)
131 if (indexed_commits_nr >= indexed_commits_alloc) {
132 indexed_commits_alloc = (indexed_commits_alloc + 32) * 2;
133 REALLOC_ARRAY(indexed_commits, indexed_commits_alloc);
136 indexed_commits[indexed_commits_nr++] = commit;
139 static void *get_delta(struct object_entry *entry)
141 unsigned long size, base_size, delta_size;
142 void *buf, *base_buf, *delta_buf;
143 enum object_type type;
145 buf = read_object_file(&entry->idx.oid, &type, &size);
146 if (!buf)
147 die("unable to read %s", oid_to_hex(&entry->idx.oid));
148 base_buf = read_object_file(&DELTA(entry)->idx.oid, &type,
149 &base_size);
150 if (!base_buf)
151 die("unable to read %s",
152 oid_to_hex(&DELTA(entry)->idx.oid));
153 delta_buf = diff_delta(base_buf, base_size,
154 buf, size, &delta_size, 0);
155 if (!delta_buf || delta_size != DELTA_SIZE(entry))
156 die("delta size changed");
157 free(buf);
158 free(base_buf);
159 return delta_buf;
162 static unsigned long do_compress(void **pptr, unsigned long size)
164 git_zstream stream;
165 void *in, *out;
166 unsigned long maxsize;
168 git_deflate_init(&stream, pack_compression_level);
169 maxsize = git_deflate_bound(&stream, size);
171 in = *pptr;
172 out = xmalloc(maxsize);
173 *pptr = out;
175 stream.next_in = in;
176 stream.avail_in = size;
177 stream.next_out = out;
178 stream.avail_out = maxsize;
179 while (git_deflate(&stream, Z_FINISH) == Z_OK)
180 ; /* nothing */
181 git_deflate_end(&stream);
183 free(in);
184 return stream.total_out;
187 static unsigned long write_large_blob_data(struct git_istream *st, struct hashfile *f,
188 const struct object_id *oid)
190 git_zstream stream;
191 unsigned char ibuf[1024 * 16];
192 unsigned char obuf[1024 * 16];
193 unsigned long olen = 0;
195 git_deflate_init(&stream, pack_compression_level);
197 for (;;) {
198 ssize_t readlen;
199 int zret = Z_OK;
200 readlen = read_istream(st, ibuf, sizeof(ibuf));
201 if (readlen == -1)
202 die(_("unable to read %s"), oid_to_hex(oid));
204 stream.next_in = ibuf;
205 stream.avail_in = readlen;
206 while ((stream.avail_in || readlen == 0) &&
207 (zret == Z_OK || zret == Z_BUF_ERROR)) {
208 stream.next_out = obuf;
209 stream.avail_out = sizeof(obuf);
210 zret = git_deflate(&stream, readlen ? 0 : Z_FINISH);
211 hashwrite(f, obuf, stream.next_out - obuf);
212 olen += stream.next_out - obuf;
214 if (stream.avail_in)
215 die(_("deflate error (%d)"), zret);
216 if (readlen == 0) {
217 if (zret != Z_STREAM_END)
218 die(_("deflate error (%d)"), zret);
219 break;
222 git_deflate_end(&stream);
223 return olen;
227 * we are going to reuse the existing object data as is. make
228 * sure it is not corrupt.
230 static int check_pack_inflate(struct packed_git *p,
231 struct pack_window **w_curs,
232 off_t offset,
233 off_t len,
234 unsigned long expect)
236 git_zstream stream;
237 unsigned char fakebuf[4096], *in;
238 int st;
240 memset(&stream, 0, sizeof(stream));
241 git_inflate_init(&stream);
242 do {
243 in = use_pack(p, w_curs, offset, &stream.avail_in);
244 stream.next_in = in;
245 stream.next_out = fakebuf;
246 stream.avail_out = sizeof(fakebuf);
247 st = git_inflate(&stream, Z_FINISH);
248 offset += stream.next_in - in;
249 } while (st == Z_OK || st == Z_BUF_ERROR);
250 git_inflate_end(&stream);
251 return (st == Z_STREAM_END &&
252 stream.total_out == expect &&
253 stream.total_in == len) ? 0 : -1;
256 static void copy_pack_data(struct hashfile *f,
257 struct packed_git *p,
258 struct pack_window **w_curs,
259 off_t offset,
260 off_t len)
262 unsigned char *in;
263 unsigned long avail;
265 while (len) {
266 in = use_pack(p, w_curs, offset, &avail);
267 if (avail > len)
268 avail = (unsigned long)len;
269 hashwrite(f, in, avail);
270 offset += avail;
271 len -= avail;
275 /* Return 0 if we will bust the pack-size limit */
276 static unsigned long write_no_reuse_object(struct hashfile *f, struct object_entry *entry,
277 unsigned long limit, int usable_delta)
279 unsigned long size, datalen;
280 unsigned char header[MAX_PACK_OBJECT_HEADER],
281 dheader[MAX_PACK_OBJECT_HEADER];
282 unsigned hdrlen;
283 enum object_type type;
284 void *buf;
285 struct git_istream *st = NULL;
286 const unsigned hashsz = the_hash_algo->rawsz;
288 if (!usable_delta) {
289 if (oe_type(entry) == OBJ_BLOB &&
290 oe_size_greater_than(&to_pack, entry, big_file_threshold) &&
291 (st = open_istream(&entry->idx.oid, &type, &size, NULL)) != NULL)
292 buf = NULL;
293 else {
294 buf = read_object_file(&entry->idx.oid, &type, &size);
295 if (!buf)
296 die(_("unable to read %s"),
297 oid_to_hex(&entry->idx.oid));
300 * make sure no cached delta data remains from a
301 * previous attempt before a pack split occurred.
303 FREE_AND_NULL(entry->delta_data);
304 entry->z_delta_size = 0;
305 } else if (entry->delta_data) {
306 size = DELTA_SIZE(entry);
307 buf = entry->delta_data;
308 entry->delta_data = NULL;
309 type = (allow_ofs_delta && DELTA(entry)->idx.offset) ?
310 OBJ_OFS_DELTA : OBJ_REF_DELTA;
311 } else {
312 buf = get_delta(entry);
313 size = DELTA_SIZE(entry);
314 type = (allow_ofs_delta && DELTA(entry)->idx.offset) ?
315 OBJ_OFS_DELTA : OBJ_REF_DELTA;
318 if (st) /* large blob case, just assume we don't compress well */
319 datalen = size;
320 else if (entry->z_delta_size)
321 datalen = entry->z_delta_size;
322 else
323 datalen = do_compress(&buf, size);
326 * The object header is a byte of 'type' followed by zero or
327 * more bytes of length.
329 hdrlen = encode_in_pack_object_header(header, sizeof(header),
330 type, size);
332 if (type == OBJ_OFS_DELTA) {
334 * Deltas with relative base contain an additional
335 * encoding of the relative offset for the delta
336 * base from this object's position in the pack.
338 off_t ofs = entry->idx.offset - DELTA(entry)->idx.offset;
339 unsigned pos = sizeof(dheader) - 1;
340 dheader[pos] = ofs & 127;
341 while (ofs >>= 7)
342 dheader[--pos] = 128 | (--ofs & 127);
343 if (limit && hdrlen + sizeof(dheader) - pos + datalen + hashsz >= limit) {
344 if (st)
345 close_istream(st);
346 free(buf);
347 return 0;
349 hashwrite(f, header, hdrlen);
350 hashwrite(f, dheader + pos, sizeof(dheader) - pos);
351 hdrlen += sizeof(dheader) - pos;
352 } else if (type == OBJ_REF_DELTA) {
354 * Deltas with a base reference contain
355 * additional bytes for the base object ID.
357 if (limit && hdrlen + hashsz + datalen + hashsz >= limit) {
358 if (st)
359 close_istream(st);
360 free(buf);
361 return 0;
363 hashwrite(f, header, hdrlen);
364 hashwrite(f, DELTA(entry)->idx.oid.hash, hashsz);
365 hdrlen += hashsz;
366 } else {
367 if (limit && hdrlen + datalen + hashsz >= limit) {
368 if (st)
369 close_istream(st);
370 free(buf);
371 return 0;
373 hashwrite(f, header, hdrlen);
375 if (st) {
376 datalen = write_large_blob_data(st, f, &entry->idx.oid);
377 close_istream(st);
378 } else {
379 hashwrite(f, buf, datalen);
380 free(buf);
383 return hdrlen + datalen;
386 /* Return 0 if we will bust the pack-size limit */
387 static off_t write_reuse_object(struct hashfile *f, struct object_entry *entry,
388 unsigned long limit, int usable_delta)
390 struct packed_git *p = IN_PACK(entry);
391 struct pack_window *w_curs = NULL;
392 struct revindex_entry *revidx;
393 off_t offset;
394 enum object_type type = oe_type(entry);
395 off_t datalen;
396 unsigned char header[MAX_PACK_OBJECT_HEADER],
397 dheader[MAX_PACK_OBJECT_HEADER];
398 unsigned hdrlen;
399 const unsigned hashsz = the_hash_algo->rawsz;
400 unsigned long entry_size = SIZE(entry);
402 if (DELTA(entry))
403 type = (allow_ofs_delta && DELTA(entry)->idx.offset) ?
404 OBJ_OFS_DELTA : OBJ_REF_DELTA;
405 hdrlen = encode_in_pack_object_header(header, sizeof(header),
406 type, entry_size);
408 offset = entry->in_pack_offset;
409 revidx = find_pack_revindex(p, offset);
410 datalen = revidx[1].offset - offset;
411 if (!pack_to_stdout && p->index_version > 1 &&
412 check_pack_crc(p, &w_curs, offset, datalen, revidx->nr)) {
413 error("bad packed object CRC for %s",
414 oid_to_hex(&entry->idx.oid));
415 unuse_pack(&w_curs);
416 return write_no_reuse_object(f, entry, limit, usable_delta);
419 offset += entry->in_pack_header_size;
420 datalen -= entry->in_pack_header_size;
422 if (!pack_to_stdout && p->index_version == 1 &&
423 check_pack_inflate(p, &w_curs, offset, datalen, entry_size)) {
424 error("corrupt packed object for %s",
425 oid_to_hex(&entry->idx.oid));
426 unuse_pack(&w_curs);
427 return write_no_reuse_object(f, entry, limit, usable_delta);
430 if (type == OBJ_OFS_DELTA) {
431 off_t ofs = entry->idx.offset - DELTA(entry)->idx.offset;
432 unsigned pos = sizeof(dheader) - 1;
433 dheader[pos] = ofs & 127;
434 while (ofs >>= 7)
435 dheader[--pos] = 128 | (--ofs & 127);
436 if (limit && hdrlen + sizeof(dheader) - pos + datalen + hashsz >= limit) {
437 unuse_pack(&w_curs);
438 return 0;
440 hashwrite(f, header, hdrlen);
441 hashwrite(f, dheader + pos, sizeof(dheader) - pos);
442 hdrlen += sizeof(dheader) - pos;
443 reused_delta++;
444 } else if (type == OBJ_REF_DELTA) {
445 if (limit && hdrlen + hashsz + datalen + hashsz >= limit) {
446 unuse_pack(&w_curs);
447 return 0;
449 hashwrite(f, header, hdrlen);
450 hashwrite(f, DELTA(entry)->idx.oid.hash, hashsz);
451 hdrlen += hashsz;
452 reused_delta++;
453 } else {
454 if (limit && hdrlen + datalen + hashsz >= limit) {
455 unuse_pack(&w_curs);
456 return 0;
458 hashwrite(f, header, hdrlen);
460 copy_pack_data(f, p, &w_curs, offset, datalen);
461 unuse_pack(&w_curs);
462 reused++;
463 return hdrlen + datalen;
466 /* Return 0 if we will bust the pack-size limit */
467 static off_t write_object(struct hashfile *f,
468 struct object_entry *entry,
469 off_t write_offset)
471 unsigned long limit;
472 off_t len;
473 int usable_delta, to_reuse;
475 if (!pack_to_stdout)
476 crc32_begin(f);
478 /* apply size limit if limited packsize and not first object */
479 if (!pack_size_limit || !nr_written)
480 limit = 0;
481 else if (pack_size_limit <= write_offset)
483 * the earlier object did not fit the limit; avoid
484 * mistaking this with unlimited (i.e. limit = 0).
486 limit = 1;
487 else
488 limit = pack_size_limit - write_offset;
490 if (!DELTA(entry))
491 usable_delta = 0; /* no delta */
492 else if (!pack_size_limit)
493 usable_delta = 1; /* unlimited packfile */
494 else if (DELTA(entry)->idx.offset == (off_t)-1)
495 usable_delta = 0; /* base was written to another pack */
496 else if (DELTA(entry)->idx.offset)
497 usable_delta = 1; /* base already exists in this pack */
498 else
499 usable_delta = 0; /* base could end up in another pack */
501 if (!reuse_object)
502 to_reuse = 0; /* explicit */
503 else if (!IN_PACK(entry))
504 to_reuse = 0; /* can't reuse what we don't have */
505 else if (oe_type(entry) == OBJ_REF_DELTA ||
506 oe_type(entry) == OBJ_OFS_DELTA)
507 /* check_object() decided it for us ... */
508 to_reuse = usable_delta;
509 /* ... but pack split may override that */
510 else if (oe_type(entry) != entry->in_pack_type)
511 to_reuse = 0; /* pack has delta which is unusable */
512 else if (DELTA(entry))
513 to_reuse = 0; /* we want to pack afresh */
514 else
515 to_reuse = 1; /* we have it in-pack undeltified,
516 * and we do not need to deltify it.
519 if (!to_reuse)
520 len = write_no_reuse_object(f, entry, limit, usable_delta);
521 else
522 len = write_reuse_object(f, entry, limit, usable_delta);
523 if (!len)
524 return 0;
526 if (usable_delta)
527 written_delta++;
528 written++;
529 if (!pack_to_stdout)
530 entry->idx.crc32 = crc32_end(f);
531 return len;
534 enum write_one_status {
535 WRITE_ONE_SKIP = -1, /* already written */
536 WRITE_ONE_BREAK = 0, /* writing this will bust the limit; not written */
537 WRITE_ONE_WRITTEN = 1, /* normal */
538 WRITE_ONE_RECURSIVE = 2 /* already scheduled to be written */
541 static enum write_one_status write_one(struct hashfile *f,
542 struct object_entry *e,
543 off_t *offset)
545 off_t size;
546 int recursing;
549 * we set offset to 1 (which is an impossible value) to mark
550 * the fact that this object is involved in "write its base
551 * first before writing a deltified object" recursion.
553 recursing = (e->idx.offset == 1);
554 if (recursing) {
555 warning("recursive delta detected for object %s",
556 oid_to_hex(&e->idx.oid));
557 return WRITE_ONE_RECURSIVE;
558 } else if (e->idx.offset || e->preferred_base) {
559 /* offset is non zero if object is written already. */
560 return WRITE_ONE_SKIP;
563 /* if we are deltified, write out base object first. */
564 if (DELTA(e)) {
565 e->idx.offset = 1; /* now recurse */
566 switch (write_one(f, DELTA(e), offset)) {
567 case WRITE_ONE_RECURSIVE:
568 /* we cannot depend on this one */
569 SET_DELTA(e, NULL);
570 break;
571 default:
572 break;
573 case WRITE_ONE_BREAK:
574 e->idx.offset = recursing;
575 return WRITE_ONE_BREAK;
579 e->idx.offset = *offset;
580 size = write_object(f, e, *offset);
581 if (!size) {
582 e->idx.offset = recursing;
583 return WRITE_ONE_BREAK;
585 written_list[nr_written++] = &e->idx;
587 /* make sure off_t is sufficiently large not to wrap */
588 if (signed_add_overflows(*offset, size))
589 die("pack too large for current definition of off_t");
590 *offset += size;
591 return WRITE_ONE_WRITTEN;
594 static int mark_tagged(const char *path, const struct object_id *oid, int flag,
595 void *cb_data)
597 struct object_id peeled;
598 struct object_entry *entry = packlist_find(&to_pack, oid->hash, NULL);
600 if (entry)
601 entry->tagged = 1;
602 if (!peel_ref(path, &peeled)) {
603 entry = packlist_find(&to_pack, peeled.hash, NULL);
604 if (entry)
605 entry->tagged = 1;
607 return 0;
610 static inline void add_to_write_order(struct object_entry **wo,
611 unsigned int *endp,
612 struct object_entry *e)
614 if (e->filled || oe_layer(&to_pack, e) != write_layer)
615 return;
616 wo[(*endp)++] = e;
617 e->filled = 1;
620 static void add_descendants_to_write_order(struct object_entry **wo,
621 unsigned int *endp,
622 struct object_entry *e)
624 int add_to_order = 1;
625 while (e) {
626 if (add_to_order) {
627 struct object_entry *s;
628 /* add this node... */
629 add_to_write_order(wo, endp, e);
630 /* all its siblings... */
631 for (s = DELTA_SIBLING(e); s; s = DELTA_SIBLING(s)) {
632 add_to_write_order(wo, endp, s);
635 /* drop down a level to add left subtree nodes if possible */
636 if (DELTA_CHILD(e)) {
637 add_to_order = 1;
638 e = DELTA_CHILD(e);
639 } else {
640 add_to_order = 0;
641 /* our sibling might have some children, it is next */
642 if (DELTA_SIBLING(e)) {
643 e = DELTA_SIBLING(e);
644 continue;
646 /* go back to our parent node */
647 e = DELTA(e);
648 while (e && !DELTA_SIBLING(e)) {
649 /* we're on the right side of a subtree, keep
650 * going up until we can go right again */
651 e = DELTA(e);
653 if (!e) {
654 /* done- we hit our original root node */
655 return;
657 /* pass it off to sibling at this level */
658 e = DELTA_SIBLING(e);
663 static void add_family_to_write_order(struct object_entry **wo,
664 unsigned int *endp,
665 struct object_entry *e)
667 struct object_entry *root;
669 for (root = e; DELTA(root); root = DELTA(root))
670 ; /* nothing */
671 add_descendants_to_write_order(wo, endp, root);
674 static void compute_layer_order(struct object_entry **wo, unsigned int *wo_end)
676 unsigned int i, last_untagged;
677 struct object_entry *objects = to_pack.objects;
679 for (i = 0; i < to_pack.nr_objects; i++) {
680 if (objects[i].tagged)
681 break;
682 add_to_write_order(wo, wo_end, &objects[i]);
684 last_untagged = i;
687 * Then fill all the tagged tips.
689 for (; i < to_pack.nr_objects; i++) {
690 if (objects[i].tagged)
691 add_to_write_order(wo, wo_end, &objects[i]);
695 * And then all remaining commits and tags.
697 for (i = last_untagged; i < to_pack.nr_objects; i++) {
698 if (oe_type(&objects[i]) != OBJ_COMMIT &&
699 oe_type(&objects[i]) != OBJ_TAG)
700 continue;
701 add_to_write_order(wo, wo_end, &objects[i]);
705 * And then all the trees.
707 for (i = last_untagged; i < to_pack.nr_objects; i++) {
708 if (oe_type(&objects[i]) != OBJ_TREE)
709 continue;
710 add_to_write_order(wo, wo_end, &objects[i]);
714 * Finally all the rest in really tight order
716 for (i = last_untagged; i < to_pack.nr_objects; i++) {
717 if (!objects[i].filled && oe_layer(&to_pack, &objects[i]) == write_layer)
718 add_family_to_write_order(wo, wo_end, &objects[i]);
722 static struct object_entry **compute_write_order(void)
724 uint32_t max_layers = 1;
725 unsigned int i, wo_end;
727 struct object_entry **wo;
728 struct object_entry *objects = to_pack.objects;
730 for (i = 0; i < to_pack.nr_objects; i++) {
731 objects[i].tagged = 0;
732 objects[i].filled = 0;
733 SET_DELTA_CHILD(&objects[i], NULL);
734 SET_DELTA_SIBLING(&objects[i], NULL);
738 * Fully connect delta_child/delta_sibling network.
739 * Make sure delta_sibling is sorted in the original
740 * recency order.
742 for (i = to_pack.nr_objects; i > 0;) {
743 struct object_entry *e = &objects[--i];
744 if (!DELTA(e))
745 continue;
746 /* Mark me as the first child */
747 e->delta_sibling_idx = DELTA(e)->delta_child_idx;
748 SET_DELTA_CHILD(DELTA(e), e);
752 * Mark objects that are at the tip of tags.
754 for_each_tag_ref(mark_tagged, NULL);
756 if (use_delta_islands)
757 max_layers = compute_pack_layers(&to_pack);
759 ALLOC_ARRAY(wo, to_pack.nr_objects);
760 wo_end = 0;
762 for (; write_layer < max_layers; ++write_layer)
763 compute_layer_order(wo, &wo_end);
765 if (wo_end != to_pack.nr_objects)
766 die("ordered %u objects, expected %"PRIu32, wo_end, to_pack.nr_objects);
768 return wo;
771 static off_t write_reused_pack(struct hashfile *f)
773 unsigned char buffer[8192];
774 off_t to_write, total;
775 int fd;
777 if (!is_pack_valid(reuse_packfile))
778 die("packfile is invalid: %s", reuse_packfile->pack_name);
780 fd = git_open(reuse_packfile->pack_name);
781 if (fd < 0)
782 die_errno("unable to open packfile for reuse: %s",
783 reuse_packfile->pack_name);
785 if (lseek(fd, sizeof(struct pack_header), SEEK_SET) == -1)
786 die_errno("unable to seek in reused packfile");
788 if (reuse_packfile_offset < 0)
789 reuse_packfile_offset = reuse_packfile->pack_size - the_hash_algo->rawsz;
791 total = to_write = reuse_packfile_offset - sizeof(struct pack_header);
793 while (to_write) {
794 int read_pack = xread(fd, buffer, sizeof(buffer));
796 if (read_pack <= 0)
797 die_errno("unable to read from reused packfile");
799 if (read_pack > to_write)
800 read_pack = to_write;
802 hashwrite(f, buffer, read_pack);
803 to_write -= read_pack;
806 * We don't know the actual number of objects written,
807 * only how many bytes written, how many bytes total, and
808 * how many objects total. So we can fake it by pretending all
809 * objects we are writing are the same size. This gives us a
810 * smooth progress meter, and at the end it matches the true
811 * answer.
813 written = reuse_packfile_objects *
814 (((double)(total - to_write)) / total);
815 display_progress(progress_state, written);
818 close(fd);
819 written = reuse_packfile_objects;
820 display_progress(progress_state, written);
821 return reuse_packfile_offset - sizeof(struct pack_header);
824 static const char no_split_warning[] = N_(
825 "disabling bitmap writing, packs are split due to pack.packSizeLimit"
828 static void write_pack_file(void)
830 uint32_t i = 0, j;
831 struct hashfile *f;
832 off_t offset;
833 uint32_t nr_remaining = nr_result;
834 time_t last_mtime = 0;
835 struct object_entry **write_order;
837 if (progress > pack_to_stdout)
838 progress_state = start_progress(_("Writing objects"), nr_result);
839 ALLOC_ARRAY(written_list, to_pack.nr_objects);
840 write_order = compute_write_order();
842 do {
843 struct object_id oid;
844 char *pack_tmp_name = NULL;
846 if (pack_to_stdout)
847 f = hashfd_throughput(1, "<stdout>", progress_state);
848 else
849 f = create_tmp_packfile(&pack_tmp_name);
851 offset = write_pack_header(f, nr_remaining);
853 if (reuse_packfile) {
854 off_t packfile_size;
855 assert(pack_to_stdout);
857 packfile_size = write_reused_pack(f);
858 offset += packfile_size;
861 nr_written = 0;
862 for (; i < to_pack.nr_objects; i++) {
863 struct object_entry *e = write_order[i];
864 if (write_one(f, e, &offset) == WRITE_ONE_BREAK)
865 break;
866 display_progress(progress_state, written);
870 * Did we write the wrong # entries in the header?
871 * If so, rewrite it like in fast-import
873 if (pack_to_stdout) {
874 finalize_hashfile(f, oid.hash, CSUM_HASH_IN_STREAM | CSUM_CLOSE);
875 } else if (nr_written == nr_remaining) {
876 finalize_hashfile(f, oid.hash, CSUM_HASH_IN_STREAM | CSUM_FSYNC | CSUM_CLOSE);
877 } else {
878 int fd = finalize_hashfile(f, oid.hash, 0);
879 fixup_pack_header_footer(fd, oid.hash, pack_tmp_name,
880 nr_written, oid.hash, offset);
881 close(fd);
882 if (write_bitmap_index) {
883 warning(_(no_split_warning));
884 write_bitmap_index = 0;
888 if (!pack_to_stdout) {
889 struct stat st;
890 struct strbuf tmpname = STRBUF_INIT;
893 * Packs are runtime accessed in their mtime
894 * order since newer packs are more likely to contain
895 * younger objects. So if we are creating multiple
896 * packs then we should modify the mtime of later ones
897 * to preserve this property.
899 if (stat(pack_tmp_name, &st) < 0) {
900 warning_errno("failed to stat %s", pack_tmp_name);
901 } else if (!last_mtime) {
902 last_mtime = st.st_mtime;
903 } else {
904 struct utimbuf utb;
905 utb.actime = st.st_atime;
906 utb.modtime = --last_mtime;
907 if (utime(pack_tmp_name, &utb) < 0)
908 warning_errno("failed utime() on %s", pack_tmp_name);
911 strbuf_addf(&tmpname, "%s-", base_name);
913 if (write_bitmap_index) {
914 bitmap_writer_set_checksum(oid.hash);
915 bitmap_writer_build_type_index(
916 &to_pack, written_list, nr_written);
919 finish_tmp_packfile(&tmpname, pack_tmp_name,
920 written_list, nr_written,
921 &pack_idx_opts, oid.hash);
923 if (write_bitmap_index) {
924 strbuf_addf(&tmpname, "%s.bitmap", oid_to_hex(&oid));
926 stop_progress(&progress_state);
928 bitmap_writer_show_progress(progress);
929 bitmap_writer_reuse_bitmaps(&to_pack);
930 bitmap_writer_select_commits(indexed_commits, indexed_commits_nr, -1);
931 bitmap_writer_build(&to_pack);
932 bitmap_writer_finish(written_list, nr_written,
933 tmpname.buf, write_bitmap_options);
934 write_bitmap_index = 0;
937 strbuf_release(&tmpname);
938 free(pack_tmp_name);
939 puts(oid_to_hex(&oid));
942 /* mark written objects as written to previous pack */
943 for (j = 0; j < nr_written; j++) {
944 written_list[j]->offset = (off_t)-1;
946 nr_remaining -= nr_written;
947 } while (nr_remaining && i < to_pack.nr_objects);
949 free(written_list);
950 free(write_order);
951 stop_progress(&progress_state);
952 if (written != nr_result)
953 die("wrote %"PRIu32" objects while expecting %"PRIu32,
954 written, nr_result);
957 static int no_try_delta(const char *path)
959 static struct attr_check *check;
961 if (!check)
962 check = attr_check_initl("delta", NULL);
963 if (git_check_attr(path, check))
964 return 0;
965 if (ATTR_FALSE(check->items[0].value))
966 return 1;
967 return 0;
971 * When adding an object, check whether we have already added it
972 * to our packing list. If so, we can skip. However, if we are
973 * being asked to excludei t, but the previous mention was to include
974 * it, make sure to adjust its flags and tweak our numbers accordingly.
976 * As an optimization, we pass out the index position where we would have
977 * found the item, since that saves us from having to look it up again a
978 * few lines later when we want to add the new entry.
980 static int have_duplicate_entry(const struct object_id *oid,
981 int exclude,
982 uint32_t *index_pos)
984 struct object_entry *entry;
986 entry = packlist_find(&to_pack, oid->hash, index_pos);
987 if (!entry)
988 return 0;
990 if (exclude) {
991 if (!entry->preferred_base)
992 nr_result--;
993 entry->preferred_base = 1;
996 return 1;
999 static int want_found_object(int exclude, struct packed_git *p)
1001 if (exclude)
1002 return 1;
1003 if (incremental)
1004 return 0;
1007 * When asked to do --local (do not include an object that appears in a
1008 * pack we borrow from elsewhere) or --honor-pack-keep (do not include
1009 * an object that appears in a pack marked with .keep), finding a pack
1010 * that matches the criteria is sufficient for us to decide to omit it.
1011 * However, even if this pack does not satisfy the criteria, we need to
1012 * make sure no copy of this object appears in _any_ pack that makes us
1013 * to omit the object, so we need to check all the packs.
1015 * We can however first check whether these options can possible matter;
1016 * if they do not matter we know we want the object in generated pack.
1017 * Otherwise, we signal "-1" at the end to tell the caller that we do
1018 * not know either way, and it needs to check more packs.
1020 if (!ignore_packed_keep_on_disk &&
1021 !ignore_packed_keep_in_core &&
1022 (!local || !have_non_local_packs))
1023 return 1;
1025 if (local && !p->pack_local)
1026 return 0;
1027 if (p->pack_local &&
1028 ((ignore_packed_keep_on_disk && p->pack_keep) ||
1029 (ignore_packed_keep_in_core && p->pack_keep_in_core)))
1030 return 0;
1032 /* we don't know yet; keep looking for more packs */
1033 return -1;
1037 * Check whether we want the object in the pack (e.g., we do not want
1038 * objects found in non-local stores if the "--local" option was used).
1040 * If the caller already knows an existing pack it wants to take the object
1041 * from, that is passed in *found_pack and *found_offset; otherwise this
1042 * function finds if there is any pack that has the object and returns the pack
1043 * and its offset in these variables.
1045 static int want_object_in_pack(const struct object_id *oid,
1046 int exclude,
1047 struct packed_git **found_pack,
1048 off_t *found_offset)
1050 int want;
1051 struct list_head *pos;
1053 if (!exclude && local && has_loose_object_nonlocal(oid))
1054 return 0;
1057 * If we already know the pack object lives in, start checks from that
1058 * pack - in the usual case when neither --local was given nor .keep files
1059 * are present we will determine the answer right now.
1061 if (*found_pack) {
1062 want = want_found_object(exclude, *found_pack);
1063 if (want != -1)
1064 return want;
1066 list_for_each(pos, get_packed_git_mru(the_repository)) {
1067 struct packed_git *p = list_entry(pos, struct packed_git, mru);
1068 off_t offset;
1070 if (p == *found_pack)
1071 offset = *found_offset;
1072 else
1073 offset = find_pack_entry_one(oid->hash, p);
1075 if (offset) {
1076 if (!*found_pack) {
1077 if (!is_pack_valid(p))
1078 continue;
1079 *found_offset = offset;
1080 *found_pack = p;
1082 want = want_found_object(exclude, p);
1083 if (!exclude && want > 0)
1084 list_move(&p->mru,
1085 get_packed_git_mru(the_repository));
1086 if (want != -1)
1087 return want;
1091 return 1;
1094 static void create_object_entry(const struct object_id *oid,
1095 enum object_type type,
1096 uint32_t hash,
1097 int exclude,
1098 int no_try_delta,
1099 uint32_t index_pos,
1100 struct packed_git *found_pack,
1101 off_t found_offset)
1103 struct object_entry *entry;
1105 entry = packlist_alloc(&to_pack, oid->hash, index_pos);
1106 entry->hash = hash;
1107 oe_set_type(entry, type);
1108 if (exclude)
1109 entry->preferred_base = 1;
1110 else
1111 nr_result++;
1112 if (found_pack) {
1113 oe_set_in_pack(&to_pack, entry, found_pack);
1114 entry->in_pack_offset = found_offset;
1117 entry->no_try_delta = no_try_delta;
1120 static const char no_closure_warning[] = N_(
1121 "disabling bitmap writing, as some objects are not being packed"
1124 static int add_object_entry(const struct object_id *oid, enum object_type type,
1125 const char *name, int exclude)
1127 struct packed_git *found_pack = NULL;
1128 off_t found_offset = 0;
1129 uint32_t index_pos;
1131 display_progress(progress_state, ++nr_seen);
1133 if (have_duplicate_entry(oid, exclude, &index_pos))
1134 return 0;
1136 if (!want_object_in_pack(oid, exclude, &found_pack, &found_offset)) {
1137 /* The pack is missing an object, so it will not have closure */
1138 if (write_bitmap_index) {
1139 warning(_(no_closure_warning));
1140 write_bitmap_index = 0;
1142 return 0;
1145 create_object_entry(oid, type, pack_name_hash(name),
1146 exclude, name && no_try_delta(name),
1147 index_pos, found_pack, found_offset);
1148 return 1;
1151 static int add_object_entry_from_bitmap(const struct object_id *oid,
1152 enum object_type type,
1153 int flags, uint32_t name_hash,
1154 struct packed_git *pack, off_t offset)
1156 uint32_t index_pos;
1158 display_progress(progress_state, ++nr_seen);
1160 if (have_duplicate_entry(oid, 0, &index_pos))
1161 return 0;
1163 if (!want_object_in_pack(oid, 0, &pack, &offset))
1164 return 0;
1166 create_object_entry(oid, type, name_hash, 0, 0, index_pos, pack, offset);
1167 return 1;
1170 struct pbase_tree_cache {
1171 struct object_id oid;
1172 int ref;
1173 int temporary;
1174 void *tree_data;
1175 unsigned long tree_size;
1178 static struct pbase_tree_cache *(pbase_tree_cache[256]);
1179 static int pbase_tree_cache_ix(const struct object_id *oid)
1181 return oid->hash[0] % ARRAY_SIZE(pbase_tree_cache);
1183 static int pbase_tree_cache_ix_incr(int ix)
1185 return (ix+1) % ARRAY_SIZE(pbase_tree_cache);
1188 static struct pbase_tree {
1189 struct pbase_tree *next;
1190 /* This is a phony "cache" entry; we are not
1191 * going to evict it or find it through _get()
1192 * mechanism -- this is for the toplevel node that
1193 * would almost always change with any commit.
1195 struct pbase_tree_cache pcache;
1196 } *pbase_tree;
1198 static struct pbase_tree_cache *pbase_tree_get(const struct object_id *oid)
1200 struct pbase_tree_cache *ent, *nent;
1201 void *data;
1202 unsigned long size;
1203 enum object_type type;
1204 int neigh;
1205 int my_ix = pbase_tree_cache_ix(oid);
1206 int available_ix = -1;
1208 /* pbase-tree-cache acts as a limited hashtable.
1209 * your object will be found at your index or within a few
1210 * slots after that slot if it is cached.
1212 for (neigh = 0; neigh < 8; neigh++) {
1213 ent = pbase_tree_cache[my_ix];
1214 if (ent && !oidcmp(&ent->oid, oid)) {
1215 ent->ref++;
1216 return ent;
1218 else if (((available_ix < 0) && (!ent || !ent->ref)) ||
1219 ((0 <= available_ix) &&
1220 (!ent && pbase_tree_cache[available_ix])))
1221 available_ix = my_ix;
1222 if (!ent)
1223 break;
1224 my_ix = pbase_tree_cache_ix_incr(my_ix);
1227 /* Did not find one. Either we got a bogus request or
1228 * we need to read and perhaps cache.
1230 data = read_object_file(oid, &type, &size);
1231 if (!data)
1232 return NULL;
1233 if (type != OBJ_TREE) {
1234 free(data);
1235 return NULL;
1238 /* We need to either cache or return a throwaway copy */
1240 if (available_ix < 0)
1241 ent = NULL;
1242 else {
1243 ent = pbase_tree_cache[available_ix];
1244 my_ix = available_ix;
1247 if (!ent) {
1248 nent = xmalloc(sizeof(*nent));
1249 nent->temporary = (available_ix < 0);
1251 else {
1252 /* evict and reuse */
1253 free(ent->tree_data);
1254 nent = ent;
1256 oidcpy(&nent->oid, oid);
1257 nent->tree_data = data;
1258 nent->tree_size = size;
1259 nent->ref = 1;
1260 if (!nent->temporary)
1261 pbase_tree_cache[my_ix] = nent;
1262 return nent;
1265 static void pbase_tree_put(struct pbase_tree_cache *cache)
1267 if (!cache->temporary) {
1268 cache->ref--;
1269 return;
1271 free(cache->tree_data);
1272 free(cache);
1275 static int name_cmp_len(const char *name)
1277 int i;
1278 for (i = 0; name[i] && name[i] != '\n' && name[i] != '/'; i++)
1280 return i;
1283 static void add_pbase_object(struct tree_desc *tree,
1284 const char *name,
1285 int cmplen,
1286 const char *fullname)
1288 struct name_entry entry;
1289 int cmp;
1291 while (tree_entry(tree,&entry)) {
1292 if (S_ISGITLINK(entry.mode))
1293 continue;
1294 cmp = tree_entry_len(&entry) != cmplen ? 1 :
1295 memcmp(name, entry.path, cmplen);
1296 if (cmp > 0)
1297 continue;
1298 if (cmp < 0)
1299 return;
1300 if (name[cmplen] != '/') {
1301 add_object_entry(entry.oid,
1302 object_type(entry.mode),
1303 fullname, 1);
1304 return;
1306 if (S_ISDIR(entry.mode)) {
1307 struct tree_desc sub;
1308 struct pbase_tree_cache *tree;
1309 const char *down = name+cmplen+1;
1310 int downlen = name_cmp_len(down);
1312 tree = pbase_tree_get(entry.oid);
1313 if (!tree)
1314 return;
1315 init_tree_desc(&sub, tree->tree_data, tree->tree_size);
1317 add_pbase_object(&sub, down, downlen, fullname);
1318 pbase_tree_put(tree);
1323 static unsigned *done_pbase_paths;
1324 static int done_pbase_paths_num;
1325 static int done_pbase_paths_alloc;
1326 static int done_pbase_path_pos(unsigned hash)
1328 int lo = 0;
1329 int hi = done_pbase_paths_num;
1330 while (lo < hi) {
1331 int mi = lo + (hi - lo) / 2;
1332 if (done_pbase_paths[mi] == hash)
1333 return mi;
1334 if (done_pbase_paths[mi] < hash)
1335 hi = mi;
1336 else
1337 lo = mi + 1;
1339 return -lo-1;
1342 static int check_pbase_path(unsigned hash)
1344 int pos = done_pbase_path_pos(hash);
1345 if (0 <= pos)
1346 return 1;
1347 pos = -pos - 1;
1348 ALLOC_GROW(done_pbase_paths,
1349 done_pbase_paths_num + 1,
1350 done_pbase_paths_alloc);
1351 done_pbase_paths_num++;
1352 if (pos < done_pbase_paths_num)
1353 MOVE_ARRAY(done_pbase_paths + pos + 1, done_pbase_paths + pos,
1354 done_pbase_paths_num - pos - 1);
1355 done_pbase_paths[pos] = hash;
1356 return 0;
1359 static void add_preferred_base_object(const char *name)
1361 struct pbase_tree *it;
1362 int cmplen;
1363 unsigned hash = pack_name_hash(name);
1365 if (!num_preferred_base || check_pbase_path(hash))
1366 return;
1368 cmplen = name_cmp_len(name);
1369 for (it = pbase_tree; it; it = it->next) {
1370 if (cmplen == 0) {
1371 add_object_entry(&it->pcache.oid, OBJ_TREE, NULL, 1);
1373 else {
1374 struct tree_desc tree;
1375 init_tree_desc(&tree, it->pcache.tree_data, it->pcache.tree_size);
1376 add_pbase_object(&tree, name, cmplen, name);
1381 static void add_preferred_base(struct object_id *oid)
1383 struct pbase_tree *it;
1384 void *data;
1385 unsigned long size;
1386 struct object_id tree_oid;
1388 if (window <= num_preferred_base++)
1389 return;
1391 data = read_object_with_reference(oid, tree_type, &size, &tree_oid);
1392 if (!data)
1393 return;
1395 for (it = pbase_tree; it; it = it->next) {
1396 if (!oidcmp(&it->pcache.oid, &tree_oid)) {
1397 free(data);
1398 return;
1402 it = xcalloc(1, sizeof(*it));
1403 it->next = pbase_tree;
1404 pbase_tree = it;
1406 oidcpy(&it->pcache.oid, &tree_oid);
1407 it->pcache.tree_data = data;
1408 it->pcache.tree_size = size;
1411 static void cleanup_preferred_base(void)
1413 struct pbase_tree *it;
1414 unsigned i;
1416 it = pbase_tree;
1417 pbase_tree = NULL;
1418 while (it) {
1419 struct pbase_tree *tmp = it;
1420 it = tmp->next;
1421 free(tmp->pcache.tree_data);
1422 free(tmp);
1425 for (i = 0; i < ARRAY_SIZE(pbase_tree_cache); i++) {
1426 if (!pbase_tree_cache[i])
1427 continue;
1428 free(pbase_tree_cache[i]->tree_data);
1429 FREE_AND_NULL(pbase_tree_cache[i]);
1432 FREE_AND_NULL(done_pbase_paths);
1433 done_pbase_paths_num = done_pbase_paths_alloc = 0;
1436 static void check_object(struct object_entry *entry)
1438 unsigned long canonical_size;
1440 if (IN_PACK(entry)) {
1441 struct packed_git *p = IN_PACK(entry);
1442 struct pack_window *w_curs = NULL;
1443 const unsigned char *base_ref = NULL;
1444 struct object_entry *base_entry;
1445 unsigned long used, used_0;
1446 unsigned long avail;
1447 off_t ofs;
1448 unsigned char *buf, c;
1449 enum object_type type;
1450 unsigned long in_pack_size;
1452 buf = use_pack(p, &w_curs, entry->in_pack_offset, &avail);
1455 * We want in_pack_type even if we do not reuse delta
1456 * since non-delta representations could still be reused.
1458 used = unpack_object_header_buffer(buf, avail,
1459 &type,
1460 &in_pack_size);
1461 if (used == 0)
1462 goto give_up;
1464 if (type < 0)
1465 BUG("invalid type %d", type);
1466 entry->in_pack_type = type;
1469 * Determine if this is a delta and if so whether we can
1470 * reuse it or not. Otherwise let's find out as cheaply as
1471 * possible what the actual type and size for this object is.
1473 switch (entry->in_pack_type) {
1474 default:
1475 /* Not a delta hence we've already got all we need. */
1476 oe_set_type(entry, entry->in_pack_type);
1477 SET_SIZE(entry, in_pack_size);
1478 entry->in_pack_header_size = used;
1479 if (oe_type(entry) < OBJ_COMMIT || oe_type(entry) > OBJ_BLOB)
1480 goto give_up;
1481 unuse_pack(&w_curs);
1482 return;
1483 case OBJ_REF_DELTA:
1484 if (reuse_delta && !entry->preferred_base)
1485 base_ref = use_pack(p, &w_curs,
1486 entry->in_pack_offset + used, NULL);
1487 entry->in_pack_header_size = used + the_hash_algo->rawsz;
1488 break;
1489 case OBJ_OFS_DELTA:
1490 buf = use_pack(p, &w_curs,
1491 entry->in_pack_offset + used, NULL);
1492 used_0 = 0;
1493 c = buf[used_0++];
1494 ofs = c & 127;
1495 while (c & 128) {
1496 ofs += 1;
1497 if (!ofs || MSB(ofs, 7)) {
1498 error("delta base offset overflow in pack for %s",
1499 oid_to_hex(&entry->idx.oid));
1500 goto give_up;
1502 c = buf[used_0++];
1503 ofs = (ofs << 7) + (c & 127);
1505 ofs = entry->in_pack_offset - ofs;
1506 if (ofs <= 0 || ofs >= entry->in_pack_offset) {
1507 error("delta base offset out of bound for %s",
1508 oid_to_hex(&entry->idx.oid));
1509 goto give_up;
1511 if (reuse_delta && !entry->preferred_base) {
1512 struct revindex_entry *revidx;
1513 revidx = find_pack_revindex(p, ofs);
1514 if (!revidx)
1515 goto give_up;
1516 base_ref = nth_packed_object_sha1(p, revidx->nr);
1518 entry->in_pack_header_size = used + used_0;
1519 break;
1522 if (base_ref && (base_entry = packlist_find(&to_pack, base_ref, NULL)) &&
1523 in_same_island(&entry->idx.oid, &base_entry->idx.oid)) {
1525 * If base_ref was set above that means we wish to
1526 * reuse delta data, and we even found that base
1527 * in the list of objects we want to pack. Goodie!
1529 * Depth value does not matter - find_deltas() will
1530 * never consider reused delta as the base object to
1531 * deltify other objects against, in order to avoid
1532 * circular deltas.
1534 oe_set_type(entry, entry->in_pack_type);
1535 SET_SIZE(entry, in_pack_size); /* delta size */
1536 SET_DELTA(entry, base_entry);
1537 SET_DELTA_SIZE(entry, in_pack_size);
1538 entry->delta_sibling_idx = base_entry->delta_child_idx;
1539 SET_DELTA_CHILD(base_entry, entry);
1540 unuse_pack(&w_curs);
1541 return;
1544 if (oe_type(entry)) {
1545 off_t delta_pos;
1548 * This must be a delta and we already know what the
1549 * final object type is. Let's extract the actual
1550 * object size from the delta header.
1552 delta_pos = entry->in_pack_offset + entry->in_pack_header_size;
1553 canonical_size = get_size_from_delta(p, &w_curs, delta_pos);
1554 if (canonical_size == 0)
1555 goto give_up;
1556 SET_SIZE(entry, canonical_size);
1557 unuse_pack(&w_curs);
1558 return;
1562 * No choice but to fall back to the recursive delta walk
1563 * with sha1_object_info() to find about the object type
1564 * at this point...
1566 give_up:
1567 unuse_pack(&w_curs);
1570 oe_set_type(entry,
1571 oid_object_info(the_repository, &entry->idx.oid, &canonical_size));
1572 if (entry->type_valid) {
1573 SET_SIZE(entry, canonical_size);
1574 } else {
1576 * Bad object type is checked in prepare_pack(). This is
1577 * to permit a missing preferred base object to be ignored
1578 * as a preferred base. Doing so can result in a larger
1579 * pack file, but the transfer will still take place.
1584 static int pack_offset_sort(const void *_a, const void *_b)
1586 const struct object_entry *a = *(struct object_entry **)_a;
1587 const struct object_entry *b = *(struct object_entry **)_b;
1588 const struct packed_git *a_in_pack = IN_PACK(a);
1589 const struct packed_git *b_in_pack = IN_PACK(b);
1591 /* avoid filesystem trashing with loose objects */
1592 if (!a_in_pack && !b_in_pack)
1593 return oidcmp(&a->idx.oid, &b->idx.oid);
1595 if (a_in_pack < b_in_pack)
1596 return -1;
1597 if (a_in_pack > b_in_pack)
1598 return 1;
1599 return a->in_pack_offset < b->in_pack_offset ? -1 :
1600 (a->in_pack_offset > b->in_pack_offset);
1604 * Drop an on-disk delta we were planning to reuse. Naively, this would
1605 * just involve blanking out the "delta" field, but we have to deal
1606 * with some extra book-keeping:
1608 * 1. Removing ourselves from the delta_sibling linked list.
1610 * 2. Updating our size/type to the non-delta representation. These were
1611 * either not recorded initially (size) or overwritten with the delta type
1612 * (type) when check_object() decided to reuse the delta.
1614 * 3. Resetting our delta depth, as we are now a base object.
1616 static void drop_reused_delta(struct object_entry *entry)
1618 unsigned *idx = &to_pack.objects[entry->delta_idx - 1].delta_child_idx;
1619 struct object_info oi = OBJECT_INFO_INIT;
1620 enum object_type type;
1621 unsigned long size;
1623 while (*idx) {
1624 struct object_entry *oe = &to_pack.objects[*idx - 1];
1626 if (oe == entry)
1627 *idx = oe->delta_sibling_idx;
1628 else
1629 idx = &oe->delta_sibling_idx;
1631 SET_DELTA(entry, NULL);
1632 entry->depth = 0;
1634 oi.sizep = &size;
1635 oi.typep = &type;
1636 if (packed_object_info(the_repository, IN_PACK(entry), entry->in_pack_offset, &oi) < 0) {
1638 * We failed to get the info from this pack for some reason;
1639 * fall back to sha1_object_info, which may find another copy.
1640 * And if that fails, the error will be recorded in oe_type(entry)
1641 * and dealt with in prepare_pack().
1643 oe_set_type(entry,
1644 oid_object_info(the_repository, &entry->idx.oid, &size));
1645 } else {
1646 oe_set_type(entry, type);
1648 SET_SIZE(entry, size);
1652 * Follow the chain of deltas from this entry onward, throwing away any links
1653 * that cause us to hit a cycle (as determined by the DFS state flags in
1654 * the entries).
1656 * We also detect too-long reused chains that would violate our --depth
1657 * limit.
1659 static void break_delta_chains(struct object_entry *entry)
1662 * The actual depth of each object we will write is stored as an int,
1663 * as it cannot exceed our int "depth" limit. But before we break
1664 * changes based no that limit, we may potentially go as deep as the
1665 * number of objects, which is elsewhere bounded to a uint32_t.
1667 uint32_t total_depth;
1668 struct object_entry *cur, *next;
1670 for (cur = entry, total_depth = 0;
1671 cur;
1672 cur = DELTA(cur), total_depth++) {
1673 if (cur->dfs_state == DFS_DONE) {
1675 * We've already seen this object and know it isn't
1676 * part of a cycle. We do need to append its depth
1677 * to our count.
1679 total_depth += cur->depth;
1680 break;
1684 * We break cycles before looping, so an ACTIVE state (or any
1685 * other cruft which made its way into the state variable)
1686 * is a bug.
1688 if (cur->dfs_state != DFS_NONE)
1689 BUG("confusing delta dfs state in first pass: %d",
1690 cur->dfs_state);
1693 * Now we know this is the first time we've seen the object. If
1694 * it's not a delta, we're done traversing, but we'll mark it
1695 * done to save time on future traversals.
1697 if (!DELTA(cur)) {
1698 cur->dfs_state = DFS_DONE;
1699 break;
1703 * Mark ourselves as active and see if the next step causes
1704 * us to cycle to another active object. It's important to do
1705 * this _before_ we loop, because it impacts where we make the
1706 * cut, and thus how our total_depth counter works.
1707 * E.g., We may see a partial loop like:
1709 * A -> B -> C -> D -> B
1711 * Cutting B->C breaks the cycle. But now the depth of A is
1712 * only 1, and our total_depth counter is at 3. The size of the
1713 * error is always one less than the size of the cycle we
1714 * broke. Commits C and D were "lost" from A's chain.
1716 * If we instead cut D->B, then the depth of A is correct at 3.
1717 * We keep all commits in the chain that we examined.
1719 cur->dfs_state = DFS_ACTIVE;
1720 if (DELTA(cur)->dfs_state == DFS_ACTIVE) {
1721 drop_reused_delta(cur);
1722 cur->dfs_state = DFS_DONE;
1723 break;
1728 * And now that we've gone all the way to the bottom of the chain, we
1729 * need to clear the active flags and set the depth fields as
1730 * appropriate. Unlike the loop above, which can quit when it drops a
1731 * delta, we need to keep going to look for more depth cuts. So we need
1732 * an extra "next" pointer to keep going after we reset cur->delta.
1734 for (cur = entry; cur; cur = next) {
1735 next = DELTA(cur);
1738 * We should have a chain of zero or more ACTIVE states down to
1739 * a final DONE. We can quit after the DONE, because either it
1740 * has no bases, or we've already handled them in a previous
1741 * call.
1743 if (cur->dfs_state == DFS_DONE)
1744 break;
1745 else if (cur->dfs_state != DFS_ACTIVE)
1746 BUG("confusing delta dfs state in second pass: %d",
1747 cur->dfs_state);
1750 * If the total_depth is more than depth, then we need to snip
1751 * the chain into two or more smaller chains that don't exceed
1752 * the maximum depth. Most of the resulting chains will contain
1753 * (depth + 1) entries (i.e., depth deltas plus one base), and
1754 * the last chain (i.e., the one containing entry) will contain
1755 * whatever entries are left over, namely
1756 * (total_depth % (depth + 1)) of them.
1758 * Since we are iterating towards decreasing depth, we need to
1759 * decrement total_depth as we go, and we need to write to the
1760 * entry what its final depth will be after all of the
1761 * snipping. Since we're snipping into chains of length (depth
1762 * + 1) entries, the final depth of an entry will be its
1763 * original depth modulo (depth + 1). Any time we encounter an
1764 * entry whose final depth is supposed to be zero, we snip it
1765 * from its delta base, thereby making it so.
1767 cur->depth = (total_depth--) % (depth + 1);
1768 if (!cur->depth)
1769 drop_reused_delta(cur);
1771 cur->dfs_state = DFS_DONE;
1775 static void get_object_details(void)
1777 uint32_t i;
1778 struct object_entry **sorted_by_offset;
1780 if (progress)
1781 progress_state = start_progress(_("Counting objects"),
1782 to_pack.nr_objects);
1784 sorted_by_offset = xcalloc(to_pack.nr_objects, sizeof(struct object_entry *));
1785 for (i = 0; i < to_pack.nr_objects; i++)
1786 sorted_by_offset[i] = to_pack.objects + i;
1787 QSORT(sorted_by_offset, to_pack.nr_objects, pack_offset_sort);
1789 for (i = 0; i < to_pack.nr_objects; i++) {
1790 struct object_entry *entry = sorted_by_offset[i];
1791 check_object(entry);
1792 if (entry->type_valid &&
1793 oe_size_greater_than(&to_pack, entry, big_file_threshold))
1794 entry->no_try_delta = 1;
1795 display_progress(progress_state, i + 1);
1797 stop_progress(&progress_state);
1800 * This must happen in a second pass, since we rely on the delta
1801 * information for the whole list being completed.
1803 for (i = 0; i < to_pack.nr_objects; i++)
1804 break_delta_chains(&to_pack.objects[i]);
1806 free(sorted_by_offset);
1810 * We search for deltas in a list sorted by type, by filename hash, and then
1811 * by size, so that we see progressively smaller and smaller files.
1812 * That's because we prefer deltas to be from the bigger file
1813 * to the smaller -- deletes are potentially cheaper, but perhaps
1814 * more importantly, the bigger file is likely the more recent
1815 * one. The deepest deltas are therefore the oldest objects which are
1816 * less susceptible to be accessed often.
1818 static int type_size_sort(const void *_a, const void *_b)
1820 const struct object_entry *a = *(struct object_entry **)_a;
1821 const struct object_entry *b = *(struct object_entry **)_b;
1822 enum object_type a_type = oe_type(a);
1823 enum object_type b_type = oe_type(b);
1824 unsigned long a_size = SIZE(a);
1825 unsigned long b_size = SIZE(b);
1827 if (a_type > b_type)
1828 return -1;
1829 if (a_type < b_type)
1830 return 1;
1831 if (a->hash > b->hash)
1832 return -1;
1833 if (a->hash < b->hash)
1834 return 1;
1835 if (a->preferred_base > b->preferred_base)
1836 return -1;
1837 if (a->preferred_base < b->preferred_base)
1838 return 1;
1839 if (use_delta_islands) {
1840 int island_cmp = island_delta_cmp(&a->idx.oid, &b->idx.oid);
1841 if (island_cmp)
1842 return island_cmp;
1844 if (a_size > b_size)
1845 return -1;
1846 if (a_size < b_size)
1847 return 1;
1848 return a < b ? -1 : (a > b); /* newest first */
1851 struct unpacked {
1852 struct object_entry *entry;
1853 void *data;
1854 struct delta_index *index;
1855 unsigned depth;
1858 static int delta_cacheable(unsigned long src_size, unsigned long trg_size,
1859 unsigned long delta_size)
1861 if (max_delta_cache_size && delta_cache_size + delta_size > max_delta_cache_size)
1862 return 0;
1864 if (delta_size < cache_max_small_delta_size)
1865 return 1;
1867 /* cache delta, if objects are large enough compared to delta size */
1868 if ((src_size >> 20) + (trg_size >> 21) > (delta_size >> 10))
1869 return 1;
1871 return 0;
1874 #ifndef NO_PTHREADS
1876 static pthread_mutex_t read_mutex;
1877 #define read_lock() pthread_mutex_lock(&read_mutex)
1878 #define read_unlock() pthread_mutex_unlock(&read_mutex)
1880 static pthread_mutex_t cache_mutex;
1881 #define cache_lock() pthread_mutex_lock(&cache_mutex)
1882 #define cache_unlock() pthread_mutex_unlock(&cache_mutex)
1884 static pthread_mutex_t progress_mutex;
1885 #define progress_lock() pthread_mutex_lock(&progress_mutex)
1886 #define progress_unlock() pthread_mutex_unlock(&progress_mutex)
1888 #else
1890 #define read_lock() (void)0
1891 #define read_unlock() (void)0
1892 #define cache_lock() (void)0
1893 #define cache_unlock() (void)0
1894 #define progress_lock() (void)0
1895 #define progress_unlock() (void)0
1897 #endif
1900 * Return the size of the object without doing any delta
1901 * reconstruction (so non-deltas are true object sizes, but deltas
1902 * return the size of the delta data).
1904 unsigned long oe_get_size_slow(struct packing_data *pack,
1905 const struct object_entry *e)
1907 struct packed_git *p;
1908 struct pack_window *w_curs;
1909 unsigned char *buf;
1910 enum object_type type;
1911 unsigned long used, avail, size;
1913 if (e->type_ != OBJ_OFS_DELTA && e->type_ != OBJ_REF_DELTA) {
1914 read_lock();
1915 if (oid_object_info(the_repository, &e->idx.oid, &size) < 0)
1916 die(_("unable to get size of %s"),
1917 oid_to_hex(&e->idx.oid));
1918 read_unlock();
1919 return size;
1922 p = oe_in_pack(pack, e);
1923 if (!p)
1924 BUG("when e->type is a delta, it must belong to a pack");
1926 read_lock();
1927 w_curs = NULL;
1928 buf = use_pack(p, &w_curs, e->in_pack_offset, &avail);
1929 used = unpack_object_header_buffer(buf, avail, &type, &size);
1930 if (used == 0)
1931 die(_("unable to parse object header of %s"),
1932 oid_to_hex(&e->idx.oid));
1934 unuse_pack(&w_curs);
1935 read_unlock();
1936 return size;
1939 static int try_delta(struct unpacked *trg, struct unpacked *src,
1940 unsigned max_depth, unsigned long *mem_usage)
1942 struct object_entry *trg_entry = trg->entry;
1943 struct object_entry *src_entry = src->entry;
1944 unsigned long trg_size, src_size, delta_size, sizediff, max_size, sz;
1945 unsigned ref_depth;
1946 enum object_type type;
1947 void *delta_buf;
1949 /* Don't bother doing diffs between different types */
1950 if (oe_type(trg_entry) != oe_type(src_entry))
1951 return -1;
1954 * We do not bother to try a delta that we discarded on an
1955 * earlier try, but only when reusing delta data. Note that
1956 * src_entry that is marked as the preferred_base should always
1957 * be considered, as even if we produce a suboptimal delta against
1958 * it, we will still save the transfer cost, as we already know
1959 * the other side has it and we won't send src_entry at all.
1961 if (reuse_delta && IN_PACK(trg_entry) &&
1962 IN_PACK(trg_entry) == IN_PACK(src_entry) &&
1963 !src_entry->preferred_base &&
1964 trg_entry->in_pack_type != OBJ_REF_DELTA &&
1965 trg_entry->in_pack_type != OBJ_OFS_DELTA)
1966 return 0;
1968 /* Let's not bust the allowed depth. */
1969 if (src->depth >= max_depth)
1970 return 0;
1972 /* Now some size filtering heuristics. */
1973 trg_size = SIZE(trg_entry);
1974 if (!DELTA(trg_entry)) {
1975 max_size = trg_size/2 - the_hash_algo->rawsz;
1976 ref_depth = 1;
1977 } else {
1978 max_size = DELTA_SIZE(trg_entry);
1979 ref_depth = trg->depth;
1981 max_size = (uint64_t)max_size * (max_depth - src->depth) /
1982 (max_depth - ref_depth + 1);
1983 if (max_size == 0)
1984 return 0;
1985 src_size = SIZE(src_entry);
1986 sizediff = src_size < trg_size ? trg_size - src_size : 0;
1987 if (sizediff >= max_size)
1988 return 0;
1989 if (trg_size < src_size / 32)
1990 return 0;
1992 if (!in_same_island(&trg->entry->idx.oid, &src->entry->idx.oid))
1993 return 0;
1995 /* Load data if not already done */
1996 if (!trg->data) {
1997 read_lock();
1998 trg->data = read_object_file(&trg_entry->idx.oid, &type, &sz);
1999 read_unlock();
2000 if (!trg->data)
2001 die("object %s cannot be read",
2002 oid_to_hex(&trg_entry->idx.oid));
2003 if (sz != trg_size)
2004 die("object %s inconsistent object length (%lu vs %lu)",
2005 oid_to_hex(&trg_entry->idx.oid), sz,
2006 trg_size);
2007 *mem_usage += sz;
2009 if (!src->data) {
2010 read_lock();
2011 src->data = read_object_file(&src_entry->idx.oid, &type, &sz);
2012 read_unlock();
2013 if (!src->data) {
2014 if (src_entry->preferred_base) {
2015 static int warned = 0;
2016 if (!warned++)
2017 warning("object %s cannot be read",
2018 oid_to_hex(&src_entry->idx.oid));
2020 * Those objects are not included in the
2021 * resulting pack. Be resilient and ignore
2022 * them if they can't be read, in case the
2023 * pack could be created nevertheless.
2025 return 0;
2027 die("object %s cannot be read",
2028 oid_to_hex(&src_entry->idx.oid));
2030 if (sz != src_size)
2031 die("object %s inconsistent object length (%lu vs %lu)",
2032 oid_to_hex(&src_entry->idx.oid), sz,
2033 src_size);
2034 *mem_usage += sz;
2036 if (!src->index) {
2037 src->index = create_delta_index(src->data, src_size);
2038 if (!src->index) {
2039 static int warned = 0;
2040 if (!warned++)
2041 warning("suboptimal pack - out of memory");
2042 return 0;
2044 *mem_usage += sizeof_delta_index(src->index);
2047 delta_buf = create_delta(src->index, trg->data, trg_size, &delta_size, max_size);
2048 if (!delta_buf)
2049 return 0;
2050 if (delta_size >= (1U << OE_DELTA_SIZE_BITS)) {
2051 free(delta_buf);
2052 return 0;
2055 if (DELTA(trg_entry)) {
2056 /* Prefer only shallower same-sized deltas. */
2057 if (delta_size == DELTA_SIZE(trg_entry) &&
2058 src->depth + 1 >= trg->depth) {
2059 free(delta_buf);
2060 return 0;
2065 * Handle memory allocation outside of the cache
2066 * accounting lock. Compiler will optimize the strangeness
2067 * away when NO_PTHREADS is defined.
2069 free(trg_entry->delta_data);
2070 cache_lock();
2071 if (trg_entry->delta_data) {
2072 delta_cache_size -= DELTA_SIZE(trg_entry);
2073 trg_entry->delta_data = NULL;
2075 if (delta_cacheable(src_size, trg_size, delta_size)) {
2076 delta_cache_size += delta_size;
2077 cache_unlock();
2078 trg_entry->delta_data = xrealloc(delta_buf, delta_size);
2079 } else {
2080 cache_unlock();
2081 free(delta_buf);
2084 SET_DELTA(trg_entry, src_entry);
2085 SET_DELTA_SIZE(trg_entry, delta_size);
2086 trg->depth = src->depth + 1;
2088 return 1;
2091 static unsigned int check_delta_limit(struct object_entry *me, unsigned int n)
2093 struct object_entry *child = DELTA_CHILD(me);
2094 unsigned int m = n;
2095 while (child) {
2096 unsigned int c = check_delta_limit(child, n + 1);
2097 if (m < c)
2098 m = c;
2099 child = DELTA_SIBLING(child);
2101 return m;
2104 static unsigned long free_unpacked(struct unpacked *n)
2106 unsigned long freed_mem = sizeof_delta_index(n->index);
2107 free_delta_index(n->index);
2108 n->index = NULL;
2109 if (n->data) {
2110 freed_mem += SIZE(n->entry);
2111 FREE_AND_NULL(n->data);
2113 n->entry = NULL;
2114 n->depth = 0;
2115 return freed_mem;
2118 static void find_deltas(struct object_entry **list, unsigned *list_size,
2119 int window, int depth, unsigned *processed)
2121 uint32_t i, idx = 0, count = 0;
2122 struct unpacked *array;
2123 unsigned long mem_usage = 0;
2125 array = xcalloc(window, sizeof(struct unpacked));
2127 for (;;) {
2128 struct object_entry *entry;
2129 struct unpacked *n = array + idx;
2130 int j, max_depth, best_base = -1;
2132 progress_lock();
2133 if (!*list_size) {
2134 progress_unlock();
2135 break;
2137 entry = *list++;
2138 (*list_size)--;
2139 if (!entry->preferred_base) {
2140 (*processed)++;
2141 display_progress(progress_state, *processed);
2143 progress_unlock();
2145 mem_usage -= free_unpacked(n);
2146 n->entry = entry;
2148 while (window_memory_limit &&
2149 mem_usage > window_memory_limit &&
2150 count > 1) {
2151 uint32_t tail = (idx + window - count) % window;
2152 mem_usage -= free_unpacked(array + tail);
2153 count--;
2156 /* We do not compute delta to *create* objects we are not
2157 * going to pack.
2159 if (entry->preferred_base)
2160 goto next;
2163 * If the current object is at pack edge, take the depth the
2164 * objects that depend on the current object into account
2165 * otherwise they would become too deep.
2167 max_depth = depth;
2168 if (DELTA_CHILD(entry)) {
2169 max_depth -= check_delta_limit(entry, 0);
2170 if (max_depth <= 0)
2171 goto next;
2174 j = window;
2175 while (--j > 0) {
2176 int ret;
2177 uint32_t other_idx = idx + j;
2178 struct unpacked *m;
2179 if (other_idx >= window)
2180 other_idx -= window;
2181 m = array + other_idx;
2182 if (!m->entry)
2183 break;
2184 ret = try_delta(n, m, max_depth, &mem_usage);
2185 if (ret < 0)
2186 break;
2187 else if (ret > 0)
2188 best_base = other_idx;
2192 * If we decided to cache the delta data, then it is best
2193 * to compress it right away. First because we have to do
2194 * it anyway, and doing it here while we're threaded will
2195 * save a lot of time in the non threaded write phase,
2196 * as well as allow for caching more deltas within
2197 * the same cache size limit.
2198 * ...
2199 * But only if not writing to stdout, since in that case
2200 * the network is most likely throttling writes anyway,
2201 * and therefore it is best to go to the write phase ASAP
2202 * instead, as we can afford spending more time compressing
2203 * between writes at that moment.
2205 if (entry->delta_data && !pack_to_stdout) {
2206 unsigned long size;
2208 size = do_compress(&entry->delta_data, DELTA_SIZE(entry));
2209 if (size < (1U << OE_Z_DELTA_BITS)) {
2210 entry->z_delta_size = size;
2211 cache_lock();
2212 delta_cache_size -= DELTA_SIZE(entry);
2213 delta_cache_size += entry->z_delta_size;
2214 cache_unlock();
2215 } else {
2216 FREE_AND_NULL(entry->delta_data);
2217 entry->z_delta_size = 0;
2221 /* if we made n a delta, and if n is already at max
2222 * depth, leaving it in the window is pointless. we
2223 * should evict it first.
2225 if (DELTA(entry) && max_depth <= n->depth)
2226 continue;
2229 * Move the best delta base up in the window, after the
2230 * currently deltified object, to keep it longer. It will
2231 * be the first base object to be attempted next.
2233 if (DELTA(entry)) {
2234 struct unpacked swap = array[best_base];
2235 int dist = (window + idx - best_base) % window;
2236 int dst = best_base;
2237 while (dist--) {
2238 int src = (dst + 1) % window;
2239 array[dst] = array[src];
2240 dst = src;
2242 array[dst] = swap;
2245 next:
2246 idx++;
2247 if (count + 1 < window)
2248 count++;
2249 if (idx >= window)
2250 idx = 0;
2253 for (i = 0; i < window; ++i) {
2254 free_delta_index(array[i].index);
2255 free(array[i].data);
2257 free(array);
2260 #ifndef NO_PTHREADS
2262 static void try_to_free_from_threads(size_t size)
2264 read_lock();
2265 release_pack_memory(size);
2266 read_unlock();
2269 static try_to_free_t old_try_to_free_routine;
2272 * The main thread waits on the condition that (at least) one of the workers
2273 * has stopped working (which is indicated in the .working member of
2274 * struct thread_params).
2275 * When a work thread has completed its work, it sets .working to 0 and
2276 * signals the main thread and waits on the condition that .data_ready
2277 * becomes 1.
2280 struct thread_params {
2281 pthread_t thread;
2282 struct object_entry **list;
2283 unsigned list_size;
2284 unsigned remaining;
2285 int window;
2286 int depth;
2287 int working;
2288 int data_ready;
2289 pthread_mutex_t mutex;
2290 pthread_cond_t cond;
2291 unsigned *processed;
2294 static pthread_cond_t progress_cond;
2297 * Mutex and conditional variable can't be statically-initialized on Windows.
2299 static void init_threaded_search(void)
2301 init_recursive_mutex(&read_mutex);
2302 pthread_mutex_init(&cache_mutex, NULL);
2303 pthread_mutex_init(&progress_mutex, NULL);
2304 pthread_cond_init(&progress_cond, NULL);
2305 old_try_to_free_routine = set_try_to_free_routine(try_to_free_from_threads);
2308 static void cleanup_threaded_search(void)
2310 set_try_to_free_routine(old_try_to_free_routine);
2311 pthread_cond_destroy(&progress_cond);
2312 pthread_mutex_destroy(&read_mutex);
2313 pthread_mutex_destroy(&cache_mutex);
2314 pthread_mutex_destroy(&progress_mutex);
2317 static void *threaded_find_deltas(void *arg)
2319 struct thread_params *me = arg;
2321 progress_lock();
2322 while (me->remaining) {
2323 progress_unlock();
2325 find_deltas(me->list, &me->remaining,
2326 me->window, me->depth, me->processed);
2328 progress_lock();
2329 me->working = 0;
2330 pthread_cond_signal(&progress_cond);
2331 progress_unlock();
2334 * We must not set ->data_ready before we wait on the
2335 * condition because the main thread may have set it to 1
2336 * before we get here. In order to be sure that new
2337 * work is available if we see 1 in ->data_ready, it
2338 * was initialized to 0 before this thread was spawned
2339 * and we reset it to 0 right away.
2341 pthread_mutex_lock(&me->mutex);
2342 while (!me->data_ready)
2343 pthread_cond_wait(&me->cond, &me->mutex);
2344 me->data_ready = 0;
2345 pthread_mutex_unlock(&me->mutex);
2347 progress_lock();
2349 progress_unlock();
2350 /* leave ->working 1 so that this doesn't get more work assigned */
2351 return NULL;
2354 static void ll_find_deltas(struct object_entry **list, unsigned list_size,
2355 int window, int depth, unsigned *processed)
2357 struct thread_params *p;
2358 int i, ret, active_threads = 0;
2360 init_threaded_search();
2362 if (delta_search_threads <= 1) {
2363 find_deltas(list, &list_size, window, depth, processed);
2364 cleanup_threaded_search();
2365 return;
2367 if (progress > pack_to_stdout)
2368 fprintf(stderr, "Delta compression using up to %d threads.\n",
2369 delta_search_threads);
2370 p = xcalloc(delta_search_threads, sizeof(*p));
2372 /* Partition the work amongst work threads. */
2373 for (i = 0; i < delta_search_threads; i++) {
2374 unsigned sub_size = list_size / (delta_search_threads - i);
2376 /* don't use too small segments or no deltas will be found */
2377 if (sub_size < 2*window && i+1 < delta_search_threads)
2378 sub_size = 0;
2380 p[i].window = window;
2381 p[i].depth = depth;
2382 p[i].processed = processed;
2383 p[i].working = 1;
2384 p[i].data_ready = 0;
2386 /* try to split chunks on "path" boundaries */
2387 while (sub_size && sub_size < list_size &&
2388 list[sub_size]->hash &&
2389 list[sub_size]->hash == list[sub_size-1]->hash)
2390 sub_size++;
2392 p[i].list = list;
2393 p[i].list_size = sub_size;
2394 p[i].remaining = sub_size;
2396 list += sub_size;
2397 list_size -= sub_size;
2400 /* Start work threads. */
2401 for (i = 0; i < delta_search_threads; i++) {
2402 if (!p[i].list_size)
2403 continue;
2404 pthread_mutex_init(&p[i].mutex, NULL);
2405 pthread_cond_init(&p[i].cond, NULL);
2406 ret = pthread_create(&p[i].thread, NULL,
2407 threaded_find_deltas, &p[i]);
2408 if (ret)
2409 die("unable to create thread: %s", strerror(ret));
2410 active_threads++;
2414 * Now let's wait for work completion. Each time a thread is done
2415 * with its work, we steal half of the remaining work from the
2416 * thread with the largest number of unprocessed objects and give
2417 * it to that newly idle thread. This ensure good load balancing
2418 * until the remaining object list segments are simply too short
2419 * to be worth splitting anymore.
2421 while (active_threads) {
2422 struct thread_params *target = NULL;
2423 struct thread_params *victim = NULL;
2424 unsigned sub_size = 0;
2426 progress_lock();
2427 for (;;) {
2428 for (i = 0; !target && i < delta_search_threads; i++)
2429 if (!p[i].working)
2430 target = &p[i];
2431 if (target)
2432 break;
2433 pthread_cond_wait(&progress_cond, &progress_mutex);
2436 for (i = 0; i < delta_search_threads; i++)
2437 if (p[i].remaining > 2*window &&
2438 (!victim || victim->remaining < p[i].remaining))
2439 victim = &p[i];
2440 if (victim) {
2441 sub_size = victim->remaining / 2;
2442 list = victim->list + victim->list_size - sub_size;
2443 while (sub_size && list[0]->hash &&
2444 list[0]->hash == list[-1]->hash) {
2445 list++;
2446 sub_size--;
2448 if (!sub_size) {
2450 * It is possible for some "paths" to have
2451 * so many objects that no hash boundary
2452 * might be found. Let's just steal the
2453 * exact half in that case.
2455 sub_size = victim->remaining / 2;
2456 list -= sub_size;
2458 target->list = list;
2459 victim->list_size -= sub_size;
2460 victim->remaining -= sub_size;
2462 target->list_size = sub_size;
2463 target->remaining = sub_size;
2464 target->working = 1;
2465 progress_unlock();
2467 pthread_mutex_lock(&target->mutex);
2468 target->data_ready = 1;
2469 pthread_cond_signal(&target->cond);
2470 pthread_mutex_unlock(&target->mutex);
2472 if (!sub_size) {
2473 pthread_join(target->thread, NULL);
2474 pthread_cond_destroy(&target->cond);
2475 pthread_mutex_destroy(&target->mutex);
2476 active_threads--;
2479 cleanup_threaded_search();
2480 free(p);
2483 #else
2484 #define ll_find_deltas(l, s, w, d, p) find_deltas(l, &s, w, d, p)
2485 #endif
2487 static void add_tag_chain(const struct object_id *oid)
2489 struct tag *tag;
2492 * We catch duplicates already in add_object_entry(), but we'd
2493 * prefer to do this extra check to avoid having to parse the
2494 * tag at all if we already know that it's being packed (e.g., if
2495 * it was included via bitmaps, we would not have parsed it
2496 * previously).
2498 if (packlist_find(&to_pack, oid->hash, NULL))
2499 return;
2501 tag = lookup_tag(the_repository, oid);
2502 while (1) {
2503 if (!tag || parse_tag(tag) || !tag->tagged)
2504 die("unable to pack objects reachable from tag %s",
2505 oid_to_hex(oid));
2507 add_object_entry(&tag->object.oid, OBJ_TAG, NULL, 0);
2509 if (tag->tagged->type != OBJ_TAG)
2510 return;
2512 tag = (struct tag *)tag->tagged;
2516 static int add_ref_tag(const char *path, const struct object_id *oid, int flag, void *cb_data)
2518 struct object_id peeled;
2520 if (starts_with(path, "refs/tags/") && /* is a tag? */
2521 !peel_ref(path, &peeled) && /* peelable? */
2522 packlist_find(&to_pack, peeled.hash, NULL)) /* object packed? */
2523 add_tag_chain(oid);
2524 return 0;
2527 static void prepare_pack(int window, int depth)
2529 struct object_entry **delta_list;
2530 uint32_t i, nr_deltas;
2531 unsigned n;
2533 if (use_delta_islands)
2534 resolve_tree_islands(progress, &to_pack);
2536 get_object_details();
2539 * If we're locally repacking then we need to be doubly careful
2540 * from now on in order to make sure no stealth corruption gets
2541 * propagated to the new pack. Clients receiving streamed packs
2542 * should validate everything they get anyway so no need to incur
2543 * the additional cost here in that case.
2545 if (!pack_to_stdout)
2546 do_check_packed_object_crc = 1;
2548 if (!to_pack.nr_objects || !window || !depth)
2549 return;
2551 ALLOC_ARRAY(delta_list, to_pack.nr_objects);
2552 nr_deltas = n = 0;
2554 for (i = 0; i < to_pack.nr_objects; i++) {
2555 struct object_entry *entry = to_pack.objects + i;
2557 if (DELTA(entry))
2558 /* This happens if we decided to reuse existing
2559 * delta from a pack. "reuse_delta &&" is implied.
2561 continue;
2563 if (!entry->type_valid ||
2564 oe_size_less_than(&to_pack, entry, 50))
2565 continue;
2567 if (entry->no_try_delta)
2568 continue;
2570 if (!entry->preferred_base) {
2571 nr_deltas++;
2572 if (oe_type(entry) < 0)
2573 die("unable to get type of object %s",
2574 oid_to_hex(&entry->idx.oid));
2575 } else {
2576 if (oe_type(entry) < 0) {
2578 * This object is not found, but we
2579 * don't have to include it anyway.
2581 continue;
2585 delta_list[n++] = entry;
2588 if (nr_deltas && n > 1) {
2589 unsigned nr_done = 0;
2590 if (progress)
2591 progress_state = start_progress(_("Compressing objects"),
2592 nr_deltas);
2593 QSORT(delta_list, n, type_size_sort);
2594 ll_find_deltas(delta_list, n, window+1, depth, &nr_done);
2595 stop_progress(&progress_state);
2596 if (nr_done != nr_deltas)
2597 die("inconsistency with delta count");
2599 free(delta_list);
2602 static int git_pack_config(const char *k, const char *v, void *cb)
2604 if (!strcmp(k, "pack.window")) {
2605 window = git_config_int(k, v);
2606 return 0;
2608 if (!strcmp(k, "pack.windowmemory")) {
2609 window_memory_limit = git_config_ulong(k, v);
2610 return 0;
2612 if (!strcmp(k, "pack.depth")) {
2613 depth = git_config_int(k, v);
2614 return 0;
2616 if (!strcmp(k, "pack.deltacachesize")) {
2617 max_delta_cache_size = git_config_int(k, v);
2618 return 0;
2620 if (!strcmp(k, "pack.deltacachelimit")) {
2621 cache_max_small_delta_size = git_config_int(k, v);
2622 return 0;
2624 if (!strcmp(k, "pack.writebitmaphashcache")) {
2625 if (git_config_bool(k, v))
2626 write_bitmap_options |= BITMAP_OPT_HASH_CACHE;
2627 else
2628 write_bitmap_options &= ~BITMAP_OPT_HASH_CACHE;
2630 if (!strcmp(k, "pack.usebitmaps")) {
2631 use_bitmap_index_default = git_config_bool(k, v);
2632 return 0;
2634 if (!strcmp(k, "pack.threads")) {
2635 delta_search_threads = git_config_int(k, v);
2636 if (delta_search_threads < 0)
2637 die("invalid number of threads specified (%d)",
2638 delta_search_threads);
2639 #ifdef NO_PTHREADS
2640 if (delta_search_threads != 1) {
2641 warning("no threads support, ignoring %s", k);
2642 delta_search_threads = 0;
2644 #endif
2645 return 0;
2647 if (!strcmp(k, "pack.indexversion")) {
2648 pack_idx_opts.version = git_config_int(k, v);
2649 if (pack_idx_opts.version > 2)
2650 die("bad pack.indexversion=%"PRIu32,
2651 pack_idx_opts.version);
2652 return 0;
2654 return git_default_config(k, v, cb);
2657 static void read_object_list_from_stdin(void)
2659 char line[GIT_MAX_HEXSZ + 1 + PATH_MAX + 2];
2660 struct object_id oid;
2661 const char *p;
2663 for (;;) {
2664 if (!fgets(line, sizeof(line), stdin)) {
2665 if (feof(stdin))
2666 break;
2667 if (!ferror(stdin))
2668 die("fgets returned NULL, not EOF, not error!");
2669 if (errno != EINTR)
2670 die_errno("fgets");
2671 clearerr(stdin);
2672 continue;
2674 if (line[0] == '-') {
2675 if (get_oid_hex(line+1, &oid))
2676 die("expected edge object ID, got garbage:\n %s",
2677 line);
2678 add_preferred_base(&oid);
2679 continue;
2681 if (parse_oid_hex(line, &oid, &p))
2682 die("expected object ID, got garbage:\n %s", line);
2684 add_preferred_base_object(p + 1);
2685 add_object_entry(&oid, OBJ_NONE, p + 1, 0);
2689 /* Remember to update object flag allocation in object.h */
2690 #define OBJECT_ADDED (1u<<20)
2692 static void show_commit(struct commit *commit, void *data)
2694 add_object_entry(&commit->object.oid, OBJ_COMMIT, NULL, 0);
2695 commit->object.flags |= OBJECT_ADDED;
2697 if (write_bitmap_index)
2698 index_commit_for_bitmap(commit);
2700 if (use_delta_islands)
2701 propagate_island_marks(commit);
2704 static void show_object(struct object *obj, const char *name, void *data)
2706 add_preferred_base_object(name);
2707 add_object_entry(&obj->oid, obj->type, name, 0);
2708 obj->flags |= OBJECT_ADDED;
2710 if (use_delta_islands) {
2711 const char *p;
2712 unsigned depth;
2713 struct object_entry *ent;
2715 /* the empty string is a root tree, which is depth 0 */
2716 depth = *name ? 1 : 0;
2717 for (p = strchr(name, '/'); p; p = strchr(p + 1, '/'))
2718 depth++;
2720 ent = packlist_find(&to_pack, obj->oid.hash, NULL);
2721 if (ent && depth > oe_tree_depth(&to_pack, ent))
2722 oe_set_tree_depth(&to_pack, ent, depth);
2726 static void show_object__ma_allow_any(struct object *obj, const char *name, void *data)
2728 assert(arg_missing_action == MA_ALLOW_ANY);
2731 * Quietly ignore ALL missing objects. This avoids problems with
2732 * staging them now and getting an odd error later.
2734 if (!has_object_file(&obj->oid))
2735 return;
2737 show_object(obj, name, data);
2740 static void show_object__ma_allow_promisor(struct object *obj, const char *name, void *data)
2742 assert(arg_missing_action == MA_ALLOW_PROMISOR);
2745 * Quietly ignore EXPECTED missing objects. This avoids problems with
2746 * staging them now and getting an odd error later.
2748 if (!has_object_file(&obj->oid) && is_promisor_object(&obj->oid))
2749 return;
2751 show_object(obj, name, data);
2754 static int option_parse_missing_action(const struct option *opt,
2755 const char *arg, int unset)
2757 assert(arg);
2758 assert(!unset);
2760 if (!strcmp(arg, "error")) {
2761 arg_missing_action = MA_ERROR;
2762 fn_show_object = show_object;
2763 return 0;
2766 if (!strcmp(arg, "allow-any")) {
2767 arg_missing_action = MA_ALLOW_ANY;
2768 fetch_if_missing = 0;
2769 fn_show_object = show_object__ma_allow_any;
2770 return 0;
2773 if (!strcmp(arg, "allow-promisor")) {
2774 arg_missing_action = MA_ALLOW_PROMISOR;
2775 fetch_if_missing = 0;
2776 fn_show_object = show_object__ma_allow_promisor;
2777 return 0;
2780 die(_("invalid value for --missing"));
2781 return 0;
2784 static void show_edge(struct commit *commit)
2786 add_preferred_base(&commit->object.oid);
2789 struct in_pack_object {
2790 off_t offset;
2791 struct object *object;
2794 struct in_pack {
2795 unsigned int alloc;
2796 unsigned int nr;
2797 struct in_pack_object *array;
2800 static void mark_in_pack_object(struct object *object, struct packed_git *p, struct in_pack *in_pack)
2802 in_pack->array[in_pack->nr].offset = find_pack_entry_one(object->oid.hash, p);
2803 in_pack->array[in_pack->nr].object = object;
2804 in_pack->nr++;
2808 * Compare the objects in the offset order, in order to emulate the
2809 * "git rev-list --objects" output that produced the pack originally.
2811 static int ofscmp(const void *a_, const void *b_)
2813 struct in_pack_object *a = (struct in_pack_object *)a_;
2814 struct in_pack_object *b = (struct in_pack_object *)b_;
2816 if (a->offset < b->offset)
2817 return -1;
2818 else if (a->offset > b->offset)
2819 return 1;
2820 else
2821 return oidcmp(&a->object->oid, &b->object->oid);
2824 static void add_objects_in_unpacked_packs(struct rev_info *revs)
2826 struct packed_git *p;
2827 struct in_pack in_pack;
2828 uint32_t i;
2830 memset(&in_pack, 0, sizeof(in_pack));
2832 for (p = get_packed_git(the_repository); p; p = p->next) {
2833 struct object_id oid;
2834 struct object *o;
2836 if (!p->pack_local || p->pack_keep || p->pack_keep_in_core)
2837 continue;
2838 if (open_pack_index(p))
2839 die("cannot open pack index");
2841 ALLOC_GROW(in_pack.array,
2842 in_pack.nr + p->num_objects,
2843 in_pack.alloc);
2845 for (i = 0; i < p->num_objects; i++) {
2846 nth_packed_object_oid(&oid, p, i);
2847 o = lookup_unknown_object(oid.hash);
2848 if (!(o->flags & OBJECT_ADDED))
2849 mark_in_pack_object(o, p, &in_pack);
2850 o->flags |= OBJECT_ADDED;
2854 if (in_pack.nr) {
2855 QSORT(in_pack.array, in_pack.nr, ofscmp);
2856 for (i = 0; i < in_pack.nr; i++) {
2857 struct object *o = in_pack.array[i].object;
2858 add_object_entry(&o->oid, o->type, "", 0);
2861 free(in_pack.array);
2864 static int add_loose_object(const struct object_id *oid, const char *path,
2865 void *data)
2867 enum object_type type = oid_object_info(the_repository, oid, NULL);
2869 if (type < 0) {
2870 warning("loose object at %s could not be examined", path);
2871 return 0;
2874 add_object_entry(oid, type, "", 0);
2875 return 0;
2879 * We actually don't even have to worry about reachability here.
2880 * add_object_entry will weed out duplicates, so we just add every
2881 * loose object we find.
2883 static void add_unreachable_loose_objects(void)
2885 for_each_loose_file_in_objdir(get_object_directory(),
2886 add_loose_object,
2887 NULL, NULL, NULL);
2890 static int has_sha1_pack_kept_or_nonlocal(const struct object_id *oid)
2892 static struct packed_git *last_found = (void *)1;
2893 struct packed_git *p;
2895 p = (last_found != (void *)1) ? last_found :
2896 get_packed_git(the_repository);
2898 while (p) {
2899 if ((!p->pack_local || p->pack_keep ||
2900 p->pack_keep_in_core) &&
2901 find_pack_entry_one(oid->hash, p)) {
2902 last_found = p;
2903 return 1;
2905 if (p == last_found)
2906 p = get_packed_git(the_repository);
2907 else
2908 p = p->next;
2909 if (p == last_found)
2910 p = p->next;
2912 return 0;
2916 * Store a list of sha1s that are should not be discarded
2917 * because they are either written too recently, or are
2918 * reachable from another object that was.
2920 * This is filled by get_object_list.
2922 static struct oid_array recent_objects;
2924 static int loosened_object_can_be_discarded(const struct object_id *oid,
2925 timestamp_t mtime)
2927 if (!unpack_unreachable_expiration)
2928 return 0;
2929 if (mtime > unpack_unreachable_expiration)
2930 return 0;
2931 if (oid_array_lookup(&recent_objects, oid) >= 0)
2932 return 0;
2933 return 1;
2936 static void loosen_unused_packed_objects(struct rev_info *revs)
2938 struct packed_git *p;
2939 uint32_t i;
2940 struct object_id oid;
2942 for (p = get_packed_git(the_repository); p; p = p->next) {
2943 if (!p->pack_local || p->pack_keep || p->pack_keep_in_core)
2944 continue;
2946 if (open_pack_index(p))
2947 die("cannot open pack index");
2949 for (i = 0; i < p->num_objects; i++) {
2950 nth_packed_object_oid(&oid, p, i);
2951 if (!packlist_find(&to_pack, oid.hash, NULL) &&
2952 !has_sha1_pack_kept_or_nonlocal(&oid) &&
2953 !loosened_object_can_be_discarded(&oid, p->mtime))
2954 if (force_object_loose(&oid, p->mtime))
2955 die("unable to force loose object");
2961 * This tracks any options which pack-reuse code expects to be on, or which a
2962 * reader of the pack might not understand, and which would therefore prevent
2963 * blind reuse of what we have on disk.
2965 static int pack_options_allow_reuse(void)
2967 return pack_to_stdout &&
2968 allow_ofs_delta &&
2969 !ignore_packed_keep_on_disk &&
2970 !ignore_packed_keep_in_core &&
2971 (!local || !have_non_local_packs) &&
2972 !incremental;
2975 static int get_object_list_from_bitmap(struct rev_info *revs)
2977 struct bitmap_index *bitmap_git;
2978 if (!(bitmap_git = prepare_bitmap_walk(revs)))
2979 return -1;
2981 if (pack_options_allow_reuse() &&
2982 !reuse_partial_packfile_from_bitmap(
2983 bitmap_git,
2984 &reuse_packfile,
2985 &reuse_packfile_objects,
2986 &reuse_packfile_offset)) {
2987 assert(reuse_packfile_objects);
2988 nr_result += reuse_packfile_objects;
2989 display_progress(progress_state, nr_result);
2992 traverse_bitmap_commit_list(bitmap_git, &add_object_entry_from_bitmap);
2993 free_bitmap_index(bitmap_git);
2994 return 0;
2997 static void record_recent_object(struct object *obj,
2998 const char *name,
2999 void *data)
3001 oid_array_append(&recent_objects, &obj->oid);
3004 static void record_recent_commit(struct commit *commit, void *data)
3006 oid_array_append(&recent_objects, &commit->object.oid);
3009 static void get_object_list(int ac, const char **av)
3011 struct rev_info revs;
3012 char line[1000];
3013 int flags = 0;
3015 init_revisions(&revs, NULL);
3016 save_commit_buffer = 0;
3017 setup_revisions(ac, av, &revs, NULL);
3019 /* make sure shallows are read */
3020 is_repository_shallow(the_repository);
3022 while (fgets(line, sizeof(line), stdin) != NULL) {
3023 int len = strlen(line);
3024 if (len && line[len - 1] == '\n')
3025 line[--len] = 0;
3026 if (!len)
3027 break;
3028 if (*line == '-') {
3029 if (!strcmp(line, "--not")) {
3030 flags ^= UNINTERESTING;
3031 write_bitmap_index = 0;
3032 continue;
3034 if (starts_with(line, "--shallow ")) {
3035 struct object_id oid;
3036 if (get_oid_hex(line + 10, &oid))
3037 die("not an SHA-1 '%s'", line + 10);
3038 register_shallow(the_repository, &oid);
3039 use_bitmap_index = 0;
3040 continue;
3042 die("not a rev '%s'", line);
3044 if (handle_revision_arg(line, &revs, flags, REVARG_CANNOT_BE_FILENAME))
3045 die("bad revision '%s'", line);
3048 if (use_bitmap_index && !get_object_list_from_bitmap(&revs))
3049 return;
3051 if (use_delta_islands)
3052 load_delta_islands();
3054 if (prepare_revision_walk(&revs))
3055 die("revision walk setup failed");
3056 mark_edges_uninteresting(&revs, show_edge);
3058 if (!fn_show_object)
3059 fn_show_object = show_object;
3060 traverse_commit_list_filtered(&filter_options, &revs,
3061 show_commit, fn_show_object, NULL,
3062 NULL);
3064 if (unpack_unreachable_expiration) {
3065 revs.ignore_missing_links = 1;
3066 if (add_unseen_recent_objects_to_traversal(&revs,
3067 unpack_unreachable_expiration))
3068 die("unable to add recent objects");
3069 if (prepare_revision_walk(&revs))
3070 die("revision walk setup failed");
3071 traverse_commit_list(&revs, record_recent_commit,
3072 record_recent_object, NULL);
3075 if (keep_unreachable)
3076 add_objects_in_unpacked_packs(&revs);
3077 if (pack_loose_unreachable)
3078 add_unreachable_loose_objects();
3079 if (unpack_unreachable)
3080 loosen_unused_packed_objects(&revs);
3082 oid_array_clear(&recent_objects);
3085 static void add_extra_kept_packs(const struct string_list *names)
3087 struct packed_git *p;
3089 if (!names->nr)
3090 return;
3092 for (p = get_packed_git(the_repository); p; p = p->next) {
3093 const char *name = basename(p->pack_name);
3094 int i;
3096 if (!p->pack_local)
3097 continue;
3099 for (i = 0; i < names->nr; i++)
3100 if (!fspathcmp(name, names->items[i].string))
3101 break;
3103 if (i < names->nr) {
3104 p->pack_keep_in_core = 1;
3105 ignore_packed_keep_in_core = 1;
3106 continue;
3111 static int option_parse_index_version(const struct option *opt,
3112 const char *arg, int unset)
3114 char *c;
3115 const char *val = arg;
3116 pack_idx_opts.version = strtoul(val, &c, 10);
3117 if (pack_idx_opts.version > 2)
3118 die(_("unsupported index version %s"), val);
3119 if (*c == ',' && c[1])
3120 pack_idx_opts.off32_limit = strtoul(c+1, &c, 0);
3121 if (*c || pack_idx_opts.off32_limit & 0x80000000)
3122 die(_("bad index version '%s'"), val);
3123 return 0;
3126 static int option_parse_unpack_unreachable(const struct option *opt,
3127 const char *arg, int unset)
3129 if (unset) {
3130 unpack_unreachable = 0;
3131 unpack_unreachable_expiration = 0;
3133 else {
3134 unpack_unreachable = 1;
3135 if (arg)
3136 unpack_unreachable_expiration = approxidate(arg);
3138 return 0;
3141 int cmd_pack_objects(int argc, const char **argv, const char *prefix)
3143 int use_internal_rev_list = 0;
3144 int thin = 0;
3145 int shallow = 0;
3146 int all_progress_implied = 0;
3147 struct argv_array rp = ARGV_ARRAY_INIT;
3148 int rev_list_unpacked = 0, rev_list_all = 0, rev_list_reflog = 0;
3149 int rev_list_index = 0;
3150 struct string_list keep_pack_list = STRING_LIST_INIT_NODUP;
3151 struct option pack_objects_options[] = {
3152 OPT_SET_INT('q', "quiet", &progress,
3153 N_("do not show progress meter"), 0),
3154 OPT_SET_INT(0, "progress", &progress,
3155 N_("show progress meter"), 1),
3156 OPT_SET_INT(0, "all-progress", &progress,
3157 N_("show progress meter during object writing phase"), 2),
3158 OPT_BOOL(0, "all-progress-implied",
3159 &all_progress_implied,
3160 N_("similar to --all-progress when progress meter is shown")),
3161 { OPTION_CALLBACK, 0, "index-version", NULL, N_("version[,offset]"),
3162 N_("write the pack index file in the specified idx format version"),
3163 0, option_parse_index_version },
3164 OPT_MAGNITUDE(0, "max-pack-size", &pack_size_limit,
3165 N_("maximum size of each output pack file")),
3166 OPT_BOOL(0, "local", &local,
3167 N_("ignore borrowed objects from alternate object store")),
3168 OPT_BOOL(0, "incremental", &incremental,
3169 N_("ignore packed objects")),
3170 OPT_INTEGER(0, "window", &window,
3171 N_("limit pack window by objects")),
3172 OPT_MAGNITUDE(0, "window-memory", &window_memory_limit,
3173 N_("limit pack window by memory in addition to object limit")),
3174 OPT_INTEGER(0, "depth", &depth,
3175 N_("maximum length of delta chain allowed in the resulting pack")),
3176 OPT_BOOL(0, "reuse-delta", &reuse_delta,
3177 N_("reuse existing deltas")),
3178 OPT_BOOL(0, "reuse-object", &reuse_object,
3179 N_("reuse existing objects")),
3180 OPT_BOOL(0, "delta-base-offset", &allow_ofs_delta,
3181 N_("use OFS_DELTA objects")),
3182 OPT_INTEGER(0, "threads", &delta_search_threads,
3183 N_("use threads when searching for best delta matches")),
3184 OPT_BOOL(0, "non-empty", &non_empty,
3185 N_("do not create an empty pack output")),
3186 OPT_BOOL(0, "revs", &use_internal_rev_list,
3187 N_("read revision arguments from standard input")),
3188 OPT_SET_INT_F(0, "unpacked", &rev_list_unpacked,
3189 N_("limit the objects to those that are not yet packed"),
3190 1, PARSE_OPT_NONEG),
3191 OPT_SET_INT_F(0, "all", &rev_list_all,
3192 N_("include objects reachable from any reference"),
3193 1, PARSE_OPT_NONEG),
3194 OPT_SET_INT_F(0, "reflog", &rev_list_reflog,
3195 N_("include objects referred by reflog entries"),
3196 1, PARSE_OPT_NONEG),
3197 OPT_SET_INT_F(0, "indexed-objects", &rev_list_index,
3198 N_("include objects referred to by the index"),
3199 1, PARSE_OPT_NONEG),
3200 OPT_BOOL(0, "stdout", &pack_to_stdout,
3201 N_("output pack to stdout")),
3202 OPT_BOOL(0, "include-tag", &include_tag,
3203 N_("include tag objects that refer to objects to be packed")),
3204 OPT_BOOL(0, "keep-unreachable", &keep_unreachable,
3205 N_("keep unreachable objects")),
3206 OPT_BOOL(0, "pack-loose-unreachable", &pack_loose_unreachable,
3207 N_("pack loose unreachable objects")),
3208 { OPTION_CALLBACK, 0, "unpack-unreachable", NULL, N_("time"),
3209 N_("unpack unreachable objects newer than <time>"),
3210 PARSE_OPT_OPTARG, option_parse_unpack_unreachable },
3211 OPT_BOOL(0, "thin", &thin,
3212 N_("create thin packs")),
3213 OPT_BOOL(0, "shallow", &shallow,
3214 N_("create packs suitable for shallow fetches")),
3215 OPT_BOOL(0, "honor-pack-keep", &ignore_packed_keep_on_disk,
3216 N_("ignore packs that have companion .keep file")),
3217 OPT_STRING_LIST(0, "keep-pack", &keep_pack_list, N_("name"),
3218 N_("ignore this pack")),
3219 OPT_INTEGER(0, "compression", &pack_compression_level,
3220 N_("pack compression level")),
3221 OPT_SET_INT(0, "keep-true-parents", &grafts_replace_parents,
3222 N_("do not hide commits by grafts"), 0),
3223 OPT_BOOL(0, "use-bitmap-index", &use_bitmap_index,
3224 N_("use a bitmap index if available to speed up counting objects")),
3225 OPT_BOOL(0, "write-bitmap-index", &write_bitmap_index,
3226 N_("write a bitmap index together with the pack index")),
3227 OPT_PARSE_LIST_OBJECTS_FILTER(&filter_options),
3228 { OPTION_CALLBACK, 0, "missing", NULL, N_("action"),
3229 N_("handling for missing objects"), PARSE_OPT_NONEG,
3230 option_parse_missing_action },
3231 OPT_BOOL(0, "exclude-promisor-objects", &exclude_promisor_objects,
3232 N_("do not pack objects in promisor packfiles")),
3233 OPT_BOOL(0, "delta-islands", &use_delta_islands,
3234 N_("respect islands during delta compression")),
3235 OPT_END(),
3238 if (DFS_NUM_STATES > (1 << OE_DFS_STATE_BITS))
3239 BUG("too many dfs states, increase OE_DFS_STATE_BITS");
3241 check_replace_refs = 0;
3243 reset_pack_idx_option(&pack_idx_opts);
3244 git_config(git_pack_config, NULL);
3246 progress = isatty(2);
3247 argc = parse_options(argc, argv, prefix, pack_objects_options,
3248 pack_usage, 0);
3250 if (argc) {
3251 base_name = argv[0];
3252 argc--;
3254 if (pack_to_stdout != !base_name || argc)
3255 usage_with_options(pack_usage, pack_objects_options);
3257 if (depth >= (1 << OE_DEPTH_BITS)) {
3258 warning(_("delta chain depth %d is too deep, forcing %d"),
3259 depth, (1 << OE_DEPTH_BITS) - 1);
3260 depth = (1 << OE_DEPTH_BITS) - 1;
3262 if (cache_max_small_delta_size >= (1U << OE_Z_DELTA_BITS)) {
3263 warning(_("pack.deltaCacheLimit is too high, forcing %d"),
3264 (1U << OE_Z_DELTA_BITS) - 1);
3265 cache_max_small_delta_size = (1U << OE_Z_DELTA_BITS) - 1;
3268 argv_array_push(&rp, "pack-objects");
3269 if (thin) {
3270 use_internal_rev_list = 1;
3271 argv_array_push(&rp, shallow
3272 ? "--objects-edge-aggressive"
3273 : "--objects-edge");
3274 } else
3275 argv_array_push(&rp, "--objects");
3277 if (rev_list_all) {
3278 use_internal_rev_list = 1;
3279 argv_array_push(&rp, "--all");
3281 if (rev_list_reflog) {
3282 use_internal_rev_list = 1;
3283 argv_array_push(&rp, "--reflog");
3285 if (rev_list_index) {
3286 use_internal_rev_list = 1;
3287 argv_array_push(&rp, "--indexed-objects");
3289 if (rev_list_unpacked) {
3290 use_internal_rev_list = 1;
3291 argv_array_push(&rp, "--unpacked");
3294 if (exclude_promisor_objects) {
3295 use_internal_rev_list = 1;
3296 fetch_if_missing = 0;
3297 argv_array_push(&rp, "--exclude-promisor-objects");
3299 if (unpack_unreachable || keep_unreachable || pack_loose_unreachable)
3300 use_internal_rev_list = 1;
3302 if (!reuse_object)
3303 reuse_delta = 0;
3304 if (pack_compression_level == -1)
3305 pack_compression_level = Z_DEFAULT_COMPRESSION;
3306 else if (pack_compression_level < 0 || pack_compression_level > Z_BEST_COMPRESSION)
3307 die("bad pack compression level %d", pack_compression_level);
3309 if (!delta_search_threads) /* --threads=0 means autodetect */
3310 delta_search_threads = online_cpus();
3312 #ifdef NO_PTHREADS
3313 if (delta_search_threads != 1)
3314 warning("no threads support, ignoring --threads");
3315 #endif
3316 if (!pack_to_stdout && !pack_size_limit)
3317 pack_size_limit = pack_size_limit_cfg;
3318 if (pack_to_stdout && pack_size_limit)
3319 die("--max-pack-size cannot be used to build a pack for transfer.");
3320 if (pack_size_limit && pack_size_limit < 1024*1024) {
3321 warning("minimum pack size limit is 1 MiB");
3322 pack_size_limit = 1024*1024;
3325 if (!pack_to_stdout && thin)
3326 die("--thin cannot be used to build an indexable pack.");
3328 if (keep_unreachable && unpack_unreachable)
3329 die("--keep-unreachable and --unpack-unreachable are incompatible.");
3330 if (!rev_list_all || !rev_list_reflog || !rev_list_index)
3331 unpack_unreachable_expiration = 0;
3333 if (filter_options.choice) {
3334 if (!pack_to_stdout)
3335 die("cannot use --filter without --stdout.");
3336 use_bitmap_index = 0;
3340 * "soft" reasons not to use bitmaps - for on-disk repack by default we want
3342 * - to produce good pack (with bitmap index not-yet-packed objects are
3343 * packed in suboptimal order).
3345 * - to use more robust pack-generation codepath (avoiding possible
3346 * bugs in bitmap code and possible bitmap index corruption).
3348 if (!pack_to_stdout)
3349 use_bitmap_index_default = 0;
3351 if (use_bitmap_index < 0)
3352 use_bitmap_index = use_bitmap_index_default;
3354 /* "hard" reasons not to use bitmaps; these just won't work at all */
3355 if (!use_internal_rev_list || (!pack_to_stdout && write_bitmap_index) || is_repository_shallow(the_repository))
3356 use_bitmap_index = 0;
3358 if (pack_to_stdout || !rev_list_all)
3359 write_bitmap_index = 0;
3361 if (use_delta_islands)
3362 argv_array_push(&rp, "--topo-order");
3364 if (progress && all_progress_implied)
3365 progress = 2;
3367 add_extra_kept_packs(&keep_pack_list);
3368 if (ignore_packed_keep_on_disk) {
3369 struct packed_git *p;
3370 for (p = get_packed_git(the_repository); p; p = p->next)
3371 if (p->pack_local && p->pack_keep)
3372 break;
3373 if (!p) /* no keep-able packs found */
3374 ignore_packed_keep_on_disk = 0;
3376 if (local) {
3378 * unlike ignore_packed_keep_on_disk above, we do not
3379 * want to unset "local" based on looking at packs, as
3380 * it also covers non-local objects
3382 struct packed_git *p;
3383 for (p = get_packed_git(the_repository); p; p = p->next) {
3384 if (!p->pack_local) {
3385 have_non_local_packs = 1;
3386 break;
3391 prepare_packing_data(&to_pack);
3393 if (progress)
3394 progress_state = start_progress(_("Enumerating objects"), 0);
3395 if (!use_internal_rev_list)
3396 read_object_list_from_stdin();
3397 else {
3398 get_object_list(rp.argc, rp.argv);
3399 argv_array_clear(&rp);
3401 cleanup_preferred_base();
3402 if (include_tag && nr_result)
3403 for_each_ref(add_ref_tag, NULL);
3404 stop_progress(&progress_state);
3406 if (non_empty && !nr_result)
3407 return 0;
3408 if (nr_result)
3409 prepare_pack(window, depth);
3410 write_pack_file();
3411 if (progress)
3412 fprintf(stderr, "Total %"PRIu32" (delta %"PRIu32"),"
3413 " reused %"PRIu32" (delta %"PRIu32")\n",
3414 written, written_delta, reused, reused_delta);
3415 return 0;