Merge branch 'ds/multi-pack-verify'
[git/git.git] / builtin / pack-objects.c
1 #include "builtin.h"
2 #include "cache.h"
3 #include "repository.h"
4 #include "config.h"
5 #include "attr.h"
6 #include "object.h"
7 #include "blob.h"
8 #include "commit.h"
9 #include "tag.h"
10 #include "tree.h"
11 #include "delta.h"
12 #include "pack.h"
13 #include "pack-revindex.h"
14 #include "csum-file.h"
15 #include "tree-walk.h"
16 #include "diff.h"
17 #include "revision.h"
18 #include "list-objects.h"
19 #include "list-objects-filter.h"
20 #include "list-objects-filter-options.h"
21 #include "pack-objects.h"
22 #include "progress.h"
23 #include "refs.h"
24 #include "streaming.h"
25 #include "thread-utils.h"
26 #include "pack-bitmap.h"
27 #include "delta-islands.h"
28 #include "reachable.h"
29 #include "sha1-array.h"
30 #include "argv-array.h"
31 #include "list.h"
32 #include "packfile.h"
33 #include "object-store.h"
34 #include "dir.h"
35 #include "midx.h"
36
37 #define IN_PACK(obj) oe_in_pack(&to_pack, obj)
38 #define SIZE(obj) oe_size(&to_pack, obj)
39 #define SET_SIZE(obj,size) oe_set_size(&to_pack, obj, size)
40 #define DELTA_SIZE(obj) oe_delta_size(&to_pack, obj)
41 #define DELTA(obj) oe_delta(&to_pack, obj)
42 #define DELTA_CHILD(obj) oe_delta_child(&to_pack, obj)
43 #define DELTA_SIBLING(obj) oe_delta_sibling(&to_pack, obj)
44 #define SET_DELTA(obj, val) oe_set_delta(&to_pack, obj, val)
45 #define SET_DELTA_EXT(obj, oid) oe_set_delta_ext(&to_pack, obj, oid)
46 #define SET_DELTA_SIZE(obj, val) oe_set_delta_size(&to_pack, obj, val)
47 #define SET_DELTA_CHILD(obj, val) oe_set_delta_child(&to_pack, obj, val)
48 #define SET_DELTA_SIBLING(obj, val) oe_set_delta_sibling(&to_pack, obj, val)
49
50 static const char *pack_usage[] = {
51 N_("git pack-objects --stdout [<options>...] [< <ref-list> | < <object-list>]"),
52 N_("git pack-objects [<options>...] <base-name> [< <ref-list> | < <object-list>]"),
53 NULL
54 };
55
56 /*
57 * Objects we are going to pack are collected in the `to_pack` structure.
58 * It contains an array (dynamically expanded) of the object data, and a map
59 * that can resolve SHA1s to their position in the array.
60 */
61 static struct packing_data to_pack;
62
63 static struct pack_idx_entry **written_list;
64 static uint32_t nr_result, nr_written, nr_seen;
65 static struct bitmap_index *bitmap_git;
66 static uint32_t write_layer;
67
68 static int non_empty;
69 static int reuse_delta = 1, reuse_object = 1;
70 static int keep_unreachable, unpack_unreachable, include_tag;
71 static timestamp_t unpack_unreachable_expiration;
72 static int pack_loose_unreachable;
73 static int local;
74 static int have_non_local_packs;
75 static int incremental;
76 static int ignore_packed_keep_on_disk;
77 static int ignore_packed_keep_in_core;
78 static int allow_ofs_delta;
79 static struct pack_idx_option pack_idx_opts;
80 static const char *base_name;
81 static int progress = 1;
82 static int window = 10;
83 static unsigned long pack_size_limit;
84 static int depth = 50;
85 static int delta_search_threads;
86 static int pack_to_stdout;
87 static int thin;
88 static int num_preferred_base;
89 static struct progress *progress_state;
90
91 static struct packed_git *reuse_packfile;
92 static uint32_t reuse_packfile_objects;
93 static off_t reuse_packfile_offset;
94
95 static int use_bitmap_index_default = 1;
96 static int use_bitmap_index = -1;
97 static int write_bitmap_index;
98 static uint16_t write_bitmap_options;
99
100 static int exclude_promisor_objects;
101
102 static int use_delta_islands;
103
104 static unsigned long delta_cache_size = 0;
105 static unsigned long max_delta_cache_size = DEFAULT_DELTA_CACHE_SIZE;
106 static unsigned long cache_max_small_delta_size = 1000;
107
108 static unsigned long window_memory_limit = 0;
109
110 static struct list_objects_filter_options filter_options;
111
112 enum missing_action {
113 MA_ERROR = 0, /* fail if any missing objects are encountered */
114 MA_ALLOW_ANY, /* silently allow ALL missing objects */
115 MA_ALLOW_PROMISOR, /* silently allow all missing PROMISOR objects */
116 };
117 static enum missing_action arg_missing_action;
118 static show_object_fn fn_show_object;
119
120 /*
121 * stats
122 */
123 static uint32_t written, written_delta;
124 static uint32_t reused, reused_delta;
125
126 /*
127 * Indexed commits
128 */
129 static struct commit **indexed_commits;
130 static unsigned int indexed_commits_nr;
131 static unsigned int indexed_commits_alloc;
132
133 static void index_commit_for_bitmap(struct commit *commit)
134 {
135 if (indexed_commits_nr >= indexed_commits_alloc) {
136 indexed_commits_alloc = (indexed_commits_alloc + 32) * 2;
137 REALLOC_ARRAY(indexed_commits, indexed_commits_alloc);
138 }
139
140 indexed_commits[indexed_commits_nr++] = commit;
141 }
142
143 static void *get_delta(struct object_entry *entry)
144 {
145 unsigned long size, base_size, delta_size;
146 void *buf, *base_buf, *delta_buf;
147 enum object_type type;
148
149 buf = read_object_file(&entry->idx.oid, &type, &size);
150 if (!buf)
151 die(_("unable to read %s"), oid_to_hex(&entry->idx.oid));
152 base_buf = read_object_file(&DELTA(entry)->idx.oid, &type,
153 &base_size);
154 if (!base_buf)
155 die("unable to read %s",
156 oid_to_hex(&DELTA(entry)->idx.oid));
157 delta_buf = diff_delta(base_buf, base_size,
158 buf, size, &delta_size, 0);
159 /*
160 * We succesfully computed this delta once but dropped it for
161 * memory reasons. Something is very wrong if this time we
162 * recompute and create a different delta.
163 */
164 if (!delta_buf || delta_size != DELTA_SIZE(entry))
165 BUG("delta size changed");
166 free(buf);
167 free(base_buf);
168 return delta_buf;
169 }
170
171 static unsigned long do_compress(void **pptr, unsigned long size)
172 {
173 git_zstream stream;
174 void *in, *out;
175 unsigned long maxsize;
176
177 git_deflate_init(&stream, pack_compression_level);
178 maxsize = git_deflate_bound(&stream, size);
179
180 in = *pptr;
181 out = xmalloc(maxsize);
182 *pptr = out;
183
184 stream.next_in = in;
185 stream.avail_in = size;
186 stream.next_out = out;
187 stream.avail_out = maxsize;
188 while (git_deflate(&stream, Z_FINISH) == Z_OK)
189 ; /* nothing */
190 git_deflate_end(&stream);
191
192 free(in);
193 return stream.total_out;
194 }
195
196 static unsigned long write_large_blob_data(struct git_istream *st, struct hashfile *f,
197 const struct object_id *oid)
198 {
199 git_zstream stream;
200 unsigned char ibuf[1024 * 16];
201 unsigned char obuf[1024 * 16];
202 unsigned long olen = 0;
203
204 git_deflate_init(&stream, pack_compression_level);
205
206 for (;;) {
207 ssize_t readlen;
208 int zret = Z_OK;
209 readlen = read_istream(st, ibuf, sizeof(ibuf));
210 if (readlen == -1)
211 die(_("unable to read %s"), oid_to_hex(oid));
212
213 stream.next_in = ibuf;
214 stream.avail_in = readlen;
215 while ((stream.avail_in || readlen == 0) &&
216 (zret == Z_OK || zret == Z_BUF_ERROR)) {
217 stream.next_out = obuf;
218 stream.avail_out = sizeof(obuf);
219 zret = git_deflate(&stream, readlen ? 0 : Z_FINISH);
220 hashwrite(f, obuf, stream.next_out - obuf);
221 olen += stream.next_out - obuf;
222 }
223 if (stream.avail_in)
224 die(_("deflate error (%d)"), zret);
225 if (readlen == 0) {
226 if (zret != Z_STREAM_END)
227 die(_("deflate error (%d)"), zret);
228 break;
229 }
230 }
231 git_deflate_end(&stream);
232 return olen;
233 }
234
235 /*
236 * we are going to reuse the existing object data as is. make
237 * sure it is not corrupt.
238 */
239 static int check_pack_inflate(struct packed_git *p,
240 struct pack_window **w_curs,
241 off_t offset,
242 off_t len,
243 unsigned long expect)
244 {
245 git_zstream stream;
246 unsigned char fakebuf[4096], *in;
247 int st;
248
249 memset(&stream, 0, sizeof(stream));
250 git_inflate_init(&stream);
251 do {
252 in = use_pack(p, w_curs, offset, &stream.avail_in);
253 stream.next_in = in;
254 stream.next_out = fakebuf;
255 stream.avail_out = sizeof(fakebuf);
256 st = git_inflate(&stream, Z_FINISH);
257 offset += stream.next_in - in;
258 } while (st == Z_OK || st == Z_BUF_ERROR);
259 git_inflate_end(&stream);
260 return (st == Z_STREAM_END &&
261 stream.total_out == expect &&
262 stream.total_in == len) ? 0 : -1;
263 }
264
265 static void copy_pack_data(struct hashfile *f,
266 struct packed_git *p,
267 struct pack_window **w_curs,
268 off_t offset,
269 off_t len)
270 {
271 unsigned char *in;
272 unsigned long avail;
273
274 while (len) {
275 in = use_pack(p, w_curs, offset, &avail);
276 if (avail > len)
277 avail = (unsigned long)len;
278 hashwrite(f, in, avail);
279 offset += avail;
280 len -= avail;
281 }
282 }
283
284 /* Return 0 if we will bust the pack-size limit */
285 static unsigned long write_no_reuse_object(struct hashfile *f, struct object_entry *entry,
286 unsigned long limit, int usable_delta)
287 {
288 unsigned long size, datalen;
289 unsigned char header[MAX_PACK_OBJECT_HEADER],
290 dheader[MAX_PACK_OBJECT_HEADER];
291 unsigned hdrlen;
292 enum object_type type;
293 void *buf;
294 struct git_istream *st = NULL;
295 const unsigned hashsz = the_hash_algo->rawsz;
296
297 if (!usable_delta) {
298 if (oe_type(entry) == OBJ_BLOB &&
299 oe_size_greater_than(&to_pack, entry, big_file_threshold) &&
300 (st = open_istream(&entry->idx.oid, &type, &size, NULL)) != NULL)
301 buf = NULL;
302 else {
303 buf = read_object_file(&entry->idx.oid, &type, &size);
304 if (!buf)
305 die(_("unable to read %s"),
306 oid_to_hex(&entry->idx.oid));
307 }
308 /*
309 * make sure no cached delta data remains from a
310 * previous attempt before a pack split occurred.
311 */
312 FREE_AND_NULL(entry->delta_data);
313 entry->z_delta_size = 0;
314 } else if (entry->delta_data) {
315 size = DELTA_SIZE(entry);
316 buf = entry->delta_data;
317 entry->delta_data = NULL;
318 type = (allow_ofs_delta && DELTA(entry)->idx.offset) ?
319 OBJ_OFS_DELTA : OBJ_REF_DELTA;
320 } else {
321 buf = get_delta(entry);
322 size = DELTA_SIZE(entry);
323 type = (allow_ofs_delta && DELTA(entry)->idx.offset) ?
324 OBJ_OFS_DELTA : OBJ_REF_DELTA;
325 }
326
327 if (st) /* large blob case, just assume we don't compress well */
328 datalen = size;
329 else if (entry->z_delta_size)
330 datalen = entry->z_delta_size;
331 else
332 datalen = do_compress(&buf, size);
333
334 /*
335 * The object header is a byte of 'type' followed by zero or
336 * more bytes of length.
337 */
338 hdrlen = encode_in_pack_object_header(header, sizeof(header),
339 type, size);
340
341 if (type == OBJ_OFS_DELTA) {
342 /*
343 * Deltas with relative base contain an additional
344 * encoding of the relative offset for the delta
345 * base from this object's position in the pack.
346 */
347 off_t ofs = entry->idx.offset - DELTA(entry)->idx.offset;
348 unsigned pos = sizeof(dheader) - 1;
349 dheader[pos] = ofs & 127;
350 while (ofs >>= 7)
351 dheader[--pos] = 128 | (--ofs & 127);
352 if (limit && hdrlen + sizeof(dheader) - pos + datalen + hashsz >= limit) {
353 if (st)
354 close_istream(st);
355 free(buf);
356 return 0;
357 }
358 hashwrite(f, header, hdrlen);
359 hashwrite(f, dheader + pos, sizeof(dheader) - pos);
360 hdrlen += sizeof(dheader) - pos;
361 } else if (type == OBJ_REF_DELTA) {
362 /*
363 * Deltas with a base reference contain
364 * additional bytes for the base object ID.
365 */
366 if (limit && hdrlen + hashsz + datalen + hashsz >= limit) {
367 if (st)
368 close_istream(st);
369 free(buf);
370 return 0;
371 }
372 hashwrite(f, header, hdrlen);
373 hashwrite(f, DELTA(entry)->idx.oid.hash, hashsz);
374 hdrlen += hashsz;
375 } else {
376 if (limit && hdrlen + datalen + hashsz >= limit) {
377 if (st)
378 close_istream(st);
379 free(buf);
380 return 0;
381 }
382 hashwrite(f, header, hdrlen);
383 }
384 if (st) {
385 datalen = write_large_blob_data(st, f, &entry->idx.oid);
386 close_istream(st);
387 } else {
388 hashwrite(f, buf, datalen);
389 free(buf);
390 }
391
392 return hdrlen + datalen;
393 }
394
395 /* Return 0 if we will bust the pack-size limit */
396 static off_t write_reuse_object(struct hashfile *f, struct object_entry *entry,
397 unsigned long limit, int usable_delta)
398 {
399 struct packed_git *p = IN_PACK(entry);
400 struct pack_window *w_curs = NULL;
401 struct revindex_entry *revidx;
402 off_t offset;
403 enum object_type type = oe_type(entry);
404 off_t datalen;
405 unsigned char header[MAX_PACK_OBJECT_HEADER],
406 dheader[MAX_PACK_OBJECT_HEADER];
407 unsigned hdrlen;
408 const unsigned hashsz = the_hash_algo->rawsz;
409 unsigned long entry_size = SIZE(entry);
410
411 if (DELTA(entry))
412 type = (allow_ofs_delta && DELTA(entry)->idx.offset) ?
413 OBJ_OFS_DELTA : OBJ_REF_DELTA;
414 hdrlen = encode_in_pack_object_header(header, sizeof(header),
415 type, entry_size);
416
417 offset = entry->in_pack_offset;
418 revidx = find_pack_revindex(p, offset);
419 datalen = revidx[1].offset - offset;
420 if (!pack_to_stdout && p->index_version > 1 &&
421 check_pack_crc(p, &w_curs, offset, datalen, revidx->nr)) {
422 error(_("bad packed object CRC for %s"),
423 oid_to_hex(&entry->idx.oid));
424 unuse_pack(&w_curs);
425 return write_no_reuse_object(f, entry, limit, usable_delta);
426 }
427
428 offset += entry->in_pack_header_size;
429 datalen -= entry->in_pack_header_size;
430
431 if (!pack_to_stdout && p->index_version == 1 &&
432 check_pack_inflate(p, &w_curs, offset, datalen, entry_size)) {
433 error(_("corrupt packed object for %s"),
434 oid_to_hex(&entry->idx.oid));
435 unuse_pack(&w_curs);
436 return write_no_reuse_object(f, entry, limit, usable_delta);
437 }
438
439 if (type == OBJ_OFS_DELTA) {
440 off_t ofs = entry->idx.offset - DELTA(entry)->idx.offset;
441 unsigned pos = sizeof(dheader) - 1;
442 dheader[pos] = ofs & 127;
443 while (ofs >>= 7)
444 dheader[--pos] = 128 | (--ofs & 127);
445 if (limit && hdrlen + sizeof(dheader) - pos + datalen + hashsz >= limit) {
446 unuse_pack(&w_curs);
447 return 0;
448 }
449 hashwrite(f, header, hdrlen);
450 hashwrite(f, dheader + pos, sizeof(dheader) - pos);
451 hdrlen += sizeof(dheader) - pos;
452 reused_delta++;
453 } else if (type == OBJ_REF_DELTA) {
454 if (limit && hdrlen + hashsz + datalen + hashsz >= limit) {
455 unuse_pack(&w_curs);
456 return 0;
457 }
458 hashwrite(f, header, hdrlen);
459 hashwrite(f, DELTA(entry)->idx.oid.hash, hashsz);
460 hdrlen += hashsz;
461 reused_delta++;
462 } else {
463 if (limit && hdrlen + datalen + hashsz >= limit) {
464 unuse_pack(&w_curs);
465 return 0;
466 }
467 hashwrite(f, header, hdrlen);
468 }
469 copy_pack_data(f, p, &w_curs, offset, datalen);
470 unuse_pack(&w_curs);
471 reused++;
472 return hdrlen + datalen;
473 }
474
475 /* Return 0 if we will bust the pack-size limit */
476 static off_t write_object(struct hashfile *f,
477 struct object_entry *entry,
478 off_t write_offset)
479 {
480 unsigned long limit;
481 off_t len;
482 int usable_delta, to_reuse;
483
484 if (!pack_to_stdout)
485 crc32_begin(f);
486
487 /* apply size limit if limited packsize and not first object */
488 if (!pack_size_limit || !nr_written)
489 limit = 0;
490 else if (pack_size_limit <= write_offset)
491 /*
492 * the earlier object did not fit the limit; avoid
493 * mistaking this with unlimited (i.e. limit = 0).
494 */
495 limit = 1;
496 else
497 limit = pack_size_limit - write_offset;
498
499 if (!DELTA(entry))
500 usable_delta = 0; /* no delta */
501 else if (!pack_size_limit)
502 usable_delta = 1; /* unlimited packfile */
503 else if (DELTA(entry)->idx.offset == (off_t)-1)
504 usable_delta = 0; /* base was written to another pack */
505 else if (DELTA(entry)->idx.offset)
506 usable_delta = 1; /* base already exists in this pack */
507 else
508 usable_delta = 0; /* base could end up in another pack */
509
510 if (!reuse_object)
511 to_reuse = 0; /* explicit */
512 else if (!IN_PACK(entry))
513 to_reuse = 0; /* can't reuse what we don't have */
514 else if (oe_type(entry) == OBJ_REF_DELTA ||
515 oe_type(entry) == OBJ_OFS_DELTA)
516 /* check_object() decided it for us ... */
517 to_reuse = usable_delta;
518 /* ... but pack split may override that */
519 else if (oe_type(entry) != entry->in_pack_type)
520 to_reuse = 0; /* pack has delta which is unusable */
521 else if (DELTA(entry))
522 to_reuse = 0; /* we want to pack afresh */
523 else
524 to_reuse = 1; /* we have it in-pack undeltified,
525 * and we do not need to deltify it.
526 */
527
528 if (!to_reuse)
529 len = write_no_reuse_object(f, entry, limit, usable_delta);
530 else
531 len = write_reuse_object(f, entry, limit, usable_delta);
532 if (!len)
533 return 0;
534
535 if (usable_delta)
536 written_delta++;
537 written++;
538 if (!pack_to_stdout)
539 entry->idx.crc32 = crc32_end(f);
540 return len;
541 }
542
543 enum write_one_status {
544 WRITE_ONE_SKIP = -1, /* already written */
545 WRITE_ONE_BREAK = 0, /* writing this will bust the limit; not written */
546 WRITE_ONE_WRITTEN = 1, /* normal */
547 WRITE_ONE_RECURSIVE = 2 /* already scheduled to be written */
548 };
549
550 static enum write_one_status write_one(struct hashfile *f,
551 struct object_entry *e,
552 off_t *offset)
553 {
554 off_t size;
555 int recursing;
556
557 /*
558 * we set offset to 1 (which is an impossible value) to mark
559 * the fact that this object is involved in "write its base
560 * first before writing a deltified object" recursion.
561 */
562 recursing = (e->idx.offset == 1);
563 if (recursing) {
564 warning(_("recursive delta detected for object %s"),
565 oid_to_hex(&e->idx.oid));
566 return WRITE_ONE_RECURSIVE;
567 } else if (e->idx.offset || e->preferred_base) {
568 /* offset is non zero if object is written already. */
569 return WRITE_ONE_SKIP;
570 }
571
572 /* if we are deltified, write out base object first. */
573 if (DELTA(e)) {
574 e->idx.offset = 1; /* now recurse */
575 switch (write_one(f, DELTA(e), offset)) {
576 case WRITE_ONE_RECURSIVE:
577 /* we cannot depend on this one */
578 SET_DELTA(e, NULL);
579 break;
580 default:
581 break;
582 case WRITE_ONE_BREAK:
583 e->idx.offset = recursing;
584 return WRITE_ONE_BREAK;
585 }
586 }
587
588 e->idx.offset = *offset;
589 size = write_object(f, e, *offset);
590 if (!size) {
591 e->idx.offset = recursing;
592 return WRITE_ONE_BREAK;
593 }
594 written_list[nr_written++] = &e->idx;
595
596 /* make sure off_t is sufficiently large not to wrap */
597 if (signed_add_overflows(*offset, size))
598 die(_("pack too large for current definition of off_t"));
599 *offset += size;
600 return WRITE_ONE_WRITTEN;
601 }
602
603 static int mark_tagged(const char *path, const struct object_id *oid, int flag,
604 void *cb_data)
605 {
606 struct object_id peeled;
607 struct object_entry *entry = packlist_find(&to_pack, oid->hash, NULL);
608
609 if (entry)
610 entry->tagged = 1;
611 if (!peel_ref(path, &peeled)) {
612 entry = packlist_find(&to_pack, peeled.hash, NULL);
613 if (entry)
614 entry->tagged = 1;
615 }
616 return 0;
617 }
618
619 static inline void add_to_write_order(struct object_entry **wo,
620 unsigned int *endp,
621 struct object_entry *e)
622 {
623 if (e->filled || oe_layer(&to_pack, e) != write_layer)
624 return;
625 wo[(*endp)++] = e;
626 e->filled = 1;
627 }
628
629 static void add_descendants_to_write_order(struct object_entry **wo,
630 unsigned int *endp,
631 struct object_entry *e)
632 {
633 int add_to_order = 1;
634 while (e) {
635 if (add_to_order) {
636 struct object_entry *s;
637 /* add this node... */
638 add_to_write_order(wo, endp, e);
639 /* all its siblings... */
640 for (s = DELTA_SIBLING(e); s; s = DELTA_SIBLING(s)) {
641 add_to_write_order(wo, endp, s);
642 }
643 }
644 /* drop down a level to add left subtree nodes if possible */
645 if (DELTA_CHILD(e)) {
646 add_to_order = 1;
647 e = DELTA_CHILD(e);
648 } else {
649 add_to_order = 0;
650 /* our sibling might have some children, it is next */
651 if (DELTA_SIBLING(e)) {
652 e = DELTA_SIBLING(e);
653 continue;
654 }
655 /* go back to our parent node */
656 e = DELTA(e);
657 while (e && !DELTA_SIBLING(e)) {
658 /* we're on the right side of a subtree, keep
659 * going up until we can go right again */
660 e = DELTA(e);
661 }
662 if (!e) {
663 /* done- we hit our original root node */
664 return;
665 }
666 /* pass it off to sibling at this level */
667 e = DELTA_SIBLING(e);
668 }
669 };
670 }
671
672 static void add_family_to_write_order(struct object_entry **wo,
673 unsigned int *endp,
674 struct object_entry *e)
675 {
676 struct object_entry *root;
677
678 for (root = e; DELTA(root); root = DELTA(root))
679 ; /* nothing */
680 add_descendants_to_write_order(wo, endp, root);
681 }
682
683 static void compute_layer_order(struct object_entry **wo, unsigned int *wo_end)
684 {
685 unsigned int i, last_untagged;
686 struct object_entry *objects = to_pack.objects;
687
688 for (i = 0; i < to_pack.nr_objects; i++) {
689 if (objects[i].tagged)
690 break;
691 add_to_write_order(wo, wo_end, &objects[i]);
692 }
693 last_untagged = i;
694
695 /*
696 * Then fill all the tagged tips.
697 */
698 for (; i < to_pack.nr_objects; i++) {
699 if (objects[i].tagged)
700 add_to_write_order(wo, wo_end, &objects[i]);
701 }
702
703 /*
704 * And then all remaining commits and tags.
705 */
706 for (i = last_untagged; i < to_pack.nr_objects; i++) {
707 if (oe_type(&objects[i]) != OBJ_COMMIT &&
708 oe_type(&objects[i]) != OBJ_TAG)
709 continue;
710 add_to_write_order(wo, wo_end, &objects[i]);
711 }
712
713 /*
714 * And then all the trees.
715 */
716 for (i = last_untagged; i < to_pack.nr_objects; i++) {
717 if (oe_type(&objects[i]) != OBJ_TREE)
718 continue;
719 add_to_write_order(wo, wo_end, &objects[i]);
720 }
721
722 /*
723 * Finally all the rest in really tight order
724 */
725 for (i = last_untagged; i < to_pack.nr_objects; i++) {
726 if (!objects[i].filled && oe_layer(&to_pack, &objects[i]) == write_layer)
727 add_family_to_write_order(wo, wo_end, &objects[i]);
728 }
729 }
730
731 static struct object_entry **compute_write_order(void)
732 {
733 uint32_t max_layers = 1;
734 unsigned int i, wo_end;
735
736 struct object_entry **wo;
737 struct object_entry *objects = to_pack.objects;
738
739 for (i = 0; i < to_pack.nr_objects; i++) {
740 objects[i].tagged = 0;
741 objects[i].filled = 0;
742 SET_DELTA_CHILD(&objects[i], NULL);
743 SET_DELTA_SIBLING(&objects[i], NULL);
744 }
745
746 /*
747 * Fully connect delta_child/delta_sibling network.
748 * Make sure delta_sibling is sorted in the original
749 * recency order.
750 */
751 for (i = to_pack.nr_objects; i > 0;) {
752 struct object_entry *e = &objects[--i];
753 if (!DELTA(e))
754 continue;
755 /* Mark me as the first child */
756 e->delta_sibling_idx = DELTA(e)->delta_child_idx;
757 SET_DELTA_CHILD(DELTA(e), e);
758 }
759
760 /*
761 * Mark objects that are at the tip of tags.
762 */
763 for_each_tag_ref(mark_tagged, NULL);
764
765 if (use_delta_islands)
766 max_layers = compute_pack_layers(&to_pack);
767
768 ALLOC_ARRAY(wo, to_pack.nr_objects);
769 wo_end = 0;
770
771 for (; write_layer < max_layers; ++write_layer)
772 compute_layer_order(wo, &wo_end);
773
774 if (wo_end != to_pack.nr_objects)
775 die(_("ordered %u objects, expected %"PRIu32),
776 wo_end, to_pack.nr_objects);
777
778 return wo;
779 }
780
781 static off_t write_reused_pack(struct hashfile *f)
782 {
783 unsigned char buffer[8192];
784 off_t to_write, total;
785 int fd;
786
787 if (!is_pack_valid(reuse_packfile))
788 die(_("packfile is invalid: %s"), reuse_packfile->pack_name);
789
790 fd = git_open(reuse_packfile->pack_name);
791 if (fd < 0)
792 die_errno(_("unable to open packfile for reuse: %s"),
793 reuse_packfile->pack_name);
794
795 if (lseek(fd, sizeof(struct pack_header), SEEK_SET) == -1)
796 die_errno(_("unable to seek in reused packfile"));
797
798 if (reuse_packfile_offset < 0)
799 reuse_packfile_offset = reuse_packfile->pack_size - the_hash_algo->rawsz;
800
801 total = to_write = reuse_packfile_offset - sizeof(struct pack_header);
802
803 while (to_write) {
804 int read_pack = xread(fd, buffer, sizeof(buffer));
805
806 if (read_pack <= 0)
807 die_errno(_("unable to read from reused packfile"));
808
809 if (read_pack > to_write)
810 read_pack = to_write;
811
812 hashwrite(f, buffer, read_pack);
813 to_write -= read_pack;
814
815 /*
816 * We don't know the actual number of objects written,
817 * only how many bytes written, how many bytes total, and
818 * how many objects total. So we can fake it by pretending all
819 * objects we are writing are the same size. This gives us a
820 * smooth progress meter, and at the end it matches the true
821 * answer.
822 */
823 written = reuse_packfile_objects *
824 (((double)(total - to_write)) / total);
825 display_progress(progress_state, written);
826 }
827
828 close(fd);
829 written = reuse_packfile_objects;
830 display_progress(progress_state, written);
831 return reuse_packfile_offset - sizeof(struct pack_header);
832 }
833
834 static const char no_split_warning[] = N_(
835 "disabling bitmap writing, packs are split due to pack.packSizeLimit"
836 );
837
838 static void write_pack_file(void)
839 {
840 uint32_t i = 0, j;
841 struct hashfile *f;
842 off_t offset;
843 uint32_t nr_remaining = nr_result;
844 time_t last_mtime = 0;
845 struct object_entry **write_order;
846
847 if (progress > pack_to_stdout)
848 progress_state = start_progress(_("Writing objects"), nr_result);
849 ALLOC_ARRAY(written_list, to_pack.nr_objects);
850 write_order = compute_write_order();
851
852 do {
853 struct object_id oid;
854 char *pack_tmp_name = NULL;
855
856 if (pack_to_stdout)
857 f = hashfd_throughput(1, "<stdout>", progress_state);
858 else
859 f = create_tmp_packfile(&pack_tmp_name);
860
861 offset = write_pack_header(f, nr_remaining);
862
863 if (reuse_packfile) {
864 off_t packfile_size;
865 assert(pack_to_stdout);
866
867 packfile_size = write_reused_pack(f);
868 offset += packfile_size;
869 }
870
871 nr_written = 0;
872 for (; i < to_pack.nr_objects; i++) {
873 struct object_entry *e = write_order[i];
874 if (write_one(f, e, &offset) == WRITE_ONE_BREAK)
875 break;
876 display_progress(progress_state, written);
877 }
878
879 /*
880 * Did we write the wrong # entries in the header?
881 * If so, rewrite it like in fast-import
882 */
883 if (pack_to_stdout) {
884 finalize_hashfile(f, oid.hash, CSUM_HASH_IN_STREAM | CSUM_CLOSE);
885 } else if (nr_written == nr_remaining) {
886 finalize_hashfile(f, oid.hash, CSUM_HASH_IN_STREAM | CSUM_FSYNC | CSUM_CLOSE);
887 } else {
888 int fd = finalize_hashfile(f, oid.hash, 0);
889 fixup_pack_header_footer(fd, oid.hash, pack_tmp_name,
890 nr_written, oid.hash, offset);
891 close(fd);
892 if (write_bitmap_index) {
893 warning(_(no_split_warning));
894 write_bitmap_index = 0;
895 }
896 }
897
898 if (!pack_to_stdout) {
899 struct stat st;
900 struct strbuf tmpname = STRBUF_INIT;
901
902 /*
903 * Packs are runtime accessed in their mtime
904 * order since newer packs are more likely to contain
905 * younger objects. So if we are creating multiple
906 * packs then we should modify the mtime of later ones
907 * to preserve this property.
908 */
909 if (stat(pack_tmp_name, &st) < 0) {
910 warning_errno(_("failed to stat %s"), pack_tmp_name);
911 } else if (!last_mtime) {
912 last_mtime = st.st_mtime;
913 } else {
914 struct utimbuf utb;
915 utb.actime = st.st_atime;
916 utb.modtime = --last_mtime;
917 if (utime(pack_tmp_name, &utb) < 0)
918 warning_errno(_("failed utime() on %s"), pack_tmp_name);
919 }
920
921 strbuf_addf(&tmpname, "%s-", base_name);
922
923 if (write_bitmap_index) {
924 bitmap_writer_set_checksum(oid.hash);
925 bitmap_writer_build_type_index(
926 &to_pack, written_list, nr_written);
927 }
928
929 finish_tmp_packfile(&tmpname, pack_tmp_name,
930 written_list, nr_written,
931 &pack_idx_opts, oid.hash);
932
933 if (write_bitmap_index) {
934 strbuf_addf(&tmpname, "%s.bitmap", oid_to_hex(&oid));
935
936 stop_progress(&progress_state);
937
938 bitmap_writer_show_progress(progress);
939 bitmap_writer_reuse_bitmaps(&to_pack);
940 bitmap_writer_select_commits(indexed_commits, indexed_commits_nr, -1);
941 bitmap_writer_build(&to_pack);
942 bitmap_writer_finish(written_list, nr_written,
943 tmpname.buf, write_bitmap_options);
944 write_bitmap_index = 0;
945 }
946
947 strbuf_release(&tmpname);
948 free(pack_tmp_name);
949 puts(oid_to_hex(&oid));
950 }
951
952 /* mark written objects as written to previous pack */
953 for (j = 0; j < nr_written; j++) {
954 written_list[j]->offset = (off_t)-1;
955 }
956 nr_remaining -= nr_written;
957 } while (nr_remaining && i < to_pack.nr_objects);
958
959 free(written_list);
960 free(write_order);
961 stop_progress(&progress_state);
962 if (written != nr_result)
963 die(_("wrote %"PRIu32" objects while expecting %"PRIu32),
964 written, nr_result);
965 }
966
967 static int no_try_delta(const char *path)
968 {
969 static struct attr_check *check;
970
971 if (!check)
972 check = attr_check_initl("delta", NULL);
973 git_check_attr(&the_index, path, check);
974 if (ATTR_FALSE(check->items[0].value))
975 return 1;
976 return 0;
977 }
978
979 /*
980 * When adding an object, check whether we have already added it
981 * to our packing list. If so, we can skip. However, if we are
982 * being asked to excludei t, but the previous mention was to include
983 * it, make sure to adjust its flags and tweak our numbers accordingly.
984 *
985 * As an optimization, we pass out the index position where we would have
986 * found the item, since that saves us from having to look it up again a
987 * few lines later when we want to add the new entry.
988 */
989 static int have_duplicate_entry(const struct object_id *oid,
990 int exclude,
991 uint32_t *index_pos)
992 {
993 struct object_entry *entry;
994
995 entry = packlist_find(&to_pack, oid->hash, index_pos);
996 if (!entry)
997 return 0;
998
999 if (exclude) {
1000 if (!entry->preferred_base)
1001 nr_result--;
1002 entry->preferred_base = 1;
1003 }
1004
1005 return 1;
1006 }
1007
1008 static int want_found_object(int exclude, struct packed_git *p)
1009 {
1010 if (exclude)
1011 return 1;
1012 if (incremental)
1013 return 0;
1014
1015 /*
1016 * When asked to do --local (do not include an object that appears in a
1017 * pack we borrow from elsewhere) or --honor-pack-keep (do not include
1018 * an object that appears in a pack marked with .keep), finding a pack
1019 * that matches the criteria is sufficient for us to decide to omit it.
1020 * However, even if this pack does not satisfy the criteria, we need to
1021 * make sure no copy of this object appears in _any_ pack that makes us
1022 * to omit the object, so we need to check all the packs.
1023 *
1024 * We can however first check whether these options can possible matter;
1025 * if they do not matter we know we want the object in generated pack.
1026 * Otherwise, we signal "-1" at the end to tell the caller that we do
1027 * not know either way, and it needs to check more packs.
1028 */
1029 if (!ignore_packed_keep_on_disk &&
1030 !ignore_packed_keep_in_core &&
1031 (!local || !have_non_local_packs))
1032 return 1;
1033
1034 if (local && !p->pack_local)
1035 return 0;
1036 if (p->pack_local &&
1037 ((ignore_packed_keep_on_disk && p->pack_keep) ||
1038 (ignore_packed_keep_in_core && p->pack_keep_in_core)))
1039 return 0;
1040
1041 /* we don't know yet; keep looking for more packs */
1042 return -1;
1043 }
1044
1045 /*
1046 * Check whether we want the object in the pack (e.g., we do not want
1047 * objects found in non-local stores if the "--local" option was used).
1048 *
1049 * If the caller already knows an existing pack it wants to take the object
1050 * from, that is passed in *found_pack and *found_offset; otherwise this
1051 * function finds if there is any pack that has the object and returns the pack
1052 * and its offset in these variables.
1053 */
1054 static int want_object_in_pack(const struct object_id *oid,
1055 int exclude,
1056 struct packed_git **found_pack,
1057 off_t *found_offset)
1058 {
1059 int want;
1060 struct list_head *pos;
1061 struct multi_pack_index *m;
1062
1063 if (!exclude && local && has_loose_object_nonlocal(oid))
1064 return 0;
1065
1066 /*
1067 * If we already know the pack object lives in, start checks from that
1068 * pack - in the usual case when neither --local was given nor .keep files
1069 * are present we will determine the answer right now.
1070 */
1071 if (*found_pack) {
1072 want = want_found_object(exclude, *found_pack);
1073 if (want != -1)
1074 return want;
1075 }
1076
1077 for (m = get_multi_pack_index(the_repository); m; m = m->next) {
1078 struct pack_entry e;
1079 if (fill_midx_entry(oid, &e, m)) {
1080 struct packed_git *p = e.p;
1081 off_t offset;
1082
1083 if (p == *found_pack)
1084 offset = *found_offset;
1085 else
1086 offset = find_pack_entry_one(oid->hash, p);
1087
1088 if (offset) {
1089 if (!*found_pack) {
1090 if (!is_pack_valid(p))
1091 continue;
1092 *found_offset = offset;
1093 *found_pack = p;
1094 }
1095 want = want_found_object(exclude, p);
1096 if (want != -1)
1097 return want;
1098 }
1099 }
1100 }
1101
1102 list_for_each(pos, get_packed_git_mru(the_repository)) {
1103 struct packed_git *p = list_entry(pos, struct packed_git, mru);
1104 off_t offset;
1105
1106 if (p == *found_pack)
1107 offset = *found_offset;
1108 else
1109 offset = find_pack_entry_one(oid->hash, p);
1110
1111 if (offset) {
1112 if (!*found_pack) {
1113 if (!is_pack_valid(p))
1114 continue;
1115 *found_offset = offset;
1116 *found_pack = p;
1117 }
1118 want = want_found_object(exclude, p);
1119 if (!exclude && want > 0)
1120 list_move(&p->mru,
1121 get_packed_git_mru(the_repository));
1122 if (want != -1)
1123 return want;
1124 }
1125 }
1126
1127 return 1;
1128 }
1129
1130 static void create_object_entry(const struct object_id *oid,
1131 enum object_type type,
1132 uint32_t hash,
1133 int exclude,
1134 int no_try_delta,
1135 uint32_t index_pos,
1136 struct packed_git *found_pack,
1137 off_t found_offset)
1138 {
1139 struct object_entry *entry;
1140
1141 entry = packlist_alloc(&to_pack, oid->hash, index_pos);
1142 entry->hash = hash;
1143 oe_set_type(entry, type);
1144 if (exclude)
1145 entry->preferred_base = 1;
1146 else
1147 nr_result++;
1148 if (found_pack) {
1149 oe_set_in_pack(&to_pack, entry, found_pack);
1150 entry->in_pack_offset = found_offset;
1151 }
1152
1153 entry->no_try_delta = no_try_delta;
1154 }
1155
1156 static const char no_closure_warning[] = N_(
1157 "disabling bitmap writing, as some objects are not being packed"
1158 );
1159
1160 static int add_object_entry(const struct object_id *oid, enum object_type type,
1161 const char *name, int exclude)
1162 {
1163 struct packed_git *found_pack = NULL;
1164 off_t found_offset = 0;
1165 uint32_t index_pos;
1166
1167 display_progress(progress_state, ++nr_seen);
1168
1169 if (have_duplicate_entry(oid, exclude, &index_pos))
1170 return 0;
1171
1172 if (!want_object_in_pack(oid, exclude, &found_pack, &found_offset)) {
1173 /* The pack is missing an object, so it will not have closure */
1174 if (write_bitmap_index) {
1175 warning(_(no_closure_warning));
1176 write_bitmap_index = 0;
1177 }
1178 return 0;
1179 }
1180
1181 create_object_entry(oid, type, pack_name_hash(name),
1182 exclude, name && no_try_delta(name),
1183 index_pos, found_pack, found_offset);
1184 return 1;
1185 }
1186
1187 static int add_object_entry_from_bitmap(const struct object_id *oid,
1188 enum object_type type,
1189 int flags, uint32_t name_hash,
1190 struct packed_git *pack, off_t offset)
1191 {
1192 uint32_t index_pos;
1193
1194 display_progress(progress_state, ++nr_seen);
1195
1196 if (have_duplicate_entry(oid, 0, &index_pos))
1197 return 0;
1198
1199 if (!want_object_in_pack(oid, 0, &pack, &offset))
1200 return 0;
1201
1202 create_object_entry(oid, type, name_hash, 0, 0, index_pos, pack, offset);
1203 return 1;
1204 }
1205
1206 struct pbase_tree_cache {
1207 struct object_id oid;
1208 int ref;
1209 int temporary;
1210 void *tree_data;
1211 unsigned long tree_size;
1212 };
1213
1214 static struct pbase_tree_cache *(pbase_tree_cache[256]);
1215 static int pbase_tree_cache_ix(const struct object_id *oid)
1216 {
1217 return oid->hash[0] % ARRAY_SIZE(pbase_tree_cache);
1218 }
1219 static int pbase_tree_cache_ix_incr(int ix)
1220 {
1221 return (ix+1) % ARRAY_SIZE(pbase_tree_cache);
1222 }
1223
1224 static struct pbase_tree {
1225 struct pbase_tree *next;
1226 /* This is a phony "cache" entry; we are not
1227 * going to evict it or find it through _get()
1228 * mechanism -- this is for the toplevel node that
1229 * would almost always change with any commit.
1230 */
1231 struct pbase_tree_cache pcache;
1232 } *pbase_tree;
1233
1234 static struct pbase_tree_cache *pbase_tree_get(const struct object_id *oid)
1235 {
1236 struct pbase_tree_cache *ent, *nent;
1237 void *data;
1238 unsigned long size;
1239 enum object_type type;
1240 int neigh;
1241 int my_ix = pbase_tree_cache_ix(oid);
1242 int available_ix = -1;
1243
1244 /* pbase-tree-cache acts as a limited hashtable.
1245 * your object will be found at your index or within a few
1246 * slots after that slot if it is cached.
1247 */
1248 for (neigh = 0; neigh < 8; neigh++) {
1249 ent = pbase_tree_cache[my_ix];
1250 if (ent && oideq(&ent->oid, oid)) {
1251 ent->ref++;
1252 return ent;
1253 }
1254 else if (((available_ix < 0) && (!ent || !ent->ref)) ||
1255 ((0 <= available_ix) &&
1256 (!ent && pbase_tree_cache[available_ix])))
1257 available_ix = my_ix;
1258 if (!ent)
1259 break;
1260 my_ix = pbase_tree_cache_ix_incr(my_ix);
1261 }
1262
1263 /* Did not find one. Either we got a bogus request or
1264 * we need to read and perhaps cache.
1265 */
1266 data = read_object_file(oid, &type, &size);
1267 if (!data)
1268 return NULL;
1269 if (type != OBJ_TREE) {
1270 free(data);
1271 return NULL;
1272 }
1273
1274 /* We need to either cache or return a throwaway copy */
1275
1276 if (available_ix < 0)
1277 ent = NULL;
1278 else {
1279 ent = pbase_tree_cache[available_ix];
1280 my_ix = available_ix;
1281 }
1282
1283 if (!ent) {
1284 nent = xmalloc(sizeof(*nent));
1285 nent->temporary = (available_ix < 0);
1286 }
1287 else {
1288 /* evict and reuse */
1289 free(ent->tree_data);
1290 nent = ent;
1291 }
1292 oidcpy(&nent->oid, oid);
1293 nent->tree_data = data;
1294 nent->tree_size = size;
1295 nent->ref = 1;
1296 if (!nent->temporary)
1297 pbase_tree_cache[my_ix] = nent;
1298 return nent;
1299 }
1300
1301 static void pbase_tree_put(struct pbase_tree_cache *cache)
1302 {
1303 if (!cache->temporary) {
1304 cache->ref--;
1305 return;
1306 }
1307 free(cache->tree_data);
1308 free(cache);
1309 }
1310
1311 static int name_cmp_len(const char *name)
1312 {
1313 int i;
1314 for (i = 0; name[i] && name[i] != '\n' && name[i] != '/'; i++)
1315 ;
1316 return i;
1317 }
1318
1319 static void add_pbase_object(struct tree_desc *tree,
1320 const char *name,
1321 int cmplen,
1322 const char *fullname)
1323 {
1324 struct name_entry entry;
1325 int cmp;
1326
1327 while (tree_entry(tree,&entry)) {
1328 if (S_ISGITLINK(entry.mode))
1329 continue;
1330 cmp = tree_entry_len(&entry) != cmplen ? 1 :
1331 memcmp(name, entry.path, cmplen);
1332 if (cmp > 0)
1333 continue;
1334 if (cmp < 0)
1335 return;
1336 if (name[cmplen] != '/') {
1337 add_object_entry(entry.oid,
1338 object_type(entry.mode),
1339 fullname, 1);
1340 return;
1341 }
1342 if (S_ISDIR(entry.mode)) {
1343 struct tree_desc sub;
1344 struct pbase_tree_cache *tree;
1345 const char *down = name+cmplen+1;
1346 int downlen = name_cmp_len(down);
1347
1348 tree = pbase_tree_get(entry.oid);
1349 if (!tree)
1350 return;
1351 init_tree_desc(&sub, tree->tree_data, tree->tree_size);
1352
1353 add_pbase_object(&sub, down, downlen, fullname);
1354 pbase_tree_put(tree);
1355 }
1356 }
1357 }
1358
1359 static unsigned *done_pbase_paths;
1360 static int done_pbase_paths_num;
1361 static int done_pbase_paths_alloc;
1362 static int done_pbase_path_pos(unsigned hash)
1363 {
1364 int lo = 0;
1365 int hi = done_pbase_paths_num;
1366 while (lo < hi) {
1367 int mi = lo + (hi - lo) / 2;
1368 if (done_pbase_paths[mi] == hash)
1369 return mi;
1370 if (done_pbase_paths[mi] < hash)
1371 hi = mi;
1372 else
1373 lo = mi + 1;
1374 }
1375 return -lo-1;
1376 }
1377
1378 static int check_pbase_path(unsigned hash)
1379 {
1380 int pos = done_pbase_path_pos(hash);
1381 if (0 <= pos)
1382 return 1;
1383 pos = -pos - 1;
1384 ALLOC_GROW(done_pbase_paths,
1385 done_pbase_paths_num + 1,
1386 done_pbase_paths_alloc);
1387 done_pbase_paths_num++;
1388 if (pos < done_pbase_paths_num)
1389 MOVE_ARRAY(done_pbase_paths + pos + 1, done_pbase_paths + pos,
1390 done_pbase_paths_num - pos - 1);
1391 done_pbase_paths[pos] = hash;
1392 return 0;
1393 }
1394
1395 static void add_preferred_base_object(const char *name)
1396 {
1397 struct pbase_tree *it;
1398 int cmplen;
1399 unsigned hash = pack_name_hash(name);
1400
1401 if (!num_preferred_base || check_pbase_path(hash))
1402 return;
1403
1404 cmplen = name_cmp_len(name);
1405 for (it = pbase_tree; it; it = it->next) {
1406 if (cmplen == 0) {
1407 add_object_entry(&it->pcache.oid, OBJ_TREE, NULL, 1);
1408 }
1409 else {
1410 struct tree_desc tree;
1411 init_tree_desc(&tree, it->pcache.tree_data, it->pcache.tree_size);
1412 add_pbase_object(&tree, name, cmplen, name);
1413 }
1414 }
1415 }
1416
1417 static void add_preferred_base(struct object_id *oid)
1418 {
1419 struct pbase_tree *it;
1420 void *data;
1421 unsigned long size;
1422 struct object_id tree_oid;
1423
1424 if (window <= num_preferred_base++)
1425 return;
1426
1427 data = read_object_with_reference(oid, tree_type, &size, &tree_oid);
1428 if (!data)
1429 return;
1430
1431 for (it = pbase_tree; it; it = it->next) {
1432 if (oideq(&it->pcache.oid, &tree_oid)) {
1433 free(data);
1434 return;
1435 }
1436 }
1437
1438 it = xcalloc(1, sizeof(*it));
1439 it->next = pbase_tree;
1440 pbase_tree = it;
1441
1442 oidcpy(&it->pcache.oid, &tree_oid);
1443 it->pcache.tree_data = data;
1444 it->pcache.tree_size = size;
1445 }
1446
1447 static void cleanup_preferred_base(void)
1448 {
1449 struct pbase_tree *it;
1450 unsigned i;
1451
1452 it = pbase_tree;
1453 pbase_tree = NULL;
1454 while (it) {
1455 struct pbase_tree *tmp = it;
1456 it = tmp->next;
1457 free(tmp->pcache.tree_data);
1458 free(tmp);
1459 }
1460
1461 for (i = 0; i < ARRAY_SIZE(pbase_tree_cache); i++) {
1462 if (!pbase_tree_cache[i])
1463 continue;
1464 free(pbase_tree_cache[i]->tree_data);
1465 FREE_AND_NULL(pbase_tree_cache[i]);
1466 }
1467
1468 FREE_AND_NULL(done_pbase_paths);
1469 done_pbase_paths_num = done_pbase_paths_alloc = 0;
1470 }
1471
1472 static void check_object(struct object_entry *entry)
1473 {
1474 unsigned long canonical_size;
1475
1476 if (IN_PACK(entry)) {
1477 struct packed_git *p = IN_PACK(entry);
1478 struct pack_window *w_curs = NULL;
1479 const unsigned char *base_ref = NULL;
1480 struct object_entry *base_entry;
1481 unsigned long used, used_0;
1482 unsigned long avail;
1483 off_t ofs;
1484 unsigned char *buf, c;
1485 enum object_type type;
1486 unsigned long in_pack_size;
1487
1488 buf = use_pack(p, &w_curs, entry->in_pack_offset, &avail);
1489
1490 /*
1491 * We want in_pack_type even if we do not reuse delta
1492 * since non-delta representations could still be reused.
1493 */
1494 used = unpack_object_header_buffer(buf, avail,
1495 &type,
1496 &in_pack_size);
1497 if (used == 0)
1498 goto give_up;
1499
1500 if (type < 0)
1501 BUG("invalid type %d", type);
1502 entry->in_pack_type = type;
1503
1504 /*
1505 * Determine if this is a delta and if so whether we can
1506 * reuse it or not. Otherwise let's find out as cheaply as
1507 * possible what the actual type and size for this object is.
1508 */
1509 switch (entry->in_pack_type) {
1510 default:
1511 /* Not a delta hence we've already got all we need. */
1512 oe_set_type(entry, entry->in_pack_type);
1513 SET_SIZE(entry, in_pack_size);
1514 entry->in_pack_header_size = used;
1515 if (oe_type(entry) < OBJ_COMMIT || oe_type(entry) > OBJ_BLOB)
1516 goto give_up;
1517 unuse_pack(&w_curs);
1518 return;
1519 case OBJ_REF_DELTA:
1520 if (reuse_delta && !entry->preferred_base)
1521 base_ref = use_pack(p, &w_curs,
1522 entry->in_pack_offset + used, NULL);
1523 entry->in_pack_header_size = used + the_hash_algo->rawsz;
1524 break;
1525 case OBJ_OFS_DELTA:
1526 buf = use_pack(p, &w_curs,
1527 entry->in_pack_offset + used, NULL);
1528 used_0 = 0;
1529 c = buf[used_0++];
1530 ofs = c & 127;
1531 while (c & 128) {
1532 ofs += 1;
1533 if (!ofs || MSB(ofs, 7)) {
1534 error(_("delta base offset overflow in pack for %s"),
1535 oid_to_hex(&entry->idx.oid));
1536 goto give_up;
1537 }
1538 c = buf[used_0++];
1539 ofs = (ofs << 7) + (c & 127);
1540 }
1541 ofs = entry->in_pack_offset - ofs;
1542 if (ofs <= 0 || ofs >= entry->in_pack_offset) {
1543 error(_("delta base offset out of bound for %s"),
1544 oid_to_hex(&entry->idx.oid));
1545 goto give_up;
1546 }
1547 if (reuse_delta && !entry->preferred_base) {
1548 struct revindex_entry *revidx;
1549 revidx = find_pack_revindex(p, ofs);
1550 if (!revidx)
1551 goto give_up;
1552 base_ref = nth_packed_object_sha1(p, revidx->nr);
1553 }
1554 entry->in_pack_header_size = used + used_0;
1555 break;
1556 }
1557
1558 if (base_ref && (
1559 (base_entry = packlist_find(&to_pack, base_ref, NULL)) ||
1560 (thin &&
1561 bitmap_has_sha1_in_uninteresting(bitmap_git, base_ref))) &&
1562 in_same_island(&entry->idx.oid, &base_entry->idx.oid)) {
1563 /*
1564 * If base_ref was set above that means we wish to
1565 * reuse delta data, and either we found that object in
1566 * the list of objects we want to pack, or it's one we
1567 * know the receiver has.
1568 *
1569 * Depth value does not matter - find_deltas() will
1570 * never consider reused delta as the base object to
1571 * deltify other objects against, in order to avoid
1572 * circular deltas.
1573 */
1574 oe_set_type(entry, entry->in_pack_type);
1575 SET_SIZE(entry, in_pack_size); /* delta size */
1576 SET_DELTA_SIZE(entry, in_pack_size);
1577
1578 if (base_entry) {
1579 SET_DELTA(entry, base_entry);
1580 entry->delta_sibling_idx = base_entry->delta_child_idx;
1581 SET_DELTA_CHILD(base_entry, entry);
1582 } else {
1583 SET_DELTA_EXT(entry, base_ref);
1584 }
1585
1586 unuse_pack(&w_curs);
1587 return;
1588 }
1589
1590 if (oe_type(entry)) {
1591 off_t delta_pos;
1592
1593 /*
1594 * This must be a delta and we already know what the
1595 * final object type is. Let's extract the actual
1596 * object size from the delta header.
1597 */
1598 delta_pos = entry->in_pack_offset + entry->in_pack_header_size;
1599 canonical_size = get_size_from_delta(p, &w_curs, delta_pos);
1600 if (canonical_size == 0)
1601 goto give_up;
1602 SET_SIZE(entry, canonical_size);
1603 unuse_pack(&w_curs);
1604 return;
1605 }
1606
1607 /*
1608 * No choice but to fall back to the recursive delta walk
1609 * with sha1_object_info() to find about the object type
1610 * at this point...
1611 */
1612 give_up:
1613 unuse_pack(&w_curs);
1614 }
1615
1616 oe_set_type(entry,
1617 oid_object_info(the_repository, &entry->idx.oid, &canonical_size));
1618 if (entry->type_valid) {
1619 SET_SIZE(entry, canonical_size);
1620 } else {
1621 /*
1622 * Bad object type is checked in prepare_pack(). This is
1623 * to permit a missing preferred base object to be ignored
1624 * as a preferred base. Doing so can result in a larger
1625 * pack file, but the transfer will still take place.
1626 */
1627 }
1628 }
1629
1630 static int pack_offset_sort(const void *_a, const void *_b)
1631 {
1632 const struct object_entry *a = *(struct object_entry **)_a;
1633 const struct object_entry *b = *(struct object_entry **)_b;
1634 const struct packed_git *a_in_pack = IN_PACK(a);
1635 const struct packed_git *b_in_pack = IN_PACK(b);
1636
1637 /* avoid filesystem trashing with loose objects */
1638 if (!a_in_pack && !b_in_pack)
1639 return oidcmp(&a->idx.oid, &b->idx.oid);
1640
1641 if (a_in_pack < b_in_pack)
1642 return -1;
1643 if (a_in_pack > b_in_pack)
1644 return 1;
1645 return a->in_pack_offset < b->in_pack_offset ? -1 :
1646 (a->in_pack_offset > b->in_pack_offset);
1647 }
1648
1649 /*
1650 * Drop an on-disk delta we were planning to reuse. Naively, this would
1651 * just involve blanking out the "delta" field, but we have to deal
1652 * with some extra book-keeping:
1653 *
1654 * 1. Removing ourselves from the delta_sibling linked list.
1655 *
1656 * 2. Updating our size/type to the non-delta representation. These were
1657 * either not recorded initially (size) or overwritten with the delta type
1658 * (type) when check_object() decided to reuse the delta.
1659 *
1660 * 3. Resetting our delta depth, as we are now a base object.
1661 */
1662 static void drop_reused_delta(struct object_entry *entry)
1663 {
1664 unsigned *idx = &to_pack.objects[entry->delta_idx - 1].delta_child_idx;
1665 struct object_info oi = OBJECT_INFO_INIT;
1666 enum object_type type;
1667 unsigned long size;
1668
1669 while (*idx) {
1670 struct object_entry *oe = &to_pack.objects[*idx - 1];
1671
1672 if (oe == entry)
1673 *idx = oe->delta_sibling_idx;
1674 else
1675 idx = &oe->delta_sibling_idx;
1676 }
1677 SET_DELTA(entry, NULL);
1678 entry->depth = 0;
1679
1680 oi.sizep = &size;
1681 oi.typep = &type;
1682 if (packed_object_info(the_repository, IN_PACK(entry), entry->in_pack_offset, &oi) < 0) {
1683 /*
1684 * We failed to get the info from this pack for some reason;
1685 * fall back to sha1_object_info, which may find another copy.
1686 * And if that fails, the error will be recorded in oe_type(entry)
1687 * and dealt with in prepare_pack().
1688 */
1689 oe_set_type(entry,
1690 oid_object_info(the_repository, &entry->idx.oid, &size));
1691 } else {
1692 oe_set_type(entry, type);
1693 }
1694 SET_SIZE(entry, size);
1695 }
1696
1697 /*
1698 * Follow the chain of deltas from this entry onward, throwing away any links
1699 * that cause us to hit a cycle (as determined by the DFS state flags in
1700 * the entries).
1701 *
1702 * We also detect too-long reused chains that would violate our --depth
1703 * limit.
1704 */
1705 static void break_delta_chains(struct object_entry *entry)
1706 {
1707 /*
1708 * The actual depth of each object we will write is stored as an int,
1709 * as it cannot exceed our int "depth" limit. But before we break
1710 * changes based no that limit, we may potentially go as deep as the
1711 * number of objects, which is elsewhere bounded to a uint32_t.
1712 */
1713 uint32_t total_depth;
1714 struct object_entry *cur, *next;
1715
1716 for (cur = entry, total_depth = 0;
1717 cur;
1718 cur = DELTA(cur), total_depth++) {
1719 if (cur->dfs_state == DFS_DONE) {
1720 /*
1721 * We've already seen this object and know it isn't
1722 * part of a cycle. We do need to append its depth
1723 * to our count.
1724 */
1725 total_depth += cur->depth;
1726 break;
1727 }
1728
1729 /*
1730 * We break cycles before looping, so an ACTIVE state (or any
1731 * other cruft which made its way into the state variable)
1732 * is a bug.
1733 */
1734 if (cur->dfs_state != DFS_NONE)
1735 BUG("confusing delta dfs state in first pass: %d",
1736 cur->dfs_state);
1737
1738 /*
1739 * Now we know this is the first time we've seen the object. If
1740 * it's not a delta, we're done traversing, but we'll mark it
1741 * done to save time on future traversals.
1742 */
1743 if (!DELTA(cur)) {
1744 cur->dfs_state = DFS_DONE;
1745 break;
1746 }
1747
1748 /*
1749 * Mark ourselves as active and see if the next step causes
1750 * us to cycle to another active object. It's important to do
1751 * this _before_ we loop, because it impacts where we make the
1752 * cut, and thus how our total_depth counter works.
1753 * E.g., We may see a partial loop like:
1754 *
1755 * A -> B -> C -> D -> B
1756 *
1757 * Cutting B->C breaks the cycle. But now the depth of A is
1758 * only 1, and our total_depth counter is at 3. The size of the
1759 * error is always one less than the size of the cycle we
1760 * broke. Commits C and D were "lost" from A's chain.
1761 *
1762 * If we instead cut D->B, then the depth of A is correct at 3.
1763 * We keep all commits in the chain that we examined.
1764 */
1765 cur->dfs_state = DFS_ACTIVE;
1766 if (DELTA(cur)->dfs_state == DFS_ACTIVE) {
1767 drop_reused_delta(cur);
1768 cur->dfs_state = DFS_DONE;
1769 break;
1770 }
1771 }
1772
1773 /*
1774 * And now that we've gone all the way to the bottom of the chain, we
1775 * need to clear the active flags and set the depth fields as
1776 * appropriate. Unlike the loop above, which can quit when it drops a
1777 * delta, we need to keep going to look for more depth cuts. So we need
1778 * an extra "next" pointer to keep going after we reset cur->delta.
1779 */
1780 for (cur = entry; cur; cur = next) {
1781 next = DELTA(cur);
1782
1783 /*
1784 * We should have a chain of zero or more ACTIVE states down to
1785 * a final DONE. We can quit after the DONE, because either it
1786 * has no bases, or we've already handled them in a previous
1787 * call.
1788 */
1789 if (cur->dfs_state == DFS_DONE)
1790 break;
1791 else if (cur->dfs_state != DFS_ACTIVE)
1792 BUG("confusing delta dfs state in second pass: %d",
1793 cur->dfs_state);
1794
1795 /*
1796 * If the total_depth is more than depth, then we need to snip
1797 * the chain into two or more smaller chains that don't exceed
1798 * the maximum depth. Most of the resulting chains will contain
1799 * (depth + 1) entries (i.e., depth deltas plus one base), and
1800 * the last chain (i.e., the one containing entry) will contain
1801 * whatever entries are left over, namely
1802 * (total_depth % (depth + 1)) of them.
1803 *
1804 * Since we are iterating towards decreasing depth, we need to
1805 * decrement total_depth as we go, and we need to write to the
1806 * entry what its final depth will be after all of the
1807 * snipping. Since we're snipping into chains of length (depth
1808 * + 1) entries, the final depth of an entry will be its
1809 * original depth modulo (depth + 1). Any time we encounter an
1810 * entry whose final depth is supposed to be zero, we snip it
1811 * from its delta base, thereby making it so.
1812 */
1813 cur->depth = (total_depth--) % (depth + 1);
1814 if (!cur->depth)
1815 drop_reused_delta(cur);
1816
1817 cur->dfs_state = DFS_DONE;
1818 }
1819 }
1820
1821 static void get_object_details(void)
1822 {
1823 uint32_t i;
1824 struct object_entry **sorted_by_offset;
1825
1826 if (progress)
1827 progress_state = start_progress(_("Counting objects"),
1828 to_pack.nr_objects);
1829
1830 sorted_by_offset = xcalloc(to_pack.nr_objects, sizeof(struct object_entry *));
1831 for (i = 0; i < to_pack.nr_objects; i++)
1832 sorted_by_offset[i] = to_pack.objects + i;
1833 QSORT(sorted_by_offset, to_pack.nr_objects, pack_offset_sort);
1834
1835 for (i = 0; i < to_pack.nr_objects; i++) {
1836 struct object_entry *entry = sorted_by_offset[i];
1837 check_object(entry);
1838 if (entry->type_valid &&
1839 oe_size_greater_than(&to_pack, entry, big_file_threshold))
1840 entry->no_try_delta = 1;
1841 display_progress(progress_state, i + 1);
1842 }
1843 stop_progress(&progress_state);
1844
1845 /*
1846 * This must happen in a second pass, since we rely on the delta
1847 * information for the whole list being completed.
1848 */
1849 for (i = 0; i < to_pack.nr_objects; i++)
1850 break_delta_chains(&to_pack.objects[i]);
1851
1852 free(sorted_by_offset);
1853 }
1854
1855 /*
1856 * We search for deltas in a list sorted by type, by filename hash, and then
1857 * by size, so that we see progressively smaller and smaller files.
1858 * That's because we prefer deltas to be from the bigger file
1859 * to the smaller -- deletes are potentially cheaper, but perhaps
1860 * more importantly, the bigger file is likely the more recent
1861 * one. The deepest deltas are therefore the oldest objects which are
1862 * less susceptible to be accessed often.
1863 */
1864 static int type_size_sort(const void *_a, const void *_b)
1865 {
1866 const struct object_entry *a = *(struct object_entry **)_a;
1867 const struct object_entry *b = *(struct object_entry **)_b;
1868 enum object_type a_type = oe_type(a);
1869 enum object_type b_type = oe_type(b);
1870 unsigned long a_size = SIZE(a);
1871 unsigned long b_size = SIZE(b);
1872
1873 if (a_type > b_type)
1874 return -1;
1875 if (a_type < b_type)
1876 return 1;
1877 if (a->hash > b->hash)
1878 return -1;
1879 if (a->hash < b->hash)
1880 return 1;
1881 if (a->preferred_base > b->preferred_base)
1882 return -1;
1883 if (a->preferred_base < b->preferred_base)
1884 return 1;
1885 if (use_delta_islands) {
1886 int island_cmp = island_delta_cmp(&a->idx.oid, &b->idx.oid);
1887 if (island_cmp)
1888 return island_cmp;
1889 }
1890 if (a_size > b_size)
1891 return -1;
1892 if (a_size < b_size)
1893 return 1;
1894 return a < b ? -1 : (a > b); /* newest first */
1895 }
1896
1897 struct unpacked {
1898 struct object_entry *entry;
1899 void *data;
1900 struct delta_index *index;
1901 unsigned depth;
1902 };
1903
1904 static int delta_cacheable(unsigned long src_size, unsigned long trg_size,
1905 unsigned long delta_size)
1906 {
1907 if (max_delta_cache_size && delta_cache_size + delta_size > max_delta_cache_size)
1908 return 0;
1909
1910 if (delta_size < cache_max_small_delta_size)
1911 return 1;
1912
1913 /* cache delta, if objects are large enough compared to delta size */
1914 if ((src_size >> 20) + (trg_size >> 21) > (delta_size >> 10))
1915 return 1;
1916
1917 return 0;
1918 }
1919
1920 #ifndef NO_PTHREADS
1921
1922 /* Protect access to object database */
1923 static pthread_mutex_t read_mutex;
1924 #define read_lock() pthread_mutex_lock(&read_mutex)
1925 #define read_unlock() pthread_mutex_unlock(&read_mutex)
1926
1927 /* Protect delta_cache_size */
1928 static pthread_mutex_t cache_mutex;
1929 #define cache_lock() pthread_mutex_lock(&cache_mutex)
1930 #define cache_unlock() pthread_mutex_unlock(&cache_mutex)
1931
1932 /*
1933 * Protect object list partitioning (e.g. struct thread_param) and
1934 * progress_state
1935 */
1936 static pthread_mutex_t progress_mutex;
1937 #define progress_lock() pthread_mutex_lock(&progress_mutex)
1938 #define progress_unlock() pthread_mutex_unlock(&progress_mutex)
1939
1940 /*
1941 * Access to struct object_entry is unprotected since each thread owns
1942 * a portion of the main object list. Just don't access object entries
1943 * ahead in the list because they can be stolen and would need
1944 * progress_mutex for protection.
1945 */
1946 #else
1947
1948 #define read_lock() (void)0
1949 #define read_unlock() (void)0
1950 #define cache_lock() (void)0
1951 #define cache_unlock() (void)0
1952 #define progress_lock() (void)0
1953 #define progress_unlock() (void)0
1954
1955 #endif
1956
1957 /*
1958 * Return the size of the object without doing any delta
1959 * reconstruction (so non-deltas are true object sizes, but deltas
1960 * return the size of the delta data).
1961 */
1962 unsigned long oe_get_size_slow(struct packing_data *pack,
1963 const struct object_entry *e)
1964 {
1965 struct packed_git *p;
1966 struct pack_window *w_curs;
1967 unsigned char *buf;
1968 enum object_type type;
1969 unsigned long used, avail, size;
1970
1971 if (e->type_ != OBJ_OFS_DELTA && e->type_ != OBJ_REF_DELTA) {
1972 read_lock();
1973 if (oid_object_info(the_repository, &e->idx.oid, &size) < 0)
1974 die(_("unable to get size of %s"),
1975 oid_to_hex(&e->idx.oid));
1976 read_unlock();
1977 return size;
1978 }
1979
1980 p = oe_in_pack(pack, e);
1981 if (!p)
1982 BUG("when e->type is a delta, it must belong to a pack");
1983
1984 read_lock();
1985 w_curs = NULL;
1986 buf = use_pack(p, &w_curs, e->in_pack_offset, &avail);
1987 used = unpack_object_header_buffer(buf, avail, &type, &size);
1988 if (used == 0)
1989 die(_("unable to parse object header of %s"),
1990 oid_to_hex(&e->idx.oid));
1991
1992 unuse_pack(&w_curs);
1993 read_unlock();
1994 return size;
1995 }
1996
1997 static int try_delta(struct unpacked *trg, struct unpacked *src,
1998 unsigned max_depth, unsigned long *mem_usage)
1999 {
2000 struct object_entry *trg_entry = trg->entry;
2001 struct object_entry *src_entry = src->entry;
2002 unsigned long trg_size, src_size, delta_size, sizediff, max_size, sz;
2003 unsigned ref_depth;
2004 enum object_type type;
2005 void *delta_buf;
2006
2007 /* Don't bother doing diffs between different types */
2008 if (oe_type(trg_entry) != oe_type(src_entry))
2009 return -1;
2010
2011 /*
2012 * We do not bother to try a delta that we discarded on an
2013 * earlier try, but only when reusing delta data. Note that
2014 * src_entry that is marked as the preferred_base should always
2015 * be considered, as even if we produce a suboptimal delta against
2016 * it, we will still save the transfer cost, as we already know
2017 * the other side has it and we won't send src_entry at all.
2018 */
2019 if (reuse_delta && IN_PACK(trg_entry) &&
2020 IN_PACK(trg_entry) == IN_PACK(src_entry) &&
2021 !src_entry->preferred_base &&
2022 trg_entry->in_pack_type != OBJ_REF_DELTA &&
2023 trg_entry->in_pack_type != OBJ_OFS_DELTA)
2024 return 0;
2025
2026 /* Let's not bust the allowed depth. */
2027 if (src->depth >= max_depth)
2028 return 0;
2029
2030 /* Now some size filtering heuristics. */
2031 trg_size = SIZE(trg_entry);
2032 if (!DELTA(trg_entry)) {
2033 max_size = trg_size/2 - the_hash_algo->rawsz;
2034 ref_depth = 1;
2035 } else {
2036 max_size = DELTA_SIZE(trg_entry);
2037 ref_depth = trg->depth;
2038 }
2039 max_size = (uint64_t)max_size * (max_depth - src->depth) /
2040 (max_depth - ref_depth + 1);
2041 if (max_size == 0)
2042 return 0;
2043 src_size = SIZE(src_entry);
2044 sizediff = src_size < trg_size ? trg_size - src_size : 0;
2045 if (sizediff >= max_size)
2046 return 0;
2047 if (trg_size < src_size / 32)
2048 return 0;
2049
2050 if (!in_same_island(&trg->entry->idx.oid, &src->entry->idx.oid))
2051 return 0;
2052
2053 /* Load data if not already done */
2054 if (!trg->data) {
2055 read_lock();
2056 trg->data = read_object_file(&trg_entry->idx.oid, &type, &sz);
2057 read_unlock();
2058 if (!trg->data)
2059 die(_("object %s cannot be read"),
2060 oid_to_hex(&trg_entry->idx.oid));
2061 if (sz != trg_size)
2062 die(_("object %s inconsistent object length (%lu vs %lu)"),
2063 oid_to_hex(&trg_entry->idx.oid), sz,
2064 trg_size);
2065 *mem_usage += sz;
2066 }
2067 if (!src->data) {
2068 read_lock();
2069 src->data = read_object_file(&src_entry->idx.oid, &type, &sz);
2070 read_unlock();
2071 if (!src->data) {
2072 if (src_entry->preferred_base) {
2073 static int warned = 0;
2074 if (!warned++)
2075 warning(_("object %s cannot be read"),
2076 oid_to_hex(&src_entry->idx.oid));
2077 /*
2078 * Those objects are not included in the
2079 * resulting pack. Be resilient and ignore
2080 * them if they can't be read, in case the
2081 * pack could be created nevertheless.
2082 */
2083 return 0;
2084 }
2085 die(_("object %s cannot be read"),
2086 oid_to_hex(&src_entry->idx.oid));
2087 }
2088 if (sz != src_size)
2089 die(_("object %s inconsistent object length (%lu vs %lu)"),
2090 oid_to_hex(&src_entry->idx.oid), sz,
2091 src_size);
2092 *mem_usage += sz;
2093 }
2094 if (!src->index) {
2095 src->index = create_delta_index(src->data, src_size);
2096 if (!src->index) {
2097 static int warned = 0;
2098 if (!warned++)
2099 warning(_("suboptimal pack - out of memory"));
2100 return 0;
2101 }
2102 *mem_usage += sizeof_delta_index(src->index);
2103 }
2104
2105 delta_buf = create_delta(src->index, trg->data, trg_size, &delta_size, max_size);
2106 if (!delta_buf)
2107 return 0;
2108
2109 if (DELTA(trg_entry)) {
2110 /* Prefer only shallower same-sized deltas. */
2111 if (delta_size == DELTA_SIZE(trg_entry) &&
2112 src->depth + 1 >= trg->depth) {
2113 free(delta_buf);
2114 return 0;
2115 }
2116 }
2117
2118 /*
2119 * Handle memory allocation outside of the cache
2120 * accounting lock. Compiler will optimize the strangeness
2121 * away when NO_PTHREADS is defined.
2122 */
2123 free(trg_entry->delta_data);
2124 cache_lock();
2125 if (trg_entry->delta_data) {
2126 delta_cache_size -= DELTA_SIZE(trg_entry);
2127 trg_entry->delta_data = NULL;
2128 }
2129 if (delta_cacheable(src_size, trg_size, delta_size)) {
2130 delta_cache_size += delta_size;
2131 cache_unlock();
2132 trg_entry->delta_data = xrealloc(delta_buf, delta_size);
2133 } else {
2134 cache_unlock();
2135 free(delta_buf);
2136 }
2137
2138 SET_DELTA(trg_entry, src_entry);
2139 SET_DELTA_SIZE(trg_entry, delta_size);
2140 trg->depth = src->depth + 1;
2141
2142 return 1;
2143 }
2144
2145 static unsigned int check_delta_limit(struct object_entry *me, unsigned int n)
2146 {
2147 struct object_entry *child = DELTA_CHILD(me);
2148 unsigned int m = n;
2149 while (child) {
2150 unsigned int c = check_delta_limit(child, n + 1);
2151 if (m < c)
2152 m = c;
2153 child = DELTA_SIBLING(child);
2154 }
2155 return m;
2156 }
2157
2158 static unsigned long free_unpacked(struct unpacked *n)
2159 {
2160 unsigned long freed_mem = sizeof_delta_index(n->index);
2161 free_delta_index(n->index);
2162 n->index = NULL;
2163 if (n->data) {
2164 freed_mem += SIZE(n->entry);
2165 FREE_AND_NULL(n->data);
2166 }
2167 n->entry = NULL;
2168 n->depth = 0;
2169 return freed_mem;
2170 }
2171
2172 static void find_deltas(struct object_entry **list, unsigned *list_size,
2173 int window, int depth, unsigned *processed)
2174 {
2175 uint32_t i, idx = 0, count = 0;
2176 struct unpacked *array;
2177 unsigned long mem_usage = 0;
2178
2179 array = xcalloc(window, sizeof(struct unpacked));
2180
2181 for (;;) {
2182 struct object_entry *entry;
2183 struct unpacked *n = array + idx;
2184 int j, max_depth, best_base = -1;
2185
2186 progress_lock();
2187 if (!*list_size) {
2188 progress_unlock();
2189 break;
2190 }
2191 entry = *list++;
2192 (*list_size)--;
2193 if (!entry->preferred_base) {
2194 (*processed)++;
2195 display_progress(progress_state, *processed);
2196 }
2197 progress_unlock();
2198
2199 mem_usage -= free_unpacked(n);
2200 n->entry = entry;
2201
2202 while (window_memory_limit &&
2203 mem_usage > window_memory_limit &&
2204 count > 1) {
2205 uint32_t tail = (idx + window - count) % window;
2206 mem_usage -= free_unpacked(array + tail);
2207 count--;
2208 }
2209
2210 /* We do not compute delta to *create* objects we are not
2211 * going to pack.
2212 */
2213 if (entry->preferred_base)
2214 goto next;
2215
2216 /*
2217 * If the current object is at pack edge, take the depth the
2218 * objects that depend on the current object into account
2219 * otherwise they would become too deep.
2220 */
2221 max_depth = depth;
2222 if (DELTA_CHILD(entry)) {
2223 max_depth -= check_delta_limit(entry, 0);
2224 if (max_depth <= 0)
2225 goto next;
2226 }
2227
2228 j = window;
2229 while (--j > 0) {
2230 int ret;
2231 uint32_t other_idx = idx + j;
2232 struct unpacked *m;
2233 if (other_idx >= window)
2234 other_idx -= window;
2235 m = array + other_idx;
2236 if (!m->entry)
2237 break;
2238 ret = try_delta(n, m, max_depth, &mem_usage);
2239 if (ret < 0)
2240 break;
2241 else if (ret > 0)
2242 best_base = other_idx;
2243 }
2244
2245 /*
2246 * If we decided to cache the delta data, then it is best
2247 * to compress it right away. First because we have to do
2248 * it anyway, and doing it here while we're threaded will
2249 * save a lot of time in the non threaded write phase,
2250 * as well as allow for caching more deltas within
2251 * the same cache size limit.
2252 * ...
2253 * But only if not writing to stdout, since in that case
2254 * the network is most likely throttling writes anyway,
2255 * and therefore it is best to go to the write phase ASAP
2256 * instead, as we can afford spending more time compressing
2257 * between writes at that moment.
2258 */
2259 if (entry->delta_data && !pack_to_stdout) {
2260 unsigned long size;
2261
2262 size = do_compress(&entry->delta_data, DELTA_SIZE(entry));
2263 if (size < (1U << OE_Z_DELTA_BITS)) {
2264 entry->z_delta_size = size;
2265 cache_lock();
2266 delta_cache_size -= DELTA_SIZE(entry);
2267 delta_cache_size += entry->z_delta_size;
2268 cache_unlock();
2269 } else {
2270 FREE_AND_NULL(entry->delta_data);
2271 entry->z_delta_size = 0;
2272 }
2273 }
2274
2275 /* if we made n a delta, and if n is already at max
2276 * depth, leaving it in the window is pointless. we
2277 * should evict it first.
2278 */
2279 if (DELTA(entry) && max_depth <= n->depth)
2280 continue;
2281
2282 /*
2283 * Move the best delta base up in the window, after the
2284 * currently deltified object, to keep it longer. It will
2285 * be the first base object to be attempted next.
2286 */
2287 if (DELTA(entry)) {
2288 struct unpacked swap = array[best_base];
2289 int dist = (window + idx - best_base) % window;
2290 int dst = best_base;
2291 while (dist--) {
2292 int src = (dst + 1) % window;
2293 array[dst] = array[src];
2294 dst = src;
2295 }
2296 array[dst] = swap;
2297 }
2298
2299 next:
2300 idx++;
2301 if (count + 1 < window)
2302 count++;
2303 if (idx >= window)
2304 idx = 0;
2305 }
2306
2307 for (i = 0; i < window; ++i) {
2308 free_delta_index(array[i].index);
2309 free(array[i].data);
2310 }
2311 free(array);
2312 }
2313
2314 #ifndef NO_PTHREADS
2315
2316 static void try_to_free_from_threads(size_t size)
2317 {
2318 read_lock();
2319 release_pack_memory(size);
2320 read_unlock();
2321 }
2322
2323 static try_to_free_t old_try_to_free_routine;
2324
2325 /*
2326 * The main object list is split into smaller lists, each is handed to
2327 * one worker.
2328 *
2329 * The main thread waits on the condition that (at least) one of the workers
2330 * has stopped working (which is indicated in the .working member of
2331 * struct thread_params).
2332 *
2333 * When a work thread has completed its work, it sets .working to 0 and
2334 * signals the main thread and waits on the condition that .data_ready
2335 * becomes 1.
2336 *
2337 * The main thread steals half of the work from the worker that has
2338 * most work left to hand it to the idle worker.
2339 */
2340
2341 struct thread_params {
2342 pthread_t thread;
2343 struct object_entry **list;
2344 unsigned list_size;
2345 unsigned remaining;
2346 int window;
2347 int depth;
2348 int working;
2349 int data_ready;
2350 pthread_mutex_t mutex;
2351 pthread_cond_t cond;
2352 unsigned *processed;
2353 };
2354
2355 static pthread_cond_t progress_cond;
2356
2357 /*
2358 * Mutex and conditional variable can't be statically-initialized on Windows.
2359 */
2360 static void init_threaded_search(void)
2361 {
2362 init_recursive_mutex(&read_mutex);
2363 pthread_mutex_init(&cache_mutex, NULL);
2364 pthread_mutex_init(&progress_mutex, NULL);
2365 pthread_cond_init(&progress_cond, NULL);
2366 pthread_mutex_init(&to_pack.lock, NULL);
2367 old_try_to_free_routine = set_try_to_free_routine(try_to_free_from_threads);
2368 }
2369
2370 static void cleanup_threaded_search(void)
2371 {
2372 set_try_to_free_routine(old_try_to_free_routine);
2373 pthread_cond_destroy(&progress_cond);
2374 pthread_mutex_destroy(&read_mutex);
2375 pthread_mutex_destroy(&cache_mutex);
2376 pthread_mutex_destroy(&progress_mutex);
2377 }
2378
2379 static void *threaded_find_deltas(void *arg)
2380 {
2381 struct thread_params *me = arg;
2382
2383 progress_lock();
2384 while (me->remaining) {
2385 progress_unlock();
2386
2387 find_deltas(me->list, &me->remaining,
2388 me->window, me->depth, me->processed);
2389
2390 progress_lock();
2391 me->working = 0;
2392 pthread_cond_signal(&progress_cond);
2393 progress_unlock();
2394
2395 /*
2396 * We must not set ->data_ready before we wait on the
2397 * condition because the main thread may have set it to 1
2398 * before we get here. In order to be sure that new
2399 * work is available if we see 1 in ->data_ready, it
2400 * was initialized to 0 before this thread was spawned
2401 * and we reset it to 0 right away.
2402 */
2403 pthread_mutex_lock(&me->mutex);
2404 while (!me->data_ready)
2405 pthread_cond_wait(&me->cond, &me->mutex);
2406 me->data_ready = 0;
2407 pthread_mutex_unlock(&me->mutex);
2408
2409 progress_lock();
2410 }
2411 progress_unlock();
2412 /* leave ->working 1 so that this doesn't get more work assigned */
2413 return NULL;
2414 }
2415
2416 static void ll_find_deltas(struct object_entry **list, unsigned list_size,
2417 int window, int depth, unsigned *processed)
2418 {
2419 struct thread_params *p;
2420 int i, ret, active_threads = 0;
2421
2422 init_threaded_search();
2423
2424 if (delta_search_threads <= 1) {
2425 find_deltas(list, &list_size, window, depth, processed);
2426 cleanup_threaded_search();
2427 return;
2428 }
2429 if (progress > pack_to_stdout)
2430 fprintf_ln(stderr, _("Delta compression using up to %d threads"),
2431 delta_search_threads);
2432 p = xcalloc(delta_search_threads, sizeof(*p));
2433
2434 /* Partition the work amongst work threads. */
2435 for (i = 0; i < delta_search_threads; i++) {
2436 unsigned sub_size = list_size / (delta_search_threads - i);
2437
2438 /* don't use too small segments or no deltas will be found */
2439 if (sub_size < 2*window && i+1 < delta_search_threads)
2440 sub_size = 0;
2441
2442 p[i].window = window;
2443 p[i].depth = depth;
2444 p[i].processed = processed;
2445 p[i].working = 1;
2446 p[i].data_ready = 0;
2447
2448 /* try to split chunks on "path" boundaries */
2449 while (sub_size && sub_size < list_size &&
2450 list[sub_size]->hash &&
2451 list[sub_size]->hash == list[sub_size-1]->hash)
2452 sub_size++;
2453
2454 p[i].list = list;
2455 p[i].list_size = sub_size;
2456 p[i].remaining = sub_size;
2457
2458 list += sub_size;
2459 list_size -= sub_size;
2460 }
2461
2462 /* Start work threads. */
2463 for (i = 0; i < delta_search_threads; i++) {
2464 if (!p[i].list_size)
2465 continue;
2466 pthread_mutex_init(&p[i].mutex, NULL);
2467 pthread_cond_init(&p[i].cond, NULL);
2468 ret = pthread_create(&p[i].thread, NULL,
2469 threaded_find_deltas, &p[i]);
2470 if (ret)
2471 die(_("unable to create thread: %s"), strerror(ret));
2472 active_threads++;
2473 }
2474
2475 /*
2476 * Now let's wait for work completion. Each time a thread is done
2477 * with its work, we steal half of the remaining work from the
2478 * thread with the largest number of unprocessed objects and give
2479 * it to that newly idle thread. This ensure good load balancing
2480 * until the remaining object list segments are simply too short
2481 * to be worth splitting anymore.
2482 */
2483 while (active_threads) {
2484 struct thread_params *target = NULL;
2485 struct thread_params *victim = NULL;
2486 unsigned sub_size = 0;
2487
2488 progress_lock();
2489 for (;;) {
2490 for (i = 0; !target && i < delta_search_threads; i++)
2491 if (!p[i].working)
2492 target = &p[i];
2493 if (target)
2494 break;
2495 pthread_cond_wait(&progress_cond, &progress_mutex);
2496 }
2497
2498 for (i = 0; i < delta_search_threads; i++)
2499 if (p[i].remaining > 2*window &&
2500 (!victim || victim->remaining < p[i].remaining))
2501 victim = &p[i];
2502 if (victim) {
2503 sub_size = victim->remaining / 2;
2504 list = victim->list + victim->list_size - sub_size;
2505 while (sub_size && list[0]->hash &&
2506 list[0]->hash == list[-1]->hash) {
2507 list++;
2508 sub_size--;
2509 }
2510 if (!sub_size) {
2511 /*
2512 * It is possible for some "paths" to have
2513 * so many objects that no hash boundary
2514 * might be found. Let's just steal the
2515 * exact half in that case.
2516 */
2517 sub_size = victim->remaining / 2;
2518 list -= sub_size;
2519 }
2520 target->list = list;
2521 victim->list_size -= sub_size;
2522 victim->remaining -= sub_size;
2523 }
2524 target->list_size = sub_size;
2525 target->remaining = sub_size;
2526 target->working = 1;
2527 progress_unlock();
2528
2529 pthread_mutex_lock(&target->mutex);
2530 target->data_ready = 1;
2531 pthread_cond_signal(&target->cond);
2532 pthread_mutex_unlock(&target->mutex);
2533
2534 if (!sub_size) {
2535 pthread_join(target->thread, NULL);
2536 pthread_cond_destroy(&target->cond);
2537 pthread_mutex_destroy(&target->mutex);
2538 active_threads--;
2539 }
2540 }
2541 cleanup_threaded_search();
2542 free(p);
2543 }
2544
2545 #else
2546 #define ll_find_deltas(l, s, w, d, p) find_deltas(l, &s, w, d, p)
2547 #endif
2548
2549 static void add_tag_chain(const struct object_id *oid)
2550 {
2551 struct tag *tag;
2552
2553 /*
2554 * We catch duplicates already in add_object_entry(), but we'd
2555 * prefer to do this extra check to avoid having to parse the
2556 * tag at all if we already know that it's being packed (e.g., if
2557 * it was included via bitmaps, we would not have parsed it
2558 * previously).
2559 */
2560 if (packlist_find(&to_pack, oid->hash, NULL))
2561 return;
2562
2563 tag = lookup_tag(the_repository, oid);
2564 while (1) {
2565 if (!tag || parse_tag(tag) || !tag->tagged)
2566 die(_("unable to pack objects reachable from tag %s"),
2567 oid_to_hex(oid));
2568
2569 add_object_entry(&tag->object.oid, OBJ_TAG, NULL, 0);
2570
2571 if (tag->tagged->type != OBJ_TAG)
2572 return;
2573
2574 tag = (struct tag *)tag->tagged;
2575 }
2576 }
2577
2578 static int add_ref_tag(const char *path, const struct object_id *oid, int flag, void *cb_data)
2579 {
2580 struct object_id peeled;
2581
2582 if (starts_with(path, "refs/tags/") && /* is a tag? */
2583 !peel_ref(path, &peeled) && /* peelable? */
2584 packlist_find(&to_pack, peeled.hash, NULL)) /* object packed? */
2585 add_tag_chain(oid);
2586 return 0;
2587 }
2588
2589 static void prepare_pack(int window, int depth)
2590 {
2591 struct object_entry **delta_list;
2592 uint32_t i, nr_deltas;
2593 unsigned n;
2594
2595 if (use_delta_islands)
2596 resolve_tree_islands(progress, &to_pack);
2597
2598 get_object_details();
2599
2600 /*
2601 * If we're locally repacking then we need to be doubly careful
2602 * from now on in order to make sure no stealth corruption gets
2603 * propagated to the new pack. Clients receiving streamed packs
2604 * should validate everything they get anyway so no need to incur
2605 * the additional cost here in that case.
2606 */
2607 if (!pack_to_stdout)
2608 do_check_packed_object_crc = 1;
2609
2610 if (!to_pack.nr_objects || !window || !depth)
2611 return;
2612
2613 ALLOC_ARRAY(delta_list, to_pack.nr_objects);
2614 nr_deltas = n = 0;
2615
2616 for (i = 0; i < to_pack.nr_objects; i++) {
2617 struct object_entry *entry = to_pack.objects + i;
2618
2619 if (DELTA(entry))
2620 /* This happens if we decided to reuse existing
2621 * delta from a pack. "reuse_delta &&" is implied.
2622 */
2623 continue;
2624
2625 if (!entry->type_valid ||
2626 oe_size_less_than(&to_pack, entry, 50))
2627 continue;
2628
2629 if (entry->no_try_delta)
2630 continue;
2631
2632 if (!entry->preferred_base) {
2633 nr_deltas++;
2634 if (oe_type(entry) < 0)
2635 die(_("unable to get type of object %s"),
2636 oid_to_hex(&entry->idx.oid));
2637 } else {
2638 if (oe_type(entry) < 0) {
2639 /*
2640 * This object is not found, but we
2641 * don't have to include it anyway.
2642 */
2643 continue;
2644 }
2645 }
2646
2647 delta_list[n++] = entry;
2648 }
2649
2650 if (nr_deltas && n > 1) {
2651 unsigned nr_done = 0;
2652 if (progress)
2653 progress_state = start_progress(_("Compressing objects"),
2654 nr_deltas);
2655 QSORT(delta_list, n, type_size_sort);
2656 ll_find_deltas(delta_list, n, window+1, depth, &nr_done);
2657 stop_progress(&progress_state);
2658 if (nr_done != nr_deltas)
2659 die(_("inconsistency with delta count"));
2660 }
2661 free(delta_list);
2662 }
2663
2664 static int git_pack_config(const char *k, const char *v, void *cb)
2665 {
2666 if (!strcmp(k, "pack.window")) {
2667 window = git_config_int(k, v);
2668 return 0;
2669 }
2670 if (!strcmp(k, "pack.windowmemory")) {
2671 window_memory_limit = git_config_ulong(k, v);
2672 return 0;
2673 }
2674 if (!strcmp(k, "pack.depth")) {
2675 depth = git_config_int(k, v);
2676 return 0;
2677 }
2678 if (!strcmp(k, "pack.deltacachesize")) {
2679 max_delta_cache_size = git_config_int(k, v);
2680 return 0;
2681 }
2682 if (!strcmp(k, "pack.deltacachelimit")) {
2683 cache_max_small_delta_size = git_config_int(k, v);
2684 return 0;
2685 }
2686 if (!strcmp(k, "pack.writebitmaphashcache")) {
2687 if (git_config_bool(k, v))
2688 write_bitmap_options |= BITMAP_OPT_HASH_CACHE;
2689 else
2690 write_bitmap_options &= ~BITMAP_OPT_HASH_CACHE;
2691 }
2692 if (!strcmp(k, "pack.usebitmaps")) {
2693 use_bitmap_index_default = git_config_bool(k, v);
2694 return 0;
2695 }
2696 if (!strcmp(k, "pack.threads")) {
2697 delta_search_threads = git_config_int(k, v);
2698 if (delta_search_threads < 0)
2699 die(_("invalid number of threads specified (%d)"),
2700 delta_search_threads);
2701 #ifdef NO_PTHREADS
2702 if (delta_search_threads != 1) {
2703 warning(_("no threads support, ignoring %s"), k);
2704 delta_search_threads = 0;
2705 }
2706 #endif
2707 return 0;
2708 }
2709 if (!strcmp(k, "pack.indexversion")) {
2710 pack_idx_opts.version = git_config_int(k, v);
2711 if (pack_idx_opts.version > 2)
2712 die(_("bad pack.indexversion=%"PRIu32),
2713 pack_idx_opts.version);
2714 return 0;
2715 }
2716 return git_default_config(k, v, cb);
2717 }
2718
2719 static void read_object_list_from_stdin(void)
2720 {
2721 char line[GIT_MAX_HEXSZ + 1 + PATH_MAX + 2];
2722 struct object_id oid;
2723 const char *p;
2724
2725 for (;;) {
2726 if (!fgets(line, sizeof(line), stdin)) {
2727 if (feof(stdin))
2728 break;
2729 if (!ferror(stdin))
2730 die("BUG: fgets returned NULL, not EOF, not error!");
2731 if (errno != EINTR)
2732 die_errno("fgets");
2733 clearerr(stdin);
2734 continue;
2735 }
2736 if (line[0] == '-') {
2737 if (get_oid_hex(line+1, &oid))
2738 die(_("expected edge object ID, got garbage:\n %s"),
2739 line);
2740 add_preferred_base(&oid);
2741 continue;
2742 }
2743 if (parse_oid_hex(line, &oid, &p))
2744 die(_("expected object ID, got garbage:\n %s"), line);
2745
2746 add_preferred_base_object(p + 1);
2747 add_object_entry(&oid, OBJ_NONE, p + 1, 0);
2748 }
2749 }
2750
2751 /* Remember to update object flag allocation in object.h */
2752 #define OBJECT_ADDED (1u<<20)
2753
2754 static void show_commit(struct commit *commit, void *data)
2755 {
2756 add_object_entry(&commit->object.oid, OBJ_COMMIT, NULL, 0);
2757 commit->object.flags |= OBJECT_ADDED;
2758
2759 if (write_bitmap_index)
2760 index_commit_for_bitmap(commit);
2761
2762 if (use_delta_islands)
2763 propagate_island_marks(commit);
2764 }
2765
2766 static void show_object(struct object *obj, const char *name, void *data)
2767 {
2768 add_preferred_base_object(name);
2769 add_object_entry(&obj->oid, obj->type, name, 0);
2770 obj->flags |= OBJECT_ADDED;
2771
2772 if (use_delta_islands) {
2773 const char *p;
2774 unsigned depth = 0;
2775 struct object_entry *ent;
2776
2777 for (p = strchr(name, '/'); p; p = strchr(p + 1, '/'))
2778 depth++;
2779
2780 ent = packlist_find(&to_pack, obj->oid.hash, NULL);
2781 if (ent && depth > oe_tree_depth(&to_pack, ent))
2782 oe_set_tree_depth(&to_pack, ent, depth);
2783 }
2784 }
2785
2786 static void show_object__ma_allow_any(struct object *obj, const char *name, void *data)
2787 {
2788 assert(arg_missing_action == MA_ALLOW_ANY);
2789
2790 /*
2791 * Quietly ignore ALL missing objects. This avoids problems with
2792 * staging them now and getting an odd error later.
2793 */
2794 if (!has_object_file(&obj->oid))
2795 return;
2796
2797 show_object(obj, name, data);
2798 }
2799
2800 static void show_object__ma_allow_promisor(struct object *obj, const char *name, void *data)
2801 {
2802 assert(arg_missing_action == MA_ALLOW_PROMISOR);
2803
2804 /*
2805 * Quietly ignore EXPECTED missing objects. This avoids problems with
2806 * staging them now and getting an odd error later.
2807 */
2808 if (!has_object_file(&obj->oid) && is_promisor_object(&obj->oid))
2809 return;
2810
2811 show_object(obj, name, data);
2812 }
2813
2814 static int option_parse_missing_action(const struct option *opt,
2815 const char *arg, int unset)
2816 {
2817 assert(arg);
2818 assert(!unset);
2819
2820 if (!strcmp(arg, "error")) {
2821 arg_missing_action = MA_ERROR;
2822 fn_show_object = show_object;
2823 return 0;
2824 }
2825
2826 if (!strcmp(arg, "allow-any")) {
2827 arg_missing_action = MA_ALLOW_ANY;
2828 fetch_if_missing = 0;
2829 fn_show_object = show_object__ma_allow_any;
2830 return 0;
2831 }
2832
2833 if (!strcmp(arg, "allow-promisor")) {
2834 arg_missing_action = MA_ALLOW_PROMISOR;
2835 fetch_if_missing = 0;
2836 fn_show_object = show_object__ma_allow_promisor;
2837 return 0;
2838 }
2839
2840 die(_("invalid value for --missing"));
2841 return 0;
2842 }
2843
2844 static void show_edge(struct commit *commit)
2845 {
2846 add_preferred_base(&commit->object.oid);
2847 }
2848
2849 struct in_pack_object {
2850 off_t offset;
2851 struct object *object;
2852 };
2853
2854 struct in_pack {
2855 unsigned int alloc;
2856 unsigned int nr;
2857 struct in_pack_object *array;
2858 };
2859
2860 static void mark_in_pack_object(struct object *object, struct packed_git *p, struct in_pack *in_pack)
2861 {
2862 in_pack->array[in_pack->nr].offset = find_pack_entry_one(object->oid.hash, p);
2863 in_pack->array[in_pack->nr].object = object;
2864 in_pack->nr++;
2865 }
2866
2867 /*
2868 * Compare the objects in the offset order, in order to emulate the
2869 * "git rev-list --objects" output that produced the pack originally.
2870 */
2871 static int ofscmp(const void *a_, const void *b_)
2872 {
2873 struct in_pack_object *a = (struct in_pack_object *)a_;
2874 struct in_pack_object *b = (struct in_pack_object *)b_;
2875
2876 if (a->offset < b->offset)
2877 return -1;
2878 else if (a->offset > b->offset)
2879 return 1;
2880 else
2881 return oidcmp(&a->object->oid, &b->object->oid);
2882 }
2883
2884 static void add_objects_in_unpacked_packs(struct rev_info *revs)
2885 {
2886 struct packed_git *p;
2887 struct in_pack in_pack;
2888 uint32_t i;
2889
2890 memset(&in_pack, 0, sizeof(in_pack));
2891
2892 for (p = get_all_packs(the_repository); p; p = p->next) {
2893 struct object_id oid;
2894 struct object *o;
2895
2896 if (!p->pack_local || p->pack_keep || p->pack_keep_in_core)
2897 continue;
2898 if (open_pack_index(p))
2899 die(_("cannot open pack index"));
2900
2901 ALLOC_GROW(in_pack.array,
2902 in_pack.nr + p->num_objects,
2903 in_pack.alloc);
2904
2905 for (i = 0; i < p->num_objects; i++) {
2906 nth_packed_object_oid(&oid, p, i);
2907 o = lookup_unknown_object(oid.hash);
2908 if (!(o->flags & OBJECT_ADDED))
2909 mark_in_pack_object(o, p, &in_pack);
2910 o->flags |= OBJECT_ADDED;
2911 }
2912 }
2913
2914 if (in_pack.nr) {
2915 QSORT(in_pack.array, in_pack.nr, ofscmp);
2916 for (i = 0; i < in_pack.nr; i++) {
2917 struct object *o = in_pack.array[i].object;
2918 add_object_entry(&o->oid, o->type, "", 0);
2919 }
2920 }
2921 free(in_pack.array);
2922 }
2923
2924 static int add_loose_object(const struct object_id *oid, const char *path,
2925 void *data)
2926 {
2927 enum object_type type = oid_object_info(the_repository, oid, NULL);
2928
2929 if (type < 0) {
2930 warning(_("loose object at %s could not be examined"), path);
2931 return 0;
2932 }
2933
2934 add_object_entry(oid, type, "", 0);
2935 return 0;
2936 }
2937
2938 /*
2939 * We actually don't even have to worry about reachability here.
2940 * add_object_entry will weed out duplicates, so we just add every
2941 * loose object we find.
2942 */
2943 static void add_unreachable_loose_objects(void)
2944 {
2945 for_each_loose_file_in_objdir(get_object_directory(),
2946 add_loose_object,
2947 NULL, NULL, NULL);
2948 }
2949
2950 static int has_sha1_pack_kept_or_nonlocal(const struct object_id *oid)
2951 {
2952 static struct packed_git *last_found = (void *)1;
2953 struct packed_git *p;
2954
2955 p = (last_found != (void *)1) ? last_found :
2956 get_all_packs(the_repository);
2957
2958 while (p) {
2959 if ((!p->pack_local || p->pack_keep ||
2960 p->pack_keep_in_core) &&
2961 find_pack_entry_one(oid->hash, p)) {
2962 last_found = p;
2963 return 1;
2964 }
2965 if (p == last_found)
2966 p = get_all_packs(the_repository);
2967 else
2968 p = p->next;
2969 if (p == last_found)
2970 p = p->next;
2971 }
2972 return 0;
2973 }
2974
2975 /*
2976 * Store a list of sha1s that are should not be discarded
2977 * because they are either written too recently, or are
2978 * reachable from another object that was.
2979 *
2980 * This is filled by get_object_list.
2981 */
2982 static struct oid_array recent_objects;
2983
2984 static int loosened_object_can_be_discarded(const struct object_id *oid,
2985 timestamp_t mtime)
2986 {
2987 if (!unpack_unreachable_expiration)
2988 return 0;
2989 if (mtime > unpack_unreachable_expiration)
2990 return 0;
2991 if (oid_array_lookup(&recent_objects, oid) >= 0)
2992 return 0;
2993 return 1;
2994 }
2995
2996 static void loosen_unused_packed_objects(struct rev_info *revs)
2997 {
2998 struct packed_git *p;
2999 uint32_t i;
3000 struct object_id oid;
3001
3002 for (p = get_all_packs(the_repository); p; p = p->next) {
3003 if (!p->pack_local || p->pack_keep || p->pack_keep_in_core)
3004 continue;
3005
3006 if (open_pack_index(p))
3007 die(_("cannot open pack index"));
3008
3009 for (i = 0; i < p->num_objects; i++) {
3010 nth_packed_object_oid(&oid, p, i);
3011 if (!packlist_find(&to_pack, oid.hash, NULL) &&
3012 !has_sha1_pack_kept_or_nonlocal(&oid) &&
3013 !loosened_object_can_be_discarded(&oid, p->mtime))
3014 if (force_object_loose(&oid, p->mtime))
3015 die(_("unable to force loose object"));
3016 }
3017 }
3018 }
3019
3020 /*
3021 * This tracks any options which pack-reuse code expects to be on, or which a
3022 * reader of the pack might not understand, and which would therefore prevent
3023 * blind reuse of what we have on disk.
3024 */
3025 static int pack_options_allow_reuse(void)
3026 {
3027 return pack_to_stdout &&
3028 allow_ofs_delta &&
3029 !ignore_packed_keep_on_disk &&
3030 !ignore_packed_keep_in_core &&
3031 (!local || !have_non_local_packs) &&
3032 !incremental;
3033 }
3034
3035 static int get_object_list_from_bitmap(struct rev_info *revs)
3036 {
3037 if (!(bitmap_git = prepare_bitmap_walk(revs)))
3038 return -1;
3039
3040 if (pack_options_allow_reuse() &&
3041 !reuse_partial_packfile_from_bitmap(
3042 bitmap_git,
3043 &reuse_packfile,
3044 &reuse_packfile_objects,
3045 &reuse_packfile_offset)) {
3046 assert(reuse_packfile_objects);
3047 nr_result += reuse_packfile_objects;
3048 display_progress(progress_state, nr_result);
3049 }
3050
3051 traverse_bitmap_commit_list(bitmap_git, &add_object_entry_from_bitmap);
3052 return 0;
3053 }
3054
3055 static void record_recent_object(struct object *obj,
3056 const char *name,
3057 void *data)
3058 {
3059 oid_array_append(&recent_objects, &obj->oid);
3060 }
3061
3062 static void record_recent_commit(struct commit *commit, void *data)
3063 {
3064 oid_array_append(&recent_objects, &commit->object.oid);
3065 }
3066
3067 static void get_object_list(int ac, const char **av)
3068 {
3069 struct rev_info revs;
3070 char line[1000];
3071 int flags = 0;
3072
3073 init_revisions(&revs, NULL);
3074 save_commit_buffer = 0;
3075 setup_revisions(ac, av, &revs, NULL);
3076
3077 /* make sure shallows are read */
3078 is_repository_shallow(the_repository);
3079
3080 while (fgets(line, sizeof(line), stdin) != NULL) {
3081 int len = strlen(line);
3082 if (len && line[len - 1] == '\n')
3083 line[--len] = 0;
3084 if (!len)
3085 break;
3086 if (*line == '-') {
3087 if (!strcmp(line, "--not")) {
3088 flags ^= UNINTERESTING;
3089 write_bitmap_index = 0;
3090 continue;
3091 }
3092 if (starts_with(line, "--shallow ")) {
3093 struct object_id oid;
3094 if (get_oid_hex(line + 10, &oid))
3095 die("not an SHA-1 '%s'", line + 10);
3096 register_shallow(the_repository, &oid);
3097 use_bitmap_index = 0;
3098 continue;
3099 }
3100 die(_("not a rev '%s'"), line);
3101 }
3102 if (handle_revision_arg(line, &revs, flags, REVARG_CANNOT_BE_FILENAME))
3103 die(_("bad revision '%s'"), line);
3104 }
3105
3106 if (use_bitmap_index && !get_object_list_from_bitmap(&revs))
3107 return;
3108
3109 if (use_delta_islands)
3110 load_delta_islands();
3111
3112 if (prepare_revision_walk(&revs))
3113 die(_("revision walk setup failed"));
3114 mark_edges_uninteresting(&revs, show_edge);
3115
3116 if (!fn_show_object)
3117 fn_show_object = show_object;
3118 traverse_commit_list_filtered(&filter_options, &revs,
3119 show_commit, fn_show_object, NULL,
3120 NULL);
3121
3122 if (unpack_unreachable_expiration) {
3123 revs.ignore_missing_links = 1;
3124 if (add_unseen_recent_objects_to_traversal(&revs,
3125 unpack_unreachable_expiration))
3126 die(_("unable to add recent objects"));
3127 if (prepare_revision_walk(&revs))
3128 die(_("revision walk setup failed"));
3129 traverse_commit_list(&revs, record_recent_commit,
3130 record_recent_object, NULL);
3131 }
3132
3133 if (keep_unreachable)
3134 add_objects_in_unpacked_packs(&revs);
3135 if (pack_loose_unreachable)
3136 add_unreachable_loose_objects();
3137 if (unpack_unreachable)
3138 loosen_unused_packed_objects(&revs);
3139
3140 oid_array_clear(&recent_objects);
3141 }
3142
3143 static void add_extra_kept_packs(const struct string_list *names)
3144 {
3145 struct packed_git *p;
3146
3147 if (!names->nr)
3148 return;
3149
3150 for (p = get_all_packs(the_repository); p; p = p->next) {
3151 const char *name = basename(p->pack_name);
3152 int i;
3153
3154 if (!p->pack_local)
3155 continue;
3156
3157 for (i = 0; i < names->nr; i++)
3158 if (!fspathcmp(name, names->items[i].string))
3159 break;
3160
3161 if (i < names->nr) {
3162 p->pack_keep_in_core = 1;
3163 ignore_packed_keep_in_core = 1;
3164 continue;
3165 }
3166 }
3167 }
3168
3169 static int option_parse_index_version(const struct option *opt,
3170 const char *arg, int unset)
3171 {
3172 char *c;
3173 const char *val = arg;
3174 pack_idx_opts.version = strtoul(val, &c, 10);
3175 if (pack_idx_opts.version > 2)
3176 die(_("unsupported index version %s"), val);
3177 if (*c == ',' && c[1])
3178 pack_idx_opts.off32_limit = strtoul(c+1, &c, 0);
3179 if (*c || pack_idx_opts.off32_limit & 0x80000000)
3180 die(_("bad index version '%s'"), val);
3181 return 0;
3182 }
3183
3184 static int option_parse_unpack_unreachable(const struct option *opt,
3185 const char *arg, int unset)
3186 {
3187 if (unset) {
3188 unpack_unreachable = 0;
3189 unpack_unreachable_expiration = 0;
3190 }
3191 else {
3192 unpack_unreachable = 1;
3193 if (arg)
3194 unpack_unreachable_expiration = approxidate(arg);
3195 }
3196 return 0;
3197 }
3198
3199 int cmd_pack_objects(int argc, const char **argv, const char *prefix)
3200 {
3201 int use_internal_rev_list = 0;
3202 int shallow = 0;
3203 int all_progress_implied = 0;
3204 struct argv_array rp = ARGV_ARRAY_INIT;
3205 int rev_list_unpacked = 0, rev_list_all = 0, rev_list_reflog = 0;
3206 int rev_list_index = 0;
3207 struct string_list keep_pack_list = STRING_LIST_INIT_NODUP;
3208 struct option pack_objects_options[] = {
3209 OPT_SET_INT('q', "quiet", &progress,
3210 N_("do not show progress meter"), 0),
3211 OPT_SET_INT(0, "progress", &progress,
3212 N_("show progress meter"), 1),
3213 OPT_SET_INT(0, "all-progress", &progress,
3214 N_("show progress meter during object writing phase"), 2),
3215 OPT_BOOL(0, "all-progress-implied",
3216 &all_progress_implied,
3217 N_("similar to --all-progress when progress meter is shown")),
3218 { OPTION_CALLBACK, 0, "index-version", NULL, N_("<version>[,<offset>]"),
3219 N_("write the pack index file in the specified idx format version"),
3220 0, option_parse_index_version },
3221 OPT_MAGNITUDE(0, "max-pack-size", &pack_size_limit,
3222 N_("maximum size of each output pack file")),
3223 OPT_BOOL(0, "local", &local,
3224 N_("ignore borrowed objects from alternate object store")),
3225 OPT_BOOL(0, "incremental", &incremental,
3226 N_("ignore packed objects")),
3227 OPT_INTEGER(0, "window", &window,
3228 N_("limit pack window by objects")),
3229 OPT_MAGNITUDE(0, "window-memory", &window_memory_limit,
3230 N_("limit pack window by memory in addition to object limit")),
3231 OPT_INTEGER(0, "depth", &depth,
3232 N_("maximum length of delta chain allowed in the resulting pack")),
3233 OPT_BOOL(0, "reuse-delta", &reuse_delta,
3234 N_("reuse existing deltas")),
3235 OPT_BOOL(0, "reuse-object", &reuse_object,
3236 N_("reuse existing objects")),
3237 OPT_BOOL(0, "delta-base-offset", &allow_ofs_delta,
3238 N_("use OFS_DELTA objects")),
3239 OPT_INTEGER(0, "threads", &delta_search_threads,
3240 N_("use threads when searching for best delta matches")),
3241 OPT_BOOL(0, "non-empty", &non_empty,
3242 N_("do not create an empty pack output")),
3243 OPT_BOOL(0, "revs", &use_internal_rev_list,
3244 N_("read revision arguments from standard input")),
3245 OPT_SET_INT_F(0, "unpacked", &rev_list_unpacked,
3246 N_("limit the objects to those that are not yet packed"),
3247 1, PARSE_OPT_NONEG),
3248 OPT_SET_INT_F(0, "all", &rev_list_all,
3249 N_("include objects reachable from any reference"),
3250 1, PARSE_OPT_NONEG),
3251 OPT_SET_INT_F(0, "reflog", &rev_list_reflog,
3252 N_("include objects referred by reflog entries"),
3253 1, PARSE_OPT_NONEG),
3254 OPT_SET_INT_F(0, "indexed-objects", &rev_list_index,
3255 N_("include objects referred to by the index"),
3256 1, PARSE_OPT_NONEG),
3257 OPT_BOOL(0, "stdout", &pack_to_stdout,
3258 N_("output pack to stdout")),
3259 OPT_BOOL(0, "include-tag", &include_tag,
3260 N_("include tag objects that refer to objects to be packed")),
3261 OPT_BOOL(0, "keep-unreachable", &keep_unreachable,
3262 N_("keep unreachable objects")),
3263 OPT_BOOL(0, "pack-loose-unreachable", &pack_loose_unreachable,
3264 N_("pack loose unreachable objects")),
3265 { OPTION_CALLBACK, 0, "unpack-unreachable", NULL, N_("time"),
3266 N_("unpack unreachable objects newer than <time>"),
3267 PARSE_OPT_OPTARG, option_parse_unpack_unreachable },
3268 OPT_BOOL(0, "thin", &thin,
3269 N_("create thin packs")),
3270 OPT_BOOL(0, "shallow", &shallow,
3271 N_("create packs suitable for shallow fetches")),
3272 OPT_BOOL(0, "honor-pack-keep", &ignore_packed_keep_on_disk,
3273 N_("ignore packs that have companion .keep file")),
3274 OPT_STRING_LIST(0, "keep-pack", &keep_pack_list, N_("name"),
3275 N_("ignore this pack")),
3276 OPT_INTEGER(0, "compression", &pack_compression_level,
3277 N_("pack compression level")),
3278 OPT_SET_INT(0, "keep-true-parents", &grafts_replace_parents,
3279 N_("do not hide commits by grafts"), 0),
3280 OPT_BOOL(0, "use-bitmap-index", &use_bitmap_index,
3281 N_("use a bitmap index if available to speed up counting objects")),
3282 OPT_BOOL(0, "write-bitmap-index", &write_bitmap_index,
3283 N_("write a bitmap index together with the pack index")),
3284 OPT_PARSE_LIST_OBJECTS_FILTER(&filter_options),
3285 { OPTION_CALLBACK, 0, "missing", NULL, N_("action"),
3286 N_("handling for missing objects"), PARSE_OPT_NONEG,
3287 option_parse_missing_action },
3288 OPT_BOOL(0, "exclude-promisor-objects", &exclude_promisor_objects,
3289 N_("do not pack objects in promisor packfiles")),
3290 OPT_BOOL(0, "delta-islands", &use_delta_islands,
3291 N_("respect islands during delta compression")),
3292 OPT_END(),
3293 };
3294
3295 if (DFS_NUM_STATES > (1 << OE_DFS_STATE_BITS))
3296 BUG("too many dfs states, increase OE_DFS_STATE_BITS");
3297
3298 read_replace_refs = 0;
3299
3300 reset_pack_idx_option(&pack_idx_opts);
3301 git_config(git_pack_config, NULL);
3302
3303 progress = isatty(2);
3304 argc = parse_options(argc, argv, prefix, pack_objects_options,
3305 pack_usage, 0);
3306
3307 if (argc) {
3308 base_name = argv[0];
3309 argc--;
3310 }
3311 if (pack_to_stdout != !base_name || argc)
3312 usage_with_options(pack_usage, pack_objects_options);
3313
3314 if (depth >= (1 << OE_DEPTH_BITS)) {
3315 warning(_("delta chain depth %d is too deep, forcing %d"),
3316 depth, (1 << OE_DEPTH_BITS) - 1);
3317 depth = (1 << OE_DEPTH_BITS) - 1;
3318 }
3319 if (cache_max_small_delta_size >= (1U << OE_Z_DELTA_BITS)) {
3320 warning(_("pack.deltaCacheLimit is too high, forcing %d"),
3321 (1U << OE_Z_DELTA_BITS) - 1);
3322 cache_max_small_delta_size = (1U << OE_Z_DELTA_BITS) - 1;
3323 }
3324
3325 argv_array_push(&rp, "pack-objects");
3326 if (thin) {
3327 use_internal_rev_list = 1;
3328 argv_array_push(&rp, shallow
3329 ? "--objects-edge-aggressive"
3330 : "--objects-edge");
3331 } else
3332 argv_array_push(&rp, "--objects");
3333
3334 if (rev_list_all) {
3335 use_internal_rev_list = 1;
3336 argv_array_push(&rp, "--all");
3337 }
3338 if (rev_list_reflog) {
3339 use_internal_rev_list = 1;
3340 argv_array_push(&rp, "--reflog");
3341 }
3342 if (rev_list_index) {
3343 use_internal_rev_list = 1;
3344 argv_array_push(&rp, "--indexed-objects");
3345 }
3346 if (rev_list_unpacked) {
3347 use_internal_rev_list = 1;
3348 argv_array_push(&rp, "--unpacked");
3349 }
3350
3351 if (exclude_promisor_objects) {
3352 use_internal_rev_list = 1;
3353 fetch_if_missing = 0;
3354 argv_array_push(&rp, "--exclude-promisor-objects");
3355 }
3356 if (unpack_unreachable || keep_unreachable || pack_loose_unreachable)
3357 use_internal_rev_list = 1;
3358
3359 if (!reuse_object)
3360 reuse_delta = 0;
3361 if (pack_compression_level == -1)
3362 pack_compression_level = Z_DEFAULT_COMPRESSION;
3363 else if (pack_compression_level < 0 || pack_compression_level > Z_BEST_COMPRESSION)
3364 die(_("bad pack compression level %d"), pack_compression_level);
3365
3366 if (!delta_search_threads) /* --threads=0 means autodetect */
3367 delta_search_threads = online_cpus();
3368
3369 #ifdef NO_PTHREADS
3370 if (delta_search_threads != 1)
3371 warning(_("no threads support, ignoring --threads"));
3372 #endif
3373 if (!pack_to_stdout && !pack_size_limit)
3374 pack_size_limit = pack_size_limit_cfg;
3375 if (pack_to_stdout && pack_size_limit)
3376 die(_("--max-pack-size cannot be used to build a pack for transfer"));
3377 if (pack_size_limit && pack_size_limit < 1024*1024) {
3378 warning(_("minimum pack size limit is 1 MiB"));
3379 pack_size_limit = 1024*1024;
3380 }
3381
3382 if (!pack_to_stdout && thin)
3383 die(_("--thin cannot be used to build an indexable pack"));
3384
3385 if (keep_unreachable && unpack_unreachable)
3386 die(_("--keep-unreachable and --unpack-unreachable are incompatible"));
3387 if (!rev_list_all || !rev_list_reflog || !rev_list_index)
3388 unpack_unreachable_expiration = 0;
3389
3390 if (filter_options.choice) {
3391 if (!pack_to_stdout)
3392 die(_("cannot use --filter without --stdout"));
3393 use_bitmap_index = 0;
3394 }
3395
3396 /*
3397 * "soft" reasons not to use bitmaps - for on-disk repack by default we want
3398 *
3399 * - to produce good pack (with bitmap index not-yet-packed objects are
3400 * packed in suboptimal order).
3401 *
3402 * - to use more robust pack-generation codepath (avoiding possible
3403 * bugs in bitmap code and possible bitmap index corruption).
3404 */
3405 if (!pack_to_stdout)
3406 use_bitmap_index_default = 0;
3407
3408 if (use_bitmap_index < 0)
3409 use_bitmap_index = use_bitmap_index_default;
3410
3411 /* "hard" reasons not to use bitmaps; these just won't work at all */
3412 if (!use_internal_rev_list || (!pack_to_stdout && write_bitmap_index) || is_repository_shallow(the_repository))
3413 use_bitmap_index = 0;
3414
3415 if (pack_to_stdout || !rev_list_all)
3416 write_bitmap_index = 0;
3417
3418 if (use_delta_islands)
3419 argv_array_push(&rp, "--topo-order");
3420
3421 if (progress && all_progress_implied)
3422 progress = 2;
3423
3424 add_extra_kept_packs(&keep_pack_list);
3425 if (ignore_packed_keep_on_disk) {
3426 struct packed_git *p;
3427 for (p = get_all_packs(the_repository); p; p = p->next)
3428 if (p->pack_local && p->pack_keep)
3429 break;
3430 if (!p) /* no keep-able packs found */
3431 ignore_packed_keep_on_disk = 0;
3432 }
3433 if (local) {
3434 /*
3435 * unlike ignore_packed_keep_on_disk above, we do not
3436 * want to unset "local" based on looking at packs, as
3437 * it also covers non-local objects
3438 */
3439 struct packed_git *p;
3440 for (p = get_all_packs(the_repository); p; p = p->next) {
3441 if (!p->pack_local) {
3442 have_non_local_packs = 1;
3443 break;
3444 }
3445 }
3446 }
3447
3448 prepare_packing_data(&to_pack);
3449
3450 if (progress)
3451 progress_state = start_progress(_("Enumerating objects"), 0);
3452 if (!use_internal_rev_list)
3453 read_object_list_from_stdin();
3454 else {
3455 get_object_list(rp.argc, rp.argv);
3456 argv_array_clear(&rp);
3457 }
3458 cleanup_preferred_base();
3459 if (include_tag && nr_result)
3460 for_each_ref(add_ref_tag, NULL);
3461 stop_progress(&progress_state);
3462
3463 if (non_empty && !nr_result)
3464 return 0;
3465 if (nr_result)
3466 prepare_pack(window, depth);
3467 write_pack_file();
3468 if (progress)
3469 fprintf_ln(stderr,
3470 _("Total %"PRIu32" (delta %"PRIu32"),"
3471 " reused %"PRIu32" (delta %"PRIu32")"),
3472 written, written_delta, reused, reused_delta);
3473 return 0;
3474 }