Merge branch 'rs/repack-without-loosening-promised-objects'
[alt-git.git] / builtin / pack-objects.c
blobcdc38c275bc9d1be86db4fb91f50369261bdbab3
1 #include "builtin.h"
2 #include "cache.h"
3 #include "repository.h"
4 #include "config.h"
5 #include "attr.h"
6 #include "object.h"
7 #include "blob.h"
8 #include "commit.h"
9 #include "tag.h"
10 #include "tree.h"
11 #include "delta.h"
12 #include "pack.h"
13 #include "pack-revindex.h"
14 #include "csum-file.h"
15 #include "tree-walk.h"
16 #include "diff.h"
17 #include "revision.h"
18 #include "list-objects.h"
19 #include "list-objects-filter.h"
20 #include "list-objects-filter-options.h"
21 #include "pack-objects.h"
22 #include "progress.h"
23 #include "refs.h"
24 #include "streaming.h"
25 #include "thread-utils.h"
26 #include "pack-bitmap.h"
27 #include "delta-islands.h"
28 #include "reachable.h"
29 #include "oid-array.h"
30 #include "strvec.h"
31 #include "list.h"
32 #include "packfile.h"
33 #include "object-store.h"
34 #include "dir.h"
35 #include "midx.h"
36 #include "trace2.h"
37 #include "shallow.h"
38 #include "promisor-remote.h"
40 #define IN_PACK(obj) oe_in_pack(&to_pack, obj)
41 #define SIZE(obj) oe_size(&to_pack, obj)
42 #define SET_SIZE(obj,size) oe_set_size(&to_pack, obj, size)
43 #define DELTA_SIZE(obj) oe_delta_size(&to_pack, obj)
44 #define DELTA(obj) oe_delta(&to_pack, obj)
45 #define DELTA_CHILD(obj) oe_delta_child(&to_pack, obj)
46 #define DELTA_SIBLING(obj) oe_delta_sibling(&to_pack, obj)
47 #define SET_DELTA(obj, val) oe_set_delta(&to_pack, obj, val)
48 #define SET_DELTA_EXT(obj, oid) oe_set_delta_ext(&to_pack, obj, oid)
49 #define SET_DELTA_SIZE(obj, val) oe_set_delta_size(&to_pack, obj, val)
50 #define SET_DELTA_CHILD(obj, val) oe_set_delta_child(&to_pack, obj, val)
51 #define SET_DELTA_SIBLING(obj, val) oe_set_delta_sibling(&to_pack, obj, val)
53 static const char *pack_usage[] = {
54 N_("git pack-objects --stdout [<options>...] [< <ref-list> | < <object-list>]"),
55 N_("git pack-objects [<options>...] <base-name> [< <ref-list> | < <object-list>]"),
56 NULL
60 * Objects we are going to pack are collected in the `to_pack` structure.
61 * It contains an array (dynamically expanded) of the object data, and a map
62 * that can resolve SHA1s to their position in the array.
64 static struct packing_data to_pack;
66 static struct pack_idx_entry **written_list;
67 static uint32_t nr_result, nr_written, nr_seen;
68 static struct bitmap_index *bitmap_git;
69 static uint32_t write_layer;
71 static int non_empty;
72 static int reuse_delta = 1, reuse_object = 1;
73 static int keep_unreachable, unpack_unreachable, include_tag;
74 static timestamp_t unpack_unreachable_expiration;
75 static int pack_loose_unreachable;
76 static int local;
77 static int have_non_local_packs;
78 static int incremental;
79 static int ignore_packed_keep_on_disk;
80 static int ignore_packed_keep_in_core;
81 static int allow_ofs_delta;
82 static struct pack_idx_option pack_idx_opts;
83 static const char *base_name;
84 static int progress = 1;
85 static int window = 10;
86 static unsigned long pack_size_limit;
87 static int depth = 50;
88 static int delta_search_threads;
89 static int pack_to_stdout;
90 static int sparse;
91 static int thin;
92 static int num_preferred_base;
93 static struct progress *progress_state;
95 static struct packed_git *reuse_packfile;
96 static uint32_t reuse_packfile_objects;
97 static struct bitmap *reuse_packfile_bitmap;
99 static int use_bitmap_index_default = 1;
100 static int use_bitmap_index = -1;
101 static int allow_pack_reuse = 1;
102 static enum {
103 WRITE_BITMAP_FALSE = 0,
104 WRITE_BITMAP_QUIET,
105 WRITE_BITMAP_TRUE,
106 } write_bitmap_index;
107 static uint16_t write_bitmap_options = BITMAP_OPT_HASH_CACHE;
109 static int exclude_promisor_objects;
111 static int use_delta_islands;
113 static unsigned long delta_cache_size = 0;
114 static unsigned long max_delta_cache_size = DEFAULT_DELTA_CACHE_SIZE;
115 static unsigned long cache_max_small_delta_size = 1000;
117 static unsigned long window_memory_limit = 0;
119 static struct list_objects_filter_options filter_options;
121 static struct string_list uri_protocols = STRING_LIST_INIT_NODUP;
123 enum missing_action {
124 MA_ERROR = 0, /* fail if any missing objects are encountered */
125 MA_ALLOW_ANY, /* silently allow ALL missing objects */
126 MA_ALLOW_PROMISOR, /* silently allow all missing PROMISOR objects */
128 static enum missing_action arg_missing_action;
129 static show_object_fn fn_show_object;
131 struct configured_exclusion {
132 struct oidmap_entry e;
133 char *pack_hash_hex;
134 char *uri;
136 static struct oidmap configured_exclusions;
138 static struct oidset excluded_by_config;
141 * stats
143 static uint32_t written, written_delta;
144 static uint32_t reused, reused_delta;
147 * Indexed commits
149 static struct commit **indexed_commits;
150 static unsigned int indexed_commits_nr;
151 static unsigned int indexed_commits_alloc;
153 static void index_commit_for_bitmap(struct commit *commit)
155 if (indexed_commits_nr >= indexed_commits_alloc) {
156 indexed_commits_alloc = (indexed_commits_alloc + 32) * 2;
157 REALLOC_ARRAY(indexed_commits, indexed_commits_alloc);
160 indexed_commits[indexed_commits_nr++] = commit;
163 static void *get_delta(struct object_entry *entry)
165 unsigned long size, base_size, delta_size;
166 void *buf, *base_buf, *delta_buf;
167 enum object_type type;
169 buf = read_object_file(&entry->idx.oid, &type, &size);
170 if (!buf)
171 die(_("unable to read %s"), oid_to_hex(&entry->idx.oid));
172 base_buf = read_object_file(&DELTA(entry)->idx.oid, &type,
173 &base_size);
174 if (!base_buf)
175 die("unable to read %s",
176 oid_to_hex(&DELTA(entry)->idx.oid));
177 delta_buf = diff_delta(base_buf, base_size,
178 buf, size, &delta_size, 0);
180 * We successfully computed this delta once but dropped it for
181 * memory reasons. Something is very wrong if this time we
182 * recompute and create a different delta.
184 if (!delta_buf || delta_size != DELTA_SIZE(entry))
185 BUG("delta size changed");
186 free(buf);
187 free(base_buf);
188 return delta_buf;
191 static unsigned long do_compress(void **pptr, unsigned long size)
193 git_zstream stream;
194 void *in, *out;
195 unsigned long maxsize;
197 git_deflate_init(&stream, pack_compression_level);
198 maxsize = git_deflate_bound(&stream, size);
200 in = *pptr;
201 out = xmalloc(maxsize);
202 *pptr = out;
204 stream.next_in = in;
205 stream.avail_in = size;
206 stream.next_out = out;
207 stream.avail_out = maxsize;
208 while (git_deflate(&stream, Z_FINISH) == Z_OK)
209 ; /* nothing */
210 git_deflate_end(&stream);
212 free(in);
213 return stream.total_out;
216 static unsigned long write_large_blob_data(struct git_istream *st, struct hashfile *f,
217 const struct object_id *oid)
219 git_zstream stream;
220 unsigned char ibuf[1024 * 16];
221 unsigned char obuf[1024 * 16];
222 unsigned long olen = 0;
224 git_deflate_init(&stream, pack_compression_level);
226 for (;;) {
227 ssize_t readlen;
228 int zret = Z_OK;
229 readlen = read_istream(st, ibuf, sizeof(ibuf));
230 if (readlen == -1)
231 die(_("unable to read %s"), oid_to_hex(oid));
233 stream.next_in = ibuf;
234 stream.avail_in = readlen;
235 while ((stream.avail_in || readlen == 0) &&
236 (zret == Z_OK || zret == Z_BUF_ERROR)) {
237 stream.next_out = obuf;
238 stream.avail_out = sizeof(obuf);
239 zret = git_deflate(&stream, readlen ? 0 : Z_FINISH);
240 hashwrite(f, obuf, stream.next_out - obuf);
241 olen += stream.next_out - obuf;
243 if (stream.avail_in)
244 die(_("deflate error (%d)"), zret);
245 if (readlen == 0) {
246 if (zret != Z_STREAM_END)
247 die(_("deflate error (%d)"), zret);
248 break;
251 git_deflate_end(&stream);
252 return olen;
256 * we are going to reuse the existing object data as is. make
257 * sure it is not corrupt.
259 static int check_pack_inflate(struct packed_git *p,
260 struct pack_window **w_curs,
261 off_t offset,
262 off_t len,
263 unsigned long expect)
265 git_zstream stream;
266 unsigned char fakebuf[4096], *in;
267 int st;
269 memset(&stream, 0, sizeof(stream));
270 git_inflate_init(&stream);
271 do {
272 in = use_pack(p, w_curs, offset, &stream.avail_in);
273 stream.next_in = in;
274 stream.next_out = fakebuf;
275 stream.avail_out = sizeof(fakebuf);
276 st = git_inflate(&stream, Z_FINISH);
277 offset += stream.next_in - in;
278 } while (st == Z_OK || st == Z_BUF_ERROR);
279 git_inflate_end(&stream);
280 return (st == Z_STREAM_END &&
281 stream.total_out == expect &&
282 stream.total_in == len) ? 0 : -1;
285 static void copy_pack_data(struct hashfile *f,
286 struct packed_git *p,
287 struct pack_window **w_curs,
288 off_t offset,
289 off_t len)
291 unsigned char *in;
292 unsigned long avail;
294 while (len) {
295 in = use_pack(p, w_curs, offset, &avail);
296 if (avail > len)
297 avail = (unsigned long)len;
298 hashwrite(f, in, avail);
299 offset += avail;
300 len -= avail;
304 /* Return 0 if we will bust the pack-size limit */
305 static unsigned long write_no_reuse_object(struct hashfile *f, struct object_entry *entry,
306 unsigned long limit, int usable_delta)
308 unsigned long size, datalen;
309 unsigned char header[MAX_PACK_OBJECT_HEADER],
310 dheader[MAX_PACK_OBJECT_HEADER];
311 unsigned hdrlen;
312 enum object_type type;
313 void *buf;
314 struct git_istream *st = NULL;
315 const unsigned hashsz = the_hash_algo->rawsz;
317 if (!usable_delta) {
318 if (oe_type(entry) == OBJ_BLOB &&
319 oe_size_greater_than(&to_pack, entry, big_file_threshold) &&
320 (st = open_istream(the_repository, &entry->idx.oid, &type,
321 &size, NULL)) != NULL)
322 buf = NULL;
323 else {
324 buf = read_object_file(&entry->idx.oid, &type, &size);
325 if (!buf)
326 die(_("unable to read %s"),
327 oid_to_hex(&entry->idx.oid));
330 * make sure no cached delta data remains from a
331 * previous attempt before a pack split occurred.
333 FREE_AND_NULL(entry->delta_data);
334 entry->z_delta_size = 0;
335 } else if (entry->delta_data) {
336 size = DELTA_SIZE(entry);
337 buf = entry->delta_data;
338 entry->delta_data = NULL;
339 type = (allow_ofs_delta && DELTA(entry)->idx.offset) ?
340 OBJ_OFS_DELTA : OBJ_REF_DELTA;
341 } else {
342 buf = get_delta(entry);
343 size = DELTA_SIZE(entry);
344 type = (allow_ofs_delta && DELTA(entry)->idx.offset) ?
345 OBJ_OFS_DELTA : OBJ_REF_DELTA;
348 if (st) /* large blob case, just assume we don't compress well */
349 datalen = size;
350 else if (entry->z_delta_size)
351 datalen = entry->z_delta_size;
352 else
353 datalen = do_compress(&buf, size);
356 * The object header is a byte of 'type' followed by zero or
357 * more bytes of length.
359 hdrlen = encode_in_pack_object_header(header, sizeof(header),
360 type, size);
362 if (type == OBJ_OFS_DELTA) {
364 * Deltas with relative base contain an additional
365 * encoding of the relative offset for the delta
366 * base from this object's position in the pack.
368 off_t ofs = entry->idx.offset - DELTA(entry)->idx.offset;
369 unsigned pos = sizeof(dheader) - 1;
370 dheader[pos] = ofs & 127;
371 while (ofs >>= 7)
372 dheader[--pos] = 128 | (--ofs & 127);
373 if (limit && hdrlen + sizeof(dheader) - pos + datalen + hashsz >= limit) {
374 if (st)
375 close_istream(st);
376 free(buf);
377 return 0;
379 hashwrite(f, header, hdrlen);
380 hashwrite(f, dheader + pos, sizeof(dheader) - pos);
381 hdrlen += sizeof(dheader) - pos;
382 } else if (type == OBJ_REF_DELTA) {
384 * Deltas with a base reference contain
385 * additional bytes for the base object ID.
387 if (limit && hdrlen + hashsz + datalen + hashsz >= limit) {
388 if (st)
389 close_istream(st);
390 free(buf);
391 return 0;
393 hashwrite(f, header, hdrlen);
394 hashwrite(f, DELTA(entry)->idx.oid.hash, hashsz);
395 hdrlen += hashsz;
396 } else {
397 if (limit && hdrlen + datalen + hashsz >= limit) {
398 if (st)
399 close_istream(st);
400 free(buf);
401 return 0;
403 hashwrite(f, header, hdrlen);
405 if (st) {
406 datalen = write_large_blob_data(st, f, &entry->idx.oid);
407 close_istream(st);
408 } else {
409 hashwrite(f, buf, datalen);
410 free(buf);
413 return hdrlen + datalen;
416 /* Return 0 if we will bust the pack-size limit */
417 static off_t write_reuse_object(struct hashfile *f, struct object_entry *entry,
418 unsigned long limit, int usable_delta)
420 struct packed_git *p = IN_PACK(entry);
421 struct pack_window *w_curs = NULL;
422 uint32_t pos;
423 off_t offset;
424 enum object_type type = oe_type(entry);
425 off_t datalen;
426 unsigned char header[MAX_PACK_OBJECT_HEADER],
427 dheader[MAX_PACK_OBJECT_HEADER];
428 unsigned hdrlen;
429 const unsigned hashsz = the_hash_algo->rawsz;
430 unsigned long entry_size = SIZE(entry);
432 if (DELTA(entry))
433 type = (allow_ofs_delta && DELTA(entry)->idx.offset) ?
434 OBJ_OFS_DELTA : OBJ_REF_DELTA;
435 hdrlen = encode_in_pack_object_header(header, sizeof(header),
436 type, entry_size);
438 offset = entry->in_pack_offset;
439 if (offset_to_pack_pos(p, offset, &pos) < 0)
440 die(_("write_reuse_object: could not locate %s, expected at "
441 "offset %"PRIuMAX" in pack %s"),
442 oid_to_hex(&entry->idx.oid), (uintmax_t)offset,
443 p->pack_name);
444 datalen = pack_pos_to_offset(p, pos + 1) - offset;
445 if (!pack_to_stdout && p->index_version > 1 &&
446 check_pack_crc(p, &w_curs, offset, datalen,
447 pack_pos_to_index(p, pos))) {
448 error(_("bad packed object CRC for %s"),
449 oid_to_hex(&entry->idx.oid));
450 unuse_pack(&w_curs);
451 return write_no_reuse_object(f, entry, limit, usable_delta);
454 offset += entry->in_pack_header_size;
455 datalen -= entry->in_pack_header_size;
457 if (!pack_to_stdout && p->index_version == 1 &&
458 check_pack_inflate(p, &w_curs, offset, datalen, entry_size)) {
459 error(_("corrupt packed object for %s"),
460 oid_to_hex(&entry->idx.oid));
461 unuse_pack(&w_curs);
462 return write_no_reuse_object(f, entry, limit, usable_delta);
465 if (type == OBJ_OFS_DELTA) {
466 off_t ofs = entry->idx.offset - DELTA(entry)->idx.offset;
467 unsigned pos = sizeof(dheader) - 1;
468 dheader[pos] = ofs & 127;
469 while (ofs >>= 7)
470 dheader[--pos] = 128 | (--ofs & 127);
471 if (limit && hdrlen + sizeof(dheader) - pos + datalen + hashsz >= limit) {
472 unuse_pack(&w_curs);
473 return 0;
475 hashwrite(f, header, hdrlen);
476 hashwrite(f, dheader + pos, sizeof(dheader) - pos);
477 hdrlen += sizeof(dheader) - pos;
478 reused_delta++;
479 } else if (type == OBJ_REF_DELTA) {
480 if (limit && hdrlen + hashsz + datalen + hashsz >= limit) {
481 unuse_pack(&w_curs);
482 return 0;
484 hashwrite(f, header, hdrlen);
485 hashwrite(f, DELTA(entry)->idx.oid.hash, hashsz);
486 hdrlen += hashsz;
487 reused_delta++;
488 } else {
489 if (limit && hdrlen + datalen + hashsz >= limit) {
490 unuse_pack(&w_curs);
491 return 0;
493 hashwrite(f, header, hdrlen);
495 copy_pack_data(f, p, &w_curs, offset, datalen);
496 unuse_pack(&w_curs);
497 reused++;
498 return hdrlen + datalen;
501 /* Return 0 if we will bust the pack-size limit */
502 static off_t write_object(struct hashfile *f,
503 struct object_entry *entry,
504 off_t write_offset)
506 unsigned long limit;
507 off_t len;
508 int usable_delta, to_reuse;
510 if (!pack_to_stdout)
511 crc32_begin(f);
513 /* apply size limit if limited packsize and not first object */
514 if (!pack_size_limit || !nr_written)
515 limit = 0;
516 else if (pack_size_limit <= write_offset)
518 * the earlier object did not fit the limit; avoid
519 * mistaking this with unlimited (i.e. limit = 0).
521 limit = 1;
522 else
523 limit = pack_size_limit - write_offset;
525 if (!DELTA(entry))
526 usable_delta = 0; /* no delta */
527 else if (!pack_size_limit)
528 usable_delta = 1; /* unlimited packfile */
529 else if (DELTA(entry)->idx.offset == (off_t)-1)
530 usable_delta = 0; /* base was written to another pack */
531 else if (DELTA(entry)->idx.offset)
532 usable_delta = 1; /* base already exists in this pack */
533 else
534 usable_delta = 0; /* base could end up in another pack */
536 if (!reuse_object)
537 to_reuse = 0; /* explicit */
538 else if (!IN_PACK(entry))
539 to_reuse = 0; /* can't reuse what we don't have */
540 else if (oe_type(entry) == OBJ_REF_DELTA ||
541 oe_type(entry) == OBJ_OFS_DELTA)
542 /* check_object() decided it for us ... */
543 to_reuse = usable_delta;
544 /* ... but pack split may override that */
545 else if (oe_type(entry) != entry->in_pack_type)
546 to_reuse = 0; /* pack has delta which is unusable */
547 else if (DELTA(entry))
548 to_reuse = 0; /* we want to pack afresh */
549 else
550 to_reuse = 1; /* we have it in-pack undeltified,
551 * and we do not need to deltify it.
554 if (!to_reuse)
555 len = write_no_reuse_object(f, entry, limit, usable_delta);
556 else
557 len = write_reuse_object(f, entry, limit, usable_delta);
558 if (!len)
559 return 0;
561 if (usable_delta)
562 written_delta++;
563 written++;
564 if (!pack_to_stdout)
565 entry->idx.crc32 = crc32_end(f);
566 return len;
569 enum write_one_status {
570 WRITE_ONE_SKIP = -1, /* already written */
571 WRITE_ONE_BREAK = 0, /* writing this will bust the limit; not written */
572 WRITE_ONE_WRITTEN = 1, /* normal */
573 WRITE_ONE_RECURSIVE = 2 /* already scheduled to be written */
576 static enum write_one_status write_one(struct hashfile *f,
577 struct object_entry *e,
578 off_t *offset)
580 off_t size;
581 int recursing;
584 * we set offset to 1 (which is an impossible value) to mark
585 * the fact that this object is involved in "write its base
586 * first before writing a deltified object" recursion.
588 recursing = (e->idx.offset == 1);
589 if (recursing) {
590 warning(_("recursive delta detected for object %s"),
591 oid_to_hex(&e->idx.oid));
592 return WRITE_ONE_RECURSIVE;
593 } else if (e->idx.offset || e->preferred_base) {
594 /* offset is non zero if object is written already. */
595 return WRITE_ONE_SKIP;
598 /* if we are deltified, write out base object first. */
599 if (DELTA(e)) {
600 e->idx.offset = 1; /* now recurse */
601 switch (write_one(f, DELTA(e), offset)) {
602 case WRITE_ONE_RECURSIVE:
603 /* we cannot depend on this one */
604 SET_DELTA(e, NULL);
605 break;
606 default:
607 break;
608 case WRITE_ONE_BREAK:
609 e->idx.offset = recursing;
610 return WRITE_ONE_BREAK;
614 e->idx.offset = *offset;
615 size = write_object(f, e, *offset);
616 if (!size) {
617 e->idx.offset = recursing;
618 return WRITE_ONE_BREAK;
620 written_list[nr_written++] = &e->idx;
622 /* make sure off_t is sufficiently large not to wrap */
623 if (signed_add_overflows(*offset, size))
624 die(_("pack too large for current definition of off_t"));
625 *offset += size;
626 return WRITE_ONE_WRITTEN;
629 static int mark_tagged(const char *path, const struct object_id *oid, int flag,
630 void *cb_data)
632 struct object_id peeled;
633 struct object_entry *entry = packlist_find(&to_pack, oid);
635 if (entry)
636 entry->tagged = 1;
637 if (!peel_iterated_oid(oid, &peeled)) {
638 entry = packlist_find(&to_pack, &peeled);
639 if (entry)
640 entry->tagged = 1;
642 return 0;
645 static inline void add_to_write_order(struct object_entry **wo,
646 unsigned int *endp,
647 struct object_entry *e)
649 if (e->filled || oe_layer(&to_pack, e) != write_layer)
650 return;
651 wo[(*endp)++] = e;
652 e->filled = 1;
655 static void add_descendants_to_write_order(struct object_entry **wo,
656 unsigned int *endp,
657 struct object_entry *e)
659 int add_to_order = 1;
660 while (e) {
661 if (add_to_order) {
662 struct object_entry *s;
663 /* add this node... */
664 add_to_write_order(wo, endp, e);
665 /* all its siblings... */
666 for (s = DELTA_SIBLING(e); s; s = DELTA_SIBLING(s)) {
667 add_to_write_order(wo, endp, s);
670 /* drop down a level to add left subtree nodes if possible */
671 if (DELTA_CHILD(e)) {
672 add_to_order = 1;
673 e = DELTA_CHILD(e);
674 } else {
675 add_to_order = 0;
676 /* our sibling might have some children, it is next */
677 if (DELTA_SIBLING(e)) {
678 e = DELTA_SIBLING(e);
679 continue;
681 /* go back to our parent node */
682 e = DELTA(e);
683 while (e && !DELTA_SIBLING(e)) {
684 /* we're on the right side of a subtree, keep
685 * going up until we can go right again */
686 e = DELTA(e);
688 if (!e) {
689 /* done- we hit our original root node */
690 return;
692 /* pass it off to sibling at this level */
693 e = DELTA_SIBLING(e);
698 static void add_family_to_write_order(struct object_entry **wo,
699 unsigned int *endp,
700 struct object_entry *e)
702 struct object_entry *root;
704 for (root = e; DELTA(root); root = DELTA(root))
705 ; /* nothing */
706 add_descendants_to_write_order(wo, endp, root);
709 static void compute_layer_order(struct object_entry **wo, unsigned int *wo_end)
711 unsigned int i, last_untagged;
712 struct object_entry *objects = to_pack.objects;
714 for (i = 0; i < to_pack.nr_objects; i++) {
715 if (objects[i].tagged)
716 break;
717 add_to_write_order(wo, wo_end, &objects[i]);
719 last_untagged = i;
722 * Then fill all the tagged tips.
724 for (; i < to_pack.nr_objects; i++) {
725 if (objects[i].tagged)
726 add_to_write_order(wo, wo_end, &objects[i]);
730 * And then all remaining commits and tags.
732 for (i = last_untagged; i < to_pack.nr_objects; i++) {
733 if (oe_type(&objects[i]) != OBJ_COMMIT &&
734 oe_type(&objects[i]) != OBJ_TAG)
735 continue;
736 add_to_write_order(wo, wo_end, &objects[i]);
740 * And then all the trees.
742 for (i = last_untagged; i < to_pack.nr_objects; i++) {
743 if (oe_type(&objects[i]) != OBJ_TREE)
744 continue;
745 add_to_write_order(wo, wo_end, &objects[i]);
749 * Finally all the rest in really tight order
751 for (i = last_untagged; i < to_pack.nr_objects; i++) {
752 if (!objects[i].filled && oe_layer(&to_pack, &objects[i]) == write_layer)
753 add_family_to_write_order(wo, wo_end, &objects[i]);
757 static struct object_entry **compute_write_order(void)
759 uint32_t max_layers = 1;
760 unsigned int i, wo_end;
762 struct object_entry **wo;
763 struct object_entry *objects = to_pack.objects;
765 for (i = 0; i < to_pack.nr_objects; i++) {
766 objects[i].tagged = 0;
767 objects[i].filled = 0;
768 SET_DELTA_CHILD(&objects[i], NULL);
769 SET_DELTA_SIBLING(&objects[i], NULL);
773 * Fully connect delta_child/delta_sibling network.
774 * Make sure delta_sibling is sorted in the original
775 * recency order.
777 for (i = to_pack.nr_objects; i > 0;) {
778 struct object_entry *e = &objects[--i];
779 if (!DELTA(e))
780 continue;
781 /* Mark me as the first child */
782 e->delta_sibling_idx = DELTA(e)->delta_child_idx;
783 SET_DELTA_CHILD(DELTA(e), e);
787 * Mark objects that are at the tip of tags.
789 for_each_tag_ref(mark_tagged, NULL);
791 if (use_delta_islands)
792 max_layers = compute_pack_layers(&to_pack);
794 ALLOC_ARRAY(wo, to_pack.nr_objects);
795 wo_end = 0;
797 for (; write_layer < max_layers; ++write_layer)
798 compute_layer_order(wo, &wo_end);
800 if (wo_end != to_pack.nr_objects)
801 die(_("ordered %u objects, expected %"PRIu32),
802 wo_end, to_pack.nr_objects);
804 return wo;
809 * A reused set of objects. All objects in a chunk have the same
810 * relative position in the original packfile and the generated
811 * packfile.
814 static struct reused_chunk {
815 /* The offset of the first object of this chunk in the original
816 * packfile. */
817 off_t original;
818 /* The difference for "original" minus the offset of the first object of
819 * this chunk in the generated packfile. */
820 off_t difference;
821 } *reused_chunks;
822 static int reused_chunks_nr;
823 static int reused_chunks_alloc;
825 static void record_reused_object(off_t where, off_t offset)
827 if (reused_chunks_nr && reused_chunks[reused_chunks_nr-1].difference == offset)
828 return;
830 ALLOC_GROW(reused_chunks, reused_chunks_nr + 1,
831 reused_chunks_alloc);
832 reused_chunks[reused_chunks_nr].original = where;
833 reused_chunks[reused_chunks_nr].difference = offset;
834 reused_chunks_nr++;
838 * Binary search to find the chunk that "where" is in. Note
839 * that we're not looking for an exact match, just the first
840 * chunk that contains it (which implicitly ends at the start
841 * of the next chunk.
843 static off_t find_reused_offset(off_t where)
845 int lo = 0, hi = reused_chunks_nr;
846 while (lo < hi) {
847 int mi = lo + ((hi - lo) / 2);
848 if (where == reused_chunks[mi].original)
849 return reused_chunks[mi].difference;
850 if (where < reused_chunks[mi].original)
851 hi = mi;
852 else
853 lo = mi + 1;
857 * The first chunk starts at zero, so we can't have gone below
858 * there.
860 assert(lo);
861 return reused_chunks[lo-1].difference;
864 static void write_reused_pack_one(size_t pos, struct hashfile *out,
865 struct pack_window **w_curs)
867 off_t offset, next, cur;
868 enum object_type type;
869 unsigned long size;
871 offset = pack_pos_to_offset(reuse_packfile, pos);
872 next = pack_pos_to_offset(reuse_packfile, pos + 1);
874 record_reused_object(offset, offset - hashfile_total(out));
876 cur = offset;
877 type = unpack_object_header(reuse_packfile, w_curs, &cur, &size);
878 assert(type >= 0);
880 if (type == OBJ_OFS_DELTA) {
881 off_t base_offset;
882 off_t fixup;
884 unsigned char header[MAX_PACK_OBJECT_HEADER];
885 unsigned len;
887 base_offset = get_delta_base(reuse_packfile, w_curs, &cur, type, offset);
888 assert(base_offset != 0);
890 /* Convert to REF_DELTA if we must... */
891 if (!allow_ofs_delta) {
892 uint32_t base_pos;
893 struct object_id base_oid;
895 if (offset_to_pack_pos(reuse_packfile, base_offset, &base_pos) < 0)
896 die(_("expected object at offset %"PRIuMAX" "
897 "in pack %s"),
898 (uintmax_t)base_offset,
899 reuse_packfile->pack_name);
901 nth_packed_object_id(&base_oid, reuse_packfile,
902 pack_pos_to_index(reuse_packfile, base_pos));
904 len = encode_in_pack_object_header(header, sizeof(header),
905 OBJ_REF_DELTA, size);
906 hashwrite(out, header, len);
907 hashwrite(out, base_oid.hash, the_hash_algo->rawsz);
908 copy_pack_data(out, reuse_packfile, w_curs, cur, next - cur);
909 return;
912 /* Otherwise see if we need to rewrite the offset... */
913 fixup = find_reused_offset(offset) -
914 find_reused_offset(base_offset);
915 if (fixup) {
916 unsigned char ofs_header[10];
917 unsigned i, ofs_len;
918 off_t ofs = offset - base_offset - fixup;
920 len = encode_in_pack_object_header(header, sizeof(header),
921 OBJ_OFS_DELTA, size);
923 i = sizeof(ofs_header) - 1;
924 ofs_header[i] = ofs & 127;
925 while (ofs >>= 7)
926 ofs_header[--i] = 128 | (--ofs & 127);
928 ofs_len = sizeof(ofs_header) - i;
930 hashwrite(out, header, len);
931 hashwrite(out, ofs_header + sizeof(ofs_header) - ofs_len, ofs_len);
932 copy_pack_data(out, reuse_packfile, w_curs, cur, next - cur);
933 return;
936 /* ...otherwise we have no fixup, and can write it verbatim */
939 copy_pack_data(out, reuse_packfile, w_curs, offset, next - offset);
942 static size_t write_reused_pack_verbatim(struct hashfile *out,
943 struct pack_window **w_curs)
945 size_t pos = 0;
947 while (pos < reuse_packfile_bitmap->word_alloc &&
948 reuse_packfile_bitmap->words[pos] == (eword_t)~0)
949 pos++;
951 if (pos) {
952 off_t to_write;
954 written = (pos * BITS_IN_EWORD);
955 to_write = pack_pos_to_offset(reuse_packfile, written)
956 - sizeof(struct pack_header);
958 /* We're recording one chunk, not one object. */
959 record_reused_object(sizeof(struct pack_header), 0);
960 hashflush(out);
961 copy_pack_data(out, reuse_packfile, w_curs,
962 sizeof(struct pack_header), to_write);
964 display_progress(progress_state, written);
966 return pos;
969 static void write_reused_pack(struct hashfile *f)
971 size_t i = 0;
972 uint32_t offset;
973 struct pack_window *w_curs = NULL;
975 if (allow_ofs_delta)
976 i = write_reused_pack_verbatim(f, &w_curs);
978 for (; i < reuse_packfile_bitmap->word_alloc; ++i) {
979 eword_t word = reuse_packfile_bitmap->words[i];
980 size_t pos = (i * BITS_IN_EWORD);
982 for (offset = 0; offset < BITS_IN_EWORD; ++offset) {
983 if ((word >> offset) == 0)
984 break;
986 offset += ewah_bit_ctz64(word >> offset);
987 write_reused_pack_one(pos + offset, f, &w_curs);
988 display_progress(progress_state, ++written);
992 unuse_pack(&w_curs);
995 static void write_excluded_by_configs(void)
997 struct oidset_iter iter;
998 const struct object_id *oid;
1000 oidset_iter_init(&excluded_by_config, &iter);
1001 while ((oid = oidset_iter_next(&iter))) {
1002 struct configured_exclusion *ex =
1003 oidmap_get(&configured_exclusions, oid);
1005 if (!ex)
1006 BUG("configured exclusion wasn't configured");
1007 write_in_full(1, ex->pack_hash_hex, strlen(ex->pack_hash_hex));
1008 write_in_full(1, " ", 1);
1009 write_in_full(1, ex->uri, strlen(ex->uri));
1010 write_in_full(1, "\n", 1);
1014 static const char no_split_warning[] = N_(
1015 "disabling bitmap writing, packs are split due to pack.packSizeLimit"
1018 static void write_pack_file(void)
1020 uint32_t i = 0, j;
1021 struct hashfile *f;
1022 off_t offset;
1023 uint32_t nr_remaining = nr_result;
1024 time_t last_mtime = 0;
1025 struct object_entry **write_order;
1027 if (progress > pack_to_stdout)
1028 progress_state = start_progress(_("Writing objects"), nr_result);
1029 ALLOC_ARRAY(written_list, to_pack.nr_objects);
1030 write_order = compute_write_order();
1032 do {
1033 unsigned char hash[GIT_MAX_RAWSZ];
1034 char *pack_tmp_name = NULL;
1036 if (pack_to_stdout)
1037 f = hashfd_throughput(1, "<stdout>", progress_state);
1038 else
1039 f = create_tmp_packfile(&pack_tmp_name);
1041 offset = write_pack_header(f, nr_remaining);
1043 if (reuse_packfile) {
1044 assert(pack_to_stdout);
1045 write_reused_pack(f);
1046 offset = hashfile_total(f);
1049 nr_written = 0;
1050 for (; i < to_pack.nr_objects; i++) {
1051 struct object_entry *e = write_order[i];
1052 if (write_one(f, e, &offset) == WRITE_ONE_BREAK)
1053 break;
1054 display_progress(progress_state, written);
1058 * Did we write the wrong # entries in the header?
1059 * If so, rewrite it like in fast-import
1061 if (pack_to_stdout) {
1062 finalize_hashfile(f, hash, CSUM_HASH_IN_STREAM | CSUM_CLOSE);
1063 } else if (nr_written == nr_remaining) {
1064 finalize_hashfile(f, hash, CSUM_HASH_IN_STREAM | CSUM_FSYNC | CSUM_CLOSE);
1065 } else {
1066 int fd = finalize_hashfile(f, hash, 0);
1067 fixup_pack_header_footer(fd, hash, pack_tmp_name,
1068 nr_written, hash, offset);
1069 close(fd);
1070 if (write_bitmap_index) {
1071 if (write_bitmap_index != WRITE_BITMAP_QUIET)
1072 warning(_(no_split_warning));
1073 write_bitmap_index = 0;
1077 if (!pack_to_stdout) {
1078 struct stat st;
1079 struct strbuf tmpname = STRBUF_INIT;
1082 * Packs are runtime accessed in their mtime
1083 * order since newer packs are more likely to contain
1084 * younger objects. So if we are creating multiple
1085 * packs then we should modify the mtime of later ones
1086 * to preserve this property.
1088 if (stat(pack_tmp_name, &st) < 0) {
1089 warning_errno(_("failed to stat %s"), pack_tmp_name);
1090 } else if (!last_mtime) {
1091 last_mtime = st.st_mtime;
1092 } else {
1093 struct utimbuf utb;
1094 utb.actime = st.st_atime;
1095 utb.modtime = --last_mtime;
1096 if (utime(pack_tmp_name, &utb) < 0)
1097 warning_errno(_("failed utime() on %s"), pack_tmp_name);
1100 strbuf_addf(&tmpname, "%s-", base_name);
1102 if (write_bitmap_index) {
1103 bitmap_writer_set_checksum(hash);
1104 bitmap_writer_build_type_index(
1105 &to_pack, written_list, nr_written);
1108 finish_tmp_packfile(&tmpname, pack_tmp_name,
1109 written_list, nr_written,
1110 &pack_idx_opts, hash);
1112 if (write_bitmap_index) {
1113 strbuf_addf(&tmpname, "%s.bitmap", hash_to_hex(hash));
1115 stop_progress(&progress_state);
1117 bitmap_writer_show_progress(progress);
1118 bitmap_writer_select_commits(indexed_commits, indexed_commits_nr, -1);
1119 bitmap_writer_build(&to_pack);
1120 bitmap_writer_finish(written_list, nr_written,
1121 tmpname.buf, write_bitmap_options);
1122 write_bitmap_index = 0;
1125 strbuf_release(&tmpname);
1126 free(pack_tmp_name);
1127 puts(hash_to_hex(hash));
1130 /* mark written objects as written to previous pack */
1131 for (j = 0; j < nr_written; j++) {
1132 written_list[j]->offset = (off_t)-1;
1134 nr_remaining -= nr_written;
1135 } while (nr_remaining && i < to_pack.nr_objects);
1137 free(written_list);
1138 free(write_order);
1139 stop_progress(&progress_state);
1140 if (written != nr_result)
1141 die(_("wrote %"PRIu32" objects while expecting %"PRIu32),
1142 written, nr_result);
1143 trace2_data_intmax("pack-objects", the_repository,
1144 "write_pack_file/wrote", nr_result);
1147 static int no_try_delta(const char *path)
1149 static struct attr_check *check;
1151 if (!check)
1152 check = attr_check_initl("delta", NULL);
1153 git_check_attr(the_repository->index, path, check);
1154 if (ATTR_FALSE(check->items[0].value))
1155 return 1;
1156 return 0;
1160 * When adding an object, check whether we have already added it
1161 * to our packing list. If so, we can skip. However, if we are
1162 * being asked to excludei t, but the previous mention was to include
1163 * it, make sure to adjust its flags and tweak our numbers accordingly.
1165 * As an optimization, we pass out the index position where we would have
1166 * found the item, since that saves us from having to look it up again a
1167 * few lines later when we want to add the new entry.
1169 static int have_duplicate_entry(const struct object_id *oid,
1170 int exclude)
1172 struct object_entry *entry;
1174 if (reuse_packfile_bitmap &&
1175 bitmap_walk_contains(bitmap_git, reuse_packfile_bitmap, oid))
1176 return 1;
1178 entry = packlist_find(&to_pack, oid);
1179 if (!entry)
1180 return 0;
1182 if (exclude) {
1183 if (!entry->preferred_base)
1184 nr_result--;
1185 entry->preferred_base = 1;
1188 return 1;
1191 static int want_found_object(const struct object_id *oid, int exclude,
1192 struct packed_git *p)
1194 if (exclude)
1195 return 1;
1196 if (incremental)
1197 return 0;
1200 * When asked to do --local (do not include an object that appears in a
1201 * pack we borrow from elsewhere) or --honor-pack-keep (do not include
1202 * an object that appears in a pack marked with .keep), finding a pack
1203 * that matches the criteria is sufficient for us to decide to omit it.
1204 * However, even if this pack does not satisfy the criteria, we need to
1205 * make sure no copy of this object appears in _any_ pack that makes us
1206 * to omit the object, so we need to check all the packs.
1208 * We can however first check whether these options can possibly matter;
1209 * if they do not matter we know we want the object in generated pack.
1210 * Otherwise, we signal "-1" at the end to tell the caller that we do
1211 * not know either way, and it needs to check more packs.
1215 * Objects in packs borrowed from elsewhere are discarded regardless of
1216 * if they appear in other packs that weren't borrowed.
1218 if (local && !p->pack_local)
1219 return 0;
1222 * Then handle .keep first, as we have a fast(er) path there.
1224 if (ignore_packed_keep_on_disk || ignore_packed_keep_in_core) {
1226 * Set the flags for the kept-pack cache to be the ones we want
1227 * to ignore.
1229 * That is, if we are ignoring objects in on-disk keep packs,
1230 * then we want to search through the on-disk keep and ignore
1231 * the in-core ones.
1233 unsigned flags = 0;
1234 if (ignore_packed_keep_on_disk)
1235 flags |= ON_DISK_KEEP_PACKS;
1236 if (ignore_packed_keep_in_core)
1237 flags |= IN_CORE_KEEP_PACKS;
1239 if (ignore_packed_keep_on_disk && p->pack_keep)
1240 return 0;
1241 if (ignore_packed_keep_in_core && p->pack_keep_in_core)
1242 return 0;
1243 if (has_object_kept_pack(oid, flags))
1244 return 0;
1248 * At this point we know definitively that either we don't care about
1249 * keep-packs, or the object is not in one. Keep checking other
1250 * conditions...
1252 if (!local || !have_non_local_packs)
1253 return 1;
1255 /* we don't know yet; keep looking for more packs */
1256 return -1;
1259 static int want_object_in_pack_one(struct packed_git *p,
1260 const struct object_id *oid,
1261 int exclude,
1262 struct packed_git **found_pack,
1263 off_t *found_offset)
1265 off_t offset;
1267 if (p == *found_pack)
1268 offset = *found_offset;
1269 else
1270 offset = find_pack_entry_one(oid->hash, p);
1272 if (offset) {
1273 if (!*found_pack) {
1274 if (!is_pack_valid(p))
1275 return -1;
1276 *found_offset = offset;
1277 *found_pack = p;
1279 return want_found_object(oid, exclude, p);
1281 return -1;
1285 * Check whether we want the object in the pack (e.g., we do not want
1286 * objects found in non-local stores if the "--local" option was used).
1288 * If the caller already knows an existing pack it wants to take the object
1289 * from, that is passed in *found_pack and *found_offset; otherwise this
1290 * function finds if there is any pack that has the object and returns the pack
1291 * and its offset in these variables.
1293 static int want_object_in_pack(const struct object_id *oid,
1294 int exclude,
1295 struct packed_git **found_pack,
1296 off_t *found_offset)
1298 int want;
1299 struct list_head *pos;
1300 struct multi_pack_index *m;
1302 if (!exclude && local && has_loose_object_nonlocal(oid))
1303 return 0;
1306 * If we already know the pack object lives in, start checks from that
1307 * pack - in the usual case when neither --local was given nor .keep files
1308 * are present we will determine the answer right now.
1310 if (*found_pack) {
1311 want = want_found_object(oid, exclude, *found_pack);
1312 if (want != -1)
1313 return want;
1316 for (m = get_multi_pack_index(the_repository); m; m = m->next) {
1317 struct pack_entry e;
1318 if (fill_midx_entry(the_repository, oid, &e, m)) {
1319 want = want_object_in_pack_one(e.p, oid, exclude, found_pack, found_offset);
1320 if (want != -1)
1321 return want;
1325 list_for_each(pos, get_packed_git_mru(the_repository)) {
1326 struct packed_git *p = list_entry(pos, struct packed_git, mru);
1327 want = want_object_in_pack_one(p, oid, exclude, found_pack, found_offset);
1328 if (!exclude && want > 0)
1329 list_move(&p->mru,
1330 get_packed_git_mru(the_repository));
1331 if (want != -1)
1332 return want;
1335 if (uri_protocols.nr) {
1336 struct configured_exclusion *ex =
1337 oidmap_get(&configured_exclusions, oid);
1338 int i;
1339 const char *p;
1341 if (ex) {
1342 for (i = 0; i < uri_protocols.nr; i++) {
1343 if (skip_prefix(ex->uri,
1344 uri_protocols.items[i].string,
1345 &p) &&
1346 *p == ':') {
1347 oidset_insert(&excluded_by_config, oid);
1348 return 0;
1354 return 1;
1357 static void create_object_entry(const struct object_id *oid,
1358 enum object_type type,
1359 uint32_t hash,
1360 int exclude,
1361 int no_try_delta,
1362 struct packed_git *found_pack,
1363 off_t found_offset)
1365 struct object_entry *entry;
1367 entry = packlist_alloc(&to_pack, oid);
1368 entry->hash = hash;
1369 oe_set_type(entry, type);
1370 if (exclude)
1371 entry->preferred_base = 1;
1372 else
1373 nr_result++;
1374 if (found_pack) {
1375 oe_set_in_pack(&to_pack, entry, found_pack);
1376 entry->in_pack_offset = found_offset;
1379 entry->no_try_delta = no_try_delta;
1382 static const char no_closure_warning[] = N_(
1383 "disabling bitmap writing, as some objects are not being packed"
1386 static int add_object_entry(const struct object_id *oid, enum object_type type,
1387 const char *name, int exclude)
1389 struct packed_git *found_pack = NULL;
1390 off_t found_offset = 0;
1392 display_progress(progress_state, ++nr_seen);
1394 if (have_duplicate_entry(oid, exclude))
1395 return 0;
1397 if (!want_object_in_pack(oid, exclude, &found_pack, &found_offset)) {
1398 /* The pack is missing an object, so it will not have closure */
1399 if (write_bitmap_index) {
1400 if (write_bitmap_index != WRITE_BITMAP_QUIET)
1401 warning(_(no_closure_warning));
1402 write_bitmap_index = 0;
1404 return 0;
1407 create_object_entry(oid, type, pack_name_hash(name),
1408 exclude, name && no_try_delta(name),
1409 found_pack, found_offset);
1410 return 1;
1413 static int add_object_entry_from_bitmap(const struct object_id *oid,
1414 enum object_type type,
1415 int flags, uint32_t name_hash,
1416 struct packed_git *pack, off_t offset)
1418 display_progress(progress_state, ++nr_seen);
1420 if (have_duplicate_entry(oid, 0))
1421 return 0;
1423 if (!want_object_in_pack(oid, 0, &pack, &offset))
1424 return 0;
1426 create_object_entry(oid, type, name_hash, 0, 0, pack, offset);
1427 return 1;
1430 struct pbase_tree_cache {
1431 struct object_id oid;
1432 int ref;
1433 int temporary;
1434 void *tree_data;
1435 unsigned long tree_size;
1438 static struct pbase_tree_cache *(pbase_tree_cache[256]);
1439 static int pbase_tree_cache_ix(const struct object_id *oid)
1441 return oid->hash[0] % ARRAY_SIZE(pbase_tree_cache);
1443 static int pbase_tree_cache_ix_incr(int ix)
1445 return (ix+1) % ARRAY_SIZE(pbase_tree_cache);
1448 static struct pbase_tree {
1449 struct pbase_tree *next;
1450 /* This is a phony "cache" entry; we are not
1451 * going to evict it or find it through _get()
1452 * mechanism -- this is for the toplevel node that
1453 * would almost always change with any commit.
1455 struct pbase_tree_cache pcache;
1456 } *pbase_tree;
1458 static struct pbase_tree_cache *pbase_tree_get(const struct object_id *oid)
1460 struct pbase_tree_cache *ent, *nent;
1461 void *data;
1462 unsigned long size;
1463 enum object_type type;
1464 int neigh;
1465 int my_ix = pbase_tree_cache_ix(oid);
1466 int available_ix = -1;
1468 /* pbase-tree-cache acts as a limited hashtable.
1469 * your object will be found at your index or within a few
1470 * slots after that slot if it is cached.
1472 for (neigh = 0; neigh < 8; neigh++) {
1473 ent = pbase_tree_cache[my_ix];
1474 if (ent && oideq(&ent->oid, oid)) {
1475 ent->ref++;
1476 return ent;
1478 else if (((available_ix < 0) && (!ent || !ent->ref)) ||
1479 ((0 <= available_ix) &&
1480 (!ent && pbase_tree_cache[available_ix])))
1481 available_ix = my_ix;
1482 if (!ent)
1483 break;
1484 my_ix = pbase_tree_cache_ix_incr(my_ix);
1487 /* Did not find one. Either we got a bogus request or
1488 * we need to read and perhaps cache.
1490 data = read_object_file(oid, &type, &size);
1491 if (!data)
1492 return NULL;
1493 if (type != OBJ_TREE) {
1494 free(data);
1495 return NULL;
1498 /* We need to either cache or return a throwaway copy */
1500 if (available_ix < 0)
1501 ent = NULL;
1502 else {
1503 ent = pbase_tree_cache[available_ix];
1504 my_ix = available_ix;
1507 if (!ent) {
1508 nent = xmalloc(sizeof(*nent));
1509 nent->temporary = (available_ix < 0);
1511 else {
1512 /* evict and reuse */
1513 free(ent->tree_data);
1514 nent = ent;
1516 oidcpy(&nent->oid, oid);
1517 nent->tree_data = data;
1518 nent->tree_size = size;
1519 nent->ref = 1;
1520 if (!nent->temporary)
1521 pbase_tree_cache[my_ix] = nent;
1522 return nent;
1525 static void pbase_tree_put(struct pbase_tree_cache *cache)
1527 if (!cache->temporary) {
1528 cache->ref--;
1529 return;
1531 free(cache->tree_data);
1532 free(cache);
1535 static int name_cmp_len(const char *name)
1537 int i;
1538 for (i = 0; name[i] && name[i] != '\n' && name[i] != '/'; i++)
1540 return i;
1543 static void add_pbase_object(struct tree_desc *tree,
1544 const char *name,
1545 int cmplen,
1546 const char *fullname)
1548 struct name_entry entry;
1549 int cmp;
1551 while (tree_entry(tree,&entry)) {
1552 if (S_ISGITLINK(entry.mode))
1553 continue;
1554 cmp = tree_entry_len(&entry) != cmplen ? 1 :
1555 memcmp(name, entry.path, cmplen);
1556 if (cmp > 0)
1557 continue;
1558 if (cmp < 0)
1559 return;
1560 if (name[cmplen] != '/') {
1561 add_object_entry(&entry.oid,
1562 object_type(entry.mode),
1563 fullname, 1);
1564 return;
1566 if (S_ISDIR(entry.mode)) {
1567 struct tree_desc sub;
1568 struct pbase_tree_cache *tree;
1569 const char *down = name+cmplen+1;
1570 int downlen = name_cmp_len(down);
1572 tree = pbase_tree_get(&entry.oid);
1573 if (!tree)
1574 return;
1575 init_tree_desc(&sub, tree->tree_data, tree->tree_size);
1577 add_pbase_object(&sub, down, downlen, fullname);
1578 pbase_tree_put(tree);
1583 static unsigned *done_pbase_paths;
1584 static int done_pbase_paths_num;
1585 static int done_pbase_paths_alloc;
1586 static int done_pbase_path_pos(unsigned hash)
1588 int lo = 0;
1589 int hi = done_pbase_paths_num;
1590 while (lo < hi) {
1591 int mi = lo + (hi - lo) / 2;
1592 if (done_pbase_paths[mi] == hash)
1593 return mi;
1594 if (done_pbase_paths[mi] < hash)
1595 hi = mi;
1596 else
1597 lo = mi + 1;
1599 return -lo-1;
1602 static int check_pbase_path(unsigned hash)
1604 int pos = done_pbase_path_pos(hash);
1605 if (0 <= pos)
1606 return 1;
1607 pos = -pos - 1;
1608 ALLOC_GROW(done_pbase_paths,
1609 done_pbase_paths_num + 1,
1610 done_pbase_paths_alloc);
1611 done_pbase_paths_num++;
1612 if (pos < done_pbase_paths_num)
1613 MOVE_ARRAY(done_pbase_paths + pos + 1, done_pbase_paths + pos,
1614 done_pbase_paths_num - pos - 1);
1615 done_pbase_paths[pos] = hash;
1616 return 0;
1619 static void add_preferred_base_object(const char *name)
1621 struct pbase_tree *it;
1622 int cmplen;
1623 unsigned hash = pack_name_hash(name);
1625 if (!num_preferred_base || check_pbase_path(hash))
1626 return;
1628 cmplen = name_cmp_len(name);
1629 for (it = pbase_tree; it; it = it->next) {
1630 if (cmplen == 0) {
1631 add_object_entry(&it->pcache.oid, OBJ_TREE, NULL, 1);
1633 else {
1634 struct tree_desc tree;
1635 init_tree_desc(&tree, it->pcache.tree_data, it->pcache.tree_size);
1636 add_pbase_object(&tree, name, cmplen, name);
1641 static void add_preferred_base(struct object_id *oid)
1643 struct pbase_tree *it;
1644 void *data;
1645 unsigned long size;
1646 struct object_id tree_oid;
1648 if (window <= num_preferred_base++)
1649 return;
1651 data = read_object_with_reference(the_repository, oid,
1652 tree_type, &size, &tree_oid);
1653 if (!data)
1654 return;
1656 for (it = pbase_tree; it; it = it->next) {
1657 if (oideq(&it->pcache.oid, &tree_oid)) {
1658 free(data);
1659 return;
1663 CALLOC_ARRAY(it, 1);
1664 it->next = pbase_tree;
1665 pbase_tree = it;
1667 oidcpy(&it->pcache.oid, &tree_oid);
1668 it->pcache.tree_data = data;
1669 it->pcache.tree_size = size;
1672 static void cleanup_preferred_base(void)
1674 struct pbase_tree *it;
1675 unsigned i;
1677 it = pbase_tree;
1678 pbase_tree = NULL;
1679 while (it) {
1680 struct pbase_tree *tmp = it;
1681 it = tmp->next;
1682 free(tmp->pcache.tree_data);
1683 free(tmp);
1686 for (i = 0; i < ARRAY_SIZE(pbase_tree_cache); i++) {
1687 if (!pbase_tree_cache[i])
1688 continue;
1689 free(pbase_tree_cache[i]->tree_data);
1690 FREE_AND_NULL(pbase_tree_cache[i]);
1693 FREE_AND_NULL(done_pbase_paths);
1694 done_pbase_paths_num = done_pbase_paths_alloc = 0;
1698 * Return 1 iff the object specified by "delta" can be sent
1699 * literally as a delta against the base in "base_sha1". If
1700 * so, then *base_out will point to the entry in our packing
1701 * list, or NULL if we must use the external-base list.
1703 * Depth value does not matter - find_deltas() will
1704 * never consider reused delta as the base object to
1705 * deltify other objects against, in order to avoid
1706 * circular deltas.
1708 static int can_reuse_delta(const struct object_id *base_oid,
1709 struct object_entry *delta,
1710 struct object_entry **base_out)
1712 struct object_entry *base;
1715 * First see if we're already sending the base (or it's explicitly in
1716 * our "excluded" list).
1718 base = packlist_find(&to_pack, base_oid);
1719 if (base) {
1720 if (!in_same_island(&delta->idx.oid, &base->idx.oid))
1721 return 0;
1722 *base_out = base;
1723 return 1;
1727 * Otherwise, reachability bitmaps may tell us if the receiver has it,
1728 * even if it was buried too deep in history to make it into the
1729 * packing list.
1731 if (thin && bitmap_has_oid_in_uninteresting(bitmap_git, base_oid)) {
1732 if (use_delta_islands) {
1733 if (!in_same_island(&delta->idx.oid, base_oid))
1734 return 0;
1736 *base_out = NULL;
1737 return 1;
1740 return 0;
1743 static void prefetch_to_pack(uint32_t object_index_start) {
1744 struct oid_array to_fetch = OID_ARRAY_INIT;
1745 uint32_t i;
1747 for (i = object_index_start; i < to_pack.nr_objects; i++) {
1748 struct object_entry *entry = to_pack.objects + i;
1750 if (!oid_object_info_extended(the_repository,
1751 &entry->idx.oid,
1752 NULL,
1753 OBJECT_INFO_FOR_PREFETCH))
1754 continue;
1755 oid_array_append(&to_fetch, &entry->idx.oid);
1757 promisor_remote_get_direct(the_repository,
1758 to_fetch.oid, to_fetch.nr);
1759 oid_array_clear(&to_fetch);
1762 static void check_object(struct object_entry *entry, uint32_t object_index)
1764 unsigned long canonical_size;
1765 enum object_type type;
1766 struct object_info oi = {.typep = &type, .sizep = &canonical_size};
1768 if (IN_PACK(entry)) {
1769 struct packed_git *p = IN_PACK(entry);
1770 struct pack_window *w_curs = NULL;
1771 int have_base = 0;
1772 struct object_id base_ref;
1773 struct object_entry *base_entry;
1774 unsigned long used, used_0;
1775 unsigned long avail;
1776 off_t ofs;
1777 unsigned char *buf, c;
1778 enum object_type type;
1779 unsigned long in_pack_size;
1781 buf = use_pack(p, &w_curs, entry->in_pack_offset, &avail);
1784 * We want in_pack_type even if we do not reuse delta
1785 * since non-delta representations could still be reused.
1787 used = unpack_object_header_buffer(buf, avail,
1788 &type,
1789 &in_pack_size);
1790 if (used == 0)
1791 goto give_up;
1793 if (type < 0)
1794 BUG("invalid type %d", type);
1795 entry->in_pack_type = type;
1798 * Determine if this is a delta and if so whether we can
1799 * reuse it or not. Otherwise let's find out as cheaply as
1800 * possible what the actual type and size for this object is.
1802 switch (entry->in_pack_type) {
1803 default:
1804 /* Not a delta hence we've already got all we need. */
1805 oe_set_type(entry, entry->in_pack_type);
1806 SET_SIZE(entry, in_pack_size);
1807 entry->in_pack_header_size = used;
1808 if (oe_type(entry) < OBJ_COMMIT || oe_type(entry) > OBJ_BLOB)
1809 goto give_up;
1810 unuse_pack(&w_curs);
1811 return;
1812 case OBJ_REF_DELTA:
1813 if (reuse_delta && !entry->preferred_base) {
1814 oidread(&base_ref,
1815 use_pack(p, &w_curs,
1816 entry->in_pack_offset + used,
1817 NULL));
1818 have_base = 1;
1820 entry->in_pack_header_size = used + the_hash_algo->rawsz;
1821 break;
1822 case OBJ_OFS_DELTA:
1823 buf = use_pack(p, &w_curs,
1824 entry->in_pack_offset + used, NULL);
1825 used_0 = 0;
1826 c = buf[used_0++];
1827 ofs = c & 127;
1828 while (c & 128) {
1829 ofs += 1;
1830 if (!ofs || MSB(ofs, 7)) {
1831 error(_("delta base offset overflow in pack for %s"),
1832 oid_to_hex(&entry->idx.oid));
1833 goto give_up;
1835 c = buf[used_0++];
1836 ofs = (ofs << 7) + (c & 127);
1838 ofs = entry->in_pack_offset - ofs;
1839 if (ofs <= 0 || ofs >= entry->in_pack_offset) {
1840 error(_("delta base offset out of bound for %s"),
1841 oid_to_hex(&entry->idx.oid));
1842 goto give_up;
1844 if (reuse_delta && !entry->preferred_base) {
1845 uint32_t pos;
1846 if (offset_to_pack_pos(p, ofs, &pos) < 0)
1847 goto give_up;
1848 if (!nth_packed_object_id(&base_ref, p,
1849 pack_pos_to_index(p, pos)))
1850 have_base = 1;
1852 entry->in_pack_header_size = used + used_0;
1853 break;
1856 if (have_base &&
1857 can_reuse_delta(&base_ref, entry, &base_entry)) {
1858 oe_set_type(entry, entry->in_pack_type);
1859 SET_SIZE(entry, in_pack_size); /* delta size */
1860 SET_DELTA_SIZE(entry, in_pack_size);
1862 if (base_entry) {
1863 SET_DELTA(entry, base_entry);
1864 entry->delta_sibling_idx = base_entry->delta_child_idx;
1865 SET_DELTA_CHILD(base_entry, entry);
1866 } else {
1867 SET_DELTA_EXT(entry, &base_ref);
1870 unuse_pack(&w_curs);
1871 return;
1874 if (oe_type(entry)) {
1875 off_t delta_pos;
1878 * This must be a delta and we already know what the
1879 * final object type is. Let's extract the actual
1880 * object size from the delta header.
1882 delta_pos = entry->in_pack_offset + entry->in_pack_header_size;
1883 canonical_size = get_size_from_delta(p, &w_curs, delta_pos);
1884 if (canonical_size == 0)
1885 goto give_up;
1886 SET_SIZE(entry, canonical_size);
1887 unuse_pack(&w_curs);
1888 return;
1892 * No choice but to fall back to the recursive delta walk
1893 * with oid_object_info() to find about the object type
1894 * at this point...
1896 give_up:
1897 unuse_pack(&w_curs);
1900 if (oid_object_info_extended(the_repository, &entry->idx.oid, &oi,
1901 OBJECT_INFO_SKIP_FETCH_OBJECT | OBJECT_INFO_LOOKUP_REPLACE) < 0) {
1902 if (has_promisor_remote()) {
1903 prefetch_to_pack(object_index);
1904 if (oid_object_info_extended(the_repository, &entry->idx.oid, &oi,
1905 OBJECT_INFO_SKIP_FETCH_OBJECT | OBJECT_INFO_LOOKUP_REPLACE) < 0)
1906 type = -1;
1907 } else {
1908 type = -1;
1911 oe_set_type(entry, type);
1912 if (entry->type_valid) {
1913 SET_SIZE(entry, canonical_size);
1914 } else {
1916 * Bad object type is checked in prepare_pack(). This is
1917 * to permit a missing preferred base object to be ignored
1918 * as a preferred base. Doing so can result in a larger
1919 * pack file, but the transfer will still take place.
1924 static int pack_offset_sort(const void *_a, const void *_b)
1926 const struct object_entry *a = *(struct object_entry **)_a;
1927 const struct object_entry *b = *(struct object_entry **)_b;
1928 const struct packed_git *a_in_pack = IN_PACK(a);
1929 const struct packed_git *b_in_pack = IN_PACK(b);
1931 /* avoid filesystem trashing with loose objects */
1932 if (!a_in_pack && !b_in_pack)
1933 return oidcmp(&a->idx.oid, &b->idx.oid);
1935 if (a_in_pack < b_in_pack)
1936 return -1;
1937 if (a_in_pack > b_in_pack)
1938 return 1;
1939 return a->in_pack_offset < b->in_pack_offset ? -1 :
1940 (a->in_pack_offset > b->in_pack_offset);
1944 * Drop an on-disk delta we were planning to reuse. Naively, this would
1945 * just involve blanking out the "delta" field, but we have to deal
1946 * with some extra book-keeping:
1948 * 1. Removing ourselves from the delta_sibling linked list.
1950 * 2. Updating our size/type to the non-delta representation. These were
1951 * either not recorded initially (size) or overwritten with the delta type
1952 * (type) when check_object() decided to reuse the delta.
1954 * 3. Resetting our delta depth, as we are now a base object.
1956 static void drop_reused_delta(struct object_entry *entry)
1958 unsigned *idx = &to_pack.objects[entry->delta_idx - 1].delta_child_idx;
1959 struct object_info oi = OBJECT_INFO_INIT;
1960 enum object_type type;
1961 unsigned long size;
1963 while (*idx) {
1964 struct object_entry *oe = &to_pack.objects[*idx - 1];
1966 if (oe == entry)
1967 *idx = oe->delta_sibling_idx;
1968 else
1969 idx = &oe->delta_sibling_idx;
1971 SET_DELTA(entry, NULL);
1972 entry->depth = 0;
1974 oi.sizep = &size;
1975 oi.typep = &type;
1976 if (packed_object_info(the_repository, IN_PACK(entry), entry->in_pack_offset, &oi) < 0) {
1978 * We failed to get the info from this pack for some reason;
1979 * fall back to oid_object_info, which may find another copy.
1980 * And if that fails, the error will be recorded in oe_type(entry)
1981 * and dealt with in prepare_pack().
1983 oe_set_type(entry,
1984 oid_object_info(the_repository, &entry->idx.oid, &size));
1985 } else {
1986 oe_set_type(entry, type);
1988 SET_SIZE(entry, size);
1992 * Follow the chain of deltas from this entry onward, throwing away any links
1993 * that cause us to hit a cycle (as determined by the DFS state flags in
1994 * the entries).
1996 * We also detect too-long reused chains that would violate our --depth
1997 * limit.
1999 static void break_delta_chains(struct object_entry *entry)
2002 * The actual depth of each object we will write is stored as an int,
2003 * as it cannot exceed our int "depth" limit. But before we break
2004 * changes based no that limit, we may potentially go as deep as the
2005 * number of objects, which is elsewhere bounded to a uint32_t.
2007 uint32_t total_depth;
2008 struct object_entry *cur, *next;
2010 for (cur = entry, total_depth = 0;
2011 cur;
2012 cur = DELTA(cur), total_depth++) {
2013 if (cur->dfs_state == DFS_DONE) {
2015 * We've already seen this object and know it isn't
2016 * part of a cycle. We do need to append its depth
2017 * to our count.
2019 total_depth += cur->depth;
2020 break;
2024 * We break cycles before looping, so an ACTIVE state (or any
2025 * other cruft which made its way into the state variable)
2026 * is a bug.
2028 if (cur->dfs_state != DFS_NONE)
2029 BUG("confusing delta dfs state in first pass: %d",
2030 cur->dfs_state);
2033 * Now we know this is the first time we've seen the object. If
2034 * it's not a delta, we're done traversing, but we'll mark it
2035 * done to save time on future traversals.
2037 if (!DELTA(cur)) {
2038 cur->dfs_state = DFS_DONE;
2039 break;
2043 * Mark ourselves as active and see if the next step causes
2044 * us to cycle to another active object. It's important to do
2045 * this _before_ we loop, because it impacts where we make the
2046 * cut, and thus how our total_depth counter works.
2047 * E.g., We may see a partial loop like:
2049 * A -> B -> C -> D -> B
2051 * Cutting B->C breaks the cycle. But now the depth of A is
2052 * only 1, and our total_depth counter is at 3. The size of the
2053 * error is always one less than the size of the cycle we
2054 * broke. Commits C and D were "lost" from A's chain.
2056 * If we instead cut D->B, then the depth of A is correct at 3.
2057 * We keep all commits in the chain that we examined.
2059 cur->dfs_state = DFS_ACTIVE;
2060 if (DELTA(cur)->dfs_state == DFS_ACTIVE) {
2061 drop_reused_delta(cur);
2062 cur->dfs_state = DFS_DONE;
2063 break;
2068 * And now that we've gone all the way to the bottom of the chain, we
2069 * need to clear the active flags and set the depth fields as
2070 * appropriate. Unlike the loop above, which can quit when it drops a
2071 * delta, we need to keep going to look for more depth cuts. So we need
2072 * an extra "next" pointer to keep going after we reset cur->delta.
2074 for (cur = entry; cur; cur = next) {
2075 next = DELTA(cur);
2078 * We should have a chain of zero or more ACTIVE states down to
2079 * a final DONE. We can quit after the DONE, because either it
2080 * has no bases, or we've already handled them in a previous
2081 * call.
2083 if (cur->dfs_state == DFS_DONE)
2084 break;
2085 else if (cur->dfs_state != DFS_ACTIVE)
2086 BUG("confusing delta dfs state in second pass: %d",
2087 cur->dfs_state);
2090 * If the total_depth is more than depth, then we need to snip
2091 * the chain into two or more smaller chains that don't exceed
2092 * the maximum depth. Most of the resulting chains will contain
2093 * (depth + 1) entries (i.e., depth deltas plus one base), and
2094 * the last chain (i.e., the one containing entry) will contain
2095 * whatever entries are left over, namely
2096 * (total_depth % (depth + 1)) of them.
2098 * Since we are iterating towards decreasing depth, we need to
2099 * decrement total_depth as we go, and we need to write to the
2100 * entry what its final depth will be after all of the
2101 * snipping. Since we're snipping into chains of length (depth
2102 * + 1) entries, the final depth of an entry will be its
2103 * original depth modulo (depth + 1). Any time we encounter an
2104 * entry whose final depth is supposed to be zero, we snip it
2105 * from its delta base, thereby making it so.
2107 cur->depth = (total_depth--) % (depth + 1);
2108 if (!cur->depth)
2109 drop_reused_delta(cur);
2111 cur->dfs_state = DFS_DONE;
2115 static void get_object_details(void)
2117 uint32_t i;
2118 struct object_entry **sorted_by_offset;
2120 if (progress)
2121 progress_state = start_progress(_("Counting objects"),
2122 to_pack.nr_objects);
2124 CALLOC_ARRAY(sorted_by_offset, to_pack.nr_objects);
2125 for (i = 0; i < to_pack.nr_objects; i++)
2126 sorted_by_offset[i] = to_pack.objects + i;
2127 QSORT(sorted_by_offset, to_pack.nr_objects, pack_offset_sort);
2129 for (i = 0; i < to_pack.nr_objects; i++) {
2130 struct object_entry *entry = sorted_by_offset[i];
2131 check_object(entry, i);
2132 if (entry->type_valid &&
2133 oe_size_greater_than(&to_pack, entry, big_file_threshold))
2134 entry->no_try_delta = 1;
2135 display_progress(progress_state, i + 1);
2137 stop_progress(&progress_state);
2140 * This must happen in a second pass, since we rely on the delta
2141 * information for the whole list being completed.
2143 for (i = 0; i < to_pack.nr_objects; i++)
2144 break_delta_chains(&to_pack.objects[i]);
2146 free(sorted_by_offset);
2150 * We search for deltas in a list sorted by type, by filename hash, and then
2151 * by size, so that we see progressively smaller and smaller files.
2152 * That's because we prefer deltas to be from the bigger file
2153 * to the smaller -- deletes are potentially cheaper, but perhaps
2154 * more importantly, the bigger file is likely the more recent
2155 * one. The deepest deltas are therefore the oldest objects which are
2156 * less susceptible to be accessed often.
2158 static int type_size_sort(const void *_a, const void *_b)
2160 const struct object_entry *a = *(struct object_entry **)_a;
2161 const struct object_entry *b = *(struct object_entry **)_b;
2162 const enum object_type a_type = oe_type(a);
2163 const enum object_type b_type = oe_type(b);
2164 const unsigned long a_size = SIZE(a);
2165 const unsigned long b_size = SIZE(b);
2167 if (a_type > b_type)
2168 return -1;
2169 if (a_type < b_type)
2170 return 1;
2171 if (a->hash > b->hash)
2172 return -1;
2173 if (a->hash < b->hash)
2174 return 1;
2175 if (a->preferred_base > b->preferred_base)
2176 return -1;
2177 if (a->preferred_base < b->preferred_base)
2178 return 1;
2179 if (use_delta_islands) {
2180 const int island_cmp = island_delta_cmp(&a->idx.oid, &b->idx.oid);
2181 if (island_cmp)
2182 return island_cmp;
2184 if (a_size > b_size)
2185 return -1;
2186 if (a_size < b_size)
2187 return 1;
2188 return a < b ? -1 : (a > b); /* newest first */
2191 struct unpacked {
2192 struct object_entry *entry;
2193 void *data;
2194 struct delta_index *index;
2195 unsigned depth;
2198 static int delta_cacheable(unsigned long src_size, unsigned long trg_size,
2199 unsigned long delta_size)
2201 if (max_delta_cache_size && delta_cache_size + delta_size > max_delta_cache_size)
2202 return 0;
2204 if (delta_size < cache_max_small_delta_size)
2205 return 1;
2207 /* cache delta, if objects are large enough compared to delta size */
2208 if ((src_size >> 20) + (trg_size >> 21) > (delta_size >> 10))
2209 return 1;
2211 return 0;
2214 /* Protect delta_cache_size */
2215 static pthread_mutex_t cache_mutex;
2216 #define cache_lock() pthread_mutex_lock(&cache_mutex)
2217 #define cache_unlock() pthread_mutex_unlock(&cache_mutex)
2220 * Protect object list partitioning (e.g. struct thread_param) and
2221 * progress_state
2223 static pthread_mutex_t progress_mutex;
2224 #define progress_lock() pthread_mutex_lock(&progress_mutex)
2225 #define progress_unlock() pthread_mutex_unlock(&progress_mutex)
2228 * Access to struct object_entry is unprotected since each thread owns
2229 * a portion of the main object list. Just don't access object entries
2230 * ahead in the list because they can be stolen and would need
2231 * progress_mutex for protection.
2235 * Return the size of the object without doing any delta
2236 * reconstruction (so non-deltas are true object sizes, but deltas
2237 * return the size of the delta data).
2239 unsigned long oe_get_size_slow(struct packing_data *pack,
2240 const struct object_entry *e)
2242 struct packed_git *p;
2243 struct pack_window *w_curs;
2244 unsigned char *buf;
2245 enum object_type type;
2246 unsigned long used, avail, size;
2248 if (e->type_ != OBJ_OFS_DELTA && e->type_ != OBJ_REF_DELTA) {
2249 packing_data_lock(&to_pack);
2250 if (oid_object_info(the_repository, &e->idx.oid, &size) < 0)
2251 die(_("unable to get size of %s"),
2252 oid_to_hex(&e->idx.oid));
2253 packing_data_unlock(&to_pack);
2254 return size;
2257 p = oe_in_pack(pack, e);
2258 if (!p)
2259 BUG("when e->type is a delta, it must belong to a pack");
2261 packing_data_lock(&to_pack);
2262 w_curs = NULL;
2263 buf = use_pack(p, &w_curs, e->in_pack_offset, &avail);
2264 used = unpack_object_header_buffer(buf, avail, &type, &size);
2265 if (used == 0)
2266 die(_("unable to parse object header of %s"),
2267 oid_to_hex(&e->idx.oid));
2269 unuse_pack(&w_curs);
2270 packing_data_unlock(&to_pack);
2271 return size;
2274 static int try_delta(struct unpacked *trg, struct unpacked *src,
2275 unsigned max_depth, unsigned long *mem_usage)
2277 struct object_entry *trg_entry = trg->entry;
2278 struct object_entry *src_entry = src->entry;
2279 unsigned long trg_size, src_size, delta_size, sizediff, max_size, sz;
2280 unsigned ref_depth;
2281 enum object_type type;
2282 void *delta_buf;
2284 /* Don't bother doing diffs between different types */
2285 if (oe_type(trg_entry) != oe_type(src_entry))
2286 return -1;
2289 * We do not bother to try a delta that we discarded on an
2290 * earlier try, but only when reusing delta data. Note that
2291 * src_entry that is marked as the preferred_base should always
2292 * be considered, as even if we produce a suboptimal delta against
2293 * it, we will still save the transfer cost, as we already know
2294 * the other side has it and we won't send src_entry at all.
2296 if (reuse_delta && IN_PACK(trg_entry) &&
2297 IN_PACK(trg_entry) == IN_PACK(src_entry) &&
2298 !src_entry->preferred_base &&
2299 trg_entry->in_pack_type != OBJ_REF_DELTA &&
2300 trg_entry->in_pack_type != OBJ_OFS_DELTA)
2301 return 0;
2303 /* Let's not bust the allowed depth. */
2304 if (src->depth >= max_depth)
2305 return 0;
2307 /* Now some size filtering heuristics. */
2308 trg_size = SIZE(trg_entry);
2309 if (!DELTA(trg_entry)) {
2310 max_size = trg_size/2 - the_hash_algo->rawsz;
2311 ref_depth = 1;
2312 } else {
2313 max_size = DELTA_SIZE(trg_entry);
2314 ref_depth = trg->depth;
2316 max_size = (uint64_t)max_size * (max_depth - src->depth) /
2317 (max_depth - ref_depth + 1);
2318 if (max_size == 0)
2319 return 0;
2320 src_size = SIZE(src_entry);
2321 sizediff = src_size < trg_size ? trg_size - src_size : 0;
2322 if (sizediff >= max_size)
2323 return 0;
2324 if (trg_size < src_size / 32)
2325 return 0;
2327 if (!in_same_island(&trg->entry->idx.oid, &src->entry->idx.oid))
2328 return 0;
2330 /* Load data if not already done */
2331 if (!trg->data) {
2332 packing_data_lock(&to_pack);
2333 trg->data = read_object_file(&trg_entry->idx.oid, &type, &sz);
2334 packing_data_unlock(&to_pack);
2335 if (!trg->data)
2336 die(_("object %s cannot be read"),
2337 oid_to_hex(&trg_entry->idx.oid));
2338 if (sz != trg_size)
2339 die(_("object %s inconsistent object length (%"PRIuMAX" vs %"PRIuMAX")"),
2340 oid_to_hex(&trg_entry->idx.oid), (uintmax_t)sz,
2341 (uintmax_t)trg_size);
2342 *mem_usage += sz;
2344 if (!src->data) {
2345 packing_data_lock(&to_pack);
2346 src->data = read_object_file(&src_entry->idx.oid, &type, &sz);
2347 packing_data_unlock(&to_pack);
2348 if (!src->data) {
2349 if (src_entry->preferred_base) {
2350 static int warned = 0;
2351 if (!warned++)
2352 warning(_("object %s cannot be read"),
2353 oid_to_hex(&src_entry->idx.oid));
2355 * Those objects are not included in the
2356 * resulting pack. Be resilient and ignore
2357 * them if they can't be read, in case the
2358 * pack could be created nevertheless.
2360 return 0;
2362 die(_("object %s cannot be read"),
2363 oid_to_hex(&src_entry->idx.oid));
2365 if (sz != src_size)
2366 die(_("object %s inconsistent object length (%"PRIuMAX" vs %"PRIuMAX")"),
2367 oid_to_hex(&src_entry->idx.oid), (uintmax_t)sz,
2368 (uintmax_t)src_size);
2369 *mem_usage += sz;
2371 if (!src->index) {
2372 src->index = create_delta_index(src->data, src_size);
2373 if (!src->index) {
2374 static int warned = 0;
2375 if (!warned++)
2376 warning(_("suboptimal pack - out of memory"));
2377 return 0;
2379 *mem_usage += sizeof_delta_index(src->index);
2382 delta_buf = create_delta(src->index, trg->data, trg_size, &delta_size, max_size);
2383 if (!delta_buf)
2384 return 0;
2386 if (DELTA(trg_entry)) {
2387 /* Prefer only shallower same-sized deltas. */
2388 if (delta_size == DELTA_SIZE(trg_entry) &&
2389 src->depth + 1 >= trg->depth) {
2390 free(delta_buf);
2391 return 0;
2396 * Handle memory allocation outside of the cache
2397 * accounting lock. Compiler will optimize the strangeness
2398 * away when NO_PTHREADS is defined.
2400 free(trg_entry->delta_data);
2401 cache_lock();
2402 if (trg_entry->delta_data) {
2403 delta_cache_size -= DELTA_SIZE(trg_entry);
2404 trg_entry->delta_data = NULL;
2406 if (delta_cacheable(src_size, trg_size, delta_size)) {
2407 delta_cache_size += delta_size;
2408 cache_unlock();
2409 trg_entry->delta_data = xrealloc(delta_buf, delta_size);
2410 } else {
2411 cache_unlock();
2412 free(delta_buf);
2415 SET_DELTA(trg_entry, src_entry);
2416 SET_DELTA_SIZE(trg_entry, delta_size);
2417 trg->depth = src->depth + 1;
2419 return 1;
2422 static unsigned int check_delta_limit(struct object_entry *me, unsigned int n)
2424 struct object_entry *child = DELTA_CHILD(me);
2425 unsigned int m = n;
2426 while (child) {
2427 const unsigned int c = check_delta_limit(child, n + 1);
2428 if (m < c)
2429 m = c;
2430 child = DELTA_SIBLING(child);
2432 return m;
2435 static unsigned long free_unpacked(struct unpacked *n)
2437 unsigned long freed_mem = sizeof_delta_index(n->index);
2438 free_delta_index(n->index);
2439 n->index = NULL;
2440 if (n->data) {
2441 freed_mem += SIZE(n->entry);
2442 FREE_AND_NULL(n->data);
2444 n->entry = NULL;
2445 n->depth = 0;
2446 return freed_mem;
2449 static void find_deltas(struct object_entry **list, unsigned *list_size,
2450 int window, int depth, unsigned *processed)
2452 uint32_t i, idx = 0, count = 0;
2453 struct unpacked *array;
2454 unsigned long mem_usage = 0;
2456 CALLOC_ARRAY(array, window);
2458 for (;;) {
2459 struct object_entry *entry;
2460 struct unpacked *n = array + idx;
2461 int j, max_depth, best_base = -1;
2463 progress_lock();
2464 if (!*list_size) {
2465 progress_unlock();
2466 break;
2468 entry = *list++;
2469 (*list_size)--;
2470 if (!entry->preferred_base) {
2471 (*processed)++;
2472 display_progress(progress_state, *processed);
2474 progress_unlock();
2476 mem_usage -= free_unpacked(n);
2477 n->entry = entry;
2479 while (window_memory_limit &&
2480 mem_usage > window_memory_limit &&
2481 count > 1) {
2482 const uint32_t tail = (idx + window - count) % window;
2483 mem_usage -= free_unpacked(array + tail);
2484 count--;
2487 /* We do not compute delta to *create* objects we are not
2488 * going to pack.
2490 if (entry->preferred_base)
2491 goto next;
2494 * If the current object is at pack edge, take the depth the
2495 * objects that depend on the current object into account
2496 * otherwise they would become too deep.
2498 max_depth = depth;
2499 if (DELTA_CHILD(entry)) {
2500 max_depth -= check_delta_limit(entry, 0);
2501 if (max_depth <= 0)
2502 goto next;
2505 j = window;
2506 while (--j > 0) {
2507 int ret;
2508 uint32_t other_idx = idx + j;
2509 struct unpacked *m;
2510 if (other_idx >= window)
2511 other_idx -= window;
2512 m = array + other_idx;
2513 if (!m->entry)
2514 break;
2515 ret = try_delta(n, m, max_depth, &mem_usage);
2516 if (ret < 0)
2517 break;
2518 else if (ret > 0)
2519 best_base = other_idx;
2523 * If we decided to cache the delta data, then it is best
2524 * to compress it right away. First because we have to do
2525 * it anyway, and doing it here while we're threaded will
2526 * save a lot of time in the non threaded write phase,
2527 * as well as allow for caching more deltas within
2528 * the same cache size limit.
2529 * ...
2530 * But only if not writing to stdout, since in that case
2531 * the network is most likely throttling writes anyway,
2532 * and therefore it is best to go to the write phase ASAP
2533 * instead, as we can afford spending more time compressing
2534 * between writes at that moment.
2536 if (entry->delta_data && !pack_to_stdout) {
2537 unsigned long size;
2539 size = do_compress(&entry->delta_data, DELTA_SIZE(entry));
2540 if (size < (1U << OE_Z_DELTA_BITS)) {
2541 entry->z_delta_size = size;
2542 cache_lock();
2543 delta_cache_size -= DELTA_SIZE(entry);
2544 delta_cache_size += entry->z_delta_size;
2545 cache_unlock();
2546 } else {
2547 FREE_AND_NULL(entry->delta_data);
2548 entry->z_delta_size = 0;
2552 /* if we made n a delta, and if n is already at max
2553 * depth, leaving it in the window is pointless. we
2554 * should evict it first.
2556 if (DELTA(entry) && max_depth <= n->depth)
2557 continue;
2560 * Move the best delta base up in the window, after the
2561 * currently deltified object, to keep it longer. It will
2562 * be the first base object to be attempted next.
2564 if (DELTA(entry)) {
2565 struct unpacked swap = array[best_base];
2566 int dist = (window + idx - best_base) % window;
2567 int dst = best_base;
2568 while (dist--) {
2569 int src = (dst + 1) % window;
2570 array[dst] = array[src];
2571 dst = src;
2573 array[dst] = swap;
2576 next:
2577 idx++;
2578 if (count + 1 < window)
2579 count++;
2580 if (idx >= window)
2581 idx = 0;
2584 for (i = 0; i < window; ++i) {
2585 free_delta_index(array[i].index);
2586 free(array[i].data);
2588 free(array);
2592 * The main object list is split into smaller lists, each is handed to
2593 * one worker.
2595 * The main thread waits on the condition that (at least) one of the workers
2596 * has stopped working (which is indicated in the .working member of
2597 * struct thread_params).
2599 * When a work thread has completed its work, it sets .working to 0 and
2600 * signals the main thread and waits on the condition that .data_ready
2601 * becomes 1.
2603 * The main thread steals half of the work from the worker that has
2604 * most work left to hand it to the idle worker.
2607 struct thread_params {
2608 pthread_t thread;
2609 struct object_entry **list;
2610 unsigned list_size;
2611 unsigned remaining;
2612 int window;
2613 int depth;
2614 int working;
2615 int data_ready;
2616 pthread_mutex_t mutex;
2617 pthread_cond_t cond;
2618 unsigned *processed;
2621 static pthread_cond_t progress_cond;
2624 * Mutex and conditional variable can't be statically-initialized on Windows.
2626 static void init_threaded_search(void)
2628 pthread_mutex_init(&cache_mutex, NULL);
2629 pthread_mutex_init(&progress_mutex, NULL);
2630 pthread_cond_init(&progress_cond, NULL);
2633 static void cleanup_threaded_search(void)
2635 pthread_cond_destroy(&progress_cond);
2636 pthread_mutex_destroy(&cache_mutex);
2637 pthread_mutex_destroy(&progress_mutex);
2640 static void *threaded_find_deltas(void *arg)
2642 struct thread_params *me = arg;
2644 progress_lock();
2645 while (me->remaining) {
2646 progress_unlock();
2648 find_deltas(me->list, &me->remaining,
2649 me->window, me->depth, me->processed);
2651 progress_lock();
2652 me->working = 0;
2653 pthread_cond_signal(&progress_cond);
2654 progress_unlock();
2657 * We must not set ->data_ready before we wait on the
2658 * condition because the main thread may have set it to 1
2659 * before we get here. In order to be sure that new
2660 * work is available if we see 1 in ->data_ready, it
2661 * was initialized to 0 before this thread was spawned
2662 * and we reset it to 0 right away.
2664 pthread_mutex_lock(&me->mutex);
2665 while (!me->data_ready)
2666 pthread_cond_wait(&me->cond, &me->mutex);
2667 me->data_ready = 0;
2668 pthread_mutex_unlock(&me->mutex);
2670 progress_lock();
2672 progress_unlock();
2673 /* leave ->working 1 so that this doesn't get more work assigned */
2674 return NULL;
2677 static void ll_find_deltas(struct object_entry **list, unsigned list_size,
2678 int window, int depth, unsigned *processed)
2680 struct thread_params *p;
2681 int i, ret, active_threads = 0;
2683 init_threaded_search();
2685 if (delta_search_threads <= 1) {
2686 find_deltas(list, &list_size, window, depth, processed);
2687 cleanup_threaded_search();
2688 return;
2690 if (progress > pack_to_stdout)
2691 fprintf_ln(stderr, _("Delta compression using up to %d threads"),
2692 delta_search_threads);
2693 CALLOC_ARRAY(p, delta_search_threads);
2695 /* Partition the work amongst work threads. */
2696 for (i = 0; i < delta_search_threads; i++) {
2697 unsigned sub_size = list_size / (delta_search_threads - i);
2699 /* don't use too small segments or no deltas will be found */
2700 if (sub_size < 2*window && i+1 < delta_search_threads)
2701 sub_size = 0;
2703 p[i].window = window;
2704 p[i].depth = depth;
2705 p[i].processed = processed;
2706 p[i].working = 1;
2707 p[i].data_ready = 0;
2709 /* try to split chunks on "path" boundaries */
2710 while (sub_size && sub_size < list_size &&
2711 list[sub_size]->hash &&
2712 list[sub_size]->hash == list[sub_size-1]->hash)
2713 sub_size++;
2715 p[i].list = list;
2716 p[i].list_size = sub_size;
2717 p[i].remaining = sub_size;
2719 list += sub_size;
2720 list_size -= sub_size;
2723 /* Start work threads. */
2724 for (i = 0; i < delta_search_threads; i++) {
2725 if (!p[i].list_size)
2726 continue;
2727 pthread_mutex_init(&p[i].mutex, NULL);
2728 pthread_cond_init(&p[i].cond, NULL);
2729 ret = pthread_create(&p[i].thread, NULL,
2730 threaded_find_deltas, &p[i]);
2731 if (ret)
2732 die(_("unable to create thread: %s"), strerror(ret));
2733 active_threads++;
2737 * Now let's wait for work completion. Each time a thread is done
2738 * with its work, we steal half of the remaining work from the
2739 * thread with the largest number of unprocessed objects and give
2740 * it to that newly idle thread. This ensure good load balancing
2741 * until the remaining object list segments are simply too short
2742 * to be worth splitting anymore.
2744 while (active_threads) {
2745 struct thread_params *target = NULL;
2746 struct thread_params *victim = NULL;
2747 unsigned sub_size = 0;
2749 progress_lock();
2750 for (;;) {
2751 for (i = 0; !target && i < delta_search_threads; i++)
2752 if (!p[i].working)
2753 target = &p[i];
2754 if (target)
2755 break;
2756 pthread_cond_wait(&progress_cond, &progress_mutex);
2759 for (i = 0; i < delta_search_threads; i++)
2760 if (p[i].remaining > 2*window &&
2761 (!victim || victim->remaining < p[i].remaining))
2762 victim = &p[i];
2763 if (victim) {
2764 sub_size = victim->remaining / 2;
2765 list = victim->list + victim->list_size - sub_size;
2766 while (sub_size && list[0]->hash &&
2767 list[0]->hash == list[-1]->hash) {
2768 list++;
2769 sub_size--;
2771 if (!sub_size) {
2773 * It is possible for some "paths" to have
2774 * so many objects that no hash boundary
2775 * might be found. Let's just steal the
2776 * exact half in that case.
2778 sub_size = victim->remaining / 2;
2779 list -= sub_size;
2781 target->list = list;
2782 victim->list_size -= sub_size;
2783 victim->remaining -= sub_size;
2785 target->list_size = sub_size;
2786 target->remaining = sub_size;
2787 target->working = 1;
2788 progress_unlock();
2790 pthread_mutex_lock(&target->mutex);
2791 target->data_ready = 1;
2792 pthread_cond_signal(&target->cond);
2793 pthread_mutex_unlock(&target->mutex);
2795 if (!sub_size) {
2796 pthread_join(target->thread, NULL);
2797 pthread_cond_destroy(&target->cond);
2798 pthread_mutex_destroy(&target->mutex);
2799 active_threads--;
2802 cleanup_threaded_search();
2803 free(p);
2806 static int obj_is_packed(const struct object_id *oid)
2808 return packlist_find(&to_pack, oid) ||
2809 (reuse_packfile_bitmap &&
2810 bitmap_walk_contains(bitmap_git, reuse_packfile_bitmap, oid));
2813 static void add_tag_chain(const struct object_id *oid)
2815 struct tag *tag;
2818 * We catch duplicates already in add_object_entry(), but we'd
2819 * prefer to do this extra check to avoid having to parse the
2820 * tag at all if we already know that it's being packed (e.g., if
2821 * it was included via bitmaps, we would not have parsed it
2822 * previously).
2824 if (obj_is_packed(oid))
2825 return;
2827 tag = lookup_tag(the_repository, oid);
2828 while (1) {
2829 if (!tag || parse_tag(tag) || !tag->tagged)
2830 die(_("unable to pack objects reachable from tag %s"),
2831 oid_to_hex(oid));
2833 add_object_entry(&tag->object.oid, OBJ_TAG, NULL, 0);
2835 if (tag->tagged->type != OBJ_TAG)
2836 return;
2838 tag = (struct tag *)tag->tagged;
2842 static int add_ref_tag(const char *tag, const struct object_id *oid, int flag, void *cb_data)
2844 struct object_id peeled;
2846 if (!peel_iterated_oid(oid, &peeled) && obj_is_packed(&peeled))
2847 add_tag_chain(oid);
2848 return 0;
2851 static void prepare_pack(int window, int depth)
2853 struct object_entry **delta_list;
2854 uint32_t i, nr_deltas;
2855 unsigned n;
2857 if (use_delta_islands)
2858 resolve_tree_islands(the_repository, progress, &to_pack);
2860 get_object_details();
2863 * If we're locally repacking then we need to be doubly careful
2864 * from now on in order to make sure no stealth corruption gets
2865 * propagated to the new pack. Clients receiving streamed packs
2866 * should validate everything they get anyway so no need to incur
2867 * the additional cost here in that case.
2869 if (!pack_to_stdout)
2870 do_check_packed_object_crc = 1;
2872 if (!to_pack.nr_objects || !window || !depth)
2873 return;
2875 ALLOC_ARRAY(delta_list, to_pack.nr_objects);
2876 nr_deltas = n = 0;
2878 for (i = 0; i < to_pack.nr_objects; i++) {
2879 struct object_entry *entry = to_pack.objects + i;
2881 if (DELTA(entry))
2882 /* This happens if we decided to reuse existing
2883 * delta from a pack. "reuse_delta &&" is implied.
2885 continue;
2887 if (!entry->type_valid ||
2888 oe_size_less_than(&to_pack, entry, 50))
2889 continue;
2891 if (entry->no_try_delta)
2892 continue;
2894 if (!entry->preferred_base) {
2895 nr_deltas++;
2896 if (oe_type(entry) < 0)
2897 die(_("unable to get type of object %s"),
2898 oid_to_hex(&entry->idx.oid));
2899 } else {
2900 if (oe_type(entry) < 0) {
2902 * This object is not found, but we
2903 * don't have to include it anyway.
2905 continue;
2909 delta_list[n++] = entry;
2912 if (nr_deltas && n > 1) {
2913 unsigned nr_done = 0;
2915 if (progress)
2916 progress_state = start_progress(_("Compressing objects"),
2917 nr_deltas);
2918 QSORT(delta_list, n, type_size_sort);
2919 ll_find_deltas(delta_list, n, window+1, depth, &nr_done);
2920 stop_progress(&progress_state);
2921 if (nr_done != nr_deltas)
2922 die(_("inconsistency with delta count"));
2924 free(delta_list);
2927 static int git_pack_config(const char *k, const char *v, void *cb)
2929 if (!strcmp(k, "pack.window")) {
2930 window = git_config_int(k, v);
2931 return 0;
2933 if (!strcmp(k, "pack.windowmemory")) {
2934 window_memory_limit = git_config_ulong(k, v);
2935 return 0;
2937 if (!strcmp(k, "pack.depth")) {
2938 depth = git_config_int(k, v);
2939 return 0;
2941 if (!strcmp(k, "pack.deltacachesize")) {
2942 max_delta_cache_size = git_config_int(k, v);
2943 return 0;
2945 if (!strcmp(k, "pack.deltacachelimit")) {
2946 cache_max_small_delta_size = git_config_int(k, v);
2947 return 0;
2949 if (!strcmp(k, "pack.writebitmaphashcache")) {
2950 if (git_config_bool(k, v))
2951 write_bitmap_options |= BITMAP_OPT_HASH_CACHE;
2952 else
2953 write_bitmap_options &= ~BITMAP_OPT_HASH_CACHE;
2955 if (!strcmp(k, "pack.usebitmaps")) {
2956 use_bitmap_index_default = git_config_bool(k, v);
2957 return 0;
2959 if (!strcmp(k, "pack.allowpackreuse")) {
2960 allow_pack_reuse = git_config_bool(k, v);
2961 return 0;
2963 if (!strcmp(k, "pack.threads")) {
2964 delta_search_threads = git_config_int(k, v);
2965 if (delta_search_threads < 0)
2966 die(_("invalid number of threads specified (%d)"),
2967 delta_search_threads);
2968 if (!HAVE_THREADS && delta_search_threads != 1) {
2969 warning(_("no threads support, ignoring %s"), k);
2970 delta_search_threads = 0;
2972 return 0;
2974 if (!strcmp(k, "pack.indexversion")) {
2975 pack_idx_opts.version = git_config_int(k, v);
2976 if (pack_idx_opts.version > 2)
2977 die(_("bad pack.indexversion=%"PRIu32),
2978 pack_idx_opts.version);
2979 return 0;
2981 if (!strcmp(k, "pack.writereverseindex")) {
2982 if (git_config_bool(k, v))
2983 pack_idx_opts.flags |= WRITE_REV;
2984 else
2985 pack_idx_opts.flags &= ~WRITE_REV;
2986 return 0;
2988 if (!strcmp(k, "uploadpack.blobpackfileuri")) {
2989 struct configured_exclusion *ex = xmalloc(sizeof(*ex));
2990 const char *oid_end, *pack_end;
2992 * Stores the pack hash. This is not a true object ID, but is
2993 * of the same form.
2995 struct object_id pack_hash;
2997 if (parse_oid_hex(v, &ex->e.oid, &oid_end) ||
2998 *oid_end != ' ' ||
2999 parse_oid_hex(oid_end + 1, &pack_hash, &pack_end) ||
3000 *pack_end != ' ')
3001 die(_("value of uploadpack.blobpackfileuri must be "
3002 "of the form '<object-hash> <pack-hash> <uri>' (got '%s')"), v);
3003 if (oidmap_get(&configured_exclusions, &ex->e.oid))
3004 die(_("object already configured in another "
3005 "uploadpack.blobpackfileuri (got '%s')"), v);
3006 ex->pack_hash_hex = xcalloc(1, pack_end - oid_end);
3007 memcpy(ex->pack_hash_hex, oid_end + 1, pack_end - oid_end - 1);
3008 ex->uri = xstrdup(pack_end + 1);
3009 oidmap_put(&configured_exclusions, ex);
3011 return git_default_config(k, v, cb);
3014 /* Counters for trace2 output when in --stdin-packs mode. */
3015 static int stdin_packs_found_nr;
3016 static int stdin_packs_hints_nr;
3018 static int add_object_entry_from_pack(const struct object_id *oid,
3019 struct packed_git *p,
3020 uint32_t pos,
3021 void *_data)
3023 struct rev_info *revs = _data;
3024 struct object_info oi = OBJECT_INFO_INIT;
3025 off_t ofs;
3026 enum object_type type;
3028 display_progress(progress_state, ++nr_seen);
3030 if (have_duplicate_entry(oid, 0))
3031 return 0;
3033 ofs = nth_packed_object_offset(p, pos);
3034 if (!want_object_in_pack(oid, 0, &p, &ofs))
3035 return 0;
3037 oi.typep = &type;
3038 if (packed_object_info(the_repository, p, ofs, &oi) < 0)
3039 die(_("could not get type of object %s in pack %s"),
3040 oid_to_hex(oid), p->pack_name);
3041 else if (type == OBJ_COMMIT) {
3043 * commits in included packs are used as starting points for the
3044 * subsequent revision walk
3046 add_pending_oid(revs, NULL, oid, 0);
3049 stdin_packs_found_nr++;
3051 create_object_entry(oid, type, 0, 0, 0, p, ofs);
3053 return 0;
3056 static void show_commit_pack_hint(struct commit *commit, void *_data)
3058 /* nothing to do; commits don't have a namehash */
3061 static void show_object_pack_hint(struct object *object, const char *name,
3062 void *_data)
3064 struct object_entry *oe = packlist_find(&to_pack, &object->oid);
3065 if (!oe)
3066 return;
3069 * Our 'to_pack' list was constructed by iterating all objects packed in
3070 * included packs, and so doesn't have a non-zero hash field that you
3071 * would typically pick up during a reachability traversal.
3073 * Make a best-effort attempt to fill in the ->hash and ->no_try_delta
3074 * here using a now in order to perhaps improve the delta selection
3075 * process.
3077 oe->hash = pack_name_hash(name);
3078 oe->no_try_delta = name && no_try_delta(name);
3080 stdin_packs_hints_nr++;
3083 static int pack_mtime_cmp(const void *_a, const void *_b)
3085 struct packed_git *a = ((const struct string_list_item*)_a)->util;
3086 struct packed_git *b = ((const struct string_list_item*)_b)->util;
3089 * order packs by descending mtime so that objects are laid out
3090 * roughly as newest-to-oldest
3092 if (a->mtime < b->mtime)
3093 return 1;
3094 else if (b->mtime < a->mtime)
3095 return -1;
3096 else
3097 return 0;
3100 static void read_packs_list_from_stdin(void)
3102 struct strbuf buf = STRBUF_INIT;
3103 struct string_list include_packs = STRING_LIST_INIT_DUP;
3104 struct string_list exclude_packs = STRING_LIST_INIT_DUP;
3105 struct string_list_item *item = NULL;
3107 struct packed_git *p;
3108 struct rev_info revs;
3110 repo_init_revisions(the_repository, &revs, NULL);
3112 * Use a revision walk to fill in the namehash of objects in the include
3113 * packs. To save time, we'll avoid traversing through objects that are
3114 * in excluded packs.
3116 * That may cause us to avoid populating all of the namehash fields of
3117 * all included objects, but our goal is best-effort, since this is only
3118 * an optimization during delta selection.
3120 revs.no_kept_objects = 1;
3121 revs.keep_pack_cache_flags |= IN_CORE_KEEP_PACKS;
3122 revs.blob_objects = 1;
3123 revs.tree_objects = 1;
3124 revs.tag_objects = 1;
3125 revs.ignore_missing_links = 1;
3127 while (strbuf_getline(&buf, stdin) != EOF) {
3128 if (!buf.len)
3129 continue;
3131 if (*buf.buf == '^')
3132 string_list_append(&exclude_packs, buf.buf + 1);
3133 else
3134 string_list_append(&include_packs, buf.buf);
3136 strbuf_reset(&buf);
3139 string_list_sort(&include_packs);
3140 string_list_sort(&exclude_packs);
3142 for (p = get_all_packs(the_repository); p; p = p->next) {
3143 const char *pack_name = pack_basename(p);
3145 item = string_list_lookup(&include_packs, pack_name);
3146 if (!item)
3147 item = string_list_lookup(&exclude_packs, pack_name);
3149 if (item)
3150 item->util = p;
3154 * First handle all of the excluded packs, marking them as kept in-core
3155 * so that later calls to add_object_entry() discards any objects that
3156 * are also found in excluded packs.
3158 for_each_string_list_item(item, &exclude_packs) {
3159 struct packed_git *p = item->util;
3160 if (!p)
3161 die(_("could not find pack '%s'"), item->string);
3162 p->pack_keep_in_core = 1;
3166 * Order packs by ascending mtime; use QSORT directly to access the
3167 * string_list_item's ->util pointer, which string_list_sort() does not
3168 * provide.
3170 QSORT(include_packs.items, include_packs.nr, pack_mtime_cmp);
3172 for_each_string_list_item(item, &include_packs) {
3173 struct packed_git *p = item->util;
3174 if (!p)
3175 die(_("could not find pack '%s'"), item->string);
3176 for_each_object_in_pack(p,
3177 add_object_entry_from_pack,
3178 &revs,
3179 FOR_EACH_OBJECT_PACK_ORDER);
3182 if (prepare_revision_walk(&revs))
3183 die(_("revision walk setup failed"));
3184 traverse_commit_list(&revs,
3185 show_commit_pack_hint,
3186 show_object_pack_hint,
3187 NULL);
3189 trace2_data_intmax("pack-objects", the_repository, "stdin_packs_found",
3190 stdin_packs_found_nr);
3191 trace2_data_intmax("pack-objects", the_repository, "stdin_packs_hints",
3192 stdin_packs_hints_nr);
3194 strbuf_release(&buf);
3195 string_list_clear(&include_packs, 0);
3196 string_list_clear(&exclude_packs, 0);
3199 static void read_object_list_from_stdin(void)
3201 char line[GIT_MAX_HEXSZ + 1 + PATH_MAX + 2];
3202 struct object_id oid;
3203 const char *p;
3205 for (;;) {
3206 if (!fgets(line, sizeof(line), stdin)) {
3207 if (feof(stdin))
3208 break;
3209 if (!ferror(stdin))
3210 die("BUG: fgets returned NULL, not EOF, not error!");
3211 if (errno != EINTR)
3212 die_errno("fgets");
3213 clearerr(stdin);
3214 continue;
3216 if (line[0] == '-') {
3217 if (get_oid_hex(line+1, &oid))
3218 die(_("expected edge object ID, got garbage:\n %s"),
3219 line);
3220 add_preferred_base(&oid);
3221 continue;
3223 if (parse_oid_hex(line, &oid, &p))
3224 die(_("expected object ID, got garbage:\n %s"), line);
3226 add_preferred_base_object(p + 1);
3227 add_object_entry(&oid, OBJ_NONE, p + 1, 0);
3231 /* Remember to update object flag allocation in object.h */
3232 #define OBJECT_ADDED (1u<<20)
3234 static void show_commit(struct commit *commit, void *data)
3236 add_object_entry(&commit->object.oid, OBJ_COMMIT, NULL, 0);
3237 commit->object.flags |= OBJECT_ADDED;
3239 if (write_bitmap_index)
3240 index_commit_for_bitmap(commit);
3242 if (use_delta_islands)
3243 propagate_island_marks(commit);
3246 static void show_object(struct object *obj, const char *name, void *data)
3248 add_preferred_base_object(name);
3249 add_object_entry(&obj->oid, obj->type, name, 0);
3250 obj->flags |= OBJECT_ADDED;
3252 if (use_delta_islands) {
3253 const char *p;
3254 unsigned depth;
3255 struct object_entry *ent;
3257 /* the empty string is a root tree, which is depth 0 */
3258 depth = *name ? 1 : 0;
3259 for (p = strchr(name, '/'); p; p = strchr(p + 1, '/'))
3260 depth++;
3262 ent = packlist_find(&to_pack, &obj->oid);
3263 if (ent && depth > oe_tree_depth(&to_pack, ent))
3264 oe_set_tree_depth(&to_pack, ent, depth);
3268 static void show_object__ma_allow_any(struct object *obj, const char *name, void *data)
3270 assert(arg_missing_action == MA_ALLOW_ANY);
3273 * Quietly ignore ALL missing objects. This avoids problems with
3274 * staging them now and getting an odd error later.
3276 if (!has_object(the_repository, &obj->oid, 0))
3277 return;
3279 show_object(obj, name, data);
3282 static void show_object__ma_allow_promisor(struct object *obj, const char *name, void *data)
3284 assert(arg_missing_action == MA_ALLOW_PROMISOR);
3287 * Quietly ignore EXPECTED missing objects. This avoids problems with
3288 * staging them now and getting an odd error later.
3290 if (!has_object(the_repository, &obj->oid, 0) && is_promisor_object(&obj->oid))
3291 return;
3293 show_object(obj, name, data);
3296 static int option_parse_missing_action(const struct option *opt,
3297 const char *arg, int unset)
3299 assert(arg);
3300 assert(!unset);
3302 if (!strcmp(arg, "error")) {
3303 arg_missing_action = MA_ERROR;
3304 fn_show_object = show_object;
3305 return 0;
3308 if (!strcmp(arg, "allow-any")) {
3309 arg_missing_action = MA_ALLOW_ANY;
3310 fetch_if_missing = 0;
3311 fn_show_object = show_object__ma_allow_any;
3312 return 0;
3315 if (!strcmp(arg, "allow-promisor")) {
3316 arg_missing_action = MA_ALLOW_PROMISOR;
3317 fetch_if_missing = 0;
3318 fn_show_object = show_object__ma_allow_promisor;
3319 return 0;
3322 die(_("invalid value for --missing"));
3323 return 0;
3326 static void show_edge(struct commit *commit)
3328 add_preferred_base(&commit->object.oid);
3331 struct in_pack_object {
3332 off_t offset;
3333 struct object *object;
3336 struct in_pack {
3337 unsigned int alloc;
3338 unsigned int nr;
3339 struct in_pack_object *array;
3342 static void mark_in_pack_object(struct object *object, struct packed_git *p, struct in_pack *in_pack)
3344 in_pack->array[in_pack->nr].offset = find_pack_entry_one(object->oid.hash, p);
3345 in_pack->array[in_pack->nr].object = object;
3346 in_pack->nr++;
3350 * Compare the objects in the offset order, in order to emulate the
3351 * "git rev-list --objects" output that produced the pack originally.
3353 static int ofscmp(const void *a_, const void *b_)
3355 struct in_pack_object *a = (struct in_pack_object *)a_;
3356 struct in_pack_object *b = (struct in_pack_object *)b_;
3358 if (a->offset < b->offset)
3359 return -1;
3360 else if (a->offset > b->offset)
3361 return 1;
3362 else
3363 return oidcmp(&a->object->oid, &b->object->oid);
3366 static void add_objects_in_unpacked_packs(void)
3368 struct packed_git *p;
3369 struct in_pack in_pack;
3370 uint32_t i;
3372 memset(&in_pack, 0, sizeof(in_pack));
3374 for (p = get_all_packs(the_repository); p; p = p->next) {
3375 struct object_id oid;
3376 struct object *o;
3378 if (!p->pack_local || p->pack_keep || p->pack_keep_in_core)
3379 continue;
3380 if (open_pack_index(p))
3381 die(_("cannot open pack index"));
3383 ALLOC_GROW(in_pack.array,
3384 in_pack.nr + p->num_objects,
3385 in_pack.alloc);
3387 for (i = 0; i < p->num_objects; i++) {
3388 nth_packed_object_id(&oid, p, i);
3389 o = lookup_unknown_object(the_repository, &oid);
3390 if (!(o->flags & OBJECT_ADDED))
3391 mark_in_pack_object(o, p, &in_pack);
3392 o->flags |= OBJECT_ADDED;
3396 if (in_pack.nr) {
3397 QSORT(in_pack.array, in_pack.nr, ofscmp);
3398 for (i = 0; i < in_pack.nr; i++) {
3399 struct object *o = in_pack.array[i].object;
3400 add_object_entry(&o->oid, o->type, "", 0);
3403 free(in_pack.array);
3406 static int add_loose_object(const struct object_id *oid, const char *path,
3407 void *data)
3409 enum object_type type = oid_object_info(the_repository, oid, NULL);
3411 if (type < 0) {
3412 warning(_("loose object at %s could not be examined"), path);
3413 return 0;
3416 add_object_entry(oid, type, "", 0);
3417 return 0;
3421 * We actually don't even have to worry about reachability here.
3422 * add_object_entry will weed out duplicates, so we just add every
3423 * loose object we find.
3425 static void add_unreachable_loose_objects(void)
3427 for_each_loose_file_in_objdir(get_object_directory(),
3428 add_loose_object,
3429 NULL, NULL, NULL);
3432 static int has_sha1_pack_kept_or_nonlocal(const struct object_id *oid)
3434 static struct packed_git *last_found = (void *)1;
3435 struct packed_git *p;
3437 p = (last_found != (void *)1) ? last_found :
3438 get_all_packs(the_repository);
3440 while (p) {
3441 if ((!p->pack_local || p->pack_keep ||
3442 p->pack_keep_in_core) &&
3443 find_pack_entry_one(oid->hash, p)) {
3444 last_found = p;
3445 return 1;
3447 if (p == last_found)
3448 p = get_all_packs(the_repository);
3449 else
3450 p = p->next;
3451 if (p == last_found)
3452 p = p->next;
3454 return 0;
3458 * Store a list of sha1s that are should not be discarded
3459 * because they are either written too recently, or are
3460 * reachable from another object that was.
3462 * This is filled by get_object_list.
3464 static struct oid_array recent_objects;
3466 static int loosened_object_can_be_discarded(const struct object_id *oid,
3467 timestamp_t mtime)
3469 if (!unpack_unreachable_expiration)
3470 return 0;
3471 if (mtime > unpack_unreachable_expiration)
3472 return 0;
3473 if (oid_array_lookup(&recent_objects, oid) >= 0)
3474 return 0;
3475 return 1;
3478 static void loosen_unused_packed_objects(void)
3480 struct packed_git *p;
3481 uint32_t i;
3482 uint32_t loosened_objects_nr = 0;
3483 struct object_id oid;
3485 for (p = get_all_packs(the_repository); p; p = p->next) {
3486 if (!p->pack_local || p->pack_keep || p->pack_keep_in_core)
3487 continue;
3489 if (open_pack_index(p))
3490 die(_("cannot open pack index"));
3492 for (i = 0; i < p->num_objects; i++) {
3493 nth_packed_object_id(&oid, p, i);
3494 if (!packlist_find(&to_pack, &oid) &&
3495 !has_sha1_pack_kept_or_nonlocal(&oid) &&
3496 !loosened_object_can_be_discarded(&oid, p->mtime)) {
3497 if (force_object_loose(&oid, p->mtime))
3498 die(_("unable to force loose object"));
3499 loosened_objects_nr++;
3504 trace2_data_intmax("pack-objects", the_repository,
3505 "loosen_unused_packed_objects/loosened", loosened_objects_nr);
3509 * This tracks any options which pack-reuse code expects to be on, or which a
3510 * reader of the pack might not understand, and which would therefore prevent
3511 * blind reuse of what we have on disk.
3513 static int pack_options_allow_reuse(void)
3515 return allow_pack_reuse &&
3516 pack_to_stdout &&
3517 !ignore_packed_keep_on_disk &&
3518 !ignore_packed_keep_in_core &&
3519 (!local || !have_non_local_packs) &&
3520 !incremental;
3523 static int get_object_list_from_bitmap(struct rev_info *revs)
3525 if (!(bitmap_git = prepare_bitmap_walk(revs, &filter_options, 0)))
3526 return -1;
3528 if (pack_options_allow_reuse() &&
3529 !reuse_partial_packfile_from_bitmap(
3530 bitmap_git,
3531 &reuse_packfile,
3532 &reuse_packfile_objects,
3533 &reuse_packfile_bitmap)) {
3534 assert(reuse_packfile_objects);
3535 nr_result += reuse_packfile_objects;
3536 nr_seen += reuse_packfile_objects;
3537 display_progress(progress_state, nr_seen);
3540 traverse_bitmap_commit_list(bitmap_git, revs,
3541 &add_object_entry_from_bitmap);
3542 return 0;
3545 static void record_recent_object(struct object *obj,
3546 const char *name,
3547 void *data)
3549 oid_array_append(&recent_objects, &obj->oid);
3552 static void record_recent_commit(struct commit *commit, void *data)
3554 oid_array_append(&recent_objects, &commit->object.oid);
3557 static int mark_bitmap_preferred_tip(const char *refname,
3558 const struct object_id *oid, int flags,
3559 void *_data)
3561 struct object_id peeled;
3562 struct object *object;
3564 if (!peel_iterated_oid(oid, &peeled))
3565 oid = &peeled;
3567 object = parse_object_or_die(oid, refname);
3568 if (object->type == OBJ_COMMIT)
3569 object->flags |= NEEDS_BITMAP;
3571 return 0;
3574 static void mark_bitmap_preferred_tips(void)
3576 struct string_list_item *item;
3577 const struct string_list *preferred_tips;
3579 preferred_tips = bitmap_preferred_tips(the_repository);
3580 if (!preferred_tips)
3581 return;
3583 for_each_string_list_item(item, preferred_tips) {
3584 for_each_ref_in(item->string, mark_bitmap_preferred_tip, NULL);
3588 static void get_object_list(int ac, const char **av)
3590 struct rev_info revs;
3591 struct setup_revision_opt s_r_opt = {
3592 .allow_exclude_promisor_objects = 1,
3594 char line[1000];
3595 int flags = 0;
3596 int save_warning;
3598 repo_init_revisions(the_repository, &revs, NULL);
3599 save_commit_buffer = 0;
3600 setup_revisions(ac, av, &revs, &s_r_opt);
3602 /* make sure shallows are read */
3603 is_repository_shallow(the_repository);
3605 save_warning = warn_on_object_refname_ambiguity;
3606 warn_on_object_refname_ambiguity = 0;
3608 while (fgets(line, sizeof(line), stdin) != NULL) {
3609 int len = strlen(line);
3610 if (len && line[len - 1] == '\n')
3611 line[--len] = 0;
3612 if (!len)
3613 break;
3614 if (*line == '-') {
3615 if (!strcmp(line, "--not")) {
3616 flags ^= UNINTERESTING;
3617 write_bitmap_index = 0;
3618 continue;
3620 if (starts_with(line, "--shallow ")) {
3621 struct object_id oid;
3622 if (get_oid_hex(line + 10, &oid))
3623 die("not an object name '%s'", line + 10);
3624 register_shallow(the_repository, &oid);
3625 use_bitmap_index = 0;
3626 continue;
3628 die(_("not a rev '%s'"), line);
3630 if (handle_revision_arg(line, &revs, flags, REVARG_CANNOT_BE_FILENAME))
3631 die(_("bad revision '%s'"), line);
3634 warn_on_object_refname_ambiguity = save_warning;
3636 if (use_bitmap_index && !get_object_list_from_bitmap(&revs))
3637 return;
3639 if (use_delta_islands)
3640 load_delta_islands(the_repository, progress);
3642 if (write_bitmap_index)
3643 mark_bitmap_preferred_tips();
3645 if (prepare_revision_walk(&revs))
3646 die(_("revision walk setup failed"));
3647 mark_edges_uninteresting(&revs, show_edge, sparse);
3649 if (!fn_show_object)
3650 fn_show_object = show_object;
3651 traverse_commit_list_filtered(&filter_options, &revs,
3652 show_commit, fn_show_object, NULL,
3653 NULL);
3655 if (unpack_unreachable_expiration) {
3656 revs.ignore_missing_links = 1;
3657 if (add_unseen_recent_objects_to_traversal(&revs,
3658 unpack_unreachable_expiration))
3659 die(_("unable to add recent objects"));
3660 if (prepare_revision_walk(&revs))
3661 die(_("revision walk setup failed"));
3662 traverse_commit_list(&revs, record_recent_commit,
3663 record_recent_object, NULL);
3666 if (keep_unreachable)
3667 add_objects_in_unpacked_packs();
3668 if (pack_loose_unreachable)
3669 add_unreachable_loose_objects();
3670 if (unpack_unreachable)
3671 loosen_unused_packed_objects();
3673 oid_array_clear(&recent_objects);
3676 static void add_extra_kept_packs(const struct string_list *names)
3678 struct packed_git *p;
3680 if (!names->nr)
3681 return;
3683 for (p = get_all_packs(the_repository); p; p = p->next) {
3684 const char *name = basename(p->pack_name);
3685 int i;
3687 if (!p->pack_local)
3688 continue;
3690 for (i = 0; i < names->nr; i++)
3691 if (!fspathcmp(name, names->items[i].string))
3692 break;
3694 if (i < names->nr) {
3695 p->pack_keep_in_core = 1;
3696 ignore_packed_keep_in_core = 1;
3697 continue;
3702 static int option_parse_index_version(const struct option *opt,
3703 const char *arg, int unset)
3705 char *c;
3706 const char *val = arg;
3708 BUG_ON_OPT_NEG(unset);
3710 pack_idx_opts.version = strtoul(val, &c, 10);
3711 if (pack_idx_opts.version > 2)
3712 die(_("unsupported index version %s"), val);
3713 if (*c == ',' && c[1])
3714 pack_idx_opts.off32_limit = strtoul(c+1, &c, 0);
3715 if (*c || pack_idx_opts.off32_limit & 0x80000000)
3716 die(_("bad index version '%s'"), val);
3717 return 0;
3720 static int option_parse_unpack_unreachable(const struct option *opt,
3721 const char *arg, int unset)
3723 if (unset) {
3724 unpack_unreachable = 0;
3725 unpack_unreachable_expiration = 0;
3727 else {
3728 unpack_unreachable = 1;
3729 if (arg)
3730 unpack_unreachable_expiration = approxidate(arg);
3732 return 0;
3735 int cmd_pack_objects(int argc, const char **argv, const char *prefix)
3737 int use_internal_rev_list = 0;
3738 int shallow = 0;
3739 int all_progress_implied = 0;
3740 struct strvec rp = STRVEC_INIT;
3741 int rev_list_unpacked = 0, rev_list_all = 0, rev_list_reflog = 0;
3742 int rev_list_index = 0;
3743 int stdin_packs = 0;
3744 struct string_list keep_pack_list = STRING_LIST_INIT_NODUP;
3745 struct option pack_objects_options[] = {
3746 OPT_SET_INT('q', "quiet", &progress,
3747 N_("do not show progress meter"), 0),
3748 OPT_SET_INT(0, "progress", &progress,
3749 N_("show progress meter"), 1),
3750 OPT_SET_INT(0, "all-progress", &progress,
3751 N_("show progress meter during object writing phase"), 2),
3752 OPT_BOOL(0, "all-progress-implied",
3753 &all_progress_implied,
3754 N_("similar to --all-progress when progress meter is shown")),
3755 OPT_CALLBACK_F(0, "index-version", NULL, N_("<version>[,<offset>]"),
3756 N_("write the pack index file in the specified idx format version"),
3757 PARSE_OPT_NONEG, option_parse_index_version),
3758 OPT_MAGNITUDE(0, "max-pack-size", &pack_size_limit,
3759 N_("maximum size of each output pack file")),
3760 OPT_BOOL(0, "local", &local,
3761 N_("ignore borrowed objects from alternate object store")),
3762 OPT_BOOL(0, "incremental", &incremental,
3763 N_("ignore packed objects")),
3764 OPT_INTEGER(0, "window", &window,
3765 N_("limit pack window by objects")),
3766 OPT_MAGNITUDE(0, "window-memory", &window_memory_limit,
3767 N_("limit pack window by memory in addition to object limit")),
3768 OPT_INTEGER(0, "depth", &depth,
3769 N_("maximum length of delta chain allowed in the resulting pack")),
3770 OPT_BOOL(0, "reuse-delta", &reuse_delta,
3771 N_("reuse existing deltas")),
3772 OPT_BOOL(0, "reuse-object", &reuse_object,
3773 N_("reuse existing objects")),
3774 OPT_BOOL(0, "delta-base-offset", &allow_ofs_delta,
3775 N_("use OFS_DELTA objects")),
3776 OPT_INTEGER(0, "threads", &delta_search_threads,
3777 N_("use threads when searching for best delta matches")),
3778 OPT_BOOL(0, "non-empty", &non_empty,
3779 N_("do not create an empty pack output")),
3780 OPT_BOOL(0, "revs", &use_internal_rev_list,
3781 N_("read revision arguments from standard input")),
3782 OPT_SET_INT_F(0, "unpacked", &rev_list_unpacked,
3783 N_("limit the objects to those that are not yet packed"),
3784 1, PARSE_OPT_NONEG),
3785 OPT_SET_INT_F(0, "all", &rev_list_all,
3786 N_("include objects reachable from any reference"),
3787 1, PARSE_OPT_NONEG),
3788 OPT_SET_INT_F(0, "reflog", &rev_list_reflog,
3789 N_("include objects referred by reflog entries"),
3790 1, PARSE_OPT_NONEG),
3791 OPT_SET_INT_F(0, "indexed-objects", &rev_list_index,
3792 N_("include objects referred to by the index"),
3793 1, PARSE_OPT_NONEG),
3794 OPT_BOOL(0, "stdin-packs", &stdin_packs,
3795 N_("read packs from stdin")),
3796 OPT_BOOL(0, "stdout", &pack_to_stdout,
3797 N_("output pack to stdout")),
3798 OPT_BOOL(0, "include-tag", &include_tag,
3799 N_("include tag objects that refer to objects to be packed")),
3800 OPT_BOOL(0, "keep-unreachable", &keep_unreachable,
3801 N_("keep unreachable objects")),
3802 OPT_BOOL(0, "pack-loose-unreachable", &pack_loose_unreachable,
3803 N_("pack loose unreachable objects")),
3804 OPT_CALLBACK_F(0, "unpack-unreachable", NULL, N_("time"),
3805 N_("unpack unreachable objects newer than <time>"),
3806 PARSE_OPT_OPTARG, option_parse_unpack_unreachable),
3807 OPT_BOOL(0, "sparse", &sparse,
3808 N_("use the sparse reachability algorithm")),
3809 OPT_BOOL(0, "thin", &thin,
3810 N_("create thin packs")),
3811 OPT_BOOL(0, "shallow", &shallow,
3812 N_("create packs suitable for shallow fetches")),
3813 OPT_BOOL(0, "honor-pack-keep", &ignore_packed_keep_on_disk,
3814 N_("ignore packs that have companion .keep file")),
3815 OPT_STRING_LIST(0, "keep-pack", &keep_pack_list, N_("name"),
3816 N_("ignore this pack")),
3817 OPT_INTEGER(0, "compression", &pack_compression_level,
3818 N_("pack compression level")),
3819 OPT_SET_INT(0, "keep-true-parents", &grafts_replace_parents,
3820 N_("do not hide commits by grafts"), 0),
3821 OPT_BOOL(0, "use-bitmap-index", &use_bitmap_index,
3822 N_("use a bitmap index if available to speed up counting objects")),
3823 OPT_SET_INT(0, "write-bitmap-index", &write_bitmap_index,
3824 N_("write a bitmap index together with the pack index"),
3825 WRITE_BITMAP_TRUE),
3826 OPT_SET_INT_F(0, "write-bitmap-index-quiet",
3827 &write_bitmap_index,
3828 N_("write a bitmap index if possible"),
3829 WRITE_BITMAP_QUIET, PARSE_OPT_HIDDEN),
3830 OPT_PARSE_LIST_OBJECTS_FILTER(&filter_options),
3831 OPT_CALLBACK_F(0, "missing", NULL, N_("action"),
3832 N_("handling for missing objects"), PARSE_OPT_NONEG,
3833 option_parse_missing_action),
3834 OPT_BOOL(0, "exclude-promisor-objects", &exclude_promisor_objects,
3835 N_("do not pack objects in promisor packfiles")),
3836 OPT_BOOL(0, "delta-islands", &use_delta_islands,
3837 N_("respect islands during delta compression")),
3838 OPT_STRING_LIST(0, "uri-protocol", &uri_protocols,
3839 N_("protocol"),
3840 N_("exclude any configured uploadpack.blobpackfileuri with this protocol")),
3841 OPT_END(),
3844 if (DFS_NUM_STATES > (1 << OE_DFS_STATE_BITS))
3845 BUG("too many dfs states, increase OE_DFS_STATE_BITS");
3847 read_replace_refs = 0;
3849 sparse = git_env_bool("GIT_TEST_PACK_SPARSE", -1);
3850 prepare_repo_settings(the_repository);
3851 if (sparse < 0)
3852 sparse = the_repository->settings.pack_use_sparse;
3854 reset_pack_idx_option(&pack_idx_opts);
3855 git_config(git_pack_config, NULL);
3856 if (git_env_bool(GIT_TEST_WRITE_REV_INDEX, 0))
3857 pack_idx_opts.flags |= WRITE_REV;
3859 progress = isatty(2);
3860 argc = parse_options(argc, argv, prefix, pack_objects_options,
3861 pack_usage, 0);
3863 if (argc) {
3864 base_name = argv[0];
3865 argc--;
3867 if (pack_to_stdout != !base_name || argc)
3868 usage_with_options(pack_usage, pack_objects_options);
3870 if (depth >= (1 << OE_DEPTH_BITS)) {
3871 warning(_("delta chain depth %d is too deep, forcing %d"),
3872 depth, (1 << OE_DEPTH_BITS) - 1);
3873 depth = (1 << OE_DEPTH_BITS) - 1;
3875 if (cache_max_small_delta_size >= (1U << OE_Z_DELTA_BITS)) {
3876 warning(_("pack.deltaCacheLimit is too high, forcing %d"),
3877 (1U << OE_Z_DELTA_BITS) - 1);
3878 cache_max_small_delta_size = (1U << OE_Z_DELTA_BITS) - 1;
3881 strvec_push(&rp, "pack-objects");
3882 if (thin) {
3883 use_internal_rev_list = 1;
3884 strvec_push(&rp, shallow
3885 ? "--objects-edge-aggressive"
3886 : "--objects-edge");
3887 } else
3888 strvec_push(&rp, "--objects");
3890 if (rev_list_all) {
3891 use_internal_rev_list = 1;
3892 strvec_push(&rp, "--all");
3894 if (rev_list_reflog) {
3895 use_internal_rev_list = 1;
3896 strvec_push(&rp, "--reflog");
3898 if (rev_list_index) {
3899 use_internal_rev_list = 1;
3900 strvec_push(&rp, "--indexed-objects");
3902 if (rev_list_unpacked && !stdin_packs) {
3903 use_internal_rev_list = 1;
3904 strvec_push(&rp, "--unpacked");
3907 if (exclude_promisor_objects) {
3908 use_internal_rev_list = 1;
3909 fetch_if_missing = 0;
3910 strvec_push(&rp, "--exclude-promisor-objects");
3912 if (unpack_unreachable || keep_unreachable || pack_loose_unreachable)
3913 use_internal_rev_list = 1;
3915 if (!reuse_object)
3916 reuse_delta = 0;
3917 if (pack_compression_level == -1)
3918 pack_compression_level = Z_DEFAULT_COMPRESSION;
3919 else if (pack_compression_level < 0 || pack_compression_level > Z_BEST_COMPRESSION)
3920 die(_("bad pack compression level %d"), pack_compression_level);
3922 if (!delta_search_threads) /* --threads=0 means autodetect */
3923 delta_search_threads = online_cpus();
3925 if (!HAVE_THREADS && delta_search_threads != 1)
3926 warning(_("no threads support, ignoring --threads"));
3927 if (!pack_to_stdout && !pack_size_limit)
3928 pack_size_limit = pack_size_limit_cfg;
3929 if (pack_to_stdout && pack_size_limit)
3930 die(_("--max-pack-size cannot be used to build a pack for transfer"));
3931 if (pack_size_limit && pack_size_limit < 1024*1024) {
3932 warning(_("minimum pack size limit is 1 MiB"));
3933 pack_size_limit = 1024*1024;
3936 if (!pack_to_stdout && thin)
3937 die(_("--thin cannot be used to build an indexable pack"));
3939 if (keep_unreachable && unpack_unreachable)
3940 die(_("--keep-unreachable and --unpack-unreachable are incompatible"));
3941 if (!rev_list_all || !rev_list_reflog || !rev_list_index)
3942 unpack_unreachable_expiration = 0;
3944 if (filter_options.choice) {
3945 if (!pack_to_stdout)
3946 die(_("cannot use --filter without --stdout"));
3947 if (stdin_packs)
3948 die(_("cannot use --filter with --stdin-packs"));
3951 if (stdin_packs && use_internal_rev_list)
3952 die(_("cannot use internal rev list with --stdin-packs"));
3955 * "soft" reasons not to use bitmaps - for on-disk repack by default we want
3957 * - to produce good pack (with bitmap index not-yet-packed objects are
3958 * packed in suboptimal order).
3960 * - to use more robust pack-generation codepath (avoiding possible
3961 * bugs in bitmap code and possible bitmap index corruption).
3963 if (!pack_to_stdout)
3964 use_bitmap_index_default = 0;
3966 if (use_bitmap_index < 0)
3967 use_bitmap_index = use_bitmap_index_default;
3969 /* "hard" reasons not to use bitmaps; these just won't work at all */
3970 if (!use_internal_rev_list || (!pack_to_stdout && write_bitmap_index) || is_repository_shallow(the_repository))
3971 use_bitmap_index = 0;
3973 if (pack_to_stdout || !rev_list_all)
3974 write_bitmap_index = 0;
3976 if (use_delta_islands)
3977 strvec_push(&rp, "--topo-order");
3979 if (progress && all_progress_implied)
3980 progress = 2;
3982 add_extra_kept_packs(&keep_pack_list);
3983 if (ignore_packed_keep_on_disk) {
3984 struct packed_git *p;
3985 for (p = get_all_packs(the_repository); p; p = p->next)
3986 if (p->pack_local && p->pack_keep)
3987 break;
3988 if (!p) /* no keep-able packs found */
3989 ignore_packed_keep_on_disk = 0;
3991 if (local) {
3993 * unlike ignore_packed_keep_on_disk above, we do not
3994 * want to unset "local" based on looking at packs, as
3995 * it also covers non-local objects
3997 struct packed_git *p;
3998 for (p = get_all_packs(the_repository); p; p = p->next) {
3999 if (!p->pack_local) {
4000 have_non_local_packs = 1;
4001 break;
4006 trace2_region_enter("pack-objects", "enumerate-objects",
4007 the_repository);
4008 prepare_packing_data(the_repository, &to_pack);
4010 if (progress)
4011 progress_state = start_progress(_("Enumerating objects"), 0);
4012 if (stdin_packs) {
4013 /* avoids adding objects in excluded packs */
4014 ignore_packed_keep_in_core = 1;
4015 read_packs_list_from_stdin();
4016 if (rev_list_unpacked)
4017 add_unreachable_loose_objects();
4018 } else if (!use_internal_rev_list)
4019 read_object_list_from_stdin();
4020 else {
4021 get_object_list(rp.nr, rp.v);
4022 strvec_clear(&rp);
4024 cleanup_preferred_base();
4025 if (include_tag && nr_result)
4026 for_each_tag_ref(add_ref_tag, NULL);
4027 stop_progress(&progress_state);
4028 trace2_region_leave("pack-objects", "enumerate-objects",
4029 the_repository);
4031 if (non_empty && !nr_result)
4032 return 0;
4033 if (nr_result) {
4034 trace2_region_enter("pack-objects", "prepare-pack",
4035 the_repository);
4036 prepare_pack(window, depth);
4037 trace2_region_leave("pack-objects", "prepare-pack",
4038 the_repository);
4041 trace2_region_enter("pack-objects", "write-pack-file", the_repository);
4042 write_excluded_by_configs();
4043 write_pack_file();
4044 trace2_region_leave("pack-objects", "write-pack-file", the_repository);
4046 if (progress)
4047 fprintf_ln(stderr,
4048 _("Total %"PRIu32" (delta %"PRIu32"),"
4049 " reused %"PRIu32" (delta %"PRIu32"),"
4050 " pack-reused %"PRIu32),
4051 written, written_delta, reused, reused_delta,
4052 reuse_packfile_objects);
4053 return 0;