at commit a6c98376

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