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