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