]> git.ipfire.org Git - thirdparty/git.git/blob - builtin/pack-objects.c
alloc.h: move ALLOC_GROW() functions from cache.h
[thirdparty/git.git] / builtin / pack-objects.c
1 #include "builtin.h"
2 #include "alloc.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"
39 #include "pack-mtimes.h"
40
41 /*
42 * Objects we are going to pack are collected in the `to_pack` structure.
43 * It contains an array (dynamically expanded) of the object data, and a map
44 * that can resolve SHA1s to their position in the array.
45 */
46 static struct packing_data to_pack;
47
48 static inline struct object_entry *oe_delta(
49 const struct packing_data *pack,
50 const struct object_entry *e)
51 {
52 if (!e->delta_idx)
53 return NULL;
54 if (e->ext_base)
55 return &pack->ext_bases[e->delta_idx - 1];
56 else
57 return &pack->objects[e->delta_idx - 1];
58 }
59
60 static inline unsigned long oe_delta_size(struct packing_data *pack,
61 const struct object_entry *e)
62 {
63 if (e->delta_size_valid)
64 return e->delta_size_;
65
66 /*
67 * pack->delta_size[] can't be NULL because oe_set_delta_size()
68 * must have been called when a new delta is saved with
69 * oe_set_delta().
70 * If oe_delta() returns NULL (i.e. default state, which means
71 * delta_size_valid is also false), then the caller must never
72 * call oe_delta_size().
73 */
74 return pack->delta_size[e - pack->objects];
75 }
76
77 unsigned long oe_get_size_slow(struct packing_data *pack,
78 const struct object_entry *e);
79
80 static inline unsigned long oe_size(struct packing_data *pack,
81 const struct object_entry *e)
82 {
83 if (e->size_valid)
84 return e->size_;
85
86 return oe_get_size_slow(pack, e);
87 }
88
89 static inline void oe_set_delta(struct packing_data *pack,
90 struct object_entry *e,
91 struct object_entry *delta)
92 {
93 if (delta)
94 e->delta_idx = (delta - pack->objects) + 1;
95 else
96 e->delta_idx = 0;
97 }
98
99 static inline struct object_entry *oe_delta_sibling(
100 const struct packing_data *pack,
101 const struct object_entry *e)
102 {
103 if (e->delta_sibling_idx)
104 return &pack->objects[e->delta_sibling_idx - 1];
105 return NULL;
106 }
107
108 static inline struct object_entry *oe_delta_child(
109 const struct packing_data *pack,
110 const struct object_entry *e)
111 {
112 if (e->delta_child_idx)
113 return &pack->objects[e->delta_child_idx - 1];
114 return NULL;
115 }
116
117 static inline void oe_set_delta_child(struct packing_data *pack,
118 struct object_entry *e,
119 struct object_entry *delta)
120 {
121 if (delta)
122 e->delta_child_idx = (delta - pack->objects) + 1;
123 else
124 e->delta_child_idx = 0;
125 }
126
127 static inline void oe_set_delta_sibling(struct packing_data *pack,
128 struct object_entry *e,
129 struct object_entry *delta)
130 {
131 if (delta)
132 e->delta_sibling_idx = (delta - pack->objects) + 1;
133 else
134 e->delta_sibling_idx = 0;
135 }
136
137 static inline void oe_set_size(struct packing_data *pack,
138 struct object_entry *e,
139 unsigned long size)
140 {
141 if (size < pack->oe_size_limit) {
142 e->size_ = size;
143 e->size_valid = 1;
144 } else {
145 e->size_valid = 0;
146 if (oe_get_size_slow(pack, e) != size)
147 BUG("'size' is supposed to be the object size!");
148 }
149 }
150
151 static inline void oe_set_delta_size(struct packing_data *pack,
152 struct object_entry *e,
153 unsigned long size)
154 {
155 if (size < pack->oe_delta_size_limit) {
156 e->delta_size_ = size;
157 e->delta_size_valid = 1;
158 } else {
159 packing_data_lock(pack);
160 if (!pack->delta_size)
161 ALLOC_ARRAY(pack->delta_size, pack->nr_alloc);
162 packing_data_unlock(pack);
163
164 pack->delta_size[e - pack->objects] = size;
165 e->delta_size_valid = 0;
166 }
167 }
168
169 #define IN_PACK(obj) oe_in_pack(&to_pack, obj)
170 #define SIZE(obj) oe_size(&to_pack, obj)
171 #define SET_SIZE(obj,size) oe_set_size(&to_pack, obj, size)
172 #define DELTA_SIZE(obj) oe_delta_size(&to_pack, obj)
173 #define DELTA(obj) oe_delta(&to_pack, obj)
174 #define DELTA_CHILD(obj) oe_delta_child(&to_pack, obj)
175 #define DELTA_SIBLING(obj) oe_delta_sibling(&to_pack, obj)
176 #define SET_DELTA(obj, val) oe_set_delta(&to_pack, obj, val)
177 #define SET_DELTA_EXT(obj, oid) oe_set_delta_ext(&to_pack, obj, oid)
178 #define SET_DELTA_SIZE(obj, val) oe_set_delta_size(&to_pack, obj, val)
179 #define SET_DELTA_CHILD(obj, val) oe_set_delta_child(&to_pack, obj, val)
180 #define SET_DELTA_SIBLING(obj, val) oe_set_delta_sibling(&to_pack, obj, val)
181
182 static const char *pack_usage[] = {
183 N_("git pack-objects --stdout [<options>] [< <ref-list> | < <object-list>]"),
184 N_("git pack-objects [<options>] <base-name> [< <ref-list> | < <object-list>]"),
185 NULL
186 };
187
188 static struct pack_idx_entry **written_list;
189 static uint32_t nr_result, nr_written, nr_seen;
190 static struct bitmap_index *bitmap_git;
191 static uint32_t write_layer;
192
193 static int non_empty;
194 static int reuse_delta = 1, reuse_object = 1;
195 static int keep_unreachable, unpack_unreachable, include_tag;
196 static timestamp_t unpack_unreachable_expiration;
197 static int pack_loose_unreachable;
198 static int cruft;
199 static timestamp_t cruft_expiration;
200 static int local;
201 static int have_non_local_packs;
202 static int incremental;
203 static int ignore_packed_keep_on_disk;
204 static int ignore_packed_keep_in_core;
205 static int allow_ofs_delta;
206 static struct pack_idx_option pack_idx_opts;
207 static const char *base_name;
208 static int progress = 1;
209 static int window = 10;
210 static unsigned long pack_size_limit;
211 static int depth = 50;
212 static int delta_search_threads;
213 static int pack_to_stdout;
214 static int sparse;
215 static int thin;
216 static int num_preferred_base;
217 static struct progress *progress_state;
218
219 static struct packed_git *reuse_packfile;
220 static uint32_t reuse_packfile_objects;
221 static struct bitmap *reuse_packfile_bitmap;
222
223 static int use_bitmap_index_default = 1;
224 static int use_bitmap_index = -1;
225 static int allow_pack_reuse = 1;
226 static enum {
227 WRITE_BITMAP_FALSE = 0,
228 WRITE_BITMAP_QUIET,
229 WRITE_BITMAP_TRUE,
230 } write_bitmap_index;
231 static uint16_t write_bitmap_options = BITMAP_OPT_HASH_CACHE;
232
233 static int exclude_promisor_objects;
234
235 static int use_delta_islands;
236
237 static unsigned long delta_cache_size = 0;
238 static unsigned long max_delta_cache_size = DEFAULT_DELTA_CACHE_SIZE;
239 static unsigned long cache_max_small_delta_size = 1000;
240
241 static unsigned long window_memory_limit = 0;
242
243 static struct string_list uri_protocols = STRING_LIST_INIT_NODUP;
244
245 enum missing_action {
246 MA_ERROR = 0, /* fail if any missing objects are encountered */
247 MA_ALLOW_ANY, /* silently allow ALL missing objects */
248 MA_ALLOW_PROMISOR, /* silently allow all missing PROMISOR objects */
249 };
250 static enum missing_action arg_missing_action;
251 static show_object_fn fn_show_object;
252
253 struct configured_exclusion {
254 struct oidmap_entry e;
255 char *pack_hash_hex;
256 char *uri;
257 };
258 static struct oidmap configured_exclusions;
259
260 static struct oidset excluded_by_config;
261
262 /*
263 * stats
264 */
265 static uint32_t written, written_delta;
266 static uint32_t reused, reused_delta;
267
268 /*
269 * Indexed commits
270 */
271 static struct commit **indexed_commits;
272 static unsigned int indexed_commits_nr;
273 static unsigned int indexed_commits_alloc;
274
275 static void index_commit_for_bitmap(struct commit *commit)
276 {
277 if (indexed_commits_nr >= indexed_commits_alloc) {
278 indexed_commits_alloc = (indexed_commits_alloc + 32) * 2;
279 REALLOC_ARRAY(indexed_commits, indexed_commits_alloc);
280 }
281
282 indexed_commits[indexed_commits_nr++] = commit;
283 }
284
285 static void *get_delta(struct object_entry *entry)
286 {
287 unsigned long size, base_size, delta_size;
288 void *buf, *base_buf, *delta_buf;
289 enum object_type type;
290
291 buf = read_object_file(&entry->idx.oid, &type, &size);
292 if (!buf)
293 die(_("unable to read %s"), oid_to_hex(&entry->idx.oid));
294 base_buf = read_object_file(&DELTA(entry)->idx.oid, &type,
295 &base_size);
296 if (!base_buf)
297 die("unable to read %s",
298 oid_to_hex(&DELTA(entry)->idx.oid));
299 delta_buf = diff_delta(base_buf, base_size,
300 buf, size, &delta_size, 0);
301 /*
302 * We successfully computed this delta once but dropped it for
303 * memory reasons. Something is very wrong if this time we
304 * recompute and create a different delta.
305 */
306 if (!delta_buf || delta_size != DELTA_SIZE(entry))
307 BUG("delta size changed");
308 free(buf);
309 free(base_buf);
310 return delta_buf;
311 }
312
313 static unsigned long do_compress(void **pptr, unsigned long size)
314 {
315 git_zstream stream;
316 void *in, *out;
317 unsigned long maxsize;
318
319 git_deflate_init(&stream, pack_compression_level);
320 maxsize = git_deflate_bound(&stream, size);
321
322 in = *pptr;
323 out = xmalloc(maxsize);
324 *pptr = out;
325
326 stream.next_in = in;
327 stream.avail_in = size;
328 stream.next_out = out;
329 stream.avail_out = maxsize;
330 while (git_deflate(&stream, Z_FINISH) == Z_OK)
331 ; /* nothing */
332 git_deflate_end(&stream);
333
334 free(in);
335 return stream.total_out;
336 }
337
338 static unsigned long write_large_blob_data(struct git_istream *st, struct hashfile *f,
339 const struct object_id *oid)
340 {
341 git_zstream stream;
342 unsigned char ibuf[1024 * 16];
343 unsigned char obuf[1024 * 16];
344 unsigned long olen = 0;
345
346 git_deflate_init(&stream, pack_compression_level);
347
348 for (;;) {
349 ssize_t readlen;
350 int zret = Z_OK;
351 readlen = read_istream(st, ibuf, sizeof(ibuf));
352 if (readlen == -1)
353 die(_("unable to read %s"), oid_to_hex(oid));
354
355 stream.next_in = ibuf;
356 stream.avail_in = readlen;
357 while ((stream.avail_in || readlen == 0) &&
358 (zret == Z_OK || zret == Z_BUF_ERROR)) {
359 stream.next_out = obuf;
360 stream.avail_out = sizeof(obuf);
361 zret = git_deflate(&stream, readlen ? 0 : Z_FINISH);
362 hashwrite(f, obuf, stream.next_out - obuf);
363 olen += stream.next_out - obuf;
364 }
365 if (stream.avail_in)
366 die(_("deflate error (%d)"), zret);
367 if (readlen == 0) {
368 if (zret != Z_STREAM_END)
369 die(_("deflate error (%d)"), zret);
370 break;
371 }
372 }
373 git_deflate_end(&stream);
374 return olen;
375 }
376
377 /*
378 * we are going to reuse the existing object data as is. make
379 * sure it is not corrupt.
380 */
381 static int check_pack_inflate(struct packed_git *p,
382 struct pack_window **w_curs,
383 off_t offset,
384 off_t len,
385 unsigned long expect)
386 {
387 git_zstream stream;
388 unsigned char fakebuf[4096], *in;
389 int st;
390
391 memset(&stream, 0, sizeof(stream));
392 git_inflate_init(&stream);
393 do {
394 in = use_pack(p, w_curs, offset, &stream.avail_in);
395 stream.next_in = in;
396 stream.next_out = fakebuf;
397 stream.avail_out = sizeof(fakebuf);
398 st = git_inflate(&stream, Z_FINISH);
399 offset += stream.next_in - in;
400 } while (st == Z_OK || st == Z_BUF_ERROR);
401 git_inflate_end(&stream);
402 return (st == Z_STREAM_END &&
403 stream.total_out == expect &&
404 stream.total_in == len) ? 0 : -1;
405 }
406
407 static void copy_pack_data(struct hashfile *f,
408 struct packed_git *p,
409 struct pack_window **w_curs,
410 off_t offset,
411 off_t len)
412 {
413 unsigned char *in;
414 unsigned long avail;
415
416 while (len) {
417 in = use_pack(p, w_curs, offset, &avail);
418 if (avail > len)
419 avail = (unsigned long)len;
420 hashwrite(f, in, avail);
421 offset += avail;
422 len -= avail;
423 }
424 }
425
426 static inline int oe_size_greater_than(struct packing_data *pack,
427 const struct object_entry *lhs,
428 unsigned long rhs)
429 {
430 if (lhs->size_valid)
431 return lhs->size_ > rhs;
432 if (rhs < pack->oe_size_limit) /* rhs < 2^x <= lhs ? */
433 return 1;
434 return oe_get_size_slow(pack, lhs) > rhs;
435 }
436
437 /* Return 0 if we will bust the pack-size limit */
438 static unsigned long write_no_reuse_object(struct hashfile *f, struct object_entry *entry,
439 unsigned long limit, int usable_delta)
440 {
441 unsigned long size, datalen;
442 unsigned char header[MAX_PACK_OBJECT_HEADER],
443 dheader[MAX_PACK_OBJECT_HEADER];
444 unsigned hdrlen;
445 enum object_type type;
446 void *buf;
447 struct git_istream *st = NULL;
448 const unsigned hashsz = the_hash_algo->rawsz;
449
450 if (!usable_delta) {
451 if (oe_type(entry) == OBJ_BLOB &&
452 oe_size_greater_than(&to_pack, entry, big_file_threshold) &&
453 (st = open_istream(the_repository, &entry->idx.oid, &type,
454 &size, NULL)) != NULL)
455 buf = NULL;
456 else {
457 buf = read_object_file(&entry->idx.oid, &type, &size);
458 if (!buf)
459 die(_("unable to read %s"),
460 oid_to_hex(&entry->idx.oid));
461 }
462 /*
463 * make sure no cached delta data remains from a
464 * previous attempt before a pack split occurred.
465 */
466 FREE_AND_NULL(entry->delta_data);
467 entry->z_delta_size = 0;
468 } else if (entry->delta_data) {
469 size = DELTA_SIZE(entry);
470 buf = entry->delta_data;
471 entry->delta_data = NULL;
472 type = (allow_ofs_delta && DELTA(entry)->idx.offset) ?
473 OBJ_OFS_DELTA : OBJ_REF_DELTA;
474 } else {
475 buf = get_delta(entry);
476 size = DELTA_SIZE(entry);
477 type = (allow_ofs_delta && DELTA(entry)->idx.offset) ?
478 OBJ_OFS_DELTA : OBJ_REF_DELTA;
479 }
480
481 if (st) /* large blob case, just assume we don't compress well */
482 datalen = size;
483 else if (entry->z_delta_size)
484 datalen = entry->z_delta_size;
485 else
486 datalen = do_compress(&buf, size);
487
488 /*
489 * The object header is a byte of 'type' followed by zero or
490 * more bytes of length.
491 */
492 hdrlen = encode_in_pack_object_header(header, sizeof(header),
493 type, size);
494
495 if (type == OBJ_OFS_DELTA) {
496 /*
497 * Deltas with relative base contain an additional
498 * encoding of the relative offset for the delta
499 * base from this object's position in the pack.
500 */
501 off_t ofs = entry->idx.offset - DELTA(entry)->idx.offset;
502 unsigned pos = sizeof(dheader) - 1;
503 dheader[pos] = ofs & 127;
504 while (ofs >>= 7)
505 dheader[--pos] = 128 | (--ofs & 127);
506 if (limit && hdrlen + sizeof(dheader) - pos + datalen + hashsz >= limit) {
507 if (st)
508 close_istream(st);
509 free(buf);
510 return 0;
511 }
512 hashwrite(f, header, hdrlen);
513 hashwrite(f, dheader + pos, sizeof(dheader) - pos);
514 hdrlen += sizeof(dheader) - pos;
515 } else if (type == OBJ_REF_DELTA) {
516 /*
517 * Deltas with a base reference contain
518 * additional bytes for the base object ID.
519 */
520 if (limit && hdrlen + hashsz + datalen + hashsz >= limit) {
521 if (st)
522 close_istream(st);
523 free(buf);
524 return 0;
525 }
526 hashwrite(f, header, hdrlen);
527 hashwrite(f, DELTA(entry)->idx.oid.hash, hashsz);
528 hdrlen += hashsz;
529 } else {
530 if (limit && hdrlen + datalen + hashsz >= limit) {
531 if (st)
532 close_istream(st);
533 free(buf);
534 return 0;
535 }
536 hashwrite(f, header, hdrlen);
537 }
538 if (st) {
539 datalen = write_large_blob_data(st, f, &entry->idx.oid);
540 close_istream(st);
541 } else {
542 hashwrite(f, buf, datalen);
543 free(buf);
544 }
545
546 return hdrlen + datalen;
547 }
548
549 /* Return 0 if we will bust the pack-size limit */
550 static off_t write_reuse_object(struct hashfile *f, struct object_entry *entry,
551 unsigned long limit, int usable_delta)
552 {
553 struct packed_git *p = IN_PACK(entry);
554 struct pack_window *w_curs = NULL;
555 uint32_t pos;
556 off_t offset;
557 enum object_type type = oe_type(entry);
558 off_t datalen;
559 unsigned char header[MAX_PACK_OBJECT_HEADER],
560 dheader[MAX_PACK_OBJECT_HEADER];
561 unsigned hdrlen;
562 const unsigned hashsz = the_hash_algo->rawsz;
563 unsigned long entry_size = SIZE(entry);
564
565 if (DELTA(entry))
566 type = (allow_ofs_delta && DELTA(entry)->idx.offset) ?
567 OBJ_OFS_DELTA : OBJ_REF_DELTA;
568 hdrlen = encode_in_pack_object_header(header, sizeof(header),
569 type, entry_size);
570
571 offset = entry->in_pack_offset;
572 if (offset_to_pack_pos(p, offset, &pos) < 0)
573 die(_("write_reuse_object: could not locate %s, expected at "
574 "offset %"PRIuMAX" in pack %s"),
575 oid_to_hex(&entry->idx.oid), (uintmax_t)offset,
576 p->pack_name);
577 datalen = pack_pos_to_offset(p, pos + 1) - offset;
578 if (!pack_to_stdout && p->index_version > 1 &&
579 check_pack_crc(p, &w_curs, offset, datalen,
580 pack_pos_to_index(p, pos))) {
581 error(_("bad packed object CRC for %s"),
582 oid_to_hex(&entry->idx.oid));
583 unuse_pack(&w_curs);
584 return write_no_reuse_object(f, entry, limit, usable_delta);
585 }
586
587 offset += entry->in_pack_header_size;
588 datalen -= entry->in_pack_header_size;
589
590 if (!pack_to_stdout && p->index_version == 1 &&
591 check_pack_inflate(p, &w_curs, offset, datalen, entry_size)) {
592 error(_("corrupt packed object for %s"),
593 oid_to_hex(&entry->idx.oid));
594 unuse_pack(&w_curs);
595 return write_no_reuse_object(f, entry, limit, usable_delta);
596 }
597
598 if (type == OBJ_OFS_DELTA) {
599 off_t ofs = entry->idx.offset - DELTA(entry)->idx.offset;
600 unsigned pos = sizeof(dheader) - 1;
601 dheader[pos] = ofs & 127;
602 while (ofs >>= 7)
603 dheader[--pos] = 128 | (--ofs & 127);
604 if (limit && hdrlen + sizeof(dheader) - pos + datalen + hashsz >= limit) {
605 unuse_pack(&w_curs);
606 return 0;
607 }
608 hashwrite(f, header, hdrlen);
609 hashwrite(f, dheader + pos, sizeof(dheader) - pos);
610 hdrlen += sizeof(dheader) - pos;
611 reused_delta++;
612 } else if (type == OBJ_REF_DELTA) {
613 if (limit && hdrlen + hashsz + datalen + hashsz >= limit) {
614 unuse_pack(&w_curs);
615 return 0;
616 }
617 hashwrite(f, header, hdrlen);
618 hashwrite(f, DELTA(entry)->idx.oid.hash, hashsz);
619 hdrlen += hashsz;
620 reused_delta++;
621 } else {
622 if (limit && hdrlen + datalen + hashsz >= limit) {
623 unuse_pack(&w_curs);
624 return 0;
625 }
626 hashwrite(f, header, hdrlen);
627 }
628 copy_pack_data(f, p, &w_curs, offset, datalen);
629 unuse_pack(&w_curs);
630 reused++;
631 return hdrlen + datalen;
632 }
633
634 /* Return 0 if we will bust the pack-size limit */
635 static off_t write_object(struct hashfile *f,
636 struct object_entry *entry,
637 off_t write_offset)
638 {
639 unsigned long limit;
640 off_t len;
641 int usable_delta, to_reuse;
642
643 if (!pack_to_stdout)
644 crc32_begin(f);
645
646 /* apply size limit if limited packsize and not first object */
647 if (!pack_size_limit || !nr_written)
648 limit = 0;
649 else if (pack_size_limit <= write_offset)
650 /*
651 * the earlier object did not fit the limit; avoid
652 * mistaking this with unlimited (i.e. limit = 0).
653 */
654 limit = 1;
655 else
656 limit = pack_size_limit - write_offset;
657
658 if (!DELTA(entry))
659 usable_delta = 0; /* no delta */
660 else if (!pack_size_limit)
661 usable_delta = 1; /* unlimited packfile */
662 else if (DELTA(entry)->idx.offset == (off_t)-1)
663 usable_delta = 0; /* base was written to another pack */
664 else if (DELTA(entry)->idx.offset)
665 usable_delta = 1; /* base already exists in this pack */
666 else
667 usable_delta = 0; /* base could end up in another pack */
668
669 if (!reuse_object)
670 to_reuse = 0; /* explicit */
671 else if (!IN_PACK(entry))
672 to_reuse = 0; /* can't reuse what we don't have */
673 else if (oe_type(entry) == OBJ_REF_DELTA ||
674 oe_type(entry) == OBJ_OFS_DELTA)
675 /* check_object() decided it for us ... */
676 to_reuse = usable_delta;
677 /* ... but pack split may override that */
678 else if (oe_type(entry) != entry->in_pack_type)
679 to_reuse = 0; /* pack has delta which is unusable */
680 else if (DELTA(entry))
681 to_reuse = 0; /* we want to pack afresh */
682 else
683 to_reuse = 1; /* we have it in-pack undeltified,
684 * and we do not need to deltify it.
685 */
686
687 if (!to_reuse)
688 len = write_no_reuse_object(f, entry, limit, usable_delta);
689 else
690 len = write_reuse_object(f, entry, limit, usable_delta);
691 if (!len)
692 return 0;
693
694 if (usable_delta)
695 written_delta++;
696 written++;
697 if (!pack_to_stdout)
698 entry->idx.crc32 = crc32_end(f);
699 return len;
700 }
701
702 enum write_one_status {
703 WRITE_ONE_SKIP = -1, /* already written */
704 WRITE_ONE_BREAK = 0, /* writing this will bust the limit; not written */
705 WRITE_ONE_WRITTEN = 1, /* normal */
706 WRITE_ONE_RECURSIVE = 2 /* already scheduled to be written */
707 };
708
709 static enum write_one_status write_one(struct hashfile *f,
710 struct object_entry *e,
711 off_t *offset)
712 {
713 off_t size;
714 int recursing;
715
716 /*
717 * we set offset to 1 (which is an impossible value) to mark
718 * the fact that this object is involved in "write its base
719 * first before writing a deltified object" recursion.
720 */
721 recursing = (e->idx.offset == 1);
722 if (recursing) {
723 warning(_("recursive delta detected for object %s"),
724 oid_to_hex(&e->idx.oid));
725 return WRITE_ONE_RECURSIVE;
726 } else if (e->idx.offset || e->preferred_base) {
727 /* offset is non zero if object is written already. */
728 return WRITE_ONE_SKIP;
729 }
730
731 /* if we are deltified, write out base object first. */
732 if (DELTA(e)) {
733 e->idx.offset = 1; /* now recurse */
734 switch (write_one(f, DELTA(e), offset)) {
735 case WRITE_ONE_RECURSIVE:
736 /* we cannot depend on this one */
737 SET_DELTA(e, NULL);
738 break;
739 default:
740 break;
741 case WRITE_ONE_BREAK:
742 e->idx.offset = recursing;
743 return WRITE_ONE_BREAK;
744 }
745 }
746
747 e->idx.offset = *offset;
748 size = write_object(f, e, *offset);
749 if (!size) {
750 e->idx.offset = recursing;
751 return WRITE_ONE_BREAK;
752 }
753 written_list[nr_written++] = &e->idx;
754
755 /* make sure off_t is sufficiently large not to wrap */
756 if (signed_add_overflows(*offset, size))
757 die(_("pack too large for current definition of off_t"));
758 *offset += size;
759 return WRITE_ONE_WRITTEN;
760 }
761
762 static int mark_tagged(const char *path UNUSED, const struct object_id *oid,
763 int flag UNUSED, void *cb_data UNUSED)
764 {
765 struct object_id peeled;
766 struct object_entry *entry = packlist_find(&to_pack, oid);
767
768 if (entry)
769 entry->tagged = 1;
770 if (!peel_iterated_oid(oid, &peeled)) {
771 entry = packlist_find(&to_pack, &peeled);
772 if (entry)
773 entry->tagged = 1;
774 }
775 return 0;
776 }
777
778 static inline unsigned char oe_layer(struct packing_data *pack,
779 struct object_entry *e)
780 {
781 if (!pack->layer)
782 return 0;
783 return pack->layer[e - pack->objects];
784 }
785
786 static inline void add_to_write_order(struct object_entry **wo,
787 unsigned int *endp,
788 struct object_entry *e)
789 {
790 if (e->filled || oe_layer(&to_pack, e) != write_layer)
791 return;
792 wo[(*endp)++] = e;
793 e->filled = 1;
794 }
795
796 static void add_descendants_to_write_order(struct object_entry **wo,
797 unsigned int *endp,
798 struct object_entry *e)
799 {
800 int add_to_order = 1;
801 while (e) {
802 if (add_to_order) {
803 struct object_entry *s;
804 /* add this node... */
805 add_to_write_order(wo, endp, e);
806 /* all its siblings... */
807 for (s = DELTA_SIBLING(e); s; s = DELTA_SIBLING(s)) {
808 add_to_write_order(wo, endp, s);
809 }
810 }
811 /* drop down a level to add left subtree nodes if possible */
812 if (DELTA_CHILD(e)) {
813 add_to_order = 1;
814 e = DELTA_CHILD(e);
815 } else {
816 add_to_order = 0;
817 /* our sibling might have some children, it is next */
818 if (DELTA_SIBLING(e)) {
819 e = DELTA_SIBLING(e);
820 continue;
821 }
822 /* go back to our parent node */
823 e = DELTA(e);
824 while (e && !DELTA_SIBLING(e)) {
825 /* we're on the right side of a subtree, keep
826 * going up until we can go right again */
827 e = DELTA(e);
828 }
829 if (!e) {
830 /* done- we hit our original root node */
831 return;
832 }
833 /* pass it off to sibling at this level */
834 e = DELTA_SIBLING(e);
835 }
836 };
837 }
838
839 static void add_family_to_write_order(struct object_entry **wo,
840 unsigned int *endp,
841 struct object_entry *e)
842 {
843 struct object_entry *root;
844
845 for (root = e; DELTA(root); root = DELTA(root))
846 ; /* nothing */
847 add_descendants_to_write_order(wo, endp, root);
848 }
849
850 static void compute_layer_order(struct object_entry **wo, unsigned int *wo_end)
851 {
852 unsigned int i, last_untagged;
853 struct object_entry *objects = to_pack.objects;
854
855 for (i = 0; i < to_pack.nr_objects; i++) {
856 if (objects[i].tagged)
857 break;
858 add_to_write_order(wo, wo_end, &objects[i]);
859 }
860 last_untagged = i;
861
862 /*
863 * Then fill all the tagged tips.
864 */
865 for (; i < to_pack.nr_objects; i++) {
866 if (objects[i].tagged)
867 add_to_write_order(wo, wo_end, &objects[i]);
868 }
869
870 /*
871 * And then all remaining commits and tags.
872 */
873 for (i = last_untagged; i < to_pack.nr_objects; i++) {
874 if (oe_type(&objects[i]) != OBJ_COMMIT &&
875 oe_type(&objects[i]) != OBJ_TAG)
876 continue;
877 add_to_write_order(wo, wo_end, &objects[i]);
878 }
879
880 /*
881 * And then all the trees.
882 */
883 for (i = last_untagged; i < to_pack.nr_objects; i++) {
884 if (oe_type(&objects[i]) != OBJ_TREE)
885 continue;
886 add_to_write_order(wo, wo_end, &objects[i]);
887 }
888
889 /*
890 * Finally all the rest in really tight order
891 */
892 for (i = last_untagged; i < to_pack.nr_objects; i++) {
893 if (!objects[i].filled && oe_layer(&to_pack, &objects[i]) == write_layer)
894 add_family_to_write_order(wo, wo_end, &objects[i]);
895 }
896 }
897
898 static struct object_entry **compute_write_order(void)
899 {
900 uint32_t max_layers = 1;
901 unsigned int i, wo_end;
902
903 struct object_entry **wo;
904 struct object_entry *objects = to_pack.objects;
905
906 for (i = 0; i < to_pack.nr_objects; i++) {
907 objects[i].tagged = 0;
908 objects[i].filled = 0;
909 SET_DELTA_CHILD(&objects[i], NULL);
910 SET_DELTA_SIBLING(&objects[i], NULL);
911 }
912
913 /*
914 * Fully connect delta_child/delta_sibling network.
915 * Make sure delta_sibling is sorted in the original
916 * recency order.
917 */
918 for (i = to_pack.nr_objects; i > 0;) {
919 struct object_entry *e = &objects[--i];
920 if (!DELTA(e))
921 continue;
922 /* Mark me as the first child */
923 e->delta_sibling_idx = DELTA(e)->delta_child_idx;
924 SET_DELTA_CHILD(DELTA(e), e);
925 }
926
927 /*
928 * Mark objects that are at the tip of tags.
929 */
930 for_each_tag_ref(mark_tagged, NULL);
931
932 if (use_delta_islands) {
933 max_layers = compute_pack_layers(&to_pack);
934 free_island_marks();
935 }
936
937 ALLOC_ARRAY(wo, to_pack.nr_objects);
938 wo_end = 0;
939
940 for (; write_layer < max_layers; ++write_layer)
941 compute_layer_order(wo, &wo_end);
942
943 if (wo_end != to_pack.nr_objects)
944 die(_("ordered %u objects, expected %"PRIu32),
945 wo_end, to_pack.nr_objects);
946
947 return wo;
948 }
949
950
951 /*
952 * A reused set of objects. All objects in a chunk have the same
953 * relative position in the original packfile and the generated
954 * packfile.
955 */
956
957 static struct reused_chunk {
958 /* The offset of the first object of this chunk in the original
959 * packfile. */
960 off_t original;
961 /* The difference for "original" minus the offset of the first object of
962 * this chunk in the generated packfile. */
963 off_t difference;
964 } *reused_chunks;
965 static int reused_chunks_nr;
966 static int reused_chunks_alloc;
967
968 static void record_reused_object(off_t where, off_t offset)
969 {
970 if (reused_chunks_nr && reused_chunks[reused_chunks_nr-1].difference == offset)
971 return;
972
973 ALLOC_GROW(reused_chunks, reused_chunks_nr + 1,
974 reused_chunks_alloc);
975 reused_chunks[reused_chunks_nr].original = where;
976 reused_chunks[reused_chunks_nr].difference = offset;
977 reused_chunks_nr++;
978 }
979
980 /*
981 * Binary search to find the chunk that "where" is in. Note
982 * that we're not looking for an exact match, just the first
983 * chunk that contains it (which implicitly ends at the start
984 * of the next chunk.
985 */
986 static off_t find_reused_offset(off_t where)
987 {
988 int lo = 0, hi = reused_chunks_nr;
989 while (lo < hi) {
990 int mi = lo + ((hi - lo) / 2);
991 if (where == reused_chunks[mi].original)
992 return reused_chunks[mi].difference;
993 if (where < reused_chunks[mi].original)
994 hi = mi;
995 else
996 lo = mi + 1;
997 }
998
999 /*
1000 * The first chunk starts at zero, so we can't have gone below
1001 * there.
1002 */
1003 assert(lo);
1004 return reused_chunks[lo-1].difference;
1005 }
1006
1007 static void write_reused_pack_one(size_t pos, struct hashfile *out,
1008 struct pack_window **w_curs)
1009 {
1010 off_t offset, next, cur;
1011 enum object_type type;
1012 unsigned long size;
1013
1014 offset = pack_pos_to_offset(reuse_packfile, pos);
1015 next = pack_pos_to_offset(reuse_packfile, pos + 1);
1016
1017 record_reused_object(offset, offset - hashfile_total(out));
1018
1019 cur = offset;
1020 type = unpack_object_header(reuse_packfile, w_curs, &cur, &size);
1021 assert(type >= 0);
1022
1023 if (type == OBJ_OFS_DELTA) {
1024 off_t base_offset;
1025 off_t fixup;
1026
1027 unsigned char header[MAX_PACK_OBJECT_HEADER];
1028 unsigned len;
1029
1030 base_offset = get_delta_base(reuse_packfile, w_curs, &cur, type, offset);
1031 assert(base_offset != 0);
1032
1033 /* Convert to REF_DELTA if we must... */
1034 if (!allow_ofs_delta) {
1035 uint32_t base_pos;
1036 struct object_id base_oid;
1037
1038 if (offset_to_pack_pos(reuse_packfile, base_offset, &base_pos) < 0)
1039 die(_("expected object at offset %"PRIuMAX" "
1040 "in pack %s"),
1041 (uintmax_t)base_offset,
1042 reuse_packfile->pack_name);
1043
1044 nth_packed_object_id(&base_oid, reuse_packfile,
1045 pack_pos_to_index(reuse_packfile, base_pos));
1046
1047 len = encode_in_pack_object_header(header, sizeof(header),
1048 OBJ_REF_DELTA, size);
1049 hashwrite(out, header, len);
1050 hashwrite(out, base_oid.hash, the_hash_algo->rawsz);
1051 copy_pack_data(out, reuse_packfile, w_curs, cur, next - cur);
1052 return;
1053 }
1054
1055 /* Otherwise see if we need to rewrite the offset... */
1056 fixup = find_reused_offset(offset) -
1057 find_reused_offset(base_offset);
1058 if (fixup) {
1059 unsigned char ofs_header[10];
1060 unsigned i, ofs_len;
1061 off_t ofs = offset - base_offset - fixup;
1062
1063 len = encode_in_pack_object_header(header, sizeof(header),
1064 OBJ_OFS_DELTA, size);
1065
1066 i = sizeof(ofs_header) - 1;
1067 ofs_header[i] = ofs & 127;
1068 while (ofs >>= 7)
1069 ofs_header[--i] = 128 | (--ofs & 127);
1070
1071 ofs_len = sizeof(ofs_header) - i;
1072
1073 hashwrite(out, header, len);
1074 hashwrite(out, ofs_header + sizeof(ofs_header) - ofs_len, ofs_len);
1075 copy_pack_data(out, reuse_packfile, w_curs, cur, next - cur);
1076 return;
1077 }
1078
1079 /* ...otherwise we have no fixup, and can write it verbatim */
1080 }
1081
1082 copy_pack_data(out, reuse_packfile, w_curs, offset, next - offset);
1083 }
1084
1085 static size_t write_reused_pack_verbatim(struct hashfile *out,
1086 struct pack_window **w_curs)
1087 {
1088 size_t pos = 0;
1089
1090 while (pos < reuse_packfile_bitmap->word_alloc &&
1091 reuse_packfile_bitmap->words[pos] == (eword_t)~0)
1092 pos++;
1093
1094 if (pos) {
1095 off_t to_write;
1096
1097 written = (pos * BITS_IN_EWORD);
1098 to_write = pack_pos_to_offset(reuse_packfile, written)
1099 - sizeof(struct pack_header);
1100
1101 /* We're recording one chunk, not one object. */
1102 record_reused_object(sizeof(struct pack_header), 0);
1103 hashflush(out);
1104 copy_pack_data(out, reuse_packfile, w_curs,
1105 sizeof(struct pack_header), to_write);
1106
1107 display_progress(progress_state, written);
1108 }
1109 return pos;
1110 }
1111
1112 static void write_reused_pack(struct hashfile *f)
1113 {
1114 size_t i = 0;
1115 uint32_t offset;
1116 struct pack_window *w_curs = NULL;
1117
1118 if (allow_ofs_delta)
1119 i = write_reused_pack_verbatim(f, &w_curs);
1120
1121 for (; i < reuse_packfile_bitmap->word_alloc; ++i) {
1122 eword_t word = reuse_packfile_bitmap->words[i];
1123 size_t pos = (i * BITS_IN_EWORD);
1124
1125 for (offset = 0; offset < BITS_IN_EWORD; ++offset) {
1126 if ((word >> offset) == 0)
1127 break;
1128
1129 offset += ewah_bit_ctz64(word >> offset);
1130 /*
1131 * Can use bit positions directly, even for MIDX
1132 * bitmaps. See comment in try_partial_reuse()
1133 * for why.
1134 */
1135 write_reused_pack_one(pos + offset, f, &w_curs);
1136 display_progress(progress_state, ++written);
1137 }
1138 }
1139
1140 unuse_pack(&w_curs);
1141 }
1142
1143 static void write_excluded_by_configs(void)
1144 {
1145 struct oidset_iter iter;
1146 const struct object_id *oid;
1147
1148 oidset_iter_init(&excluded_by_config, &iter);
1149 while ((oid = oidset_iter_next(&iter))) {
1150 struct configured_exclusion *ex =
1151 oidmap_get(&configured_exclusions, oid);
1152
1153 if (!ex)
1154 BUG("configured exclusion wasn't configured");
1155 write_in_full(1, ex->pack_hash_hex, strlen(ex->pack_hash_hex));
1156 write_in_full(1, " ", 1);
1157 write_in_full(1, ex->uri, strlen(ex->uri));
1158 write_in_full(1, "\n", 1);
1159 }
1160 }
1161
1162 static const char no_split_warning[] = N_(
1163 "disabling bitmap writing, packs are split due to pack.packSizeLimit"
1164 );
1165
1166 static void write_pack_file(void)
1167 {
1168 uint32_t i = 0, j;
1169 struct hashfile *f;
1170 off_t offset;
1171 uint32_t nr_remaining = nr_result;
1172 time_t last_mtime = 0;
1173 struct object_entry **write_order;
1174
1175 if (progress > pack_to_stdout)
1176 progress_state = start_progress(_("Writing objects"), nr_result);
1177 ALLOC_ARRAY(written_list, to_pack.nr_objects);
1178 write_order = compute_write_order();
1179
1180 do {
1181 unsigned char hash[GIT_MAX_RAWSZ];
1182 char *pack_tmp_name = NULL;
1183
1184 if (pack_to_stdout)
1185 f = hashfd_throughput(1, "<stdout>", progress_state);
1186 else
1187 f = create_tmp_packfile(&pack_tmp_name);
1188
1189 offset = write_pack_header(f, nr_remaining);
1190
1191 if (reuse_packfile) {
1192 assert(pack_to_stdout);
1193 write_reused_pack(f);
1194 offset = hashfile_total(f);
1195 }
1196
1197 nr_written = 0;
1198 for (; i < to_pack.nr_objects; i++) {
1199 struct object_entry *e = write_order[i];
1200 if (write_one(f, e, &offset) == WRITE_ONE_BREAK)
1201 break;
1202 display_progress(progress_state, written);
1203 }
1204
1205 if (pack_to_stdout) {
1206 /*
1207 * We never fsync when writing to stdout since we may
1208 * not be writing to an actual pack file. For instance,
1209 * the upload-pack code passes a pipe here. Calling
1210 * fsync on a pipe results in unnecessary
1211 * synchronization with the reader on some platforms.
1212 */
1213 finalize_hashfile(f, hash, FSYNC_COMPONENT_NONE,
1214 CSUM_HASH_IN_STREAM | CSUM_CLOSE);
1215 } else if (nr_written == nr_remaining) {
1216 finalize_hashfile(f, hash, FSYNC_COMPONENT_PACK,
1217 CSUM_HASH_IN_STREAM | CSUM_FSYNC | CSUM_CLOSE);
1218 } else {
1219 /*
1220 * If we wrote the wrong number of entries in the
1221 * header, rewrite it like in fast-import.
1222 */
1223
1224 int fd = finalize_hashfile(f, hash, FSYNC_COMPONENT_PACK, 0);
1225 fixup_pack_header_footer(fd, hash, pack_tmp_name,
1226 nr_written, hash, offset);
1227 close(fd);
1228 if (write_bitmap_index) {
1229 if (write_bitmap_index != WRITE_BITMAP_QUIET)
1230 warning(_(no_split_warning));
1231 write_bitmap_index = 0;
1232 }
1233 }
1234
1235 if (!pack_to_stdout) {
1236 struct stat st;
1237 struct strbuf tmpname = STRBUF_INIT;
1238 char *idx_tmp_name = NULL;
1239
1240 /*
1241 * Packs are runtime accessed in their mtime
1242 * order since newer packs are more likely to contain
1243 * younger objects. So if we are creating multiple
1244 * packs then we should modify the mtime of later ones
1245 * to preserve this property.
1246 */
1247 if (stat(pack_tmp_name, &st) < 0) {
1248 warning_errno(_("failed to stat %s"), pack_tmp_name);
1249 } else if (!last_mtime) {
1250 last_mtime = st.st_mtime;
1251 } else {
1252 struct utimbuf utb;
1253 utb.actime = st.st_atime;
1254 utb.modtime = --last_mtime;
1255 if (utime(pack_tmp_name, &utb) < 0)
1256 warning_errno(_("failed utime() on %s"), pack_tmp_name);
1257 }
1258
1259 strbuf_addf(&tmpname, "%s-%s.", base_name,
1260 hash_to_hex(hash));
1261
1262 if (write_bitmap_index) {
1263 bitmap_writer_set_checksum(hash);
1264 bitmap_writer_build_type_index(
1265 &to_pack, written_list, nr_written);
1266 }
1267
1268 if (cruft)
1269 pack_idx_opts.flags |= WRITE_MTIMES;
1270
1271 stage_tmp_packfiles(&tmpname, pack_tmp_name,
1272 written_list, nr_written,
1273 &to_pack, &pack_idx_opts, hash,
1274 &idx_tmp_name);
1275
1276 if (write_bitmap_index) {
1277 size_t tmpname_len = tmpname.len;
1278
1279 strbuf_addstr(&tmpname, "bitmap");
1280 stop_progress(&progress_state);
1281
1282 bitmap_writer_show_progress(progress);
1283 bitmap_writer_select_commits(indexed_commits, indexed_commits_nr, -1);
1284 if (bitmap_writer_build(&to_pack) < 0)
1285 die(_("failed to write bitmap index"));
1286 bitmap_writer_finish(written_list, nr_written,
1287 tmpname.buf, write_bitmap_options);
1288 write_bitmap_index = 0;
1289 strbuf_setlen(&tmpname, tmpname_len);
1290 }
1291
1292 rename_tmp_packfile_idx(&tmpname, &idx_tmp_name);
1293
1294 free(idx_tmp_name);
1295 strbuf_release(&tmpname);
1296 free(pack_tmp_name);
1297 puts(hash_to_hex(hash));
1298 }
1299
1300 /* mark written objects as written to previous pack */
1301 for (j = 0; j < nr_written; j++) {
1302 written_list[j]->offset = (off_t)-1;
1303 }
1304 nr_remaining -= nr_written;
1305 } while (nr_remaining && i < to_pack.nr_objects);
1306
1307 free(written_list);
1308 free(write_order);
1309 stop_progress(&progress_state);
1310 if (written != nr_result)
1311 die(_("wrote %"PRIu32" objects while expecting %"PRIu32),
1312 written, nr_result);
1313 trace2_data_intmax("pack-objects", the_repository,
1314 "write_pack_file/wrote", nr_result);
1315 }
1316
1317 static int no_try_delta(const char *path)
1318 {
1319 static struct attr_check *check;
1320
1321 if (!check)
1322 check = attr_check_initl("delta", NULL);
1323 git_check_attr(the_repository->index, NULL, path, check);
1324 if (ATTR_FALSE(check->items[0].value))
1325 return 1;
1326 return 0;
1327 }
1328
1329 /*
1330 * When adding an object, check whether we have already added it
1331 * to our packing list. If so, we can skip. However, if we are
1332 * being asked to excludei t, but the previous mention was to include
1333 * it, make sure to adjust its flags and tweak our numbers accordingly.
1334 *
1335 * As an optimization, we pass out the index position where we would have
1336 * found the item, since that saves us from having to look it up again a
1337 * few lines later when we want to add the new entry.
1338 */
1339 static int have_duplicate_entry(const struct object_id *oid,
1340 int exclude)
1341 {
1342 struct object_entry *entry;
1343
1344 if (reuse_packfile_bitmap &&
1345 bitmap_walk_contains(bitmap_git, reuse_packfile_bitmap, oid))
1346 return 1;
1347
1348 entry = packlist_find(&to_pack, oid);
1349 if (!entry)
1350 return 0;
1351
1352 if (exclude) {
1353 if (!entry->preferred_base)
1354 nr_result--;
1355 entry->preferred_base = 1;
1356 }
1357
1358 return 1;
1359 }
1360
1361 static int want_found_object(const struct object_id *oid, int exclude,
1362 struct packed_git *p)
1363 {
1364 if (exclude)
1365 return 1;
1366 if (incremental)
1367 return 0;
1368
1369 if (!is_pack_valid(p))
1370 return -1;
1371
1372 /*
1373 * When asked to do --local (do not include an object that appears in a
1374 * pack we borrow from elsewhere) or --honor-pack-keep (do not include
1375 * an object that appears in a pack marked with .keep), finding a pack
1376 * that matches the criteria is sufficient for us to decide to omit it.
1377 * However, even if this pack does not satisfy the criteria, we need to
1378 * make sure no copy of this object appears in _any_ pack that makes us
1379 * to omit the object, so we need to check all the packs.
1380 *
1381 * We can however first check whether these options can possibly matter;
1382 * if they do not matter we know we want the object in generated pack.
1383 * Otherwise, we signal "-1" at the end to tell the caller that we do
1384 * not know either way, and it needs to check more packs.
1385 */
1386
1387 /*
1388 * Objects in packs borrowed from elsewhere are discarded regardless of
1389 * if they appear in other packs that weren't borrowed.
1390 */
1391 if (local && !p->pack_local)
1392 return 0;
1393
1394 /*
1395 * Then handle .keep first, as we have a fast(er) path there.
1396 */
1397 if (ignore_packed_keep_on_disk || ignore_packed_keep_in_core) {
1398 /*
1399 * Set the flags for the kept-pack cache to be the ones we want
1400 * to ignore.
1401 *
1402 * That is, if we are ignoring objects in on-disk keep packs,
1403 * then we want to search through the on-disk keep and ignore
1404 * the in-core ones.
1405 */
1406 unsigned flags = 0;
1407 if (ignore_packed_keep_on_disk)
1408 flags |= ON_DISK_KEEP_PACKS;
1409 if (ignore_packed_keep_in_core)
1410 flags |= IN_CORE_KEEP_PACKS;
1411
1412 if (ignore_packed_keep_on_disk && p->pack_keep)
1413 return 0;
1414 if (ignore_packed_keep_in_core && p->pack_keep_in_core)
1415 return 0;
1416 if (has_object_kept_pack(oid, flags))
1417 return 0;
1418 }
1419
1420 /*
1421 * At this point we know definitively that either we don't care about
1422 * keep-packs, or the object is not in one. Keep checking other
1423 * conditions...
1424 */
1425 if (!local || !have_non_local_packs)
1426 return 1;
1427
1428 /* we don't know yet; keep looking for more packs */
1429 return -1;
1430 }
1431
1432 static int want_object_in_pack_one(struct packed_git *p,
1433 const struct object_id *oid,
1434 int exclude,
1435 struct packed_git **found_pack,
1436 off_t *found_offset)
1437 {
1438 off_t offset;
1439
1440 if (p == *found_pack)
1441 offset = *found_offset;
1442 else
1443 offset = find_pack_entry_one(oid->hash, p);
1444
1445 if (offset) {
1446 if (!*found_pack) {
1447 if (!is_pack_valid(p))
1448 return -1;
1449 *found_offset = offset;
1450 *found_pack = p;
1451 }
1452 return want_found_object(oid, exclude, p);
1453 }
1454 return -1;
1455 }
1456
1457 /*
1458 * Check whether we want the object in the pack (e.g., we do not want
1459 * objects found in non-local stores if the "--local" option was used).
1460 *
1461 * If the caller already knows an existing pack it wants to take the object
1462 * from, that is passed in *found_pack and *found_offset; otherwise this
1463 * function finds if there is any pack that has the object and returns the pack
1464 * and its offset in these variables.
1465 */
1466 static int want_object_in_pack(const struct object_id *oid,
1467 int exclude,
1468 struct packed_git **found_pack,
1469 off_t *found_offset)
1470 {
1471 int want;
1472 struct list_head *pos;
1473 struct multi_pack_index *m;
1474
1475 if (!exclude && local && has_loose_object_nonlocal(oid))
1476 return 0;
1477
1478 /*
1479 * If we already know the pack object lives in, start checks from that
1480 * pack - in the usual case when neither --local was given nor .keep files
1481 * are present we will determine the answer right now.
1482 */
1483 if (*found_pack) {
1484 want = want_found_object(oid, exclude, *found_pack);
1485 if (want != -1)
1486 return want;
1487
1488 *found_pack = NULL;
1489 *found_offset = 0;
1490 }
1491
1492 for (m = get_multi_pack_index(the_repository); m; m = m->next) {
1493 struct pack_entry e;
1494 if (fill_midx_entry(the_repository, oid, &e, m)) {
1495 want = want_object_in_pack_one(e.p, oid, exclude, found_pack, found_offset);
1496 if (want != -1)
1497 return want;
1498 }
1499 }
1500
1501 list_for_each(pos, get_packed_git_mru(the_repository)) {
1502 struct packed_git *p = list_entry(pos, struct packed_git, mru);
1503 want = want_object_in_pack_one(p, oid, exclude, found_pack, found_offset);
1504 if (!exclude && want > 0)
1505 list_move(&p->mru,
1506 get_packed_git_mru(the_repository));
1507 if (want != -1)
1508 return want;
1509 }
1510
1511 if (uri_protocols.nr) {
1512 struct configured_exclusion *ex =
1513 oidmap_get(&configured_exclusions, oid);
1514 int i;
1515 const char *p;
1516
1517 if (ex) {
1518 for (i = 0; i < uri_protocols.nr; i++) {
1519 if (skip_prefix(ex->uri,
1520 uri_protocols.items[i].string,
1521 &p) &&
1522 *p == ':') {
1523 oidset_insert(&excluded_by_config, oid);
1524 return 0;
1525 }
1526 }
1527 }
1528 }
1529
1530 return 1;
1531 }
1532
1533 static struct object_entry *create_object_entry(const struct object_id *oid,
1534 enum object_type type,
1535 uint32_t hash,
1536 int exclude,
1537 int no_try_delta,
1538 struct packed_git *found_pack,
1539 off_t found_offset)
1540 {
1541 struct object_entry *entry;
1542
1543 entry = packlist_alloc(&to_pack, oid);
1544 entry->hash = hash;
1545 oe_set_type(entry, type);
1546 if (exclude)
1547 entry->preferred_base = 1;
1548 else
1549 nr_result++;
1550 if (found_pack) {
1551 oe_set_in_pack(&to_pack, entry, found_pack);
1552 entry->in_pack_offset = found_offset;
1553 }
1554
1555 entry->no_try_delta = no_try_delta;
1556
1557 return entry;
1558 }
1559
1560 static const char no_closure_warning[] = N_(
1561 "disabling bitmap writing, as some objects are not being packed"
1562 );
1563
1564 static int add_object_entry(const struct object_id *oid, enum object_type type,
1565 const char *name, int exclude)
1566 {
1567 struct packed_git *found_pack = NULL;
1568 off_t found_offset = 0;
1569
1570 display_progress(progress_state, ++nr_seen);
1571
1572 if (have_duplicate_entry(oid, exclude))
1573 return 0;
1574
1575 if (!want_object_in_pack(oid, exclude, &found_pack, &found_offset)) {
1576 /* The pack is missing an object, so it will not have closure */
1577 if (write_bitmap_index) {
1578 if (write_bitmap_index != WRITE_BITMAP_QUIET)
1579 warning(_(no_closure_warning));
1580 write_bitmap_index = 0;
1581 }
1582 return 0;
1583 }
1584
1585 create_object_entry(oid, type, pack_name_hash(name),
1586 exclude, name && no_try_delta(name),
1587 found_pack, found_offset);
1588 return 1;
1589 }
1590
1591 static int add_object_entry_from_bitmap(const struct object_id *oid,
1592 enum object_type type,
1593 int flags, uint32_t name_hash,
1594 struct packed_git *pack, off_t offset)
1595 {
1596 display_progress(progress_state, ++nr_seen);
1597
1598 if (have_duplicate_entry(oid, 0))
1599 return 0;
1600
1601 if (!want_object_in_pack(oid, 0, &pack, &offset))
1602 return 0;
1603
1604 create_object_entry(oid, type, name_hash, 0, 0, pack, offset);
1605 return 1;
1606 }
1607
1608 struct pbase_tree_cache {
1609 struct object_id oid;
1610 int ref;
1611 int temporary;
1612 void *tree_data;
1613 unsigned long tree_size;
1614 };
1615
1616 static struct pbase_tree_cache *(pbase_tree_cache[256]);
1617 static int pbase_tree_cache_ix(const struct object_id *oid)
1618 {
1619 return oid->hash[0] % ARRAY_SIZE(pbase_tree_cache);
1620 }
1621 static int pbase_tree_cache_ix_incr(int ix)
1622 {
1623 return (ix+1) % ARRAY_SIZE(pbase_tree_cache);
1624 }
1625
1626 static struct pbase_tree {
1627 struct pbase_tree *next;
1628 /* This is a phony "cache" entry; we are not
1629 * going to evict it or find it through _get()
1630 * mechanism -- this is for the toplevel node that
1631 * would almost always change with any commit.
1632 */
1633 struct pbase_tree_cache pcache;
1634 } *pbase_tree;
1635
1636 static struct pbase_tree_cache *pbase_tree_get(const struct object_id *oid)
1637 {
1638 struct pbase_tree_cache *ent, *nent;
1639 void *data;
1640 unsigned long size;
1641 enum object_type type;
1642 int neigh;
1643 int my_ix = pbase_tree_cache_ix(oid);
1644 int available_ix = -1;
1645
1646 /* pbase-tree-cache acts as a limited hashtable.
1647 * your object will be found at your index or within a few
1648 * slots after that slot if it is cached.
1649 */
1650 for (neigh = 0; neigh < 8; neigh++) {
1651 ent = pbase_tree_cache[my_ix];
1652 if (ent && oideq(&ent->oid, oid)) {
1653 ent->ref++;
1654 return ent;
1655 }
1656 else if (((available_ix < 0) && (!ent || !ent->ref)) ||
1657 ((0 <= available_ix) &&
1658 (!ent && pbase_tree_cache[available_ix])))
1659 available_ix = my_ix;
1660 if (!ent)
1661 break;
1662 my_ix = pbase_tree_cache_ix_incr(my_ix);
1663 }
1664
1665 /* Did not find one. Either we got a bogus request or
1666 * we need to read and perhaps cache.
1667 */
1668 data = read_object_file(oid, &type, &size);
1669 if (!data)
1670 return NULL;
1671 if (type != OBJ_TREE) {
1672 free(data);
1673 return NULL;
1674 }
1675
1676 /* We need to either cache or return a throwaway copy */
1677
1678 if (available_ix < 0)
1679 ent = NULL;
1680 else {
1681 ent = pbase_tree_cache[available_ix];
1682 my_ix = available_ix;
1683 }
1684
1685 if (!ent) {
1686 nent = xmalloc(sizeof(*nent));
1687 nent->temporary = (available_ix < 0);
1688 }
1689 else {
1690 /* evict and reuse */
1691 free(ent->tree_data);
1692 nent = ent;
1693 }
1694 oidcpy(&nent->oid, oid);
1695 nent->tree_data = data;
1696 nent->tree_size = size;
1697 nent->ref = 1;
1698 if (!nent->temporary)
1699 pbase_tree_cache[my_ix] = nent;
1700 return nent;
1701 }
1702
1703 static void pbase_tree_put(struct pbase_tree_cache *cache)
1704 {
1705 if (!cache->temporary) {
1706 cache->ref--;
1707 return;
1708 }
1709 free(cache->tree_data);
1710 free(cache);
1711 }
1712
1713 static size_t name_cmp_len(const char *name)
1714 {
1715 return strcspn(name, "\n/");
1716 }
1717
1718 static void add_pbase_object(struct tree_desc *tree,
1719 const char *name,
1720 size_t cmplen,
1721 const char *fullname)
1722 {
1723 struct name_entry entry;
1724 int cmp;
1725
1726 while (tree_entry(tree,&entry)) {
1727 if (S_ISGITLINK(entry.mode))
1728 continue;
1729 cmp = tree_entry_len(&entry) != cmplen ? 1 :
1730 memcmp(name, entry.path, cmplen);
1731 if (cmp > 0)
1732 continue;
1733 if (cmp < 0)
1734 return;
1735 if (name[cmplen] != '/') {
1736 add_object_entry(&entry.oid,
1737 object_type(entry.mode),
1738 fullname, 1);
1739 return;
1740 }
1741 if (S_ISDIR(entry.mode)) {
1742 struct tree_desc sub;
1743 struct pbase_tree_cache *tree;
1744 const char *down = name+cmplen+1;
1745 size_t downlen = name_cmp_len(down);
1746
1747 tree = pbase_tree_get(&entry.oid);
1748 if (!tree)
1749 return;
1750 init_tree_desc(&sub, tree->tree_data, tree->tree_size);
1751
1752 add_pbase_object(&sub, down, downlen, fullname);
1753 pbase_tree_put(tree);
1754 }
1755 }
1756 }
1757
1758 static unsigned *done_pbase_paths;
1759 static int done_pbase_paths_num;
1760 static int done_pbase_paths_alloc;
1761 static int done_pbase_path_pos(unsigned hash)
1762 {
1763 int lo = 0;
1764 int hi = done_pbase_paths_num;
1765 while (lo < hi) {
1766 int mi = lo + (hi - lo) / 2;
1767 if (done_pbase_paths[mi] == hash)
1768 return mi;
1769 if (done_pbase_paths[mi] < hash)
1770 hi = mi;
1771 else
1772 lo = mi + 1;
1773 }
1774 return -lo-1;
1775 }
1776
1777 static int check_pbase_path(unsigned hash)
1778 {
1779 int pos = done_pbase_path_pos(hash);
1780 if (0 <= pos)
1781 return 1;
1782 pos = -pos - 1;
1783 ALLOC_GROW(done_pbase_paths,
1784 done_pbase_paths_num + 1,
1785 done_pbase_paths_alloc);
1786 done_pbase_paths_num++;
1787 if (pos < done_pbase_paths_num)
1788 MOVE_ARRAY(done_pbase_paths + pos + 1, done_pbase_paths + pos,
1789 done_pbase_paths_num - pos - 1);
1790 done_pbase_paths[pos] = hash;
1791 return 0;
1792 }
1793
1794 static void add_preferred_base_object(const char *name)
1795 {
1796 struct pbase_tree *it;
1797 size_t cmplen;
1798 unsigned hash = pack_name_hash(name);
1799
1800 if (!num_preferred_base || check_pbase_path(hash))
1801 return;
1802
1803 cmplen = name_cmp_len(name);
1804 for (it = pbase_tree; it; it = it->next) {
1805 if (cmplen == 0) {
1806 add_object_entry(&it->pcache.oid, OBJ_TREE, NULL, 1);
1807 }
1808 else {
1809 struct tree_desc tree;
1810 init_tree_desc(&tree, it->pcache.tree_data, it->pcache.tree_size);
1811 add_pbase_object(&tree, name, cmplen, name);
1812 }
1813 }
1814 }
1815
1816 static void add_preferred_base(struct object_id *oid)
1817 {
1818 struct pbase_tree *it;
1819 void *data;
1820 unsigned long size;
1821 struct object_id tree_oid;
1822
1823 if (window <= num_preferred_base++)
1824 return;
1825
1826 data = read_object_with_reference(the_repository, oid,
1827 OBJ_TREE, &size, &tree_oid);
1828 if (!data)
1829 return;
1830
1831 for (it = pbase_tree; it; it = it->next) {
1832 if (oideq(&it->pcache.oid, &tree_oid)) {
1833 free(data);
1834 return;
1835 }
1836 }
1837
1838 CALLOC_ARRAY(it, 1);
1839 it->next = pbase_tree;
1840 pbase_tree = it;
1841
1842 oidcpy(&it->pcache.oid, &tree_oid);
1843 it->pcache.tree_data = data;
1844 it->pcache.tree_size = size;
1845 }
1846
1847 static void cleanup_preferred_base(void)
1848 {
1849 struct pbase_tree *it;
1850 unsigned i;
1851
1852 it = pbase_tree;
1853 pbase_tree = NULL;
1854 while (it) {
1855 struct pbase_tree *tmp = it;
1856 it = tmp->next;
1857 free(tmp->pcache.tree_data);
1858 free(tmp);
1859 }
1860
1861 for (i = 0; i < ARRAY_SIZE(pbase_tree_cache); i++) {
1862 if (!pbase_tree_cache[i])
1863 continue;
1864 free(pbase_tree_cache[i]->tree_data);
1865 FREE_AND_NULL(pbase_tree_cache[i]);
1866 }
1867
1868 FREE_AND_NULL(done_pbase_paths);
1869 done_pbase_paths_num = done_pbase_paths_alloc = 0;
1870 }
1871
1872 /*
1873 * Return 1 iff the object specified by "delta" can be sent
1874 * literally as a delta against the base in "base_sha1". If
1875 * so, then *base_out will point to the entry in our packing
1876 * list, or NULL if we must use the external-base list.
1877 *
1878 * Depth value does not matter - find_deltas() will
1879 * never consider reused delta as the base object to
1880 * deltify other objects against, in order to avoid
1881 * circular deltas.
1882 */
1883 static int can_reuse_delta(const struct object_id *base_oid,
1884 struct object_entry *delta,
1885 struct object_entry **base_out)
1886 {
1887 struct object_entry *base;
1888
1889 /*
1890 * First see if we're already sending the base (or it's explicitly in
1891 * our "excluded" list).
1892 */
1893 base = packlist_find(&to_pack, base_oid);
1894 if (base) {
1895 if (!in_same_island(&delta->idx.oid, &base->idx.oid))
1896 return 0;
1897 *base_out = base;
1898 return 1;
1899 }
1900
1901 /*
1902 * Otherwise, reachability bitmaps may tell us if the receiver has it,
1903 * even if it was buried too deep in history to make it into the
1904 * packing list.
1905 */
1906 if (thin && bitmap_has_oid_in_uninteresting(bitmap_git, base_oid)) {
1907 if (use_delta_islands) {
1908 if (!in_same_island(&delta->idx.oid, base_oid))
1909 return 0;
1910 }
1911 *base_out = NULL;
1912 return 1;
1913 }
1914
1915 return 0;
1916 }
1917
1918 static void prefetch_to_pack(uint32_t object_index_start) {
1919 struct oid_array to_fetch = OID_ARRAY_INIT;
1920 uint32_t i;
1921
1922 for (i = object_index_start; i < to_pack.nr_objects; i++) {
1923 struct object_entry *entry = to_pack.objects + i;
1924
1925 if (!oid_object_info_extended(the_repository,
1926 &entry->idx.oid,
1927 NULL,
1928 OBJECT_INFO_FOR_PREFETCH))
1929 continue;
1930 oid_array_append(&to_fetch, &entry->idx.oid);
1931 }
1932 promisor_remote_get_direct(the_repository,
1933 to_fetch.oid, to_fetch.nr);
1934 oid_array_clear(&to_fetch);
1935 }
1936
1937 static void check_object(struct object_entry *entry, uint32_t object_index)
1938 {
1939 unsigned long canonical_size;
1940 enum object_type type;
1941 struct object_info oi = {.typep = &type, .sizep = &canonical_size};
1942
1943 if (IN_PACK(entry)) {
1944 struct packed_git *p = IN_PACK(entry);
1945 struct pack_window *w_curs = NULL;
1946 int have_base = 0;
1947 struct object_id base_ref;
1948 struct object_entry *base_entry;
1949 unsigned long used, used_0;
1950 unsigned long avail;
1951 off_t ofs;
1952 unsigned char *buf, c;
1953 enum object_type type;
1954 unsigned long in_pack_size;
1955
1956 buf = use_pack(p, &w_curs, entry->in_pack_offset, &avail);
1957
1958 /*
1959 * We want in_pack_type even if we do not reuse delta
1960 * since non-delta representations could still be reused.
1961 */
1962 used = unpack_object_header_buffer(buf, avail,
1963 &type,
1964 &in_pack_size);
1965 if (used == 0)
1966 goto give_up;
1967
1968 if (type < 0)
1969 BUG("invalid type %d", type);
1970 entry->in_pack_type = type;
1971
1972 /*
1973 * Determine if this is a delta and if so whether we can
1974 * reuse it or not. Otherwise let's find out as cheaply as
1975 * possible what the actual type and size for this object is.
1976 */
1977 switch (entry->in_pack_type) {
1978 default:
1979 /* Not a delta hence we've already got all we need. */
1980 oe_set_type(entry, entry->in_pack_type);
1981 SET_SIZE(entry, in_pack_size);
1982 entry->in_pack_header_size = used;
1983 if (oe_type(entry) < OBJ_COMMIT || oe_type(entry) > OBJ_BLOB)
1984 goto give_up;
1985 unuse_pack(&w_curs);
1986 return;
1987 case OBJ_REF_DELTA:
1988 if (reuse_delta && !entry->preferred_base) {
1989 oidread(&base_ref,
1990 use_pack(p, &w_curs,
1991 entry->in_pack_offset + used,
1992 NULL));
1993 have_base = 1;
1994 }
1995 entry->in_pack_header_size = used + the_hash_algo->rawsz;
1996 break;
1997 case OBJ_OFS_DELTA:
1998 buf = use_pack(p, &w_curs,
1999 entry->in_pack_offset + used, NULL);
2000 used_0 = 0;
2001 c = buf[used_0++];
2002 ofs = c & 127;
2003 while (c & 128) {
2004 ofs += 1;
2005 if (!ofs || MSB(ofs, 7)) {
2006 error(_("delta base offset overflow in pack for %s"),
2007 oid_to_hex(&entry->idx.oid));
2008 goto give_up;
2009 }
2010 c = buf[used_0++];
2011 ofs = (ofs << 7) + (c & 127);
2012 }
2013 ofs = entry->in_pack_offset - ofs;
2014 if (ofs <= 0 || ofs >= entry->in_pack_offset) {
2015 error(_("delta base offset out of bound for %s"),
2016 oid_to_hex(&entry->idx.oid));
2017 goto give_up;
2018 }
2019 if (reuse_delta && !entry->preferred_base) {
2020 uint32_t pos;
2021 if (offset_to_pack_pos(p, ofs, &pos) < 0)
2022 goto give_up;
2023 if (!nth_packed_object_id(&base_ref, p,
2024 pack_pos_to_index(p, pos)))
2025 have_base = 1;
2026 }
2027 entry->in_pack_header_size = used + used_0;
2028 break;
2029 }
2030
2031 if (have_base &&
2032 can_reuse_delta(&base_ref, entry, &base_entry)) {
2033 oe_set_type(entry, entry->in_pack_type);
2034 SET_SIZE(entry, in_pack_size); /* delta size */
2035 SET_DELTA_SIZE(entry, in_pack_size);
2036
2037 if (base_entry) {
2038 SET_DELTA(entry, base_entry);
2039 entry->delta_sibling_idx = base_entry->delta_child_idx;
2040 SET_DELTA_CHILD(base_entry, entry);
2041 } else {
2042 SET_DELTA_EXT(entry, &base_ref);
2043 }
2044
2045 unuse_pack(&w_curs);
2046 return;
2047 }
2048
2049 if (oe_type(entry)) {
2050 off_t delta_pos;
2051
2052 /*
2053 * This must be a delta and we already know what the
2054 * final object type is. Let's extract the actual
2055 * object size from the delta header.
2056 */
2057 delta_pos = entry->in_pack_offset + entry->in_pack_header_size;
2058 canonical_size = get_size_from_delta(p, &w_curs, delta_pos);
2059 if (canonical_size == 0)
2060 goto give_up;
2061 SET_SIZE(entry, canonical_size);
2062 unuse_pack(&w_curs);
2063 return;
2064 }
2065
2066 /*
2067 * No choice but to fall back to the recursive delta walk
2068 * with oid_object_info() to find about the object type
2069 * at this point...
2070 */
2071 give_up:
2072 unuse_pack(&w_curs);
2073 }
2074
2075 if (oid_object_info_extended(the_repository, &entry->idx.oid, &oi,
2076 OBJECT_INFO_SKIP_FETCH_OBJECT | OBJECT_INFO_LOOKUP_REPLACE) < 0) {
2077 if (has_promisor_remote()) {
2078 prefetch_to_pack(object_index);
2079 if (oid_object_info_extended(the_repository, &entry->idx.oid, &oi,
2080 OBJECT_INFO_SKIP_FETCH_OBJECT | OBJECT_INFO_LOOKUP_REPLACE) < 0)
2081 type = -1;
2082 } else {
2083 type = -1;
2084 }
2085 }
2086 oe_set_type(entry, type);
2087 if (entry->type_valid) {
2088 SET_SIZE(entry, canonical_size);
2089 } else {
2090 /*
2091 * Bad object type is checked in prepare_pack(). This is
2092 * to permit a missing preferred base object to be ignored
2093 * as a preferred base. Doing so can result in a larger
2094 * pack file, but the transfer will still take place.
2095 */
2096 }
2097 }
2098
2099 static int pack_offset_sort(const void *_a, const void *_b)
2100 {
2101 const struct object_entry *a = *(struct object_entry **)_a;
2102 const struct object_entry *b = *(struct object_entry **)_b;
2103 const struct packed_git *a_in_pack = IN_PACK(a);
2104 const struct packed_git *b_in_pack = IN_PACK(b);
2105
2106 /* avoid filesystem trashing with loose objects */
2107 if (!a_in_pack && !b_in_pack)
2108 return oidcmp(&a->idx.oid, &b->idx.oid);
2109
2110 if (a_in_pack < b_in_pack)
2111 return -1;
2112 if (a_in_pack > b_in_pack)
2113 return 1;
2114 return a->in_pack_offset < b->in_pack_offset ? -1 :
2115 (a->in_pack_offset > b->in_pack_offset);
2116 }
2117
2118 /*
2119 * Drop an on-disk delta we were planning to reuse. Naively, this would
2120 * just involve blanking out the "delta" field, but we have to deal
2121 * with some extra book-keeping:
2122 *
2123 * 1. Removing ourselves from the delta_sibling linked list.
2124 *
2125 * 2. Updating our size/type to the non-delta representation. These were
2126 * either not recorded initially (size) or overwritten with the delta type
2127 * (type) when check_object() decided to reuse the delta.
2128 *
2129 * 3. Resetting our delta depth, as we are now a base object.
2130 */
2131 static void drop_reused_delta(struct object_entry *entry)
2132 {
2133 unsigned *idx = &to_pack.objects[entry->delta_idx - 1].delta_child_idx;
2134 struct object_info oi = OBJECT_INFO_INIT;
2135 enum object_type type;
2136 unsigned long size;
2137
2138 while (*idx) {
2139 struct object_entry *oe = &to_pack.objects[*idx - 1];
2140
2141 if (oe == entry)
2142 *idx = oe->delta_sibling_idx;
2143 else
2144 idx = &oe->delta_sibling_idx;
2145 }
2146 SET_DELTA(entry, NULL);
2147 entry->depth = 0;
2148
2149 oi.sizep = &size;
2150 oi.typep = &type;
2151 if (packed_object_info(the_repository, IN_PACK(entry), entry->in_pack_offset, &oi) < 0) {
2152 /*
2153 * We failed to get the info from this pack for some reason;
2154 * fall back to oid_object_info, which may find another copy.
2155 * And if that fails, the error will be recorded in oe_type(entry)
2156 * and dealt with in prepare_pack().
2157 */
2158 oe_set_type(entry,
2159 oid_object_info(the_repository, &entry->idx.oid, &size));
2160 } else {
2161 oe_set_type(entry, type);
2162 }
2163 SET_SIZE(entry, size);
2164 }
2165
2166 /*
2167 * Follow the chain of deltas from this entry onward, throwing away any links
2168 * that cause us to hit a cycle (as determined by the DFS state flags in
2169 * the entries).
2170 *
2171 * We also detect too-long reused chains that would violate our --depth
2172 * limit.
2173 */
2174 static void break_delta_chains(struct object_entry *entry)
2175 {
2176 /*
2177 * The actual depth of each object we will write is stored as an int,
2178 * as it cannot exceed our int "depth" limit. But before we break
2179 * changes based no that limit, we may potentially go as deep as the
2180 * number of objects, which is elsewhere bounded to a uint32_t.
2181 */
2182 uint32_t total_depth;
2183 struct object_entry *cur, *next;
2184
2185 for (cur = entry, total_depth = 0;
2186 cur;
2187 cur = DELTA(cur), total_depth++) {
2188 if (cur->dfs_state == DFS_DONE) {
2189 /*
2190 * We've already seen this object and know it isn't
2191 * part of a cycle. We do need to append its depth
2192 * to our count.
2193 */
2194 total_depth += cur->depth;
2195 break;
2196 }
2197
2198 /*
2199 * We break cycles before looping, so an ACTIVE state (or any
2200 * other cruft which made its way into the state variable)
2201 * is a bug.
2202 */
2203 if (cur->dfs_state != DFS_NONE)
2204 BUG("confusing delta dfs state in first pass: %d",
2205 cur->dfs_state);
2206
2207 /*
2208 * Now we know this is the first time we've seen the object. If
2209 * it's not a delta, we're done traversing, but we'll mark it
2210 * done to save time on future traversals.
2211 */
2212 if (!DELTA(cur)) {
2213 cur->dfs_state = DFS_DONE;
2214 break;
2215 }
2216
2217 /*
2218 * Mark ourselves as active and see if the next step causes
2219 * us to cycle to another active object. It's important to do
2220 * this _before_ we loop, because it impacts where we make the
2221 * cut, and thus how our total_depth counter works.
2222 * E.g., We may see a partial loop like:
2223 *
2224 * A -> B -> C -> D -> B
2225 *
2226 * Cutting B->C breaks the cycle. But now the depth of A is
2227 * only 1, and our total_depth counter is at 3. The size of the
2228 * error is always one less than the size of the cycle we
2229 * broke. Commits C and D were "lost" from A's chain.
2230 *
2231 * If we instead cut D->B, then the depth of A is correct at 3.
2232 * We keep all commits in the chain that we examined.
2233 */
2234 cur->dfs_state = DFS_ACTIVE;
2235 if (DELTA(cur)->dfs_state == DFS_ACTIVE) {
2236 drop_reused_delta(cur);
2237 cur->dfs_state = DFS_DONE;
2238 break;
2239 }
2240 }
2241
2242 /*
2243 * And now that we've gone all the way to the bottom of the chain, we
2244 * need to clear the active flags and set the depth fields as
2245 * appropriate. Unlike the loop above, which can quit when it drops a
2246 * delta, we need to keep going to look for more depth cuts. So we need
2247 * an extra "next" pointer to keep going after we reset cur->delta.
2248 */
2249 for (cur = entry; cur; cur = next) {
2250 next = DELTA(cur);
2251
2252 /*
2253 * We should have a chain of zero or more ACTIVE states down to
2254 * a final DONE. We can quit after the DONE, because either it
2255 * has no bases, or we've already handled them in a previous
2256 * call.
2257 */
2258 if (cur->dfs_state == DFS_DONE)
2259 break;
2260 else if (cur->dfs_state != DFS_ACTIVE)
2261 BUG("confusing delta dfs state in second pass: %d",
2262 cur->dfs_state);
2263
2264 /*
2265 * If the total_depth is more than depth, then we need to snip
2266 * the chain into two or more smaller chains that don't exceed
2267 * the maximum depth. Most of the resulting chains will contain
2268 * (depth + 1) entries (i.e., depth deltas plus one base), and
2269 * the last chain (i.e., the one containing entry) will contain
2270 * whatever entries are left over, namely
2271 * (total_depth % (depth + 1)) of them.
2272 *
2273 * Since we are iterating towards decreasing depth, we need to
2274 * decrement total_depth as we go, and we need to write to the
2275 * entry what its final depth will be after all of the
2276 * snipping. Since we're snipping into chains of length (depth
2277 * + 1) entries, the final depth of an entry will be its
2278 * original depth modulo (depth + 1). Any time we encounter an
2279 * entry whose final depth is supposed to be zero, we snip it
2280 * from its delta base, thereby making it so.
2281 */
2282 cur->depth = (total_depth--) % (depth + 1);
2283 if (!cur->depth)
2284 drop_reused_delta(cur);
2285
2286 cur->dfs_state = DFS_DONE;
2287 }
2288 }
2289
2290 static void get_object_details(void)
2291 {
2292 uint32_t i;
2293 struct object_entry **sorted_by_offset;
2294
2295 if (progress)
2296 progress_state = start_progress(_("Counting objects"),
2297 to_pack.nr_objects);
2298
2299 CALLOC_ARRAY(sorted_by_offset, to_pack.nr_objects);
2300 for (i = 0; i < to_pack.nr_objects; i++)
2301 sorted_by_offset[i] = to_pack.objects + i;
2302 QSORT(sorted_by_offset, to_pack.nr_objects, pack_offset_sort);
2303
2304 for (i = 0; i < to_pack.nr_objects; i++) {
2305 struct object_entry *entry = sorted_by_offset[i];
2306 check_object(entry, i);
2307 if (entry->type_valid &&
2308 oe_size_greater_than(&to_pack, entry, big_file_threshold))
2309 entry->no_try_delta = 1;
2310 display_progress(progress_state, i + 1);
2311 }
2312 stop_progress(&progress_state);
2313
2314 /*
2315 * This must happen in a second pass, since we rely on the delta
2316 * information for the whole list being completed.
2317 */
2318 for (i = 0; i < to_pack.nr_objects; i++)
2319 break_delta_chains(&to_pack.objects[i]);
2320
2321 free(sorted_by_offset);
2322 }
2323
2324 /*
2325 * We search for deltas in a list sorted by type, by filename hash, and then
2326 * by size, so that we see progressively smaller and smaller files.
2327 * That's because we prefer deltas to be from the bigger file
2328 * to the smaller -- deletes are potentially cheaper, but perhaps
2329 * more importantly, the bigger file is likely the more recent
2330 * one. The deepest deltas are therefore the oldest objects which are
2331 * less susceptible to be accessed often.
2332 */
2333 static int type_size_sort(const void *_a, const void *_b)
2334 {
2335 const struct object_entry *a = *(struct object_entry **)_a;
2336 const struct object_entry *b = *(struct object_entry **)_b;
2337 const enum object_type a_type = oe_type(a);
2338 const enum object_type b_type = oe_type(b);
2339 const unsigned long a_size = SIZE(a);
2340 const unsigned long b_size = SIZE(b);
2341
2342 if (a_type > b_type)
2343 return -1;
2344 if (a_type < b_type)
2345 return 1;
2346 if (a->hash > b->hash)
2347 return -1;
2348 if (a->hash < b->hash)
2349 return 1;
2350 if (a->preferred_base > b->preferred_base)
2351 return -1;
2352 if (a->preferred_base < b->preferred_base)
2353 return 1;
2354 if (use_delta_islands) {
2355 const int island_cmp = island_delta_cmp(&a->idx.oid, &b->idx.oid);
2356 if (island_cmp)
2357 return island_cmp;
2358 }
2359 if (a_size > b_size)
2360 return -1;
2361 if (a_size < b_size)
2362 return 1;
2363 return a < b ? -1 : (a > b); /* newest first */
2364 }
2365
2366 struct unpacked {
2367 struct object_entry *entry;
2368 void *data;
2369 struct delta_index *index;
2370 unsigned depth;
2371 };
2372
2373 static int delta_cacheable(unsigned long src_size, unsigned long trg_size,
2374 unsigned long delta_size)
2375 {
2376 if (max_delta_cache_size && delta_cache_size + delta_size > max_delta_cache_size)
2377 return 0;
2378
2379 if (delta_size < cache_max_small_delta_size)
2380 return 1;
2381
2382 /* cache delta, if objects are large enough compared to delta size */
2383 if ((src_size >> 20) + (trg_size >> 21) > (delta_size >> 10))
2384 return 1;
2385
2386 return 0;
2387 }
2388
2389 /* Protect delta_cache_size */
2390 static pthread_mutex_t cache_mutex;
2391 #define cache_lock() pthread_mutex_lock(&cache_mutex)
2392 #define cache_unlock() pthread_mutex_unlock(&cache_mutex)
2393
2394 /*
2395 * Protect object list partitioning (e.g. struct thread_param) and
2396 * progress_state
2397 */
2398 static pthread_mutex_t progress_mutex;
2399 #define progress_lock() pthread_mutex_lock(&progress_mutex)
2400 #define progress_unlock() pthread_mutex_unlock(&progress_mutex)
2401
2402 /*
2403 * Access to struct object_entry is unprotected since each thread owns
2404 * a portion of the main object list. Just don't access object entries
2405 * ahead in the list because they can be stolen and would need
2406 * progress_mutex for protection.
2407 */
2408
2409 static inline int oe_size_less_than(struct packing_data *pack,
2410 const struct object_entry *lhs,
2411 unsigned long rhs)
2412 {
2413 if (lhs->size_valid)
2414 return lhs->size_ < rhs;
2415 if (rhs < pack->oe_size_limit) /* rhs < 2^x <= lhs ? */
2416 return 0;
2417 return oe_get_size_slow(pack, lhs) < rhs;
2418 }
2419
2420 static inline void oe_set_tree_depth(struct packing_data *pack,
2421 struct object_entry *e,
2422 unsigned int tree_depth)
2423 {
2424 if (!pack->tree_depth)
2425 CALLOC_ARRAY(pack->tree_depth, pack->nr_alloc);
2426 pack->tree_depth[e - pack->objects] = tree_depth;
2427 }
2428
2429 /*
2430 * Return the size of the object without doing any delta
2431 * reconstruction (so non-deltas are true object sizes, but deltas
2432 * return the size of the delta data).
2433 */
2434 unsigned long oe_get_size_slow(struct packing_data *pack,
2435 const struct object_entry *e)
2436 {
2437 struct packed_git *p;
2438 struct pack_window *w_curs;
2439 unsigned char *buf;
2440 enum object_type type;
2441 unsigned long used, avail, size;
2442
2443 if (e->type_ != OBJ_OFS_DELTA && e->type_ != OBJ_REF_DELTA) {
2444 packing_data_lock(&to_pack);
2445 if (oid_object_info(the_repository, &e->idx.oid, &size) < 0)
2446 die(_("unable to get size of %s"),
2447 oid_to_hex(&e->idx.oid));
2448 packing_data_unlock(&to_pack);
2449 return size;
2450 }
2451
2452 p = oe_in_pack(pack, e);
2453 if (!p)
2454 BUG("when e->type is a delta, it must belong to a pack");
2455
2456 packing_data_lock(&to_pack);
2457 w_curs = NULL;
2458 buf = use_pack(p, &w_curs, e->in_pack_offset, &avail);
2459 used = unpack_object_header_buffer(buf, avail, &type, &size);
2460 if (used == 0)
2461 die(_("unable to parse object header of %s"),
2462 oid_to_hex(&e->idx.oid));
2463
2464 unuse_pack(&w_curs);
2465 packing_data_unlock(&to_pack);
2466 return size;
2467 }
2468
2469 static int try_delta(struct unpacked *trg, struct unpacked *src,
2470 unsigned max_depth, unsigned long *mem_usage)
2471 {
2472 struct object_entry *trg_entry = trg->entry;
2473 struct object_entry *src_entry = src->entry;
2474 unsigned long trg_size, src_size, delta_size, sizediff, max_size, sz;
2475 unsigned ref_depth;
2476 enum object_type type;
2477 void *delta_buf;
2478
2479 /* Don't bother doing diffs between different types */
2480 if (oe_type(trg_entry) != oe_type(src_entry))
2481 return -1;
2482
2483 /*
2484 * We do not bother to try a delta that we discarded on an
2485 * earlier try, but only when reusing delta data. Note that
2486 * src_entry that is marked as the preferred_base should always
2487 * be considered, as even if we produce a suboptimal delta against
2488 * it, we will still save the transfer cost, as we already know
2489 * the other side has it and we won't send src_entry at all.
2490 */
2491 if (reuse_delta && IN_PACK(trg_entry) &&
2492 IN_PACK(trg_entry) == IN_PACK(src_entry) &&
2493 !src_entry->preferred_base &&
2494 trg_entry->in_pack_type != OBJ_REF_DELTA &&
2495 trg_entry->in_pack_type != OBJ_OFS_DELTA)
2496 return 0;
2497
2498 /* Let's not bust the allowed depth. */
2499 if (src->depth >= max_depth)
2500 return 0;
2501
2502 /* Now some size filtering heuristics. */
2503 trg_size = SIZE(trg_entry);
2504 if (!DELTA(trg_entry)) {
2505 max_size = trg_size/2 - the_hash_algo->rawsz;
2506 ref_depth = 1;
2507 } else {
2508 max_size = DELTA_SIZE(trg_entry);
2509 ref_depth = trg->depth;
2510 }
2511 max_size = (uint64_t)max_size * (max_depth - src->depth) /
2512 (max_depth - ref_depth + 1);
2513 if (max_size == 0)
2514 return 0;
2515 src_size = SIZE(src_entry);
2516 sizediff = src_size < trg_size ? trg_size - src_size : 0;
2517 if (sizediff >= max_size)
2518 return 0;
2519 if (trg_size < src_size / 32)
2520 return 0;
2521
2522 if (!in_same_island(&trg->entry->idx.oid, &src->entry->idx.oid))
2523 return 0;
2524
2525 /* Load data if not already done */
2526 if (!trg->data) {
2527 packing_data_lock(&to_pack);
2528 trg->data = read_object_file(&trg_entry->idx.oid, &type, &sz);
2529 packing_data_unlock(&to_pack);
2530 if (!trg->data)
2531 die(_("object %s cannot be read"),
2532 oid_to_hex(&trg_entry->idx.oid));
2533 if (sz != trg_size)
2534 die(_("object %s inconsistent object length (%"PRIuMAX" vs %"PRIuMAX")"),
2535 oid_to_hex(&trg_entry->idx.oid), (uintmax_t)sz,
2536 (uintmax_t)trg_size);
2537 *mem_usage += sz;
2538 }
2539 if (!src->data) {
2540 packing_data_lock(&to_pack);
2541 src->data = read_object_file(&src_entry->idx.oid, &type, &sz);
2542 packing_data_unlock(&to_pack);
2543 if (!src->data) {
2544 if (src_entry->preferred_base) {
2545 static int warned = 0;
2546 if (!warned++)
2547 warning(_("object %s cannot be read"),
2548 oid_to_hex(&src_entry->idx.oid));
2549 /*
2550 * Those objects are not included in the
2551 * resulting pack. Be resilient and ignore
2552 * them if they can't be read, in case the
2553 * pack could be created nevertheless.
2554 */
2555 return 0;
2556 }
2557 die(_("object %s cannot be read"),
2558 oid_to_hex(&src_entry->idx.oid));
2559 }
2560 if (sz != src_size)
2561 die(_("object %s inconsistent object length (%"PRIuMAX" vs %"PRIuMAX")"),
2562 oid_to_hex(&src_entry->idx.oid), (uintmax_t)sz,
2563 (uintmax_t)src_size);
2564 *mem_usage += sz;
2565 }
2566 if (!src->index) {
2567 src->index = create_delta_index(src->data, src_size);
2568 if (!src->index) {
2569 static int warned = 0;
2570 if (!warned++)
2571 warning(_("suboptimal pack - out of memory"));
2572 return 0;
2573 }
2574 *mem_usage += sizeof_delta_index(src->index);
2575 }
2576
2577 delta_buf = create_delta(src->index, trg->data, trg_size, &delta_size, max_size);
2578 if (!delta_buf)
2579 return 0;
2580
2581 if (DELTA(trg_entry)) {
2582 /* Prefer only shallower same-sized deltas. */
2583 if (delta_size == DELTA_SIZE(trg_entry) &&
2584 src->depth + 1 >= trg->depth) {
2585 free(delta_buf);
2586 return 0;
2587 }
2588 }
2589
2590 /*
2591 * Handle memory allocation outside of the cache
2592 * accounting lock. Compiler will optimize the strangeness
2593 * away when NO_PTHREADS is defined.
2594 */
2595 free(trg_entry->delta_data);
2596 cache_lock();
2597 if (trg_entry->delta_data) {
2598 delta_cache_size -= DELTA_SIZE(trg_entry);
2599 trg_entry->delta_data = NULL;
2600 }
2601 if (delta_cacheable(src_size, trg_size, delta_size)) {
2602 delta_cache_size += delta_size;
2603 cache_unlock();
2604 trg_entry->delta_data = xrealloc(delta_buf, delta_size);
2605 } else {
2606 cache_unlock();
2607 free(delta_buf);
2608 }
2609
2610 SET_DELTA(trg_entry, src_entry);
2611 SET_DELTA_SIZE(trg_entry, delta_size);
2612 trg->depth = src->depth + 1;
2613
2614 return 1;
2615 }
2616
2617 static unsigned int check_delta_limit(struct object_entry *me, unsigned int n)
2618 {
2619 struct object_entry *child = DELTA_CHILD(me);
2620 unsigned int m = n;
2621 while (child) {
2622 const unsigned int c = check_delta_limit(child, n + 1);
2623 if (m < c)
2624 m = c;
2625 child = DELTA_SIBLING(child);
2626 }
2627 return m;
2628 }
2629
2630 static unsigned long free_unpacked(struct unpacked *n)
2631 {
2632 unsigned long freed_mem = sizeof_delta_index(n->index);
2633 free_delta_index(n->index);
2634 n->index = NULL;
2635 if (n->data) {
2636 freed_mem += SIZE(n->entry);
2637 FREE_AND_NULL(n->data);
2638 }
2639 n->entry = NULL;
2640 n->depth = 0;
2641 return freed_mem;
2642 }
2643
2644 static void find_deltas(struct object_entry **list, unsigned *list_size,
2645 int window, int depth, unsigned *processed)
2646 {
2647 uint32_t i, idx = 0, count = 0;
2648 struct unpacked *array;
2649 unsigned long mem_usage = 0;
2650
2651 CALLOC_ARRAY(array, window);
2652
2653 for (;;) {
2654 struct object_entry *entry;
2655 struct unpacked *n = array + idx;
2656 int j, max_depth, best_base = -1;
2657
2658 progress_lock();
2659 if (!*list_size) {
2660 progress_unlock();
2661 break;
2662 }
2663 entry = *list++;
2664 (*list_size)--;
2665 if (!entry->preferred_base) {
2666 (*processed)++;
2667 display_progress(progress_state, *processed);
2668 }
2669 progress_unlock();
2670
2671 mem_usage -= free_unpacked(n);
2672 n->entry = entry;
2673
2674 while (window_memory_limit &&
2675 mem_usage > window_memory_limit &&
2676 count > 1) {
2677 const uint32_t tail = (idx + window - count) % window;
2678 mem_usage -= free_unpacked(array + tail);
2679 count--;
2680 }
2681
2682 /* We do not compute delta to *create* objects we are not
2683 * going to pack.
2684 */
2685 if (entry->preferred_base)
2686 goto next;
2687
2688 /*
2689 * If the current object is at pack edge, take the depth the
2690 * objects that depend on the current object into account
2691 * otherwise they would become too deep.
2692 */
2693 max_depth = depth;
2694 if (DELTA_CHILD(entry)) {
2695 max_depth -= check_delta_limit(entry, 0);
2696 if (max_depth <= 0)
2697 goto next;
2698 }
2699
2700 j = window;
2701 while (--j > 0) {
2702 int ret;
2703 uint32_t other_idx = idx + j;
2704 struct unpacked *m;
2705 if (other_idx >= window)
2706 other_idx -= window;
2707 m = array + other_idx;
2708 if (!m->entry)
2709 break;
2710 ret = try_delta(n, m, max_depth, &mem_usage);
2711 if (ret < 0)
2712 break;
2713 else if (ret > 0)
2714 best_base = other_idx;
2715 }
2716
2717 /*
2718 * If we decided to cache the delta data, then it is best
2719 * to compress it right away. First because we have to do
2720 * it anyway, and doing it here while we're threaded will
2721 * save a lot of time in the non threaded write phase,
2722 * as well as allow for caching more deltas within
2723 * the same cache size limit.
2724 * ...
2725 * But only if not writing to stdout, since in that case
2726 * the network is most likely throttling writes anyway,
2727 * and therefore it is best to go to the write phase ASAP
2728 * instead, as we can afford spending more time compressing
2729 * between writes at that moment.
2730 */
2731 if (entry->delta_data && !pack_to_stdout) {
2732 unsigned long size;
2733
2734 size = do_compress(&entry->delta_data, DELTA_SIZE(entry));
2735 if (size < (1U << OE_Z_DELTA_BITS)) {
2736 entry->z_delta_size = size;
2737 cache_lock();
2738 delta_cache_size -= DELTA_SIZE(entry);
2739 delta_cache_size += entry->z_delta_size;
2740 cache_unlock();
2741 } else {
2742 FREE_AND_NULL(entry->delta_data);
2743 entry->z_delta_size = 0;
2744 }
2745 }
2746
2747 /* if we made n a delta, and if n is already at max
2748 * depth, leaving it in the window is pointless. we
2749 * should evict it first.
2750 */
2751 if (DELTA(entry) && max_depth <= n->depth)
2752 continue;
2753
2754 /*
2755 * Move the best delta base up in the window, after the
2756 * currently deltified object, to keep it longer. It will
2757 * be the first base object to be attempted next.
2758 */
2759 if (DELTA(entry)) {
2760 struct unpacked swap = array[best_base];
2761 int dist = (window + idx - best_base) % window;
2762 int dst = best_base;
2763 while (dist--) {
2764 int src = (dst + 1) % window;
2765 array[dst] = array[src];
2766 dst = src;
2767 }
2768 array[dst] = swap;
2769 }
2770
2771 next:
2772 idx++;
2773 if (count + 1 < window)
2774 count++;
2775 if (idx >= window)
2776 idx = 0;
2777 }
2778
2779 for (i = 0; i < window; ++i) {
2780 free_delta_index(array[i].index);
2781 free(array[i].data);
2782 }
2783 free(array);
2784 }
2785
2786 /*
2787 * The main object list is split into smaller lists, each is handed to
2788 * one worker.
2789 *
2790 * The main thread waits on the condition that (at least) one of the workers
2791 * has stopped working (which is indicated in the .working member of
2792 * struct thread_params).
2793 *
2794 * When a work thread has completed its work, it sets .working to 0 and
2795 * signals the main thread and waits on the condition that .data_ready
2796 * becomes 1.
2797 *
2798 * The main thread steals half of the work from the worker that has
2799 * most work left to hand it to the idle worker.
2800 */
2801
2802 struct thread_params {
2803 pthread_t thread;
2804 struct object_entry **list;
2805 unsigned list_size;
2806 unsigned remaining;
2807 int window;
2808 int depth;
2809 int working;
2810 int data_ready;
2811 pthread_mutex_t mutex;
2812 pthread_cond_t cond;
2813 unsigned *processed;
2814 };
2815
2816 static pthread_cond_t progress_cond;
2817
2818 /*
2819 * Mutex and conditional variable can't be statically-initialized on Windows.
2820 */
2821 static void init_threaded_search(void)
2822 {
2823 pthread_mutex_init(&cache_mutex, NULL);
2824 pthread_mutex_init(&progress_mutex, NULL);
2825 pthread_cond_init(&progress_cond, NULL);
2826 }
2827
2828 static void cleanup_threaded_search(void)
2829 {
2830 pthread_cond_destroy(&progress_cond);
2831 pthread_mutex_destroy(&cache_mutex);
2832 pthread_mutex_destroy(&progress_mutex);
2833 }
2834
2835 static void *threaded_find_deltas(void *arg)
2836 {
2837 struct thread_params *me = arg;
2838
2839 progress_lock();
2840 while (me->remaining) {
2841 progress_unlock();
2842
2843 find_deltas(me->list, &me->remaining,
2844 me->window, me->depth, me->processed);
2845
2846 progress_lock();
2847 me->working = 0;
2848 pthread_cond_signal(&progress_cond);
2849 progress_unlock();
2850
2851 /*
2852 * We must not set ->data_ready before we wait on the
2853 * condition because the main thread may have set it to 1
2854 * before we get here. In order to be sure that new
2855 * work is available if we see 1 in ->data_ready, it
2856 * was initialized to 0 before this thread was spawned
2857 * and we reset it to 0 right away.
2858 */
2859 pthread_mutex_lock(&me->mutex);
2860 while (!me->data_ready)
2861 pthread_cond_wait(&me->cond, &me->mutex);
2862 me->data_ready = 0;
2863 pthread_mutex_unlock(&me->mutex);
2864
2865 progress_lock();
2866 }
2867 progress_unlock();
2868 /* leave ->working 1 so that this doesn't get more work assigned */
2869 return NULL;
2870 }
2871
2872 static void ll_find_deltas(struct object_entry **list, unsigned list_size,
2873 int window, int depth, unsigned *processed)
2874 {
2875 struct thread_params *p;
2876 int i, ret, active_threads = 0;
2877
2878 init_threaded_search();
2879
2880 if (delta_search_threads <= 1) {
2881 find_deltas(list, &list_size, window, depth, processed);
2882 cleanup_threaded_search();
2883 return;
2884 }
2885 if (progress > pack_to_stdout)
2886 fprintf_ln(stderr, _("Delta compression using up to %d threads"),
2887 delta_search_threads);
2888 CALLOC_ARRAY(p, delta_search_threads);
2889
2890 /* Partition the work amongst work threads. */
2891 for (i = 0; i < delta_search_threads; i++) {
2892 unsigned sub_size = list_size / (delta_search_threads - i);
2893
2894 /* don't use too small segments or no deltas will be found */
2895 if (sub_size < 2*window && i+1 < delta_search_threads)
2896 sub_size = 0;
2897
2898 p[i].window = window;
2899 p[i].depth = depth;
2900 p[i].processed = processed;
2901 p[i].working = 1;
2902 p[i].data_ready = 0;
2903
2904 /* try to split chunks on "path" boundaries */
2905 while (sub_size && sub_size < list_size &&
2906 list[sub_size]->hash &&
2907 list[sub_size]->hash == list[sub_size-1]->hash)
2908 sub_size++;
2909
2910 p[i].list = list;
2911 p[i].list_size = sub_size;
2912 p[i].remaining = sub_size;
2913
2914 list += sub_size;
2915 list_size -= sub_size;
2916 }
2917
2918 /* Start work threads. */
2919 for (i = 0; i < delta_search_threads; i++) {
2920 if (!p[i].list_size)
2921 continue;
2922 pthread_mutex_init(&p[i].mutex, NULL);
2923 pthread_cond_init(&p[i].cond, NULL);
2924 ret = pthread_create(&p[i].thread, NULL,
2925 threaded_find_deltas, &p[i]);
2926 if (ret)
2927 die(_("unable to create thread: %s"), strerror(ret));
2928 active_threads++;
2929 }
2930
2931 /*
2932 * Now let's wait for work completion. Each time a thread is done
2933 * with its work, we steal half of the remaining work from the
2934 * thread with the largest number of unprocessed objects and give
2935 * it to that newly idle thread. This ensure good load balancing
2936 * until the remaining object list segments are simply too short
2937 * to be worth splitting anymore.
2938 */
2939 while (active_threads) {
2940 struct thread_params *target = NULL;
2941 struct thread_params *victim = NULL;
2942 unsigned sub_size = 0;
2943
2944 progress_lock();
2945 for (;;) {
2946 for (i = 0; !target && i < delta_search_threads; i++)
2947 if (!p[i].working)
2948 target = &p[i];
2949 if (target)
2950 break;
2951 pthread_cond_wait(&progress_cond, &progress_mutex);
2952 }
2953
2954 for (i = 0; i < delta_search_threads; i++)
2955 if (p[i].remaining > 2*window &&
2956 (!victim || victim->remaining < p[i].remaining))
2957 victim = &p[i];
2958 if (victim) {
2959 sub_size = victim->remaining / 2;
2960 list = victim->list + victim->list_size - sub_size;
2961 while (sub_size && list[0]->hash &&
2962 list[0]->hash == list[-1]->hash) {
2963 list++;
2964 sub_size--;
2965 }
2966 if (!sub_size) {
2967 /*
2968 * It is possible for some "paths" to have
2969 * so many objects that no hash boundary
2970 * might be found. Let's just steal the
2971 * exact half in that case.
2972 */
2973 sub_size = victim->remaining / 2;
2974 list -= sub_size;
2975 }
2976 target->list = list;
2977 victim->list_size -= sub_size;
2978 victim->remaining -= sub_size;
2979 }
2980 target->list_size = sub_size;
2981 target->remaining = sub_size;
2982 target->working = 1;
2983 progress_unlock();
2984
2985 pthread_mutex_lock(&target->mutex);
2986 target->data_ready = 1;
2987 pthread_cond_signal(&target->cond);
2988 pthread_mutex_unlock(&target->mutex);
2989
2990 if (!sub_size) {
2991 pthread_join(target->thread, NULL);
2992 pthread_cond_destroy(&target->cond);
2993 pthread_mutex_destroy(&target->mutex);
2994 active_threads--;
2995 }
2996 }
2997 cleanup_threaded_search();
2998 free(p);
2999 }
3000
3001 static int obj_is_packed(const struct object_id *oid)
3002 {
3003 return packlist_find(&to_pack, oid) ||
3004 (reuse_packfile_bitmap &&
3005 bitmap_walk_contains(bitmap_git, reuse_packfile_bitmap, oid));
3006 }
3007
3008 static void add_tag_chain(const struct object_id *oid)
3009 {
3010 struct tag *tag;
3011
3012 /*
3013 * We catch duplicates already in add_object_entry(), but we'd
3014 * prefer to do this extra check to avoid having to parse the
3015 * tag at all if we already know that it's being packed (e.g., if
3016 * it was included via bitmaps, we would not have parsed it
3017 * previously).
3018 */
3019 if (obj_is_packed(oid))
3020 return;
3021
3022 tag = lookup_tag(the_repository, oid);
3023 while (1) {
3024 if (!tag || parse_tag(tag) || !tag->tagged)
3025 die(_("unable to pack objects reachable from tag %s"),
3026 oid_to_hex(oid));
3027
3028 add_object_entry(&tag->object.oid, OBJ_TAG, NULL, 0);
3029
3030 if (tag->tagged->type != OBJ_TAG)
3031 return;
3032
3033 tag = (struct tag *)tag->tagged;
3034 }
3035 }
3036
3037 static int add_ref_tag(const char *tag UNUSED, const struct object_id *oid,
3038 int flag UNUSED, void *cb_data UNUSED)
3039 {
3040 struct object_id peeled;
3041
3042 if (!peel_iterated_oid(oid, &peeled) && obj_is_packed(&peeled))
3043 add_tag_chain(oid);
3044 return 0;
3045 }
3046
3047 static void prepare_pack(int window, int depth)
3048 {
3049 struct object_entry **delta_list;
3050 uint32_t i, nr_deltas;
3051 unsigned n;
3052
3053 if (use_delta_islands)
3054 resolve_tree_islands(the_repository, progress, &to_pack);
3055
3056 get_object_details();
3057
3058 /*
3059 * If we're locally repacking then we need to be doubly careful
3060 * from now on in order to make sure no stealth corruption gets
3061 * propagated to the new pack. Clients receiving streamed packs
3062 * should validate everything they get anyway so no need to incur
3063 * the additional cost here in that case.
3064 */
3065 if (!pack_to_stdout)
3066 do_check_packed_object_crc = 1;
3067
3068 if (!to_pack.nr_objects || !window || !depth)
3069 return;
3070
3071 ALLOC_ARRAY(delta_list, to_pack.nr_objects);
3072 nr_deltas = n = 0;
3073
3074 for (i = 0; i < to_pack.nr_objects; i++) {
3075 struct object_entry *entry = to_pack.objects + i;
3076
3077 if (DELTA(entry))
3078 /* This happens if we decided to reuse existing
3079 * delta from a pack. "reuse_delta &&" is implied.
3080 */
3081 continue;
3082
3083 if (!entry->type_valid ||
3084 oe_size_less_than(&to_pack, entry, 50))
3085 continue;
3086
3087 if (entry->no_try_delta)
3088 continue;
3089
3090 if (!entry->preferred_base) {
3091 nr_deltas++;
3092 if (oe_type(entry) < 0)
3093 die(_("unable to get type of object %s"),
3094 oid_to_hex(&entry->idx.oid));
3095 } else {
3096 if (oe_type(entry) < 0) {
3097 /*
3098 * This object is not found, but we
3099 * don't have to include it anyway.
3100 */
3101 continue;
3102 }
3103 }
3104
3105 delta_list[n++] = entry;
3106 }
3107
3108 if (nr_deltas && n > 1) {
3109 unsigned nr_done = 0;
3110
3111 if (progress)
3112 progress_state = start_progress(_("Compressing objects"),
3113 nr_deltas);
3114 QSORT(delta_list, n, type_size_sort);
3115 ll_find_deltas(delta_list, n, window+1, depth, &nr_done);
3116 stop_progress(&progress_state);
3117 if (nr_done != nr_deltas)
3118 die(_("inconsistency with delta count"));
3119 }
3120 free(delta_list);
3121 }
3122
3123 static int git_pack_config(const char *k, const char *v, void *cb)
3124 {
3125 if (!strcmp(k, "pack.window")) {
3126 window = git_config_int(k, v);
3127 return 0;
3128 }
3129 if (!strcmp(k, "pack.windowmemory")) {
3130 window_memory_limit = git_config_ulong(k, v);
3131 return 0;
3132 }
3133 if (!strcmp(k, "pack.depth")) {
3134 depth = git_config_int(k, v);
3135 return 0;
3136 }
3137 if (!strcmp(k, "pack.deltacachesize")) {
3138 max_delta_cache_size = git_config_int(k, v);
3139 return 0;
3140 }
3141 if (!strcmp(k, "pack.deltacachelimit")) {
3142 cache_max_small_delta_size = git_config_int(k, v);
3143 return 0;
3144 }
3145 if (!strcmp(k, "pack.writebitmaphashcache")) {
3146 if (git_config_bool(k, v))
3147 write_bitmap_options |= BITMAP_OPT_HASH_CACHE;
3148 else
3149 write_bitmap_options &= ~BITMAP_OPT_HASH_CACHE;
3150 }
3151
3152 if (!strcmp(k, "pack.writebitmaplookuptable")) {
3153 if (git_config_bool(k, v))
3154 write_bitmap_options |= BITMAP_OPT_LOOKUP_TABLE;
3155 else
3156 write_bitmap_options &= ~BITMAP_OPT_LOOKUP_TABLE;
3157 }
3158
3159 if (!strcmp(k, "pack.usebitmaps")) {
3160 use_bitmap_index_default = git_config_bool(k, v);
3161 return 0;
3162 }
3163 if (!strcmp(k, "pack.allowpackreuse")) {
3164 allow_pack_reuse = git_config_bool(k, v);
3165 return 0;
3166 }
3167 if (!strcmp(k, "pack.threads")) {
3168 delta_search_threads = git_config_int(k, v);
3169 if (delta_search_threads < 0)
3170 die(_("invalid number of threads specified (%d)"),
3171 delta_search_threads);
3172 if (!HAVE_THREADS && delta_search_threads != 1) {
3173 warning(_("no threads support, ignoring %s"), k);
3174 delta_search_threads = 0;
3175 }
3176 return 0;
3177 }
3178 if (!strcmp(k, "pack.indexversion")) {
3179 pack_idx_opts.version = git_config_int(k, v);
3180 if (pack_idx_opts.version > 2)
3181 die(_("bad pack.indexVersion=%"PRIu32),
3182 pack_idx_opts.version);
3183 return 0;
3184 }
3185 if (!strcmp(k, "pack.writereverseindex")) {
3186 if (git_config_bool(k, v))
3187 pack_idx_opts.flags |= WRITE_REV;
3188 else
3189 pack_idx_opts.flags &= ~WRITE_REV;
3190 return 0;
3191 }
3192 if (!strcmp(k, "uploadpack.blobpackfileuri")) {
3193 struct configured_exclusion *ex = xmalloc(sizeof(*ex));
3194 const char *oid_end, *pack_end;
3195 /*
3196 * Stores the pack hash. This is not a true object ID, but is
3197 * of the same form.
3198 */
3199 struct object_id pack_hash;
3200
3201 if (parse_oid_hex(v, &ex->e.oid, &oid_end) ||
3202 *oid_end != ' ' ||
3203 parse_oid_hex(oid_end + 1, &pack_hash, &pack_end) ||
3204 *pack_end != ' ')
3205 die(_("value of uploadpack.blobpackfileuri must be "
3206 "of the form '<object-hash> <pack-hash> <uri>' (got '%s')"), v);
3207 if (oidmap_get(&configured_exclusions, &ex->e.oid))
3208 die(_("object already configured in another "
3209 "uploadpack.blobpackfileuri (got '%s')"), v);
3210 ex->pack_hash_hex = xcalloc(1, pack_end - oid_end);
3211 memcpy(ex->pack_hash_hex, oid_end + 1, pack_end - oid_end - 1);
3212 ex->uri = xstrdup(pack_end + 1);
3213 oidmap_put(&configured_exclusions, ex);
3214 }
3215 return git_default_config(k, v, cb);
3216 }
3217
3218 /* Counters for trace2 output when in --stdin-packs mode. */
3219 static int stdin_packs_found_nr;
3220 static int stdin_packs_hints_nr;
3221
3222 static int add_object_entry_from_pack(const struct object_id *oid,
3223 struct packed_git *p,
3224 uint32_t pos,
3225 void *_data)
3226 {
3227 off_t ofs;
3228 enum object_type type = OBJ_NONE;
3229
3230 display_progress(progress_state, ++nr_seen);
3231
3232 if (have_duplicate_entry(oid, 0))
3233 return 0;
3234
3235 ofs = nth_packed_object_offset(p, pos);
3236 if (!want_object_in_pack(oid, 0, &p, &ofs))
3237 return 0;
3238
3239 if (p) {
3240 struct rev_info *revs = _data;
3241 struct object_info oi = OBJECT_INFO_INIT;
3242
3243 oi.typep = &type;
3244 if (packed_object_info(the_repository, p, ofs, &oi) < 0) {
3245 die(_("could not get type of object %s in pack %s"),
3246 oid_to_hex(oid), p->pack_name);
3247 } else if (type == OBJ_COMMIT) {
3248 /*
3249 * commits in included packs are used as starting points for the
3250 * subsequent revision walk
3251 */
3252 add_pending_oid(revs, NULL, oid, 0);
3253 }
3254
3255 stdin_packs_found_nr++;
3256 }
3257
3258 create_object_entry(oid, type, 0, 0, 0, p, ofs);
3259
3260 return 0;
3261 }
3262
3263 static void show_commit_pack_hint(struct commit *commit, void *_data)
3264 {
3265 /* nothing to do; commits don't have a namehash */
3266 }
3267
3268 static void show_object_pack_hint(struct object *object, const char *name,
3269 void *_data)
3270 {
3271 struct object_entry *oe = packlist_find(&to_pack, &object->oid);
3272 if (!oe)
3273 return;
3274
3275 /*
3276 * Our 'to_pack' list was constructed by iterating all objects packed in
3277 * included packs, and so doesn't have a non-zero hash field that you
3278 * would typically pick up during a reachability traversal.
3279 *
3280 * Make a best-effort attempt to fill in the ->hash and ->no_try_delta
3281 * here using a now in order to perhaps improve the delta selection
3282 * process.
3283 */
3284 oe->hash = pack_name_hash(name);
3285 oe->no_try_delta = name && no_try_delta(name);
3286
3287 stdin_packs_hints_nr++;
3288 }
3289
3290 static int pack_mtime_cmp(const void *_a, const void *_b)
3291 {
3292 struct packed_git *a = ((const struct string_list_item*)_a)->util;
3293 struct packed_git *b = ((const struct string_list_item*)_b)->util;
3294
3295 /*
3296 * order packs by descending mtime so that objects are laid out
3297 * roughly as newest-to-oldest
3298 */
3299 if (a->mtime < b->mtime)
3300 return 1;
3301 else if (b->mtime < a->mtime)
3302 return -1;
3303 else
3304 return 0;
3305 }
3306
3307 static void read_packs_list_from_stdin(void)
3308 {
3309 struct strbuf buf = STRBUF_INIT;
3310 struct string_list include_packs = STRING_LIST_INIT_DUP;
3311 struct string_list exclude_packs = STRING_LIST_INIT_DUP;
3312 struct string_list_item *item = NULL;
3313
3314 struct packed_git *p;
3315 struct rev_info revs;
3316
3317 repo_init_revisions(the_repository, &revs, NULL);
3318 /*
3319 * Use a revision walk to fill in the namehash of objects in the include
3320 * packs. To save time, we'll avoid traversing through objects that are
3321 * in excluded packs.
3322 *
3323 * That may cause us to avoid populating all of the namehash fields of
3324 * all included objects, but our goal is best-effort, since this is only
3325 * an optimization during delta selection.
3326 */
3327 revs.no_kept_objects = 1;
3328 revs.keep_pack_cache_flags |= IN_CORE_KEEP_PACKS;
3329 revs.blob_objects = 1;
3330 revs.tree_objects = 1;
3331 revs.tag_objects = 1;
3332 revs.ignore_missing_links = 1;
3333
3334 while (strbuf_getline(&buf, stdin) != EOF) {
3335 if (!buf.len)
3336 continue;
3337
3338 if (*buf.buf == '^')
3339 string_list_append(&exclude_packs, buf.buf + 1);
3340 else
3341 string_list_append(&include_packs, buf.buf);
3342
3343 strbuf_reset(&buf);
3344 }
3345
3346 string_list_sort(&include_packs);
3347 string_list_sort(&exclude_packs);
3348
3349 for (p = get_all_packs(the_repository); p; p = p->next) {
3350 const char *pack_name = pack_basename(p);
3351
3352 item = string_list_lookup(&include_packs, pack_name);
3353 if (!item)
3354 item = string_list_lookup(&exclude_packs, pack_name);
3355
3356 if (item)
3357 item->util = p;
3358 }
3359
3360 /*
3361 * Arguments we got on stdin may not even be packs. First
3362 * check that to avoid segfaulting later on in
3363 * e.g. pack_mtime_cmp(), excluded packs are handled below.
3364 *
3365 * Since we first parsed our STDIN and then sorted the input
3366 * lines the pack we error on will be whatever line happens to
3367 * sort first. This is lazy, it's enough that we report one
3368 * bad case here, we don't need to report the first/last one,
3369 * or all of them.
3370 */
3371 for_each_string_list_item(item, &include_packs) {
3372 struct packed_git *p = item->util;
3373 if (!p)
3374 die(_("could not find pack '%s'"), item->string);
3375 if (!is_pack_valid(p))
3376 die(_("packfile %s cannot be accessed"), p->pack_name);
3377 }
3378
3379 /*
3380 * Then, handle all of the excluded packs, marking them as
3381 * kept in-core so that later calls to add_object_entry()
3382 * discards any objects that are also found in excluded packs.
3383 */
3384 for_each_string_list_item(item, &exclude_packs) {
3385 struct packed_git *p = item->util;
3386 if (!p)
3387 die(_("could not find pack '%s'"), item->string);
3388 p->pack_keep_in_core = 1;
3389 }
3390
3391 /*
3392 * Order packs by ascending mtime; use QSORT directly to access the
3393 * string_list_item's ->util pointer, which string_list_sort() does not
3394 * provide.
3395 */
3396 QSORT(include_packs.items, include_packs.nr, pack_mtime_cmp);
3397
3398 for_each_string_list_item(item, &include_packs) {
3399 struct packed_git *p = item->util;
3400 for_each_object_in_pack(p,
3401 add_object_entry_from_pack,
3402 &revs,
3403 FOR_EACH_OBJECT_PACK_ORDER);
3404 }
3405
3406 if (prepare_revision_walk(&revs))
3407 die(_("revision walk setup failed"));
3408 traverse_commit_list(&revs,
3409 show_commit_pack_hint,
3410 show_object_pack_hint,
3411 NULL);
3412
3413 trace2_data_intmax("pack-objects", the_repository, "stdin_packs_found",
3414 stdin_packs_found_nr);
3415 trace2_data_intmax("pack-objects", the_repository, "stdin_packs_hints",
3416 stdin_packs_hints_nr);
3417
3418 strbuf_release(&buf);
3419 string_list_clear(&include_packs, 0);
3420 string_list_clear(&exclude_packs, 0);
3421 }
3422
3423 static void add_cruft_object_entry(const struct object_id *oid, enum object_type type,
3424 struct packed_git *pack, off_t offset,
3425 const char *name, uint32_t mtime)
3426 {
3427 struct object_entry *entry;
3428
3429 display_progress(progress_state, ++nr_seen);
3430
3431 entry = packlist_find(&to_pack, oid);
3432 if (entry) {
3433 if (name) {
3434 entry->hash = pack_name_hash(name);
3435 entry->no_try_delta = no_try_delta(name);
3436 }
3437 } else {
3438 if (!want_object_in_pack(oid, 0, &pack, &offset))
3439 return;
3440 if (!pack && type == OBJ_BLOB && !has_loose_object(oid)) {
3441 /*
3442 * If a traversed tree has a missing blob then we want
3443 * to avoid adding that missing object to our pack.
3444 *
3445 * This only applies to missing blobs, not trees,
3446 * because the traversal needs to parse sub-trees but
3447 * not blobs.
3448 *
3449 * Note we only perform this check when we couldn't
3450 * already find the object in a pack, so we're really
3451 * limited to "ensure non-tip blobs which don't exist in
3452 * packs do exist via loose objects". Confused?
3453 */
3454 return;
3455 }
3456
3457 entry = create_object_entry(oid, type, pack_name_hash(name),
3458 0, name && no_try_delta(name),
3459 pack, offset);
3460 }
3461
3462 if (mtime > oe_cruft_mtime(&to_pack, entry))
3463 oe_set_cruft_mtime(&to_pack, entry, mtime);
3464 return;
3465 }
3466
3467 static void show_cruft_object(struct object *obj, const char *name, void *data)
3468 {
3469 /*
3470 * if we did not record it earlier, it's at least as old as our
3471 * expiration value. Rather than find it exactly, just use that
3472 * value. This may bump it forward from its real mtime, but it
3473 * will still be "too old" next time we run with the same
3474 * expiration.
3475 *
3476 * if obj does appear in the packing list, this call is a noop (or may
3477 * set the namehash).
3478 */
3479 add_cruft_object_entry(&obj->oid, obj->type, NULL, 0, name, cruft_expiration);
3480 }
3481
3482 static void show_cruft_commit(struct commit *commit, void *data)
3483 {
3484 show_cruft_object((struct object*)commit, NULL, data);
3485 }
3486
3487 static int cruft_include_check_obj(struct object *obj, void *data)
3488 {
3489 return !has_object_kept_pack(&obj->oid, IN_CORE_KEEP_PACKS);
3490 }
3491
3492 static int cruft_include_check(struct commit *commit, void *data)
3493 {
3494 return cruft_include_check_obj((struct object*)commit, data);
3495 }
3496
3497 static void set_cruft_mtime(const struct object *object,
3498 struct packed_git *pack,
3499 off_t offset, time_t mtime)
3500 {
3501 add_cruft_object_entry(&object->oid, object->type, pack, offset, NULL,
3502 mtime);
3503 }
3504
3505 static void mark_pack_kept_in_core(struct string_list *packs, unsigned keep)
3506 {
3507 struct string_list_item *item = NULL;
3508 for_each_string_list_item(item, packs) {
3509 struct packed_git *p = item->util;
3510 if (!p)
3511 die(_("could not find pack '%s'"), item->string);
3512 p->pack_keep_in_core = keep;
3513 }
3514 }
3515
3516 static void add_unreachable_loose_objects(void);
3517 static void add_objects_in_unpacked_packs(void);
3518
3519 static void enumerate_cruft_objects(void)
3520 {
3521 if (progress)
3522 progress_state = start_progress(_("Enumerating cruft objects"), 0);
3523
3524 add_objects_in_unpacked_packs();
3525 add_unreachable_loose_objects();
3526
3527 stop_progress(&progress_state);
3528 }
3529
3530 static void enumerate_and_traverse_cruft_objects(struct string_list *fresh_packs)
3531 {
3532 struct packed_git *p;
3533 struct rev_info revs;
3534 int ret;
3535
3536 repo_init_revisions(the_repository, &revs, NULL);
3537
3538 revs.tag_objects = 1;
3539 revs.tree_objects = 1;
3540 revs.blob_objects = 1;
3541
3542 revs.include_check = cruft_include_check;
3543 revs.include_check_obj = cruft_include_check_obj;
3544
3545 revs.ignore_missing_links = 1;
3546
3547 if (progress)
3548 progress_state = start_progress(_("Enumerating cruft objects"), 0);
3549 ret = add_unseen_recent_objects_to_traversal(&revs, cruft_expiration,
3550 set_cruft_mtime, 1);
3551 stop_progress(&progress_state);
3552
3553 if (ret)
3554 die(_("unable to add cruft objects"));
3555
3556 /*
3557 * Re-mark only the fresh packs as kept so that objects in
3558 * unknown packs do not halt the reachability traversal early.
3559 */
3560 for (p = get_all_packs(the_repository); p; p = p->next)
3561 p->pack_keep_in_core = 0;
3562 mark_pack_kept_in_core(fresh_packs, 1);
3563
3564 if (prepare_revision_walk(&revs))
3565 die(_("revision walk setup failed"));
3566 if (progress)
3567 progress_state = start_progress(_("Traversing cruft objects"), 0);
3568 nr_seen = 0;
3569 traverse_commit_list(&revs, show_cruft_commit, show_cruft_object, NULL);
3570
3571 stop_progress(&progress_state);
3572 }
3573
3574 static void read_cruft_objects(void)
3575 {
3576 struct strbuf buf = STRBUF_INIT;
3577 struct string_list discard_packs = STRING_LIST_INIT_DUP;
3578 struct string_list fresh_packs = STRING_LIST_INIT_DUP;
3579 struct packed_git *p;
3580
3581 ignore_packed_keep_in_core = 1;
3582
3583 while (strbuf_getline(&buf, stdin) != EOF) {
3584 if (!buf.len)
3585 continue;
3586
3587 if (*buf.buf == '-')
3588 string_list_append(&discard_packs, buf.buf + 1);
3589 else
3590 string_list_append(&fresh_packs, buf.buf);
3591 strbuf_reset(&buf);
3592 }
3593
3594 string_list_sort(&discard_packs);
3595 string_list_sort(&fresh_packs);
3596
3597 for (p = get_all_packs(the_repository); p; p = p->next) {
3598 const char *pack_name = pack_basename(p);
3599 struct string_list_item *item;
3600
3601 item = string_list_lookup(&fresh_packs, pack_name);
3602 if (!item)
3603 item = string_list_lookup(&discard_packs, pack_name);
3604
3605 if (item) {
3606 item->util = p;
3607 } else {
3608 /*
3609 * This pack wasn't mentioned in either the "fresh" or
3610 * "discard" list, so the caller didn't know about it.
3611 *
3612 * Mark it as kept so that its objects are ignored by
3613 * add_unseen_recent_objects_to_traversal(). We'll
3614 * unmark it before starting the traversal so it doesn't
3615 * halt the traversal early.
3616 */
3617 p->pack_keep_in_core = 1;
3618 }
3619 }
3620
3621 mark_pack_kept_in_core(&fresh_packs, 1);
3622 mark_pack_kept_in_core(&discard_packs, 0);
3623
3624 if (cruft_expiration)
3625 enumerate_and_traverse_cruft_objects(&fresh_packs);
3626 else
3627 enumerate_cruft_objects();
3628
3629 strbuf_release(&buf);
3630 string_list_clear(&discard_packs, 0);
3631 string_list_clear(&fresh_packs, 0);
3632 }
3633
3634 static void read_object_list_from_stdin(void)
3635 {
3636 char line[GIT_MAX_HEXSZ + 1 + PATH_MAX + 2];
3637 struct object_id oid;
3638 const char *p;
3639
3640 for (;;) {
3641 if (!fgets(line, sizeof(line), stdin)) {
3642 if (feof(stdin))
3643 break;
3644 if (!ferror(stdin))
3645 BUG("fgets returned NULL, not EOF, not error!");
3646 if (errno != EINTR)
3647 die_errno("fgets");
3648 clearerr(stdin);
3649 continue;
3650 }
3651 if (line[0] == '-') {
3652 if (get_oid_hex(line+1, &oid))
3653 die(_("expected edge object ID, got garbage:\n %s"),
3654 line);
3655 add_preferred_base(&oid);
3656 continue;
3657 }
3658 if (parse_oid_hex(line, &oid, &p))
3659 die(_("expected object ID, got garbage:\n %s"), line);
3660
3661 add_preferred_base_object(p + 1);
3662 add_object_entry(&oid, OBJ_NONE, p + 1, 0);
3663 }
3664 }
3665
3666 static void show_commit(struct commit *commit, void *data)
3667 {
3668 add_object_entry(&commit->object.oid, OBJ_COMMIT, NULL, 0);
3669
3670 if (write_bitmap_index)
3671 index_commit_for_bitmap(commit);
3672
3673 if (use_delta_islands)
3674 propagate_island_marks(commit);
3675 }
3676
3677 static void show_object(struct object *obj, const char *name, void *data)
3678 {
3679 add_preferred_base_object(name);
3680 add_object_entry(&obj->oid, obj->type, name, 0);
3681
3682 if (use_delta_islands) {
3683 const char *p;
3684 unsigned depth;
3685 struct object_entry *ent;
3686
3687 /* the empty string is a root tree, which is depth 0 */
3688 depth = *name ? 1 : 0;
3689 for (p = strchr(name, '/'); p; p = strchr(p + 1, '/'))
3690 depth++;
3691
3692 ent = packlist_find(&to_pack, &obj->oid);
3693 if (ent && depth > oe_tree_depth(&to_pack, ent))
3694 oe_set_tree_depth(&to_pack, ent, depth);
3695 }
3696 }
3697
3698 static void show_object__ma_allow_any(struct object *obj, const char *name, void *data)
3699 {
3700 assert(arg_missing_action == MA_ALLOW_ANY);
3701
3702 /*
3703 * Quietly ignore ALL missing objects. This avoids problems with
3704 * staging them now and getting an odd error later.
3705 */
3706 if (!has_object(the_repository, &obj->oid, 0))
3707 return;
3708
3709 show_object(obj, name, data);
3710 }
3711
3712 static void show_object__ma_allow_promisor(struct object *obj, const char *name, void *data)
3713 {
3714 assert(arg_missing_action == MA_ALLOW_PROMISOR);
3715
3716 /*
3717 * Quietly ignore EXPECTED missing objects. This avoids problems with
3718 * staging them now and getting an odd error later.
3719 */
3720 if (!has_object(the_repository, &obj->oid, 0) && is_promisor_object(&obj->oid))
3721 return;
3722
3723 show_object(obj, name, data);
3724 }
3725
3726 static int option_parse_missing_action(const struct option *opt,
3727 const char *arg, int unset)
3728 {
3729 assert(arg);
3730 assert(!unset);
3731
3732 if (!strcmp(arg, "error")) {
3733 arg_missing_action = MA_ERROR;
3734 fn_show_object = show_object;
3735 return 0;
3736 }
3737
3738 if (!strcmp(arg, "allow-any")) {
3739 arg_missing_action = MA_ALLOW_ANY;
3740 fetch_if_missing = 0;
3741 fn_show_object = show_object__ma_allow_any;
3742 return 0;
3743 }
3744
3745 if (!strcmp(arg, "allow-promisor")) {
3746 arg_missing_action = MA_ALLOW_PROMISOR;
3747 fetch_if_missing = 0;
3748 fn_show_object = show_object__ma_allow_promisor;
3749 return 0;
3750 }
3751
3752 die(_("invalid value for '%s': '%s'"), "--missing", arg);
3753 return 0;
3754 }
3755
3756 static void show_edge(struct commit *commit)
3757 {
3758 add_preferred_base(&commit->object.oid);
3759 }
3760
3761 static int add_object_in_unpacked_pack(const struct object_id *oid,
3762 struct packed_git *pack,
3763 uint32_t pos,
3764 void *_data)
3765 {
3766 if (cruft) {
3767 off_t offset;
3768 time_t mtime;
3769
3770 if (pack->is_cruft) {
3771 if (load_pack_mtimes(pack) < 0)
3772 die(_("could not load cruft pack .mtimes"));
3773 mtime = nth_packed_mtime(pack, pos);
3774 } else {
3775 mtime = pack->mtime;
3776 }
3777 offset = nth_packed_object_offset(pack, pos);
3778
3779 add_cruft_object_entry(oid, OBJ_NONE, pack, offset,
3780 NULL, mtime);
3781 } else {
3782 add_object_entry(oid, OBJ_NONE, "", 0);
3783 }
3784 return 0;
3785 }
3786
3787 static void add_objects_in_unpacked_packs(void)
3788 {
3789 if (for_each_packed_object(add_object_in_unpacked_pack, NULL,
3790 FOR_EACH_OBJECT_PACK_ORDER |
3791 FOR_EACH_OBJECT_LOCAL_ONLY |
3792 FOR_EACH_OBJECT_SKIP_IN_CORE_KEPT_PACKS |
3793 FOR_EACH_OBJECT_SKIP_ON_DISK_KEPT_PACKS))
3794 die(_("cannot open pack index"));
3795 }
3796
3797 static int add_loose_object(const struct object_id *oid, const char *path,
3798 void *data)
3799 {
3800 enum object_type type = oid_object_info(the_repository, oid, NULL);
3801
3802 if (type < 0) {
3803 warning(_("loose object at %s could not be examined"), path);
3804 return 0;
3805 }
3806
3807 if (cruft) {
3808 struct stat st;
3809 if (stat(path, &st) < 0) {
3810 if (errno == ENOENT)
3811 return 0;
3812 return error_errno("unable to stat %s", oid_to_hex(oid));
3813 }
3814
3815 add_cruft_object_entry(oid, type, NULL, 0, NULL,
3816 st.st_mtime);
3817 } else {
3818 add_object_entry(oid, type, "", 0);
3819 }
3820 return 0;
3821 }
3822
3823 /*
3824 * We actually don't even have to worry about reachability here.
3825 * add_object_entry will weed out duplicates, so we just add every
3826 * loose object we find.
3827 */
3828 static void add_unreachable_loose_objects(void)
3829 {
3830 for_each_loose_file_in_objdir(get_object_directory(),
3831 add_loose_object,
3832 NULL, NULL, NULL);
3833 }
3834
3835 static int has_sha1_pack_kept_or_nonlocal(const struct object_id *oid)
3836 {
3837 static struct packed_git *last_found = (void *)1;
3838 struct packed_git *p;
3839
3840 p = (last_found != (void *)1) ? last_found :
3841 get_all_packs(the_repository);
3842
3843 while (p) {
3844 if ((!p->pack_local || p->pack_keep ||
3845 p->pack_keep_in_core) &&
3846 find_pack_entry_one(oid->hash, p)) {
3847 last_found = p;
3848 return 1;
3849 }
3850 if (p == last_found)
3851 p = get_all_packs(the_repository);
3852 else
3853 p = p->next;
3854 if (p == last_found)
3855 p = p->next;
3856 }
3857 return 0;
3858 }
3859
3860 /*
3861 * Store a list of sha1s that are should not be discarded
3862 * because they are either written too recently, or are
3863 * reachable from another object that was.
3864 *
3865 * This is filled by get_object_list.
3866 */
3867 static struct oid_array recent_objects;
3868
3869 static int loosened_object_can_be_discarded(const struct object_id *oid,
3870 timestamp_t mtime)
3871 {
3872 if (!unpack_unreachable_expiration)
3873 return 0;
3874 if (mtime > unpack_unreachable_expiration)
3875 return 0;
3876 if (oid_array_lookup(&recent_objects, oid) >= 0)
3877 return 0;
3878 return 1;
3879 }
3880
3881 static void loosen_unused_packed_objects(void)
3882 {
3883 struct packed_git *p;
3884 uint32_t i;
3885 uint32_t loosened_objects_nr = 0;
3886 struct object_id oid;
3887
3888 for (p = get_all_packs(the_repository); p; p = p->next) {
3889 if (!p->pack_local || p->pack_keep || p->pack_keep_in_core)
3890 continue;
3891
3892 if (open_pack_index(p))
3893 die(_("cannot open pack index"));
3894
3895 for (i = 0; i < p->num_objects; i++) {
3896 nth_packed_object_id(&oid, p, i);
3897 if (!packlist_find(&to_pack, &oid) &&
3898 !has_sha1_pack_kept_or_nonlocal(&oid) &&
3899 !loosened_object_can_be_discarded(&oid, p->mtime)) {
3900 if (force_object_loose(&oid, p->mtime))
3901 die(_("unable to force loose object"));
3902 loosened_objects_nr++;
3903 }
3904 }
3905 }
3906
3907 trace2_data_intmax("pack-objects", the_repository,
3908 "loosen_unused_packed_objects/loosened", loosened_objects_nr);
3909 }
3910
3911 /*
3912 * This tracks any options which pack-reuse code expects to be on, or which a
3913 * reader of the pack might not understand, and which would therefore prevent
3914 * blind reuse of what we have on disk.
3915 */
3916 static int pack_options_allow_reuse(void)
3917 {
3918 return allow_pack_reuse &&
3919 pack_to_stdout &&
3920 !ignore_packed_keep_on_disk &&
3921 !ignore_packed_keep_in_core &&
3922 (!local || !have_non_local_packs) &&
3923 !incremental;
3924 }
3925
3926 static int get_object_list_from_bitmap(struct rev_info *revs)
3927 {
3928 if (!(bitmap_git = prepare_bitmap_walk(revs, 0)))
3929 return -1;
3930
3931 if (pack_options_allow_reuse() &&
3932 !reuse_partial_packfile_from_bitmap(
3933 bitmap_git,
3934 &reuse_packfile,
3935 &reuse_packfile_objects,
3936 &reuse_packfile_bitmap)) {
3937 assert(reuse_packfile_objects);
3938 nr_result += reuse_packfile_objects;
3939 nr_seen += reuse_packfile_objects;
3940 display_progress(progress_state, nr_seen);
3941 }
3942
3943 traverse_bitmap_commit_list(bitmap_git, revs,
3944 &add_object_entry_from_bitmap);
3945 return 0;
3946 }
3947
3948 static void record_recent_object(struct object *obj,
3949 const char *name,
3950 void *data)
3951 {
3952 oid_array_append(&recent_objects, &obj->oid);
3953 }
3954
3955 static void record_recent_commit(struct commit *commit, void *data)
3956 {
3957 oid_array_append(&recent_objects, &commit->object.oid);
3958 }
3959
3960 static int mark_bitmap_preferred_tip(const char *refname,
3961 const struct object_id *oid,
3962 int flags UNUSED,
3963 void *data UNUSED)
3964 {
3965 struct object_id peeled;
3966 struct object *object;
3967
3968 if (!peel_iterated_oid(oid, &peeled))
3969 oid = &peeled;
3970
3971 object = parse_object_or_die(oid, refname);
3972 if (object->type == OBJ_COMMIT)
3973 object->flags |= NEEDS_BITMAP;
3974
3975 return 0;
3976 }
3977
3978 static void mark_bitmap_preferred_tips(void)
3979 {
3980 struct string_list_item *item;
3981 const struct string_list *preferred_tips;
3982
3983 preferred_tips = bitmap_preferred_tips(the_repository);
3984 if (!preferred_tips)
3985 return;
3986
3987 for_each_string_list_item(item, preferred_tips) {
3988 for_each_ref_in(item->string, mark_bitmap_preferred_tip, NULL);
3989 }
3990 }
3991
3992 static void get_object_list(struct rev_info *revs, int ac, const char **av)
3993 {
3994 struct setup_revision_opt s_r_opt = {
3995 .allow_exclude_promisor_objects = 1,
3996 };
3997 char line[1000];
3998 int flags = 0;
3999 int save_warning;
4000
4001 save_commit_buffer = 0;
4002 setup_revisions(ac, av, revs, &s_r_opt);
4003
4004 /* make sure shallows are read */
4005 is_repository_shallow(the_repository);
4006
4007 save_warning = warn_on_object_refname_ambiguity;
4008 warn_on_object_refname_ambiguity = 0;
4009
4010 while (fgets(line, sizeof(line), stdin) != NULL) {
4011 int len = strlen(line);
4012 if (len && line[len - 1] == '\n')
4013 line[--len] = 0;
4014 if (!len)
4015 break;
4016 if (*line == '-') {
4017 if (!strcmp(line, "--not")) {
4018 flags ^= UNINTERESTING;
4019 write_bitmap_index = 0;
4020 continue;
4021 }
4022 if (starts_with(line, "--shallow ")) {
4023 struct object_id oid;
4024 if (get_oid_hex(line + 10, &oid))
4025 die("not an object name '%s'", line + 10);
4026 register_shallow(the_repository, &oid);
4027 use_bitmap_index = 0;
4028 continue;
4029 }
4030 die(_("not a rev '%s'"), line);
4031 }
4032 if (handle_revision_arg(line, revs, flags, REVARG_CANNOT_BE_FILENAME))
4033 die(_("bad revision '%s'"), line);
4034 }
4035
4036 warn_on_object_refname_ambiguity = save_warning;
4037
4038 if (use_bitmap_index && !get_object_list_from_bitmap(revs))
4039 return;
4040
4041 if (use_delta_islands)
4042 load_delta_islands(the_repository, progress);
4043
4044 if (write_bitmap_index)
4045 mark_bitmap_preferred_tips();
4046
4047 if (prepare_revision_walk(revs))
4048 die(_("revision walk setup failed"));
4049 mark_edges_uninteresting(revs, show_edge, sparse);
4050
4051 if (!fn_show_object)
4052 fn_show_object = show_object;
4053 traverse_commit_list(revs,
4054 show_commit, fn_show_object,
4055 NULL);
4056
4057 if (unpack_unreachable_expiration) {
4058 revs->ignore_missing_links = 1;
4059 if (add_unseen_recent_objects_to_traversal(revs,
4060 unpack_unreachable_expiration, NULL, 0))
4061 die(_("unable to add recent objects"));
4062 if (prepare_revision_walk(revs))
4063 die(_("revision walk setup failed"));
4064 traverse_commit_list(revs, record_recent_commit,
4065 record_recent_object, NULL);
4066 }
4067
4068 if (keep_unreachable)
4069 add_objects_in_unpacked_packs();
4070 if (pack_loose_unreachable)
4071 add_unreachable_loose_objects();
4072 if (unpack_unreachable)
4073 loosen_unused_packed_objects();
4074
4075 oid_array_clear(&recent_objects);
4076 }
4077
4078 static void add_extra_kept_packs(const struct string_list *names)
4079 {
4080 struct packed_git *p;
4081
4082 if (!names->nr)
4083 return;
4084
4085 for (p = get_all_packs(the_repository); p; p = p->next) {
4086 const char *name = basename(p->pack_name);
4087 int i;
4088
4089 if (!p->pack_local)
4090 continue;
4091
4092 for (i = 0; i < names->nr; i++)
4093 if (!fspathcmp(name, names->items[i].string))
4094 break;
4095
4096 if (i < names->nr) {
4097 p->pack_keep_in_core = 1;
4098 ignore_packed_keep_in_core = 1;
4099 continue;
4100 }
4101 }
4102 }
4103
4104 static int option_parse_index_version(const struct option *opt,
4105 const char *arg, int unset)
4106 {
4107 char *c;
4108 const char *val = arg;
4109
4110 BUG_ON_OPT_NEG(unset);
4111
4112 pack_idx_opts.version = strtoul(val, &c, 10);
4113 if (pack_idx_opts.version > 2)
4114 die(_("unsupported index version %s"), val);
4115 if (*c == ',' && c[1])
4116 pack_idx_opts.off32_limit = strtoul(c+1, &c, 0);
4117 if (*c || pack_idx_opts.off32_limit & 0x80000000)
4118 die(_("bad index version '%s'"), val);
4119 return 0;
4120 }
4121
4122 static int option_parse_unpack_unreachable(const struct option *opt,
4123 const char *arg, int unset)
4124 {
4125 if (unset) {
4126 unpack_unreachable = 0;
4127 unpack_unreachable_expiration = 0;
4128 }
4129 else {
4130 unpack_unreachable = 1;
4131 if (arg)
4132 unpack_unreachable_expiration = approxidate(arg);
4133 }
4134 return 0;
4135 }
4136
4137 static int option_parse_cruft_expiration(const struct option *opt,
4138 const char *arg, int unset)
4139 {
4140 if (unset) {
4141 cruft = 0;
4142 cruft_expiration = 0;
4143 } else {
4144 cruft = 1;
4145 if (arg)
4146 cruft_expiration = approxidate(arg);
4147 }
4148 return 0;
4149 }
4150
4151 int cmd_pack_objects(int argc, const char **argv, const char *prefix)
4152 {
4153 int use_internal_rev_list = 0;
4154 int shallow = 0;
4155 int all_progress_implied = 0;
4156 struct strvec rp = STRVEC_INIT;
4157 int rev_list_unpacked = 0, rev_list_all = 0, rev_list_reflog = 0;
4158 int rev_list_index = 0;
4159 int stdin_packs = 0;
4160 struct string_list keep_pack_list = STRING_LIST_INIT_NODUP;
4161 struct list_objects_filter_options filter_options =
4162 LIST_OBJECTS_FILTER_INIT;
4163
4164 struct option pack_objects_options[] = {
4165 OPT_SET_INT('q', "quiet", &progress,
4166 N_("do not show progress meter"), 0),
4167 OPT_SET_INT(0, "progress", &progress,
4168 N_("show progress meter"), 1),
4169 OPT_SET_INT(0, "all-progress", &progress,
4170 N_("show progress meter during object writing phase"), 2),
4171 OPT_BOOL(0, "all-progress-implied",
4172 &all_progress_implied,
4173 N_("similar to --all-progress when progress meter is shown")),
4174 OPT_CALLBACK_F(0, "index-version", NULL, N_("<version>[,<offset>]"),
4175 N_("write the pack index file in the specified idx format version"),
4176 PARSE_OPT_NONEG, option_parse_index_version),
4177 OPT_MAGNITUDE(0, "max-pack-size", &pack_size_limit,
4178 N_("maximum size of each output pack file")),
4179 OPT_BOOL(0, "local", &local,
4180 N_("ignore borrowed objects from alternate object store")),
4181 OPT_BOOL(0, "incremental", &incremental,
4182 N_("ignore packed objects")),
4183 OPT_INTEGER(0, "window", &window,
4184 N_("limit pack window by objects")),
4185 OPT_MAGNITUDE(0, "window-memory", &window_memory_limit,
4186 N_("limit pack window by memory in addition to object limit")),
4187 OPT_INTEGER(0, "depth", &depth,
4188 N_("maximum length of delta chain allowed in the resulting pack")),
4189 OPT_BOOL(0, "reuse-delta", &reuse_delta,
4190 N_("reuse existing deltas")),
4191 OPT_BOOL(0, "reuse-object", &reuse_object,
4192 N_("reuse existing objects")),
4193 OPT_BOOL(0, "delta-base-offset", &allow_ofs_delta,
4194 N_("use OFS_DELTA objects")),
4195 OPT_INTEGER(0, "threads", &delta_search_threads,
4196 N_("use threads when searching for best delta matches")),
4197 OPT_BOOL(0, "non-empty", &non_empty,
4198 N_("do not create an empty pack output")),
4199 OPT_BOOL(0, "revs", &use_internal_rev_list,
4200 N_("read revision arguments from standard input")),
4201 OPT_SET_INT_F(0, "unpacked", &rev_list_unpacked,
4202 N_("limit the objects to those that are not yet packed"),
4203 1, PARSE_OPT_NONEG),
4204 OPT_SET_INT_F(0, "all", &rev_list_all,
4205 N_("include objects reachable from any reference"),
4206 1, PARSE_OPT_NONEG),
4207 OPT_SET_INT_F(0, "reflog", &rev_list_reflog,
4208 N_("include objects referred by reflog entries"),
4209 1, PARSE_OPT_NONEG),
4210 OPT_SET_INT_F(0, "indexed-objects", &rev_list_index,
4211 N_("include objects referred to by the index"),
4212 1, PARSE_OPT_NONEG),
4213 OPT_BOOL(0, "stdin-packs", &stdin_packs,
4214 N_("read packs from stdin")),
4215 OPT_BOOL(0, "stdout", &pack_to_stdout,
4216 N_("output pack to stdout")),
4217 OPT_BOOL(0, "include-tag", &include_tag,
4218 N_("include tag objects that refer to objects to be packed")),
4219 OPT_BOOL(0, "keep-unreachable", &keep_unreachable,
4220 N_("keep unreachable objects")),
4221 OPT_BOOL(0, "pack-loose-unreachable", &pack_loose_unreachable,
4222 N_("pack loose unreachable objects")),
4223 OPT_CALLBACK_F(0, "unpack-unreachable", NULL, N_("time"),
4224 N_("unpack unreachable objects newer than <time>"),
4225 PARSE_OPT_OPTARG, option_parse_unpack_unreachable),
4226 OPT_BOOL(0, "cruft", &cruft, N_("create a cruft pack")),
4227 OPT_CALLBACK_F(0, "cruft-expiration", NULL, N_("time"),
4228 N_("expire cruft objects older than <time>"),
4229 PARSE_OPT_OPTARG, option_parse_cruft_expiration),
4230 OPT_BOOL(0, "sparse", &sparse,
4231 N_("use the sparse reachability algorithm")),
4232 OPT_BOOL(0, "thin", &thin,
4233 N_("create thin packs")),
4234 OPT_BOOL(0, "shallow", &shallow,
4235 N_("create packs suitable for shallow fetches")),
4236 OPT_BOOL(0, "honor-pack-keep", &ignore_packed_keep_on_disk,
4237 N_("ignore packs that have companion .keep file")),
4238 OPT_STRING_LIST(0, "keep-pack", &keep_pack_list, N_("name"),
4239 N_("ignore this pack")),
4240 OPT_INTEGER(0, "compression", &pack_compression_level,
4241 N_("pack compression level")),
4242 OPT_SET_INT(0, "keep-true-parents", &grafts_replace_parents,
4243 N_("do not hide commits by grafts"), 0),
4244 OPT_BOOL(0, "use-bitmap-index", &use_bitmap_index,
4245 N_("use a bitmap index if available to speed up counting objects")),
4246 OPT_SET_INT(0, "write-bitmap-index", &write_bitmap_index,
4247 N_("write a bitmap index together with the pack index"),
4248 WRITE_BITMAP_TRUE),
4249 OPT_SET_INT_F(0, "write-bitmap-index-quiet",
4250 &write_bitmap_index,
4251 N_("write a bitmap index if possible"),
4252 WRITE_BITMAP_QUIET, PARSE_OPT_HIDDEN),
4253 OPT_PARSE_LIST_OBJECTS_FILTER(&filter_options),
4254 OPT_CALLBACK_F(0, "missing", NULL, N_("action"),
4255 N_("handling for missing objects"), PARSE_OPT_NONEG,
4256 option_parse_missing_action),
4257 OPT_BOOL(0, "exclude-promisor-objects", &exclude_promisor_objects,
4258 N_("do not pack objects in promisor packfiles")),
4259 OPT_BOOL(0, "delta-islands", &use_delta_islands,
4260 N_("respect islands during delta compression")),
4261 OPT_STRING_LIST(0, "uri-protocol", &uri_protocols,
4262 N_("protocol"),
4263 N_("exclude any configured uploadpack.blobpackfileuri with this protocol")),
4264 OPT_END(),
4265 };
4266
4267 if (DFS_NUM_STATES > (1 << OE_DFS_STATE_BITS))
4268 BUG("too many dfs states, increase OE_DFS_STATE_BITS");
4269
4270 read_replace_refs = 0;
4271
4272 sparse = git_env_bool("GIT_TEST_PACK_SPARSE", -1);
4273 if (the_repository->gitdir) {
4274 prepare_repo_settings(the_repository);
4275 if (sparse < 0)
4276 sparse = the_repository->settings.pack_use_sparse;
4277 }
4278
4279 reset_pack_idx_option(&pack_idx_opts);
4280 git_config(git_pack_config, NULL);
4281 if (git_env_bool(GIT_TEST_WRITE_REV_INDEX, 0))
4282 pack_idx_opts.flags |= WRITE_REV;
4283
4284 progress = isatty(2);
4285 argc = parse_options(argc, argv, prefix, pack_objects_options,
4286 pack_usage, 0);
4287
4288 if (argc) {
4289 base_name = argv[0];
4290 argc--;
4291 }
4292 if (pack_to_stdout != !base_name || argc)
4293 usage_with_options(pack_usage, pack_objects_options);
4294
4295 if (depth < 0)
4296 depth = 0;
4297 if (depth >= (1 << OE_DEPTH_BITS)) {
4298 warning(_("delta chain depth %d is too deep, forcing %d"),
4299 depth, (1 << OE_DEPTH_BITS) - 1);
4300 depth = (1 << OE_DEPTH_BITS) - 1;
4301 }
4302 if (cache_max_small_delta_size >= (1U << OE_Z_DELTA_BITS)) {
4303 warning(_("pack.deltaCacheLimit is too high, forcing %d"),
4304 (1U << OE_Z_DELTA_BITS) - 1);
4305 cache_max_small_delta_size = (1U << OE_Z_DELTA_BITS) - 1;
4306 }
4307 if (window < 0)
4308 window = 0;
4309
4310 strvec_push(&rp, "pack-objects");
4311 if (thin) {
4312 use_internal_rev_list = 1;
4313 strvec_push(&rp, shallow
4314 ? "--objects-edge-aggressive"
4315 : "--objects-edge");
4316 } else
4317 strvec_push(&rp, "--objects");
4318
4319 if (rev_list_all) {
4320 use_internal_rev_list = 1;
4321 strvec_push(&rp, "--all");
4322 }
4323 if (rev_list_reflog) {
4324 use_internal_rev_list = 1;
4325 strvec_push(&rp, "--reflog");
4326 }
4327 if (rev_list_index) {
4328 use_internal_rev_list = 1;
4329 strvec_push(&rp, "--indexed-objects");
4330 }
4331 if (rev_list_unpacked && !stdin_packs) {
4332 use_internal_rev_list = 1;
4333 strvec_push(&rp, "--unpacked");
4334 }
4335
4336 if (exclude_promisor_objects) {
4337 use_internal_rev_list = 1;
4338 fetch_if_missing = 0;
4339 strvec_push(&rp, "--exclude-promisor-objects");
4340 }
4341 if (unpack_unreachable || keep_unreachable || pack_loose_unreachable)
4342 use_internal_rev_list = 1;
4343
4344 if (!reuse_object)
4345 reuse_delta = 0;
4346 if (pack_compression_level == -1)
4347 pack_compression_level = Z_DEFAULT_COMPRESSION;
4348 else if (pack_compression_level < 0 || pack_compression_level > Z_BEST_COMPRESSION)
4349 die(_("bad pack compression level %d"), pack_compression_level);
4350
4351 if (!delta_search_threads) /* --threads=0 means autodetect */
4352 delta_search_threads = online_cpus();
4353
4354 if (!HAVE_THREADS && delta_search_threads != 1)
4355 warning(_("no threads support, ignoring --threads"));
4356 if (!pack_to_stdout && !pack_size_limit && !cruft)
4357 pack_size_limit = pack_size_limit_cfg;
4358 if (pack_to_stdout && pack_size_limit)
4359 die(_("--max-pack-size cannot be used to build a pack for transfer"));
4360 if (pack_size_limit && pack_size_limit < 1024*1024) {
4361 warning(_("minimum pack size limit is 1 MiB"));
4362 pack_size_limit = 1024*1024;
4363 }
4364
4365 if (!pack_to_stdout && thin)
4366 die(_("--thin cannot be used to build an indexable pack"));
4367
4368 if (keep_unreachable && unpack_unreachable)
4369 die(_("options '%s' and '%s' cannot be used together"), "--keep-unreachable", "--unpack-unreachable");
4370 if (!rev_list_all || !rev_list_reflog || !rev_list_index)
4371 unpack_unreachable_expiration = 0;
4372
4373 if (filter_options.choice) {
4374 if (!pack_to_stdout)
4375 die(_("cannot use --filter without --stdout"));
4376 if (stdin_packs)
4377 die(_("cannot use --filter with --stdin-packs"));
4378 }
4379
4380 if (stdin_packs && use_internal_rev_list)
4381 die(_("cannot use internal rev list with --stdin-packs"));
4382
4383 if (cruft) {
4384 if (use_internal_rev_list)
4385 die(_("cannot use internal rev list with --cruft"));
4386 if (stdin_packs)
4387 die(_("cannot use --stdin-packs with --cruft"));
4388 if (pack_size_limit)
4389 die(_("cannot use --max-pack-size with --cruft"));
4390 }
4391
4392 /*
4393 * "soft" reasons not to use bitmaps - for on-disk repack by default we want
4394 *
4395 * - to produce good pack (with bitmap index not-yet-packed objects are
4396 * packed in suboptimal order).
4397 *
4398 * - to use more robust pack-generation codepath (avoiding possible
4399 * bugs in bitmap code and possible bitmap index corruption).
4400 */
4401 if (!pack_to_stdout)
4402 use_bitmap_index_default = 0;
4403
4404 if (use_bitmap_index < 0)
4405 use_bitmap_index = use_bitmap_index_default;
4406
4407 /* "hard" reasons not to use bitmaps; these just won't work at all */
4408 if (!use_internal_rev_list || (!pack_to_stdout && write_bitmap_index) || is_repository_shallow(the_repository))
4409 use_bitmap_index = 0;
4410
4411 if (pack_to_stdout || !rev_list_all)
4412 write_bitmap_index = 0;
4413
4414 if (use_delta_islands)
4415 strvec_push(&rp, "--topo-order");
4416
4417 if (progress && all_progress_implied)
4418 progress = 2;
4419
4420 add_extra_kept_packs(&keep_pack_list);
4421 if (ignore_packed_keep_on_disk) {
4422 struct packed_git *p;
4423 for (p = get_all_packs(the_repository); p; p = p->next)
4424 if (p->pack_local && p->pack_keep)
4425 break;
4426 if (!p) /* no keep-able packs found */
4427 ignore_packed_keep_on_disk = 0;
4428 }
4429 if (local) {
4430 /*
4431 * unlike ignore_packed_keep_on_disk above, we do not
4432 * want to unset "local" based on looking at packs, as
4433 * it also covers non-local objects
4434 */
4435 struct packed_git *p;
4436 for (p = get_all_packs(the_repository); p; p = p->next) {
4437 if (!p->pack_local) {
4438 have_non_local_packs = 1;
4439 break;
4440 }
4441 }
4442 }
4443
4444 trace2_region_enter("pack-objects", "enumerate-objects",
4445 the_repository);
4446 prepare_packing_data(the_repository, &to_pack);
4447
4448 if (progress && !cruft)
4449 progress_state = start_progress(_("Enumerating objects"), 0);
4450 if (stdin_packs) {
4451 /* avoids adding objects in excluded packs */
4452 ignore_packed_keep_in_core = 1;
4453 read_packs_list_from_stdin();
4454 if (rev_list_unpacked)
4455 add_unreachable_loose_objects();
4456 } else if (cruft) {
4457 read_cruft_objects();
4458 } else if (!use_internal_rev_list) {
4459 read_object_list_from_stdin();
4460 } else {
4461 struct rev_info revs;
4462
4463 repo_init_revisions(the_repository, &revs, NULL);
4464 list_objects_filter_copy(&revs.filter, &filter_options);
4465 get_object_list(&revs, rp.nr, rp.v);
4466 release_revisions(&revs);
4467 }
4468 cleanup_preferred_base();
4469 if (include_tag && nr_result)
4470 for_each_tag_ref(add_ref_tag, NULL);
4471 stop_progress(&progress_state);
4472 trace2_region_leave("pack-objects", "enumerate-objects",
4473 the_repository);
4474
4475 if (non_empty && !nr_result)
4476 goto cleanup;
4477 if (nr_result) {
4478 trace2_region_enter("pack-objects", "prepare-pack",
4479 the_repository);
4480 prepare_pack(window, depth);
4481 trace2_region_leave("pack-objects", "prepare-pack",
4482 the_repository);
4483 }
4484
4485 trace2_region_enter("pack-objects", "write-pack-file", the_repository);
4486 write_excluded_by_configs();
4487 write_pack_file();
4488 trace2_region_leave("pack-objects", "write-pack-file", the_repository);
4489
4490 if (progress)
4491 fprintf_ln(stderr,
4492 _("Total %"PRIu32" (delta %"PRIu32"),"
4493 " reused %"PRIu32" (delta %"PRIu32"),"
4494 " pack-reused %"PRIu32),
4495 written, written_delta, reused, reused_delta,
4496 reuse_packfile_objects);
4497
4498 cleanup:
4499 list_objects_filter_release(&filter_options);
4500 strvec_clear(&rp);
4501
4502 return 0;
4503 }