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 /*
1193 * We can't reuse whole chunks verbatim out of
1194 * non-preferred packs since we can't guarantee that
1195 * all duplicate objects were resolved in favor of
1196 * that pack.
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 non-preferred 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 /*
1274 * When doing multi-pack reuse on a
1275 * non-preferred pack, translate bit positions
1276 * from the MIDX pseudo-pack order back to their
1277 * pack-relative positions before attempting
1278 * reuse.
1279 */
1280 struct multi_pack_index *m = reuse_packfile->from_midx;
1281 uint32_t midx_pos;
1282 off_t pack_ofs;
1283
1284 if (!m)
1285 BUG("non-zero bitmap position without MIDX");
1286
1287 midx_pos = pack_pos_to_midx(m, pos + offset);
1288 pack_ofs = nth_midxed_offset(m, midx_pos);
1289
1290 if (offset_to_pack_pos(reuse_packfile->p,
1291 pack_ofs, &pack_pos) < 0)
1292 BUG("could not find expected object at offset %"PRIuMAX" in pack %s",
1293 (uintmax_t)pack_ofs,
1294 pack_basename(reuse_packfile->p));
1295 } else {
1296 /*
1297 * Can use bit positions directly, even for MIDX
1298 * bitmaps. See comment in try_partial_reuse()
1299 * for why.
1300 */
1301 pack_pos = pos + offset;
1302 }
1303
1304 write_reused_pack_one(reuse_packfile->p, pack_pos, f,
1305 pack_start, &w_curs);
1306 display_progress(progress_state, ++written);
1307 }
1308 }
1309
1310 done:
1311 unuse_pack(&w_curs);
1312 }
1313
1314 static void write_excluded_by_configs(void)
1315 {
1316 struct oidset_iter iter;
1317 const struct object_id *oid;
1318
1319 oidset_iter_init(&excluded_by_config, &iter);
1320 while ((oid = oidset_iter_next(&iter))) {
1321 struct configured_exclusion *ex =
1322 oidmap_get(&configured_exclusions, oid);
1323
1324 if (!ex)
1325 BUG("configured exclusion wasn't configured");
1326 write_in_full(1, ex->pack_hash_hex, strlen(ex->pack_hash_hex));
1327 write_in_full(1, " ", 1);
1328 write_in_full(1, ex->uri, strlen(ex->uri));
1329 write_in_full(1, "\n", 1);
1330 }
1331 }
1332
1333 static const char no_split_warning[] = N_(
1334 "disabling bitmap writing, packs are split due to pack.packSizeLimit"
1335 );
1336
1337 static void write_pack_file(void)
1338 {
1339 uint32_t i = 0, j;
1340 struct hashfile *f;
1341 off_t offset;
1342 uint32_t nr_remaining = nr_result;
1343 time_t last_mtime = 0;
1344 struct object_entry **write_order;
1345
1346 if (progress > pack_to_stdout)
1347 progress_state = start_progress(the_repository,
1348 _("Writing objects"), nr_result);
1349 ALLOC_ARRAY(written_list, to_pack.nr_objects);
1350 write_order = compute_write_order();
1351
1352 do {
1353 unsigned char hash[GIT_MAX_RAWSZ];
1354 char *pack_tmp_name = NULL;
1355
1356 if (pack_to_stdout) {
1357 /*
1358 * This command is most often invoked via
1359 * git-upload-pack(1), which will typically chunk data
1360 * into pktlines. As such, we use the maximum data
1361 * length of them as buffer length.
1362 *
1363 * Note that we need to subtract one though to
1364 * accommodate for the sideband byte.
1365 */
1366 struct hashfd_options opts = {
1367 .progress = progress_state,
1368 .buffer_len = LARGE_PACKET_DATA_MAX - 1,
1369 };
1370 f = hashfd_ext(the_repository->hash_algo, 1,
1371 "<stdout>", &opts);
1372 } else {
1373 f = create_tmp_packfile(the_repository, &pack_tmp_name);
1374 }
1375
1376 offset = write_pack_header(f, nr_remaining);
1377
1378 if (reuse_packfiles_nr) {
1379 assert(pack_to_stdout);
1380 for (j = 0; j < reuse_packfiles_nr; j++) {
1381 reused_chunks_nr = 0;
1382 write_reused_pack(&reuse_packfiles[j], f);
1383 if (reused_chunks_nr)
1384 reuse_packfiles_used_nr++;
1385 }
1386 offset = hashfile_total(f);
1387 }
1388
1389 nr_written = 0;
1390 for (; i < to_pack.nr_objects; i++) {
1391 struct object_entry *e = write_order[i];
1392 if (write_one(f, e, &offset) == WRITE_ONE_BREAK)
1393 break;
1394 display_progress(progress_state, written);
1395 }
1396
1397 if (pack_to_stdout) {
1398 /*
1399 * We never fsync when writing to stdout since we may
1400 * not be writing to an actual pack file. For instance,
1401 * the upload-pack code passes a pipe here. Calling
1402 * fsync on a pipe results in unnecessary
1403 * synchronization with the reader on some platforms.
1404 */
1405 finalize_hashfile(f, hash, FSYNC_COMPONENT_NONE,
1406 CSUM_HASH_IN_STREAM | CSUM_CLOSE);
1407 } else if (nr_written == nr_remaining) {
1408 finalize_hashfile(f, hash, FSYNC_COMPONENT_PACK,
1409 CSUM_HASH_IN_STREAM | CSUM_FSYNC | CSUM_CLOSE);
1410 } else {
1411 /*
1412 * If we wrote the wrong number of entries in the
1413 * header, rewrite it like in fast-import.
1414 */
1415
1416 int fd = finalize_hashfile(f, hash, FSYNC_COMPONENT_PACK, 0);
1417 fixup_pack_header_footer(the_hash_algo, fd, hash,
1418 pack_tmp_name, nr_written,
1419 hash, offset);
1420 close(fd);
1421 if (write_bitmap_index) {
1422 if (write_bitmap_index != WRITE_BITMAP_QUIET)
1423 warning(_(no_split_warning));
1424 write_bitmap_index = 0;
1425 }
1426 }
1427
1428 if (!pack_to_stdout) {
1429 struct stat st;
1430 struct strbuf tmpname = STRBUF_INIT;
1431 struct bitmap_writer bitmap_writer;
1432 char *idx_tmp_name = NULL;
1433
1434 /*
1435 * Packs are runtime accessed in their mtime
1436 * order since newer packs are more likely to contain
1437 * younger objects. So if we are creating multiple
1438 * packs then we should modify the mtime of later ones
1439 * to preserve this property.
1440 */
1441 if (stat(pack_tmp_name, &st) < 0) {
1442 warning_errno(_("failed to stat %s"), pack_tmp_name);
1443 } else if (!last_mtime) {
1444 last_mtime = st.st_mtime;
1445 } else {
1446 struct utimbuf utb;
1447 utb.actime = st.st_atime;
1448 utb.modtime = --last_mtime;
1449 if (utime(pack_tmp_name, &utb) < 0)
1450 warning_errno(_("failed utime() on %s"), pack_tmp_name);
1451 }
1452
1453 strbuf_addf(&tmpname, "%s-%s.", base_name,
1454 hash_to_hex(hash));
1455
1456 if (write_bitmap_index) {
1457 bitmap_writer_init(&bitmap_writer,
1458 the_repository, &to_pack,
1459 NULL);
1460 bitmap_writer_set_checksum(&bitmap_writer, hash);
1461 bitmap_writer_build_type_index(&bitmap_writer,
1462 written_list);
1463 }
1464
1465 if (cruft)
1466 pack_idx_opts.flags |= WRITE_MTIMES;
1467
1468 stage_tmp_packfiles(the_repository, &tmpname,
1469 pack_tmp_name, written_list,
1470 nr_written, &to_pack,
1471 &pack_idx_opts, hash,
1472 &idx_tmp_name);
1473
1474 if (write_bitmap_index) {
1475 size_t tmpname_len = tmpname.len;
1476
1477 strbuf_addstr(&tmpname, "bitmap");
1478 stop_progress(&progress_state);
1479
1480 bitmap_writer_show_progress(&bitmap_writer,
1481 progress);
1482 bitmap_writer_select_commits(&bitmap_writer,
1483 indexed_commits,
1484 indexed_commits_nr);
1485 if (bitmap_writer_build(&bitmap_writer) < 0)
1486 die(_("failed to write bitmap index"));
1487 bitmap_writer_finish(&bitmap_writer,
1488 written_list,
1489 tmpname.buf, write_bitmap_options);
1490 bitmap_writer_free(&bitmap_writer);
1491 write_bitmap_index = 0;
1492 strbuf_setlen(&tmpname, tmpname_len);
1493 }
1494
1495 rename_tmp_packfile_idx(the_repository, &tmpname, &idx_tmp_name);
1496
1497 free(idx_tmp_name);
1498 strbuf_release(&tmpname);
1499 free(pack_tmp_name);
1500 puts(hash_to_hex(hash));
1501 }
1502
1503 /* mark written objects as written to previous pack */
1504 for (j = 0; j < nr_written; j++) {
1505 written_list[j]->offset = (off_t)-1;
1506 }
1507 nr_remaining -= nr_written;
1508 } while (nr_remaining && i < to_pack.nr_objects);
1509
1510 free(written_list);
1511 free(write_order);
1512 stop_progress(&progress_state);
1513 if (written != nr_result)
1514 die(_("wrote %"PRIu32" objects while expecting %"PRIu32),
1515 written, nr_result);
1516 trace2_data_intmax("pack-objects", the_repository,
1517 "write_pack_file/wrote", nr_result);
1518 }
1519
1520 static int no_try_delta(const char *path)
1521 {
1522 static struct attr_check *check;
1523
1524 if (!check)
1525 check = attr_check_initl("delta", NULL);
1526 git_check_attr(the_repository->index, path, check);
1527 if (ATTR_FALSE(check->items[0].value))
1528 return 1;
1529 return 0;
1530 }
1531
1532 /*
1533 * When adding an object, check whether we have already added it
1534 * to our packing list. If so, we can skip. However, if we are
1535 * being asked to excludei t, but the previous mention was to include
1536 * it, make sure to adjust its flags and tweak our numbers accordingly.
1537 *
1538 * As an optimization, we pass out the index position where we would have
1539 * found the item, since that saves us from having to look it up again a
1540 * few lines later when we want to add the new entry.
1541 */
1542 static int have_duplicate_entry(const struct object_id *oid,
1543 int exclude)
1544 {
1545 struct object_entry *entry;
1546
1547 if (reuse_packfile_bitmap &&
1548 bitmap_walk_contains(bitmap_git, reuse_packfile_bitmap, oid))
1549 return 1;
1550
1551 entry = packlist_find(&to_pack, oid);
1552 if (!entry)
1553 return 0;
1554
1555 if (exclude) {
1556 if (!entry->preferred_base)
1557 nr_result--;
1558 entry->preferred_base = 1;
1559 }
1560
1561 return 1;
1562 }
1563
1564 static int want_cruft_object_mtime(struct repository *r,
1565 const struct object_id *oid,
1566 unsigned flags, uint32_t mtime)
1567 {
1568 struct odb_source *source;
1569
1570 for (source = r->objects->sources; source; source = source->next) {
1571 struct odb_source_files *files = odb_source_files_downcast(source);
1572 struct packed_git **cache = packfile_store_get_kept_pack_cache(files->packed, flags);
1573
1574 for (; *cache; cache++) {
1575 struct packed_git *p = *cache;
1576 off_t ofs;
1577 uint32_t candidate_mtime;
1578
1579 ofs = find_pack_entry_one(oid, p);
1580 if (!ofs)
1581 continue;
1582
1583 /*
1584 * We have a copy of the object 'oid' in a non-cruft
1585 * pack. We can avoid packing an additional copy
1586 * regardless of what the existing copy's mtime is since
1587 * it is outside of a cruft pack.
1588 */
1589 if (!p->is_cruft)
1590 return 0;
1591
1592 /*
1593 * If we have a copy of the object 'oid' in a cruft
1594 * pack, then either read the cruft pack's mtime for
1595 * that object, or, if that can't be loaded, assume the
1596 * pack's mtime itself.
1597 */
1598 if (!load_pack_mtimes(p)) {
1599 uint32_t pos;
1600 if (offset_to_pack_pos(p, ofs, &pos) < 0)
1601 continue;
1602 candidate_mtime = nth_packed_mtime(p, pos);
1603 } else {
1604 candidate_mtime = p->mtime;
1605 }
1606
1607 /*
1608 * We have a surviving copy of the object in a cruft
1609 * pack whose mtime is greater than or equal to the one
1610 * we are considering. We can thus avoid packing an
1611 * additional copy of that object.
1612 */
1613 if (mtime <= candidate_mtime)
1614 return 0;
1615 }
1616 }
1617
1618 return -1;
1619 }
1620
1621 static int want_found_object(const struct object_id *oid, int exclude,
1622 struct packed_git *p, uint32_t mtime)
1623 {
1624 if (exclude)
1625 return 1;
1626 if (incremental)
1627 return 0;
1628
1629 if (!is_pack_valid(p))
1630 return -1;
1631
1632 /*
1633 * When asked to do --local (do not include an object that appears in a
1634 * pack we borrow from elsewhere) or --honor-pack-keep (do not include
1635 * an object that appears in a pack marked with .keep), finding a pack
1636 * that matches the criteria is sufficient for us to decide to omit it.
1637 * However, even if this pack does not satisfy the criteria, we need to
1638 * make sure no copy of this object appears in _any_ pack that makes us
1639 * to omit the object, so we need to check all the packs.
1640 *
1641 * We can however first check whether these options can possibly matter;
1642 * if they do not matter we know we want the object in generated pack.
1643 * Otherwise, we signal "-1" at the end to tell the caller that we do
1644 * not know either way, and it needs to check more packs.
1645 */
1646
1647 /*
1648 * Objects in packs borrowed from elsewhere are discarded regardless of
1649 * if they appear in other packs that weren't borrowed.
1650 */
1651 if (local && !p->pack_local)
1652 return 0;
1653
1654 /*
1655 * Then handle .keep first, as we have a fast(er) path there.
1656 */
1657 if (ignore_packed_keep_on_disk || ignore_packed_keep_in_core ||
1658 ignore_packed_keep_in_core_open) {
1659 /*
1660 * Set the flags for the kept-pack cache to be the ones we want
1661 * to ignore.
1662 *
1663 * That is, if we are ignoring objects in on-disk keep packs,
1664 * then we want to search through the on-disk keep and ignore
1665 * the in-core ones.
1666 */
1667 unsigned flags = 0;
1668 if (ignore_packed_keep_on_disk)
1669 flags |= KEPT_PACK_ON_DISK;
1670 if (ignore_packed_keep_in_core)
1671 flags |= KEPT_PACK_IN_CORE;
1672 if (ignore_packed_keep_in_core_open)
1673 flags |= KEPT_PACK_IN_CORE_OPEN;
1674
1675 /*
1676 * If the object is in a pack that we want to ignore, *and* we
1677 * don't have any cruft packs that are being retained, we can
1678 * abort quickly.
1679 */
1680 if (!ignore_packed_keep_in_core_has_cruft) {
1681 if (ignore_packed_keep_on_disk && p->pack_keep)
1682 return 0;
1683 if (ignore_packed_keep_in_core && p->pack_keep_in_core)
1684 return 0;
1685 if (ignore_packed_keep_in_core_open && p->pack_keep_in_core_open)
1686 return 0;
1687 if (has_object_kept_pack(p->repo, oid, flags))
1688 return 0;
1689 } else {
1690 /*
1691 * But if there is at least one cruft pack which
1692 * is being kept, we only want to include the
1693 * provided object if it has a strictly greater
1694 * mtime than any existing cruft copy.
1695 */
1696 if (!want_cruft_object_mtime(p->repo, oid, flags,
1697 mtime))
1698 return 0;
1699 }
1700 }
1701
1702 /*
1703 * At this point we know definitively that either we don't care about
1704 * keep-packs, or the object is not in one. Keep checking other
1705 * conditions...
1706 */
1707 if (!local || !have_non_local_packs)
1708 return 1;
1709
1710 /* we don't know yet; keep looking for more packs */
1711 return -1;
1712 }
1713
1714 static int want_object_in_pack_one(struct packed_git *p,
1715 const struct object_id *oid,
1716 int exclude,
1717 struct packed_git **found_pack,
1718 off_t *found_offset,
1719 uint32_t found_mtime)
1720 {
1721 off_t offset;
1722
1723 if (p == *found_pack)
1724 offset = *found_offset;
1725 else
1726 offset = find_pack_entry_one(oid, p);
1727
1728 if (offset) {
1729 if (!*found_pack) {
1730 if (!is_pack_valid(p))
1731 return -1;
1732 *found_offset = offset;
1733 *found_pack = p;
1734 }
1735 return want_found_object(oid, exclude, p, found_mtime);
1736 }
1737 return -1;
1738 }
1739
1740 /*
1741 * Check whether we want the object in the pack (e.g., we do not want
1742 * objects found in non-local stores if the "--local" option was used).
1743 *
1744 * If the caller already knows an existing pack it wants to take the object
1745 * from, that is passed in *found_pack and *found_offset; otherwise this
1746 * function finds if there is any pack that has the object and returns the pack
1747 * and its offset in these variables.
1748 */
1749 static int want_object_in_pack_mtime(const struct object_id *oid,
1750 int exclude,
1751 struct packed_git **found_pack,
1752 off_t *found_offset,
1753 uint32_t found_mtime)
1754 {
1755 int want;
1756 struct packfile_list_entry *e;
1757 struct odb_source *source;
1758
1759 if (!exclude && local) {
1760 /*
1761 * Note that we start iterating at `sources->next` so that we
1762 * skip the local object source.
1763 */
1764 struct odb_source *source = the_repository->objects->sources->next;
1765 for (; source; source = source->next) {
1766 struct odb_source_files *files = odb_source_files_downcast(source);
1767 if (!odb_source_read_object_info(&files->loose->base, oid, NULL, 0))
1768 return 0;
1769 }
1770 }
1771
1772 /*
1773 * If we already know the pack object lives in, start checks from that
1774 * pack - in the usual case when neither --local was given nor .keep files
1775 * are present we will determine the answer right now.
1776 */
1777 if (*found_pack) {
1778 want = want_found_object(oid, exclude, *found_pack,
1779 found_mtime);
1780 if (want != -1)
1781 return want;
1782
1783 *found_pack = NULL;
1784 *found_offset = 0;
1785 }
1786
1787 odb_prepare_alternates(the_repository->objects);
1788
1789 for (source = the_repository->objects->sources; source; source = source->next) {
1790 struct odb_source_files *files = odb_source_files_downcast(source);
1791 struct multi_pack_index *m = get_multi_pack_index(files->packed);
1792 struct pack_entry e;
1793
1794 if (m && fill_midx_entry(m, oid, &e)) {
1795 want = want_object_in_pack_one(e.p, oid, exclude, found_pack, found_offset, found_mtime);
1796 if (want != -1)
1797 return want;
1798 }
1799 }
1800
1801 for (source = the_repository->objects->sources; source; source = source->next) {
1802 struct odb_source_files *files = odb_source_files_downcast(source);
1803
1804 for (e = files->packed->packs.head; e; e = e->next) {
1805 struct packed_git *p = e->pack;
1806 want = want_object_in_pack_one(p, oid, exclude, found_pack, found_offset, found_mtime);
1807 if (!exclude && want > 0)
1808 packfile_list_prepend(&files->packed->packs, p);
1809 if (want != -1)
1810 return want;
1811 }
1812 }
1813
1814 if (uri_protocols.nr) {
1815 struct configured_exclusion *ex =
1816 oidmap_get(&configured_exclusions, oid);
1817 int i;
1818 const char *p;
1819
1820 if (ex) {
1821 for (i = 0; i < uri_protocols.nr; i++) {
1822 if (skip_prefix(ex->uri,
1823 uri_protocols.items[i].string,
1824 &p) &&
1825 *p == ':') {
1826 oidset_insert(&excluded_by_config, oid);
1827 return 0;
1828 }
1829 }
1830 }
1831 }
1832
1833 return 1;
1834 }
1835
1836 static inline int want_object_in_pack(const struct object_id *oid,
1837 int exclude,
1838 struct packed_git **found_pack,
1839 off_t *found_offset)
1840 {
1841 return want_object_in_pack_mtime(oid, exclude, found_pack, found_offset,
1842 0);
1843 }
1844
1845 static struct object_entry *create_object_entry(const struct object_id *oid,
1846 enum object_type type,
1847 uint32_t hash,
1848 int exclude,
1849 int no_try_delta,
1850 struct packed_git *found_pack,
1851 off_t found_offset)
1852 {
1853 struct object_entry *entry;
1854
1855 entry = packlist_alloc(&to_pack, oid);
1856 entry->hash = hash;
1857 oe_set_type(entry, type);
1858 if (exclude)
1859 entry->preferred_base = 1;
1860 else
1861 nr_result++;
1862 if (found_pack) {
1863 oe_set_in_pack(&to_pack, entry, found_pack);
1864 entry->in_pack_offset = found_offset;
1865 }
1866
1867 entry->no_try_delta = no_try_delta;
1868
1869 return entry;
1870 }
1871
1872 static const char no_closure_warning[] = N_(
1873 "disabling bitmap writing, as some objects are not being packed"
1874 );
1875
1876 static void add_object_entry(const struct object_id *oid, enum object_type type,
1877 const char *name, int exclude)
1878 {
1879 struct packed_git *found_pack = NULL;
1880 off_t found_offset = 0;
1881
1882 display_progress(progress_state, ++nr_seen);
1883
1884 if (have_duplicate_entry(oid, exclude))
1885 return;
1886
1887 if (!want_object_in_pack(oid, exclude, &found_pack, &found_offset)) {
1888 /* The pack is missing an object, so it will not have closure */
1889 if (write_bitmap_index) {
1890 if (write_bitmap_index != WRITE_BITMAP_QUIET)
1891 warning(_(no_closure_warning));
1892 write_bitmap_index = 0;
1893 }
1894 return;
1895 }
1896
1897 create_object_entry(oid, type, pack_name_hash_fn(name),
1898 exclude, name && no_try_delta(name),
1899 found_pack, found_offset);
1900 }
1901
1902 static int add_object_entry_from_bitmap(const struct object_id *oid,
1903 enum object_type type,
1904 int flags UNUSED, uint32_t name_hash,
1905 struct packed_git *pack, off_t offset,
1906 void *payload UNUSED)
1907 {
1908 display_progress(progress_state, ++nr_seen);
1909
1910 if (have_duplicate_entry(oid, 0))
1911 return 0;
1912
1913 if (!want_object_in_pack(oid, 0, &pack, &offset))
1914 return 0;
1915
1916 create_object_entry(oid, type, name_hash, 0, 0, pack, offset);
1917 return 0;
1918 }
1919
1920 struct pbase_tree_cache {
1921 struct object_id oid;
1922 int ref;
1923 int temporary;
1924 void *tree_data;
1925 unsigned long tree_size;
1926 };
1927
1928 static struct pbase_tree_cache *(pbase_tree_cache[256]);
1929 static int pbase_tree_cache_ix(const struct object_id *oid)
1930 {
1931 return oid->hash[0] % ARRAY_SIZE(pbase_tree_cache);
1932 }
1933 static int pbase_tree_cache_ix_incr(int ix)
1934 {
1935 return (ix+1) % ARRAY_SIZE(pbase_tree_cache);
1936 }
1937
1938 static struct pbase_tree {
1939 struct pbase_tree *next;
1940 /* This is a phony "cache" entry; we are not
1941 * going to evict it or find it through _get()
1942 * mechanism -- this is for the toplevel node that
1943 * would almost always change with any commit.
1944 */
1945 struct pbase_tree_cache pcache;
1946 } *pbase_tree;
1947
1948 static struct pbase_tree_cache *pbase_tree_get(const struct object_id *oid)
1949 {
1950 struct pbase_tree_cache *ent, *nent;
1951 void *data;
1952 unsigned long size;
1953 size_t size_st = 0;
1954 enum object_type type;
1955 int neigh;
1956 int my_ix = pbase_tree_cache_ix(oid);
1957 int available_ix = -1;
1958
1959 /* pbase-tree-cache acts as a limited hashtable.
1960 * your object will be found at your index or within a few
1961 * slots after that slot if it is cached.
1962 */
1963 for (neigh = 0; neigh < 8; neigh++) {
1964 ent = pbase_tree_cache[my_ix];
1965 if (ent && oideq(&ent->oid, oid)) {
1966 ent->ref++;
1967 return ent;
1968 }
1969 else if (((available_ix < 0) && (!ent || !ent->ref)) ||
1970 ((0 <= available_ix) &&
1971 (!ent && pbase_tree_cache[available_ix])))
1972 available_ix = my_ix;
1973 if (!ent)
1974 break;
1975 my_ix = pbase_tree_cache_ix_incr(my_ix);
1976 }
1977
1978 /* Did not find one. Either we got a bogus request or
1979 * we need to read and perhaps cache.
1980 */
1981 data = odb_read_object(the_repository->objects, oid, &type, &size_st);
1982 size = cast_size_t_to_ulong(size_st);
1983 if (!data)
1984 return NULL;
1985 if (type != OBJ_TREE) {
1986 free(data);
1987 return NULL;
1988 }
1989
1990 /* We need to either cache or return a throwaway copy */
1991
1992 if (available_ix < 0)
1993 ent = NULL;
1994 else {
1995 ent = pbase_tree_cache[available_ix];
1996 my_ix = available_ix;
1997 }
1998
1999 if (!ent) {
2000 nent = xmalloc(sizeof(*nent));
2001 nent->temporary = (available_ix < 0);
2002 }
2003 else {
2004 /* evict and reuse */
2005 free(ent->tree_data);
2006 nent = ent;
2007 }
2008 oidcpy(&nent->oid, oid);
2009 nent->tree_data = data;
2010 nent->tree_size = size;
2011 nent->ref = 1;
2012 if (!nent->temporary)
2013 pbase_tree_cache[my_ix] = nent;
2014 return nent;
2015 }
2016
2017 static void pbase_tree_put(struct pbase_tree_cache *cache)
2018 {
2019 if (!cache->temporary) {
2020 cache->ref--;
2021 return;
2022 }
2023 free(cache->tree_data);
2024 free(cache);
2025 }
2026
2027 static size_t name_cmp_len(const char *name)
2028 {
2029 return strcspn(name, "\n/");
2030 }
2031
2032 static void add_pbase_object(struct tree_desc *tree,
2033 const char *name,
2034 size_t cmplen,
2035 const char *fullname)
2036 {
2037 struct name_entry entry;
2038 int cmp;
2039
2040 while (tree_entry(tree,&entry)) {
2041 if (S_ISGITLINK(entry.mode))
2042 continue;
2043 cmp = tree_entry_len(&entry) != cmplen ? 1 :
2044 memcmp(name, entry.path, cmplen);
2045 if (cmp > 0)
2046 continue;
2047 if (cmp < 0)
2048 return;
2049 if (name[cmplen] != '/') {
2050 add_object_entry(&entry.oid,
2051 object_type(entry.mode),
2052 fullname, 1);
2053 return;
2054 }
2055 if (S_ISDIR(entry.mode)) {
2056 struct tree_desc sub;
2057 struct pbase_tree_cache *tree;
2058 const char *down = name+cmplen+1;
2059 size_t downlen = name_cmp_len(down);
2060
2061 tree = pbase_tree_get(&entry.oid);
2062 if (!tree)
2063 return;
2064 init_tree_desc(&sub, &tree->oid,
2065 tree->tree_data, tree->tree_size);
2066
2067 add_pbase_object(&sub, down, downlen, fullname);
2068 pbase_tree_put(tree);
2069 }
2070 }
2071 }
2072
2073 static unsigned *done_pbase_paths;
2074 static int done_pbase_paths_num;
2075 static int done_pbase_paths_alloc;
2076 static int done_pbase_path_pos(unsigned hash)
2077 {
2078 int lo = 0;
2079 int hi = done_pbase_paths_num;
2080 while (lo < hi) {
2081 int mi = lo + (hi - lo) / 2;
2082 if (done_pbase_paths[mi] == hash)
2083 return mi;
2084 if (done_pbase_paths[mi] < hash)
2085 hi = mi;
2086 else
2087 lo = mi + 1;
2088 }
2089 return -lo-1;
2090 }
2091
2092 static int check_pbase_path(unsigned hash)
2093 {
2094 int pos = done_pbase_path_pos(hash);
2095 if (0 <= pos)
2096 return 1;
2097 pos = -pos - 1;
2098 ALLOC_GROW(done_pbase_paths,
2099 done_pbase_paths_num + 1,
2100 done_pbase_paths_alloc);
2101 done_pbase_paths_num++;
2102 if (pos < done_pbase_paths_num)
2103 MOVE_ARRAY(done_pbase_paths + pos + 1, done_pbase_paths + pos,
2104 done_pbase_paths_num - pos - 1);
2105 done_pbase_paths[pos] = hash;
2106 return 0;
2107 }
2108
2109 static void add_preferred_base_object(const char *name)
2110 {
2111 struct pbase_tree *it;
2112 size_t cmplen;
2113 unsigned hash = pack_name_hash_fn(name);
2114
2115 if (!num_preferred_base || check_pbase_path(hash))
2116 return;
2117
2118 cmplen = name_cmp_len(name);
2119 for (it = pbase_tree; it; it = it->next) {
2120 if (cmplen == 0) {
2121 add_object_entry(&it->pcache.oid, OBJ_TREE, NULL, 1);
2122 }
2123 else {
2124 struct tree_desc tree;
2125 init_tree_desc(&tree, &it->pcache.oid,
2126 it->pcache.tree_data, it->pcache.tree_size);
2127 add_pbase_object(&tree, name, cmplen, name);
2128 }
2129 }
2130 }
2131
2132 static void add_preferred_base(struct object_id *oid)
2133 {
2134 struct pbase_tree *it;
2135 void *data;
2136 unsigned long size;
2137 size_t size_st = 0;
2138 struct object_id tree_oid;
2139
2140 if (window <= num_preferred_base++)
2141 return;
2142
2143 data = odb_read_object_peeled(the_repository->objects, oid,
2144 OBJ_TREE, &size_st, &tree_oid);
2145 size = cast_size_t_to_ulong(size_st);
2146 if (!data)
2147 return;
2148
2149 for (it = pbase_tree; it; it = it->next) {
2150 if (oideq(&it->pcache.oid, &tree_oid)) {
2151 free(data);
2152 return;
2153 }
2154 }
2155
2156 CALLOC_ARRAY(it, 1);
2157 it->next = pbase_tree;
2158 pbase_tree = it;
2159
2160 oidcpy(&it->pcache.oid, &tree_oid);
2161 it->pcache.tree_data = data;
2162 it->pcache.tree_size = size;
2163 }
2164
2165 static void cleanup_preferred_base(void)
2166 {
2167 struct pbase_tree *it;
2168 unsigned i;
2169
2170 it = pbase_tree;
2171 pbase_tree = NULL;
2172 while (it) {
2173 struct pbase_tree *tmp = it;
2174 it = tmp->next;
2175 free(tmp->pcache.tree_data);
2176 free(tmp);
2177 }
2178
2179 for (i = 0; i < ARRAY_SIZE(pbase_tree_cache); i++) {
2180 if (!pbase_tree_cache[i])
2181 continue;
2182 free(pbase_tree_cache[i]->tree_data);
2183 FREE_AND_NULL(pbase_tree_cache[i]);
2184 }
2185
2186 FREE_AND_NULL(done_pbase_paths);
2187 done_pbase_paths_num = done_pbase_paths_alloc = 0;
2188 }
2189
2190 /*
2191 * Return 1 iff the object specified by "delta" can be sent
2192 * literally as a delta against the base in "base_sha1". If
2193 * so, then *base_out will point to the entry in our packing
2194 * list, or NULL if we must use the external-base list.
2195 *
2196 * Depth value does not matter - find_deltas() will
2197 * never consider reused delta as the base object to
2198 * deltify other objects against, in order to avoid
2199 * circular deltas.
2200 */
2201 static int can_reuse_delta(const struct object_id *base_oid,
2202 struct object_entry *delta,
2203 struct object_entry **base_out)
2204 {
2205 struct object_entry *base;
2206
2207 /*
2208 * First see if we're already sending the base (or it's explicitly in
2209 * our "excluded" list).
2210 */
2211 base = packlist_find(&to_pack, base_oid);
2212 if (base) {
2213 /*
2214 * A preferred base is omitted from the resulting pack, so it
2215 * can only be referenced by object ID.
2216 */
2217 if (base->preferred_base && !allow_ref_delta)
2218 return 0;
2219
2220 if (!in_same_island(&delta->idx.oid, &base->idx.oid))
2221 return 0;
2222 *base_out = base;
2223 return 1;
2224 }
2225
2226 /*
2227 * Otherwise, reachability bitmaps may tell us if the receiver has it,
2228 * even if it was buried too deep in history to make it into the
2229 * packing list.
2230 */
2231 if (allow_ref_delta && thin &&
2232 bitmap_has_oid_in_uninteresting(bitmap_git, base_oid)) {
2233 if (use_delta_islands) {
2234 if (!in_same_island(&delta->idx.oid, base_oid))
2235 return 0;
2236 }
2237 *base_out = NULL;
2238 return 1;
2239 }
2240
2241 return 0;
2242 }
2243
2244 static void prefetch_to_pack(uint32_t object_index_start) {
2245 struct oid_array to_fetch = OID_ARRAY_INIT;
2246 uint32_t i;
2247
2248 for (i = object_index_start; i < to_pack.nr_objects; i++) {
2249 struct object_entry *entry = to_pack.objects + i;
2250
2251 if (!odb_read_object_info_extended(the_repository->objects,
2252 &entry->idx.oid,
2253 NULL,
2254 OBJECT_INFO_FOR_PREFETCH))
2255 continue;
2256 oid_array_append(&to_fetch, &entry->idx.oid);
2257 }
2258 promisor_remote_get_direct(the_repository,
2259 to_fetch.oid, to_fetch.nr);
2260 oid_array_clear(&to_fetch);
2261 }
2262
2263 static void check_object(struct object_entry *entry, uint32_t object_index)
2264 {
2265 size_t canonical_size;
2266 enum object_type type;
2267 struct object_info oi = {.typep = &type, .sizep = &canonical_size};
2268
2269 if (IN_PACK(entry)) {
2270 struct packed_git *p = IN_PACK(entry);
2271 struct pack_window *w_curs = NULL;
2272 int have_base = 0;
2273 struct object_id base_ref;
2274 struct object_entry *base_entry;
2275 unsigned long used, used_0;
2276 size_t avail;
2277 off_t ofs;
2278 unsigned char *buf, c;
2279 enum object_type type;
2280 size_t in_pack_size;
2281
2282 buf = use_pack(p, &w_curs, entry->in_pack_offset, &avail);
2283
2284 /*
2285 * We want in_pack_type even if we do not reuse delta
2286 * since non-delta representations could still be reused.
2287 */
2288 used = unpack_object_header_buffer(buf, avail,
2289 &type,
2290 &in_pack_size);
2291 if (used == 0)
2292 goto give_up;
2293
2294 if (type < 0)
2295 BUG("invalid type %d", type);
2296 entry->in_pack_type = type;
2297
2298 /*
2299 * Determine if this is a delta and if so whether we can
2300 * reuse it or not. Otherwise let's find out as cheaply as
2301 * possible what the actual type and size for this object is.
2302 */
2303 switch (entry->in_pack_type) {
2304 default:
2305 /* Not a delta hence we've already got all we need. */
2306 oe_set_type(entry, entry->in_pack_type);
2307 SET_SIZE(entry, in_pack_size);
2308 entry->in_pack_header_size = used;
2309 if (oe_type(entry) < OBJ_COMMIT || oe_type(entry) > OBJ_BLOB)
2310 goto give_up;
2311 unuse_pack(&w_curs);
2312 return;
2313 case OBJ_REF_DELTA:
2314 if (reuse_delta && !entry->preferred_base) {
2315 oidread(&base_ref,
2316 use_pack(p, &w_curs,
2317 entry->in_pack_offset + used,
2318 NULL),
2319 the_repository->hash_algo);
2320 have_base = 1;
2321 }
2322 entry->in_pack_header_size = used + the_hash_algo->rawsz;
2323 break;
2324 case OBJ_OFS_DELTA:
2325 buf = use_pack(p, &w_curs,
2326 entry->in_pack_offset + used, NULL);
2327 used_0 = 0;
2328 c = buf[used_0++];
2329 ofs = c & 127;
2330 while (c & 128) {
2331 ofs += 1;
2332 if (!ofs || MSB(ofs, 7)) {
2333 error(_("delta base offset overflow in pack for %s"),
2334 oid_to_hex(&entry->idx.oid));
2335 goto give_up;
2336 }
2337 c = buf[used_0++];
2338 ofs = (ofs << 7) + (c & 127);
2339 }
2340 ofs = entry->in_pack_offset - ofs;
2341 if (ofs <= 0 || ofs >= entry->in_pack_offset) {
2342 error(_("delta base offset out of bound for %s"),
2343 oid_to_hex(&entry->idx.oid));
2344 goto give_up;
2345 }
2346 if (reuse_delta && !entry->preferred_base) {
2347 uint32_t pos;
2348 if (offset_to_pack_pos(p, ofs, &pos) < 0)
2349 goto give_up;
2350 if (!nth_packed_object_id(&base_ref, p,
2351 pack_pos_to_index(p, pos)))
2352 have_base = 1;
2353 }
2354 entry->in_pack_header_size = used + used_0;
2355 break;
2356 }
2357
2358 if (have_base &&
2359 can_reuse_delta(&base_ref, entry, &base_entry)) {
2360 oe_set_type(entry, entry->in_pack_type);
2361 SET_SIZE(entry, in_pack_size); /* delta size */
2362 SET_DELTA_SIZE(entry, in_pack_size);
2363
2364 if (base_entry) {
2365 SET_DELTA(entry, base_entry);
2366 entry->delta_sibling_idx = base_entry->delta_child_idx;
2367 SET_DELTA_CHILD(base_entry, entry);
2368 } else {
2369 SET_DELTA_EXT(entry, &base_ref);
2370 }
2371
2372 unuse_pack(&w_curs);
2373 return;
2374 }
2375
2376 if (oe_type(entry)) {
2377 off_t delta_pos;
2378
2379 /*
2380 * This must be a delta and we already know what the
2381 * final object type is. Let's extract the actual
2382 * object size from the delta header.
2383 */
2384 delta_pos = entry->in_pack_offset + entry->in_pack_header_size;
2385 canonical_size = get_size_from_delta(p, &w_curs,
2386 delta_pos);
2387 if (canonical_size == 0)
2388 goto give_up;
2389 SET_SIZE(entry, canonical_size);
2390 unuse_pack(&w_curs);
2391 return;
2392 }
2393
2394 /*
2395 * No choice but to fall back to the recursive delta walk
2396 * with odb_read_object_info() to find about the object type
2397 * at this point...
2398 */
2399 give_up:
2400 unuse_pack(&w_curs);
2401 }
2402
2403 if (odb_read_object_info_extended(the_repository->objects, &entry->idx.oid, &oi,
2404 OBJECT_INFO_SKIP_FETCH_OBJECT | OBJECT_INFO_LOOKUP_REPLACE) < 0) {
2405 if (repo_has_promisor_remote(the_repository)) {
2406 prefetch_to_pack(object_index);
2407 if (odb_read_object_info_extended(the_repository->objects, &entry->idx.oid, &oi,
2408 OBJECT_INFO_SKIP_FETCH_OBJECT | OBJECT_INFO_LOOKUP_REPLACE) < 0)
2409 type = -1;
2410 } else {
2411 type = -1;
2412 }
2413 }
2414 oe_set_type(entry, type);
2415 if (entry->type_valid) {
2416 SET_SIZE(entry, canonical_size);
2417 } else {
2418 /*
2419 * Bad object type is checked in prepare_pack(). This is
2420 * to permit a missing preferred base object to be ignored
2421 * as a preferred base. Doing so can result in a larger
2422 * pack file, but the transfer will still take place.
2423 */
2424 }
2425 }
2426
2427 static int pack_offset_sort(const void *_a, const void *_b)
2428 {
2429 const struct object_entry *a = *(struct object_entry **)_a;
2430 const struct object_entry *b = *(struct object_entry **)_b;
2431 const struct packed_git *a_in_pack = IN_PACK(a);
2432 const struct packed_git *b_in_pack = IN_PACK(b);
2433
2434 /* avoid filesystem trashing with loose objects */
2435 if (!a_in_pack && !b_in_pack)
2436 return oidcmp(&a->idx.oid, &b->idx.oid);
2437
2438 if (a_in_pack < b_in_pack)
2439 return -1;
2440 if (a_in_pack > b_in_pack)
2441 return 1;
2442 return a->in_pack_offset < b->in_pack_offset ? -1 :
2443 (a->in_pack_offset > b->in_pack_offset);
2444 }
2445
2446 /*
2447 * Drop an on-disk delta we were planning to reuse. Naively, this would
2448 * just involve blanking out the "delta" field, but we have to deal
2449 * with some extra book-keeping:
2450 *
2451 * 1. Removing ourselves from the delta_sibling linked list.
2452 *
2453 * 2. Updating our size/type to the non-delta representation. These were
2454 * either not recorded initially (size) or overwritten with the delta type
2455 * (type) when check_object() decided to reuse the delta.
2456 *
2457 * 3. Resetting our delta depth, as we are now a base object.
2458 */
2459 static void drop_reused_delta(struct object_entry *entry)
2460 {
2461 unsigned *idx = &to_pack.objects[entry->delta_idx - 1].delta_child_idx;
2462 struct object_info oi = OBJECT_INFO_INIT;
2463 enum object_type type;
2464 size_t size;
2465
2466 while (*idx) {
2467 struct object_entry *oe = &to_pack.objects[*idx - 1];
2468
2469 if (oe == entry)
2470 *idx = oe->delta_sibling_idx;
2471 else
2472 idx = &oe->delta_sibling_idx;
2473 }
2474 SET_DELTA(entry, NULL);
2475 entry->depth = 0;
2476
2477 oi.sizep = &size;
2478 oi.typep = &type;
2479 if (packed_object_info(NULL, IN_PACK(entry), entry->in_pack_offset, &oi) < 0) {
2480 /*
2481 * We failed to get the info from this pack for some reason;
2482 * fall back to odb_read_object_info, which may find another copy.
2483 * And if that fails, the error will be recorded in oe_type(entry)
2484 * and dealt with in prepare_pack().
2485 */
2486 oe_set_type(entry,
2487 odb_read_object_info(the_repository->objects,
2488 &entry->idx.oid, &size));
2489 } else {
2490 oe_set_type(entry, type);
2491 }
2492 SET_SIZE(entry, size);
2493 }
2494
2495 /*
2496 * Follow the chain of deltas from this entry onward, throwing away any links
2497 * that cause us to hit a cycle (as determined by the DFS state flags in
2498 * the entries).
2499 *
2500 * We also detect too-long reused chains that would violate our --depth
2501 * limit.
2502 */
2503 static void break_delta_chains(struct object_entry *entry)
2504 {
2505 /*
2506 * The actual depth of each object we will write is stored as an int,
2507 * as it cannot exceed our int "depth" limit. But before we break
2508 * changes based no that limit, we may potentially go as deep as the
2509 * number of objects, which is elsewhere bounded to a uint32_t.
2510 */
2511 uint32_t total_depth;
2512 struct object_entry *cur, *next;
2513
2514 for (cur = entry, total_depth = 0;
2515 cur;
2516 cur = DELTA(cur), total_depth++) {
2517 if (cur->dfs_state == DFS_DONE) {
2518 /*
2519 * We've already seen this object and know it isn't
2520 * part of a cycle. We do need to append its depth
2521 * to our count.
2522 */
2523 total_depth += cur->depth;
2524 break;
2525 }
2526
2527 /*
2528 * We break cycles before looping, so an ACTIVE state (or any
2529 * other cruft which made its way into the state variable)
2530 * is a bug.
2531 */
2532 if (cur->dfs_state != DFS_NONE)
2533 BUG("confusing delta dfs state in first pass: %d",
2534 cur->dfs_state);
2535
2536 /*
2537 * Now we know this is the first time we've seen the object. If
2538 * it's not a delta, we're done traversing, but we'll mark it
2539 * done to save time on future traversals.
2540 */
2541 if (!DELTA(cur)) {
2542 cur->dfs_state = DFS_DONE;
2543 break;
2544 }
2545
2546 /*
2547 * Mark ourselves as active and see if the next step causes
2548 * us to cycle to another active object. It's important to do
2549 * this _before_ we loop, because it impacts where we make the
2550 * cut, and thus how our total_depth counter works.
2551 * E.g., We may see a partial loop like:
2552 *
2553 * A -> B -> C -> D -> B
2554 *
2555 * Cutting B->C breaks the cycle. But now the depth of A is
2556 * only 1, and our total_depth counter is at 3. The size of the
2557 * error is always one less than the size of the cycle we
2558 * broke. Commits C and D were "lost" from A's chain.
2559 *
2560 * If we instead cut D->B, then the depth of A is correct at 3.
2561 * We keep all commits in the chain that we examined.
2562 */
2563 cur->dfs_state = DFS_ACTIVE;
2564 if (DELTA(cur)->dfs_state == DFS_ACTIVE) {
2565 drop_reused_delta(cur);
2566 cur->dfs_state = DFS_DONE;
2567 break;
2568 }
2569 }
2570
2571 /*
2572 * And now that we've gone all the way to the bottom of the chain, we
2573 * need to clear the active flags and set the depth fields as
2574 * appropriate. Unlike the loop above, which can quit when it drops a
2575 * delta, we need to keep going to look for more depth cuts. So we need
2576 * an extra "next" pointer to keep going after we reset cur->delta.
2577 */
2578 for (cur = entry; cur; cur = next) {
2579 next = DELTA(cur);
2580
2581 /*
2582 * We should have a chain of zero or more ACTIVE states down to
2583 * a final DONE. We can quit after the DONE, because either it
2584 * has no bases, or we've already handled them in a previous
2585 * call.
2586 */
2587 if (cur->dfs_state == DFS_DONE)
2588 break;
2589 else if (cur->dfs_state != DFS_ACTIVE)
2590 BUG("confusing delta dfs state in second pass: %d",
2591 cur->dfs_state);
2592
2593 /*
2594 * If the total_depth is more than depth, then we need to snip
2595 * the chain into two or more smaller chains that don't exceed
2596 * the maximum depth. Most of the resulting chains will contain
2597 * (depth + 1) entries (i.e., depth deltas plus one base), and
2598 * the last chain (i.e., the one containing entry) will contain
2599 * whatever entries are left over, namely
2600 * (total_depth % (depth + 1)) of them.
2601 *
2602 * Since we are iterating towards decreasing depth, we need to
2603 * decrement total_depth as we go, and we need to write to the
2604 * entry what its final depth will be after all of the
2605 * snipping. Since we're snipping into chains of length (depth
2606 * + 1) entries, the final depth of an entry will be its
2607 * original depth modulo (depth + 1). Any time we encounter an
2608 * entry whose final depth is supposed to be zero, we snip it
2609 * from its delta base, thereby making it so.
2610 */
2611 cur->depth = (total_depth--) % (depth + 1);
2612 if (!cur->depth)
2613 drop_reused_delta(cur);
2614
2615 cur->dfs_state = DFS_DONE;
2616 }
2617 }
2618
2619 static void get_object_details(void)
2620 {
2621 uint32_t i;
2622 struct object_entry **sorted_by_offset;
2623
2624 if (progress)
2625 progress_state = start_progress(the_repository,
2626 _("Counting objects"),
2627 to_pack.nr_objects);
2628
2629 CALLOC_ARRAY(sorted_by_offset, to_pack.nr_objects);
2630 for (i = 0; i < to_pack.nr_objects; i++)
2631 sorted_by_offset[i] = to_pack.objects + i;
2632 QSORT(sorted_by_offset, to_pack.nr_objects, pack_offset_sort);
2633
2634 for (i = 0; i < to_pack.nr_objects; i++) {
2635 struct object_entry *entry = sorted_by_offset[i];
2636 check_object(entry, i);
2637 if (entry->type_valid &&
2638 oe_size_greater_than(&to_pack, entry,
2639 repo_settings_get_big_file_threshold(the_repository)))
2640 entry->no_try_delta = 1;
2641 display_progress(progress_state, i + 1);
2642 }
2643 stop_progress(&progress_state);
2644
2645 /*
2646 * This must happen in a second pass, since we rely on the delta
2647 * information for the whole list being completed.
2648 */
2649 for (i = 0; i < to_pack.nr_objects; i++)
2650 break_delta_chains(&to_pack.objects[i]);
2651
2652 free(sorted_by_offset);
2653 }
2654
2655 /*
2656 * We search for deltas in a list sorted by type, by filename hash, and then
2657 * by size, so that we see progressively smaller and smaller files.
2658 * That's because we prefer deltas to be from the bigger file
2659 * to the smaller -- deletes are potentially cheaper, but perhaps
2660 * more importantly, the bigger file is likely the more recent
2661 * one. The deepest deltas are therefore the oldest objects which are
2662 * less susceptible to be accessed often.
2663 */
2664 static int type_size_sort(const void *_a, const void *_b)
2665 {
2666 const struct object_entry *a = *(struct object_entry **)_a;
2667 const struct object_entry *b = *(struct object_entry **)_b;
2668 const enum object_type a_type = oe_type(a);
2669 const enum object_type b_type = oe_type(b);
2670 const unsigned long a_size = SIZE(a);
2671 const unsigned long b_size = SIZE(b);
2672
2673 if (a_type > b_type)
2674 return -1;
2675 if (a_type < b_type)
2676 return 1;
2677 if (a->hash > b->hash)
2678 return -1;
2679 if (a->hash < b->hash)
2680 return 1;
2681 if (a->preferred_base > b->preferred_base)
2682 return -1;
2683 if (a->preferred_base < b->preferred_base)
2684 return 1;
2685 if (use_delta_islands) {
2686 const int island_cmp = island_delta_cmp(&a->idx.oid, &b->idx.oid);
2687 if (island_cmp)
2688 return island_cmp;
2689 }
2690 if (a_size > b_size)
2691 return -1;
2692 if (a_size < b_size)
2693 return 1;
2694 return a < b ? -1 : (a > b); /* newest first */
2695 }
2696
2697 struct unpacked {
2698 struct object_entry *entry;
2699 void *data;
2700 struct delta_index *index;
2701 unsigned depth;
2702 };
2703
2704 static int delta_cacheable(size_t src_size, size_t trg_size,
2705 size_t delta_size)
2706 {
2707 if (max_delta_cache_size && delta_cache_size + delta_size > max_delta_cache_size)
2708 return 0;
2709
2710 if (delta_size < cache_max_small_delta_size)
2711 return 1;
2712
2713 /* cache delta, if objects are large enough compared to delta size */
2714 if ((src_size >> 20) + (trg_size >> 21) > (delta_size >> 10))
2715 return 1;
2716
2717 return 0;
2718 }
2719
2720 /* Protect delta_cache_size */
2721 static pthread_mutex_t cache_mutex;
2722 #define cache_lock() pthread_mutex_lock(&cache_mutex)
2723 #define cache_unlock() pthread_mutex_unlock(&cache_mutex)
2724
2725 /*
2726 * Protect object list partitioning (e.g. struct thread_param) and
2727 * progress_state
2728 */
2729 static pthread_mutex_t progress_mutex;
2730 #define progress_lock() pthread_mutex_lock(&progress_mutex)
2731 #define progress_unlock() pthread_mutex_unlock(&progress_mutex)
2732
2733 /*
2734 * Access to struct object_entry is unprotected since each thread owns
2735 * a portion of the main object list. Just don't access object entries
2736 * ahead in the list because they can be stolen and would need
2737 * progress_mutex for protection.
2738 */
2739
2740 static inline int oe_size_less_than(struct packing_data *pack,
2741 const struct object_entry *lhs,
2742 size_t rhs)
2743 {
2744 if (lhs->size_valid)
2745 return lhs->size_ < rhs;
2746 if (rhs < pack->oe_size_limit) /* rhs < 2^x <= lhs ? */
2747 return 0;
2748 return oe_get_size_slow(pack, lhs) < rhs;
2749 }
2750
2751 static inline void oe_set_tree_depth(struct packing_data *pack,
2752 struct object_entry *e,
2753 unsigned int tree_depth)
2754 {
2755 if (!pack->tree_depth)
2756 CALLOC_ARRAY(pack->tree_depth, pack->nr_alloc);
2757 pack->tree_depth[e - pack->objects] = tree_depth;
2758 }
2759
2760 static void record_tree_depth(const struct object_id *oid, const char *name)
2761 {
2762 const char *p;
2763 unsigned depth;
2764 struct object_entry *ent;
2765
2766 /* the empty string is a root tree, which is depth 0 */
2767 depth = *name ? 1 : 0;
2768 for (p = strchr(name, '/'); p; p = strchr(p + 1, '/'))
2769 depth++;
2770
2771 ent = packlist_find(&to_pack, oid);
2772 if (ent && depth > oe_tree_depth(&to_pack, ent))
2773 oe_set_tree_depth(&to_pack, ent, depth);
2774 }
2775
2776 /*
2777 * Return the size of the object without doing any delta
2778 * reconstruction (so non-deltas are true object sizes, but deltas
2779 * return the size of the delta data).
2780 */
2781 size_t oe_get_size_slow(struct packing_data *pack,
2782 const struct object_entry *e)
2783 {
2784 struct packed_git *p;
2785 struct pack_window *w_curs;
2786 unsigned char *buf;
2787 enum object_type type;
2788 unsigned long used;
2789 size_t avail, size;
2790
2791 if (e->type_ != OBJ_OFS_DELTA && e->type_ != OBJ_REF_DELTA) {
2792 size_t sz;
2793 packing_data_lock(&to_pack);
2794 if (odb_read_object_info(the_repository->objects,
2795 &e->idx.oid, &sz) < 0)
2796 die(_("unable to get size of %s"),
2797 oid_to_hex(&e->idx.oid));
2798 packing_data_unlock(&to_pack);
2799 return sz;
2800 }
2801
2802 p = oe_in_pack(pack, e);
2803 if (!p)
2804 BUG("when e->type is a delta, it must belong to a pack");
2805
2806 packing_data_lock(&to_pack);
2807 w_curs = NULL;
2808 buf = use_pack(p, &w_curs, e->in_pack_offset, &avail);
2809 used = unpack_object_header_buffer(buf, avail, &type, &size);
2810 if (used == 0)
2811 die(_("unable to parse object header of %s"),
2812 oid_to_hex(&e->idx.oid));
2813
2814 unuse_pack(&w_curs);
2815 packing_data_unlock(&to_pack);
2816 return size;
2817 }
2818
2819 static int try_delta(struct unpacked *trg, struct unpacked *src,
2820 unsigned max_depth, size_t *mem_usage)
2821 {
2822 struct object_entry *trg_entry = trg->entry;
2823 struct object_entry *src_entry = src->entry;
2824 unsigned long trg_size, src_size, sizediff, max_size, sz;
2825 size_t delta_size;
2826 unsigned ref_depth;
2827 enum object_type type;
2828 void *delta_buf;
2829
2830 /* Don't bother doing diffs between different types */
2831 if (oe_type(trg_entry) != oe_type(src_entry))
2832 return -1;
2833
2834 /*
2835 * We do not bother to try a delta that we discarded on an
2836 * earlier try, but only when reusing delta data. Note that
2837 * src_entry that is marked as the preferred_base should always
2838 * be considered, as even if we produce a suboptimal delta against
2839 * it, we will still save the transfer cost, as we already know
2840 * the other side has it and we won't send src_entry at all.
2841 */
2842 if (reuse_delta && IN_PACK(trg_entry) &&
2843 IN_PACK(trg_entry) == IN_PACK(src_entry) &&
2844 !src_entry->preferred_base &&
2845 trg_entry->in_pack_type != OBJ_REF_DELTA &&
2846 trg_entry->in_pack_type != OBJ_OFS_DELTA)
2847 return 0;
2848
2849 /* Let's not bust the allowed depth. */
2850 if (src->depth >= max_depth)
2851 return 0;
2852
2853 /* Now some size filtering heuristics. */
2854 trg_size = SIZE(trg_entry);
2855 if (!DELTA(trg_entry)) {
2856 max_size = trg_size/2 - the_hash_algo->rawsz;
2857 ref_depth = 1;
2858 } else {
2859 max_size = DELTA_SIZE(trg_entry);
2860 ref_depth = trg->depth;
2861 }
2862 max_size = (uint64_t)max_size * (max_depth - src->depth) /
2863 (max_depth - ref_depth + 1);
2864 if (max_size == 0)
2865 return 0;
2866 src_size = SIZE(src_entry);
2867 sizediff = src_size < trg_size ? trg_size - src_size : 0;
2868 if (sizediff >= max_size)
2869 return 0;
2870 if (trg_size < src_size / 32)
2871 return 0;
2872
2873 if (!in_same_island(&trg->entry->idx.oid, &src->entry->idx.oid))
2874 return 0;
2875
2876 /* Load data if not already done */
2877 if (!trg->data) {
2878 size_t sz_st = 0;
2879 packing_data_lock(&to_pack);
2880 trg->data = odb_read_object(the_repository->objects,
2881 &trg_entry->idx.oid, &type,
2882 &sz_st);
2883 sz = cast_size_t_to_ulong(sz_st);
2884 packing_data_unlock(&to_pack);
2885 if (!trg->data)
2886 die(_("object %s cannot be read"),
2887 oid_to_hex(&trg_entry->idx.oid));
2888 if (sz != trg_size)
2889 die(_("object %s inconsistent object length (%"PRIuMAX" vs %"PRIuMAX")"),
2890 oid_to_hex(&trg_entry->idx.oid), (uintmax_t)sz,
2891 (uintmax_t)trg_size);
2892 *mem_usage += sz;
2893 }
2894 if (!src->data) {
2895 size_t sz_st = 0;
2896 packing_data_lock(&to_pack);
2897 src->data = odb_read_object(the_repository->objects,
2898 &src_entry->idx.oid, &type,
2899 &sz_st);
2900 sz = cast_size_t_to_ulong(sz_st);
2901 packing_data_unlock(&to_pack);
2902 if (!src->data) {
2903 if (src_entry->preferred_base) {
2904 static int warned = 0;
2905 if (!warned++)
2906 warning(_("object %s cannot be read"),
2907 oid_to_hex(&src_entry->idx.oid));
2908 /*
2909 * Those objects are not included in the
2910 * resulting pack. Be resilient and ignore
2911 * them if they can't be read, in case the
2912 * pack could be created nevertheless.
2913 */
2914 return 0;
2915 }
2916 die(_("object %s cannot be read"),
2917 oid_to_hex(&src_entry->idx.oid));
2918 }
2919 if (sz != src_size)
2920 die(_("object %s inconsistent object length (%"PRIuMAX" vs %"PRIuMAX")"),
2921 oid_to_hex(&src_entry->idx.oid), (uintmax_t)sz,
2922 (uintmax_t)src_size);
2923 *mem_usage += sz;
2924 }
2925 if (!src->index) {
2926 src->index = create_delta_index(src->data, src_size);
2927 if (!src->index) {
2928 static int warned = 0;
2929 if (!warned++)
2930 warning(_("suboptimal pack - out of memory"));
2931 return 0;
2932 }
2933 *mem_usage += sizeof_delta_index(src->index);
2934 }
2935
2936 delta_buf = create_delta(src->index, trg->data, trg_size, &delta_size, max_size);
2937 if (!delta_buf)
2938 return 0;
2939
2940 if (DELTA(trg_entry)) {
2941 /* Prefer only shallower same-sized deltas. */
2942 if (delta_size == DELTA_SIZE(trg_entry) &&
2943 src->depth + 1 >= trg->depth) {
2944 free(delta_buf);
2945 return 0;
2946 }
2947 }
2948
2949 /*
2950 * Handle memory allocation outside of the cache
2951 * accounting lock. Compiler will optimize the strangeness
2952 * away when NO_PTHREADS is defined.
2953 */
2954 free(trg_entry->delta_data);
2955 cache_lock();
2956 if (trg_entry->delta_data) {
2957 delta_cache_size -= DELTA_SIZE(trg_entry);
2958 trg_entry->delta_data = NULL;
2959 }
2960 if (delta_cacheable(src_size, trg_size, delta_size)) {
2961 delta_cache_size += delta_size;
2962 cache_unlock();
2963 trg_entry->delta_data = xrealloc(delta_buf, delta_size);
2964 } else {
2965 cache_unlock();
2966 free(delta_buf);
2967 }
2968
2969 SET_DELTA(trg_entry, src_entry);
2970 SET_DELTA_SIZE(trg_entry, delta_size);
2971 trg->depth = src->depth + 1;
2972
2973 return 1;
2974 }
2975
2976 static unsigned int check_delta_limit(struct object_entry *me, unsigned int n)
2977 {
2978 struct object_entry *child = DELTA_CHILD(me);
2979 unsigned int m = n;
2980 while (child) {
2981 const unsigned int c = check_delta_limit(child, n + 1);
2982 if (m < c)
2983 m = c;
2984 child = DELTA_SIBLING(child);
2985 }
2986 return m;
2987 }
2988
2989 static size_t free_unpacked(struct unpacked *n)
2990 {
2991 size_t freed_mem = sizeof_delta_index(n->index);
2992 free_delta_index(n->index);
2993 n->index = NULL;
2994 if (n->data) {
2995 freed_mem += SIZE(n->entry);
2996 FREE_AND_NULL(n->data);
2997 }
2998 n->entry = NULL;
2999 n->depth = 0;
3000 return freed_mem;
3001 }
3002
3003 static void find_deltas(struct object_entry **list, unsigned *list_size,
3004 int window, int depth, unsigned *processed)
3005 {
3006 uint32_t i, idx = 0, count = 0;
3007 struct unpacked *array;
3008 size_t mem_usage = 0;
3009
3010 CALLOC_ARRAY(array, window);
3011
3012 for (;;) {
3013 struct object_entry *entry;
3014 struct unpacked *n = array + idx;
3015 int j, max_depth, best_base = -1;
3016
3017 progress_lock();
3018 if (!*list_size) {
3019 progress_unlock();
3020 break;
3021 }
3022 entry = *list++;
3023 (*list_size)--;
3024 if (!entry->preferred_base) {
3025 (*processed)++;
3026 display_progress(progress_state, *processed);
3027 }
3028 progress_unlock();
3029
3030 mem_usage -= free_unpacked(n);
3031 n->entry = entry;
3032
3033 while (window_memory_limit &&
3034 mem_usage > window_memory_limit &&
3035 count > 1) {
3036 const uint32_t tail = (idx + window - count) % window;
3037 mem_usage -= free_unpacked(array + tail);
3038 count--;
3039 }
3040
3041 /* We do not compute delta to *create* objects we are not
3042 * going to pack.
3043 */
3044 if (entry->preferred_base)
3045 goto next;
3046
3047 /*
3048 * If the current object is at pack edge, take the depth the
3049 * objects that depend on the current object into account
3050 * otherwise they would become too deep.
3051 */
3052 max_depth = depth;
3053 if (DELTA_CHILD(entry)) {
3054 max_depth -= check_delta_limit(entry, 0);
3055 if (max_depth <= 0)
3056 goto next;
3057 }
3058
3059 j = window;
3060 while (--j > 0) {
3061 int ret;
3062 uint32_t other_idx = idx + j;
3063 struct unpacked *m;
3064 if (other_idx >= window)
3065 other_idx -= window;
3066 m = array + other_idx;
3067 if (!m->entry)
3068 break;
3069 ret = try_delta(n, m, max_depth, &mem_usage);
3070 if (ret < 0)
3071 break;
3072 else if (ret > 0)
3073 best_base = other_idx;
3074 }
3075
3076 /*
3077 * If we decided to cache the delta data, then it is best
3078 * to compress it right away. First because we have to do
3079 * it anyway, and doing it here while we're threaded will
3080 * save a lot of time in the non threaded write phase,
3081 * as well as allow for caching more deltas within
3082 * the same cache size limit.
3083 * ...
3084 * But only if not writing to stdout, since in that case
3085 * the network is most likely throttling writes anyway,
3086 * and therefore it is best to go to the write phase ASAP
3087 * instead, as we can afford spending more time compressing
3088 * between writes at that moment.
3089 */
3090 if (entry->delta_data && !pack_to_stdout) {
3091 unsigned long size;
3092
3093 size = do_compress(&entry->delta_data, DELTA_SIZE(entry));
3094 if (size < (1U << OE_Z_DELTA_BITS)) {
3095 entry->z_delta_size = size;
3096 cache_lock();
3097 delta_cache_size -= DELTA_SIZE(entry);
3098 delta_cache_size += entry->z_delta_size;
3099 cache_unlock();
3100 } else {
3101 FREE_AND_NULL(entry->delta_data);
3102 entry->z_delta_size = 0;
3103 }
3104 }
3105
3106 /* if we made n a delta, and if n is already at max
3107 * depth, leaving it in the window is pointless. we
3108 * should evict it first.
3109 */
3110 if (DELTA(entry) && max_depth <= n->depth)
3111 continue;
3112
3113 /*
3114 * Move the best delta base up in the window, after the
3115 * currently deltified object, to keep it longer. It will
3116 * be the first base object to be attempted next.
3117 */
3118 if (DELTA(entry)) {
3119 struct unpacked swap = array[best_base];
3120 int dist = (window + idx - best_base) % window;
3121 int dst = best_base;
3122 while (dist--) {
3123 int src = (dst + 1) % window;
3124 array[dst] = array[src];
3125 dst = src;
3126 }
3127 array[dst] = swap;
3128 }
3129
3130 next:
3131 idx++;
3132 if (count + 1 < window)
3133 count++;
3134 if (idx >= window)
3135 idx = 0;
3136 }
3137
3138 for (i = 0; i < window; ++i) {
3139 free_delta_index(array[i].index);
3140 free(array[i].data);
3141 }
3142 free(array);
3143 }
3144
3145 /*
3146 * The main object list is split into smaller lists, each is handed to
3147 * one worker.
3148 *
3149 * The main thread waits on the condition that (at least) one of the workers
3150 * has stopped working (which is indicated in the .working member of
3151 * struct thread_params).
3152 *
3153 * When a work thread has completed its work, it sets .working to 0 and
3154 * signals the main thread and waits on the condition that .data_ready
3155 * becomes 1.
3156 *
3157 * The main thread steals half of the work from the worker that has
3158 * most work left to hand it to the idle worker.
3159 */
3160
3161 struct thread_params {
3162 pthread_t thread;
3163 struct object_entry **list;
3164 struct packing_region *regions;
3165 unsigned list_size;
3166 unsigned remaining;
3167 int window;
3168 int depth;
3169 int working;
3170 int data_ready;
3171 pthread_mutex_t mutex;
3172 pthread_cond_t cond;
3173 unsigned *processed;
3174 };
3175
3176 static pthread_cond_t progress_cond;
3177
3178 /*
3179 * Mutex and conditional variable can't be statically-initialized on Windows.
3180 */
3181 static void init_threaded_search(void)
3182 {
3183 pthread_mutex_init(&cache_mutex, NULL);
3184 pthread_mutex_init(&progress_mutex, NULL);
3185 pthread_cond_init(&progress_cond, NULL);
3186 }
3187
3188 static void cleanup_threaded_search(void)
3189 {
3190 pthread_cond_destroy(&progress_cond);
3191 pthread_mutex_destroy(&cache_mutex);
3192 pthread_mutex_destroy(&progress_mutex);
3193 }
3194
3195 static void *threaded_find_deltas(void *arg)
3196 {
3197 struct thread_params *me = arg;
3198
3199 progress_lock();
3200 while (me->remaining) {
3201 progress_unlock();
3202
3203 find_deltas(me->list, &me->remaining,
3204 me->window, me->depth, me->processed);
3205
3206 progress_lock();
3207 me->working = 0;
3208 pthread_cond_signal(&progress_cond);
3209 progress_unlock();
3210
3211 /*
3212 * We must not set ->data_ready before we wait on the
3213 * condition because the main thread may have set it to 1
3214 * before we get here. In order to be sure that new
3215 * work is available if we see 1 in ->data_ready, it
3216 * was initialized to 0 before this thread was spawned
3217 * and we reset it to 0 right away.
3218 */
3219 pthread_mutex_lock(&me->mutex);
3220 while (!me->data_ready)
3221 pthread_cond_wait(&me->cond, &me->mutex);
3222 me->data_ready = 0;
3223 pthread_mutex_unlock(&me->mutex);
3224
3225 progress_lock();
3226 }
3227 progress_unlock();
3228 /* leave ->working 1 so that this doesn't get more work assigned */
3229 return NULL;
3230 }
3231
3232 static void ll_find_deltas(struct object_entry **list, unsigned list_size,
3233 int window, int depth, unsigned *processed)
3234 {
3235 struct thread_params *p;
3236 int i, ret, active_threads = 0;
3237
3238 init_threaded_search();
3239
3240 if (delta_search_threads <= 1) {
3241 find_deltas(list, &list_size, window, depth, processed);
3242 cleanup_threaded_search();
3243 return;
3244 }
3245 if (progress > pack_to_stdout)
3246 fprintf_ln(stderr, _("Delta compression using up to %d threads"),
3247 delta_search_threads);
3248 CALLOC_ARRAY(p, delta_search_threads);
3249
3250 /* Partition the work amongst work threads. */
3251 for (i = 0; i < delta_search_threads; i++) {
3252 unsigned sub_size = list_size / (delta_search_threads - i);
3253
3254 /* don't use too small segments or no deltas will be found */
3255 if (sub_size < 2*window && i+1 < delta_search_threads)
3256 sub_size = 0;
3257
3258 p[i].window = window;
3259 p[i].depth = depth;
3260 p[i].processed = processed;
3261 p[i].working = 1;
3262 p[i].data_ready = 0;
3263
3264 /* try to split chunks on "path" boundaries */
3265 while (sub_size && sub_size < list_size &&
3266 list[sub_size]->hash &&
3267 list[sub_size]->hash == list[sub_size-1]->hash)
3268 sub_size++;
3269
3270 p[i].list = list;
3271 p[i].list_size = sub_size;
3272 p[i].remaining = sub_size;
3273
3274 list += sub_size;
3275 list_size -= sub_size;
3276 }
3277
3278 /* Start work threads. */
3279 for (i = 0; i < delta_search_threads; i++) {
3280 if (!p[i].list_size)
3281 continue;
3282 pthread_mutex_init(&p[i].mutex, NULL);
3283 pthread_cond_init(&p[i].cond, NULL);
3284 ret = pthread_create(&p[i].thread, NULL,
3285 threaded_find_deltas, &p[i]);
3286 if (ret)
3287 die(_("unable to create thread: %s"), strerror(ret));
3288 active_threads++;
3289 }
3290
3291 /*
3292 * Now let's wait for work completion. Each time a thread is done
3293 * with its work, we steal half of the remaining work from the
3294 * thread with the largest number of unprocessed objects and give
3295 * it to that newly idle thread. This ensure good load balancing
3296 * until the remaining object list segments are simply too short
3297 * to be worth splitting anymore.
3298 */
3299 while (active_threads) {
3300 struct thread_params *target = NULL;
3301 struct thread_params *victim = NULL;
3302 unsigned sub_size = 0;
3303
3304 progress_lock();
3305 for (;;) {
3306 for (i = 0; !target && i < delta_search_threads; i++)
3307 if (!p[i].working)
3308 target = &p[i];
3309 if (target)
3310 break;
3311 pthread_cond_wait(&progress_cond, &progress_mutex);
3312 }
3313
3314 for (i = 0; i < delta_search_threads; i++)
3315 if (p[i].remaining > 2*window &&
3316 (!victim || victim->remaining < p[i].remaining))
3317 victim = &p[i];
3318 if (victim) {
3319 sub_size = victim->remaining / 2;
3320 list = victim->list + victim->list_size - sub_size;
3321 while (sub_size && list[0]->hash &&
3322 list[0]->hash == list[-1]->hash) {
3323 list++;
3324 sub_size--;
3325 }
3326 if (!sub_size) {
3327 /*
3328 * It is possible for some "paths" to have
3329 * so many objects that no hash boundary
3330 * might be found. Let's just steal the
3331 * exact half in that case.
3332 */
3333 sub_size = victim->remaining / 2;
3334 list -= sub_size;
3335 }
3336 target->list = list;
3337 victim->list_size -= sub_size;
3338 victim->remaining -= sub_size;
3339 }
3340 target->list_size = sub_size;
3341 target->remaining = sub_size;
3342 target->working = 1;
3343 progress_unlock();
3344
3345 pthread_mutex_lock(&target->mutex);
3346 target->data_ready = 1;
3347 pthread_cond_signal(&target->cond);
3348 pthread_mutex_unlock(&target->mutex);
3349
3350 if (!sub_size) {
3351 pthread_join(target->thread, NULL);
3352 pthread_cond_destroy(&target->cond);
3353 pthread_mutex_destroy(&target->mutex);
3354 active_threads--;
3355 }
3356 }
3357 cleanup_threaded_search();
3358 free(p);
3359 }
3360
3361 static int obj_is_packed(const struct object_id *oid)
3362 {
3363 return packlist_find(&to_pack, oid) ||
3364 (reuse_packfile_bitmap &&
3365 bitmap_walk_contains(bitmap_git, reuse_packfile_bitmap, oid));
3366 }
3367
3368 static void add_tag_chain(const struct object_id *oid)
3369 {
3370 struct tag *tag;
3371
3372 /*
3373 * We catch duplicates already in add_object_entry(), but we'd
3374 * prefer to do this extra check to avoid having to parse the
3375 * tag at all if we already know that it's being packed (e.g., if
3376 * it was included via bitmaps, we would not have parsed it
3377 * previously).
3378 */
3379 if (obj_is_packed(oid))
3380 return;
3381
3382 tag = lookup_tag(the_repository, oid);
3383 while (1) {
3384 if (!tag || parse_tag(the_repository, tag) || !tag->tagged)
3385 die(_("unable to pack objects reachable from tag %s"),
3386 oid_to_hex(oid));
3387
3388 add_object_entry(&tag->object.oid, OBJ_TAG, NULL, 0);
3389
3390 if (tag->tagged->type != OBJ_TAG)
3391 return;
3392
3393 tag = (struct tag *)tag->tagged;
3394 }
3395 }
3396
3397 static int add_ref_tag(const struct reference *ref, void *cb_data UNUSED)
3398 {
3399 struct object_id peeled;
3400
3401 if (!reference_get_peeled_oid(the_repository, ref, &peeled) &&
3402 obj_is_packed(&peeled))
3403 add_tag_chain(ref->oid);
3404 return 0;
3405 }
3406
3407 static int should_attempt_deltas(struct object_entry *entry)
3408 {
3409 if (DELTA(entry))
3410 /* This happens if we decided to reuse existing
3411 * delta from a pack. "reuse_delta &&" is implied.
3412 */
3413 return 0;
3414
3415 if (!entry->type_valid ||
3416 oe_size_less_than(&to_pack, entry, 50))
3417 return 0;
3418
3419 if (entry->no_try_delta)
3420 return 0;
3421
3422 if (entry->preferred_base && !allow_ref_delta)
3423 return 0;
3424
3425 if (!entry->preferred_base) {
3426 if (oe_type(entry) < 0)
3427 die(_("unable to get type of object %s"),
3428 oid_to_hex(&entry->idx.oid));
3429 } else if (oe_type(entry) < 0) {
3430 /*
3431 * This object is not found, but we
3432 * don't have to include it anyway.
3433 */
3434 return 0;
3435 }
3436
3437 return 1;
3438 }
3439
3440 static void find_deltas_for_region(struct object_entry *list,
3441 struct packing_region *region,
3442 unsigned int *processed)
3443 {
3444 struct object_entry **delta_list;
3445 unsigned int delta_list_nr = 0;
3446
3447 ALLOC_ARRAY(delta_list, region->nr);
3448 for (size_t i = 0; i < region->nr; i++) {
3449 struct object_entry *entry = list + region->start + i;
3450 if (should_attempt_deltas(entry))
3451 delta_list[delta_list_nr++] = entry;
3452 }
3453
3454 QSORT(delta_list, delta_list_nr, type_size_sort);
3455 find_deltas(delta_list, &delta_list_nr, window, depth, processed);
3456 free(delta_list);
3457 }
3458
3459 static void find_deltas_by_region(struct object_entry *list,
3460 struct packing_region *regions,
3461 size_t start, size_t nr)
3462 {
3463 unsigned int processed = 0;
3464 size_t progress_nr;
3465
3466 if (!nr)
3467 return;
3468
3469 progress_nr = regions[nr - 1].start + regions[nr - 1].nr;
3470
3471 if (progress)
3472 progress_state = start_progress(the_repository,
3473 _("Compressing objects by path"),
3474 progress_nr);
3475
3476 while (nr--)
3477 find_deltas_for_region(list,
3478 &regions[start++],
3479 &processed);
3480
3481 display_progress(progress_state, progress_nr);
3482 stop_progress(&progress_state);
3483 }
3484
3485 static void *threaded_find_deltas_by_path(void *arg)
3486 {
3487 struct thread_params *me = arg;
3488
3489 progress_lock();
3490 while (me->remaining) {
3491 while (me->remaining) {
3492 progress_unlock();
3493 find_deltas_for_region(to_pack.objects,
3494 me->regions,
3495 me->processed);
3496 progress_lock();
3497 me->remaining--;
3498 me->regions++;
3499 }
3500
3501 me->working = 0;
3502 pthread_cond_signal(&progress_cond);
3503 progress_unlock();
3504
3505 /*
3506 * We must not set ->data_ready before we wait on the
3507 * condition because the main thread may have set it to 1
3508 * before we get here. In order to be sure that new
3509 * work is available if we see 1 in ->data_ready, it
3510 * was initialized to 0 before this thread was spawned
3511 * and we reset it to 0 right away.
3512 */
3513 pthread_mutex_lock(&me->mutex);
3514 while (!me->data_ready)
3515 pthread_cond_wait(&me->cond, &me->mutex);
3516 me->data_ready = 0;
3517 pthread_mutex_unlock(&me->mutex);
3518
3519 progress_lock();
3520 }
3521 progress_unlock();
3522 /* leave ->working 1 so that this doesn't get more work assigned */
3523 return NULL;
3524 }
3525
3526 static void ll_find_deltas_by_region(struct object_entry *list,
3527 struct packing_region *regions,
3528 uint32_t start, uint32_t nr)
3529 {
3530 struct thread_params *p;
3531 int i, ret, active_threads = 0;
3532 unsigned int processed = 0;
3533 uint32_t progress_nr;
3534 init_threaded_search();
3535
3536 if (!nr)
3537 return;
3538
3539 progress_nr = regions[nr - 1].start + regions[nr - 1].nr;
3540 if (delta_search_threads <= 1) {
3541 find_deltas_by_region(list, regions, start, nr);
3542 cleanup_threaded_search();
3543 return;
3544 }
3545
3546 if (progress > pack_to_stdout)
3547 fprintf_ln(stderr,
3548 Q_("Path-based delta compression using up to %d thread",
3549 "Path-based delta compression using up to %d threads",
3550 delta_search_threads),
3551 delta_search_threads);
3552 CALLOC_ARRAY(p, delta_search_threads);
3553
3554 if (progress)
3555 progress_state = start_progress(the_repository,
3556 _("Compressing objects by path"),
3557 progress_nr);
3558 /* Partition the work amongst work threads. */
3559 for (i = 0; i < delta_search_threads; i++) {
3560 unsigned sub_size = nr / (delta_search_threads - i);
3561
3562 p[i].window = window;
3563 p[i].depth = depth;
3564 p[i].processed = &processed;
3565 p[i].working = 1;
3566 p[i].data_ready = 0;
3567
3568 p[i].regions = regions;
3569 p[i].list_size = sub_size;
3570 p[i].remaining = sub_size;
3571
3572 regions += sub_size;
3573 nr -= sub_size;
3574 }
3575
3576 /* Start work threads. */
3577 for (i = 0; i < delta_search_threads; i++) {
3578 if (!p[i].list_size)
3579 continue;
3580 pthread_mutex_init(&p[i].mutex, NULL);
3581 pthread_cond_init(&p[i].cond, NULL);
3582 ret = pthread_create(&p[i].thread, NULL,
3583 threaded_find_deltas_by_path, &p[i]);
3584 if (ret)
3585 die(_("unable to create thread: %s"), strerror(ret));
3586 active_threads++;
3587 }
3588
3589 /*
3590 * Now let's wait for work completion. Each time a thread is done
3591 * with its work, we steal half of the remaining work from the
3592 * thread with the largest number of unprocessed objects and give
3593 * it to that newly idle thread. This ensure good load balancing
3594 * until the remaining object list segments are simply too short
3595 * to be worth splitting anymore.
3596 */
3597 while (active_threads) {
3598 struct thread_params *target = NULL;
3599 struct thread_params *victim = NULL;
3600 unsigned sub_size = 0;
3601
3602 progress_lock();
3603 for (;;) {
3604 for (i = 0; !target && i < delta_search_threads; i++)
3605 if (!p[i].working)
3606 target = &p[i];
3607 if (target)
3608 break;
3609 pthread_cond_wait(&progress_cond, &progress_mutex);
3610 }
3611
3612 for (i = 0; i < delta_search_threads; i++)
3613 if (p[i].remaining > 2*window &&
3614 (!victim || victim->remaining < p[i].remaining))
3615 victim = &p[i];
3616 if (victim) {
3617 sub_size = victim->remaining / 2;
3618 target->regions = victim->regions + victim->remaining - sub_size;
3619 victim->list_size -= sub_size;
3620 victim->remaining -= sub_size;
3621 }
3622 target->list_size = sub_size;
3623 target->remaining = sub_size;
3624 target->working = 1;
3625 progress_unlock();
3626
3627 pthread_mutex_lock(&target->mutex);
3628 target->data_ready = 1;
3629 pthread_cond_signal(&target->cond);
3630 pthread_mutex_unlock(&target->mutex);
3631
3632 if (!sub_size) {
3633 pthread_join(target->thread, NULL);
3634 pthread_cond_destroy(&target->cond);
3635 pthread_mutex_destroy(&target->mutex);
3636 active_threads--;
3637 }
3638 }
3639 cleanup_threaded_search();
3640 free(p);
3641
3642 display_progress(progress_state, progress_nr);
3643 stop_progress(&progress_state);
3644 }
3645
3646 static void prepare_pack(int window, int depth)
3647 {
3648 struct object_entry **delta_list;
3649 uint32_t i, nr_deltas;
3650 unsigned n;
3651
3652 if (use_delta_islands)
3653 resolve_tree_islands(the_repository, progress, &to_pack);
3654
3655 get_object_details();
3656
3657 /*
3658 * If we're locally repacking then we need to be doubly careful
3659 * from now on in order to make sure no stealth corruption gets
3660 * propagated to the new pack. Clients receiving streamed packs
3661 * should validate everything they get anyway so no need to incur
3662 * the additional cost here in that case.
3663 */
3664 if (!pack_to_stdout)
3665 do_check_packed_object_crc = 1;
3666
3667 if (!to_pack.nr_objects || !window || !depth ||
3668 (!allow_ref_delta && !allow_ofs_delta))
3669 return;
3670
3671 if (path_walk)
3672 ll_find_deltas_by_region(to_pack.objects, to_pack.regions,
3673 0, to_pack.nr_regions);
3674
3675 ALLOC_ARRAY(delta_list, to_pack.nr_objects);
3676 nr_deltas = n = 0;
3677
3678 for (i = 0; i < to_pack.nr_objects; i++) {
3679 struct object_entry *entry = to_pack.objects + i;
3680
3681 if (!should_attempt_deltas(entry))
3682 continue;
3683
3684 if (!entry->preferred_base)
3685 nr_deltas++;
3686
3687 delta_list[n++] = entry;
3688 }
3689
3690 if (nr_deltas && n > 1) {
3691 unsigned nr_done = 0;
3692
3693 if (progress)
3694 progress_state = start_progress(the_repository,
3695 _("Compressing objects"),
3696 nr_deltas);
3697 QSORT(delta_list, n, type_size_sort);
3698 ll_find_deltas(delta_list, n, window+1, depth, &nr_done);
3699 stop_progress(&progress_state);
3700 if (nr_done != nr_deltas)
3701 die(_("inconsistency with delta count"));
3702 }
3703 free(delta_list);
3704 }
3705
3706 static int git_pack_config(const char *k, const char *v,
3707 const struct config_context *ctx, void *cb)
3708 {
3709 if (!strcmp(k, "pack.window")) {
3710 window = git_config_int(k, v, ctx->kvi);
3711 return 0;
3712 }
3713 if (!strcmp(k, "pack.windowmemory")) {
3714 window_memory_limit = git_config_ulong(k, v, ctx->kvi);
3715 return 0;
3716 }
3717 if (!strcmp(k, "pack.depth")) {
3718 depth = git_config_int(k, v, ctx->kvi);
3719 return 0;
3720 }
3721 if (!strcmp(k, "pack.deltacachesize")) {
3722 max_delta_cache_size = git_config_int(k, v, ctx->kvi);
3723 return 0;
3724 }
3725 if (!strcmp(k, "pack.deltacachelimit")) {
3726 cache_max_small_delta_size = git_config_int(k, v, ctx->kvi);
3727 return 0;
3728 }
3729 if (!strcmp(k, "pack.writebitmaphashcache")) {
3730 if (git_config_bool(k, v))
3731 write_bitmap_options |= BITMAP_OPT_HASH_CACHE;
3732 else
3733 write_bitmap_options &= ~BITMAP_OPT_HASH_CACHE;
3734 }
3735
3736 if (!strcmp(k, "pack.writebitmaplookuptable")) {
3737 if (git_config_bool(k, v))
3738 write_bitmap_options |= BITMAP_OPT_LOOKUP_TABLE;
3739 else
3740 write_bitmap_options &= ~BITMAP_OPT_LOOKUP_TABLE;
3741 }
3742
3743 if (!strcmp(k, "pack.usebitmaps")) {
3744 use_bitmap_index_default = git_config_bool(k, v);
3745 return 0;
3746 }
3747 if (!strcmp(k, "pack.allowpackreuse")) {
3748 int res = git_parse_maybe_bool_text(v);
3749 if (res < 0) {
3750 if (!strcasecmp(v, "single"))
3751 allow_pack_reuse = SINGLE_PACK_REUSE;
3752 else if (!strcasecmp(v, "multi"))
3753 allow_pack_reuse = MULTI_PACK_REUSE;
3754 else
3755 die(_("invalid pack.allowPackReuse value: '%s'"), v);
3756 } else if (res) {
3757 allow_pack_reuse = SINGLE_PACK_REUSE;
3758 } else {
3759 allow_pack_reuse = NO_PACK_REUSE;
3760 }
3761 return 0;
3762 }
3763 if (!strcmp(k, "pack.threads")) {
3764 delta_search_threads = git_config_int(k, v, ctx->kvi);
3765 if (delta_search_threads < 0)
3766 die(_("invalid number of threads specified (%d)"),
3767 delta_search_threads);
3768 if (!HAVE_THREADS && delta_search_threads != 1) {
3769 warning(_("no threads support, ignoring %s"), k);
3770 delta_search_threads = 0;
3771 }
3772 return 0;
3773 }
3774 if (!strcmp(k, "pack.indexversion")) {
3775 pack_idx_opts.version = git_config_int(k, v, ctx->kvi);
3776 if (pack_idx_opts.version > 2)
3777 die(_("bad pack.indexVersion=%"PRIu32),
3778 pack_idx_opts.version);
3779 return 0;
3780 }
3781 if (!strcmp(k, "pack.writereverseindex")) {
3782 if (git_config_bool(k, v))
3783 pack_idx_opts.flags |= WRITE_REV;
3784 else
3785 pack_idx_opts.flags &= ~WRITE_REV;
3786 return 0;
3787 }
3788 if (!strcmp(k, "uploadpack.blobpackfileuri")) {
3789 struct configured_exclusion *ex;
3790 const char *oid_end, *pack_end;
3791 /*
3792 * Stores the pack hash. This is not a true object ID, but is
3793 * of the same form.
3794 */
3795 struct object_id pack_hash;
3796
3797 if (!v)
3798 return config_error_nonbool(k);
3799
3800 ex = xmalloc(sizeof(*ex));
3801 if (parse_oid_hex(v, &ex->e.oid, &oid_end) ||
3802 *oid_end != ' ' ||
3803 parse_oid_hex(oid_end + 1, &pack_hash, &pack_end) ||
3804 *pack_end != ' ')
3805 die(_("value of uploadpack.blobpackfileuri must be "
3806 "of the form '<object-hash> <pack-hash> <uri>' (got '%s')"), v);
3807 if (oidmap_get(&configured_exclusions, &ex->e.oid))
3808 die(_("object already configured in another "
3809 "uploadpack.blobpackfileuri (got '%s')"), v);
3810 ex->pack_hash_hex = xcalloc(1, pack_end - oid_end);
3811 memcpy(ex->pack_hash_hex, oid_end + 1, pack_end - oid_end - 1);
3812 ex->uri = xstrdup(pack_end + 1);
3813 oidmap_put(&configured_exclusions, ex);
3814 }
3815 return git_default_config(k, v, ctx, cb);
3816 }
3817
3818 /* Counters for trace2 output when in --stdin-packs mode. */
3819 static int stdin_packs_found_nr;
3820 static int stdin_packs_hints_nr;
3821
3822 static int add_object_entry_from_pack(const struct object_id *oid,
3823 struct packed_git *p,
3824 uint32_t pos,
3825 void *_data)
3826 {
3827 off_t ofs;
3828 struct object_info oi = OBJECT_INFO_INIT;
3829 enum object_type type = OBJ_NONE;
3830
3831 display_progress(progress_state, ++nr_seen);
3832
3833 if (have_duplicate_entry(oid, 0))
3834 return 0;
3835
3836 stdin_packs_found_nr++;
3837
3838 ofs = nth_packed_object_offset(p, pos);
3839
3840 oi.typep = &type;
3841 if (packed_object_info(NULL, p, ofs, &oi) < 0) {
3842 die(_("could not get type of object %s in pack %s"),
3843 oid_to_hex(oid), p->pack_name);
3844 } else if (type == OBJ_COMMIT) {
3845 struct rev_info *revs = _data;
3846 /*
3847 * commits in included packs are used as starting points
3848 * for the subsequent revision walk
3849 *
3850 * Note that we do want to walk through commits that are
3851 * present in excluded-open ('!') packs to pick up any
3852 * objects reachable from them not present in the
3853 * excluded-closed ('^') packs.
3854 *
3855 * However, we'll only add those objects to the packing
3856 * list after checking `want_object_in_pack()` below.
3857 */
3858 add_pending_oid(revs, NULL, oid, 0);
3859 }
3860
3861 if (!want_object_in_pack(oid, 0, &p, &ofs))
3862 return 0;
3863
3864 create_object_entry(oid, type, 0, 0, 0, p, ofs);
3865
3866 return 0;
3867 }
3868
3869 static void show_object_pack_hint(struct object *object, const char *name,
3870 void *data)
3871 {
3872 enum stdin_packs_mode mode = *(enum stdin_packs_mode *)data;
3873 if (mode == STDIN_PACKS_MODE_FOLLOW ||
3874 mode == STDIN_PACKS_MODE_FOLLOW_REACHABLE) {
3875 if (object->type == OBJ_BLOB &&
3876 !odb_has_object(the_repository->objects, &object->oid, 0))
3877 return;
3878 add_object_entry(&object->oid, object->type, name, 0);
3879 } else {
3880 struct object_entry *oe = packlist_find(&to_pack, &object->oid);
3881 if (!oe)
3882 return;
3883
3884 /*
3885 * Our 'to_pack' list was constructed by iterating all
3886 * objects packed in included packs, and so doesn't have
3887 * a non-zero hash field that you would typically pick
3888 * up during a reachability traversal.
3889 *
3890 * Make a best-effort attempt to fill in the ->hash and
3891 * ->no_try_delta fields here in order to perhaps
3892 * improve the delta selection process.
3893 */
3894 oe->hash = pack_name_hash_fn(name);
3895 oe->no_try_delta = name && no_try_delta(name);
3896
3897 stdin_packs_hints_nr++;
3898 }
3899 }
3900
3901 static void show_commit_pack_hint(struct commit *commit, void *data)
3902 {
3903 enum stdin_packs_mode mode = *(enum stdin_packs_mode *)data;
3904
3905 if (mode == STDIN_PACKS_MODE_FOLLOW ||
3906 mode == STDIN_PACKS_MODE_FOLLOW_REACHABLE) {
3907 show_object_pack_hint((struct object *)commit, "", data);
3908 return;
3909 }
3910
3911 /* nothing to do; commits don't have a namehash */
3912
3913 }
3914
3915 /*
3916 * stdin_pack_info_kind specifies how a pack specified over stdin
3917 * should be treated when pack-objects is invoked with --stdin-packs.
3918 *
3919 * - STDIN_PACK_INCLUDE: objects in any packs with this flag bit set
3920 * should be included in the output pack, unless they appear in an
3921 * excluded pack.
3922 *
3923 * - STDIN_PACK_EXCLUDE_CLOSED: objects in any packs with this flag
3924 * bit set should be excluded from the output pack.
3925 *
3926 * - STDIN_PACK_EXCLUDE_OPEN: objects in any packs with this flag
3927 * bit set should be excluded from the output pack, but are not
3928 * guaranteed to be closed under reachability.
3929 *
3930 * Objects in packs whose 'kind' bits include STDIN_PACK_INCLUDE or
3931 * STDIN_PACK_EXCLUDE_OPEN are used as traversal tips when invoked
3932 * with --stdin-packs=follow.
3933 */
3934 enum stdin_pack_info_kind {
3935 STDIN_PACK_INCLUDE = (1<<0),
3936 STDIN_PACK_EXCLUDE_CLOSED = (1<<1),
3937 STDIN_PACK_EXCLUDE_OPEN = (1<<2),
3938 };
3939
3940 struct stdin_pack_info {
3941 struct packed_git *p;
3942 enum stdin_pack_info_kind kind;
3943 };
3944
3945 static int pack_mtime_cmp(const void *_a, const void *_b)
3946 {
3947 struct stdin_pack_info *a = ((const struct string_list_item*)_a)->util;
3948 struct stdin_pack_info *b = ((const struct string_list_item*)_b)->util;
3949
3950 /*
3951 * order packs by descending mtime so that objects are laid out
3952 * roughly as newest-to-oldest
3953 */
3954 if (a->p->mtime < b->p->mtime)
3955 return 1;
3956 else if (b->p->mtime < a->p->mtime)
3957 return -1;
3958 else
3959 return 0;
3960 }
3961
3962 static int stdin_packs_include_check_obj(struct object *obj, void *data UNUSED)
3963 {
3964 return !has_object_kept_pack(to_pack.repo, &obj->oid,
3965 KEPT_PACK_IN_CORE);
3966 }
3967
3968 static int stdin_packs_include_check(struct commit *commit, void *data)
3969 {
3970 return stdin_packs_include_check_obj((struct object *)commit, data);
3971 }
3972
3973 /*
3974 * Flag bit set on commits that belong to an included pack during
3975 * '--stdin-packs=follow-reachable'. Used by the pre-walk to
3976 * identify which reachable commits should be tips for the main
3977 * object traversal.
3978 */
3979 #define IN_INCLUDED_PACK (1u<<11)
3980
3981 static int mark_included_pack_tip(const struct object_id *oid,
3982 struct packed_git *p,
3983 uint32_t pos,
3984 void *data)
3985 {
3986 struct rev_info *main_revs = data;
3987 off_t ofs = nth_packed_object_offset(p, pos);
3988 enum object_type type;
3989 struct object_info oi = OBJECT_INFO_INIT;
3990 struct object *obj;
3991
3992 oi.typep = &type;
3993 if (packed_object_info(NULL, p, ofs, &oi) < 0)
3994 return 0;
3995 if (type != OBJ_COMMIT && type != OBJ_TAG)
3996 return 0;
3997
3998 obj = parse_object(the_repository, oid);
3999 if (!obj)
4000 return 0;
4001
4002 obj->flags |= IN_INCLUDED_PACK;
4003
4004 if (type == OBJ_TAG && main_revs)
4005 add_pending_object(main_revs, obj, "");
4006 return 0;
4007 }
4008
4009 static int mark_loose_object_tip(const struct object_id *oid,
4010 struct object_info *oi UNUSED,
4011 void *data)
4012 {
4013 struct rev_info *main_revs = data;
4014 struct object *obj;
4015 enum object_type type;
4016
4017 type = odb_read_object_info(the_repository->objects, oid, NULL);
4018 if (type != OBJ_COMMIT && type != OBJ_TAG)
4019 return 0;
4020
4021 obj = parse_object(the_repository, oid);
4022 if (!obj)
4023 return 0;
4024
4025 obj->flags |= IN_INCLUDED_PACK;
4026
4027 if (type == OBJ_TAG && main_revs)
4028 add_pending_object(main_revs, obj, "");
4029
4030 return 0;
4031 }
4032
4033 static int add_ref_to_pending(const struct reference *ref, void *cb_data)
4034 {
4035 struct rev_info *revs = cb_data;
4036 struct object *object;
4037
4038 object = parse_object(the_repository, ref->oid);
4039 if (!object)
4040 return 0;
4041
4042 add_pending_object(revs, object, "");
4043 return 0;
4044 }
4045
4046 static void read_refs_snapshot(const char *refs_snapshot,
4047 struct rev_info *revs)
4048 {
4049 struct strbuf buf = STRBUF_INIT;
4050 struct object_id oid;
4051 FILE *f = xfopen(refs_snapshot, "r");
4052
4053 while (strbuf_getline(&buf, f) != EOF) {
4054 struct object *object;
4055 const char *hex = buf.buf;
4056 const char *end = NULL;
4057
4058 if (*hex == '+')
4059 hex++;
4060
4061 if (parse_oid_hex_algop(hex, &oid, &end,
4062 the_repository->hash_algo) < 0)
4063 die(_("could not parse line: %s"), buf.buf);
4064 if (*end)
4065 die(_("malformed line: %s"), buf.buf);
4066
4067 object = parse_object(the_repository, &oid);
4068 if (!object)
4069 continue;
4070
4071 add_pending_object(revs, object, "");
4072 }
4073
4074 fclose(f);
4075 strbuf_release(&buf);
4076 }
4077
4078 static void stdin_packs_add_reachable_pack_entries(struct string_list *keys,
4079 struct rev_info *revs,
4080 int rev_list_unpacked)
4081 {
4082 struct rev_info pre_walk;
4083 struct commit *commit;
4084 struct string_list_item *item;
4085
4086 /*
4087 * Phase 1: mark commits in included packs, then walk from
4088 * ref tips to discover which of them are reachable. The walk
4089 * halts at excluded-closed packs (via no_kept_objects) and
4090 * continues through excluded-open ones.
4091 *
4092 * Also set include_check on the outer revs so that phase 2
4093 * (the main object traversal) halts at closed packs.
4094 */
4095 revs->include_check = stdin_packs_include_check;
4096 revs->include_check_obj = stdin_packs_include_check_obj;
4097
4098 for_each_string_list_item(item, keys) {
4099 struct stdin_pack_info *info = item->util;
4100 if (info->kind & STDIN_PACK_INCLUDE)
4101 for_each_object_in_pack(info->p,
4102 mark_included_pack_tip,
4103 revs,
4104 ODB_FOR_EACH_OBJECT_PACK_ORDER);
4105 }
4106
4107 if (rev_list_unpacked) {
4108 /*
4109 * With '--stdin-packs=follow-reachable', specifying
4110 * '--unpacked' instructs pack-objects to pack any loose
4111 * objects which are reachable.
4112 *
4113 * Pretend as if all loose objects are in an included
4114 * pack in order to make them eligible for packing.
4115 */
4116 struct odb_source *source = revs->repo->objects->sources;
4117 for (; source; source = source->next) {
4118 struct odb_source_files *files = odb_source_files_downcast(source);
4119 struct odb_for_each_object_options opts = { 0 };
4120 if (local)
4121 opts.flags |= ODB_FOR_EACH_OBJECT_LOCAL_ONLY;
4122
4123 odb_source_for_each_object(&files->loose->base, NULL,
4124 mark_loose_object_tip,
4125 revs, &opts);
4126 }
4127 }
4128
4129 repo_init_revisions(the_repository, &pre_walk, NULL);
4130 pre_walk.no_kept_objects = 1;
4131 pre_walk.keep_pack_cache_flags |= KEPT_PACK_IN_CORE;
4132 pre_walk.ignore_missing_links = 1;
4133
4134 if (stdin_packs_refs_snapshot)
4135 read_refs_snapshot(stdin_packs_refs_snapshot, &pre_walk);
4136 else
4137 refs_for_each_ref(get_main_ref_store(the_repository),
4138 add_ref_to_pending, &pre_walk);
4139
4140 if (prepare_revision_walk(&pre_walk))
4141 die(_("revision walk setup failed"));
4142
4143 /*
4144 * Phase 2 tips: every reachable commit that is in an
4145 * included pack becomes a starting point for the main
4146 * object traversal.
4147 */
4148 while ((commit = get_revision(&pre_walk)) != NULL) {
4149 if (commit->object.flags & IN_INCLUDED_PACK)
4150 add_pending_oid(revs, NULL,
4151 &commit->object.oid, 0);
4152 }
4153
4154 reset_revision_walk();
4155 release_revisions(&pre_walk);
4156 }
4157
4158 static void stdin_packs_add_all_pack_entries(struct string_list *keys,
4159 struct rev_info *revs)
4160 {
4161 struct string_list_item *item;
4162
4163 for_each_string_list_item(item, keys) {
4164 struct stdin_pack_info *info = item->util;
4165
4166 if (info->kind & STDIN_PACK_EXCLUDE_OPEN) {
4167 /*
4168 * When open-excluded packs ("!") are present, stop
4169 * the parent walk at closed-excluded ("^") packs.
4170 * Objects behind a "^" boundary are guaranteed to
4171 * have closure and should not be rescued.
4172 */
4173 revs->include_check = stdin_packs_include_check;
4174 revs->include_check_obj = stdin_packs_include_check_obj;
4175 }
4176
4177 if ((info->kind & STDIN_PACK_INCLUDE) ||
4178 (info->kind & STDIN_PACK_EXCLUDE_OPEN))
4179 for_each_object_in_pack(info->p,
4180 add_object_entry_from_pack,
4181 revs,
4182 ODB_FOR_EACH_OBJECT_PACK_ORDER);
4183 }
4184 }
4185
4186 static void stdin_packs_add_pack_entries(struct strmap *packs,
4187 struct rev_info *revs,
4188 enum stdin_packs_mode mode,
4189 int rev_list_unpacked)
4190 {
4191 struct string_list keys = STRING_LIST_INIT_NODUP;
4192 struct hashmap_iter iter;
4193 struct strmap_entry *entry;
4194
4195 strmap_for_each_entry(packs, &iter, entry) {
4196 struct stdin_pack_info *info = entry->value;
4197 if (!info->p)
4198 die(_("could not find pack '%s'"), entry->key);
4199
4200 string_list_append(&keys, entry->key)->util = info;
4201 }
4202
4203 /*
4204 * Order packs by ascending mtime; use QSORT directly to access the
4205 * string_list_item's ->util pointer, which string_list_sort() does not
4206 * provide.
4207 */
4208 QSORT(keys.items, keys.nr, pack_mtime_cmp);
4209
4210 if (mode == STDIN_PACKS_MODE_FOLLOW_REACHABLE)
4211 stdin_packs_add_reachable_pack_entries(&keys, revs,
4212 rev_list_unpacked);
4213 else
4214 stdin_packs_add_all_pack_entries(&keys, revs);
4215
4216 string_list_clear(&keys, 0);
4217 }
4218
4219 static void stdin_packs_read_input(struct rev_info *revs,
4220 enum stdin_packs_mode mode,
4221 int rev_list_unpacked)
4222 {
4223 struct strbuf buf = STRBUF_INIT;
4224 struct strmap packs = STRMAP_INIT;
4225 struct packed_git *p;
4226
4227 while (strbuf_getline(&buf, stdin) != EOF) {
4228 struct stdin_pack_info *info;
4229 enum stdin_pack_info_kind kind = STDIN_PACK_INCLUDE;
4230 const char *key = buf.buf;
4231
4232 if (!*key)
4233 continue;
4234 else if (*key == '^')
4235 kind = STDIN_PACK_EXCLUDE_CLOSED;
4236 else if (*key == '!' &&
4237 (mode == STDIN_PACKS_MODE_FOLLOW ||
4238 mode == STDIN_PACKS_MODE_FOLLOW_REACHABLE))
4239 kind = STDIN_PACK_EXCLUDE_OPEN;
4240
4241 if (kind != STDIN_PACK_INCLUDE)
4242 key++;
4243
4244 info = strmap_get(&packs, key);
4245 if (!info) {
4246 CALLOC_ARRAY(info, 1);
4247 strmap_put(&packs, key, info);
4248 }
4249
4250 info->kind |= kind;
4251
4252 strbuf_reset(&buf);
4253 }
4254
4255 repo_for_each_pack(the_repository, p) {
4256 struct stdin_pack_info *info;
4257
4258 info = strmap_get(&packs, pack_basename(p));
4259 if (!info)
4260 continue;
4261
4262 if (info->kind & STDIN_PACK_INCLUDE) {
4263 if (exclude_promisor_objects && p->pack_promisor)
4264 die(_("packfile %s is a promisor but --exclude-promisor-objects was given"), p->pack_name);
4265
4266 /*
4267 * Arguments we got on stdin may not even be
4268 * packs. First check that to avoid segfaulting
4269 * later on in e.g. pack_mtime_cmp(), excluded
4270 * packs are handled below.
4271 */
4272 if (!is_pack_valid(p))
4273 die(_("packfile %s cannot be accessed"), p->pack_name);
4274 }
4275
4276 if (info->kind & STDIN_PACK_EXCLUDE_CLOSED) {
4277 /*
4278 * Marking excluded packs as kept in-core so
4279 * that later calls to add_object_entry()
4280 * discards any objects that are also found in
4281 * excluded packs.
4282 */
4283 p->pack_keep_in_core = 1;
4284 }
4285
4286 if (info->kind & STDIN_PACK_EXCLUDE_OPEN) {
4287 /*
4288 * Marking excluded open packs as kept in-core
4289 * (open) for the same reason as we marked
4290 * exclude closed packs as kept in-core.
4291 *
4292 * Use a separate flag here to ensure we don't
4293 * halt our traversal at these packs, since they
4294 * are not guaranteed to have closure.
4295 *
4296 */
4297 p->pack_keep_in_core_open = 1;
4298 }
4299
4300 info->p = p;
4301 }
4302
4303 stdin_packs_add_pack_entries(&packs, revs, mode, rev_list_unpacked);
4304
4305 strbuf_release(&buf);
4306 strmap_clear(&packs, 1);
4307 }
4308
4309 static void add_unreachable_loose_objects(struct rev_info *revs);
4310
4311 static void read_stdin_packs(enum stdin_packs_mode mode, int rev_list_unpacked)
4312 {
4313 int prev_fetch_if_missing = fetch_if_missing;
4314 struct rev_info revs;
4315
4316 /*
4317 * The revision walk may hit objects that are promised, only. As the
4318 * walk is best-effort though we don't want to perform backfill fetches
4319 * for them.
4320 */
4321 fetch_if_missing = 0;
4322
4323 repo_init_revisions(the_repository, &revs, NULL);
4324 /*
4325 * Use a revision walk to fill in the namehash of objects in the include
4326 * packs. To save time, we'll avoid traversing through objects that are
4327 * in excluded packs.
4328 *
4329 * That may cause us to avoid populating all of the namehash fields of
4330 * all included objects, but our goal is best-effort, since this is only
4331 * an optimization during delta selection.
4332 */
4333 revs.no_kept_objects = 1;
4334 revs.keep_pack_cache_flags |= KEPT_PACK_IN_CORE;
4335 revs.blob_objects = 1;
4336 revs.tree_objects = 1;
4337 revs.tag_objects = 1;
4338 revs.ignore_missing_links = 1;
4339 revs.exclude_promisor_objects = exclude_promisor_objects;
4340
4341 /* avoids adding objects in excluded packs */
4342 ignore_packed_keep_in_core = 1;
4343 if (mode == STDIN_PACKS_MODE_FOLLOW ||
4344 mode == STDIN_PACKS_MODE_FOLLOW_REACHABLE) {
4345 /*
4346 * In '--stdin-packs=follow' mode, additionally ignore
4347 * objects in excluded-open packs to prevent them from
4348 * appearing in the resulting pack.
4349 */
4350 ignore_packed_keep_in_core_open = 1;
4351 }
4352 stdin_packs_read_input(&revs, mode, rev_list_unpacked);
4353 if (rev_list_unpacked && mode != STDIN_PACKS_MODE_FOLLOW_REACHABLE)
4354 add_unreachable_loose_objects(&revs);
4355
4356 if (prepare_revision_walk(&revs))
4357 die(_("revision walk setup failed"));
4358 traverse_commit_list(&revs,
4359 show_commit_pack_hint,
4360 show_object_pack_hint,
4361 &mode);
4362
4363 release_revisions(&revs);
4364
4365 trace2_data_intmax("pack-objects", the_repository, "stdin_packs_found",
4366 stdin_packs_found_nr);
4367 trace2_data_intmax("pack-objects", the_repository, "stdin_packs_hints",
4368 stdin_packs_hints_nr);
4369
4370 fetch_if_missing = prev_fetch_if_missing;
4371 }
4372
4373 static void add_cruft_object_entry(const struct object_id *oid, enum object_type type,
4374 struct packed_git *pack, off_t offset,
4375 const char *name, uint32_t mtime)
4376 {
4377 struct object_entry *entry;
4378
4379 display_progress(progress_state, ++nr_seen);
4380
4381 entry = packlist_find(&to_pack, oid);
4382 if (entry) {
4383 if (name) {
4384 entry->hash = pack_name_hash_fn(name);
4385 entry->no_try_delta = no_try_delta(name);
4386 }
4387 } else {
4388 if (!want_object_in_pack_mtime(oid, 0, &pack, &offset, mtime))
4389 return;
4390 if (!pack && type == OBJ_BLOB) {
4391 struct odb_source *source = the_repository->objects->sources;
4392 int found = 0;
4393
4394 for (; !found && source; source = source->next) {
4395 struct odb_source_files *files = odb_source_files_downcast(source);
4396 if (!odb_source_read_object_info(&files->loose->base, oid, NULL, 0))
4397 found = 1;
4398 }
4399
4400 /*
4401 * If a traversed tree has a missing blob then we want
4402 * to avoid adding that missing object to our pack.
4403 *
4404 * This only applies to missing blobs, not trees,
4405 * because the traversal needs to parse sub-trees but
4406 * not blobs.
4407 *
4408 * Note we only perform this check when we couldn't
4409 * already find the object in a pack, so we're really
4410 * limited to "ensure non-tip blobs which don't exist in
4411 * packs do exist via loose objects". Confused?
4412 */
4413 if (!found)
4414 return;
4415 }
4416
4417 entry = create_object_entry(oid, type, pack_name_hash_fn(name),
4418 0, name && no_try_delta(name),
4419 pack, offset);
4420 }
4421
4422 if (mtime > oe_cruft_mtime(&to_pack, entry))
4423 oe_set_cruft_mtime(&to_pack, entry, mtime);
4424 return;
4425 }
4426
4427 static void show_cruft_object(struct object *obj, const char *name, void *data UNUSED)
4428 {
4429 /*
4430 * if we did not record it earlier, it's at least as old as our
4431 * expiration value. Rather than find it exactly, just use that
4432 * value. This may bump it forward from its real mtime, but it
4433 * will still be "too old" next time we run with the same
4434 * expiration.
4435 *
4436 * if obj does appear in the packing list, this call is a noop (or may
4437 * set the namehash).
4438 */
4439 add_cruft_object_entry(&obj->oid, obj->type, NULL, 0, name, cruft_expiration);
4440 }
4441
4442 static void show_cruft_commit(struct commit *commit, void *data)
4443 {
4444 show_cruft_object((struct object*)commit, NULL, data);
4445 }
4446
4447 static int cruft_include_check_obj(struct object *obj, void *data UNUSED)
4448 {
4449 return !has_object_kept_pack(to_pack.repo, &obj->oid, KEPT_PACK_IN_CORE);
4450 }
4451
4452 static int cruft_include_check(struct commit *commit, void *data)
4453 {
4454 return cruft_include_check_obj((struct object*)commit, data);
4455 }
4456
4457 static void set_cruft_mtime(const struct object *object,
4458 struct packed_git *pack,
4459 off_t offset, time_t mtime)
4460 {
4461 add_cruft_object_entry(&object->oid, object->type, pack, offset, NULL,
4462 mtime);
4463 }
4464
4465 static void mark_pack_kept_in_core(struct string_list *packs, unsigned keep)
4466 {
4467 struct string_list_item *item = NULL;
4468 for_each_string_list_item(item, packs) {
4469 struct packed_git *p = item->util;
4470 if (!p)
4471 die(_("could not find pack '%s'"), item->string);
4472 if (p->is_cruft && keep)
4473 ignore_packed_keep_in_core_has_cruft = 1;
4474 p->pack_keep_in_core = keep;
4475 }
4476 }
4477
4478 static void add_objects_in_unpacked_packs(void);
4479
4480 static void enumerate_cruft_objects(void)
4481 {
4482 if (progress)
4483 progress_state = start_progress(the_repository,
4484 _("Enumerating cruft objects"), 0);
4485
4486 add_objects_in_unpacked_packs();
4487 add_unreachable_loose_objects(NULL);
4488
4489 stop_progress(&progress_state);
4490 }
4491
4492 static void enumerate_and_traverse_cruft_objects(struct string_list *fresh_packs)
4493 {
4494 struct packed_git *p;
4495 struct rev_info revs;
4496 int ret;
4497
4498 repo_init_revisions(the_repository, &revs, NULL);
4499
4500 revs.tag_objects = 1;
4501 revs.tree_objects = 1;
4502 revs.blob_objects = 1;
4503
4504 revs.include_check = cruft_include_check;
4505 revs.include_check_obj = cruft_include_check_obj;
4506
4507 revs.ignore_missing_links = 1;
4508
4509 if (progress)
4510 progress_state = start_progress(the_repository,
4511 _("Enumerating cruft objects"), 0);
4512 ret = add_unseen_recent_objects_to_traversal(&revs, cruft_expiration,
4513 set_cruft_mtime, 1);
4514 stop_progress(&progress_state);
4515
4516 if (ret)
4517 die(_("unable to add cruft objects"));
4518
4519 /*
4520 * Re-mark only the fresh packs as kept so that objects in
4521 * unknown packs do not halt the reachability traversal early.
4522 */
4523 repo_for_each_pack(the_repository, p)
4524 p->pack_keep_in_core = 0;
4525 mark_pack_kept_in_core(fresh_packs, 1);
4526
4527 if (prepare_revision_walk(&revs))
4528 die(_("revision walk setup failed"));
4529 if (progress)
4530 progress_state = start_progress(the_repository,
4531 _("Traversing cruft objects"), 0);
4532 nr_seen = 0;
4533 traverse_commit_list(&revs, show_cruft_commit, show_cruft_object, NULL);
4534
4535 stop_progress(&progress_state);
4536 release_revisions(&revs);
4537 }
4538
4539 static void read_cruft_objects(void)
4540 {
4541 struct strbuf buf = STRBUF_INIT;
4542 struct string_list discard_packs = STRING_LIST_INIT_DUP;
4543 struct string_list fresh_packs = STRING_LIST_INIT_DUP;
4544 struct packed_git *p;
4545
4546 ignore_packed_keep_in_core = 1;
4547
4548 while (strbuf_getline(&buf, stdin) != EOF) {
4549 if (!buf.len)
4550 continue;
4551
4552 if (*buf.buf == '-')
4553 string_list_append(&discard_packs, buf.buf + 1);
4554 else
4555 string_list_append(&fresh_packs, buf.buf);
4556 }
4557
4558 string_list_sort(&discard_packs);
4559 string_list_sort(&fresh_packs);
4560
4561 repo_for_each_pack(the_repository, p) {
4562 const char *pack_name = pack_basename(p);
4563 struct string_list_item *item;
4564
4565 item = string_list_lookup(&fresh_packs, pack_name);
4566 if (!item)
4567 item = string_list_lookup(&discard_packs, pack_name);
4568
4569 if (item) {
4570 item->util = p;
4571 } else {
4572 /*
4573 * This pack wasn't mentioned in either the "fresh" or
4574 * "discard" list, so the caller didn't know about it.
4575 *
4576 * Mark it as kept so that its objects are ignored by
4577 * add_unseen_recent_objects_to_traversal(). We'll
4578 * unmark it before starting the traversal so it doesn't
4579 * halt the traversal early.
4580 */
4581 p->pack_keep_in_core = 1;
4582 }
4583 }
4584
4585 mark_pack_kept_in_core(&fresh_packs, 1);
4586 mark_pack_kept_in_core(&discard_packs, 0);
4587
4588 if (cruft_expiration)
4589 enumerate_and_traverse_cruft_objects(&fresh_packs);
4590 else
4591 enumerate_cruft_objects();
4592
4593 strbuf_release(&buf);
4594 string_list_clear(&discard_packs, 0);
4595 string_list_clear(&fresh_packs, 0);
4596 }
4597
4598 static void read_object_list_from_stdin(void)
4599 {
4600 char line[GIT_MAX_HEXSZ + 1 + PATH_MAX + 2];
4601 struct object_id oid;
4602 const char *p;
4603
4604 for (;;) {
4605 if (!fgets(line, sizeof(line), stdin)) {
4606 if (feof(stdin))
4607 break;
4608 if (!ferror(stdin))
4609 BUG("fgets returned NULL, not EOF, not error!");
4610 if (errno != EINTR)
4611 die_errno("fgets");
4612 clearerr(stdin);
4613 continue;
4614 }
4615 if (line[0] == '-') {
4616 if (get_oid_hex(line+1, &oid))
4617 die(_("expected edge object ID, got garbage:\n %s"),
4618 line);
4619 add_preferred_base(&oid);
4620 continue;
4621 }
4622 if (parse_oid_hex(line, &oid, &p))
4623 die(_("expected object ID, got garbage:\n %s"), line);
4624
4625 add_preferred_base_object(p + 1);
4626 add_object_entry(&oid, OBJ_NONE, p + 1, 0);
4627 }
4628 }
4629
4630 static void show_commit(struct commit *commit, void *data UNUSED)
4631 {
4632 add_object_entry(&commit->object.oid, OBJ_COMMIT, NULL, 0);
4633
4634 if (write_bitmap_index)
4635 index_commit_for_bitmap(commit);
4636
4637 if (use_delta_islands)
4638 propagate_island_marks(the_repository, commit);
4639 }
4640
4641 static void show_object(struct object *obj, const char *name,
4642 void *data UNUSED)
4643 {
4644 add_preferred_base_object(name);
4645 add_object_entry(&obj->oid, obj->type, name, 0);
4646
4647 if (use_delta_islands)
4648 record_tree_depth(&obj->oid, name);
4649 }
4650
4651 static void show_object__ma_allow_any(struct object *obj, const char *name, void *data)
4652 {
4653 assert(arg_missing_action == MA_ALLOW_ANY);
4654
4655 /*
4656 * Quietly ignore ALL missing objects. This avoids problems with
4657 * staging them now and getting an odd error later.
4658 */
4659 if (!odb_has_object(the_repository->objects, &obj->oid, 0))
4660 return;
4661
4662 show_object(obj, name, data);
4663 }
4664
4665 static void show_object__ma_allow_promisor(struct object *obj, const char *name, void *data)
4666 {
4667 assert(arg_missing_action == MA_ALLOW_PROMISOR);
4668
4669 /*
4670 * Quietly ignore EXPECTED missing objects. This avoids problems with
4671 * staging them now and getting an odd error later.
4672 */
4673 if (!odb_has_object(the_repository->objects, &obj->oid, 0) &&
4674 is_promisor_object(to_pack.repo, &obj->oid))
4675 return;
4676
4677 show_object(obj, name, data);
4678 }
4679
4680 static int option_parse_missing_action(const struct option *opt UNUSED,
4681 const char *arg, int unset)
4682 {
4683 assert(arg);
4684 assert(!unset);
4685
4686 if (!strcmp(arg, "error")) {
4687 arg_missing_action = MA_ERROR;
4688 fn_show_object = show_object;
4689 return 0;
4690 }
4691
4692 if (!strcmp(arg, "allow-any")) {
4693 arg_missing_action = MA_ALLOW_ANY;
4694 fetch_if_missing = 0;
4695 fn_show_object = show_object__ma_allow_any;
4696 return 0;
4697 }
4698
4699 if (!strcmp(arg, "allow-promisor")) {
4700 arg_missing_action = MA_ALLOW_PROMISOR;
4701 fetch_if_missing = 0;
4702 fn_show_object = show_object__ma_allow_promisor;
4703 return 0;
4704 }
4705
4706 die(_("invalid value for '%s': '%s'"), "--missing", arg);
4707 return 0;
4708 }
4709
4710 static void show_edge(struct commit *commit)
4711 {
4712 add_preferred_base(&commit->object.oid);
4713 }
4714
4715 static int add_object_in_unpacked_pack(const struct object_id *oid,
4716 struct object_info *oi,
4717 void *data UNUSED)
4718 {
4719 if (cruft) {
4720 add_cruft_object_entry(oid, OBJ_NONE, oi->source_infop->u.packed.pack,
4721 oi->source_infop->u.packed.offset, NULL,
4722 *oi->mtimep);
4723 } else {
4724 add_object_entry(oid, OBJ_NONE, "", 0);
4725 }
4726 return 0;
4727 }
4728
4729 static void add_objects_in_unpacked_packs(void)
4730 {
4731 struct odb_source *source;
4732 time_t mtime;
4733 struct odb_for_each_object_options opts = {
4734 .flags = ODB_FOR_EACH_OBJECT_PACK_ORDER |
4735 ODB_FOR_EACH_OBJECT_LOCAL_ONLY |
4736 ODB_FOR_EACH_OBJECT_SKIP_IN_CORE_KEPT_PACKS |
4737 ODB_FOR_EACH_OBJECT_SKIP_ON_DISK_KEPT_PACKS,
4738 };
4739 struct odb_source_info source_info;
4740 struct object_info oi = {
4741 .mtimep = &mtime,
4742 .source_infop = &source_info,
4743 };
4744
4745 odb_prepare_alternates(to_pack.repo->objects);
4746 for (source = to_pack.repo->objects->sources; source; source = source->next) {
4747 struct odb_source_files *files = odb_source_files_downcast(source);
4748
4749 if (!source->local)
4750 continue;
4751
4752 if (odb_source_for_each_object(&files->packed->base, &oi,
4753 add_object_in_unpacked_pack, NULL, &opts))
4754 die(_("cannot open pack index"));
4755 }
4756 }
4757
4758 static int add_loose_object(const struct object_id *oid, const char *path,
4759 void *data)
4760 {
4761 struct rev_info *revs = data;
4762 enum object_type type = odb_read_object_info(the_repository->objects, oid, NULL);
4763
4764 if (type < 0) {
4765 warning(_("loose object at %s could not be examined"), path);
4766 return 0;
4767 }
4768
4769 if (cruft) {
4770 struct stat st;
4771 if (stat(path, &st) < 0) {
4772 if (errno == ENOENT)
4773 return 0;
4774 return error_errno("unable to stat %s", oid_to_hex(oid));
4775 }
4776
4777 add_cruft_object_entry(oid, type, NULL, 0, NULL,
4778 st.st_mtime);
4779 } else {
4780 add_object_entry(oid, type, "", 0);
4781 }
4782
4783 if (revs && type == OBJ_COMMIT)
4784 add_pending_oid(revs, NULL, oid, 0);
4785
4786 return 0;
4787 }
4788
4789 /*
4790 * We actually don't even have to worry about reachability here.
4791 * add_object_entry will weed out duplicates, so we just add every
4792 * loose object we find.
4793 */
4794 static void add_unreachable_loose_objects(struct rev_info *revs)
4795 {
4796 for_each_loose_file_in_source(the_repository->objects->sources,
4797 add_loose_object, NULL, NULL, revs);
4798 }
4799
4800 static int has_sha1_pack_kept_or_nonlocal(const struct object_id *oid)
4801 {
4802 static struct packed_git *last_found = NULL;
4803 struct packed_git *p;
4804
4805 if (last_found && find_pack_entry_one(oid, last_found))
4806 return 1;
4807
4808 repo_for_each_pack(the_repository, p) {
4809 /*
4810 * We have already checked `last_found`, so there is no need to
4811 * re-check here.
4812 */
4813 if (p == last_found)
4814 continue;
4815
4816 if ((!p->pack_local || p->pack_keep || p->pack_keep_in_core) &&
4817 find_pack_entry_one(oid, p)) {
4818 last_found = p;
4819 return 1;
4820 }
4821 }
4822
4823 return 0;
4824 }
4825
4826 /*
4827 * Store a list of sha1s that are should not be discarded
4828 * because they are either written too recently, or are
4829 * reachable from another object that was.
4830 *
4831 * This is filled by get_object_list.
4832 */
4833 static struct oid_array recent_objects;
4834
4835 static int loosened_object_can_be_discarded(const struct object_id *oid,
4836 timestamp_t mtime)
4837 {
4838 if (!unpack_unreachable_expiration)
4839 return 0;
4840 if (mtime > unpack_unreachable_expiration)
4841 return 0;
4842 if (oid_array_lookup(&recent_objects, oid) >= 0)
4843 return 0;
4844 return 1;
4845 }
4846
4847 static int force_object_loose(struct odb_source *source,
4848 const struct object_id *oid,
4849 const time_t *mtime)
4850 {
4851 struct odb_source_files *files = odb_source_files_downcast(source);
4852 const struct git_hash_algo *compat = source->odb->repo->compat_hash_algo;
4853 struct object_info oi = OBJECT_INFO_INIT;
4854 struct object_id compat_oid, *compat_oid_p = NULL;
4855 enum object_type type;
4856 void *buf = NULL;
4857 size_t len;
4858 int ret;
4859
4860 for (struct odb_source *s = source->odb->sources; s; s = s->next) {
4861 struct odb_source_files *files = odb_source_files_downcast(s);
4862 if (!odb_source_read_object_info(&files->loose->base, oid, NULL, 0))
4863 return 0;
4864 }
4865
4866 oi.typep = &type;
4867 oi.sizep = &len;
4868 oi.contentp = &buf;
4869 if (odb_read_object_info_extended(source->odb, oid, &oi, 0)) {
4870 ret = error(_("cannot read object for %s"), oid_to_hex(oid));
4871 goto out;
4872 }
4873
4874 if (compat) {
4875 if (repo_oid_to_algop(source->odb->repo, oid, compat, &compat_oid)) {
4876 ret = error(_("cannot map object %s to %s"),
4877 oid_to_hex(oid), compat->name);
4878 goto out;
4879 }
4880
4881 compat_oid_p = &compat_oid;
4882 }
4883
4884 ret = odb_source_write_object(&files->loose->base, buf, len, type, oid,
4885 compat_oid_p, mtime, 0);
4886
4887 out:
4888 free(buf);
4889 return ret;
4890 }
4891
4892 static void loosen_unused_packed_objects(void)
4893 {
4894 struct packed_git *p;
4895 uint32_t i;
4896 uint32_t loosened_objects_nr = 0;
4897 struct object_id oid;
4898
4899 repo_for_each_pack(the_repository, p) {
4900 if (!p->pack_local || p->pack_keep || p->pack_keep_in_core)
4901 continue;
4902
4903 if (open_pack_index(p))
4904 die(_("cannot open pack index"));
4905
4906 for (i = 0; i < p->num_objects; i++) {
4907 nth_packed_object_id(&oid, p, i);
4908 if (!packlist_find(&to_pack, &oid) &&
4909 !has_sha1_pack_kept_or_nonlocal(&oid) &&
4910 !loosened_object_can_be_discarded(&oid, p->mtime)) {
4911 if (force_object_loose(the_repository->objects->sources,
4912 &oid, &p->mtime))
4913 die(_("unable to force loose object"));
4914 loosened_objects_nr++;
4915 }
4916 }
4917 }
4918
4919 trace2_data_intmax("pack-objects", the_repository,
4920 "loosen_unused_packed_objects/loosened", loosened_objects_nr);
4921 }
4922
4923 /*
4924 * This tracks any options which pack-reuse code expects to be on, or which a
4925 * reader of the pack might not understand, and which would therefore prevent
4926 * blind reuse of what we have on disk.
4927 */
4928 static int pack_options_allow_reuse(void)
4929 {
4930 return allow_pack_reuse != NO_PACK_REUSE &&
4931 pack_to_stdout &&
4932 !ignore_packed_keep_on_disk &&
4933 !ignore_packed_keep_in_core &&
4934 (!local || !have_non_local_packs) &&
4935 !incremental && (allow_ref_delta || allow_ofs_delta);
4936 }
4937
4938 static int get_object_list_from_bitmap(struct rev_info *revs)
4939 {
4940 if (!(bitmap_git = prepare_bitmap_walk(revs, 0)))
4941 return -1;
4942
4943 /*
4944 * For now, force the name-hash version to be 1 since that
4945 * is the version implied by the bitmap format. Later, the
4946 * format can include this version explicitly in its format,
4947 * allowing readers to know the version that was used during
4948 * the bitmap write.
4949 */
4950 name_hash_version = 1;
4951
4952 if (pack_options_allow_reuse())
4953 reuse_partial_packfile_from_bitmap(bitmap_git,
4954 &reuse_packfiles,
4955 &reuse_packfiles_nr,
4956 &reuse_packfile_bitmap,
4957 allow_pack_reuse == MULTI_PACK_REUSE,
4958 allow_ref_delta);
4959
4960 if (reuse_packfiles) {
4961 reuse_packfile_objects = bitmap_popcount(reuse_packfile_bitmap);
4962 if (!reuse_packfile_objects)
4963 BUG("expected non-empty reuse bitmap");
4964
4965 nr_result += reuse_packfile_objects;
4966 nr_seen += reuse_packfile_objects;
4967 display_progress(progress_state, nr_seen);
4968 }
4969
4970 traverse_bitmap_commit_list(bitmap_git, revs,
4971 &add_object_entry_from_bitmap);
4972 return 0;
4973 }
4974
4975 static void record_recent_object(struct object *obj,
4976 const char *name UNUSED,
4977 void *data UNUSED)
4978 {
4979 oid_array_append(&recent_objects, &obj->oid);
4980 }
4981
4982 static void record_recent_commit(struct commit *commit, void *data UNUSED)
4983 {
4984 oid_array_append(&recent_objects, &commit->object.oid);
4985 }
4986
4987 static int mark_bitmap_preferred_tip(const struct reference *ref, void *data UNUSED)
4988 {
4989 const struct object_id *maybe_peeled = ref->oid;
4990 struct object_id peeled;
4991 struct object *object;
4992
4993 if (!reference_get_peeled_oid(the_repository, ref, &peeled))
4994 maybe_peeled = &peeled;
4995
4996 object = parse_object_or_die(the_repository, maybe_peeled, ref->name);
4997 if (object->type == OBJ_COMMIT)
4998 object->flags |= NEEDS_BITMAP;
4999
5000 return 0;
Showing first 5,000 of 5,770 lines. View raw