Merge branch 'en/incl-forward-decl'
[git/raj.git] / builtin / pack-objects.c
blob0d80dee2ba1ad82fd21622f73dac86b6010da4b6
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 "reachable.h"
28 #include "sha1-array.h"
29 #include "argv-array.h"
30 #include "list.h"
31 #include "packfile.h"
32 #include "object-store.h"
33 #include "dir.h"
35 #define IN_PACK(obj) oe_in_pack(&to_pack, obj)
36 #define SIZE(obj) oe_size(&to_pack, obj)
37 #define SET_SIZE(obj,size) oe_set_size(&to_pack, obj, size)
38 #define DELTA_SIZE(obj) oe_delta_size(&to_pack, obj)
39 #define DELTA(obj) oe_delta(&to_pack, obj)
40 #define DELTA_CHILD(obj) oe_delta_child(&to_pack, obj)
41 #define DELTA_SIBLING(obj) oe_delta_sibling(&to_pack, obj)
42 #define SET_DELTA(obj, val) oe_set_delta(&to_pack, obj, val)
43 #define SET_DELTA_SIZE(obj, val) oe_set_delta_size(&to_pack, obj, val)
44 #define SET_DELTA_CHILD(obj, val) oe_set_delta_child(&to_pack, obj, val)
45 #define SET_DELTA_SIBLING(obj, val) oe_set_delta_sibling(&to_pack, obj, val)
47 static const char *pack_usage[] = {
48 N_("git pack-objects --stdout [<options>...] [< <ref-list> | < <object-list>]"),
49 N_("git pack-objects [<options>...] <base-name> [< <ref-list> | < <object-list>]"),
50 NULL
54 * Objects we are going to pack are collected in the `to_pack` structure.
55 * It contains an array (dynamically expanded) of the object data, and a map
56 * that can resolve SHA1s to their position in the array.
58 static struct packing_data to_pack;
60 static struct pack_idx_entry **written_list;
61 static uint32_t nr_result, nr_written, nr_seen;
63 static int non_empty;
64 static int reuse_delta = 1, reuse_object = 1;
65 static int keep_unreachable, unpack_unreachable, include_tag;
66 static timestamp_t unpack_unreachable_expiration;
67 static int pack_loose_unreachable;
68 static int local;
69 static int have_non_local_packs;
70 static int incremental;
71 static int ignore_packed_keep_on_disk;
72 static int ignore_packed_keep_in_core;
73 static int allow_ofs_delta;
74 static struct pack_idx_option pack_idx_opts;
75 static const char *base_name;
76 static int progress = 1;
77 static int window = 10;
78 static unsigned long pack_size_limit;
79 static int depth = 50;
80 static int delta_search_threads;
81 static int pack_to_stdout;
82 static int num_preferred_base;
83 static struct progress *progress_state;
85 static struct packed_git *reuse_packfile;
86 static uint32_t reuse_packfile_objects;
87 static off_t reuse_packfile_offset;
89 static int use_bitmap_index_default = 1;
90 static int use_bitmap_index = -1;
91 static int write_bitmap_index;
92 static uint16_t write_bitmap_options;
94 static int exclude_promisor_objects;
96 static unsigned long delta_cache_size = 0;
97 static unsigned long max_delta_cache_size = DEFAULT_DELTA_CACHE_SIZE;
98 static unsigned long cache_max_small_delta_size = 1000;
100 static unsigned long window_memory_limit = 0;
102 static struct list_objects_filter_options filter_options;
104 enum missing_action {
105 MA_ERROR = 0, /* fail if any missing objects are encountered */
106 MA_ALLOW_ANY, /* silently allow ALL missing objects */
107 MA_ALLOW_PROMISOR, /* silently allow all missing PROMISOR objects */
109 static enum missing_action arg_missing_action;
110 static show_object_fn fn_show_object;
113 * stats
115 static uint32_t written, written_delta;
116 static uint32_t reused, reused_delta;
119 * Indexed commits
121 static struct commit **indexed_commits;
122 static unsigned int indexed_commits_nr;
123 static unsigned int indexed_commits_alloc;
125 static void index_commit_for_bitmap(struct commit *commit)
127 if (indexed_commits_nr >= indexed_commits_alloc) {
128 indexed_commits_alloc = (indexed_commits_alloc + 32) * 2;
129 REALLOC_ARRAY(indexed_commits, indexed_commits_alloc);
132 indexed_commits[indexed_commits_nr++] = commit;
135 static void *get_delta(struct object_entry *entry)
137 unsigned long size, base_size, delta_size;
138 void *buf, *base_buf, *delta_buf;
139 enum object_type type;
141 buf = read_object_file(&entry->idx.oid, &type, &size);
142 if (!buf)
143 die(_("unable to read %s"), oid_to_hex(&entry->idx.oid));
144 base_buf = read_object_file(&DELTA(entry)->idx.oid, &type,
145 &base_size);
146 if (!base_buf)
147 die("unable to read %s",
148 oid_to_hex(&DELTA(entry)->idx.oid));
149 delta_buf = diff_delta(base_buf, base_size,
150 buf, size, &delta_size, 0);
152 * We succesfully computed this delta once but dropped it for
153 * memory reasons. Something is very wrong if this time we
154 * recompute and create a different delta.
156 if (!delta_buf || delta_size != DELTA_SIZE(entry))
157 BUG("delta size changed");
158 free(buf);
159 free(base_buf);
160 return delta_buf;
163 static unsigned long do_compress(void **pptr, unsigned long size)
165 git_zstream stream;
166 void *in, *out;
167 unsigned long maxsize;
169 git_deflate_init(&stream, pack_compression_level);
170 maxsize = git_deflate_bound(&stream, size);
172 in = *pptr;
173 out = xmalloc(maxsize);
174 *pptr = out;
176 stream.next_in = in;
177 stream.avail_in = size;
178 stream.next_out = out;
179 stream.avail_out = maxsize;
180 while (git_deflate(&stream, Z_FINISH) == Z_OK)
181 ; /* nothing */
182 git_deflate_end(&stream);
184 free(in);
185 return stream.total_out;
188 static unsigned long write_large_blob_data(struct git_istream *st, struct hashfile *f,
189 const struct object_id *oid)
191 git_zstream stream;
192 unsigned char ibuf[1024 * 16];
193 unsigned char obuf[1024 * 16];
194 unsigned long olen = 0;
196 git_deflate_init(&stream, pack_compression_level);
198 for (;;) {
199 ssize_t readlen;
200 int zret = Z_OK;
201 readlen = read_istream(st, ibuf, sizeof(ibuf));
202 if (readlen == -1)
203 die(_("unable to read %s"), oid_to_hex(oid));
205 stream.next_in = ibuf;
206 stream.avail_in = readlen;
207 while ((stream.avail_in || readlen == 0) &&
208 (zret == Z_OK || zret == Z_BUF_ERROR)) {
209 stream.next_out = obuf;
210 stream.avail_out = sizeof(obuf);
211 zret = git_deflate(&stream, readlen ? 0 : Z_FINISH);
212 hashwrite(f, obuf, stream.next_out - obuf);
213 olen += stream.next_out - obuf;
215 if (stream.avail_in)
216 die(_("deflate error (%d)"), zret);
217 if (readlen == 0) {
218 if (zret != Z_STREAM_END)
219 die(_("deflate error (%d)"), zret);
220 break;
223 git_deflate_end(&stream);
224 return olen;
228 * we are going to reuse the existing object data as is. make
229 * sure it is not corrupt.
231 static int check_pack_inflate(struct packed_git *p,
232 struct pack_window **w_curs,
233 off_t offset,
234 off_t len,
235 unsigned long expect)
237 git_zstream stream;
238 unsigned char fakebuf[4096], *in;
239 int st;
241 memset(&stream, 0, sizeof(stream));
242 git_inflate_init(&stream);
243 do {
244 in = use_pack(p, w_curs, offset, &stream.avail_in);
245 stream.next_in = in;
246 stream.next_out = fakebuf;
247 stream.avail_out = sizeof(fakebuf);
248 st = git_inflate(&stream, Z_FINISH);
249 offset += stream.next_in - in;
250 } while (st == Z_OK || st == Z_BUF_ERROR);
251 git_inflate_end(&stream);
252 return (st == Z_STREAM_END &&
253 stream.total_out == expect &&
254 stream.total_in == len) ? 0 : -1;
257 static void copy_pack_data(struct hashfile *f,
258 struct packed_git *p,
259 struct pack_window **w_curs,
260 off_t offset,
261 off_t len)
263 unsigned char *in;
264 unsigned long avail;
266 while (len) {
267 in = use_pack(p, w_curs, offset, &avail);
268 if (avail > len)
269 avail = (unsigned long)len;
270 hashwrite(f, in, avail);
271 offset += avail;
272 len -= avail;
276 /* Return 0 if we will bust the pack-size limit */
277 static unsigned long write_no_reuse_object(struct hashfile *f, struct object_entry *entry,
278 unsigned long limit, int usable_delta)
280 unsigned long size, datalen;
281 unsigned char header[MAX_PACK_OBJECT_HEADER],
282 dheader[MAX_PACK_OBJECT_HEADER];
283 unsigned hdrlen;
284 enum object_type type;
285 void *buf;
286 struct git_istream *st = NULL;
287 const unsigned hashsz = the_hash_algo->rawsz;
289 if (!usable_delta) {
290 if (oe_type(entry) == OBJ_BLOB &&
291 oe_size_greater_than(&to_pack, entry, big_file_threshold) &&
292 (st = open_istream(&entry->idx.oid, &type, &size, NULL)) != NULL)
293 buf = NULL;
294 else {
295 buf = read_object_file(&entry->idx.oid, &type, &size);
296 if (!buf)
297 die(_("unable to read %s"),
298 oid_to_hex(&entry->idx.oid));
301 * make sure no cached delta data remains from a
302 * previous attempt before a pack split occurred.
304 FREE_AND_NULL(entry->delta_data);
305 entry->z_delta_size = 0;
306 } else if (entry->delta_data) {
307 size = DELTA_SIZE(entry);
308 buf = entry->delta_data;
309 entry->delta_data = NULL;
310 type = (allow_ofs_delta && DELTA(entry)->idx.offset) ?
311 OBJ_OFS_DELTA : OBJ_REF_DELTA;
312 } else {
313 buf = get_delta(entry);
314 size = DELTA_SIZE(entry);
315 type = (allow_ofs_delta && DELTA(entry)->idx.offset) ?
316 OBJ_OFS_DELTA : OBJ_REF_DELTA;
319 if (st) /* large blob case, just assume we don't compress well */
320 datalen = size;
321 else if (entry->z_delta_size)
322 datalen = entry->z_delta_size;
323 else
324 datalen = do_compress(&buf, size);
327 * The object header is a byte of 'type' followed by zero or
328 * more bytes of length.
330 hdrlen = encode_in_pack_object_header(header, sizeof(header),
331 type, size);
333 if (type == OBJ_OFS_DELTA) {
335 * Deltas with relative base contain an additional
336 * encoding of the relative offset for the delta
337 * base from this object's position in the pack.
339 off_t ofs = entry->idx.offset - DELTA(entry)->idx.offset;
340 unsigned pos = sizeof(dheader) - 1;
341 dheader[pos] = ofs & 127;
342 while (ofs >>= 7)
343 dheader[--pos] = 128 | (--ofs & 127);
344 if (limit && hdrlen + sizeof(dheader) - pos + datalen + hashsz >= limit) {
345 if (st)
346 close_istream(st);
347 free(buf);
348 return 0;
350 hashwrite(f, header, hdrlen);
351 hashwrite(f, dheader + pos, sizeof(dheader) - pos);
352 hdrlen += sizeof(dheader) - pos;
353 } else if (type == OBJ_REF_DELTA) {
355 * Deltas with a base reference contain
356 * additional bytes for the base object ID.
358 if (limit && hdrlen + hashsz + datalen + hashsz >= limit) {
359 if (st)
360 close_istream(st);
361 free(buf);
362 return 0;
364 hashwrite(f, header, hdrlen);
365 hashwrite(f, DELTA(entry)->idx.oid.hash, hashsz);
366 hdrlen += hashsz;
367 } else {
368 if (limit && hdrlen + datalen + hashsz >= limit) {
369 if (st)
370 close_istream(st);
371 free(buf);
372 return 0;
374 hashwrite(f, header, hdrlen);
376 if (st) {
377 datalen = write_large_blob_data(st, f, &entry->idx.oid);
378 close_istream(st);
379 } else {
380 hashwrite(f, buf, datalen);
381 free(buf);
384 return hdrlen + datalen;
387 /* Return 0 if we will bust the pack-size limit */
388 static off_t write_reuse_object(struct hashfile *f, struct object_entry *entry,
389 unsigned long limit, int usable_delta)
391 struct packed_git *p = IN_PACK(entry);
392 struct pack_window *w_curs = NULL;
393 struct revindex_entry *revidx;
394 off_t offset;
395 enum object_type type = oe_type(entry);
396 off_t datalen;
397 unsigned char header[MAX_PACK_OBJECT_HEADER],
398 dheader[MAX_PACK_OBJECT_HEADER];
399 unsigned hdrlen;
400 const unsigned hashsz = the_hash_algo->rawsz;
401 unsigned long entry_size = SIZE(entry);
403 if (DELTA(entry))
404 type = (allow_ofs_delta && DELTA(entry)->idx.offset) ?
405 OBJ_OFS_DELTA : OBJ_REF_DELTA;
406 hdrlen = encode_in_pack_object_header(header, sizeof(header),
407 type, entry_size);
409 offset = entry->in_pack_offset;
410 revidx = find_pack_revindex(p, offset);
411 datalen = revidx[1].offset - offset;
412 if (!pack_to_stdout && p->index_version > 1 &&
413 check_pack_crc(p, &w_curs, offset, datalen, revidx->nr)) {
414 error(_("bad packed object CRC for %s"),
415 oid_to_hex(&entry->idx.oid));
416 unuse_pack(&w_curs);
417 return write_no_reuse_object(f, entry, limit, usable_delta);
420 offset += entry->in_pack_header_size;
421 datalen -= entry->in_pack_header_size;
423 if (!pack_to_stdout && p->index_version == 1 &&
424 check_pack_inflate(p, &w_curs, offset, datalen, entry_size)) {
425 error(_("corrupt packed object for %s"),
426 oid_to_hex(&entry->idx.oid));
427 unuse_pack(&w_curs);
428 return write_no_reuse_object(f, entry, limit, usable_delta);
431 if (type == OBJ_OFS_DELTA) {
432 off_t ofs = entry->idx.offset - DELTA(entry)->idx.offset;
433 unsigned pos = sizeof(dheader) - 1;
434 dheader[pos] = ofs & 127;
435 while (ofs >>= 7)
436 dheader[--pos] = 128 | (--ofs & 127);
437 if (limit && hdrlen + sizeof(dheader) - pos + datalen + hashsz >= limit) {
438 unuse_pack(&w_curs);
439 return 0;
441 hashwrite(f, header, hdrlen);
442 hashwrite(f, dheader + pos, sizeof(dheader) - pos);
443 hdrlen += sizeof(dheader) - pos;
444 reused_delta++;
445 } else if (type == OBJ_REF_DELTA) {
446 if (limit && hdrlen + hashsz + datalen + hashsz >= limit) {
447 unuse_pack(&w_curs);
448 return 0;
450 hashwrite(f, header, hdrlen);
451 hashwrite(f, DELTA(entry)->idx.oid.hash, hashsz);
452 hdrlen += hashsz;
453 reused_delta++;
454 } else {
455 if (limit && hdrlen + datalen + hashsz >= limit) {
456 unuse_pack(&w_curs);
457 return 0;
459 hashwrite(f, header, hdrlen);
461 copy_pack_data(f, p, &w_curs, offset, datalen);
462 unuse_pack(&w_curs);
463 reused++;
464 return hdrlen + datalen;
467 /* Return 0 if we will bust the pack-size limit */
468 static off_t write_object(struct hashfile *f,
469 struct object_entry *entry,
470 off_t write_offset)
472 unsigned long limit;
473 off_t len;
474 int usable_delta, to_reuse;
476 if (!pack_to_stdout)
477 crc32_begin(f);
479 /* apply size limit if limited packsize and not first object */
480 if (!pack_size_limit || !nr_written)
481 limit = 0;
482 else if (pack_size_limit <= write_offset)
484 * the earlier object did not fit the limit; avoid
485 * mistaking this with unlimited (i.e. limit = 0).
487 limit = 1;
488 else
489 limit = pack_size_limit - write_offset;
491 if (!DELTA(entry))
492 usable_delta = 0; /* no delta */
493 else if (!pack_size_limit)
494 usable_delta = 1; /* unlimited packfile */
495 else if (DELTA(entry)->idx.offset == (off_t)-1)
496 usable_delta = 0; /* base was written to another pack */
497 else if (DELTA(entry)->idx.offset)
498 usable_delta = 1; /* base already exists in this pack */
499 else
500 usable_delta = 0; /* base could end up in another pack */
502 if (!reuse_object)
503 to_reuse = 0; /* explicit */
504 else if (!IN_PACK(entry))
505 to_reuse = 0; /* can't reuse what we don't have */
506 else if (oe_type(entry) == OBJ_REF_DELTA ||
507 oe_type(entry) == OBJ_OFS_DELTA)
508 /* check_object() decided it for us ... */
509 to_reuse = usable_delta;
510 /* ... but pack split may override that */
511 else if (oe_type(entry) != entry->in_pack_type)
512 to_reuse = 0; /* pack has delta which is unusable */
513 else if (DELTA(entry))
514 to_reuse = 0; /* we want to pack afresh */
515 else
516 to_reuse = 1; /* we have it in-pack undeltified,
517 * and we do not need to deltify it.
520 if (!to_reuse)
521 len = write_no_reuse_object(f, entry, limit, usable_delta);
522 else
523 len = write_reuse_object(f, entry, limit, usable_delta);
524 if (!len)
525 return 0;
527 if (usable_delta)
528 written_delta++;
529 written++;
530 if (!pack_to_stdout)
531 entry->idx.crc32 = crc32_end(f);
532 return len;
535 enum write_one_status {
536 WRITE_ONE_SKIP = -1, /* already written */
537 WRITE_ONE_BREAK = 0, /* writing this will bust the limit; not written */
538 WRITE_ONE_WRITTEN = 1, /* normal */
539 WRITE_ONE_RECURSIVE = 2 /* already scheduled to be written */
542 static enum write_one_status write_one(struct hashfile *f,
543 struct object_entry *e,
544 off_t *offset)
546 off_t size;
547 int recursing;
550 * we set offset to 1 (which is an impossible value) to mark
551 * the fact that this object is involved in "write its base
552 * first before writing a deltified object" recursion.
554 recursing = (e->idx.offset == 1);
555 if (recursing) {
556 warning(_("recursive delta detected for object %s"),
557 oid_to_hex(&e->idx.oid));
558 return WRITE_ONE_RECURSIVE;
559 } else if (e->idx.offset || e->preferred_base) {
560 /* offset is non zero if object is written already. */
561 return WRITE_ONE_SKIP;
564 /* if we are deltified, write out base object first. */
565 if (DELTA(e)) {
566 e->idx.offset = 1; /* now recurse */
567 switch (write_one(f, DELTA(e), offset)) {
568 case WRITE_ONE_RECURSIVE:
569 /* we cannot depend on this one */
570 SET_DELTA(e, NULL);
571 break;
572 default:
573 break;
574 case WRITE_ONE_BREAK:
575 e->idx.offset = recursing;
576 return WRITE_ONE_BREAK;
580 e->idx.offset = *offset;
581 size = write_object(f, e, *offset);
582 if (!size) {
583 e->idx.offset = recursing;
584 return WRITE_ONE_BREAK;
586 written_list[nr_written++] = &e->idx;
588 /* make sure off_t is sufficiently large not to wrap */
589 if (signed_add_overflows(*offset, size))
590 die(_("pack too large for current definition of off_t"));
591 *offset += size;
592 return WRITE_ONE_WRITTEN;
595 static int mark_tagged(const char *path, const struct object_id *oid, int flag,
596 void *cb_data)
598 struct object_id peeled;
599 struct object_entry *entry = packlist_find(&to_pack, oid->hash, NULL);
601 if (entry)
602 entry->tagged = 1;
603 if (!peel_ref(path, &peeled)) {
604 entry = packlist_find(&to_pack, peeled.hash, NULL);
605 if (entry)
606 entry->tagged = 1;
608 return 0;
611 static inline void add_to_write_order(struct object_entry **wo,
612 unsigned int *endp,
613 struct object_entry *e)
615 if (e->filled)
616 return;
617 wo[(*endp)++] = e;
618 e->filled = 1;
621 static void add_descendants_to_write_order(struct object_entry **wo,
622 unsigned int *endp,
623 struct object_entry *e)
625 int add_to_order = 1;
626 while (e) {
627 if (add_to_order) {
628 struct object_entry *s;
629 /* add this node... */
630 add_to_write_order(wo, endp, e);
631 /* all its siblings... */
632 for (s = DELTA_SIBLING(e); s; s = DELTA_SIBLING(s)) {
633 add_to_write_order(wo, endp, s);
636 /* drop down a level to add left subtree nodes if possible */
637 if (DELTA_CHILD(e)) {
638 add_to_order = 1;
639 e = DELTA_CHILD(e);
640 } else {
641 add_to_order = 0;
642 /* our sibling might have some children, it is next */
643 if (DELTA_SIBLING(e)) {
644 e = DELTA_SIBLING(e);
645 continue;
647 /* go back to our parent node */
648 e = DELTA(e);
649 while (e && !DELTA_SIBLING(e)) {
650 /* we're on the right side of a subtree, keep
651 * going up until we can go right again */
652 e = DELTA(e);
654 if (!e) {
655 /* done- we hit our original root node */
656 return;
658 /* pass it off to sibling at this level */
659 e = DELTA_SIBLING(e);
664 static void add_family_to_write_order(struct object_entry **wo,
665 unsigned int *endp,
666 struct object_entry *e)
668 struct object_entry *root;
670 for (root = e; DELTA(root); root = DELTA(root))
671 ; /* nothing */
672 add_descendants_to_write_order(wo, endp, root);
675 static struct object_entry **compute_write_order(void)
677 unsigned int i, wo_end, last_untagged;
679 struct object_entry **wo;
680 struct object_entry *objects = to_pack.objects;
682 for (i = 0; i < to_pack.nr_objects; i++) {
683 objects[i].tagged = 0;
684 objects[i].filled = 0;
685 SET_DELTA_CHILD(&objects[i], NULL);
686 SET_DELTA_SIBLING(&objects[i], NULL);
690 * Fully connect delta_child/delta_sibling network.
691 * Make sure delta_sibling is sorted in the original
692 * recency order.
694 for (i = to_pack.nr_objects; i > 0;) {
695 struct object_entry *e = &objects[--i];
696 if (!DELTA(e))
697 continue;
698 /* Mark me as the first child */
699 e->delta_sibling_idx = DELTA(e)->delta_child_idx;
700 SET_DELTA_CHILD(DELTA(e), e);
704 * Mark objects that are at the tip of tags.
706 for_each_tag_ref(mark_tagged, NULL);
709 * Give the objects in the original recency order until
710 * we see a tagged tip.
712 ALLOC_ARRAY(wo, to_pack.nr_objects);
713 for (i = wo_end = 0; i < to_pack.nr_objects; i++) {
714 if (objects[i].tagged)
715 break;
716 add_to_write_order(wo, &wo_end, &objects[i]);
718 last_untagged = i;
721 * Then fill all the tagged tips.
723 for (; i < to_pack.nr_objects; i++) {
724 if (objects[i].tagged)
725 add_to_write_order(wo, &wo_end, &objects[i]);
729 * And then all remaining commits and tags.
731 for (i = last_untagged; i < to_pack.nr_objects; i++) {
732 if (oe_type(&objects[i]) != OBJ_COMMIT &&
733 oe_type(&objects[i]) != OBJ_TAG)
734 continue;
735 add_to_write_order(wo, &wo_end, &objects[i]);
739 * And then all the trees.
741 for (i = last_untagged; i < to_pack.nr_objects; i++) {
742 if (oe_type(&objects[i]) != OBJ_TREE)
743 continue;
744 add_to_write_order(wo, &wo_end, &objects[i]);
748 * Finally all the rest in really tight order
750 for (i = last_untagged; i < to_pack.nr_objects; i++) {
751 if (!objects[i].filled)
752 add_family_to_write_order(wo, &wo_end, &objects[i]);
755 if (wo_end != to_pack.nr_objects)
756 die(_("ordered %u objects, expected %"PRIu32),
757 wo_end, to_pack.nr_objects);
759 return wo;
762 static off_t write_reused_pack(struct hashfile *f)
764 unsigned char buffer[8192];
765 off_t to_write, total;
766 int fd;
768 if (!is_pack_valid(reuse_packfile))
769 die(_("packfile is invalid: %s"), reuse_packfile->pack_name);
771 fd = git_open(reuse_packfile->pack_name);
772 if (fd < 0)
773 die_errno(_("unable to open packfile for reuse: %s"),
774 reuse_packfile->pack_name);
776 if (lseek(fd, sizeof(struct pack_header), SEEK_SET) == -1)
777 die_errno(_("unable to seek in reused packfile"));
779 if (reuse_packfile_offset < 0)
780 reuse_packfile_offset = reuse_packfile->pack_size - the_hash_algo->rawsz;
782 total = to_write = reuse_packfile_offset - sizeof(struct pack_header);
784 while (to_write) {
785 int read_pack = xread(fd, buffer, sizeof(buffer));
787 if (read_pack <= 0)
788 die_errno(_("unable to read from reused packfile"));
790 if (read_pack > to_write)
791 read_pack = to_write;
793 hashwrite(f, buffer, read_pack);
794 to_write -= read_pack;
797 * We don't know the actual number of objects written,
798 * only how many bytes written, how many bytes total, and
799 * how many objects total. So we can fake it by pretending all
800 * objects we are writing are the same size. This gives us a
801 * smooth progress meter, and at the end it matches the true
802 * answer.
804 written = reuse_packfile_objects *
805 (((double)(total - to_write)) / total);
806 display_progress(progress_state, written);
809 close(fd);
810 written = reuse_packfile_objects;
811 display_progress(progress_state, written);
812 return reuse_packfile_offset - sizeof(struct pack_header);
815 static const char no_split_warning[] = N_(
816 "disabling bitmap writing, packs are split due to pack.packSizeLimit"
819 static void write_pack_file(void)
821 uint32_t i = 0, j;
822 struct hashfile *f;
823 off_t offset;
824 uint32_t nr_remaining = nr_result;
825 time_t last_mtime = 0;
826 struct object_entry **write_order;
828 if (progress > pack_to_stdout)
829 progress_state = start_progress(_("Writing objects"), nr_result);
830 ALLOC_ARRAY(written_list, to_pack.nr_objects);
831 write_order = compute_write_order();
833 do {
834 struct object_id oid;
835 char *pack_tmp_name = NULL;
837 if (pack_to_stdout)
838 f = hashfd_throughput(1, "<stdout>", progress_state);
839 else
840 f = create_tmp_packfile(&pack_tmp_name);
842 offset = write_pack_header(f, nr_remaining);
844 if (reuse_packfile) {
845 off_t packfile_size;
846 assert(pack_to_stdout);
848 packfile_size = write_reused_pack(f);
849 offset += packfile_size;
852 nr_written = 0;
853 for (; i < to_pack.nr_objects; i++) {
854 struct object_entry *e = write_order[i];
855 if (write_one(f, e, &offset) == WRITE_ONE_BREAK)
856 break;
857 display_progress(progress_state, written);
861 * Did we write the wrong # entries in the header?
862 * If so, rewrite it like in fast-import
864 if (pack_to_stdout) {
865 finalize_hashfile(f, oid.hash, CSUM_HASH_IN_STREAM | CSUM_CLOSE);
866 } else if (nr_written == nr_remaining) {
867 finalize_hashfile(f, oid.hash, CSUM_HASH_IN_STREAM | CSUM_FSYNC | CSUM_CLOSE);
868 } else {
869 int fd = finalize_hashfile(f, oid.hash, 0);
870 fixup_pack_header_footer(fd, oid.hash, pack_tmp_name,
871 nr_written, oid.hash, offset);
872 close(fd);
873 if (write_bitmap_index) {
874 warning(_(no_split_warning));
875 write_bitmap_index = 0;
879 if (!pack_to_stdout) {
880 struct stat st;
881 struct strbuf tmpname = STRBUF_INIT;
884 * Packs are runtime accessed in their mtime
885 * order since newer packs are more likely to contain
886 * younger objects. So if we are creating multiple
887 * packs then we should modify the mtime of later ones
888 * to preserve this property.
890 if (stat(pack_tmp_name, &st) < 0) {
891 warning_errno(_("failed to stat %s"), pack_tmp_name);
892 } else if (!last_mtime) {
893 last_mtime = st.st_mtime;
894 } else {
895 struct utimbuf utb;
896 utb.actime = st.st_atime;
897 utb.modtime = --last_mtime;
898 if (utime(pack_tmp_name, &utb) < 0)
899 warning_errno(_("failed utime() on %s"), pack_tmp_name);
902 strbuf_addf(&tmpname, "%s-", base_name);
904 if (write_bitmap_index) {
905 bitmap_writer_set_checksum(oid.hash);
906 bitmap_writer_build_type_index(
907 &to_pack, written_list, nr_written);
910 finish_tmp_packfile(&tmpname, pack_tmp_name,
911 written_list, nr_written,
912 &pack_idx_opts, oid.hash);
914 if (write_bitmap_index) {
915 strbuf_addf(&tmpname, "%s.bitmap", oid_to_hex(&oid));
917 stop_progress(&progress_state);
919 bitmap_writer_show_progress(progress);
920 bitmap_writer_reuse_bitmaps(&to_pack);
921 bitmap_writer_select_commits(indexed_commits, indexed_commits_nr, -1);
922 bitmap_writer_build(&to_pack);
923 bitmap_writer_finish(written_list, nr_written,
924 tmpname.buf, write_bitmap_options);
925 write_bitmap_index = 0;
928 strbuf_release(&tmpname);
929 free(pack_tmp_name);
930 puts(oid_to_hex(&oid));
933 /* mark written objects as written to previous pack */
934 for (j = 0; j < nr_written; j++) {
935 written_list[j]->offset = (off_t)-1;
937 nr_remaining -= nr_written;
938 } while (nr_remaining && i < to_pack.nr_objects);
940 free(written_list);
941 free(write_order);
942 stop_progress(&progress_state);
943 if (written != nr_result)
944 die(_("wrote %"PRIu32" objects while expecting %"PRIu32),
945 written, nr_result);
948 static int no_try_delta(const char *path)
950 static struct attr_check *check;
952 if (!check)
953 check = attr_check_initl("delta", NULL);
954 if (git_check_attr(&the_index, path, check))
955 return 0;
956 if (ATTR_FALSE(check->items[0].value))
957 return 1;
958 return 0;
962 * When adding an object, check whether we have already added it
963 * to our packing list. If so, we can skip. However, if we are
964 * being asked to excludei t, but the previous mention was to include
965 * it, make sure to adjust its flags and tweak our numbers accordingly.
967 * As an optimization, we pass out the index position where we would have
968 * found the item, since that saves us from having to look it up again a
969 * few lines later when we want to add the new entry.
971 static int have_duplicate_entry(const struct object_id *oid,
972 int exclude,
973 uint32_t *index_pos)
975 struct object_entry *entry;
977 entry = packlist_find(&to_pack, oid->hash, index_pos);
978 if (!entry)
979 return 0;
981 if (exclude) {
982 if (!entry->preferred_base)
983 nr_result--;
984 entry->preferred_base = 1;
987 return 1;
990 static int want_found_object(int exclude, struct packed_git *p)
992 if (exclude)
993 return 1;
994 if (incremental)
995 return 0;
998 * When asked to do --local (do not include an object that appears in a
999 * pack we borrow from elsewhere) or --honor-pack-keep (do not include
1000 * an object that appears in a pack marked with .keep), finding a pack
1001 * that matches the criteria is sufficient for us to decide to omit it.
1002 * However, even if this pack does not satisfy the criteria, we need to
1003 * make sure no copy of this object appears in _any_ pack that makes us
1004 * to omit the object, so we need to check all the packs.
1006 * We can however first check whether these options can possible matter;
1007 * if they do not matter we know we want the object in generated pack.
1008 * Otherwise, we signal "-1" at the end to tell the caller that we do
1009 * not know either way, and it needs to check more packs.
1011 if (!ignore_packed_keep_on_disk &&
1012 !ignore_packed_keep_in_core &&
1013 (!local || !have_non_local_packs))
1014 return 1;
1016 if (local && !p->pack_local)
1017 return 0;
1018 if (p->pack_local &&
1019 ((ignore_packed_keep_on_disk && p->pack_keep) ||
1020 (ignore_packed_keep_in_core && p->pack_keep_in_core)))
1021 return 0;
1023 /* we don't know yet; keep looking for more packs */
1024 return -1;
1028 * Check whether we want the object in the pack (e.g., we do not want
1029 * objects found in non-local stores if the "--local" option was used).
1031 * If the caller already knows an existing pack it wants to take the object
1032 * from, that is passed in *found_pack and *found_offset; otherwise this
1033 * function finds if there is any pack that has the object and returns the pack
1034 * and its offset in these variables.
1036 static int want_object_in_pack(const struct object_id *oid,
1037 int exclude,
1038 struct packed_git **found_pack,
1039 off_t *found_offset)
1041 int want;
1042 struct list_head *pos;
1044 if (!exclude && local && has_loose_object_nonlocal(oid))
1045 return 0;
1048 * If we already know the pack object lives in, start checks from that
1049 * pack - in the usual case when neither --local was given nor .keep files
1050 * are present we will determine the answer right now.
1052 if (*found_pack) {
1053 want = want_found_object(exclude, *found_pack);
1054 if (want != -1)
1055 return want;
1057 list_for_each(pos, get_packed_git_mru(the_repository)) {
1058 struct packed_git *p = list_entry(pos, struct packed_git, mru);
1059 off_t offset;
1061 if (p == *found_pack)
1062 offset = *found_offset;
1063 else
1064 offset = find_pack_entry_one(oid->hash, p);
1066 if (offset) {
1067 if (!*found_pack) {
1068 if (!is_pack_valid(p))
1069 continue;
1070 *found_offset = offset;
1071 *found_pack = p;
1073 want = want_found_object(exclude, p);
1074 if (!exclude && want > 0)
1075 list_move(&p->mru,
1076 get_packed_git_mru(the_repository));
1077 if (want != -1)
1078 return want;
1082 return 1;
1085 static void create_object_entry(const struct object_id *oid,
1086 enum object_type type,
1087 uint32_t hash,
1088 int exclude,
1089 int no_try_delta,
1090 uint32_t index_pos,
1091 struct packed_git *found_pack,
1092 off_t found_offset)
1094 struct object_entry *entry;
1096 entry = packlist_alloc(&to_pack, oid->hash, index_pos);
1097 entry->hash = hash;
1098 oe_set_type(entry, type);
1099 if (exclude)
1100 entry->preferred_base = 1;
1101 else
1102 nr_result++;
1103 if (found_pack) {
1104 oe_set_in_pack(&to_pack, entry, found_pack);
1105 entry->in_pack_offset = found_offset;
1108 entry->no_try_delta = no_try_delta;
1111 static const char no_closure_warning[] = N_(
1112 "disabling bitmap writing, as some objects are not being packed"
1115 static int add_object_entry(const struct object_id *oid, enum object_type type,
1116 const char *name, int exclude)
1118 struct packed_git *found_pack = NULL;
1119 off_t found_offset = 0;
1120 uint32_t index_pos;
1122 display_progress(progress_state, ++nr_seen);
1124 if (have_duplicate_entry(oid, exclude, &index_pos))
1125 return 0;
1127 if (!want_object_in_pack(oid, exclude, &found_pack, &found_offset)) {
1128 /* The pack is missing an object, so it will not have closure */
1129 if (write_bitmap_index) {
1130 warning(_(no_closure_warning));
1131 write_bitmap_index = 0;
1133 return 0;
1136 create_object_entry(oid, type, pack_name_hash(name),
1137 exclude, name && no_try_delta(name),
1138 index_pos, found_pack, found_offset);
1139 return 1;
1142 static int add_object_entry_from_bitmap(const struct object_id *oid,
1143 enum object_type type,
1144 int flags, uint32_t name_hash,
1145 struct packed_git *pack, off_t offset)
1147 uint32_t index_pos;
1149 display_progress(progress_state, ++nr_seen);
1151 if (have_duplicate_entry(oid, 0, &index_pos))
1152 return 0;
1154 if (!want_object_in_pack(oid, 0, &pack, &offset))
1155 return 0;
1157 create_object_entry(oid, type, name_hash, 0, 0, index_pos, pack, offset);
1158 return 1;
1161 struct pbase_tree_cache {
1162 struct object_id oid;
1163 int ref;
1164 int temporary;
1165 void *tree_data;
1166 unsigned long tree_size;
1169 static struct pbase_tree_cache *(pbase_tree_cache[256]);
1170 static int pbase_tree_cache_ix(const struct object_id *oid)
1172 return oid->hash[0] % ARRAY_SIZE(pbase_tree_cache);
1174 static int pbase_tree_cache_ix_incr(int ix)
1176 return (ix+1) % ARRAY_SIZE(pbase_tree_cache);
1179 static struct pbase_tree {
1180 struct pbase_tree *next;
1181 /* This is a phony "cache" entry; we are not
1182 * going to evict it or find it through _get()
1183 * mechanism -- this is for the toplevel node that
1184 * would almost always change with any commit.
1186 struct pbase_tree_cache pcache;
1187 } *pbase_tree;
1189 static struct pbase_tree_cache *pbase_tree_get(const struct object_id *oid)
1191 struct pbase_tree_cache *ent, *nent;
1192 void *data;
1193 unsigned long size;
1194 enum object_type type;
1195 int neigh;
1196 int my_ix = pbase_tree_cache_ix(oid);
1197 int available_ix = -1;
1199 /* pbase-tree-cache acts as a limited hashtable.
1200 * your object will be found at your index or within a few
1201 * slots after that slot if it is cached.
1203 for (neigh = 0; neigh < 8; neigh++) {
1204 ent = pbase_tree_cache[my_ix];
1205 if (ent && !oidcmp(&ent->oid, oid)) {
1206 ent->ref++;
1207 return ent;
1209 else if (((available_ix < 0) && (!ent || !ent->ref)) ||
1210 ((0 <= available_ix) &&
1211 (!ent && pbase_tree_cache[available_ix])))
1212 available_ix = my_ix;
1213 if (!ent)
1214 break;
1215 my_ix = pbase_tree_cache_ix_incr(my_ix);
1218 /* Did not find one. Either we got a bogus request or
1219 * we need to read and perhaps cache.
1221 data = read_object_file(oid, &type, &size);
1222 if (!data)
1223 return NULL;
1224 if (type != OBJ_TREE) {
1225 free(data);
1226 return NULL;
1229 /* We need to either cache or return a throwaway copy */
1231 if (available_ix < 0)
1232 ent = NULL;
1233 else {
1234 ent = pbase_tree_cache[available_ix];
1235 my_ix = available_ix;
1238 if (!ent) {
1239 nent = xmalloc(sizeof(*nent));
1240 nent->temporary = (available_ix < 0);
1242 else {
1243 /* evict and reuse */
1244 free(ent->tree_data);
1245 nent = ent;
1247 oidcpy(&nent->oid, oid);
1248 nent->tree_data = data;
1249 nent->tree_size = size;
1250 nent->ref = 1;
1251 if (!nent->temporary)
1252 pbase_tree_cache[my_ix] = nent;
1253 return nent;
1256 static void pbase_tree_put(struct pbase_tree_cache *cache)
1258 if (!cache->temporary) {
1259 cache->ref--;
1260 return;
1262 free(cache->tree_data);
1263 free(cache);
1266 static int name_cmp_len(const char *name)
1268 int i;
1269 for (i = 0; name[i] && name[i] != '\n' && name[i] != '/'; i++)
1271 return i;
1274 static void add_pbase_object(struct tree_desc *tree,
1275 const char *name,
1276 int cmplen,
1277 const char *fullname)
1279 struct name_entry entry;
1280 int cmp;
1282 while (tree_entry(tree,&entry)) {
1283 if (S_ISGITLINK(entry.mode))
1284 continue;
1285 cmp = tree_entry_len(&entry) != cmplen ? 1 :
1286 memcmp(name, entry.path, cmplen);
1287 if (cmp > 0)
1288 continue;
1289 if (cmp < 0)
1290 return;
1291 if (name[cmplen] != '/') {
1292 add_object_entry(entry.oid,
1293 object_type(entry.mode),
1294 fullname, 1);
1295 return;
1297 if (S_ISDIR(entry.mode)) {
1298 struct tree_desc sub;
1299 struct pbase_tree_cache *tree;
1300 const char *down = name+cmplen+1;
1301 int downlen = name_cmp_len(down);
1303 tree = pbase_tree_get(entry.oid);
1304 if (!tree)
1305 return;
1306 init_tree_desc(&sub, tree->tree_data, tree->tree_size);
1308 add_pbase_object(&sub, down, downlen, fullname);
1309 pbase_tree_put(tree);
1314 static unsigned *done_pbase_paths;
1315 static int done_pbase_paths_num;
1316 static int done_pbase_paths_alloc;
1317 static int done_pbase_path_pos(unsigned hash)
1319 int lo = 0;
1320 int hi = done_pbase_paths_num;
1321 while (lo < hi) {
1322 int mi = lo + (hi - lo) / 2;
1323 if (done_pbase_paths[mi] == hash)
1324 return mi;
1325 if (done_pbase_paths[mi] < hash)
1326 hi = mi;
1327 else
1328 lo = mi + 1;
1330 return -lo-1;
1333 static int check_pbase_path(unsigned hash)
1335 int pos = done_pbase_path_pos(hash);
1336 if (0 <= pos)
1337 return 1;
1338 pos = -pos - 1;
1339 ALLOC_GROW(done_pbase_paths,
1340 done_pbase_paths_num + 1,
1341 done_pbase_paths_alloc);
1342 done_pbase_paths_num++;
1343 if (pos < done_pbase_paths_num)
1344 MOVE_ARRAY(done_pbase_paths + pos + 1, done_pbase_paths + pos,
1345 done_pbase_paths_num - pos - 1);
1346 done_pbase_paths[pos] = hash;
1347 return 0;
1350 static void add_preferred_base_object(const char *name)
1352 struct pbase_tree *it;
1353 int cmplen;
1354 unsigned hash = pack_name_hash(name);
1356 if (!num_preferred_base || check_pbase_path(hash))
1357 return;
1359 cmplen = name_cmp_len(name);
1360 for (it = pbase_tree; it; it = it->next) {
1361 if (cmplen == 0) {
1362 add_object_entry(&it->pcache.oid, OBJ_TREE, NULL, 1);
1364 else {
1365 struct tree_desc tree;
1366 init_tree_desc(&tree, it->pcache.tree_data, it->pcache.tree_size);
1367 add_pbase_object(&tree, name, cmplen, name);
1372 static void add_preferred_base(struct object_id *oid)
1374 struct pbase_tree *it;
1375 void *data;
1376 unsigned long size;
1377 struct object_id tree_oid;
1379 if (window <= num_preferred_base++)
1380 return;
1382 data = read_object_with_reference(oid, tree_type, &size, &tree_oid);
1383 if (!data)
1384 return;
1386 for (it = pbase_tree; it; it = it->next) {
1387 if (!oidcmp(&it->pcache.oid, &tree_oid)) {
1388 free(data);
1389 return;
1393 it = xcalloc(1, sizeof(*it));
1394 it->next = pbase_tree;
1395 pbase_tree = it;
1397 oidcpy(&it->pcache.oid, &tree_oid);
1398 it->pcache.tree_data = data;
1399 it->pcache.tree_size = size;
1402 static void cleanup_preferred_base(void)
1404 struct pbase_tree *it;
1405 unsigned i;
1407 it = pbase_tree;
1408 pbase_tree = NULL;
1409 while (it) {
1410 struct pbase_tree *tmp = it;
1411 it = tmp->next;
1412 free(tmp->pcache.tree_data);
1413 free(tmp);
1416 for (i = 0; i < ARRAY_SIZE(pbase_tree_cache); i++) {
1417 if (!pbase_tree_cache[i])
1418 continue;
1419 free(pbase_tree_cache[i]->tree_data);
1420 FREE_AND_NULL(pbase_tree_cache[i]);
1423 FREE_AND_NULL(done_pbase_paths);
1424 done_pbase_paths_num = done_pbase_paths_alloc = 0;
1427 static void check_object(struct object_entry *entry)
1429 unsigned long canonical_size;
1431 if (IN_PACK(entry)) {
1432 struct packed_git *p = IN_PACK(entry);
1433 struct pack_window *w_curs = NULL;
1434 const unsigned char *base_ref = NULL;
1435 struct object_entry *base_entry;
1436 unsigned long used, used_0;
1437 unsigned long avail;
1438 off_t ofs;
1439 unsigned char *buf, c;
1440 enum object_type type;
1441 unsigned long in_pack_size;
1443 buf = use_pack(p, &w_curs, entry->in_pack_offset, &avail);
1446 * We want in_pack_type even if we do not reuse delta
1447 * since non-delta representations could still be reused.
1449 used = unpack_object_header_buffer(buf, avail,
1450 &type,
1451 &in_pack_size);
1452 if (used == 0)
1453 goto give_up;
1455 if (type < 0)
1456 BUG("invalid type %d", type);
1457 entry->in_pack_type = type;
1460 * Determine if this is a delta and if so whether we can
1461 * reuse it or not. Otherwise let's find out as cheaply as
1462 * possible what the actual type and size for this object is.
1464 switch (entry->in_pack_type) {
1465 default:
1466 /* Not a delta hence we've already got all we need. */
1467 oe_set_type(entry, entry->in_pack_type);
1468 SET_SIZE(entry, in_pack_size);
1469 entry->in_pack_header_size = used;
1470 if (oe_type(entry) < OBJ_COMMIT || oe_type(entry) > OBJ_BLOB)
1471 goto give_up;
1472 unuse_pack(&w_curs);
1473 return;
1474 case OBJ_REF_DELTA:
1475 if (reuse_delta && !entry->preferred_base)
1476 base_ref = use_pack(p, &w_curs,
1477 entry->in_pack_offset + used, NULL);
1478 entry->in_pack_header_size = used + the_hash_algo->rawsz;
1479 break;
1480 case OBJ_OFS_DELTA:
1481 buf = use_pack(p, &w_curs,
1482 entry->in_pack_offset + used, NULL);
1483 used_0 = 0;
1484 c = buf[used_0++];
1485 ofs = c & 127;
1486 while (c & 128) {
1487 ofs += 1;
1488 if (!ofs || MSB(ofs, 7)) {
1489 error(_("delta base offset overflow in pack for %s"),
1490 oid_to_hex(&entry->idx.oid));
1491 goto give_up;
1493 c = buf[used_0++];
1494 ofs = (ofs << 7) + (c & 127);
1496 ofs = entry->in_pack_offset - ofs;
1497 if (ofs <= 0 || ofs >= entry->in_pack_offset) {
1498 error(_("delta base offset out of bound for %s"),
1499 oid_to_hex(&entry->idx.oid));
1500 goto give_up;
1502 if (reuse_delta && !entry->preferred_base) {
1503 struct revindex_entry *revidx;
1504 revidx = find_pack_revindex(p, ofs);
1505 if (!revidx)
1506 goto give_up;
1507 base_ref = nth_packed_object_sha1(p, revidx->nr);
1509 entry->in_pack_header_size = used + used_0;
1510 break;
1513 if (base_ref && (base_entry = packlist_find(&to_pack, base_ref, NULL))) {
1515 * If base_ref was set above that means we wish to
1516 * reuse delta data, and we even found that base
1517 * in the list of objects we want to pack. Goodie!
1519 * Depth value does not matter - find_deltas() will
1520 * never consider reused delta as the base object to
1521 * deltify other objects against, in order to avoid
1522 * circular deltas.
1524 oe_set_type(entry, entry->in_pack_type);
1525 SET_SIZE(entry, in_pack_size); /* delta size */
1526 SET_DELTA(entry, base_entry);
1527 SET_DELTA_SIZE(entry, in_pack_size);
1528 entry->delta_sibling_idx = base_entry->delta_child_idx;
1529 SET_DELTA_CHILD(base_entry, entry);
1530 unuse_pack(&w_curs);
1531 return;
1534 if (oe_type(entry)) {
1535 off_t delta_pos;
1538 * This must be a delta and we already know what the
1539 * final object type is. Let's extract the actual
1540 * object size from the delta header.
1542 delta_pos = entry->in_pack_offset + entry->in_pack_header_size;
1543 canonical_size = get_size_from_delta(p, &w_curs, delta_pos);
1544 if (canonical_size == 0)
1545 goto give_up;
1546 SET_SIZE(entry, canonical_size);
1547 unuse_pack(&w_curs);
1548 return;
1552 * No choice but to fall back to the recursive delta walk
1553 * with sha1_object_info() to find about the object type
1554 * at this point...
1556 give_up:
1557 unuse_pack(&w_curs);
1560 oe_set_type(entry,
1561 oid_object_info(the_repository, &entry->idx.oid, &canonical_size));
1562 if (entry->type_valid) {
1563 SET_SIZE(entry, canonical_size);
1564 } else {
1566 * Bad object type is checked in prepare_pack(). This is
1567 * to permit a missing preferred base object to be ignored
1568 * as a preferred base. Doing so can result in a larger
1569 * pack file, but the transfer will still take place.
1574 static int pack_offset_sort(const void *_a, const void *_b)
1576 const struct object_entry *a = *(struct object_entry **)_a;
1577 const struct object_entry *b = *(struct object_entry **)_b;
1578 const struct packed_git *a_in_pack = IN_PACK(a);
1579 const struct packed_git *b_in_pack = IN_PACK(b);
1581 /* avoid filesystem trashing with loose objects */
1582 if (!a_in_pack && !b_in_pack)
1583 return oidcmp(&a->idx.oid, &b->idx.oid);
1585 if (a_in_pack < b_in_pack)
1586 return -1;
1587 if (a_in_pack > b_in_pack)
1588 return 1;
1589 return a->in_pack_offset < b->in_pack_offset ? -1 :
1590 (a->in_pack_offset > b->in_pack_offset);
1594 * Drop an on-disk delta we were planning to reuse. Naively, this would
1595 * just involve blanking out the "delta" field, but we have to deal
1596 * with some extra book-keeping:
1598 * 1. Removing ourselves from the delta_sibling linked list.
1600 * 2. Updating our size/type to the non-delta representation. These were
1601 * either not recorded initially (size) or overwritten with the delta type
1602 * (type) when check_object() decided to reuse the delta.
1604 * 3. Resetting our delta depth, as we are now a base object.
1606 static void drop_reused_delta(struct object_entry *entry)
1608 unsigned *idx = &to_pack.objects[entry->delta_idx - 1].delta_child_idx;
1609 struct object_info oi = OBJECT_INFO_INIT;
1610 enum object_type type;
1611 unsigned long size;
1613 while (*idx) {
1614 struct object_entry *oe = &to_pack.objects[*idx - 1];
1616 if (oe == entry)
1617 *idx = oe->delta_sibling_idx;
1618 else
1619 idx = &oe->delta_sibling_idx;
1621 SET_DELTA(entry, NULL);
1622 entry->depth = 0;
1624 oi.sizep = &size;
1625 oi.typep = &type;
1626 if (packed_object_info(the_repository, IN_PACK(entry), entry->in_pack_offset, &oi) < 0) {
1628 * We failed to get the info from this pack for some reason;
1629 * fall back to sha1_object_info, which may find another copy.
1630 * And if that fails, the error will be recorded in oe_type(entry)
1631 * and dealt with in prepare_pack().
1633 oe_set_type(entry,
1634 oid_object_info(the_repository, &entry->idx.oid, &size));
1635 } else {
1636 oe_set_type(entry, type);
1638 SET_SIZE(entry, size);
1642 * Follow the chain of deltas from this entry onward, throwing away any links
1643 * that cause us to hit a cycle (as determined by the DFS state flags in
1644 * the entries).
1646 * We also detect too-long reused chains that would violate our --depth
1647 * limit.
1649 static void break_delta_chains(struct object_entry *entry)
1652 * The actual depth of each object we will write is stored as an int,
1653 * as it cannot exceed our int "depth" limit. But before we break
1654 * changes based no that limit, we may potentially go as deep as the
1655 * number of objects, which is elsewhere bounded to a uint32_t.
1657 uint32_t total_depth;
1658 struct object_entry *cur, *next;
1660 for (cur = entry, total_depth = 0;
1661 cur;
1662 cur = DELTA(cur), total_depth++) {
1663 if (cur->dfs_state == DFS_DONE) {
1665 * We've already seen this object and know it isn't
1666 * part of a cycle. We do need to append its depth
1667 * to our count.
1669 total_depth += cur->depth;
1670 break;
1674 * We break cycles before looping, so an ACTIVE state (or any
1675 * other cruft which made its way into the state variable)
1676 * is a bug.
1678 if (cur->dfs_state != DFS_NONE)
1679 BUG("confusing delta dfs state in first pass: %d",
1680 cur->dfs_state);
1683 * Now we know this is the first time we've seen the object. If
1684 * it's not a delta, we're done traversing, but we'll mark it
1685 * done to save time on future traversals.
1687 if (!DELTA(cur)) {
1688 cur->dfs_state = DFS_DONE;
1689 break;
1693 * Mark ourselves as active and see if the next step causes
1694 * us to cycle to another active object. It's important to do
1695 * this _before_ we loop, because it impacts where we make the
1696 * cut, and thus how our total_depth counter works.
1697 * E.g., We may see a partial loop like:
1699 * A -> B -> C -> D -> B
1701 * Cutting B->C breaks the cycle. But now the depth of A is
1702 * only 1, and our total_depth counter is at 3. The size of the
1703 * error is always one less than the size of the cycle we
1704 * broke. Commits C and D were "lost" from A's chain.
1706 * If we instead cut D->B, then the depth of A is correct at 3.
1707 * We keep all commits in the chain that we examined.
1709 cur->dfs_state = DFS_ACTIVE;
1710 if (DELTA(cur)->dfs_state == DFS_ACTIVE) {
1711 drop_reused_delta(cur);
1712 cur->dfs_state = DFS_DONE;
1713 break;
1718 * And now that we've gone all the way to the bottom of the chain, we
1719 * need to clear the active flags and set the depth fields as
1720 * appropriate. Unlike the loop above, which can quit when it drops a
1721 * delta, we need to keep going to look for more depth cuts. So we need
1722 * an extra "next" pointer to keep going after we reset cur->delta.
1724 for (cur = entry; cur; cur = next) {
1725 next = DELTA(cur);
1728 * We should have a chain of zero or more ACTIVE states down to
1729 * a final DONE. We can quit after the DONE, because either it
1730 * has no bases, or we've already handled them in a previous
1731 * call.
1733 if (cur->dfs_state == DFS_DONE)
1734 break;
1735 else if (cur->dfs_state != DFS_ACTIVE)
1736 BUG("confusing delta dfs state in second pass: %d",
1737 cur->dfs_state);
1740 * If the total_depth is more than depth, then we need to snip
1741 * the chain into two or more smaller chains that don't exceed
1742 * the maximum depth. Most of the resulting chains will contain
1743 * (depth + 1) entries (i.e., depth deltas plus one base), and
1744 * the last chain (i.e., the one containing entry) will contain
1745 * whatever entries are left over, namely
1746 * (total_depth % (depth + 1)) of them.
1748 * Since we are iterating towards decreasing depth, we need to
1749 * decrement total_depth as we go, and we need to write to the
1750 * entry what its final depth will be after all of the
1751 * snipping. Since we're snipping into chains of length (depth
1752 * + 1) entries, the final depth of an entry will be its
1753 * original depth modulo (depth + 1). Any time we encounter an
1754 * entry whose final depth is supposed to be zero, we snip it
1755 * from its delta base, thereby making it so.
1757 cur->depth = (total_depth--) % (depth + 1);
1758 if (!cur->depth)
1759 drop_reused_delta(cur);
1761 cur->dfs_state = DFS_DONE;
1765 static void get_object_details(void)
1767 uint32_t i;
1768 struct object_entry **sorted_by_offset;
1770 if (progress)
1771 progress_state = start_progress(_("Counting objects"),
1772 to_pack.nr_objects);
1774 sorted_by_offset = xcalloc(to_pack.nr_objects, sizeof(struct object_entry *));
1775 for (i = 0; i < to_pack.nr_objects; i++)
1776 sorted_by_offset[i] = to_pack.objects + i;
1777 QSORT(sorted_by_offset, to_pack.nr_objects, pack_offset_sort);
1779 for (i = 0; i < to_pack.nr_objects; i++) {
1780 struct object_entry *entry = sorted_by_offset[i];
1781 check_object(entry);
1782 if (entry->type_valid &&
1783 oe_size_greater_than(&to_pack, entry, big_file_threshold))
1784 entry->no_try_delta = 1;
1785 display_progress(progress_state, i + 1);
1787 stop_progress(&progress_state);
1790 * This must happen in a second pass, since we rely on the delta
1791 * information for the whole list being completed.
1793 for (i = 0; i < to_pack.nr_objects; i++)
1794 break_delta_chains(&to_pack.objects[i]);
1796 free(sorted_by_offset);
1800 * We search for deltas in a list sorted by type, by filename hash, and then
1801 * by size, so that we see progressively smaller and smaller files.
1802 * That's because we prefer deltas to be from the bigger file
1803 * to the smaller -- deletes are potentially cheaper, but perhaps
1804 * more importantly, the bigger file is likely the more recent
1805 * one. The deepest deltas are therefore the oldest objects which are
1806 * less susceptible to be accessed often.
1808 static int type_size_sort(const void *_a, const void *_b)
1810 const struct object_entry *a = *(struct object_entry **)_a;
1811 const struct object_entry *b = *(struct object_entry **)_b;
1812 enum object_type a_type = oe_type(a);
1813 enum object_type b_type = oe_type(b);
1814 unsigned long a_size = SIZE(a);
1815 unsigned long b_size = SIZE(b);
1817 if (a_type > b_type)
1818 return -1;
1819 if (a_type < b_type)
1820 return 1;
1821 if (a->hash > b->hash)
1822 return -1;
1823 if (a->hash < b->hash)
1824 return 1;
1825 if (a->preferred_base > b->preferred_base)
1826 return -1;
1827 if (a->preferred_base < b->preferred_base)
1828 return 1;
1829 if (a_size > b_size)
1830 return -1;
1831 if (a_size < b_size)
1832 return 1;
1833 return a < b ? -1 : (a > b); /* newest first */
1836 struct unpacked {
1837 struct object_entry *entry;
1838 void *data;
1839 struct delta_index *index;
1840 unsigned depth;
1843 static int delta_cacheable(unsigned long src_size, unsigned long trg_size,
1844 unsigned long delta_size)
1846 if (max_delta_cache_size && delta_cache_size + delta_size > max_delta_cache_size)
1847 return 0;
1849 if (delta_size < cache_max_small_delta_size)
1850 return 1;
1852 /* cache delta, if objects are large enough compared to delta size */
1853 if ((src_size >> 20) + (trg_size >> 21) > (delta_size >> 10))
1854 return 1;
1856 return 0;
1859 #ifndef NO_PTHREADS
1861 /* Protect access to object database */
1862 static pthread_mutex_t read_mutex;
1863 #define read_lock() pthread_mutex_lock(&read_mutex)
1864 #define read_unlock() pthread_mutex_unlock(&read_mutex)
1866 /* Protect delta_cache_size */
1867 static pthread_mutex_t cache_mutex;
1868 #define cache_lock() pthread_mutex_lock(&cache_mutex)
1869 #define cache_unlock() pthread_mutex_unlock(&cache_mutex)
1872 * Protect object list partitioning (e.g. struct thread_param) and
1873 * progress_state
1875 static pthread_mutex_t progress_mutex;
1876 #define progress_lock() pthread_mutex_lock(&progress_mutex)
1877 #define progress_unlock() pthread_mutex_unlock(&progress_mutex)
1880 * Access to struct object_entry is unprotected since each thread owns
1881 * a portion of the main object list. Just don't access object entries
1882 * ahead in the list because they can be stolen and would need
1883 * progress_mutex for protection.
1885 #else
1887 #define read_lock() (void)0
1888 #define read_unlock() (void)0
1889 #define cache_lock() (void)0
1890 #define cache_unlock() (void)0
1891 #define progress_lock() (void)0
1892 #define progress_unlock() (void)0
1894 #endif
1897 * Return the size of the object without doing any delta
1898 * reconstruction (so non-deltas are true object sizes, but deltas
1899 * return the size of the delta data).
1901 unsigned long oe_get_size_slow(struct packing_data *pack,
1902 const struct object_entry *e)
1904 struct packed_git *p;
1905 struct pack_window *w_curs;
1906 unsigned char *buf;
1907 enum object_type type;
1908 unsigned long used, avail, size;
1910 if (e->type_ != OBJ_OFS_DELTA && e->type_ != OBJ_REF_DELTA) {
1911 read_lock();
1912 if (oid_object_info(the_repository, &e->idx.oid, &size) < 0)
1913 die(_("unable to get size of %s"),
1914 oid_to_hex(&e->idx.oid));
1915 read_unlock();
1916 return size;
1919 p = oe_in_pack(pack, e);
1920 if (!p)
1921 BUG("when e->type is a delta, it must belong to a pack");
1923 read_lock();
1924 w_curs = NULL;
1925 buf = use_pack(p, &w_curs, e->in_pack_offset, &avail);
1926 used = unpack_object_header_buffer(buf, avail, &type, &size);
1927 if (used == 0)
1928 die(_("unable to parse object header of %s"),
1929 oid_to_hex(&e->idx.oid));
1931 unuse_pack(&w_curs);
1932 read_unlock();
1933 return size;
1936 static int try_delta(struct unpacked *trg, struct unpacked *src,
1937 unsigned max_depth, unsigned long *mem_usage)
1939 struct object_entry *trg_entry = trg->entry;
1940 struct object_entry *src_entry = src->entry;
1941 unsigned long trg_size, src_size, delta_size, sizediff, max_size, sz;
1942 unsigned ref_depth;
1943 enum object_type type;
1944 void *delta_buf;
1946 /* Don't bother doing diffs between different types */
1947 if (oe_type(trg_entry) != oe_type(src_entry))
1948 return -1;
1951 * We do not bother to try a delta that we discarded on an
1952 * earlier try, but only when reusing delta data. Note that
1953 * src_entry that is marked as the preferred_base should always
1954 * be considered, as even if we produce a suboptimal delta against
1955 * it, we will still save the transfer cost, as we already know
1956 * the other side has it and we won't send src_entry at all.
1958 if (reuse_delta && IN_PACK(trg_entry) &&
1959 IN_PACK(trg_entry) == IN_PACK(src_entry) &&
1960 !src_entry->preferred_base &&
1961 trg_entry->in_pack_type != OBJ_REF_DELTA &&
1962 trg_entry->in_pack_type != OBJ_OFS_DELTA)
1963 return 0;
1965 /* Let's not bust the allowed depth. */
1966 if (src->depth >= max_depth)
1967 return 0;
1969 /* Now some size filtering heuristics. */
1970 trg_size = SIZE(trg_entry);
1971 if (!DELTA(trg_entry)) {
1972 max_size = trg_size/2 - the_hash_algo->rawsz;
1973 ref_depth = 1;
1974 } else {
1975 max_size = DELTA_SIZE(trg_entry);
1976 ref_depth = trg->depth;
1978 max_size = (uint64_t)max_size * (max_depth - src->depth) /
1979 (max_depth - ref_depth + 1);
1980 if (max_size == 0)
1981 return 0;
1982 src_size = SIZE(src_entry);
1983 sizediff = src_size < trg_size ? trg_size - src_size : 0;
1984 if (sizediff >= max_size)
1985 return 0;
1986 if (trg_size < src_size / 32)
1987 return 0;
1989 /* Load data if not already done */
1990 if (!trg->data) {
1991 read_lock();
1992 trg->data = read_object_file(&trg_entry->idx.oid, &type, &sz);
1993 read_unlock();
1994 if (!trg->data)
1995 die(_("object %s cannot be read"),
1996 oid_to_hex(&trg_entry->idx.oid));
1997 if (sz != trg_size)
1998 die(_("object %s inconsistent object length (%lu vs %lu)"),
1999 oid_to_hex(&trg_entry->idx.oid), sz,
2000 trg_size);
2001 *mem_usage += sz;
2003 if (!src->data) {
2004 read_lock();
2005 src->data = read_object_file(&src_entry->idx.oid, &type, &sz);
2006 read_unlock();
2007 if (!src->data) {
2008 if (src_entry->preferred_base) {
2009 static int warned = 0;
2010 if (!warned++)
2011 warning(_("object %s cannot be read"),
2012 oid_to_hex(&src_entry->idx.oid));
2014 * Those objects are not included in the
2015 * resulting pack. Be resilient and ignore
2016 * them if they can't be read, in case the
2017 * pack could be created nevertheless.
2019 return 0;
2021 die(_("object %s cannot be read"),
2022 oid_to_hex(&src_entry->idx.oid));
2024 if (sz != src_size)
2025 die(_("object %s inconsistent object length (%lu vs %lu)"),
2026 oid_to_hex(&src_entry->idx.oid), sz,
2027 src_size);
2028 *mem_usage += sz;
2030 if (!src->index) {
2031 src->index = create_delta_index(src->data, src_size);
2032 if (!src->index) {
2033 static int warned = 0;
2034 if (!warned++)
2035 warning(_("suboptimal pack - out of memory"));
2036 return 0;
2038 *mem_usage += sizeof_delta_index(src->index);
2041 delta_buf = create_delta(src->index, trg->data, trg_size, &delta_size, max_size);
2042 if (!delta_buf)
2043 return 0;
2044 if (delta_size >= (1U << OE_DELTA_SIZE_BITS)) {
2045 free(delta_buf);
2046 return 0;
2049 if (DELTA(trg_entry)) {
2050 /* Prefer only shallower same-sized deltas. */
2051 if (delta_size == DELTA_SIZE(trg_entry) &&
2052 src->depth + 1 >= trg->depth) {
2053 free(delta_buf);
2054 return 0;
2059 * Handle memory allocation outside of the cache
2060 * accounting lock. Compiler will optimize the strangeness
2061 * away when NO_PTHREADS is defined.
2063 free(trg_entry->delta_data);
2064 cache_lock();
2065 if (trg_entry->delta_data) {
2066 delta_cache_size -= DELTA_SIZE(trg_entry);
2067 trg_entry->delta_data = NULL;
2069 if (delta_cacheable(src_size, trg_size, delta_size)) {
2070 delta_cache_size += delta_size;
2071 cache_unlock();
2072 trg_entry->delta_data = xrealloc(delta_buf, delta_size);
2073 } else {
2074 cache_unlock();
2075 free(delta_buf);
2078 SET_DELTA(trg_entry, src_entry);
2079 SET_DELTA_SIZE(trg_entry, delta_size);
2080 trg->depth = src->depth + 1;
2082 return 1;
2085 static unsigned int check_delta_limit(struct object_entry *me, unsigned int n)
2087 struct object_entry *child = DELTA_CHILD(me);
2088 unsigned int m = n;
2089 while (child) {
2090 unsigned int c = check_delta_limit(child, n + 1);
2091 if (m < c)
2092 m = c;
2093 child = DELTA_SIBLING(child);
2095 return m;
2098 static unsigned long free_unpacked(struct unpacked *n)
2100 unsigned long freed_mem = sizeof_delta_index(n->index);
2101 free_delta_index(n->index);
2102 n->index = NULL;
2103 if (n->data) {
2104 freed_mem += SIZE(n->entry);
2105 FREE_AND_NULL(n->data);
2107 n->entry = NULL;
2108 n->depth = 0;
2109 return freed_mem;
2112 static void find_deltas(struct object_entry **list, unsigned *list_size,
2113 int window, int depth, unsigned *processed)
2115 uint32_t i, idx = 0, count = 0;
2116 struct unpacked *array;
2117 unsigned long mem_usage = 0;
2119 array = xcalloc(window, sizeof(struct unpacked));
2121 for (;;) {
2122 struct object_entry *entry;
2123 struct unpacked *n = array + idx;
2124 int j, max_depth, best_base = -1;
2126 progress_lock();
2127 if (!*list_size) {
2128 progress_unlock();
2129 break;
2131 entry = *list++;
2132 (*list_size)--;
2133 if (!entry->preferred_base) {
2134 (*processed)++;
2135 display_progress(progress_state, *processed);
2137 progress_unlock();
2139 mem_usage -= free_unpacked(n);
2140 n->entry = entry;
2142 while (window_memory_limit &&
2143 mem_usage > window_memory_limit &&
2144 count > 1) {
2145 uint32_t tail = (idx + window - count) % window;
2146 mem_usage -= free_unpacked(array + tail);
2147 count--;
2150 /* We do not compute delta to *create* objects we are not
2151 * going to pack.
2153 if (entry->preferred_base)
2154 goto next;
2157 * If the current object is at pack edge, take the depth the
2158 * objects that depend on the current object into account
2159 * otherwise they would become too deep.
2161 max_depth = depth;
2162 if (DELTA_CHILD(entry)) {
2163 max_depth -= check_delta_limit(entry, 0);
2164 if (max_depth <= 0)
2165 goto next;
2168 j = window;
2169 while (--j > 0) {
2170 int ret;
2171 uint32_t other_idx = idx + j;
2172 struct unpacked *m;
2173 if (other_idx >= window)
2174 other_idx -= window;
2175 m = array + other_idx;
2176 if (!m->entry)
2177 break;
2178 ret = try_delta(n, m, max_depth, &mem_usage);
2179 if (ret < 0)
2180 break;
2181 else if (ret > 0)
2182 best_base = other_idx;
2186 * If we decided to cache the delta data, then it is best
2187 * to compress it right away. First because we have to do
2188 * it anyway, and doing it here while we're threaded will
2189 * save a lot of time in the non threaded write phase,
2190 * as well as allow for caching more deltas within
2191 * the same cache size limit.
2192 * ...
2193 * But only if not writing to stdout, since in that case
2194 * the network is most likely throttling writes anyway,
2195 * and therefore it is best to go to the write phase ASAP
2196 * instead, as we can afford spending more time compressing
2197 * between writes at that moment.
2199 if (entry->delta_data && !pack_to_stdout) {
2200 unsigned long size;
2202 size = do_compress(&entry->delta_data, DELTA_SIZE(entry));
2203 if (size < (1U << OE_Z_DELTA_BITS)) {
2204 entry->z_delta_size = size;
2205 cache_lock();
2206 delta_cache_size -= DELTA_SIZE(entry);
2207 delta_cache_size += entry->z_delta_size;
2208 cache_unlock();
2209 } else {
2210 FREE_AND_NULL(entry->delta_data);
2211 entry->z_delta_size = 0;
2215 /* if we made n a delta, and if n is already at max
2216 * depth, leaving it in the window is pointless. we
2217 * should evict it first.
2219 if (DELTA(entry) && max_depth <= n->depth)
2220 continue;
2223 * Move the best delta base up in the window, after the
2224 * currently deltified object, to keep it longer. It will
2225 * be the first base object to be attempted next.
2227 if (DELTA(entry)) {
2228 struct unpacked swap = array[best_base];
2229 int dist = (window + idx - best_base) % window;
2230 int dst = best_base;
2231 while (dist--) {
2232 int src = (dst + 1) % window;
2233 array[dst] = array[src];
2234 dst = src;
2236 array[dst] = swap;
2239 next:
2240 idx++;
2241 if (count + 1 < window)
2242 count++;
2243 if (idx >= window)
2244 idx = 0;
2247 for (i = 0; i < window; ++i) {
2248 free_delta_index(array[i].index);
2249 free(array[i].data);
2251 free(array);
2254 #ifndef NO_PTHREADS
2256 static void try_to_free_from_threads(size_t size)
2258 read_lock();
2259 release_pack_memory(size);
2260 read_unlock();
2263 static try_to_free_t old_try_to_free_routine;
2266 * The main object list is split into smaller lists, each is handed to
2267 * one worker.
2269 * The main thread waits on the condition that (at least) one of the workers
2270 * has stopped working (which is indicated in the .working member of
2271 * struct thread_params).
2273 * When a work thread has completed its work, it sets .working to 0 and
2274 * signals the main thread and waits on the condition that .data_ready
2275 * becomes 1.
2277 * The main thread steals half of the work from the worker that has
2278 * most work left to hand it to the idle worker.
2281 struct thread_params {
2282 pthread_t thread;
2283 struct object_entry **list;
2284 unsigned list_size;
2285 unsigned remaining;
2286 int window;
2287 int depth;
2288 int working;
2289 int data_ready;
2290 pthread_mutex_t mutex;
2291 pthread_cond_t cond;
2292 unsigned *processed;
2295 static pthread_cond_t progress_cond;
2298 * Mutex and conditional variable can't be statically-initialized on Windows.
2300 static void init_threaded_search(void)
2302 init_recursive_mutex(&read_mutex);
2303 pthread_mutex_init(&cache_mutex, NULL);
2304 pthread_mutex_init(&progress_mutex, NULL);
2305 pthread_cond_init(&progress_cond, NULL);
2306 old_try_to_free_routine = set_try_to_free_routine(try_to_free_from_threads);
2309 static void cleanup_threaded_search(void)
2311 set_try_to_free_routine(old_try_to_free_routine);
2312 pthread_cond_destroy(&progress_cond);
2313 pthread_mutex_destroy(&read_mutex);
2314 pthread_mutex_destroy(&cache_mutex);
2315 pthread_mutex_destroy(&progress_mutex);
2318 static void *threaded_find_deltas(void *arg)
2320 struct thread_params *me = arg;
2322 progress_lock();
2323 while (me->remaining) {
2324 progress_unlock();
2326 find_deltas(me->list, &me->remaining,
2327 me->window, me->depth, me->processed);
2329 progress_lock();
2330 me->working = 0;
2331 pthread_cond_signal(&progress_cond);
2332 progress_unlock();
2335 * We must not set ->data_ready before we wait on the
2336 * condition because the main thread may have set it to 1
2337 * before we get here. In order to be sure that new
2338 * work is available if we see 1 in ->data_ready, it
2339 * was initialized to 0 before this thread was spawned
2340 * and we reset it to 0 right away.
2342 pthread_mutex_lock(&me->mutex);
2343 while (!me->data_ready)
2344 pthread_cond_wait(&me->cond, &me->mutex);
2345 me->data_ready = 0;
2346 pthread_mutex_unlock(&me->mutex);
2348 progress_lock();
2350 progress_unlock();
2351 /* leave ->working 1 so that this doesn't get more work assigned */
2352 return NULL;
2355 static void ll_find_deltas(struct object_entry **list, unsigned list_size,
2356 int window, int depth, unsigned *processed)
2358 struct thread_params *p;
2359 int i, ret, active_threads = 0;
2361 init_threaded_search();
2363 if (delta_search_threads <= 1) {
2364 find_deltas(list, &list_size, window, depth, processed);
2365 cleanup_threaded_search();
2366 return;
2368 if (progress > pack_to_stdout)
2369 fprintf_ln(stderr, _("Delta compression using up to %d threads"),
2370 delta_search_threads);
2371 p = xcalloc(delta_search_threads, sizeof(*p));
2373 /* Partition the work amongst work threads. */
2374 for (i = 0; i < delta_search_threads; i++) {
2375 unsigned sub_size = list_size / (delta_search_threads - i);
2377 /* don't use too small segments or no deltas will be found */
2378 if (sub_size < 2*window && i+1 < delta_search_threads)
2379 sub_size = 0;
2381 p[i].window = window;
2382 p[i].depth = depth;
2383 p[i].processed = processed;
2384 p[i].working = 1;
2385 p[i].data_ready = 0;
2387 /* try to split chunks on "path" boundaries */
2388 while (sub_size && sub_size < list_size &&
2389 list[sub_size]->hash &&
2390 list[sub_size]->hash == list[sub_size-1]->hash)
2391 sub_size++;
2393 p[i].list = list;
2394 p[i].list_size = sub_size;
2395 p[i].remaining = sub_size;
2397 list += sub_size;
2398 list_size -= sub_size;
2401 /* Start work threads. */
2402 for (i = 0; i < delta_search_threads; i++) {
2403 if (!p[i].list_size)
2404 continue;
2405 pthread_mutex_init(&p[i].mutex, NULL);
2406 pthread_cond_init(&p[i].cond, NULL);
2407 ret = pthread_create(&p[i].thread, NULL,
2408 threaded_find_deltas, &p[i]);
2409 if (ret)
2410 die(_("unable to create thread: %s"), strerror(ret));
2411 active_threads++;
2415 * Now let's wait for work completion. Each time a thread is done
2416 * with its work, we steal half of the remaining work from the
2417 * thread with the largest number of unprocessed objects and give
2418 * it to that newly idle thread. This ensure good load balancing
2419 * until the remaining object list segments are simply too short
2420 * to be worth splitting anymore.
2422 while (active_threads) {
2423 struct thread_params *target = NULL;
2424 struct thread_params *victim = NULL;
2425 unsigned sub_size = 0;
2427 progress_lock();
2428 for (;;) {
2429 for (i = 0; !target && i < delta_search_threads; i++)
2430 if (!p[i].working)
2431 target = &p[i];
2432 if (target)
2433 break;
2434 pthread_cond_wait(&progress_cond, &progress_mutex);
2437 for (i = 0; i < delta_search_threads; i++)
2438 if (p[i].remaining > 2*window &&
2439 (!victim || victim->remaining < p[i].remaining))
2440 victim = &p[i];
2441 if (victim) {
2442 sub_size = victim->remaining / 2;
2443 list = victim->list + victim->list_size - sub_size;
2444 while (sub_size && list[0]->hash &&
2445 list[0]->hash == list[-1]->hash) {
2446 list++;
2447 sub_size--;
2449 if (!sub_size) {
2451 * It is possible for some "paths" to have
2452 * so many objects that no hash boundary
2453 * might be found. Let's just steal the
2454 * exact half in that case.
2456 sub_size = victim->remaining / 2;
2457 list -= sub_size;
2459 target->list = list;
2460 victim->list_size -= sub_size;
2461 victim->remaining -= sub_size;
2463 target->list_size = sub_size;
2464 target->remaining = sub_size;
2465 target->working = 1;
2466 progress_unlock();
2468 pthread_mutex_lock(&target->mutex);
2469 target->data_ready = 1;
2470 pthread_cond_signal(&target->cond);
2471 pthread_mutex_unlock(&target->mutex);
2473 if (!sub_size) {
2474 pthread_join(target->thread, NULL);
2475 pthread_cond_destroy(&target->cond);
2476 pthread_mutex_destroy(&target->mutex);
2477 active_threads--;
2480 cleanup_threaded_search();
2481 free(p);
2484 #else
2485 #define ll_find_deltas(l, s, w, d, p) find_deltas(l, &s, w, d, p)
2486 #endif
2488 static void add_tag_chain(const struct object_id *oid)
2490 struct tag *tag;
2493 * We catch duplicates already in add_object_entry(), but we'd
2494 * prefer to do this extra check to avoid having to parse the
2495 * tag at all if we already know that it's being packed (e.g., if
2496 * it was included via bitmaps, we would not have parsed it
2497 * previously).
2499 if (packlist_find(&to_pack, oid->hash, NULL))
2500 return;
2502 tag = lookup_tag(the_repository, oid);
2503 while (1) {
2504 if (!tag || parse_tag(tag) || !tag->tagged)
2505 die(_("unable to pack objects reachable from tag %s"),
2506 oid_to_hex(oid));
2508 add_object_entry(&tag->object.oid, OBJ_TAG, NULL, 0);
2510 if (tag->tagged->type != OBJ_TAG)
2511 return;
2513 tag = (struct tag *)tag->tagged;
2517 static int add_ref_tag(const char *path, const struct object_id *oid, int flag, void *cb_data)
2519 struct object_id peeled;
2521 if (starts_with(path, "refs/tags/") && /* is a tag? */
2522 !peel_ref(path, &peeled) && /* peelable? */
2523 packlist_find(&to_pack, peeled.hash, NULL)) /* object packed? */
2524 add_tag_chain(oid);
2525 return 0;
2528 static void prepare_pack(int window, int depth)
2530 struct object_entry **delta_list;
2531 uint32_t i, nr_deltas;
2532 unsigned n;
2534 get_object_details();
2537 * If we're locally repacking then we need to be doubly careful
2538 * from now on in order to make sure no stealth corruption gets
2539 * propagated to the new pack. Clients receiving streamed packs
2540 * should validate everything they get anyway so no need to incur
2541 * the additional cost here in that case.
2543 if (!pack_to_stdout)
2544 do_check_packed_object_crc = 1;
2546 if (!to_pack.nr_objects || !window || !depth)
2547 return;
2549 ALLOC_ARRAY(delta_list, to_pack.nr_objects);
2550 nr_deltas = n = 0;
2552 for (i = 0; i < to_pack.nr_objects; i++) {
2553 struct object_entry *entry = to_pack.objects + i;
2555 if (DELTA(entry))
2556 /* This happens if we decided to reuse existing
2557 * delta from a pack. "reuse_delta &&" is implied.
2559 continue;
2561 if (!entry->type_valid ||
2562 oe_size_less_than(&to_pack, entry, 50))
2563 continue;
2565 if (entry->no_try_delta)
2566 continue;
2568 if (!entry->preferred_base) {
2569 nr_deltas++;
2570 if (oe_type(entry) < 0)
2571 die(_("unable to get type of object %s"),
2572 oid_to_hex(&entry->idx.oid));
2573 } else {
2574 if (oe_type(entry) < 0) {
2576 * This object is not found, but we
2577 * don't have to include it anyway.
2579 continue;
2583 delta_list[n++] = entry;
2586 if (nr_deltas && n > 1) {
2587 unsigned nr_done = 0;
2588 if (progress)
2589 progress_state = start_progress(_("Compressing objects"),
2590 nr_deltas);
2591 QSORT(delta_list, n, type_size_sort);
2592 ll_find_deltas(delta_list, n, window+1, depth, &nr_done);
2593 stop_progress(&progress_state);
2594 if (nr_done != nr_deltas)
2595 die(_("inconsistency with delta count"));
2597 free(delta_list);
2600 static int git_pack_config(const char *k, const char *v, void *cb)
2602 if (!strcmp(k, "pack.window")) {
2603 window = git_config_int(k, v);
2604 return 0;
2606 if (!strcmp(k, "pack.windowmemory")) {
2607 window_memory_limit = git_config_ulong(k, v);
2608 return 0;
2610 if (!strcmp(k, "pack.depth")) {
2611 depth = git_config_int(k, v);
2612 return 0;
2614 if (!strcmp(k, "pack.deltacachesize")) {
2615 max_delta_cache_size = git_config_int(k, v);
2616 return 0;
2618 if (!strcmp(k, "pack.deltacachelimit")) {
2619 cache_max_small_delta_size = git_config_int(k, v);
2620 return 0;
2622 if (!strcmp(k, "pack.writebitmaphashcache")) {
2623 if (git_config_bool(k, v))
2624 write_bitmap_options |= BITMAP_OPT_HASH_CACHE;
2625 else
2626 write_bitmap_options &= ~BITMAP_OPT_HASH_CACHE;
2628 if (!strcmp(k, "pack.usebitmaps")) {
2629 use_bitmap_index_default = git_config_bool(k, v);
2630 return 0;
2632 if (!strcmp(k, "pack.threads")) {
2633 delta_search_threads = git_config_int(k, v);
2634 if (delta_search_threads < 0)
2635 die(_("invalid number of threads specified (%d)"),
2636 delta_search_threads);
2637 #ifdef NO_PTHREADS
2638 if (delta_search_threads != 1) {
2639 warning(_("no threads support, ignoring %s"), k);
2640 delta_search_threads = 0;
2642 #endif
2643 return 0;
2645 if (!strcmp(k, "pack.indexversion")) {
2646 pack_idx_opts.version = git_config_int(k, v);
2647 if (pack_idx_opts.version > 2)
2648 die(_("bad pack.indexversion=%"PRIu32),
2649 pack_idx_opts.version);
2650 return 0;
2652 return git_default_config(k, v, cb);
2655 static void read_object_list_from_stdin(void)
2657 char line[GIT_MAX_HEXSZ + 1 + PATH_MAX + 2];
2658 struct object_id oid;
2659 const char *p;
2661 for (;;) {
2662 if (!fgets(line, sizeof(line), stdin)) {
2663 if (feof(stdin))
2664 break;
2665 if (!ferror(stdin))
2666 die("BUG: fgets returned NULL, not EOF, not error!");
2667 if (errno != EINTR)
2668 die_errno("fgets");
2669 clearerr(stdin);
2670 continue;
2672 if (line[0] == '-') {
2673 if (get_oid_hex(line+1, &oid))
2674 die(_("expected edge object ID, got garbage:\n %s"),
2675 line);
2676 add_preferred_base(&oid);
2677 continue;
2679 if (parse_oid_hex(line, &oid, &p))
2680 die(_("expected object ID, got garbage:\n %s"), line);
2682 add_preferred_base_object(p + 1);
2683 add_object_entry(&oid, OBJ_NONE, p + 1, 0);
2687 /* Remember to update object flag allocation in object.h */
2688 #define OBJECT_ADDED (1u<<20)
2690 static void show_commit(struct commit *commit, void *data)
2692 add_object_entry(&commit->object.oid, OBJ_COMMIT, NULL, 0);
2693 commit->object.flags |= OBJECT_ADDED;
2695 if (write_bitmap_index)
2696 index_commit_for_bitmap(commit);
2699 static void show_object(struct object *obj, const char *name, void *data)
2701 add_preferred_base_object(name);
2702 add_object_entry(&obj->oid, obj->type, name, 0);
2703 obj->flags |= OBJECT_ADDED;
2706 static void show_object__ma_allow_any(struct object *obj, const char *name, void *data)
2708 assert(arg_missing_action == MA_ALLOW_ANY);
2711 * Quietly ignore ALL missing objects. This avoids problems with
2712 * staging them now and getting an odd error later.
2714 if (!has_object_file(&obj->oid))
2715 return;
2717 show_object(obj, name, data);
2720 static void show_object__ma_allow_promisor(struct object *obj, const char *name, void *data)
2722 assert(arg_missing_action == MA_ALLOW_PROMISOR);
2725 * Quietly ignore EXPECTED missing objects. This avoids problems with
2726 * staging them now and getting an odd error later.
2728 if (!has_object_file(&obj->oid) && is_promisor_object(&obj->oid))
2729 return;
2731 show_object(obj, name, data);
2734 static int option_parse_missing_action(const struct option *opt,
2735 const char *arg, int unset)
2737 assert(arg);
2738 assert(!unset);
2740 if (!strcmp(arg, "error")) {
2741 arg_missing_action = MA_ERROR;
2742 fn_show_object = show_object;
2743 return 0;
2746 if (!strcmp(arg, "allow-any")) {
2747 arg_missing_action = MA_ALLOW_ANY;
2748 fetch_if_missing = 0;
2749 fn_show_object = show_object__ma_allow_any;
2750 return 0;
2753 if (!strcmp(arg, "allow-promisor")) {
2754 arg_missing_action = MA_ALLOW_PROMISOR;
2755 fetch_if_missing = 0;
2756 fn_show_object = show_object__ma_allow_promisor;
2757 return 0;
2760 die(_("invalid value for --missing"));
2761 return 0;
2764 static void show_edge(struct commit *commit)
2766 add_preferred_base(&commit->object.oid);
2769 struct in_pack_object {
2770 off_t offset;
2771 struct object *object;
2774 struct in_pack {
2775 unsigned int alloc;
2776 unsigned int nr;
2777 struct in_pack_object *array;
2780 static void mark_in_pack_object(struct object *object, struct packed_git *p, struct in_pack *in_pack)
2782 in_pack->array[in_pack->nr].offset = find_pack_entry_one(object->oid.hash, p);
2783 in_pack->array[in_pack->nr].object = object;
2784 in_pack->nr++;
2788 * Compare the objects in the offset order, in order to emulate the
2789 * "git rev-list --objects" output that produced the pack originally.
2791 static int ofscmp(const void *a_, const void *b_)
2793 struct in_pack_object *a = (struct in_pack_object *)a_;
2794 struct in_pack_object *b = (struct in_pack_object *)b_;
2796 if (a->offset < b->offset)
2797 return -1;
2798 else if (a->offset > b->offset)
2799 return 1;
2800 else
2801 return oidcmp(&a->object->oid, &b->object->oid);
2804 static void add_objects_in_unpacked_packs(struct rev_info *revs)
2806 struct packed_git *p;
2807 struct in_pack in_pack;
2808 uint32_t i;
2810 memset(&in_pack, 0, sizeof(in_pack));
2812 for (p = get_packed_git(the_repository); p; p = p->next) {
2813 struct object_id oid;
2814 struct object *o;
2816 if (!p->pack_local || p->pack_keep || p->pack_keep_in_core)
2817 continue;
2818 if (open_pack_index(p))
2819 die(_("cannot open pack index"));
2821 ALLOC_GROW(in_pack.array,
2822 in_pack.nr + p->num_objects,
2823 in_pack.alloc);
2825 for (i = 0; i < p->num_objects; i++) {
2826 nth_packed_object_oid(&oid, p, i);
2827 o = lookup_unknown_object(oid.hash);
2828 if (!(o->flags & OBJECT_ADDED))
2829 mark_in_pack_object(o, p, &in_pack);
2830 o->flags |= OBJECT_ADDED;
2834 if (in_pack.nr) {
2835 QSORT(in_pack.array, in_pack.nr, ofscmp);
2836 for (i = 0; i < in_pack.nr; i++) {
2837 struct object *o = in_pack.array[i].object;
2838 add_object_entry(&o->oid, o->type, "", 0);
2841 free(in_pack.array);
2844 static int add_loose_object(const struct object_id *oid, const char *path,
2845 void *data)
2847 enum object_type type = oid_object_info(the_repository, oid, NULL);
2849 if (type < 0) {
2850 warning(_("loose object at %s could not be examined"), path);
2851 return 0;
2854 add_object_entry(oid, type, "", 0);
2855 return 0;
2859 * We actually don't even have to worry about reachability here.
2860 * add_object_entry will weed out duplicates, so we just add every
2861 * loose object we find.
2863 static void add_unreachable_loose_objects(void)
2865 for_each_loose_file_in_objdir(get_object_directory(),
2866 add_loose_object,
2867 NULL, NULL, NULL);
2870 static int has_sha1_pack_kept_or_nonlocal(const struct object_id *oid)
2872 static struct packed_git *last_found = (void *)1;
2873 struct packed_git *p;
2875 p = (last_found != (void *)1) ? last_found :
2876 get_packed_git(the_repository);
2878 while (p) {
2879 if ((!p->pack_local || p->pack_keep ||
2880 p->pack_keep_in_core) &&
2881 find_pack_entry_one(oid->hash, p)) {
2882 last_found = p;
2883 return 1;
2885 if (p == last_found)
2886 p = get_packed_git(the_repository);
2887 else
2888 p = p->next;
2889 if (p == last_found)
2890 p = p->next;
2892 return 0;
2896 * Store a list of sha1s that are should not be discarded
2897 * because they are either written too recently, or are
2898 * reachable from another object that was.
2900 * This is filled by get_object_list.
2902 static struct oid_array recent_objects;
2904 static int loosened_object_can_be_discarded(const struct object_id *oid,
2905 timestamp_t mtime)
2907 if (!unpack_unreachable_expiration)
2908 return 0;
2909 if (mtime > unpack_unreachable_expiration)
2910 return 0;
2911 if (oid_array_lookup(&recent_objects, oid) >= 0)
2912 return 0;
2913 return 1;
2916 static void loosen_unused_packed_objects(struct rev_info *revs)
2918 struct packed_git *p;
2919 uint32_t i;
2920 struct object_id oid;
2922 for (p = get_packed_git(the_repository); p; p = p->next) {
2923 if (!p->pack_local || p->pack_keep || p->pack_keep_in_core)
2924 continue;
2926 if (open_pack_index(p))
2927 die(_("cannot open pack index"));
2929 for (i = 0; i < p->num_objects; i++) {
2930 nth_packed_object_oid(&oid, p, i);
2931 if (!packlist_find(&to_pack, oid.hash, NULL) &&
2932 !has_sha1_pack_kept_or_nonlocal(&oid) &&
2933 !loosened_object_can_be_discarded(&oid, p->mtime))
2934 if (force_object_loose(&oid, p->mtime))
2935 die(_("unable to force loose object"));
2941 * This tracks any options which pack-reuse code expects to be on, or which a
2942 * reader of the pack might not understand, and which would therefore prevent
2943 * blind reuse of what we have on disk.
2945 static int pack_options_allow_reuse(void)
2947 return pack_to_stdout &&
2948 allow_ofs_delta &&
2949 !ignore_packed_keep_on_disk &&
2950 !ignore_packed_keep_in_core &&
2951 (!local || !have_non_local_packs) &&
2952 !incremental;
2955 static int get_object_list_from_bitmap(struct rev_info *revs)
2957 struct bitmap_index *bitmap_git;
2958 if (!(bitmap_git = prepare_bitmap_walk(revs)))
2959 return -1;
2961 if (pack_options_allow_reuse() &&
2962 !reuse_partial_packfile_from_bitmap(
2963 bitmap_git,
2964 &reuse_packfile,
2965 &reuse_packfile_objects,
2966 &reuse_packfile_offset)) {
2967 assert(reuse_packfile_objects);
2968 nr_result += reuse_packfile_objects;
2969 display_progress(progress_state, nr_result);
2972 traverse_bitmap_commit_list(bitmap_git, &add_object_entry_from_bitmap);
2973 free_bitmap_index(bitmap_git);
2974 return 0;
2977 static void record_recent_object(struct object *obj,
2978 const char *name,
2979 void *data)
2981 oid_array_append(&recent_objects, &obj->oid);
2984 static void record_recent_commit(struct commit *commit, void *data)
2986 oid_array_append(&recent_objects, &commit->object.oid);
2989 static void get_object_list(int ac, const char **av)
2991 struct rev_info revs;
2992 char line[1000];
2993 int flags = 0;
2995 init_revisions(&revs, NULL);
2996 save_commit_buffer = 0;
2997 setup_revisions(ac, av, &revs, NULL);
2999 /* make sure shallows are read */
3000 is_repository_shallow(the_repository);
3002 while (fgets(line, sizeof(line), stdin) != NULL) {
3003 int len = strlen(line);
3004 if (len && line[len - 1] == '\n')
3005 line[--len] = 0;
3006 if (!len)
3007 break;
3008 if (*line == '-') {
3009 if (!strcmp(line, "--not")) {
3010 flags ^= UNINTERESTING;
3011 write_bitmap_index = 0;
3012 continue;
3014 if (starts_with(line, "--shallow ")) {
3015 struct object_id oid;
3016 if (get_oid_hex(line + 10, &oid))
3017 die("not an SHA-1 '%s'", line + 10);
3018 register_shallow(the_repository, &oid);
3019 use_bitmap_index = 0;
3020 continue;
3022 die(_("not a rev '%s'"), line);
3024 if (handle_revision_arg(line, &revs, flags, REVARG_CANNOT_BE_FILENAME))
3025 die(_("bad revision '%s'"), line);
3028 if (use_bitmap_index && !get_object_list_from_bitmap(&revs))
3029 return;
3031 if (prepare_revision_walk(&revs))
3032 die(_("revision walk setup failed"));
3033 mark_edges_uninteresting(&revs, show_edge);
3035 if (!fn_show_object)
3036 fn_show_object = show_object;
3037 traverse_commit_list_filtered(&filter_options, &revs,
3038 show_commit, fn_show_object, NULL,
3039 NULL);
3041 if (unpack_unreachable_expiration) {
3042 revs.ignore_missing_links = 1;
3043 if (add_unseen_recent_objects_to_traversal(&revs,
3044 unpack_unreachable_expiration))
3045 die(_("unable to add recent objects"));
3046 if (prepare_revision_walk(&revs))
3047 die(_("revision walk setup failed"));
3048 traverse_commit_list(&revs, record_recent_commit,
3049 record_recent_object, NULL);
3052 if (keep_unreachable)
3053 add_objects_in_unpacked_packs(&revs);
3054 if (pack_loose_unreachable)
3055 add_unreachable_loose_objects();
3056 if (unpack_unreachable)
3057 loosen_unused_packed_objects(&revs);
3059 oid_array_clear(&recent_objects);
3062 static void add_extra_kept_packs(const struct string_list *names)
3064 struct packed_git *p;
3066 if (!names->nr)
3067 return;
3069 for (p = get_packed_git(the_repository); p; p = p->next) {
3070 const char *name = basename(p->pack_name);
3071 int i;
3073 if (!p->pack_local)
3074 continue;
3076 for (i = 0; i < names->nr; i++)
3077 if (!fspathcmp(name, names->items[i].string))
3078 break;
3080 if (i < names->nr) {
3081 p->pack_keep_in_core = 1;
3082 ignore_packed_keep_in_core = 1;
3083 continue;
3088 static int option_parse_index_version(const struct option *opt,
3089 const char *arg, int unset)
3091 char *c;
3092 const char *val = arg;
3093 pack_idx_opts.version = strtoul(val, &c, 10);
3094 if (pack_idx_opts.version > 2)
3095 die(_("unsupported index version %s"), val);
3096 if (*c == ',' && c[1])
3097 pack_idx_opts.off32_limit = strtoul(c+1, &c, 0);
3098 if (*c || pack_idx_opts.off32_limit & 0x80000000)
3099 die(_("bad index version '%s'"), val);
3100 return 0;
3103 static int option_parse_unpack_unreachable(const struct option *opt,
3104 const char *arg, int unset)
3106 if (unset) {
3107 unpack_unreachable = 0;
3108 unpack_unreachable_expiration = 0;
3110 else {
3111 unpack_unreachable = 1;
3112 if (arg)
3113 unpack_unreachable_expiration = approxidate(arg);
3115 return 0;
3118 int cmd_pack_objects(int argc, const char **argv, const char *prefix)
3120 int use_internal_rev_list = 0;
3121 int thin = 0;
3122 int shallow = 0;
3123 int all_progress_implied = 0;
3124 struct argv_array rp = ARGV_ARRAY_INIT;
3125 int rev_list_unpacked = 0, rev_list_all = 0, rev_list_reflog = 0;
3126 int rev_list_index = 0;
3127 struct string_list keep_pack_list = STRING_LIST_INIT_NODUP;
3128 struct option pack_objects_options[] = {
3129 OPT_SET_INT('q', "quiet", &progress,
3130 N_("do not show progress meter"), 0),
3131 OPT_SET_INT(0, "progress", &progress,
3132 N_("show progress meter"), 1),
3133 OPT_SET_INT(0, "all-progress", &progress,
3134 N_("show progress meter during object writing phase"), 2),
3135 OPT_BOOL(0, "all-progress-implied",
3136 &all_progress_implied,
3137 N_("similar to --all-progress when progress meter is shown")),
3138 { OPTION_CALLBACK, 0, "index-version", NULL, N_("<version>[,<offset>]"),
3139 N_("write the pack index file in the specified idx format version"),
3140 0, option_parse_index_version },
3141 OPT_MAGNITUDE(0, "max-pack-size", &pack_size_limit,
3142 N_("maximum size of each output pack file")),
3143 OPT_BOOL(0, "local", &local,
3144 N_("ignore borrowed objects from alternate object store")),
3145 OPT_BOOL(0, "incremental", &incremental,
3146 N_("ignore packed objects")),
3147 OPT_INTEGER(0, "window", &window,
3148 N_("limit pack window by objects")),
3149 OPT_MAGNITUDE(0, "window-memory", &window_memory_limit,
3150 N_("limit pack window by memory in addition to object limit")),
3151 OPT_INTEGER(0, "depth", &depth,
3152 N_("maximum length of delta chain allowed in the resulting pack")),
3153 OPT_BOOL(0, "reuse-delta", &reuse_delta,
3154 N_("reuse existing deltas")),
3155 OPT_BOOL(0, "reuse-object", &reuse_object,
3156 N_("reuse existing objects")),
3157 OPT_BOOL(0, "delta-base-offset", &allow_ofs_delta,
3158 N_("use OFS_DELTA objects")),
3159 OPT_INTEGER(0, "threads", &delta_search_threads,
3160 N_("use threads when searching for best delta matches")),
3161 OPT_BOOL(0, "non-empty", &non_empty,
3162 N_("do not create an empty pack output")),
3163 OPT_BOOL(0, "revs", &use_internal_rev_list,
3164 N_("read revision arguments from standard input")),
3165 OPT_SET_INT_F(0, "unpacked", &rev_list_unpacked,
3166 N_("limit the objects to those that are not yet packed"),
3167 1, PARSE_OPT_NONEG),
3168 OPT_SET_INT_F(0, "all", &rev_list_all,
3169 N_("include objects reachable from any reference"),
3170 1, PARSE_OPT_NONEG),
3171 OPT_SET_INT_F(0, "reflog", &rev_list_reflog,
3172 N_("include objects referred by reflog entries"),
3173 1, PARSE_OPT_NONEG),
3174 OPT_SET_INT_F(0, "indexed-objects", &rev_list_index,
3175 N_("include objects referred to by the index"),
3176 1, PARSE_OPT_NONEG),
3177 OPT_BOOL(0, "stdout", &pack_to_stdout,
3178 N_("output pack to stdout")),
3179 OPT_BOOL(0, "include-tag", &include_tag,
3180 N_("include tag objects that refer to objects to be packed")),
3181 OPT_BOOL(0, "keep-unreachable", &keep_unreachable,
3182 N_("keep unreachable objects")),
3183 OPT_BOOL(0, "pack-loose-unreachable", &pack_loose_unreachable,
3184 N_("pack loose unreachable objects")),
3185 { OPTION_CALLBACK, 0, "unpack-unreachable", NULL, N_("time"),
3186 N_("unpack unreachable objects newer than <time>"),
3187 PARSE_OPT_OPTARG, option_parse_unpack_unreachable },
3188 OPT_BOOL(0, "thin", &thin,
3189 N_("create thin packs")),
3190 OPT_BOOL(0, "shallow", &shallow,
3191 N_("create packs suitable for shallow fetches")),
3192 OPT_BOOL(0, "honor-pack-keep", &ignore_packed_keep_on_disk,
3193 N_("ignore packs that have companion .keep file")),
3194 OPT_STRING_LIST(0, "keep-pack", &keep_pack_list, N_("name"),
3195 N_("ignore this pack")),
3196 OPT_INTEGER(0, "compression", &pack_compression_level,
3197 N_("pack compression level")),
3198 OPT_SET_INT(0, "keep-true-parents", &grafts_replace_parents,
3199 N_("do not hide commits by grafts"), 0),
3200 OPT_BOOL(0, "use-bitmap-index", &use_bitmap_index,
3201 N_("use a bitmap index if available to speed up counting objects")),
3202 OPT_BOOL(0, "write-bitmap-index", &write_bitmap_index,
3203 N_("write a bitmap index together with the pack index")),
3204 OPT_PARSE_LIST_OBJECTS_FILTER(&filter_options),
3205 { OPTION_CALLBACK, 0, "missing", NULL, N_("action"),
3206 N_("handling for missing objects"), PARSE_OPT_NONEG,
3207 option_parse_missing_action },
3208 OPT_BOOL(0, "exclude-promisor-objects", &exclude_promisor_objects,
3209 N_("do not pack objects in promisor packfiles")),
3210 OPT_END(),
3213 if (DFS_NUM_STATES > (1 << OE_DFS_STATE_BITS))
3214 BUG("too many dfs states, increase OE_DFS_STATE_BITS");
3216 read_replace_refs = 0;
3218 reset_pack_idx_option(&pack_idx_opts);
3219 git_config(git_pack_config, NULL);
3221 progress = isatty(2);
3222 argc = parse_options(argc, argv, prefix, pack_objects_options,
3223 pack_usage, 0);
3225 if (argc) {
3226 base_name = argv[0];
3227 argc--;
3229 if (pack_to_stdout != !base_name || argc)
3230 usage_with_options(pack_usage, pack_objects_options);
3232 if (depth >= (1 << OE_DEPTH_BITS)) {
3233 warning(_("delta chain depth %d is too deep, forcing %d"),
3234 depth, (1 << OE_DEPTH_BITS) - 1);
3235 depth = (1 << OE_DEPTH_BITS) - 1;
3237 if (cache_max_small_delta_size >= (1U << OE_Z_DELTA_BITS)) {
3238 warning(_("pack.deltaCacheLimit is too high, forcing %d"),
3239 (1U << OE_Z_DELTA_BITS) - 1);
3240 cache_max_small_delta_size = (1U << OE_Z_DELTA_BITS) - 1;
3243 argv_array_push(&rp, "pack-objects");
3244 if (thin) {
3245 use_internal_rev_list = 1;
3246 argv_array_push(&rp, shallow
3247 ? "--objects-edge-aggressive"
3248 : "--objects-edge");
3249 } else
3250 argv_array_push(&rp, "--objects");
3252 if (rev_list_all) {
3253 use_internal_rev_list = 1;
3254 argv_array_push(&rp, "--all");
3256 if (rev_list_reflog) {
3257 use_internal_rev_list = 1;
3258 argv_array_push(&rp, "--reflog");
3260 if (rev_list_index) {
3261 use_internal_rev_list = 1;
3262 argv_array_push(&rp, "--indexed-objects");
3264 if (rev_list_unpacked) {
3265 use_internal_rev_list = 1;
3266 argv_array_push(&rp, "--unpacked");
3269 if (exclude_promisor_objects) {
3270 use_internal_rev_list = 1;
3271 fetch_if_missing = 0;
3272 argv_array_push(&rp, "--exclude-promisor-objects");
3274 if (unpack_unreachable || keep_unreachable || pack_loose_unreachable)
3275 use_internal_rev_list = 1;
3277 if (!reuse_object)
3278 reuse_delta = 0;
3279 if (pack_compression_level == -1)
3280 pack_compression_level = Z_DEFAULT_COMPRESSION;
3281 else if (pack_compression_level < 0 || pack_compression_level > Z_BEST_COMPRESSION)
3282 die(_("bad pack compression level %d"), pack_compression_level);
3284 if (!delta_search_threads) /* --threads=0 means autodetect */
3285 delta_search_threads = online_cpus();
3287 #ifdef NO_PTHREADS
3288 if (delta_search_threads != 1)
3289 warning(_("no threads support, ignoring --threads"));
3290 #endif
3291 if (!pack_to_stdout && !pack_size_limit)
3292 pack_size_limit = pack_size_limit_cfg;
3293 if (pack_to_stdout && pack_size_limit)
3294 die(_("--max-pack-size cannot be used to build a pack for transfer"));
3295 if (pack_size_limit && pack_size_limit < 1024*1024) {
3296 warning(_("minimum pack size limit is 1 MiB"));
3297 pack_size_limit = 1024*1024;
3300 if (!pack_to_stdout && thin)
3301 die(_("--thin cannot be used to build an indexable pack"));
3303 if (keep_unreachable && unpack_unreachable)
3304 die(_("--keep-unreachable and --unpack-unreachable are incompatible"));
3305 if (!rev_list_all || !rev_list_reflog || !rev_list_index)
3306 unpack_unreachable_expiration = 0;
3308 if (filter_options.choice) {
3309 if (!pack_to_stdout)
3310 die(_("cannot use --filter without --stdout"));
3311 use_bitmap_index = 0;
3315 * "soft" reasons not to use bitmaps - for on-disk repack by default we want
3317 * - to produce good pack (with bitmap index not-yet-packed objects are
3318 * packed in suboptimal order).
3320 * - to use more robust pack-generation codepath (avoiding possible
3321 * bugs in bitmap code and possible bitmap index corruption).
3323 if (!pack_to_stdout)
3324 use_bitmap_index_default = 0;
3326 if (use_bitmap_index < 0)
3327 use_bitmap_index = use_bitmap_index_default;
3329 /* "hard" reasons not to use bitmaps; these just won't work at all */
3330 if (!use_internal_rev_list || (!pack_to_stdout && write_bitmap_index) || is_repository_shallow(the_repository))
3331 use_bitmap_index = 0;
3333 if (pack_to_stdout || !rev_list_all)
3334 write_bitmap_index = 0;
3336 if (progress && all_progress_implied)
3337 progress = 2;
3339 add_extra_kept_packs(&keep_pack_list);
3340 if (ignore_packed_keep_on_disk) {
3341 struct packed_git *p;
3342 for (p = get_packed_git(the_repository); p; p = p->next)
3343 if (p->pack_local && p->pack_keep)
3344 break;
3345 if (!p) /* no keep-able packs found */
3346 ignore_packed_keep_on_disk = 0;
3348 if (local) {
3350 * unlike ignore_packed_keep_on_disk above, we do not
3351 * want to unset "local" based on looking at packs, as
3352 * it also covers non-local objects
3354 struct packed_git *p;
3355 for (p = get_packed_git(the_repository); p; p = p->next) {
3356 if (!p->pack_local) {
3357 have_non_local_packs = 1;
3358 break;
3363 prepare_packing_data(&to_pack);
3365 if (progress)
3366 progress_state = start_progress(_("Enumerating objects"), 0);
3367 if (!use_internal_rev_list)
3368 read_object_list_from_stdin();
3369 else {
3370 get_object_list(rp.argc, rp.argv);
3371 argv_array_clear(&rp);
3373 cleanup_preferred_base();
3374 if (include_tag && nr_result)
3375 for_each_ref(add_ref_tag, NULL);
3376 stop_progress(&progress_state);
3378 if (non_empty && !nr_result)
3379 return 0;
3380 if (nr_result)
3381 prepare_pack(window, depth);
3382 write_pack_file();
3383 if (progress)
3384 fprintf_ln(stderr,
3385 _("Total %"PRIu32" (delta %"PRIu32"),"
3386 " reused %"PRIu32" (delta %"PRIu32")"),
3387 written, written_delta, reused, reused_delta);
3388 return 0;