builtin/show: do not prune by pathspec
[git/mjg.git] / builtin / pack-objects.c
blob638f5c57f0d2cd9ae95d2abf4c4287b604717611
1 #include "builtin.h"
2 #include "environment.h"
3 #include "gettext.h"
4 #include "hex.h"
5 #include "repository.h"
6 #include "config.h"
7 #include "attr.h"
8 #include "object.h"
9 #include "commit.h"
10 #include "tag.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-options.h"
20 #include "pack-objects.h"
21 #include "progress.h"
22 #include "refs.h"
23 #include "streaming.h"
24 #include "thread-utils.h"
25 #include "pack-bitmap.h"
26 #include "delta-islands.h"
27 #include "reachable.h"
28 #include "oid-array.h"
29 #include "strvec.h"
30 #include "list.h"
31 #include "packfile.h"
32 #include "object-file.h"
33 #include "object-store-ll.h"
34 #include "replace-object.h"
35 #include "dir.h"
36 #include "midx.h"
37 #include "trace2.h"
38 #include "shallow.h"
39 #include "promisor-remote.h"
40 #include "pack-mtimes.h"
41 #include "parse-options.h"
44 * Objects we are going to pack are collected in the `to_pack` structure.
45 * It contains an array (dynamically expanded) of the object data, and a map
46 * that can resolve SHA1s to their position in the array.
48 static struct packing_data to_pack;
50 static inline struct object_entry *oe_delta(
51 const struct packing_data *pack,
52 const struct object_entry *e)
54 if (!e->delta_idx)
55 return NULL;
56 if (e->ext_base)
57 return &pack->ext_bases[e->delta_idx - 1];
58 else
59 return &pack->objects[e->delta_idx - 1];
62 static inline unsigned long oe_delta_size(struct packing_data *pack,
63 const struct object_entry *e)
65 if (e->delta_size_valid)
66 return e->delta_size_;
69 * pack->delta_size[] can't be NULL because oe_set_delta_size()
70 * must have been called when a new delta is saved with
71 * oe_set_delta().
72 * If oe_delta() returns NULL (i.e. default state, which means
73 * delta_size_valid is also false), then the caller must never
74 * call oe_delta_size().
76 return pack->delta_size[e - pack->objects];
79 unsigned long oe_get_size_slow(struct packing_data *pack,
80 const struct object_entry *e);
82 static inline unsigned long oe_size(struct packing_data *pack,
83 const struct object_entry *e)
85 if (e->size_valid)
86 return e->size_;
88 return oe_get_size_slow(pack, e);
91 static inline void oe_set_delta(struct packing_data *pack,
92 struct object_entry *e,
93 struct object_entry *delta)
95 if (delta)
96 e->delta_idx = (delta - pack->objects) + 1;
97 else
98 e->delta_idx = 0;
101 static inline struct object_entry *oe_delta_sibling(
102 const struct packing_data *pack,
103 const struct object_entry *e)
105 if (e->delta_sibling_idx)
106 return &pack->objects[e->delta_sibling_idx - 1];
107 return NULL;
110 static inline struct object_entry *oe_delta_child(
111 const struct packing_data *pack,
112 const struct object_entry *e)
114 if (e->delta_child_idx)
115 return &pack->objects[e->delta_child_idx - 1];
116 return NULL;
119 static inline void oe_set_delta_child(struct packing_data *pack,
120 struct object_entry *e,
121 struct object_entry *delta)
123 if (delta)
124 e->delta_child_idx = (delta - pack->objects) + 1;
125 else
126 e->delta_child_idx = 0;
129 static inline void oe_set_delta_sibling(struct packing_data *pack,
130 struct object_entry *e,
131 struct object_entry *delta)
133 if (delta)
134 e->delta_sibling_idx = (delta - pack->objects) + 1;
135 else
136 e->delta_sibling_idx = 0;
139 static inline void oe_set_size(struct packing_data *pack,
140 struct object_entry *e,
141 unsigned long size)
143 if (size < pack->oe_size_limit) {
144 e->size_ = size;
145 e->size_valid = 1;
146 } else {
147 e->size_valid = 0;
148 if (oe_get_size_slow(pack, e) != size)
149 BUG("'size' is supposed to be the object size!");
153 static inline void oe_set_delta_size(struct packing_data *pack,
154 struct object_entry *e,
155 unsigned long size)
157 if (size < pack->oe_delta_size_limit) {
158 e->delta_size_ = size;
159 e->delta_size_valid = 1;
160 } else {
161 packing_data_lock(pack);
162 if (!pack->delta_size)
163 ALLOC_ARRAY(pack->delta_size, pack->nr_alloc);
164 packing_data_unlock(pack);
166 pack->delta_size[e - pack->objects] = size;
167 e->delta_size_valid = 0;
171 #define IN_PACK(obj) oe_in_pack(&to_pack, obj)
172 #define SIZE(obj) oe_size(&to_pack, obj)
173 #define SET_SIZE(obj,size) oe_set_size(&to_pack, obj, size)
174 #define DELTA_SIZE(obj) oe_delta_size(&to_pack, obj)
175 #define DELTA(obj) oe_delta(&to_pack, obj)
176 #define DELTA_CHILD(obj) oe_delta_child(&to_pack, obj)
177 #define DELTA_SIBLING(obj) oe_delta_sibling(&to_pack, obj)
178 #define SET_DELTA(obj, val) oe_set_delta(&to_pack, obj, val)
179 #define SET_DELTA_EXT(obj, oid) oe_set_delta_ext(&to_pack, obj, oid)
180 #define SET_DELTA_SIZE(obj, val) oe_set_delta_size(&to_pack, obj, val)
181 #define SET_DELTA_CHILD(obj, val) oe_set_delta_child(&to_pack, obj, val)
182 #define SET_DELTA_SIBLING(obj, val) oe_set_delta_sibling(&to_pack, obj, val)
184 static const char *pack_usage[] = {
185 N_("git pack-objects --stdout [<options>] [< <ref-list> | < <object-list>]"),
186 N_("git pack-objects [<options>] <base-name> [< <ref-list> | < <object-list>]"),
187 NULL
190 static struct pack_idx_entry **written_list;
191 static uint32_t nr_result, nr_written, nr_seen;
192 static struct bitmap_index *bitmap_git;
193 static uint32_t write_layer;
195 static int non_empty;
196 static int reuse_delta = 1, reuse_object = 1;
197 static int keep_unreachable, unpack_unreachable, include_tag;
198 static timestamp_t unpack_unreachable_expiration;
199 static int pack_loose_unreachable;
200 static int cruft;
201 static timestamp_t cruft_expiration;
202 static int local;
203 static int have_non_local_packs;
204 static int incremental;
205 static int ignore_packed_keep_on_disk;
206 static int ignore_packed_keep_in_core;
207 static int allow_ofs_delta;
208 static struct pack_idx_option pack_idx_opts;
209 static const char *base_name;
210 static int progress = 1;
211 static int window = 10;
212 static unsigned long pack_size_limit;
213 static int depth = 50;
214 static int delta_search_threads;
215 static int pack_to_stdout;
216 static int sparse;
217 static int thin;
218 static int num_preferred_base;
219 static struct progress *progress_state;
221 static struct bitmapped_pack *reuse_packfiles;
222 static size_t reuse_packfiles_nr;
223 static size_t reuse_packfiles_used_nr;
224 static uint32_t reuse_packfile_objects;
225 static struct bitmap *reuse_packfile_bitmap;
227 static int use_bitmap_index_default = 1;
228 static int use_bitmap_index = -1;
229 static enum {
230 NO_PACK_REUSE = 0,
231 SINGLE_PACK_REUSE,
232 MULTI_PACK_REUSE,
233 } allow_pack_reuse = SINGLE_PACK_REUSE;
234 static enum {
235 WRITE_BITMAP_FALSE = 0,
236 WRITE_BITMAP_QUIET,
237 WRITE_BITMAP_TRUE,
238 } write_bitmap_index;
239 static uint16_t write_bitmap_options = BITMAP_OPT_HASH_CACHE;
241 static int exclude_promisor_objects;
243 static int use_delta_islands;
245 static unsigned long delta_cache_size = 0;
246 static unsigned long max_delta_cache_size = DEFAULT_DELTA_CACHE_SIZE;
247 static unsigned long cache_max_small_delta_size = 1000;
249 static unsigned long window_memory_limit = 0;
251 static struct string_list uri_protocols = STRING_LIST_INIT_NODUP;
253 enum missing_action {
254 MA_ERROR = 0, /* fail if any missing objects are encountered */
255 MA_ALLOW_ANY, /* silently allow ALL missing objects */
256 MA_ALLOW_PROMISOR, /* silently allow all missing PROMISOR objects */
258 static enum missing_action arg_missing_action;
259 static show_object_fn fn_show_object;
261 struct configured_exclusion {
262 struct oidmap_entry e;
263 char *pack_hash_hex;
264 char *uri;
266 static struct oidmap configured_exclusions;
268 static struct oidset excluded_by_config;
271 * stats
273 static uint32_t written, written_delta;
274 static uint32_t reused, reused_delta;
277 * Indexed commits
279 static struct commit **indexed_commits;
280 static unsigned int indexed_commits_nr;
281 static unsigned int indexed_commits_alloc;
283 static void index_commit_for_bitmap(struct commit *commit)
285 if (indexed_commits_nr >= indexed_commits_alloc) {
286 indexed_commits_alloc = (indexed_commits_alloc + 32) * 2;
287 REALLOC_ARRAY(indexed_commits, indexed_commits_alloc);
290 indexed_commits[indexed_commits_nr++] = commit;
293 static void *get_delta(struct object_entry *entry)
295 unsigned long size, base_size, delta_size;
296 void *buf, *base_buf, *delta_buf;
297 enum object_type type;
299 buf = repo_read_object_file(the_repository, &entry->idx.oid, &type,
300 &size);
301 if (!buf)
302 die(_("unable to read %s"), oid_to_hex(&entry->idx.oid));
303 base_buf = repo_read_object_file(the_repository,
304 &DELTA(entry)->idx.oid, &type,
305 &base_size);
306 if (!base_buf)
307 die("unable to read %s",
308 oid_to_hex(&DELTA(entry)->idx.oid));
309 delta_buf = diff_delta(base_buf, base_size,
310 buf, size, &delta_size, 0);
312 * We successfully computed this delta once but dropped it for
313 * memory reasons. Something is very wrong if this time we
314 * recompute and create a different delta.
316 if (!delta_buf || delta_size != DELTA_SIZE(entry))
317 BUG("delta size changed");
318 free(buf);
319 free(base_buf);
320 return delta_buf;
323 static unsigned long do_compress(void **pptr, unsigned long size)
325 git_zstream stream;
326 void *in, *out;
327 unsigned long maxsize;
329 git_deflate_init(&stream, pack_compression_level);
330 maxsize = git_deflate_bound(&stream, size);
332 in = *pptr;
333 out = xmalloc(maxsize);
334 *pptr = out;
336 stream.next_in = in;
337 stream.avail_in = size;
338 stream.next_out = out;
339 stream.avail_out = maxsize;
340 while (git_deflate(&stream, Z_FINISH) == Z_OK)
341 ; /* nothing */
342 git_deflate_end(&stream);
344 free(in);
345 return stream.total_out;
348 static unsigned long write_large_blob_data(struct git_istream *st, struct hashfile *f,
349 const struct object_id *oid)
351 git_zstream stream;
352 unsigned char ibuf[1024 * 16];
353 unsigned char obuf[1024 * 16];
354 unsigned long olen = 0;
356 git_deflate_init(&stream, pack_compression_level);
358 for (;;) {
359 ssize_t readlen;
360 int zret = Z_OK;
361 readlen = read_istream(st, ibuf, sizeof(ibuf));
362 if (readlen == -1)
363 die(_("unable to read %s"), oid_to_hex(oid));
365 stream.next_in = ibuf;
366 stream.avail_in = readlen;
367 while ((stream.avail_in || readlen == 0) &&
368 (zret == Z_OK || zret == Z_BUF_ERROR)) {
369 stream.next_out = obuf;
370 stream.avail_out = sizeof(obuf);
371 zret = git_deflate(&stream, readlen ? 0 : Z_FINISH);
372 hashwrite(f, obuf, stream.next_out - obuf);
373 olen += stream.next_out - obuf;
375 if (stream.avail_in)
376 die(_("deflate error (%d)"), zret);
377 if (readlen == 0) {
378 if (zret != Z_STREAM_END)
379 die(_("deflate error (%d)"), zret);
380 break;
383 git_deflate_end(&stream);
384 return olen;
388 * we are going to reuse the existing object data as is. make
389 * sure it is not corrupt.
391 static int check_pack_inflate(struct packed_git *p,
392 struct pack_window **w_curs,
393 off_t offset,
394 off_t len,
395 unsigned long expect)
397 git_zstream stream;
398 unsigned char fakebuf[4096], *in;
399 int st;
401 memset(&stream, 0, sizeof(stream));
402 git_inflate_init(&stream);
403 do {
404 in = use_pack(p, w_curs, offset, &stream.avail_in);
405 stream.next_in = in;
406 stream.next_out = fakebuf;
407 stream.avail_out = sizeof(fakebuf);
408 st = git_inflate(&stream, Z_FINISH);
409 offset += stream.next_in - in;
410 } while (st == Z_OK || st == Z_BUF_ERROR);
411 git_inflate_end(&stream);
412 return (st == Z_STREAM_END &&
413 stream.total_out == expect &&
414 stream.total_in == len) ? 0 : -1;
417 static void copy_pack_data(struct hashfile *f,
418 struct packed_git *p,
419 struct pack_window **w_curs,
420 off_t offset,
421 off_t len)
423 unsigned char *in;
424 unsigned long avail;
426 while (len) {
427 in = use_pack(p, w_curs, offset, &avail);
428 if (avail > len)
429 avail = (unsigned long)len;
430 hashwrite(f, in, avail);
431 offset += avail;
432 len -= avail;
436 static inline int oe_size_greater_than(struct packing_data *pack,
437 const struct object_entry *lhs,
438 unsigned long rhs)
440 if (lhs->size_valid)
441 return lhs->size_ > rhs;
442 if (rhs < pack->oe_size_limit) /* rhs < 2^x <= lhs ? */
443 return 1;
444 return oe_get_size_slow(pack, lhs) > rhs;
447 /* Return 0 if we will bust the pack-size limit */
448 static unsigned long write_no_reuse_object(struct hashfile *f, struct object_entry *entry,
449 unsigned long limit, int usable_delta)
451 unsigned long size, datalen;
452 unsigned char header[MAX_PACK_OBJECT_HEADER],
453 dheader[MAX_PACK_OBJECT_HEADER];
454 unsigned hdrlen;
455 enum object_type type;
456 void *buf;
457 struct git_istream *st = NULL;
458 const unsigned hashsz = the_hash_algo->rawsz;
460 if (!usable_delta) {
461 if (oe_type(entry) == OBJ_BLOB &&
462 oe_size_greater_than(&to_pack, entry, big_file_threshold) &&
463 (st = open_istream(the_repository, &entry->idx.oid, &type,
464 &size, NULL)) != NULL)
465 buf = NULL;
466 else {
467 buf = repo_read_object_file(the_repository,
468 &entry->idx.oid, &type,
469 &size);
470 if (!buf)
471 die(_("unable to read %s"),
472 oid_to_hex(&entry->idx.oid));
475 * make sure no cached delta data remains from a
476 * previous attempt before a pack split occurred.
478 FREE_AND_NULL(entry->delta_data);
479 entry->z_delta_size = 0;
480 } else if (entry->delta_data) {
481 size = DELTA_SIZE(entry);
482 buf = entry->delta_data;
483 entry->delta_data = NULL;
484 type = (allow_ofs_delta && DELTA(entry)->idx.offset) ?
485 OBJ_OFS_DELTA : OBJ_REF_DELTA;
486 } else {
487 buf = get_delta(entry);
488 size = DELTA_SIZE(entry);
489 type = (allow_ofs_delta && DELTA(entry)->idx.offset) ?
490 OBJ_OFS_DELTA : OBJ_REF_DELTA;
493 if (st) /* large blob case, just assume we don't compress well */
494 datalen = size;
495 else if (entry->z_delta_size)
496 datalen = entry->z_delta_size;
497 else
498 datalen = do_compress(&buf, size);
501 * The object header is a byte of 'type' followed by zero or
502 * more bytes of length.
504 hdrlen = encode_in_pack_object_header(header, sizeof(header),
505 type, size);
507 if (type == OBJ_OFS_DELTA) {
509 * Deltas with relative base contain an additional
510 * encoding of the relative offset for the delta
511 * base from this object's position in the pack.
513 off_t ofs = entry->idx.offset - DELTA(entry)->idx.offset;
514 unsigned pos = sizeof(dheader) - 1;
515 dheader[pos] = ofs & 127;
516 while (ofs >>= 7)
517 dheader[--pos] = 128 | (--ofs & 127);
518 if (limit && hdrlen + sizeof(dheader) - pos + datalen + hashsz >= limit) {
519 if (st)
520 close_istream(st);
521 free(buf);
522 return 0;
524 hashwrite(f, header, hdrlen);
525 hashwrite(f, dheader + pos, sizeof(dheader) - pos);
526 hdrlen += sizeof(dheader) - pos;
527 } else if (type == OBJ_REF_DELTA) {
529 * Deltas with a base reference contain
530 * additional bytes for the base object ID.
532 if (limit && hdrlen + hashsz + datalen + hashsz >= limit) {
533 if (st)
534 close_istream(st);
535 free(buf);
536 return 0;
538 hashwrite(f, header, hdrlen);
539 hashwrite(f, DELTA(entry)->idx.oid.hash, hashsz);
540 hdrlen += hashsz;
541 } else {
542 if (limit && hdrlen + datalen + hashsz >= limit) {
543 if (st)
544 close_istream(st);
545 free(buf);
546 return 0;
548 hashwrite(f, header, hdrlen);
550 if (st) {
551 datalen = write_large_blob_data(st, f, &entry->idx.oid);
552 close_istream(st);
553 } else {
554 hashwrite(f, buf, datalen);
555 free(buf);
558 return hdrlen + datalen;
561 /* Return 0 if we will bust the pack-size limit */
562 static off_t write_reuse_object(struct hashfile *f, struct object_entry *entry,
563 unsigned long limit, int usable_delta)
565 struct packed_git *p = IN_PACK(entry);
566 struct pack_window *w_curs = NULL;
567 uint32_t pos;
568 off_t offset;
569 enum object_type type = oe_type(entry);
570 off_t datalen;
571 unsigned char header[MAX_PACK_OBJECT_HEADER],
572 dheader[MAX_PACK_OBJECT_HEADER];
573 unsigned hdrlen;
574 const unsigned hashsz = the_hash_algo->rawsz;
575 unsigned long entry_size = SIZE(entry);
577 if (DELTA(entry))
578 type = (allow_ofs_delta && DELTA(entry)->idx.offset) ?
579 OBJ_OFS_DELTA : OBJ_REF_DELTA;
580 hdrlen = encode_in_pack_object_header(header, sizeof(header),
581 type, entry_size);
583 offset = entry->in_pack_offset;
584 if (offset_to_pack_pos(p, offset, &pos) < 0)
585 die(_("write_reuse_object: could not locate %s, expected at "
586 "offset %"PRIuMAX" in pack %s"),
587 oid_to_hex(&entry->idx.oid), (uintmax_t)offset,
588 p->pack_name);
589 datalen = pack_pos_to_offset(p, pos + 1) - offset;
590 if (!pack_to_stdout && p->index_version > 1 &&
591 check_pack_crc(p, &w_curs, offset, datalen,
592 pack_pos_to_index(p, pos))) {
593 error(_("bad packed object CRC for %s"),
594 oid_to_hex(&entry->idx.oid));
595 unuse_pack(&w_curs);
596 return write_no_reuse_object(f, entry, limit, usable_delta);
599 offset += entry->in_pack_header_size;
600 datalen -= entry->in_pack_header_size;
602 if (!pack_to_stdout && p->index_version == 1 &&
603 check_pack_inflate(p, &w_curs, offset, datalen, entry_size)) {
604 error(_("corrupt packed object for %s"),
605 oid_to_hex(&entry->idx.oid));
606 unuse_pack(&w_curs);
607 return write_no_reuse_object(f, entry, limit, usable_delta);
610 if (type == OBJ_OFS_DELTA) {
611 off_t ofs = entry->idx.offset - DELTA(entry)->idx.offset;
612 unsigned pos = sizeof(dheader) - 1;
613 dheader[pos] = ofs & 127;
614 while (ofs >>= 7)
615 dheader[--pos] = 128 | (--ofs & 127);
616 if (limit && hdrlen + sizeof(dheader) - pos + datalen + hashsz >= limit) {
617 unuse_pack(&w_curs);
618 return 0;
620 hashwrite(f, header, hdrlen);
621 hashwrite(f, dheader + pos, sizeof(dheader) - pos);
622 hdrlen += sizeof(dheader) - pos;
623 reused_delta++;
624 } else if (type == OBJ_REF_DELTA) {
625 if (limit && hdrlen + hashsz + datalen + hashsz >= limit) {
626 unuse_pack(&w_curs);
627 return 0;
629 hashwrite(f, header, hdrlen);
630 hashwrite(f, DELTA(entry)->idx.oid.hash, hashsz);
631 hdrlen += hashsz;
632 reused_delta++;
633 } else {
634 if (limit && hdrlen + datalen + hashsz >= limit) {
635 unuse_pack(&w_curs);
636 return 0;
638 hashwrite(f, header, hdrlen);
640 copy_pack_data(f, p, &w_curs, offset, datalen);
641 unuse_pack(&w_curs);
642 reused++;
643 return hdrlen + datalen;
646 /* Return 0 if we will bust the pack-size limit */
647 static off_t write_object(struct hashfile *f,
648 struct object_entry *entry,
649 off_t write_offset)
651 unsigned long limit;
652 off_t len;
653 int usable_delta, to_reuse;
655 if (!pack_to_stdout)
656 crc32_begin(f);
658 /* apply size limit if limited packsize and not first object */
659 if (!pack_size_limit || !nr_written)
660 limit = 0;
661 else if (pack_size_limit <= write_offset)
663 * the earlier object did not fit the limit; avoid
664 * mistaking this with unlimited (i.e. limit = 0).
666 limit = 1;
667 else
668 limit = pack_size_limit - write_offset;
670 if (!DELTA(entry))
671 usable_delta = 0; /* no delta */
672 else if (!pack_size_limit)
673 usable_delta = 1; /* unlimited packfile */
674 else if (DELTA(entry)->idx.offset == (off_t)-1)
675 usable_delta = 0; /* base was written to another pack */
676 else if (DELTA(entry)->idx.offset)
677 usable_delta = 1; /* base already exists in this pack */
678 else
679 usable_delta = 0; /* base could end up in another pack */
681 if (!reuse_object)
682 to_reuse = 0; /* explicit */
683 else if (!IN_PACK(entry))
684 to_reuse = 0; /* can't reuse what we don't have */
685 else if (oe_type(entry) == OBJ_REF_DELTA ||
686 oe_type(entry) == OBJ_OFS_DELTA)
687 /* check_object() decided it for us ... */
688 to_reuse = usable_delta;
689 /* ... but pack split may override that */
690 else if (oe_type(entry) != entry->in_pack_type)
691 to_reuse = 0; /* pack has delta which is unusable */
692 else if (DELTA(entry))
693 to_reuse = 0; /* we want to pack afresh */
694 else
695 to_reuse = 1; /* we have it in-pack undeltified,
696 * and we do not need to deltify it.
699 if (!to_reuse)
700 len = write_no_reuse_object(f, entry, limit, usable_delta);
701 else
702 len = write_reuse_object(f, entry, limit, usable_delta);
703 if (!len)
704 return 0;
706 if (usable_delta)
707 written_delta++;
708 written++;
709 if (!pack_to_stdout)
710 entry->idx.crc32 = crc32_end(f);
711 return len;
714 enum write_one_status {
715 WRITE_ONE_SKIP = -1, /* already written */
716 WRITE_ONE_BREAK = 0, /* writing this will bust the limit; not written */
717 WRITE_ONE_WRITTEN = 1, /* normal */
718 WRITE_ONE_RECURSIVE = 2 /* already scheduled to be written */
721 static enum write_one_status write_one(struct hashfile *f,
722 struct object_entry *e,
723 off_t *offset)
725 off_t size;
726 int recursing;
729 * we set offset to 1 (which is an impossible value) to mark
730 * the fact that this object is involved in "write its base
731 * first before writing a deltified object" recursion.
733 recursing = (e->idx.offset == 1);
734 if (recursing) {
735 warning(_("recursive delta detected for object %s"),
736 oid_to_hex(&e->idx.oid));
737 return WRITE_ONE_RECURSIVE;
738 } else if (e->idx.offset || e->preferred_base) {
739 /* offset is non zero if object is written already. */
740 return WRITE_ONE_SKIP;
743 /* if we are deltified, write out base object first. */
744 if (DELTA(e)) {
745 e->idx.offset = 1; /* now recurse */
746 switch (write_one(f, DELTA(e), offset)) {
747 case WRITE_ONE_RECURSIVE:
748 /* we cannot depend on this one */
749 SET_DELTA(e, NULL);
750 break;
751 default:
752 break;
753 case WRITE_ONE_BREAK:
754 e->idx.offset = recursing;
755 return WRITE_ONE_BREAK;
759 e->idx.offset = *offset;
760 size = write_object(f, e, *offset);
761 if (!size) {
762 e->idx.offset = recursing;
763 return WRITE_ONE_BREAK;
765 written_list[nr_written++] = &e->idx;
767 /* make sure off_t is sufficiently large not to wrap */
768 if (signed_add_overflows(*offset, size))
769 die(_("pack too large for current definition of off_t"));
770 *offset += size;
771 return WRITE_ONE_WRITTEN;
774 static int mark_tagged(const char *path UNUSED, const struct object_id *oid,
775 int flag UNUSED, void *cb_data UNUSED)
777 struct object_id peeled;
778 struct object_entry *entry = packlist_find(&to_pack, oid);
780 if (entry)
781 entry->tagged = 1;
782 if (!peel_iterated_oid(the_repository, oid, &peeled)) {
783 entry = packlist_find(&to_pack, &peeled);
784 if (entry)
785 entry->tagged = 1;
787 return 0;
790 static inline unsigned char oe_layer(struct packing_data *pack,
791 struct object_entry *e)
793 if (!pack->layer)
794 return 0;
795 return pack->layer[e - pack->objects];
798 static inline void add_to_write_order(struct object_entry **wo,
799 unsigned int *endp,
800 struct object_entry *e)
802 if (e->filled || oe_layer(&to_pack, e) != write_layer)
803 return;
804 wo[(*endp)++] = e;
805 e->filled = 1;
808 static void add_descendants_to_write_order(struct object_entry **wo,
809 unsigned int *endp,
810 struct object_entry *e)
812 int add_to_order = 1;
813 while (e) {
814 if (add_to_order) {
815 struct object_entry *s;
816 /* add this node... */
817 add_to_write_order(wo, endp, e);
818 /* all its siblings... */
819 for (s = DELTA_SIBLING(e); s; s = DELTA_SIBLING(s)) {
820 add_to_write_order(wo, endp, s);
823 /* drop down a level to add left subtree nodes if possible */
824 if (DELTA_CHILD(e)) {
825 add_to_order = 1;
826 e = DELTA_CHILD(e);
827 } else {
828 add_to_order = 0;
829 /* our sibling might have some children, it is next */
830 if (DELTA_SIBLING(e)) {
831 e = DELTA_SIBLING(e);
832 continue;
834 /* go back to our parent node */
835 e = DELTA(e);
836 while (e && !DELTA_SIBLING(e)) {
837 /* we're on the right side of a subtree, keep
838 * going up until we can go right again */
839 e = DELTA(e);
841 if (!e) {
842 /* done- we hit our original root node */
843 return;
845 /* pass it off to sibling at this level */
846 e = DELTA_SIBLING(e);
851 static void add_family_to_write_order(struct object_entry **wo,
852 unsigned int *endp,
853 struct object_entry *e)
855 struct object_entry *root;
857 for (root = e; DELTA(root); root = DELTA(root))
858 ; /* nothing */
859 add_descendants_to_write_order(wo, endp, root);
862 static void compute_layer_order(struct object_entry **wo, unsigned int *wo_end)
864 unsigned int i, last_untagged;
865 struct object_entry *objects = to_pack.objects;
867 for (i = 0; i < to_pack.nr_objects; i++) {
868 if (objects[i].tagged)
869 break;
870 add_to_write_order(wo, wo_end, &objects[i]);
872 last_untagged = i;
875 * Then fill all the tagged tips.
877 for (; i < to_pack.nr_objects; i++) {
878 if (objects[i].tagged)
879 add_to_write_order(wo, wo_end, &objects[i]);
883 * And then all remaining commits and tags.
885 for (i = last_untagged; i < to_pack.nr_objects; i++) {
886 if (oe_type(&objects[i]) != OBJ_COMMIT &&
887 oe_type(&objects[i]) != OBJ_TAG)
888 continue;
889 add_to_write_order(wo, wo_end, &objects[i]);
893 * And then all the trees.
895 for (i = last_untagged; i < to_pack.nr_objects; i++) {
896 if (oe_type(&objects[i]) != OBJ_TREE)
897 continue;
898 add_to_write_order(wo, wo_end, &objects[i]);
902 * Finally all the rest in really tight order
904 for (i = last_untagged; i < to_pack.nr_objects; i++) {
905 if (!objects[i].filled && oe_layer(&to_pack, &objects[i]) == write_layer)
906 add_family_to_write_order(wo, wo_end, &objects[i]);
910 static struct object_entry **compute_write_order(void)
912 uint32_t max_layers = 1;
913 unsigned int i, wo_end;
915 struct object_entry **wo;
916 struct object_entry *objects = to_pack.objects;
918 for (i = 0; i < to_pack.nr_objects; i++) {
919 objects[i].tagged = 0;
920 objects[i].filled = 0;
921 SET_DELTA_CHILD(&objects[i], NULL);
922 SET_DELTA_SIBLING(&objects[i], NULL);
926 * Fully connect delta_child/delta_sibling network.
927 * Make sure delta_sibling is sorted in the original
928 * recency order.
930 for (i = to_pack.nr_objects; i > 0;) {
931 struct object_entry *e = &objects[--i];
932 if (!DELTA(e))
933 continue;
934 /* Mark me as the first child */
935 e->delta_sibling_idx = DELTA(e)->delta_child_idx;
936 SET_DELTA_CHILD(DELTA(e), e);
940 * Mark objects that are at the tip of tags.
942 refs_for_each_tag_ref(get_main_ref_store(the_repository), mark_tagged,
943 NULL);
945 if (use_delta_islands) {
946 max_layers = compute_pack_layers(&to_pack);
947 free_island_marks();
950 ALLOC_ARRAY(wo, to_pack.nr_objects);
951 wo_end = 0;
953 for (; write_layer < max_layers; ++write_layer)
954 compute_layer_order(wo, &wo_end);
956 if (wo_end != to_pack.nr_objects)
957 die(_("ordered %u objects, expected %"PRIu32),
958 wo_end, to_pack.nr_objects);
960 return wo;
965 * A reused set of objects. All objects in a chunk have the same
966 * relative position in the original packfile and the generated
967 * packfile.
970 static struct reused_chunk {
971 /* The offset of the first object of this chunk in the original
972 * packfile. */
973 off_t original;
974 /* The difference for "original" minus the offset of the first object of
975 * this chunk in the generated packfile. */
976 off_t difference;
977 } *reused_chunks;
978 static int reused_chunks_nr;
979 static int reused_chunks_alloc;
981 static void record_reused_object(off_t where, off_t offset)
983 if (reused_chunks_nr && reused_chunks[reused_chunks_nr-1].difference == offset)
984 return;
986 ALLOC_GROW(reused_chunks, reused_chunks_nr + 1,
987 reused_chunks_alloc);
988 reused_chunks[reused_chunks_nr].original = where;
989 reused_chunks[reused_chunks_nr].difference = offset;
990 reused_chunks_nr++;
994 * Binary search to find the chunk that "where" is in. Note
995 * that we're not looking for an exact match, just the first
996 * chunk that contains it (which implicitly ends at the start
997 * of the next chunk.
999 static off_t find_reused_offset(off_t where)
1001 int lo = 0, hi = reused_chunks_nr;
1002 while (lo < hi) {
1003 int mi = lo + ((hi - lo) / 2);
1004 if (where == reused_chunks[mi].original)
1005 return reused_chunks[mi].difference;
1006 if (where < reused_chunks[mi].original)
1007 hi = mi;
1008 else
1009 lo = mi + 1;
1013 * The first chunk starts at zero, so we can't have gone below
1014 * there.
1016 assert(lo);
1017 return reused_chunks[lo-1].difference;
1020 static void write_reused_pack_one(struct packed_git *reuse_packfile,
1021 size_t pos, struct hashfile *out,
1022 off_t pack_start,
1023 struct pack_window **w_curs)
1025 off_t offset, next, cur;
1026 enum object_type type;
1027 unsigned long size;
1029 offset = pack_pos_to_offset(reuse_packfile, pos);
1030 next = pack_pos_to_offset(reuse_packfile, pos + 1);
1032 record_reused_object(offset,
1033 offset - (hashfile_total(out) - pack_start));
1035 cur = offset;
1036 type = unpack_object_header(reuse_packfile, w_curs, &cur, &size);
1037 assert(type >= 0);
1039 if (type == OBJ_OFS_DELTA) {
1040 off_t base_offset;
1041 off_t fixup;
1043 unsigned char header[MAX_PACK_OBJECT_HEADER];
1044 unsigned len;
1046 base_offset = get_delta_base(reuse_packfile, w_curs, &cur, type, offset);
1047 assert(base_offset != 0);
1049 /* Convert to REF_DELTA if we must... */
1050 if (!allow_ofs_delta) {
1051 uint32_t base_pos;
1052 struct object_id base_oid;
1054 if (offset_to_pack_pos(reuse_packfile, base_offset, &base_pos) < 0)
1055 die(_("expected object at offset %"PRIuMAX" "
1056 "in pack %s"),
1057 (uintmax_t)base_offset,
1058 reuse_packfile->pack_name);
1060 nth_packed_object_id(&base_oid, reuse_packfile,
1061 pack_pos_to_index(reuse_packfile, base_pos));
1063 len = encode_in_pack_object_header(header, sizeof(header),
1064 OBJ_REF_DELTA, size);
1065 hashwrite(out, header, len);
1066 hashwrite(out, base_oid.hash, the_hash_algo->rawsz);
1067 copy_pack_data(out, reuse_packfile, w_curs, cur, next - cur);
1068 return;
1071 /* Otherwise see if we need to rewrite the offset... */
1072 fixup = find_reused_offset(offset) -
1073 find_reused_offset(base_offset);
1074 if (fixup) {
1075 unsigned char ofs_header[10];
1076 unsigned i, ofs_len;
1077 off_t ofs = offset - base_offset - fixup;
1079 len = encode_in_pack_object_header(header, sizeof(header),
1080 OBJ_OFS_DELTA, size);
1082 i = sizeof(ofs_header) - 1;
1083 ofs_header[i] = ofs & 127;
1084 while (ofs >>= 7)
1085 ofs_header[--i] = 128 | (--ofs & 127);
1087 ofs_len = sizeof(ofs_header) - i;
1089 hashwrite(out, header, len);
1090 hashwrite(out, ofs_header + sizeof(ofs_header) - ofs_len, ofs_len);
1091 copy_pack_data(out, reuse_packfile, w_curs, cur, next - cur);
1092 return;
1095 /* ...otherwise we have no fixup, and can write it verbatim */
1098 copy_pack_data(out, reuse_packfile, w_curs, offset, next - offset);
1101 static size_t write_reused_pack_verbatim(struct bitmapped_pack *reuse_packfile,
1102 struct hashfile *out,
1103 off_t pack_start,
1104 struct pack_window **w_curs)
1106 size_t pos = reuse_packfile->bitmap_pos;
1107 size_t end;
1109 if (pos % BITS_IN_EWORD) {
1110 size_t word_pos = (pos / BITS_IN_EWORD);
1111 size_t offset = pos % BITS_IN_EWORD;
1112 size_t last;
1113 eword_t word = reuse_packfile_bitmap->words[word_pos];
1115 if (offset + reuse_packfile->bitmap_nr < BITS_IN_EWORD)
1116 last = offset + reuse_packfile->bitmap_nr;
1117 else
1118 last = BITS_IN_EWORD;
1120 for (; offset < last; offset++) {
1121 if (word >> offset == 0)
1122 return word_pos;
1123 if (!bitmap_get(reuse_packfile_bitmap,
1124 word_pos * BITS_IN_EWORD + offset))
1125 return word_pos;
1128 pos += BITS_IN_EWORD - (pos % BITS_IN_EWORD);
1132 * Now we're going to copy as many whole eword_t's as possible.
1133 * "end" is the index of the last whole eword_t we copy, but
1134 * there may be additional bits to process. Those are handled
1135 * individually by write_reused_pack().
1137 * Begin by advancing to the first word boundary in range of the
1138 * bit positions occupied by objects in "reuse_packfile". Then
1139 * pick the last word boundary in the same range. If we have at
1140 * least one word's worth of bits to process, continue on.
1142 end = reuse_packfile->bitmap_pos + reuse_packfile->bitmap_nr;
1143 if (end % BITS_IN_EWORD)
1144 end -= end % BITS_IN_EWORD;
1145 if (pos >= end)
1146 return reuse_packfile->bitmap_pos / BITS_IN_EWORD;
1148 while (pos < end &&
1149 reuse_packfile_bitmap->words[pos / BITS_IN_EWORD] == (eword_t)~0)
1150 pos += BITS_IN_EWORD;
1152 if (pos > end)
1153 pos = end;
1155 if (reuse_packfile->bitmap_pos < pos) {
1156 off_t pack_start_off = pack_pos_to_offset(reuse_packfile->p, 0);
1157 off_t pack_end_off = pack_pos_to_offset(reuse_packfile->p,
1158 pos - reuse_packfile->bitmap_pos);
1160 written += pos - reuse_packfile->bitmap_pos;
1162 /* We're recording one chunk, not one object. */
1163 record_reused_object(pack_start_off,
1164 pack_start_off - (hashfile_total(out) - pack_start));
1165 hashflush(out);
1166 copy_pack_data(out, reuse_packfile->p, w_curs,
1167 pack_start_off, pack_end_off - pack_start_off);
1169 display_progress(progress_state, written);
1171 if (pos % BITS_IN_EWORD)
1172 BUG("attempted to jump past a word boundary to %"PRIuMAX,
1173 (uintmax_t)pos);
1174 return pos / BITS_IN_EWORD;
1177 static void write_reused_pack(struct bitmapped_pack *reuse_packfile,
1178 struct hashfile *f)
1180 size_t i = reuse_packfile->bitmap_pos / BITS_IN_EWORD;
1181 uint32_t offset;
1182 off_t pack_start = hashfile_total(f) - sizeof(struct pack_header);
1183 struct pack_window *w_curs = NULL;
1185 if (allow_ofs_delta)
1186 i = write_reused_pack_verbatim(reuse_packfile, f, pack_start,
1187 &w_curs);
1189 for (; i < reuse_packfile_bitmap->word_alloc; ++i) {
1190 eword_t word = reuse_packfile_bitmap->words[i];
1191 size_t pos = (i * BITS_IN_EWORD);
1193 for (offset = 0; offset < BITS_IN_EWORD; ++offset) {
1194 if ((word >> offset) == 0)
1195 break;
1197 offset += ewah_bit_ctz64(word >> offset);
1198 if (pos + offset < reuse_packfile->bitmap_pos)
1199 continue;
1200 if (pos + offset >= reuse_packfile->bitmap_pos + reuse_packfile->bitmap_nr)
1201 goto done;
1203 * Can use bit positions directly, even for MIDX
1204 * bitmaps. See comment in try_partial_reuse()
1205 * for why.
1207 write_reused_pack_one(reuse_packfile->p,
1208 pos + offset - reuse_packfile->bitmap_pos,
1209 f, pack_start, &w_curs);
1210 display_progress(progress_state, ++written);
1214 done:
1215 unuse_pack(&w_curs);
1218 static void write_excluded_by_configs(void)
1220 struct oidset_iter iter;
1221 const struct object_id *oid;
1223 oidset_iter_init(&excluded_by_config, &iter);
1224 while ((oid = oidset_iter_next(&iter))) {
1225 struct configured_exclusion *ex =
1226 oidmap_get(&configured_exclusions, oid);
1228 if (!ex)
1229 BUG("configured exclusion wasn't configured");
1230 write_in_full(1, ex->pack_hash_hex, strlen(ex->pack_hash_hex));
1231 write_in_full(1, " ", 1);
1232 write_in_full(1, ex->uri, strlen(ex->uri));
1233 write_in_full(1, "\n", 1);
1237 static const char no_split_warning[] = N_(
1238 "disabling bitmap writing, packs are split due to pack.packSizeLimit"
1241 static void write_pack_file(void)
1243 uint32_t i = 0, j;
1244 struct hashfile *f;
1245 off_t offset;
1246 uint32_t nr_remaining = nr_result;
1247 time_t last_mtime = 0;
1248 struct object_entry **write_order;
1250 if (progress > pack_to_stdout)
1251 progress_state = start_progress(_("Writing objects"), nr_result);
1252 ALLOC_ARRAY(written_list, to_pack.nr_objects);
1253 write_order = compute_write_order();
1255 do {
1256 unsigned char hash[GIT_MAX_RAWSZ];
1257 char *pack_tmp_name = NULL;
1259 if (pack_to_stdout)
1260 f = hashfd_throughput(1, "<stdout>", progress_state);
1261 else
1262 f = create_tmp_packfile(&pack_tmp_name);
1264 offset = write_pack_header(f, nr_remaining);
1266 if (reuse_packfiles_nr) {
1267 assert(pack_to_stdout);
1268 for (j = 0; j < reuse_packfiles_nr; j++) {
1269 reused_chunks_nr = 0;
1270 write_reused_pack(&reuse_packfiles[j], f);
1271 if (reused_chunks_nr)
1272 reuse_packfiles_used_nr++;
1274 offset = hashfile_total(f);
1277 nr_written = 0;
1278 for (; i < to_pack.nr_objects; i++) {
1279 struct object_entry *e = write_order[i];
1280 if (write_one(f, e, &offset) == WRITE_ONE_BREAK)
1281 break;
1282 display_progress(progress_state, written);
1285 if (pack_to_stdout) {
1287 * We never fsync when writing to stdout since we may
1288 * not be writing to an actual pack file. For instance,
1289 * the upload-pack code passes a pipe here. Calling
1290 * fsync on a pipe results in unnecessary
1291 * synchronization with the reader on some platforms.
1293 finalize_hashfile(f, hash, FSYNC_COMPONENT_NONE,
1294 CSUM_HASH_IN_STREAM | CSUM_CLOSE);
1295 } else if (nr_written == nr_remaining) {
1296 finalize_hashfile(f, hash, FSYNC_COMPONENT_PACK,
1297 CSUM_HASH_IN_STREAM | CSUM_FSYNC | CSUM_CLOSE);
1298 } else {
1300 * If we wrote the wrong number of entries in the
1301 * header, rewrite it like in fast-import.
1304 int fd = finalize_hashfile(f, hash, FSYNC_COMPONENT_PACK, 0);
1305 fixup_pack_header_footer(fd, hash, pack_tmp_name,
1306 nr_written, hash, offset);
1307 close(fd);
1308 if (write_bitmap_index) {
1309 if (write_bitmap_index != WRITE_BITMAP_QUIET)
1310 warning(_(no_split_warning));
1311 write_bitmap_index = 0;
1315 if (!pack_to_stdout) {
1316 struct stat st;
1317 struct strbuf tmpname = STRBUF_INIT;
1318 struct bitmap_writer bitmap_writer;
1319 char *idx_tmp_name = NULL;
1322 * Packs are runtime accessed in their mtime
1323 * order since newer packs are more likely to contain
1324 * younger objects. So if we are creating multiple
1325 * packs then we should modify the mtime of later ones
1326 * to preserve this property.
1328 if (stat(pack_tmp_name, &st) < 0) {
1329 warning_errno(_("failed to stat %s"), pack_tmp_name);
1330 } else if (!last_mtime) {
1331 last_mtime = st.st_mtime;
1332 } else {
1333 struct utimbuf utb;
1334 utb.actime = st.st_atime;
1335 utb.modtime = --last_mtime;
1336 if (utime(pack_tmp_name, &utb) < 0)
1337 warning_errno(_("failed utime() on %s"), pack_tmp_name);
1340 strbuf_addf(&tmpname, "%s-%s.", base_name,
1341 hash_to_hex(hash));
1343 if (write_bitmap_index) {
1344 bitmap_writer_init(&bitmap_writer);
1345 bitmap_writer_set_checksum(&bitmap_writer, hash);
1346 bitmap_writer_build_type_index(&bitmap_writer,
1347 &to_pack, written_list, nr_written);
1350 if (cruft)
1351 pack_idx_opts.flags |= WRITE_MTIMES;
1353 stage_tmp_packfiles(&tmpname, pack_tmp_name,
1354 written_list, nr_written,
1355 &to_pack, &pack_idx_opts, hash,
1356 &idx_tmp_name);
1358 if (write_bitmap_index) {
1359 size_t tmpname_len = tmpname.len;
1361 strbuf_addstr(&tmpname, "bitmap");
1362 stop_progress(&progress_state);
1364 bitmap_writer_show_progress(&bitmap_writer,
1365 progress);
1366 bitmap_writer_select_commits(&bitmap_writer,
1367 indexed_commits,
1368 indexed_commits_nr);
1369 if (bitmap_writer_build(&bitmap_writer, &to_pack) < 0)
1370 die(_("failed to write bitmap index"));
1371 bitmap_writer_finish(&bitmap_writer,
1372 written_list, nr_written,
1373 tmpname.buf, write_bitmap_options);
1374 bitmap_writer_free(&bitmap_writer);
1375 write_bitmap_index = 0;
1376 strbuf_setlen(&tmpname, tmpname_len);
1379 rename_tmp_packfile_idx(&tmpname, &idx_tmp_name);
1381 free(idx_tmp_name);
1382 strbuf_release(&tmpname);
1383 free(pack_tmp_name);
1384 puts(hash_to_hex(hash));
1387 /* mark written objects as written to previous pack */
1388 for (j = 0; j < nr_written; j++) {
1389 written_list[j]->offset = (off_t)-1;
1391 nr_remaining -= nr_written;
1392 } while (nr_remaining && i < to_pack.nr_objects);
1394 free(written_list);
1395 free(write_order);
1396 stop_progress(&progress_state);
1397 if (written != nr_result)
1398 die(_("wrote %"PRIu32" objects while expecting %"PRIu32),
1399 written, nr_result);
1400 trace2_data_intmax("pack-objects", the_repository,
1401 "write_pack_file/wrote", nr_result);
1404 static int no_try_delta(const char *path)
1406 static struct attr_check *check;
1408 if (!check)
1409 check = attr_check_initl("delta", NULL);
1410 git_check_attr(the_repository->index, path, check);
1411 if (ATTR_FALSE(check->items[0].value))
1412 return 1;
1413 return 0;
1417 * When adding an object, check whether we have already added it
1418 * to our packing list. If so, we can skip. However, if we are
1419 * being asked to excludei t, but the previous mention was to include
1420 * it, make sure to adjust its flags and tweak our numbers accordingly.
1422 * As an optimization, we pass out the index position where we would have
1423 * found the item, since that saves us from having to look it up again a
1424 * few lines later when we want to add the new entry.
1426 static int have_duplicate_entry(const struct object_id *oid,
1427 int exclude)
1429 struct object_entry *entry;
1431 if (reuse_packfile_bitmap &&
1432 bitmap_walk_contains(bitmap_git, reuse_packfile_bitmap, oid))
1433 return 1;
1435 entry = packlist_find(&to_pack, oid);
1436 if (!entry)
1437 return 0;
1439 if (exclude) {
1440 if (!entry->preferred_base)
1441 nr_result--;
1442 entry->preferred_base = 1;
1445 return 1;
1448 static int want_found_object(const struct object_id *oid, int exclude,
1449 struct packed_git *p)
1451 if (exclude)
1452 return 1;
1453 if (incremental)
1454 return 0;
1456 if (!is_pack_valid(p))
1457 return -1;
1460 * When asked to do --local (do not include an object that appears in a
1461 * pack we borrow from elsewhere) or --honor-pack-keep (do not include
1462 * an object that appears in a pack marked with .keep), finding a pack
1463 * that matches the criteria is sufficient for us to decide to omit it.
1464 * However, even if this pack does not satisfy the criteria, we need to
1465 * make sure no copy of this object appears in _any_ pack that makes us
1466 * to omit the object, so we need to check all the packs.
1468 * We can however first check whether these options can possibly matter;
1469 * if they do not matter we know we want the object in generated pack.
1470 * Otherwise, we signal "-1" at the end to tell the caller that we do
1471 * not know either way, and it needs to check more packs.
1475 * Objects in packs borrowed from elsewhere are discarded regardless of
1476 * if they appear in other packs that weren't borrowed.
1478 if (local && !p->pack_local)
1479 return 0;
1482 * Then handle .keep first, as we have a fast(er) path there.
1484 if (ignore_packed_keep_on_disk || ignore_packed_keep_in_core) {
1486 * Set the flags for the kept-pack cache to be the ones we want
1487 * to ignore.
1489 * That is, if we are ignoring objects in on-disk keep packs,
1490 * then we want to search through the on-disk keep and ignore
1491 * the in-core ones.
1493 unsigned flags = 0;
1494 if (ignore_packed_keep_on_disk)
1495 flags |= ON_DISK_KEEP_PACKS;
1496 if (ignore_packed_keep_in_core)
1497 flags |= IN_CORE_KEEP_PACKS;
1499 if (ignore_packed_keep_on_disk && p->pack_keep)
1500 return 0;
1501 if (ignore_packed_keep_in_core && p->pack_keep_in_core)
1502 return 0;
1503 if (has_object_kept_pack(oid, flags))
1504 return 0;
1508 * At this point we know definitively that either we don't care about
1509 * keep-packs, or the object is not in one. Keep checking other
1510 * conditions...
1512 if (!local || !have_non_local_packs)
1513 return 1;
1515 /* we don't know yet; keep looking for more packs */
1516 return -1;
1519 static int want_object_in_pack_one(struct packed_git *p,
1520 const struct object_id *oid,
1521 int exclude,
1522 struct packed_git **found_pack,
1523 off_t *found_offset)
1525 off_t offset;
1527 if (p == *found_pack)
1528 offset = *found_offset;
1529 else
1530 offset = find_pack_entry_one(oid->hash, p);
1532 if (offset) {
1533 if (!*found_pack) {
1534 if (!is_pack_valid(p))
1535 return -1;
1536 *found_offset = offset;
1537 *found_pack = p;
1539 return want_found_object(oid, exclude, p);
1541 return -1;
1545 * Check whether we want the object in the pack (e.g., we do not want
1546 * objects found in non-local stores if the "--local" option was used).
1548 * If the caller already knows an existing pack it wants to take the object
1549 * from, that is passed in *found_pack and *found_offset; otherwise this
1550 * function finds if there is any pack that has the object and returns the pack
1551 * and its offset in these variables.
1553 static int want_object_in_pack(const struct object_id *oid,
1554 int exclude,
1555 struct packed_git **found_pack,
1556 off_t *found_offset)
1558 int want;
1559 struct list_head *pos;
1560 struct multi_pack_index *m;
1562 if (!exclude && local && has_loose_object_nonlocal(oid))
1563 return 0;
1566 * If we already know the pack object lives in, start checks from that
1567 * pack - in the usual case when neither --local was given nor .keep files
1568 * are present we will determine the answer right now.
1570 if (*found_pack) {
1571 want = want_found_object(oid, exclude, *found_pack);
1572 if (want != -1)
1573 return want;
1575 *found_pack = NULL;
1576 *found_offset = 0;
1579 for (m = get_multi_pack_index(the_repository); m; m = m->next) {
1580 struct pack_entry e;
1581 if (fill_midx_entry(the_repository, oid, &e, m)) {
1582 want = want_object_in_pack_one(e.p, oid, exclude, found_pack, found_offset);
1583 if (want != -1)
1584 return want;
1588 list_for_each(pos, get_packed_git_mru(the_repository)) {
1589 struct packed_git *p = list_entry(pos, struct packed_git, mru);
1590 want = want_object_in_pack_one(p, oid, exclude, found_pack, found_offset);
1591 if (!exclude && want > 0)
1592 list_move(&p->mru,
1593 get_packed_git_mru(the_repository));
1594 if (want != -1)
1595 return want;
1598 if (uri_protocols.nr) {
1599 struct configured_exclusion *ex =
1600 oidmap_get(&configured_exclusions, oid);
1601 int i;
1602 const char *p;
1604 if (ex) {
1605 for (i = 0; i < uri_protocols.nr; i++) {
1606 if (skip_prefix(ex->uri,
1607 uri_protocols.items[i].string,
1608 &p) &&
1609 *p == ':') {
1610 oidset_insert(&excluded_by_config, oid);
1611 return 0;
1617 return 1;
1620 static struct object_entry *create_object_entry(const struct object_id *oid,
1621 enum object_type type,
1622 uint32_t hash,
1623 int exclude,
1624 int no_try_delta,
1625 struct packed_git *found_pack,
1626 off_t found_offset)
1628 struct object_entry *entry;
1630 entry = packlist_alloc(&to_pack, oid);
1631 entry->hash = hash;
1632 oe_set_type(entry, type);
1633 if (exclude)
1634 entry->preferred_base = 1;
1635 else
1636 nr_result++;
1637 if (found_pack) {
1638 oe_set_in_pack(&to_pack, entry, found_pack);
1639 entry->in_pack_offset = found_offset;
1642 entry->no_try_delta = no_try_delta;
1644 return entry;
1647 static const char no_closure_warning[] = N_(
1648 "disabling bitmap writing, as some objects are not being packed"
1651 static int add_object_entry(const struct object_id *oid, enum object_type type,
1652 const char *name, int exclude)
1654 struct packed_git *found_pack = NULL;
1655 off_t found_offset = 0;
1657 display_progress(progress_state, ++nr_seen);
1659 if (have_duplicate_entry(oid, exclude))
1660 return 0;
1662 if (!want_object_in_pack(oid, exclude, &found_pack, &found_offset)) {
1663 /* The pack is missing an object, so it will not have closure */
1664 if (write_bitmap_index) {
1665 if (write_bitmap_index != WRITE_BITMAP_QUIET)
1666 warning(_(no_closure_warning));
1667 write_bitmap_index = 0;
1669 return 0;
1672 create_object_entry(oid, type, pack_name_hash(name),
1673 exclude, name && no_try_delta(name),
1674 found_pack, found_offset);
1675 return 1;
1678 static int add_object_entry_from_bitmap(const struct object_id *oid,
1679 enum object_type type,
1680 int flags UNUSED, uint32_t name_hash,
1681 struct packed_git *pack, off_t offset)
1683 display_progress(progress_state, ++nr_seen);
1685 if (have_duplicate_entry(oid, 0))
1686 return 0;
1688 if (!want_object_in_pack(oid, 0, &pack, &offset))
1689 return 0;
1691 create_object_entry(oid, type, name_hash, 0, 0, pack, offset);
1692 return 1;
1695 struct pbase_tree_cache {
1696 struct object_id oid;
1697 int ref;
1698 int temporary;
1699 void *tree_data;
1700 unsigned long tree_size;
1703 static struct pbase_tree_cache *(pbase_tree_cache[256]);
1704 static int pbase_tree_cache_ix(const struct object_id *oid)
1706 return oid->hash[0] % ARRAY_SIZE(pbase_tree_cache);
1708 static int pbase_tree_cache_ix_incr(int ix)
1710 return (ix+1) % ARRAY_SIZE(pbase_tree_cache);
1713 static struct pbase_tree {
1714 struct pbase_tree *next;
1715 /* This is a phony "cache" entry; we are not
1716 * going to evict it or find it through _get()
1717 * mechanism -- this is for the toplevel node that
1718 * would almost always change with any commit.
1720 struct pbase_tree_cache pcache;
1721 } *pbase_tree;
1723 static struct pbase_tree_cache *pbase_tree_get(const struct object_id *oid)
1725 struct pbase_tree_cache *ent, *nent;
1726 void *data;
1727 unsigned long size;
1728 enum object_type type;
1729 int neigh;
1730 int my_ix = pbase_tree_cache_ix(oid);
1731 int available_ix = -1;
1733 /* pbase-tree-cache acts as a limited hashtable.
1734 * your object will be found at your index or within a few
1735 * slots after that slot if it is cached.
1737 for (neigh = 0; neigh < 8; neigh++) {
1738 ent = pbase_tree_cache[my_ix];
1739 if (ent && oideq(&ent->oid, oid)) {
1740 ent->ref++;
1741 return ent;
1743 else if (((available_ix < 0) && (!ent || !ent->ref)) ||
1744 ((0 <= available_ix) &&
1745 (!ent && pbase_tree_cache[available_ix])))
1746 available_ix = my_ix;
1747 if (!ent)
1748 break;
1749 my_ix = pbase_tree_cache_ix_incr(my_ix);
1752 /* Did not find one. Either we got a bogus request or
1753 * we need to read and perhaps cache.
1755 data = repo_read_object_file(the_repository, oid, &type, &size);
1756 if (!data)
1757 return NULL;
1758 if (type != OBJ_TREE) {
1759 free(data);
1760 return NULL;
1763 /* We need to either cache or return a throwaway copy */
1765 if (available_ix < 0)
1766 ent = NULL;
1767 else {
1768 ent = pbase_tree_cache[available_ix];
1769 my_ix = available_ix;
1772 if (!ent) {
1773 nent = xmalloc(sizeof(*nent));
1774 nent->temporary = (available_ix < 0);
1776 else {
1777 /* evict and reuse */
1778 free(ent->tree_data);
1779 nent = ent;
1781 oidcpy(&nent->oid, oid);
1782 nent->tree_data = data;
1783 nent->tree_size = size;
1784 nent->ref = 1;
1785 if (!nent->temporary)
1786 pbase_tree_cache[my_ix] = nent;
1787 return nent;
1790 static void pbase_tree_put(struct pbase_tree_cache *cache)
1792 if (!cache->temporary) {
1793 cache->ref--;
1794 return;
1796 free(cache->tree_data);
1797 free(cache);
1800 static size_t name_cmp_len(const char *name)
1802 return strcspn(name, "\n/");
1805 static void add_pbase_object(struct tree_desc *tree,
1806 const char *name,
1807 size_t cmplen,
1808 const char *fullname)
1810 struct name_entry entry;
1811 int cmp;
1813 while (tree_entry(tree,&entry)) {
1814 if (S_ISGITLINK(entry.mode))
1815 continue;
1816 cmp = tree_entry_len(&entry) != cmplen ? 1 :
1817 memcmp(name, entry.path, cmplen);
1818 if (cmp > 0)
1819 continue;
1820 if (cmp < 0)
1821 return;
1822 if (name[cmplen] != '/') {
1823 add_object_entry(&entry.oid,
1824 object_type(entry.mode),
1825 fullname, 1);
1826 return;
1828 if (S_ISDIR(entry.mode)) {
1829 struct tree_desc sub;
1830 struct pbase_tree_cache *tree;
1831 const char *down = name+cmplen+1;
1832 size_t downlen = name_cmp_len(down);
1834 tree = pbase_tree_get(&entry.oid);
1835 if (!tree)
1836 return;
1837 init_tree_desc(&sub, &tree->oid,
1838 tree->tree_data, tree->tree_size);
1840 add_pbase_object(&sub, down, downlen, fullname);
1841 pbase_tree_put(tree);
1846 static unsigned *done_pbase_paths;
1847 static int done_pbase_paths_num;
1848 static int done_pbase_paths_alloc;
1849 static int done_pbase_path_pos(unsigned hash)
1851 int lo = 0;
1852 int hi = done_pbase_paths_num;
1853 while (lo < hi) {
1854 int mi = lo + (hi - lo) / 2;
1855 if (done_pbase_paths[mi] == hash)
1856 return mi;
1857 if (done_pbase_paths[mi] < hash)
1858 hi = mi;
1859 else
1860 lo = mi + 1;
1862 return -lo-1;
1865 static int check_pbase_path(unsigned hash)
1867 int pos = done_pbase_path_pos(hash);
1868 if (0 <= pos)
1869 return 1;
1870 pos = -pos - 1;
1871 ALLOC_GROW(done_pbase_paths,
1872 done_pbase_paths_num + 1,
1873 done_pbase_paths_alloc);
1874 done_pbase_paths_num++;
1875 if (pos < done_pbase_paths_num)
1876 MOVE_ARRAY(done_pbase_paths + pos + 1, done_pbase_paths + pos,
1877 done_pbase_paths_num - pos - 1);
1878 done_pbase_paths[pos] = hash;
1879 return 0;
1882 static void add_preferred_base_object(const char *name)
1884 struct pbase_tree *it;
1885 size_t cmplen;
1886 unsigned hash = pack_name_hash(name);
1888 if (!num_preferred_base || check_pbase_path(hash))
1889 return;
1891 cmplen = name_cmp_len(name);
1892 for (it = pbase_tree; it; it = it->next) {
1893 if (cmplen == 0) {
1894 add_object_entry(&it->pcache.oid, OBJ_TREE, NULL, 1);
1896 else {
1897 struct tree_desc tree;
1898 init_tree_desc(&tree, &it->pcache.oid,
1899 it->pcache.tree_data, it->pcache.tree_size);
1900 add_pbase_object(&tree, name, cmplen, name);
1905 static void add_preferred_base(struct object_id *oid)
1907 struct pbase_tree *it;
1908 void *data;
1909 unsigned long size;
1910 struct object_id tree_oid;
1912 if (window <= num_preferred_base++)
1913 return;
1915 data = read_object_with_reference(the_repository, oid,
1916 OBJ_TREE, &size, &tree_oid);
1917 if (!data)
1918 return;
1920 for (it = pbase_tree; it; it = it->next) {
1921 if (oideq(&it->pcache.oid, &tree_oid)) {
1922 free(data);
1923 return;
1927 CALLOC_ARRAY(it, 1);
1928 it->next = pbase_tree;
1929 pbase_tree = it;
1931 oidcpy(&it->pcache.oid, &tree_oid);
1932 it->pcache.tree_data = data;
1933 it->pcache.tree_size = size;
1936 static void cleanup_preferred_base(void)
1938 struct pbase_tree *it;
1939 unsigned i;
1941 it = pbase_tree;
1942 pbase_tree = NULL;
1943 while (it) {
1944 struct pbase_tree *tmp = it;
1945 it = tmp->next;
1946 free(tmp->pcache.tree_data);
1947 free(tmp);
1950 for (i = 0; i < ARRAY_SIZE(pbase_tree_cache); i++) {
1951 if (!pbase_tree_cache[i])
1952 continue;
1953 free(pbase_tree_cache[i]->tree_data);
1954 FREE_AND_NULL(pbase_tree_cache[i]);
1957 FREE_AND_NULL(done_pbase_paths);
1958 done_pbase_paths_num = done_pbase_paths_alloc = 0;
1962 * Return 1 iff the object specified by "delta" can be sent
1963 * literally as a delta against the base in "base_sha1". If
1964 * so, then *base_out will point to the entry in our packing
1965 * list, or NULL if we must use the external-base list.
1967 * Depth value does not matter - find_deltas() will
1968 * never consider reused delta as the base object to
1969 * deltify other objects against, in order to avoid
1970 * circular deltas.
1972 static int can_reuse_delta(const struct object_id *base_oid,
1973 struct object_entry *delta,
1974 struct object_entry **base_out)
1976 struct object_entry *base;
1979 * First see if we're already sending the base (or it's explicitly in
1980 * our "excluded" list).
1982 base = packlist_find(&to_pack, base_oid);
1983 if (base) {
1984 if (!in_same_island(&delta->idx.oid, &base->idx.oid))
1985 return 0;
1986 *base_out = base;
1987 return 1;
1991 * Otherwise, reachability bitmaps may tell us if the receiver has it,
1992 * even if it was buried too deep in history to make it into the
1993 * packing list.
1995 if (thin && bitmap_has_oid_in_uninteresting(bitmap_git, base_oid)) {
1996 if (use_delta_islands) {
1997 if (!in_same_island(&delta->idx.oid, base_oid))
1998 return 0;
2000 *base_out = NULL;
2001 return 1;
2004 return 0;
2007 static void prefetch_to_pack(uint32_t object_index_start) {
2008 struct oid_array to_fetch = OID_ARRAY_INIT;
2009 uint32_t i;
2011 for (i = object_index_start; i < to_pack.nr_objects; i++) {
2012 struct object_entry *entry = to_pack.objects + i;
2014 if (!oid_object_info_extended(the_repository,
2015 &entry->idx.oid,
2016 NULL,
2017 OBJECT_INFO_FOR_PREFETCH))
2018 continue;
2019 oid_array_append(&to_fetch, &entry->idx.oid);
2021 promisor_remote_get_direct(the_repository,
2022 to_fetch.oid, to_fetch.nr);
2023 oid_array_clear(&to_fetch);
2026 static void check_object(struct object_entry *entry, uint32_t object_index)
2028 unsigned long canonical_size;
2029 enum object_type type;
2030 struct object_info oi = {.typep = &type, .sizep = &canonical_size};
2032 if (IN_PACK(entry)) {
2033 struct packed_git *p = IN_PACK(entry);
2034 struct pack_window *w_curs = NULL;
2035 int have_base = 0;
2036 struct object_id base_ref;
2037 struct object_entry *base_entry;
2038 unsigned long used, used_0;
2039 unsigned long avail;
2040 off_t ofs;
2041 unsigned char *buf, c;
2042 enum object_type type;
2043 unsigned long in_pack_size;
2045 buf = use_pack(p, &w_curs, entry->in_pack_offset, &avail);
2048 * We want in_pack_type even if we do not reuse delta
2049 * since non-delta representations could still be reused.
2051 used = unpack_object_header_buffer(buf, avail,
2052 &type,
2053 &in_pack_size);
2054 if (used == 0)
2055 goto give_up;
2057 if (type < 0)
2058 BUG("invalid type %d", type);
2059 entry->in_pack_type = type;
2062 * Determine if this is a delta and if so whether we can
2063 * reuse it or not. Otherwise let's find out as cheaply as
2064 * possible what the actual type and size for this object is.
2066 switch (entry->in_pack_type) {
2067 default:
2068 /* Not a delta hence we've already got all we need. */
2069 oe_set_type(entry, entry->in_pack_type);
2070 SET_SIZE(entry, in_pack_size);
2071 entry->in_pack_header_size = used;
2072 if (oe_type(entry) < OBJ_COMMIT || oe_type(entry) > OBJ_BLOB)
2073 goto give_up;
2074 unuse_pack(&w_curs);
2075 return;
2076 case OBJ_REF_DELTA:
2077 if (reuse_delta && !entry->preferred_base) {
2078 oidread(&base_ref,
2079 use_pack(p, &w_curs,
2080 entry->in_pack_offset + used,
2081 NULL));
2082 have_base = 1;
2084 entry->in_pack_header_size = used + the_hash_algo->rawsz;
2085 break;
2086 case OBJ_OFS_DELTA:
2087 buf = use_pack(p, &w_curs,
2088 entry->in_pack_offset + used, NULL);
2089 used_0 = 0;
2090 c = buf[used_0++];
2091 ofs = c & 127;
2092 while (c & 128) {
2093 ofs += 1;
2094 if (!ofs || MSB(ofs, 7)) {
2095 error(_("delta base offset overflow in pack for %s"),
2096 oid_to_hex(&entry->idx.oid));
2097 goto give_up;
2099 c = buf[used_0++];
2100 ofs = (ofs << 7) + (c & 127);
2102 ofs = entry->in_pack_offset - ofs;
2103 if (ofs <= 0 || ofs >= entry->in_pack_offset) {
2104 error(_("delta base offset out of bound for %s"),
2105 oid_to_hex(&entry->idx.oid));
2106 goto give_up;
2108 if (reuse_delta && !entry->preferred_base) {
2109 uint32_t pos;
2110 if (offset_to_pack_pos(p, ofs, &pos) < 0)
2111 goto give_up;
2112 if (!nth_packed_object_id(&base_ref, p,
2113 pack_pos_to_index(p, pos)))
2114 have_base = 1;
2116 entry->in_pack_header_size = used + used_0;
2117 break;
2120 if (have_base &&
2121 can_reuse_delta(&base_ref, entry, &base_entry)) {
2122 oe_set_type(entry, entry->in_pack_type);
2123 SET_SIZE(entry, in_pack_size); /* delta size */
2124 SET_DELTA_SIZE(entry, in_pack_size);
2126 if (base_entry) {
2127 SET_DELTA(entry, base_entry);
2128 entry->delta_sibling_idx = base_entry->delta_child_idx;
2129 SET_DELTA_CHILD(base_entry, entry);
2130 } else {
2131 SET_DELTA_EXT(entry, &base_ref);
2134 unuse_pack(&w_curs);
2135 return;
2138 if (oe_type(entry)) {
2139 off_t delta_pos;
2142 * This must be a delta and we already know what the
2143 * final object type is. Let's extract the actual
2144 * object size from the delta header.
2146 delta_pos = entry->in_pack_offset + entry->in_pack_header_size;
2147 canonical_size = get_size_from_delta(p, &w_curs, delta_pos);
2148 if (canonical_size == 0)
2149 goto give_up;
2150 SET_SIZE(entry, canonical_size);
2151 unuse_pack(&w_curs);
2152 return;
2156 * No choice but to fall back to the recursive delta walk
2157 * with oid_object_info() to find about the object type
2158 * at this point...
2160 give_up:
2161 unuse_pack(&w_curs);
2164 if (oid_object_info_extended(the_repository, &entry->idx.oid, &oi,
2165 OBJECT_INFO_SKIP_FETCH_OBJECT | OBJECT_INFO_LOOKUP_REPLACE) < 0) {
2166 if (repo_has_promisor_remote(the_repository)) {
2167 prefetch_to_pack(object_index);
2168 if (oid_object_info_extended(the_repository, &entry->idx.oid, &oi,
2169 OBJECT_INFO_SKIP_FETCH_OBJECT | OBJECT_INFO_LOOKUP_REPLACE) < 0)
2170 type = -1;
2171 } else {
2172 type = -1;
2175 oe_set_type(entry, type);
2176 if (entry->type_valid) {
2177 SET_SIZE(entry, canonical_size);
2178 } else {
2180 * Bad object type is checked in prepare_pack(). This is
2181 * to permit a missing preferred base object to be ignored
2182 * as a preferred base. Doing so can result in a larger
2183 * pack file, but the transfer will still take place.
2188 static int pack_offset_sort(const void *_a, const void *_b)
2190 const struct object_entry *a = *(struct object_entry **)_a;
2191 const struct object_entry *b = *(struct object_entry **)_b;
2192 const struct packed_git *a_in_pack = IN_PACK(a);
2193 const struct packed_git *b_in_pack = IN_PACK(b);
2195 /* avoid filesystem trashing with loose objects */
2196 if (!a_in_pack && !b_in_pack)
2197 return oidcmp(&a->idx.oid, &b->idx.oid);
2199 if (a_in_pack < b_in_pack)
2200 return -1;
2201 if (a_in_pack > b_in_pack)
2202 return 1;
2203 return a->in_pack_offset < b->in_pack_offset ? -1 :
2204 (a->in_pack_offset > b->in_pack_offset);
2208 * Drop an on-disk delta we were planning to reuse. Naively, this would
2209 * just involve blanking out the "delta" field, but we have to deal
2210 * with some extra book-keeping:
2212 * 1. Removing ourselves from the delta_sibling linked list.
2214 * 2. Updating our size/type to the non-delta representation. These were
2215 * either not recorded initially (size) or overwritten with the delta type
2216 * (type) when check_object() decided to reuse the delta.
2218 * 3. Resetting our delta depth, as we are now a base object.
2220 static void drop_reused_delta(struct object_entry *entry)
2222 unsigned *idx = &to_pack.objects[entry->delta_idx - 1].delta_child_idx;
2223 struct object_info oi = OBJECT_INFO_INIT;
2224 enum object_type type;
2225 unsigned long size;
2227 while (*idx) {
2228 struct object_entry *oe = &to_pack.objects[*idx - 1];
2230 if (oe == entry)
2231 *idx = oe->delta_sibling_idx;
2232 else
2233 idx = &oe->delta_sibling_idx;
2235 SET_DELTA(entry, NULL);
2236 entry->depth = 0;
2238 oi.sizep = &size;
2239 oi.typep = &type;
2240 if (packed_object_info(the_repository, IN_PACK(entry), entry->in_pack_offset, &oi) < 0) {
2242 * We failed to get the info from this pack for some reason;
2243 * fall back to oid_object_info, which may find another copy.
2244 * And if that fails, the error will be recorded in oe_type(entry)
2245 * and dealt with in prepare_pack().
2247 oe_set_type(entry,
2248 oid_object_info(the_repository, &entry->idx.oid, &size));
2249 } else {
2250 oe_set_type(entry, type);
2252 SET_SIZE(entry, size);
2256 * Follow the chain of deltas from this entry onward, throwing away any links
2257 * that cause us to hit a cycle (as determined by the DFS state flags in
2258 * the entries).
2260 * We also detect too-long reused chains that would violate our --depth
2261 * limit.
2263 static void break_delta_chains(struct object_entry *entry)
2266 * The actual depth of each object we will write is stored as an int,
2267 * as it cannot exceed our int "depth" limit. But before we break
2268 * changes based no that limit, we may potentially go as deep as the
2269 * number of objects, which is elsewhere bounded to a uint32_t.
2271 uint32_t total_depth;
2272 struct object_entry *cur, *next;
2274 for (cur = entry, total_depth = 0;
2275 cur;
2276 cur = DELTA(cur), total_depth++) {
2277 if (cur->dfs_state == DFS_DONE) {
2279 * We've already seen this object and know it isn't
2280 * part of a cycle. We do need to append its depth
2281 * to our count.
2283 total_depth += cur->depth;
2284 break;
2288 * We break cycles before looping, so an ACTIVE state (or any
2289 * other cruft which made its way into the state variable)
2290 * is a bug.
2292 if (cur->dfs_state != DFS_NONE)
2293 BUG("confusing delta dfs state in first pass: %d",
2294 cur->dfs_state);
2297 * Now we know this is the first time we've seen the object. If
2298 * it's not a delta, we're done traversing, but we'll mark it
2299 * done to save time on future traversals.
2301 if (!DELTA(cur)) {
2302 cur->dfs_state = DFS_DONE;
2303 break;
2307 * Mark ourselves as active and see if the next step causes
2308 * us to cycle to another active object. It's important to do
2309 * this _before_ we loop, because it impacts where we make the
2310 * cut, and thus how our total_depth counter works.
2311 * E.g., We may see a partial loop like:
2313 * A -> B -> C -> D -> B
2315 * Cutting B->C breaks the cycle. But now the depth of A is
2316 * only 1, and our total_depth counter is at 3. The size of the
2317 * error is always one less than the size of the cycle we
2318 * broke. Commits C and D were "lost" from A's chain.
2320 * If we instead cut D->B, then the depth of A is correct at 3.
2321 * We keep all commits in the chain that we examined.
2323 cur->dfs_state = DFS_ACTIVE;
2324 if (DELTA(cur)->dfs_state == DFS_ACTIVE) {
2325 drop_reused_delta(cur);
2326 cur->dfs_state = DFS_DONE;
2327 break;
2332 * And now that we've gone all the way to the bottom of the chain, we
2333 * need to clear the active flags and set the depth fields as
2334 * appropriate. Unlike the loop above, which can quit when it drops a
2335 * delta, we need to keep going to look for more depth cuts. So we need
2336 * an extra "next" pointer to keep going after we reset cur->delta.
2338 for (cur = entry; cur; cur = next) {
2339 next = DELTA(cur);
2342 * We should have a chain of zero or more ACTIVE states down to
2343 * a final DONE. We can quit after the DONE, because either it
2344 * has no bases, or we've already handled them in a previous
2345 * call.
2347 if (cur->dfs_state == DFS_DONE)
2348 break;
2349 else if (cur->dfs_state != DFS_ACTIVE)
2350 BUG("confusing delta dfs state in second pass: %d",
2351 cur->dfs_state);
2354 * If the total_depth is more than depth, then we need to snip
2355 * the chain into two or more smaller chains that don't exceed
2356 * the maximum depth. Most of the resulting chains will contain
2357 * (depth + 1) entries (i.e., depth deltas plus one base), and
2358 * the last chain (i.e., the one containing entry) will contain
2359 * whatever entries are left over, namely
2360 * (total_depth % (depth + 1)) of them.
2362 * Since we are iterating towards decreasing depth, we need to
2363 * decrement total_depth as we go, and we need to write to the
2364 * entry what its final depth will be after all of the
2365 * snipping. Since we're snipping into chains of length (depth
2366 * + 1) entries, the final depth of an entry will be its
2367 * original depth modulo (depth + 1). Any time we encounter an
2368 * entry whose final depth is supposed to be zero, we snip it
2369 * from its delta base, thereby making it so.
2371 cur->depth = (total_depth--) % (depth + 1);
2372 if (!cur->depth)
2373 drop_reused_delta(cur);
2375 cur->dfs_state = DFS_DONE;
2379 static void get_object_details(void)
2381 uint32_t i;
2382 struct object_entry **sorted_by_offset;
2384 if (progress)
2385 progress_state = start_progress(_("Counting objects"),
2386 to_pack.nr_objects);
2388 CALLOC_ARRAY(sorted_by_offset, to_pack.nr_objects);
2389 for (i = 0; i < to_pack.nr_objects; i++)
2390 sorted_by_offset[i] = to_pack.objects + i;
2391 QSORT(sorted_by_offset, to_pack.nr_objects, pack_offset_sort);
2393 for (i = 0; i < to_pack.nr_objects; i++) {
2394 struct object_entry *entry = sorted_by_offset[i];
2395 check_object(entry, i);
2396 if (entry->type_valid &&
2397 oe_size_greater_than(&to_pack, entry, big_file_threshold))
2398 entry->no_try_delta = 1;
2399 display_progress(progress_state, i + 1);
2401 stop_progress(&progress_state);
2404 * This must happen in a second pass, since we rely on the delta
2405 * information for the whole list being completed.
2407 for (i = 0; i < to_pack.nr_objects; i++)
2408 break_delta_chains(&to_pack.objects[i]);
2410 free(sorted_by_offset);
2414 * We search for deltas in a list sorted by type, by filename hash, and then
2415 * by size, so that we see progressively smaller and smaller files.
2416 * That's because we prefer deltas to be from the bigger file
2417 * to the smaller -- deletes are potentially cheaper, but perhaps
2418 * more importantly, the bigger file is likely the more recent
2419 * one. The deepest deltas are therefore the oldest objects which are
2420 * less susceptible to be accessed often.
2422 static int type_size_sort(const void *_a, const void *_b)
2424 const struct object_entry *a = *(struct object_entry **)_a;
2425 const struct object_entry *b = *(struct object_entry **)_b;
2426 const enum object_type a_type = oe_type(a);
2427 const enum object_type b_type = oe_type(b);
2428 const unsigned long a_size = SIZE(a);
2429 const unsigned long b_size = SIZE(b);
2431 if (a_type > b_type)
2432 return -1;
2433 if (a_type < b_type)
2434 return 1;
2435 if (a->hash > b->hash)
2436 return -1;
2437 if (a->hash < b->hash)
2438 return 1;
2439 if (a->preferred_base > b->preferred_base)
2440 return -1;
2441 if (a->preferred_base < b->preferred_base)
2442 return 1;
2443 if (use_delta_islands) {
2444 const int island_cmp = island_delta_cmp(&a->idx.oid, &b->idx.oid);
2445 if (island_cmp)
2446 return island_cmp;
2448 if (a_size > b_size)
2449 return -1;
2450 if (a_size < b_size)
2451 return 1;
2452 return a < b ? -1 : (a > b); /* newest first */
2455 struct unpacked {
2456 struct object_entry *entry;
2457 void *data;
2458 struct delta_index *index;
2459 unsigned depth;
2462 static int delta_cacheable(unsigned long src_size, unsigned long trg_size,
2463 unsigned long delta_size)
2465 if (max_delta_cache_size && delta_cache_size + delta_size > max_delta_cache_size)
2466 return 0;
2468 if (delta_size < cache_max_small_delta_size)
2469 return 1;
2471 /* cache delta, if objects are large enough compared to delta size */
2472 if ((src_size >> 20) + (trg_size >> 21) > (delta_size >> 10))
2473 return 1;
2475 return 0;
2478 /* Protect delta_cache_size */
2479 static pthread_mutex_t cache_mutex;
2480 #define cache_lock() pthread_mutex_lock(&cache_mutex)
2481 #define cache_unlock() pthread_mutex_unlock(&cache_mutex)
2484 * Protect object list partitioning (e.g. struct thread_param) and
2485 * progress_state
2487 static pthread_mutex_t progress_mutex;
2488 #define progress_lock() pthread_mutex_lock(&progress_mutex)
2489 #define progress_unlock() pthread_mutex_unlock(&progress_mutex)
2492 * Access to struct object_entry is unprotected since each thread owns
2493 * a portion of the main object list. Just don't access object entries
2494 * ahead in the list because they can be stolen and would need
2495 * progress_mutex for protection.
2498 static inline int oe_size_less_than(struct packing_data *pack,
2499 const struct object_entry *lhs,
2500 unsigned long rhs)
2502 if (lhs->size_valid)
2503 return lhs->size_ < rhs;
2504 if (rhs < pack->oe_size_limit) /* rhs < 2^x <= lhs ? */
2505 return 0;
2506 return oe_get_size_slow(pack, lhs) < rhs;
2509 static inline void oe_set_tree_depth(struct packing_data *pack,
2510 struct object_entry *e,
2511 unsigned int tree_depth)
2513 if (!pack->tree_depth)
2514 CALLOC_ARRAY(pack->tree_depth, pack->nr_alloc);
2515 pack->tree_depth[e - pack->objects] = tree_depth;
2519 * Return the size of the object without doing any delta
2520 * reconstruction (so non-deltas are true object sizes, but deltas
2521 * return the size of the delta data).
2523 unsigned long oe_get_size_slow(struct packing_data *pack,
2524 const struct object_entry *e)
2526 struct packed_git *p;
2527 struct pack_window *w_curs;
2528 unsigned char *buf;
2529 enum object_type type;
2530 unsigned long used, avail, size;
2532 if (e->type_ != OBJ_OFS_DELTA && e->type_ != OBJ_REF_DELTA) {
2533 packing_data_lock(&to_pack);
2534 if (oid_object_info(the_repository, &e->idx.oid, &size) < 0)
2535 die(_("unable to get size of %s"),
2536 oid_to_hex(&e->idx.oid));
2537 packing_data_unlock(&to_pack);
2538 return size;
2541 p = oe_in_pack(pack, e);
2542 if (!p)
2543 BUG("when e->type is a delta, it must belong to a pack");
2545 packing_data_lock(&to_pack);
2546 w_curs = NULL;
2547 buf = use_pack(p, &w_curs, e->in_pack_offset, &avail);
2548 used = unpack_object_header_buffer(buf, avail, &type, &size);
2549 if (used == 0)
2550 die(_("unable to parse object header of %s"),
2551 oid_to_hex(&e->idx.oid));
2553 unuse_pack(&w_curs);
2554 packing_data_unlock(&to_pack);
2555 return size;
2558 static int try_delta(struct unpacked *trg, struct unpacked *src,
2559 unsigned max_depth, unsigned long *mem_usage)
2561 struct object_entry *trg_entry = trg->entry;
2562 struct object_entry *src_entry = src->entry;
2563 unsigned long trg_size, src_size, delta_size, sizediff, max_size, sz;
2564 unsigned ref_depth;
2565 enum object_type type;
2566 void *delta_buf;
2568 /* Don't bother doing diffs between different types */
2569 if (oe_type(trg_entry) != oe_type(src_entry))
2570 return -1;
2573 * We do not bother to try a delta that we discarded on an
2574 * earlier try, but only when reusing delta data. Note that
2575 * src_entry that is marked as the preferred_base should always
2576 * be considered, as even if we produce a suboptimal delta against
2577 * it, we will still save the transfer cost, as we already know
2578 * the other side has it and we won't send src_entry at all.
2580 if (reuse_delta && IN_PACK(trg_entry) &&
2581 IN_PACK(trg_entry) == IN_PACK(src_entry) &&
2582 !src_entry->preferred_base &&
2583 trg_entry->in_pack_type != OBJ_REF_DELTA &&
2584 trg_entry->in_pack_type != OBJ_OFS_DELTA)
2585 return 0;
2587 /* Let's not bust the allowed depth. */
2588 if (src->depth >= max_depth)
2589 return 0;
2591 /* Now some size filtering heuristics. */
2592 trg_size = SIZE(trg_entry);
2593 if (!DELTA(trg_entry)) {
2594 max_size = trg_size/2 - the_hash_algo->rawsz;
2595 ref_depth = 1;
2596 } else {
2597 max_size = DELTA_SIZE(trg_entry);
2598 ref_depth = trg->depth;
2600 max_size = (uint64_t)max_size * (max_depth - src->depth) /
2601 (max_depth - ref_depth + 1);
2602 if (max_size == 0)
2603 return 0;
2604 src_size = SIZE(src_entry);
2605 sizediff = src_size < trg_size ? trg_size - src_size : 0;
2606 if (sizediff >= max_size)
2607 return 0;
2608 if (trg_size < src_size / 32)
2609 return 0;
2611 if (!in_same_island(&trg->entry->idx.oid, &src->entry->idx.oid))
2612 return 0;
2614 /* Load data if not already done */
2615 if (!trg->data) {
2616 packing_data_lock(&to_pack);
2617 trg->data = repo_read_object_file(the_repository,
2618 &trg_entry->idx.oid, &type,
2619 &sz);
2620 packing_data_unlock(&to_pack);
2621 if (!trg->data)
2622 die(_("object %s cannot be read"),
2623 oid_to_hex(&trg_entry->idx.oid));
2624 if (sz != trg_size)
2625 die(_("object %s inconsistent object length (%"PRIuMAX" vs %"PRIuMAX")"),
2626 oid_to_hex(&trg_entry->idx.oid), (uintmax_t)sz,
2627 (uintmax_t)trg_size);
2628 *mem_usage += sz;
2630 if (!src->data) {
2631 packing_data_lock(&to_pack);
2632 src->data = repo_read_object_file(the_repository,
2633 &src_entry->idx.oid, &type,
2634 &sz);
2635 packing_data_unlock(&to_pack);
2636 if (!src->data) {
2637 if (src_entry->preferred_base) {
2638 static int warned = 0;
2639 if (!warned++)
2640 warning(_("object %s cannot be read"),
2641 oid_to_hex(&src_entry->idx.oid));
2643 * Those objects are not included in the
2644 * resulting pack. Be resilient and ignore
2645 * them if they can't be read, in case the
2646 * pack could be created nevertheless.
2648 return 0;
2650 die(_("object %s cannot be read"),
2651 oid_to_hex(&src_entry->idx.oid));
2653 if (sz != src_size)
2654 die(_("object %s inconsistent object length (%"PRIuMAX" vs %"PRIuMAX")"),
2655 oid_to_hex(&src_entry->idx.oid), (uintmax_t)sz,
2656 (uintmax_t)src_size);
2657 *mem_usage += sz;
2659 if (!src->index) {
2660 src->index = create_delta_index(src->data, src_size);
2661 if (!src->index) {
2662 static int warned = 0;
2663 if (!warned++)
2664 warning(_("suboptimal pack - out of memory"));
2665 return 0;
2667 *mem_usage += sizeof_delta_index(src->index);
2670 delta_buf = create_delta(src->index, trg->data, trg_size, &delta_size, max_size);
2671 if (!delta_buf)
2672 return 0;
2674 if (DELTA(trg_entry)) {
2675 /* Prefer only shallower same-sized deltas. */
2676 if (delta_size == DELTA_SIZE(trg_entry) &&
2677 src->depth + 1 >= trg->depth) {
2678 free(delta_buf);
2679 return 0;
2684 * Handle memory allocation outside of the cache
2685 * accounting lock. Compiler will optimize the strangeness
2686 * away when NO_PTHREADS is defined.
2688 free(trg_entry->delta_data);
2689 cache_lock();
2690 if (trg_entry->delta_data) {
2691 delta_cache_size -= DELTA_SIZE(trg_entry);
2692 trg_entry->delta_data = NULL;
2694 if (delta_cacheable(src_size, trg_size, delta_size)) {
2695 delta_cache_size += delta_size;
2696 cache_unlock();
2697 trg_entry->delta_data = xrealloc(delta_buf, delta_size);
2698 } else {
2699 cache_unlock();
2700 free(delta_buf);
2703 SET_DELTA(trg_entry, src_entry);
2704 SET_DELTA_SIZE(trg_entry, delta_size);
2705 trg->depth = src->depth + 1;
2707 return 1;
2710 static unsigned int check_delta_limit(struct object_entry *me, unsigned int n)
2712 struct object_entry *child = DELTA_CHILD(me);
2713 unsigned int m = n;
2714 while (child) {
2715 const unsigned int c = check_delta_limit(child, n + 1);
2716 if (m < c)
2717 m = c;
2718 child = DELTA_SIBLING(child);
2720 return m;
2723 static unsigned long free_unpacked(struct unpacked *n)
2725 unsigned long freed_mem = sizeof_delta_index(n->index);
2726 free_delta_index(n->index);
2727 n->index = NULL;
2728 if (n->data) {
2729 freed_mem += SIZE(n->entry);
2730 FREE_AND_NULL(n->data);
2732 n->entry = NULL;
2733 n->depth = 0;
2734 return freed_mem;
2737 static void find_deltas(struct object_entry **list, unsigned *list_size,
2738 int window, int depth, unsigned *processed)
2740 uint32_t i, idx = 0, count = 0;
2741 struct unpacked *array;
2742 unsigned long mem_usage = 0;
2744 CALLOC_ARRAY(array, window);
2746 for (;;) {
2747 struct object_entry *entry;
2748 struct unpacked *n = array + idx;
2749 int j, max_depth, best_base = -1;
2751 progress_lock();
2752 if (!*list_size) {
2753 progress_unlock();
2754 break;
2756 entry = *list++;
2757 (*list_size)--;
2758 if (!entry->preferred_base) {
2759 (*processed)++;
2760 display_progress(progress_state, *processed);
2762 progress_unlock();
2764 mem_usage -= free_unpacked(n);
2765 n->entry = entry;
2767 while (window_memory_limit &&
2768 mem_usage > window_memory_limit &&
2769 count > 1) {
2770 const uint32_t tail = (idx + window - count) % window;
2771 mem_usage -= free_unpacked(array + tail);
2772 count--;
2775 /* We do not compute delta to *create* objects we are not
2776 * going to pack.
2778 if (entry->preferred_base)
2779 goto next;
2782 * If the current object is at pack edge, take the depth the
2783 * objects that depend on the current object into account
2784 * otherwise they would become too deep.
2786 max_depth = depth;
2787 if (DELTA_CHILD(entry)) {
2788 max_depth -= check_delta_limit(entry, 0);
2789 if (max_depth <= 0)
2790 goto next;
2793 j = window;
2794 while (--j > 0) {
2795 int ret;
2796 uint32_t other_idx = idx + j;
2797 struct unpacked *m;
2798 if (other_idx >= window)
2799 other_idx -= window;
2800 m = array + other_idx;
2801 if (!m->entry)
2802 break;
2803 ret = try_delta(n, m, max_depth, &mem_usage);
2804 if (ret < 0)
2805 break;
2806 else if (ret > 0)
2807 best_base = other_idx;
2811 * If we decided to cache the delta data, then it is best
2812 * to compress it right away. First because we have to do
2813 * it anyway, and doing it here while we're threaded will
2814 * save a lot of time in the non threaded write phase,
2815 * as well as allow for caching more deltas within
2816 * the same cache size limit.
2817 * ...
2818 * But only if not writing to stdout, since in that case
2819 * the network is most likely throttling writes anyway,
2820 * and therefore it is best to go to the write phase ASAP
2821 * instead, as we can afford spending more time compressing
2822 * between writes at that moment.
2824 if (entry->delta_data && !pack_to_stdout) {
2825 unsigned long size;
2827 size = do_compress(&entry->delta_data, DELTA_SIZE(entry));
2828 if (size < (1U << OE_Z_DELTA_BITS)) {
2829 entry->z_delta_size = size;
2830 cache_lock();
2831 delta_cache_size -= DELTA_SIZE(entry);
2832 delta_cache_size += entry->z_delta_size;
2833 cache_unlock();
2834 } else {
2835 FREE_AND_NULL(entry->delta_data);
2836 entry->z_delta_size = 0;
2840 /* if we made n a delta, and if n is already at max
2841 * depth, leaving it in the window is pointless. we
2842 * should evict it first.
2844 if (DELTA(entry) && max_depth <= n->depth)
2845 continue;
2848 * Move the best delta base up in the window, after the
2849 * currently deltified object, to keep it longer. It will
2850 * be the first base object to be attempted next.
2852 if (DELTA(entry)) {
2853 struct unpacked swap = array[best_base];
2854 int dist = (window + idx - best_base) % window;
2855 int dst = best_base;
2856 while (dist--) {
2857 int src = (dst + 1) % window;
2858 array[dst] = array[src];
2859 dst = src;
2861 array[dst] = swap;
2864 next:
2865 idx++;
2866 if (count + 1 < window)
2867 count++;
2868 if (idx >= window)
2869 idx = 0;
2872 for (i = 0; i < window; ++i) {
2873 free_delta_index(array[i].index);
2874 free(array[i].data);
2876 free(array);
2880 * The main object list is split into smaller lists, each is handed to
2881 * one worker.
2883 * The main thread waits on the condition that (at least) one of the workers
2884 * has stopped working (which is indicated in the .working member of
2885 * struct thread_params).
2887 * When a work thread has completed its work, it sets .working to 0 and
2888 * signals the main thread and waits on the condition that .data_ready
2889 * becomes 1.
2891 * The main thread steals half of the work from the worker that has
2892 * most work left to hand it to the idle worker.
2895 struct thread_params {
2896 pthread_t thread;
2897 struct object_entry **list;
2898 unsigned list_size;
2899 unsigned remaining;
2900 int window;
2901 int depth;
2902 int working;
2903 int data_ready;
2904 pthread_mutex_t mutex;
2905 pthread_cond_t cond;
2906 unsigned *processed;
2909 static pthread_cond_t progress_cond;
2912 * Mutex and conditional variable can't be statically-initialized on Windows.
2914 static void init_threaded_search(void)
2916 pthread_mutex_init(&cache_mutex, NULL);
2917 pthread_mutex_init(&progress_mutex, NULL);
2918 pthread_cond_init(&progress_cond, NULL);
2921 static void cleanup_threaded_search(void)
2923 pthread_cond_destroy(&progress_cond);
2924 pthread_mutex_destroy(&cache_mutex);
2925 pthread_mutex_destroy(&progress_mutex);
2928 static void *threaded_find_deltas(void *arg)
2930 struct thread_params *me = arg;
2932 progress_lock();
2933 while (me->remaining) {
2934 progress_unlock();
2936 find_deltas(me->list, &me->remaining,
2937 me->window, me->depth, me->processed);
2939 progress_lock();
2940 me->working = 0;
2941 pthread_cond_signal(&progress_cond);
2942 progress_unlock();
2945 * We must not set ->data_ready before we wait on the
2946 * condition because the main thread may have set it to 1
2947 * before we get here. In order to be sure that new
2948 * work is available if we see 1 in ->data_ready, it
2949 * was initialized to 0 before this thread was spawned
2950 * and we reset it to 0 right away.
2952 pthread_mutex_lock(&me->mutex);
2953 while (!me->data_ready)
2954 pthread_cond_wait(&me->cond, &me->mutex);
2955 me->data_ready = 0;
2956 pthread_mutex_unlock(&me->mutex);
2958 progress_lock();
2960 progress_unlock();
2961 /* leave ->working 1 so that this doesn't get more work assigned */
2962 return NULL;
2965 static void ll_find_deltas(struct object_entry **list, unsigned list_size,
2966 int window, int depth, unsigned *processed)
2968 struct thread_params *p;
2969 int i, ret, active_threads = 0;
2971 init_threaded_search();
2973 if (delta_search_threads <= 1) {
2974 find_deltas(list, &list_size, window, depth, processed);
2975 cleanup_threaded_search();
2976 return;
2978 if (progress > pack_to_stdout)
2979 fprintf_ln(stderr, _("Delta compression using up to %d threads"),
2980 delta_search_threads);
2981 CALLOC_ARRAY(p, delta_search_threads);
2983 /* Partition the work amongst work threads. */
2984 for (i = 0; i < delta_search_threads; i++) {
2985 unsigned sub_size = list_size / (delta_search_threads - i);
2987 /* don't use too small segments or no deltas will be found */
2988 if (sub_size < 2*window && i+1 < delta_search_threads)
2989 sub_size = 0;
2991 p[i].window = window;
2992 p[i].depth = depth;
2993 p[i].processed = processed;
2994 p[i].working = 1;
2995 p[i].data_ready = 0;
2997 /* try to split chunks on "path" boundaries */
2998 while (sub_size && sub_size < list_size &&
2999 list[sub_size]->hash &&
3000 list[sub_size]->hash == list[sub_size-1]->hash)
3001 sub_size++;
3003 p[i].list = list;
3004 p[i].list_size = sub_size;
3005 p[i].remaining = sub_size;
3007 list += sub_size;
3008 list_size -= sub_size;
3011 /* Start work threads. */
3012 for (i = 0; i < delta_search_threads; i++) {
3013 if (!p[i].list_size)
3014 continue;
3015 pthread_mutex_init(&p[i].mutex, NULL);
3016 pthread_cond_init(&p[i].cond, NULL);
3017 ret = pthread_create(&p[i].thread, NULL,
3018 threaded_find_deltas, &p[i]);
3019 if (ret)
3020 die(_("unable to create thread: %s"), strerror(ret));
3021 active_threads++;
3025 * Now let's wait for work completion. Each time a thread is done
3026 * with its work, we steal half of the remaining work from the
3027 * thread with the largest number of unprocessed objects and give
3028 * it to that newly idle thread. This ensure good load balancing
3029 * until the remaining object list segments are simply too short
3030 * to be worth splitting anymore.
3032 while (active_threads) {
3033 struct thread_params *target = NULL;
3034 struct thread_params *victim = NULL;
3035 unsigned sub_size = 0;
3037 progress_lock();
3038 for (;;) {
3039 for (i = 0; !target && i < delta_search_threads; i++)
3040 if (!p[i].working)
3041 target = &p[i];
3042 if (target)
3043 break;
3044 pthread_cond_wait(&progress_cond, &progress_mutex);
3047 for (i = 0; i < delta_search_threads; i++)
3048 if (p[i].remaining > 2*window &&
3049 (!victim || victim->remaining < p[i].remaining))
3050 victim = &p[i];
3051 if (victim) {
3052 sub_size = victim->remaining / 2;
3053 list = victim->list + victim->list_size - sub_size;
3054 while (sub_size && list[0]->hash &&
3055 list[0]->hash == list[-1]->hash) {
3056 list++;
3057 sub_size--;
3059 if (!sub_size) {
3061 * It is possible for some "paths" to have
3062 * so many objects that no hash boundary
3063 * might be found. Let's just steal the
3064 * exact half in that case.
3066 sub_size = victim->remaining / 2;
3067 list -= sub_size;
3069 target->list = list;
3070 victim->list_size -= sub_size;
3071 victim->remaining -= sub_size;
3073 target->list_size = sub_size;
3074 target->remaining = sub_size;
3075 target->working = 1;
3076 progress_unlock();
3078 pthread_mutex_lock(&target->mutex);
3079 target->data_ready = 1;
3080 pthread_cond_signal(&target->cond);
3081 pthread_mutex_unlock(&target->mutex);
3083 if (!sub_size) {
3084 pthread_join(target->thread, NULL);
3085 pthread_cond_destroy(&target->cond);
3086 pthread_mutex_destroy(&target->mutex);
3087 active_threads--;
3090 cleanup_threaded_search();
3091 free(p);
3094 static int obj_is_packed(const struct object_id *oid)
3096 return packlist_find(&to_pack, oid) ||
3097 (reuse_packfile_bitmap &&
3098 bitmap_walk_contains(bitmap_git, reuse_packfile_bitmap, oid));
3101 static void add_tag_chain(const struct object_id *oid)
3103 struct tag *tag;
3106 * We catch duplicates already in add_object_entry(), but we'd
3107 * prefer to do this extra check to avoid having to parse the
3108 * tag at all if we already know that it's being packed (e.g., if
3109 * it was included via bitmaps, we would not have parsed it
3110 * previously).
3112 if (obj_is_packed(oid))
3113 return;
3115 tag = lookup_tag(the_repository, oid);
3116 while (1) {
3117 if (!tag || parse_tag(tag) || !tag->tagged)
3118 die(_("unable to pack objects reachable from tag %s"),
3119 oid_to_hex(oid));
3121 add_object_entry(&tag->object.oid, OBJ_TAG, NULL, 0);
3123 if (tag->tagged->type != OBJ_TAG)
3124 return;
3126 tag = (struct tag *)tag->tagged;
3130 static int add_ref_tag(const char *tag UNUSED, const struct object_id *oid,
3131 int flag UNUSED, void *cb_data UNUSED)
3133 struct object_id peeled;
3135 if (!peel_iterated_oid(the_repository, oid, &peeled) && obj_is_packed(&peeled))
3136 add_tag_chain(oid);
3137 return 0;
3140 static void prepare_pack(int window, int depth)
3142 struct object_entry **delta_list;
3143 uint32_t i, nr_deltas;
3144 unsigned n;
3146 if (use_delta_islands)
3147 resolve_tree_islands(the_repository, progress, &to_pack);
3149 get_object_details();
3152 * If we're locally repacking then we need to be doubly careful
3153 * from now on in order to make sure no stealth corruption gets
3154 * propagated to the new pack. Clients receiving streamed packs
3155 * should validate everything they get anyway so no need to incur
3156 * the additional cost here in that case.
3158 if (!pack_to_stdout)
3159 do_check_packed_object_crc = 1;
3161 if (!to_pack.nr_objects || !window || !depth)
3162 return;
3164 ALLOC_ARRAY(delta_list, to_pack.nr_objects);
3165 nr_deltas = n = 0;
3167 for (i = 0; i < to_pack.nr_objects; i++) {
3168 struct object_entry *entry = to_pack.objects + i;
3170 if (DELTA(entry))
3171 /* This happens if we decided to reuse existing
3172 * delta from a pack. "reuse_delta &&" is implied.
3174 continue;
3176 if (!entry->type_valid ||
3177 oe_size_less_than(&to_pack, entry, 50))
3178 continue;
3180 if (entry->no_try_delta)
3181 continue;
3183 if (!entry->preferred_base) {
3184 nr_deltas++;
3185 if (oe_type(entry) < 0)
3186 die(_("unable to get type of object %s"),
3187 oid_to_hex(&entry->idx.oid));
3188 } else {
3189 if (oe_type(entry) < 0) {
3191 * This object is not found, but we
3192 * don't have to include it anyway.
3194 continue;
3198 delta_list[n++] = entry;
3201 if (nr_deltas && n > 1) {
3202 unsigned nr_done = 0;
3204 if (progress)
3205 progress_state = start_progress(_("Compressing objects"),
3206 nr_deltas);
3207 QSORT(delta_list, n, type_size_sort);
3208 ll_find_deltas(delta_list, n, window+1, depth, &nr_done);
3209 stop_progress(&progress_state);
3210 if (nr_done != nr_deltas)
3211 die(_("inconsistency with delta count"));
3213 free(delta_list);
3216 static int git_pack_config(const char *k, const char *v,
3217 const struct config_context *ctx, void *cb)
3219 if (!strcmp(k, "pack.window")) {
3220 window = git_config_int(k, v, ctx->kvi);
3221 return 0;
3223 if (!strcmp(k, "pack.windowmemory")) {
3224 window_memory_limit = git_config_ulong(k, v, ctx->kvi);
3225 return 0;
3227 if (!strcmp(k, "pack.depth")) {
3228 depth = git_config_int(k, v, ctx->kvi);
3229 return 0;
3231 if (!strcmp(k, "pack.deltacachesize")) {
3232 max_delta_cache_size = git_config_int(k, v, ctx->kvi);
3233 return 0;
3235 if (!strcmp(k, "pack.deltacachelimit")) {
3236 cache_max_small_delta_size = git_config_int(k, v, ctx->kvi);
3237 return 0;
3239 if (!strcmp(k, "pack.writebitmaphashcache")) {
3240 if (git_config_bool(k, v))
3241 write_bitmap_options |= BITMAP_OPT_HASH_CACHE;
3242 else
3243 write_bitmap_options &= ~BITMAP_OPT_HASH_CACHE;
3246 if (!strcmp(k, "pack.writebitmaplookuptable")) {
3247 if (git_config_bool(k, v))
3248 write_bitmap_options |= BITMAP_OPT_LOOKUP_TABLE;
3249 else
3250 write_bitmap_options &= ~BITMAP_OPT_LOOKUP_TABLE;
3253 if (!strcmp(k, "pack.usebitmaps")) {
3254 use_bitmap_index_default = git_config_bool(k, v);
3255 return 0;
3257 if (!strcmp(k, "pack.allowpackreuse")) {
3258 int res = git_parse_maybe_bool_text(v);
3259 if (res < 0) {
3260 if (!strcasecmp(v, "single"))
3261 allow_pack_reuse = SINGLE_PACK_REUSE;
3262 else if (!strcasecmp(v, "multi"))
3263 allow_pack_reuse = MULTI_PACK_REUSE;
3264 else
3265 die(_("invalid pack.allowPackReuse value: '%s'"), v);
3266 } else if (res) {
3267 allow_pack_reuse = SINGLE_PACK_REUSE;
3268 } else {
3269 allow_pack_reuse = NO_PACK_REUSE;
3271 return 0;
3273 if (!strcmp(k, "pack.threads")) {
3274 delta_search_threads = git_config_int(k, v, ctx->kvi);
3275 if (delta_search_threads < 0)
3276 die(_("invalid number of threads specified (%d)"),
3277 delta_search_threads);
3278 if (!HAVE_THREADS && delta_search_threads != 1) {
3279 warning(_("no threads support, ignoring %s"), k);
3280 delta_search_threads = 0;
3282 return 0;
3284 if (!strcmp(k, "pack.indexversion")) {
3285 pack_idx_opts.version = git_config_int(k, v, ctx->kvi);
3286 if (pack_idx_opts.version > 2)
3287 die(_("bad pack.indexVersion=%"PRIu32),
3288 pack_idx_opts.version);
3289 return 0;
3291 if (!strcmp(k, "pack.writereverseindex")) {
3292 if (git_config_bool(k, v))
3293 pack_idx_opts.flags |= WRITE_REV;
3294 else
3295 pack_idx_opts.flags &= ~WRITE_REV;
3296 return 0;
3298 if (!strcmp(k, "uploadpack.blobpackfileuri")) {
3299 struct configured_exclusion *ex;
3300 const char *oid_end, *pack_end;
3302 * Stores the pack hash. This is not a true object ID, but is
3303 * of the same form.
3305 struct object_id pack_hash;
3307 if (!v)
3308 return config_error_nonbool(k);
3310 ex = xmalloc(sizeof(*ex));
3311 if (parse_oid_hex(v, &ex->e.oid, &oid_end) ||
3312 *oid_end != ' ' ||
3313 parse_oid_hex(oid_end + 1, &pack_hash, &pack_end) ||
3314 *pack_end != ' ')
3315 die(_("value of uploadpack.blobpackfileuri must be "
3316 "of the form '<object-hash> <pack-hash> <uri>' (got '%s')"), v);
3317 if (oidmap_get(&configured_exclusions, &ex->e.oid))
3318 die(_("object already configured in another "
3319 "uploadpack.blobpackfileuri (got '%s')"), v);
3320 ex->pack_hash_hex = xcalloc(1, pack_end - oid_end);
3321 memcpy(ex->pack_hash_hex, oid_end + 1, pack_end - oid_end - 1);
3322 ex->uri = xstrdup(pack_end + 1);
3323 oidmap_put(&configured_exclusions, ex);
3325 return git_default_config(k, v, ctx, cb);
3328 /* Counters for trace2 output when in --stdin-packs mode. */
3329 static int stdin_packs_found_nr;
3330 static int stdin_packs_hints_nr;
3332 static int add_object_entry_from_pack(const struct object_id *oid,
3333 struct packed_git *p,
3334 uint32_t pos,
3335 void *_data)
3337 off_t ofs;
3338 enum object_type type = OBJ_NONE;
3340 display_progress(progress_state, ++nr_seen);
3342 if (have_duplicate_entry(oid, 0))
3343 return 0;
3345 ofs = nth_packed_object_offset(p, pos);
3346 if (!want_object_in_pack(oid, 0, &p, &ofs))
3347 return 0;
3349 if (p) {
3350 struct rev_info *revs = _data;
3351 struct object_info oi = OBJECT_INFO_INIT;
3353 oi.typep = &type;
3354 if (packed_object_info(the_repository, p, ofs, &oi) < 0) {
3355 die(_("could not get type of object %s in pack %s"),
3356 oid_to_hex(oid), p->pack_name);
3357 } else if (type == OBJ_COMMIT) {
3359 * commits in included packs are used as starting points for the
3360 * subsequent revision walk
3362 add_pending_oid(revs, NULL, oid, 0);
3365 stdin_packs_found_nr++;
3368 create_object_entry(oid, type, 0, 0, 0, p, ofs);
3370 return 0;
3373 static void show_commit_pack_hint(struct commit *commit UNUSED,
3374 void *data UNUSED)
3376 /* nothing to do; commits don't have a namehash */
3379 static void show_object_pack_hint(struct object *object, const char *name,
3380 void *data UNUSED)
3382 struct object_entry *oe = packlist_find(&to_pack, &object->oid);
3383 if (!oe)
3384 return;
3387 * Our 'to_pack' list was constructed by iterating all objects packed in
3388 * included packs, and so doesn't have a non-zero hash field that you
3389 * would typically pick up during a reachability traversal.
3391 * Make a best-effort attempt to fill in the ->hash and ->no_try_delta
3392 * here using a now in order to perhaps improve the delta selection
3393 * process.
3395 oe->hash = pack_name_hash(name);
3396 oe->no_try_delta = name && no_try_delta(name);
3398 stdin_packs_hints_nr++;
3401 static int pack_mtime_cmp(const void *_a, const void *_b)
3403 struct packed_git *a = ((const struct string_list_item*)_a)->util;
3404 struct packed_git *b = ((const struct string_list_item*)_b)->util;
3407 * order packs by descending mtime so that objects are laid out
3408 * roughly as newest-to-oldest
3410 if (a->mtime < b->mtime)
3411 return 1;
3412 else if (b->mtime < a->mtime)
3413 return -1;
3414 else
3415 return 0;
3418 static void read_packs_list_from_stdin(void)
3420 struct strbuf buf = STRBUF_INIT;
3421 struct string_list include_packs = STRING_LIST_INIT_DUP;
3422 struct string_list exclude_packs = STRING_LIST_INIT_DUP;
3423 struct string_list_item *item = NULL;
3425 struct packed_git *p;
3426 struct rev_info revs;
3428 repo_init_revisions(the_repository, &revs, NULL);
3430 * Use a revision walk to fill in the namehash of objects in the include
3431 * packs. To save time, we'll avoid traversing through objects that are
3432 * in excluded packs.
3434 * That may cause us to avoid populating all of the namehash fields of
3435 * all included objects, but our goal is best-effort, since this is only
3436 * an optimization during delta selection.
3438 revs.no_kept_objects = 1;
3439 revs.keep_pack_cache_flags |= IN_CORE_KEEP_PACKS;
3440 revs.blob_objects = 1;
3441 revs.tree_objects = 1;
3442 revs.tag_objects = 1;
3443 revs.ignore_missing_links = 1;
3445 while (strbuf_getline(&buf, stdin) != EOF) {
3446 if (!buf.len)
3447 continue;
3449 if (*buf.buf == '^')
3450 string_list_append(&exclude_packs, buf.buf + 1);
3451 else
3452 string_list_append(&include_packs, buf.buf);
3454 strbuf_reset(&buf);
3457 string_list_sort(&include_packs);
3458 string_list_remove_duplicates(&include_packs, 0);
3459 string_list_sort(&exclude_packs);
3460 string_list_remove_duplicates(&exclude_packs, 0);
3462 for (p = get_all_packs(the_repository); p; p = p->next) {
3463 const char *pack_name = pack_basename(p);
3465 if ((item = string_list_lookup(&include_packs, pack_name)))
3466 item->util = p;
3467 if ((item = string_list_lookup(&exclude_packs, pack_name)))
3468 item->util = p;
3472 * Arguments we got on stdin may not even be packs. First
3473 * check that to avoid segfaulting later on in
3474 * e.g. pack_mtime_cmp(), excluded packs are handled below.
3476 * Since we first parsed our STDIN and then sorted the input
3477 * lines the pack we error on will be whatever line happens to
3478 * sort first. This is lazy, it's enough that we report one
3479 * bad case here, we don't need to report the first/last one,
3480 * or all of them.
3482 for_each_string_list_item(item, &include_packs) {
3483 struct packed_git *p = item->util;
3484 if (!p)
3485 die(_("could not find pack '%s'"), item->string);
3486 if (!is_pack_valid(p))
3487 die(_("packfile %s cannot be accessed"), p->pack_name);
3491 * Then, handle all of the excluded packs, marking them as
3492 * kept in-core so that later calls to add_object_entry()
3493 * discards any objects that are also found in excluded packs.
3495 for_each_string_list_item(item, &exclude_packs) {
3496 struct packed_git *p = item->util;
3497 if (!p)
3498 die(_("could not find pack '%s'"), item->string);
3499 p->pack_keep_in_core = 1;
3503 * Order packs by ascending mtime; use QSORT directly to access the
3504 * string_list_item's ->util pointer, which string_list_sort() does not
3505 * provide.
3507 QSORT(include_packs.items, include_packs.nr, pack_mtime_cmp);
3509 for_each_string_list_item(item, &include_packs) {
3510 struct packed_git *p = item->util;
3511 for_each_object_in_pack(p,
3512 add_object_entry_from_pack,
3513 &revs,
3514 FOR_EACH_OBJECT_PACK_ORDER);
3517 if (prepare_revision_walk(&revs))
3518 die(_("revision walk setup failed"));
3519 traverse_commit_list(&revs,
3520 show_commit_pack_hint,
3521 show_object_pack_hint,
3522 NULL);
3524 trace2_data_intmax("pack-objects", the_repository, "stdin_packs_found",
3525 stdin_packs_found_nr);
3526 trace2_data_intmax("pack-objects", the_repository, "stdin_packs_hints",
3527 stdin_packs_hints_nr);
3529 strbuf_release(&buf);
3530 string_list_clear(&include_packs, 0);
3531 string_list_clear(&exclude_packs, 0);
3534 static void add_cruft_object_entry(const struct object_id *oid, enum object_type type,
3535 struct packed_git *pack, off_t offset,
3536 const char *name, uint32_t mtime)
3538 struct object_entry *entry;
3540 display_progress(progress_state, ++nr_seen);
3542 entry = packlist_find(&to_pack, oid);
3543 if (entry) {
3544 if (name) {
3545 entry->hash = pack_name_hash(name);
3546 entry->no_try_delta = no_try_delta(name);
3548 } else {
3549 if (!want_object_in_pack(oid, 0, &pack, &offset))
3550 return;
3551 if (!pack && type == OBJ_BLOB && !has_loose_object(oid)) {
3553 * If a traversed tree has a missing blob then we want
3554 * to avoid adding that missing object to our pack.
3556 * This only applies to missing blobs, not trees,
3557 * because the traversal needs to parse sub-trees but
3558 * not blobs.
3560 * Note we only perform this check when we couldn't
3561 * already find the object in a pack, so we're really
3562 * limited to "ensure non-tip blobs which don't exist in
3563 * packs do exist via loose objects". Confused?
3565 return;
3568 entry = create_object_entry(oid, type, pack_name_hash(name),
3569 0, name && no_try_delta(name),
3570 pack, offset);
3573 if (mtime > oe_cruft_mtime(&to_pack, entry))
3574 oe_set_cruft_mtime(&to_pack, entry, mtime);
3575 return;
3578 static void show_cruft_object(struct object *obj, const char *name, void *data UNUSED)
3581 * if we did not record it earlier, it's at least as old as our
3582 * expiration value. Rather than find it exactly, just use that
3583 * value. This may bump it forward from its real mtime, but it
3584 * will still be "too old" next time we run with the same
3585 * expiration.
3587 * if obj does appear in the packing list, this call is a noop (or may
3588 * set the namehash).
3590 add_cruft_object_entry(&obj->oid, obj->type, NULL, 0, name, cruft_expiration);
3593 static void show_cruft_commit(struct commit *commit, void *data)
3595 show_cruft_object((struct object*)commit, NULL, data);
3598 static int cruft_include_check_obj(struct object *obj, void *data UNUSED)
3600 return !has_object_kept_pack(&obj->oid, IN_CORE_KEEP_PACKS);
3603 static int cruft_include_check(struct commit *commit, void *data)
3605 return cruft_include_check_obj((struct object*)commit, data);
3608 static void set_cruft_mtime(const struct object *object,
3609 struct packed_git *pack,
3610 off_t offset, time_t mtime)
3612 add_cruft_object_entry(&object->oid, object->type, pack, offset, NULL,
3613 mtime);
3616 static void mark_pack_kept_in_core(struct string_list *packs, unsigned keep)
3618 struct string_list_item *item = NULL;
3619 for_each_string_list_item(item, packs) {
3620 struct packed_git *p = item->util;
3621 if (!p)
3622 die(_("could not find pack '%s'"), item->string);
3623 p->pack_keep_in_core = keep;
3627 static void add_unreachable_loose_objects(void);
3628 static void add_objects_in_unpacked_packs(void);
3630 static void enumerate_cruft_objects(void)
3632 if (progress)
3633 progress_state = start_progress(_("Enumerating cruft objects"), 0);
3635 add_objects_in_unpacked_packs();
3636 add_unreachable_loose_objects();
3638 stop_progress(&progress_state);
3641 static void enumerate_and_traverse_cruft_objects(struct string_list *fresh_packs)
3643 struct packed_git *p;
3644 struct rev_info revs;
3645 int ret;
3647 repo_init_revisions(the_repository, &revs, NULL);
3649 revs.tag_objects = 1;
3650 revs.tree_objects = 1;
3651 revs.blob_objects = 1;
3653 revs.include_check = cruft_include_check;
3654 revs.include_check_obj = cruft_include_check_obj;
3656 revs.ignore_missing_links = 1;
3658 if (progress)
3659 progress_state = start_progress(_("Enumerating cruft objects"), 0);
3660 ret = add_unseen_recent_objects_to_traversal(&revs, cruft_expiration,
3661 set_cruft_mtime, 1);
3662 stop_progress(&progress_state);
3664 if (ret)
3665 die(_("unable to add cruft objects"));
3668 * Re-mark only the fresh packs as kept so that objects in
3669 * unknown packs do not halt the reachability traversal early.
3671 for (p = get_all_packs(the_repository); p; p = p->next)
3672 p->pack_keep_in_core = 0;
3673 mark_pack_kept_in_core(fresh_packs, 1);
3675 if (prepare_revision_walk(&revs))
3676 die(_("revision walk setup failed"));
3677 if (progress)
3678 progress_state = start_progress(_("Traversing cruft objects"), 0);
3679 nr_seen = 0;
3680 traverse_commit_list(&revs, show_cruft_commit, show_cruft_object, NULL);
3682 stop_progress(&progress_state);
3685 static void read_cruft_objects(void)
3687 struct strbuf buf = STRBUF_INIT;
3688 struct string_list discard_packs = STRING_LIST_INIT_DUP;
3689 struct string_list fresh_packs = STRING_LIST_INIT_DUP;
3690 struct packed_git *p;
3692 ignore_packed_keep_in_core = 1;
3694 while (strbuf_getline(&buf, stdin) != EOF) {
3695 if (!buf.len)
3696 continue;
3698 if (*buf.buf == '-')
3699 string_list_append(&discard_packs, buf.buf + 1);
3700 else
3701 string_list_append(&fresh_packs, buf.buf);
3704 string_list_sort(&discard_packs);
3705 string_list_sort(&fresh_packs);
3707 for (p = get_all_packs(the_repository); p; p = p->next) {
3708 const char *pack_name = pack_basename(p);
3709 struct string_list_item *item;
3711 item = string_list_lookup(&fresh_packs, pack_name);
3712 if (!item)
3713 item = string_list_lookup(&discard_packs, pack_name);
3715 if (item) {
3716 item->util = p;
3717 } else {
3719 * This pack wasn't mentioned in either the "fresh" or
3720 * "discard" list, so the caller didn't know about it.
3722 * Mark it as kept so that its objects are ignored by
3723 * add_unseen_recent_objects_to_traversal(). We'll
3724 * unmark it before starting the traversal so it doesn't
3725 * halt the traversal early.
3727 p->pack_keep_in_core = 1;
3731 mark_pack_kept_in_core(&fresh_packs, 1);
3732 mark_pack_kept_in_core(&discard_packs, 0);
3734 if (cruft_expiration)
3735 enumerate_and_traverse_cruft_objects(&fresh_packs);
3736 else
3737 enumerate_cruft_objects();
3739 strbuf_release(&buf);
3740 string_list_clear(&discard_packs, 0);
3741 string_list_clear(&fresh_packs, 0);
3744 static void read_object_list_from_stdin(void)
3746 char line[GIT_MAX_HEXSZ + 1 + PATH_MAX + 2];
3747 struct object_id oid;
3748 const char *p;
3750 for (;;) {
3751 if (!fgets(line, sizeof(line), stdin)) {
3752 if (feof(stdin))
3753 break;
3754 if (!ferror(stdin))
3755 BUG("fgets returned NULL, not EOF, not error!");
3756 if (errno != EINTR)
3757 die_errno("fgets");
3758 clearerr(stdin);
3759 continue;
3761 if (line[0] == '-') {
3762 if (get_oid_hex(line+1, &oid))
3763 die(_("expected edge object ID, got garbage:\n %s"),
3764 line);
3765 add_preferred_base(&oid);
3766 continue;
3768 if (parse_oid_hex(line, &oid, &p))
3769 die(_("expected object ID, got garbage:\n %s"), line);
3771 add_preferred_base_object(p + 1);
3772 add_object_entry(&oid, OBJ_NONE, p + 1, 0);
3776 static void show_commit(struct commit *commit, void *data UNUSED)
3778 add_object_entry(&commit->object.oid, OBJ_COMMIT, NULL, 0);
3780 if (write_bitmap_index)
3781 index_commit_for_bitmap(commit);
3783 if (use_delta_islands)
3784 propagate_island_marks(commit);
3787 static void show_object(struct object *obj, const char *name,
3788 void *data UNUSED)
3790 add_preferred_base_object(name);
3791 add_object_entry(&obj->oid, obj->type, name, 0);
3793 if (use_delta_islands) {
3794 const char *p;
3795 unsigned depth;
3796 struct object_entry *ent;
3798 /* the empty string is a root tree, which is depth 0 */
3799 depth = *name ? 1 : 0;
3800 for (p = strchr(name, '/'); p; p = strchr(p + 1, '/'))
3801 depth++;
3803 ent = packlist_find(&to_pack, &obj->oid);
3804 if (ent && depth > oe_tree_depth(&to_pack, ent))
3805 oe_set_tree_depth(&to_pack, ent, depth);
3809 static void show_object__ma_allow_any(struct object *obj, const char *name, void *data)
3811 assert(arg_missing_action == MA_ALLOW_ANY);
3814 * Quietly ignore ALL missing objects. This avoids problems with
3815 * staging them now and getting an odd error later.
3817 if (!has_object(the_repository, &obj->oid, 0))
3818 return;
3820 show_object(obj, name, data);
3823 static void show_object__ma_allow_promisor(struct object *obj, const char *name, void *data)
3825 assert(arg_missing_action == MA_ALLOW_PROMISOR);
3828 * Quietly ignore EXPECTED missing objects. This avoids problems with
3829 * staging them now and getting an odd error later.
3831 if (!has_object(the_repository, &obj->oid, 0) && is_promisor_object(&obj->oid))
3832 return;
3834 show_object(obj, name, data);
3837 static int option_parse_missing_action(const struct option *opt UNUSED,
3838 const char *arg, int unset)
3840 assert(arg);
3841 assert(!unset);
3843 if (!strcmp(arg, "error")) {
3844 arg_missing_action = MA_ERROR;
3845 fn_show_object = show_object;
3846 return 0;
3849 if (!strcmp(arg, "allow-any")) {
3850 arg_missing_action = MA_ALLOW_ANY;
3851 fetch_if_missing = 0;
3852 fn_show_object = show_object__ma_allow_any;
3853 return 0;
3856 if (!strcmp(arg, "allow-promisor")) {
3857 arg_missing_action = MA_ALLOW_PROMISOR;
3858 fetch_if_missing = 0;
3859 fn_show_object = show_object__ma_allow_promisor;
3860 return 0;
3863 die(_("invalid value for '%s': '%s'"), "--missing", arg);
3864 return 0;
3867 static void show_edge(struct commit *commit)
3869 add_preferred_base(&commit->object.oid);
3872 static int add_object_in_unpacked_pack(const struct object_id *oid,
3873 struct packed_git *pack,
3874 uint32_t pos,
3875 void *data UNUSED)
3877 if (cruft) {
3878 off_t offset;
3879 time_t mtime;
3881 if (pack->is_cruft) {
3882 if (load_pack_mtimes(pack) < 0)
3883 die(_("could not load cruft pack .mtimes"));
3884 mtime = nth_packed_mtime(pack, pos);
3885 } else {
3886 mtime = pack->mtime;
3888 offset = nth_packed_object_offset(pack, pos);
3890 add_cruft_object_entry(oid, OBJ_NONE, pack, offset,
3891 NULL, mtime);
3892 } else {
3893 add_object_entry(oid, OBJ_NONE, "", 0);
3895 return 0;
3898 static void add_objects_in_unpacked_packs(void)
3900 if (for_each_packed_object(add_object_in_unpacked_pack, NULL,
3901 FOR_EACH_OBJECT_PACK_ORDER |
3902 FOR_EACH_OBJECT_LOCAL_ONLY |
3903 FOR_EACH_OBJECT_SKIP_IN_CORE_KEPT_PACKS |
3904 FOR_EACH_OBJECT_SKIP_ON_DISK_KEPT_PACKS))
3905 die(_("cannot open pack index"));
3908 static int add_loose_object(const struct object_id *oid, const char *path,
3909 void *data UNUSED)
3911 enum object_type type = oid_object_info(the_repository, oid, NULL);
3913 if (type < 0) {
3914 warning(_("loose object at %s could not be examined"), path);
3915 return 0;
3918 if (cruft) {
3919 struct stat st;
3920 if (stat(path, &st) < 0) {
3921 if (errno == ENOENT)
3922 return 0;
3923 return error_errno("unable to stat %s", oid_to_hex(oid));
3926 add_cruft_object_entry(oid, type, NULL, 0, NULL,
3927 st.st_mtime);
3928 } else {
3929 add_object_entry(oid, type, "", 0);
3931 return 0;
3935 * We actually don't even have to worry about reachability here.
3936 * add_object_entry will weed out duplicates, so we just add every
3937 * loose object we find.
3939 static void add_unreachable_loose_objects(void)
3941 for_each_loose_file_in_objdir(get_object_directory(),
3942 add_loose_object,
3943 NULL, NULL, NULL);
3946 static int has_sha1_pack_kept_or_nonlocal(const struct object_id *oid)
3948 static struct packed_git *last_found = (void *)1;
3949 struct packed_git *p;
3951 p = (last_found != (void *)1) ? last_found :
3952 get_all_packs(the_repository);
3954 while (p) {
3955 if ((!p->pack_local || p->pack_keep ||
3956 p->pack_keep_in_core) &&
3957 find_pack_entry_one(oid->hash, p)) {
3958 last_found = p;
3959 return 1;
3961 if (p == last_found)
3962 p = get_all_packs(the_repository);
3963 else
3964 p = p->next;
3965 if (p == last_found)
3966 p = p->next;
3968 return 0;
3972 * Store a list of sha1s that are should not be discarded
3973 * because they are either written too recently, or are
3974 * reachable from another object that was.
3976 * This is filled by get_object_list.
3978 static struct oid_array recent_objects;
3980 static int loosened_object_can_be_discarded(const struct object_id *oid,
3981 timestamp_t mtime)
3983 if (!unpack_unreachable_expiration)
3984 return 0;
3985 if (mtime > unpack_unreachable_expiration)
3986 return 0;
3987 if (oid_array_lookup(&recent_objects, oid) >= 0)
3988 return 0;
3989 return 1;
3992 static void loosen_unused_packed_objects(void)
3994 struct packed_git *p;
3995 uint32_t i;
3996 uint32_t loosened_objects_nr = 0;
3997 struct object_id oid;
3999 for (p = get_all_packs(the_repository); p; p = p->next) {
4000 if (!p->pack_local || p->pack_keep || p->pack_keep_in_core)
4001 continue;
4003 if (open_pack_index(p))
4004 die(_("cannot open pack index"));
4006 for (i = 0; i < p->num_objects; i++) {
4007 nth_packed_object_id(&oid, p, i);
4008 if (!packlist_find(&to_pack, &oid) &&
4009 !has_sha1_pack_kept_or_nonlocal(&oid) &&
4010 !loosened_object_can_be_discarded(&oid, p->mtime)) {
4011 if (force_object_loose(&oid, p->mtime))
4012 die(_("unable to force loose object"));
4013 loosened_objects_nr++;
4018 trace2_data_intmax("pack-objects", the_repository,
4019 "loosen_unused_packed_objects/loosened", loosened_objects_nr);
4023 * This tracks any options which pack-reuse code expects to be on, or which a
4024 * reader of the pack might not understand, and which would therefore prevent
4025 * blind reuse of what we have on disk.
4027 static int pack_options_allow_reuse(void)
4029 return allow_pack_reuse != NO_PACK_REUSE &&
4030 pack_to_stdout &&
4031 !ignore_packed_keep_on_disk &&
4032 !ignore_packed_keep_in_core &&
4033 (!local || !have_non_local_packs) &&
4034 !incremental;
4037 static int get_object_list_from_bitmap(struct rev_info *revs)
4039 if (!(bitmap_git = prepare_bitmap_walk(revs, 0)))
4040 return -1;
4042 if (pack_options_allow_reuse())
4043 reuse_partial_packfile_from_bitmap(bitmap_git,
4044 &reuse_packfiles,
4045 &reuse_packfiles_nr,
4046 &reuse_packfile_bitmap,
4047 allow_pack_reuse == MULTI_PACK_REUSE);
4049 if (reuse_packfiles) {
4050 reuse_packfile_objects = bitmap_popcount(reuse_packfile_bitmap);
4051 if (!reuse_packfile_objects)
4052 BUG("expected non-empty reuse bitmap");
4054 nr_result += reuse_packfile_objects;
4055 nr_seen += reuse_packfile_objects;
4056 display_progress(progress_state, nr_seen);
4059 traverse_bitmap_commit_list(bitmap_git, revs,
4060 &add_object_entry_from_bitmap);
4061 return 0;
4064 static void record_recent_object(struct object *obj,
4065 const char *name UNUSED,
4066 void *data UNUSED)
4068 oid_array_append(&recent_objects, &obj->oid);
4071 static void record_recent_commit(struct commit *commit, void *data UNUSED)
4073 oid_array_append(&recent_objects, &commit->object.oid);
4076 static int mark_bitmap_preferred_tip(const char *refname,
4077 const struct object_id *oid,
4078 int flags UNUSED,
4079 void *data UNUSED)
4081 struct object_id peeled;
4082 struct object *object;
4084 if (!peel_iterated_oid(the_repository, oid, &peeled))
4085 oid = &peeled;
4087 object = parse_object_or_die(oid, refname);
4088 if (object->type == OBJ_COMMIT)
4089 object->flags |= NEEDS_BITMAP;
4091 return 0;
4094 static void mark_bitmap_preferred_tips(void)
4096 struct string_list_item *item;
4097 const struct string_list *preferred_tips;
4099 preferred_tips = bitmap_preferred_tips(the_repository);
4100 if (!preferred_tips)
4101 return;
4103 for_each_string_list_item(item, preferred_tips) {
4104 refs_for_each_ref_in(get_main_ref_store(the_repository),
4105 item->string, mark_bitmap_preferred_tip,
4106 NULL);
4110 static void get_object_list(struct rev_info *revs, int ac, const char **av)
4112 struct setup_revision_opt s_r_opt = {
4113 .allow_exclude_promisor_objects = 1,
4115 char line[1000];
4116 int flags = 0;
4117 int save_warning;
4119 save_commit_buffer = 0;
4120 setup_revisions(ac, av, revs, &s_r_opt);
4122 /* make sure shallows are read */
4123 is_repository_shallow(the_repository);
4125 save_warning = warn_on_object_refname_ambiguity;
4126 warn_on_object_refname_ambiguity = 0;
4128 while (fgets(line, sizeof(line), stdin) != NULL) {
4129 int len = strlen(line);
4130 if (len && line[len - 1] == '\n')
4131 line[--len] = 0;
4132 if (!len)
4133 break;
4134 if (*line == '-') {
4135 if (!strcmp(line, "--not")) {
4136 flags ^= UNINTERESTING;
4137 write_bitmap_index = 0;
4138 continue;
4140 if (starts_with(line, "--shallow ")) {
4141 struct object_id oid;
4142 if (get_oid_hex(line + 10, &oid))
4143 die("not an object name '%s'", line + 10);
4144 register_shallow(the_repository, &oid);
4145 use_bitmap_index = 0;
4146 continue;
4148 die(_("not a rev '%s'"), line);
4150 if (handle_revision_arg(line, revs, flags, REVARG_CANNOT_BE_FILENAME))
4151 die(_("bad revision '%s'"), line);
4154 warn_on_object_refname_ambiguity = save_warning;
4156 if (use_bitmap_index && !get_object_list_from_bitmap(revs))
4157 return;
4159 if (use_delta_islands)
4160 load_delta_islands(the_repository, progress);
4162 if (write_bitmap_index)
4163 mark_bitmap_preferred_tips();
4165 if (prepare_revision_walk(revs))
4166 die(_("revision walk setup failed"));
4167 mark_edges_uninteresting(revs, show_edge, sparse);
4169 if (!fn_show_object)
4170 fn_show_object = show_object;
4171 traverse_commit_list(revs,
4172 show_commit, fn_show_object,
4173 NULL);
4175 if (unpack_unreachable_expiration) {
4176 revs->ignore_missing_links = 1;
4177 if (add_unseen_recent_objects_to_traversal(revs,
4178 unpack_unreachable_expiration, NULL, 0))
4179 die(_("unable to add recent objects"));
4180 if (prepare_revision_walk(revs))
4181 die(_("revision walk setup failed"));
4182 traverse_commit_list(revs, record_recent_commit,
4183 record_recent_object, NULL);
4186 if (keep_unreachable)
4187 add_objects_in_unpacked_packs();
4188 if (pack_loose_unreachable)
4189 add_unreachable_loose_objects();
4190 if (unpack_unreachable)
4191 loosen_unused_packed_objects();
4193 oid_array_clear(&recent_objects);
4196 static void add_extra_kept_packs(const struct string_list *names)
4198 struct packed_git *p;
4200 if (!names->nr)
4201 return;
4203 for (p = get_all_packs(the_repository); p; p = p->next) {
4204 const char *name = basename(p->pack_name);
4205 int i;
4207 if (!p->pack_local)
4208 continue;
4210 for (i = 0; i < names->nr; i++)
4211 if (!fspathcmp(name, names->items[i].string))
4212 break;
4214 if (i < names->nr) {
4215 p->pack_keep_in_core = 1;
4216 ignore_packed_keep_in_core = 1;
4217 continue;
4222 static int option_parse_quiet(const struct option *opt, const char *arg,
4223 int unset)
4225 int *val = opt->value;
4227 BUG_ON_OPT_ARG(arg);
4229 if (!unset)
4230 *val = 0;
4231 else if (!*val)
4232 *val = 1;
4233 return 0;
4236 static int option_parse_index_version(const struct option *opt,
4237 const char *arg, int unset)
4239 struct pack_idx_option *popts = opt->value;
4240 char *c;
4241 const char *val = arg;
4243 BUG_ON_OPT_NEG(unset);
4245 popts->version = strtoul(val, &c, 10);
4246 if (popts->version > 2)
4247 die(_("unsupported index version %s"), val);
4248 if (*c == ',' && c[1])
4249 popts->off32_limit = strtoul(c+1, &c, 0);
4250 if (*c || popts->off32_limit & 0x80000000)
4251 die(_("bad index version '%s'"), val);
4252 return 0;
4255 static int option_parse_unpack_unreachable(const struct option *opt UNUSED,
4256 const char *arg, int unset)
4258 if (unset) {
4259 unpack_unreachable = 0;
4260 unpack_unreachable_expiration = 0;
4262 else {
4263 unpack_unreachable = 1;
4264 if (arg)
4265 unpack_unreachable_expiration = approxidate(arg);
4267 return 0;
4270 static int option_parse_cruft_expiration(const struct option *opt UNUSED,
4271 const char *arg, int unset)
4273 if (unset) {
4274 cruft = 0;
4275 cruft_expiration = 0;
4276 } else {
4277 cruft = 1;
4278 if (arg)
4279 cruft_expiration = approxidate(arg);
4281 return 0;
4284 int cmd_pack_objects(int argc, const char **argv, const char *prefix)
4286 int use_internal_rev_list = 0;
4287 int shallow = 0;
4288 int all_progress_implied = 0;
4289 struct strvec rp = STRVEC_INIT;
4290 int rev_list_unpacked = 0, rev_list_all = 0, rev_list_reflog = 0;
4291 int rev_list_index = 0;
4292 int stdin_packs = 0;
4293 struct string_list keep_pack_list = STRING_LIST_INIT_NODUP;
4294 struct list_objects_filter_options filter_options =
4295 LIST_OBJECTS_FILTER_INIT;
4297 struct option pack_objects_options[] = {
4298 OPT_CALLBACK_F('q', "quiet", &progress, NULL,
4299 N_("do not show progress meter"),
4300 PARSE_OPT_NOARG, option_parse_quiet),
4301 OPT_SET_INT(0, "progress", &progress,
4302 N_("show progress meter"), 1),
4303 OPT_SET_INT(0, "all-progress", &progress,
4304 N_("show progress meter during object writing phase"), 2),
4305 OPT_BOOL(0, "all-progress-implied",
4306 &all_progress_implied,
4307 N_("similar to --all-progress when progress meter is shown")),
4308 OPT_CALLBACK_F(0, "index-version", &pack_idx_opts, N_("<version>[,<offset>]"),
4309 N_("write the pack index file in the specified idx format version"),
4310 PARSE_OPT_NONEG, option_parse_index_version),
4311 OPT_MAGNITUDE(0, "max-pack-size", &pack_size_limit,
4312 N_("maximum size of each output pack file")),
4313 OPT_BOOL(0, "local", &local,
4314 N_("ignore borrowed objects from alternate object store")),
4315 OPT_BOOL(0, "incremental", &incremental,
4316 N_("ignore packed objects")),
4317 OPT_INTEGER(0, "window", &window,
4318 N_("limit pack window by objects")),
4319 OPT_MAGNITUDE(0, "window-memory", &window_memory_limit,
4320 N_("limit pack window by memory in addition to object limit")),
4321 OPT_INTEGER(0, "depth", &depth,
4322 N_("maximum length of delta chain allowed in the resulting pack")),
4323 OPT_BOOL(0, "reuse-delta", &reuse_delta,
4324 N_("reuse existing deltas")),
4325 OPT_BOOL(0, "reuse-object", &reuse_object,
4326 N_("reuse existing objects")),
4327 OPT_BOOL(0, "delta-base-offset", &allow_ofs_delta,
4328 N_("use OFS_DELTA objects")),
4329 OPT_INTEGER(0, "threads", &delta_search_threads,
4330 N_("use threads when searching for best delta matches")),
4331 OPT_BOOL(0, "non-empty", &non_empty,
4332 N_("do not create an empty pack output")),
4333 OPT_BOOL(0, "revs", &use_internal_rev_list,
4334 N_("read revision arguments from standard input")),
4335 OPT_SET_INT_F(0, "unpacked", &rev_list_unpacked,
4336 N_("limit the objects to those that are not yet packed"),
4337 1, PARSE_OPT_NONEG),
4338 OPT_SET_INT_F(0, "all", &rev_list_all,
4339 N_("include objects reachable from any reference"),
4340 1, PARSE_OPT_NONEG),
4341 OPT_SET_INT_F(0, "reflog", &rev_list_reflog,
4342 N_("include objects referred by reflog entries"),
4343 1, PARSE_OPT_NONEG),
4344 OPT_SET_INT_F(0, "indexed-objects", &rev_list_index,
4345 N_("include objects referred to by the index"),
4346 1, PARSE_OPT_NONEG),
4347 OPT_BOOL(0, "stdin-packs", &stdin_packs,
4348 N_("read packs from stdin")),
4349 OPT_BOOL(0, "stdout", &pack_to_stdout,
4350 N_("output pack to stdout")),
4351 OPT_BOOL(0, "include-tag", &include_tag,
4352 N_("include tag objects that refer to objects to be packed")),
4353 OPT_BOOL(0, "keep-unreachable", &keep_unreachable,
4354 N_("keep unreachable objects")),
4355 OPT_BOOL(0, "pack-loose-unreachable", &pack_loose_unreachable,
4356 N_("pack loose unreachable objects")),
4357 OPT_CALLBACK_F(0, "unpack-unreachable", NULL, N_("time"),
4358 N_("unpack unreachable objects newer than <time>"),
4359 PARSE_OPT_OPTARG, option_parse_unpack_unreachable),
4360 OPT_BOOL(0, "cruft", &cruft, N_("create a cruft pack")),
4361 OPT_CALLBACK_F(0, "cruft-expiration", NULL, N_("time"),
4362 N_("expire cruft objects older than <time>"),
4363 PARSE_OPT_OPTARG, option_parse_cruft_expiration),
4364 OPT_BOOL(0, "sparse", &sparse,
4365 N_("use the sparse reachability algorithm")),
4366 OPT_BOOL(0, "thin", &thin,
4367 N_("create thin packs")),
4368 OPT_BOOL(0, "shallow", &shallow,
4369 N_("create packs suitable for shallow fetches")),
4370 OPT_BOOL(0, "honor-pack-keep", &ignore_packed_keep_on_disk,
4371 N_("ignore packs that have companion .keep file")),
4372 OPT_STRING_LIST(0, "keep-pack", &keep_pack_list, N_("name"),
4373 N_("ignore this pack")),
4374 OPT_INTEGER(0, "compression", &pack_compression_level,
4375 N_("pack compression level")),
4376 OPT_BOOL(0, "keep-true-parents", &grafts_keep_true_parents,
4377 N_("do not hide commits by grafts")),
4378 OPT_BOOL(0, "use-bitmap-index", &use_bitmap_index,
4379 N_("use a bitmap index if available to speed up counting objects")),
4380 OPT_SET_INT(0, "write-bitmap-index", &write_bitmap_index,
4381 N_("write a bitmap index together with the pack index"),
4382 WRITE_BITMAP_TRUE),
4383 OPT_SET_INT_F(0, "write-bitmap-index-quiet",
4384 &write_bitmap_index,
4385 N_("write a bitmap index if possible"),
4386 WRITE_BITMAP_QUIET, PARSE_OPT_HIDDEN),
4387 OPT_PARSE_LIST_OBJECTS_FILTER(&filter_options),
4388 OPT_CALLBACK_F(0, "missing", NULL, N_("action"),
4389 N_("handling for missing objects"), PARSE_OPT_NONEG,
4390 option_parse_missing_action),
4391 OPT_BOOL(0, "exclude-promisor-objects", &exclude_promisor_objects,
4392 N_("do not pack objects in promisor packfiles")),
4393 OPT_BOOL(0, "delta-islands", &use_delta_islands,
4394 N_("respect islands during delta compression")),
4395 OPT_STRING_LIST(0, "uri-protocol", &uri_protocols,
4396 N_("protocol"),
4397 N_("exclude any configured uploadpack.blobpackfileuri with this protocol")),
4398 OPT_END(),
4401 if (DFS_NUM_STATES > (1 << OE_DFS_STATE_BITS))
4402 BUG("too many dfs states, increase OE_DFS_STATE_BITS");
4404 disable_replace_refs();
4406 sparse = git_env_bool("GIT_TEST_PACK_SPARSE", -1);
4407 if (the_repository->gitdir) {
4408 prepare_repo_settings(the_repository);
4409 if (sparse < 0)
4410 sparse = the_repository->settings.pack_use_sparse;
4411 if (the_repository->settings.pack_use_multi_pack_reuse)
4412 allow_pack_reuse = MULTI_PACK_REUSE;
4415 reset_pack_idx_option(&pack_idx_opts);
4416 pack_idx_opts.flags |= WRITE_REV;
4417 git_config(git_pack_config, NULL);
4418 if (git_env_bool(GIT_TEST_NO_WRITE_REV_INDEX, 0))
4419 pack_idx_opts.flags &= ~WRITE_REV;
4421 progress = isatty(2);
4422 argc = parse_options(argc, argv, prefix, pack_objects_options,
4423 pack_usage, 0);
4425 if (argc) {
4426 base_name = argv[0];
4427 argc--;
4429 if (pack_to_stdout != !base_name || argc)
4430 usage_with_options(pack_usage, pack_objects_options);
4432 if (depth < 0)
4433 depth = 0;
4434 if (depth >= (1 << OE_DEPTH_BITS)) {
4435 warning(_("delta chain depth %d is too deep, forcing %d"),
4436 depth, (1 << OE_DEPTH_BITS) - 1);
4437 depth = (1 << OE_DEPTH_BITS) - 1;
4439 if (cache_max_small_delta_size >= (1U << OE_Z_DELTA_BITS)) {
4440 warning(_("pack.deltaCacheLimit is too high, forcing %d"),
4441 (1U << OE_Z_DELTA_BITS) - 1);
4442 cache_max_small_delta_size = (1U << OE_Z_DELTA_BITS) - 1;
4444 if (window < 0)
4445 window = 0;
4447 strvec_push(&rp, "pack-objects");
4448 if (thin) {
4449 use_internal_rev_list = 1;
4450 strvec_push(&rp, shallow
4451 ? "--objects-edge-aggressive"
4452 : "--objects-edge");
4453 } else
4454 strvec_push(&rp, "--objects");
4456 if (rev_list_all) {
4457 use_internal_rev_list = 1;
4458 strvec_push(&rp, "--all");
4460 if (rev_list_reflog) {
4461 use_internal_rev_list = 1;
4462 strvec_push(&rp, "--reflog");
4464 if (rev_list_index) {
4465 use_internal_rev_list = 1;
4466 strvec_push(&rp, "--indexed-objects");
4468 if (rev_list_unpacked && !stdin_packs) {
4469 use_internal_rev_list = 1;
4470 strvec_push(&rp, "--unpacked");
4473 if (exclude_promisor_objects) {
4474 use_internal_rev_list = 1;
4475 fetch_if_missing = 0;
4476 strvec_push(&rp, "--exclude-promisor-objects");
4478 if (unpack_unreachable || keep_unreachable || pack_loose_unreachable)
4479 use_internal_rev_list = 1;
4481 if (!reuse_object)
4482 reuse_delta = 0;
4483 if (pack_compression_level == -1)
4484 pack_compression_level = Z_DEFAULT_COMPRESSION;
4485 else if (pack_compression_level < 0 || pack_compression_level > Z_BEST_COMPRESSION)
4486 die(_("bad pack compression level %d"), pack_compression_level);
4488 if (!delta_search_threads) /* --threads=0 means autodetect */
4489 delta_search_threads = online_cpus();
4491 if (!HAVE_THREADS && delta_search_threads != 1)
4492 warning(_("no threads support, ignoring --threads"));
4493 if (!pack_to_stdout && !pack_size_limit)
4494 pack_size_limit = pack_size_limit_cfg;
4495 if (pack_to_stdout && pack_size_limit)
4496 die(_("--max-pack-size cannot be used to build a pack for transfer"));
4497 if (pack_size_limit && pack_size_limit < 1024*1024) {
4498 warning(_("minimum pack size limit is 1 MiB"));
4499 pack_size_limit = 1024*1024;
4502 if (!pack_to_stdout && thin)
4503 die(_("--thin cannot be used to build an indexable pack"));
4505 if (keep_unreachable && unpack_unreachable)
4506 die(_("options '%s' and '%s' cannot be used together"), "--keep-unreachable", "--unpack-unreachable");
4507 if (!rev_list_all || !rev_list_reflog || !rev_list_index)
4508 unpack_unreachable_expiration = 0;
4510 if (stdin_packs && filter_options.choice)
4511 die(_("cannot use --filter with --stdin-packs"));
4513 if (stdin_packs && use_internal_rev_list)
4514 die(_("cannot use internal rev list with --stdin-packs"));
4516 if (cruft) {
4517 if (use_internal_rev_list)
4518 die(_("cannot use internal rev list with --cruft"));
4519 if (stdin_packs)
4520 die(_("cannot use --stdin-packs with --cruft"));
4524 * "soft" reasons not to use bitmaps - for on-disk repack by default we want
4526 * - to produce good pack (with bitmap index not-yet-packed objects are
4527 * packed in suboptimal order).
4529 * - to use more robust pack-generation codepath (avoiding possible
4530 * bugs in bitmap code and possible bitmap index corruption).
4532 if (!pack_to_stdout)
4533 use_bitmap_index_default = 0;
4535 if (use_bitmap_index < 0)
4536 use_bitmap_index = use_bitmap_index_default;
4538 /* "hard" reasons not to use bitmaps; these just won't work at all */
4539 if (!use_internal_rev_list || (!pack_to_stdout && write_bitmap_index) || is_repository_shallow(the_repository))
4540 use_bitmap_index = 0;
4542 if (pack_to_stdout || !rev_list_all)
4543 write_bitmap_index = 0;
4545 if (use_delta_islands)
4546 strvec_push(&rp, "--topo-order");
4548 if (progress && all_progress_implied)
4549 progress = 2;
4551 add_extra_kept_packs(&keep_pack_list);
4552 if (ignore_packed_keep_on_disk) {
4553 struct packed_git *p;
4554 for (p = get_all_packs(the_repository); p; p = p->next)
4555 if (p->pack_local && p->pack_keep)
4556 break;
4557 if (!p) /* no keep-able packs found */
4558 ignore_packed_keep_on_disk = 0;
4560 if (local) {
4562 * unlike ignore_packed_keep_on_disk above, we do not
4563 * want to unset "local" based on looking at packs, as
4564 * it also covers non-local objects
4566 struct packed_git *p;
4567 for (p = get_all_packs(the_repository); p; p = p->next) {
4568 if (!p->pack_local) {
4569 have_non_local_packs = 1;
4570 break;
4575 trace2_region_enter("pack-objects", "enumerate-objects",
4576 the_repository);
4577 prepare_packing_data(the_repository, &to_pack);
4579 if (progress && !cruft)
4580 progress_state = start_progress(_("Enumerating objects"), 0);
4581 if (stdin_packs) {
4582 /* avoids adding objects in excluded packs */
4583 ignore_packed_keep_in_core = 1;
4584 read_packs_list_from_stdin();
4585 if (rev_list_unpacked)
4586 add_unreachable_loose_objects();
4587 } else if (cruft) {
4588 read_cruft_objects();
4589 } else if (!use_internal_rev_list) {
4590 read_object_list_from_stdin();
4591 } else {
4592 struct rev_info revs;
4594 repo_init_revisions(the_repository, &revs, NULL);
4595 list_objects_filter_copy(&revs.filter, &filter_options);
4596 get_object_list(&revs, rp.nr, rp.v);
4597 release_revisions(&revs);
4599 cleanup_preferred_base();
4600 if (include_tag && nr_result)
4601 refs_for_each_tag_ref(get_main_ref_store(the_repository),
4602 add_ref_tag, NULL);
4603 stop_progress(&progress_state);
4604 trace2_region_leave("pack-objects", "enumerate-objects",
4605 the_repository);
4607 if (non_empty && !nr_result)
4608 goto cleanup;
4609 if (nr_result) {
4610 trace2_region_enter("pack-objects", "prepare-pack",
4611 the_repository);
4612 prepare_pack(window, depth);
4613 trace2_region_leave("pack-objects", "prepare-pack",
4614 the_repository);
4617 trace2_region_enter("pack-objects", "write-pack-file", the_repository);
4618 write_excluded_by_configs();
4619 write_pack_file();
4620 trace2_region_leave("pack-objects", "write-pack-file", the_repository);
4622 if (progress)
4623 fprintf_ln(stderr,
4624 _("Total %"PRIu32" (delta %"PRIu32"),"
4625 " reused %"PRIu32" (delta %"PRIu32"),"
4626 " pack-reused %"PRIu32" (from %"PRIuMAX")"),
4627 written, written_delta, reused, reused_delta,
4628 reuse_packfile_objects,
4629 (uintmax_t)reuse_packfiles_used_nr);
4631 trace2_data_intmax("pack-objects", the_repository, "written", written);
4632 trace2_data_intmax("pack-objects", the_repository, "written/delta", written_delta);
4633 trace2_data_intmax("pack-objects", the_repository, "reused", reused);
4634 trace2_data_intmax("pack-objects", the_repository, "reused/delta", reused_delta);
4635 trace2_data_intmax("pack-objects", the_repository, "pack-reused", reuse_packfile_objects);
4636 trace2_data_intmax("pack-objects", the_repository, "packs-reused", reuse_packfiles_used_nr);
4638 cleanup:
4639 clear_packing_data(&to_pack);
4640 list_objects_filter_release(&filter_options);
4641 strvec_clear(&rp);
4643 return 0;