at commit b4dedbc0

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