Merge branch 'sb/submodule-update-in-c'
[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
2073         if (DELTA(trg_entry)) {
2074                 /* Prefer only shallower same-sized deltas. */
2075                 if (delta_size == DELTA_SIZE(trg_entry) &&
2076                     src->depth + 1 >= trg->depth) {
2077                         free(delta_buf);
2078                         return 0;
2079                 }
2080         }
2081
2082         /*
2083          * Handle memory allocation outside of the cache
2084          * accounting lock.  Compiler will optimize the strangeness
2085          * away when NO_PTHREADS is defined.
2086          */
2087         free(trg_entry->delta_data);
2088         cache_lock();
2089         if (trg_entry->delta_data) {
2090                 delta_cache_size -= DELTA_SIZE(trg_entry);
2091                 trg_entry->delta_data = NULL;
2092         }
2093         if (delta_cacheable(src_size, trg_size, delta_size)) {
2094                 delta_cache_size += delta_size;
2095                 cache_unlock();
2096                 trg_entry->delta_data = xrealloc(delta_buf, delta_size);
2097         } else {
2098                 cache_unlock();
2099                 free(delta_buf);
2100         }
2101
2102         SET_DELTA(trg_entry, src_entry);
2103         SET_DELTA_SIZE(trg_entry, delta_size);
2104         trg->depth = src->depth + 1;
2105
2106         return 1;
2107 }
2108
2109 static unsigned int check_delta_limit(struct object_entry *me, unsigned int n)
2110 {
2111         struct object_entry *child = DELTA_CHILD(me);
2112         unsigned int m = n;
2113         while (child) {
2114                 unsigned int c = check_delta_limit(child, n + 1);
2115                 if (m < c)
2116                         m = c;
2117                 child = DELTA_SIBLING(child);
2118         }
2119         return m;
2120 }
2121
2122 static unsigned long free_unpacked(struct unpacked *n)
2123 {
2124         unsigned long freed_mem = sizeof_delta_index(n->index);
2125         free_delta_index(n->index);
2126         n->index = NULL;
2127         if (n->data) {
2128                 freed_mem += SIZE(n->entry);
2129                 FREE_AND_NULL(n->data);
2130         }
2131         n->entry = NULL;
2132         n->depth = 0;
2133         return freed_mem;
2134 }
2135
2136 static void find_deltas(struct object_entry **list, unsigned *list_size,
2137                         int window, int depth, unsigned *processed)
2138 {
2139         uint32_t i, idx = 0, count = 0;
2140         struct unpacked *array;
2141         unsigned long mem_usage = 0;
2142
2143         array = xcalloc(window, sizeof(struct unpacked));
2144
2145         for (;;) {
2146                 struct object_entry *entry;
2147                 struct unpacked *n = array + idx;
2148                 int j, max_depth, best_base = -1;
2149
2150                 progress_lock();
2151                 if (!*list_size) {
2152                         progress_unlock();
2153                         break;
2154                 }
2155                 entry = *list++;
2156                 (*list_size)--;
2157                 if (!entry->preferred_base) {
2158                         (*processed)++;
2159                         display_progress(progress_state, *processed);
2160                 }
2161                 progress_unlock();
2162
2163                 mem_usage -= free_unpacked(n);
2164                 n->entry = entry;
2165
2166                 while (window_memory_limit &&
2167                        mem_usage > window_memory_limit &&
2168                        count > 1) {
2169                         uint32_t tail = (idx + window - count) % window;
2170                         mem_usage -= free_unpacked(array + tail);
2171                         count--;
2172                 }
2173
2174                 /* We do not compute delta to *create* objects we are not
2175                  * going to pack.
2176                  */
2177                 if (entry->preferred_base)
2178                         goto next;
2179
2180                 /*
2181                  * If the current object is at pack edge, take the depth the
2182                  * objects that depend on the current object into account
2183                  * otherwise they would become too deep.
2184                  */
2185                 max_depth = depth;
2186                 if (DELTA_CHILD(entry)) {
2187                         max_depth -= check_delta_limit(entry, 0);
2188                         if (max_depth <= 0)
2189                                 goto next;
2190                 }
2191
2192                 j = window;
2193                 while (--j > 0) {
2194                         int ret;
2195                         uint32_t other_idx = idx + j;
2196                         struct unpacked *m;
2197                         if (other_idx >= window)
2198                                 other_idx -= window;
2199                         m = array + other_idx;
2200                         if (!m->entry)
2201                                 break;
2202                         ret = try_delta(n, m, max_depth, &mem_usage);
2203                         if (ret < 0)
2204                                 break;
2205                         else if (ret > 0)
2206                                 best_base = other_idx;
2207                 }
2208
2209                 /*
2210                  * If we decided to cache the delta data, then it is best
2211                  * to compress it right away.  First because we have to do
2212                  * it anyway, and doing it here while we're threaded will
2213                  * save a lot of time in the non threaded write phase,
2214                  * as well as allow for caching more deltas within
2215                  * the same cache size limit.
2216                  * ...
2217                  * But only if not writing to stdout, since in that case
2218                  * the network is most likely throttling writes anyway,
2219                  * and therefore it is best to go to the write phase ASAP
2220                  * instead, as we can afford spending more time compressing
2221                  * between writes at that moment.
2222                  */
2223                 if (entry->delta_data && !pack_to_stdout) {
2224                         unsigned long size;
2225
2226                         size = do_compress(&entry->delta_data, DELTA_SIZE(entry));
2227                         if (size < (1U << OE_Z_DELTA_BITS)) {
2228                                 entry->z_delta_size = size;
2229                                 cache_lock();
2230                                 delta_cache_size -= DELTA_SIZE(entry);
2231                                 delta_cache_size += entry->z_delta_size;
2232                                 cache_unlock();
2233                         } else {
2234                                 FREE_AND_NULL(entry->delta_data);
2235                                 entry->z_delta_size = 0;
2236                         }
2237                 }
2238
2239                 /* if we made n a delta, and if n is already at max
2240                  * depth, leaving it in the window is pointless.  we
2241                  * should evict it first.
2242                  */
2243                 if (DELTA(entry) && max_depth <= n->depth)
2244                         continue;
2245
2246                 /*
2247                  * Move the best delta base up in the window, after the
2248                  * currently deltified object, to keep it longer.  It will
2249                  * be the first base object to be attempted next.
2250                  */
2251                 if (DELTA(entry)) {
2252                         struct unpacked swap = array[best_base];
2253                         int dist = (window + idx - best_base) % window;
2254                         int dst = best_base;
2255                         while (dist--) {
2256                                 int src = (dst + 1) % window;
2257                                 array[dst] = array[src];
2258                                 dst = src;
2259                         }
2260                         array[dst] = swap;
2261                 }
2262
2263                 next:
2264                 idx++;
2265                 if (count + 1 < window)
2266                         count++;
2267                 if (idx >= window)
2268                         idx = 0;
2269         }
2270
2271         for (i = 0; i < window; ++i) {
2272                 free_delta_index(array[i].index);
2273                 free(array[i].data);
2274         }
2275         free(array);
2276 }
2277
2278 #ifndef NO_PTHREADS
2279
2280 static void try_to_free_from_threads(size_t size)
2281 {
2282         read_lock();
2283         release_pack_memory(size);
2284         read_unlock();
2285 }
2286
2287 static try_to_free_t old_try_to_free_routine;
2288
2289 /*
2290  * The main object list is split into smaller lists, each is handed to
2291  * one worker.
2292  *
2293  * The main thread waits on the condition that (at least) one of the workers
2294  * has stopped working (which is indicated in the .working member of
2295  * struct thread_params).
2296  *
2297  * When a work thread has completed its work, it sets .working to 0 and
2298  * signals the main thread and waits on the condition that .data_ready
2299  * becomes 1.
2300  *
2301  * The main thread steals half of the work from the worker that has
2302  * most work left to hand it to the idle worker.
2303  */
2304
2305 struct thread_params {
2306         pthread_t thread;
2307         struct object_entry **list;
2308         unsigned list_size;
2309         unsigned remaining;
2310         int window;
2311         int depth;
2312         int working;
2313         int data_ready;
2314         pthread_mutex_t mutex;
2315         pthread_cond_t cond;
2316         unsigned *processed;
2317 };
2318
2319 static pthread_cond_t progress_cond;
2320
2321 /*
2322  * Mutex and conditional variable can't be statically-initialized on Windows.
2323  */
2324 static void init_threaded_search(void)
2325 {
2326         init_recursive_mutex(&read_mutex);
2327         pthread_mutex_init(&cache_mutex, NULL);
2328         pthread_mutex_init(&progress_mutex, NULL);
2329         pthread_cond_init(&progress_cond, NULL);
2330         pthread_mutex_init(&to_pack.lock, NULL);
2331         old_try_to_free_routine = set_try_to_free_routine(try_to_free_from_threads);
2332 }
2333
2334 static void cleanup_threaded_search(void)
2335 {
2336         set_try_to_free_routine(old_try_to_free_routine);
2337         pthread_cond_destroy(&progress_cond);
2338         pthread_mutex_destroy(&read_mutex);
2339         pthread_mutex_destroy(&cache_mutex);
2340         pthread_mutex_destroy(&progress_mutex);
2341 }
2342
2343 static void *threaded_find_deltas(void *arg)
2344 {
2345         struct thread_params *me = arg;
2346
2347         progress_lock();
2348         while (me->remaining) {
2349                 progress_unlock();
2350
2351                 find_deltas(me->list, &me->remaining,
2352                             me->window, me->depth, me->processed);
2353
2354                 progress_lock();
2355                 me->working = 0;
2356                 pthread_cond_signal(&progress_cond);
2357                 progress_unlock();
2358
2359                 /*
2360                  * We must not set ->data_ready before we wait on the
2361                  * condition because the main thread may have set it to 1
2362                  * before we get here. In order to be sure that new
2363                  * work is available if we see 1 in ->data_ready, it
2364                  * was initialized to 0 before this thread was spawned
2365                  * and we reset it to 0 right away.
2366                  */
2367                 pthread_mutex_lock(&me->mutex);
2368                 while (!me->data_ready)
2369                         pthread_cond_wait(&me->cond, &me->mutex);
2370                 me->data_ready = 0;
2371                 pthread_mutex_unlock(&me->mutex);
2372
2373                 progress_lock();
2374         }
2375         progress_unlock();
2376         /* leave ->working 1 so that this doesn't get more work assigned */
2377         return NULL;
2378 }
2379
2380 static void ll_find_deltas(struct object_entry **list, unsigned list_size,
2381                            int window, int depth, unsigned *processed)
2382 {
2383         struct thread_params *p;
2384         int i, ret, active_threads = 0;
2385
2386         init_threaded_search();
2387
2388         if (delta_search_threads <= 1) {
2389                 find_deltas(list, &list_size, window, depth, processed);
2390                 cleanup_threaded_search();
2391                 return;
2392         }
2393         if (progress > pack_to_stdout)
2394                 fprintf_ln(stderr, _("Delta compression using up to %d threads"),
2395                            delta_search_threads);
2396         p = xcalloc(delta_search_threads, sizeof(*p));
2397
2398         /* Partition the work amongst work threads. */
2399         for (i = 0; i < delta_search_threads; i++) {
2400                 unsigned sub_size = list_size / (delta_search_threads - i);
2401
2402                 /* don't use too small segments or no deltas will be found */
2403                 if (sub_size < 2*window && i+1 < delta_search_threads)
2404                         sub_size = 0;
2405
2406                 p[i].window = window;
2407                 p[i].depth = depth;
2408                 p[i].processed = processed;
2409                 p[i].working = 1;
2410                 p[i].data_ready = 0;
2411
2412                 /* try to split chunks on "path" boundaries */
2413                 while (sub_size && sub_size < list_size &&
2414                        list[sub_size]->hash &&
2415                        list[sub_size]->hash == list[sub_size-1]->hash)
2416                         sub_size++;
2417
2418                 p[i].list = list;
2419                 p[i].list_size = sub_size;
2420                 p[i].remaining = sub_size;
2421
2422                 list += sub_size;
2423                 list_size -= sub_size;
2424         }
2425
2426         /* Start work threads. */
2427         for (i = 0; i < delta_search_threads; i++) {
2428                 if (!p[i].list_size)
2429                         continue;
2430                 pthread_mutex_init(&p[i].mutex, NULL);
2431                 pthread_cond_init(&p[i].cond, NULL);
2432                 ret = pthread_create(&p[i].thread, NULL,
2433                                      threaded_find_deltas, &p[i]);
2434                 if (ret)
2435                         die(_("unable to create thread: %s"), strerror(ret));
2436                 active_threads++;
2437         }
2438
2439         /*
2440          * Now let's wait for work completion.  Each time a thread is done
2441          * with its work, we steal half of the remaining work from the
2442          * thread with the largest number of unprocessed objects and give
2443          * it to that newly idle thread.  This ensure good load balancing
2444          * until the remaining object list segments are simply too short
2445          * to be worth splitting anymore.
2446          */
2447         while (active_threads) {
2448                 struct thread_params *target = NULL;
2449                 struct thread_params *victim = NULL;
2450                 unsigned sub_size = 0;
2451
2452                 progress_lock();
2453                 for (;;) {
2454                         for (i = 0; !target && i < delta_search_threads; i++)
2455                                 if (!p[i].working)
2456                                         target = &p[i];
2457                         if (target)
2458                                 break;
2459                         pthread_cond_wait(&progress_cond, &progress_mutex);
2460                 }
2461
2462                 for (i = 0; i < delta_search_threads; i++)
2463                         if (p[i].remaining > 2*window &&
2464                             (!victim || victim->remaining < p[i].remaining))
2465                                 victim = &p[i];
2466                 if (victim) {
2467                         sub_size = victim->remaining / 2;
2468                         list = victim->list + victim->list_size - sub_size;
2469                         while (sub_size && list[0]->hash &&
2470                                list[0]->hash == list[-1]->hash) {
2471                                 list++;
2472                                 sub_size--;
2473                         }
2474                         if (!sub_size) {
2475                                 /*
2476                                  * It is possible for some "paths" to have
2477                                  * so many objects that no hash boundary
2478                                  * might be found.  Let's just steal the
2479                                  * exact half in that case.
2480                                  */
2481                                 sub_size = victim->remaining / 2;
2482                                 list -= sub_size;
2483                         }
2484                         target->list = list;
2485                         victim->list_size -= sub_size;
2486                         victim->remaining -= sub_size;
2487                 }
2488                 target->list_size = sub_size;
2489                 target->remaining = sub_size;
2490                 target->working = 1;
2491                 progress_unlock();
2492
2493                 pthread_mutex_lock(&target->mutex);
2494                 target->data_ready = 1;
2495                 pthread_cond_signal(&target->cond);
2496                 pthread_mutex_unlock(&target->mutex);
2497
2498                 if (!sub_size) {
2499                         pthread_join(target->thread, NULL);
2500                         pthread_cond_destroy(&target->cond);
2501                         pthread_mutex_destroy(&target->mutex);
2502                         active_threads--;
2503                 }
2504         }
2505         cleanup_threaded_search();
2506         free(p);
2507 }
2508
2509 #else
2510 #define ll_find_deltas(l, s, w, d, p)   find_deltas(l, &s, w, d, p)
2511 #endif
2512
2513 static void add_tag_chain(const struct object_id *oid)
2514 {
2515         struct tag *tag;
2516
2517         /*
2518          * We catch duplicates already in add_object_entry(), but we'd
2519          * prefer to do this extra check to avoid having to parse the
2520          * tag at all if we already know that it's being packed (e.g., if
2521          * it was included via bitmaps, we would not have parsed it
2522          * previously).
2523          */
2524         if (packlist_find(&to_pack, oid->hash, NULL))
2525                 return;
2526
2527         tag = lookup_tag(the_repository, oid);
2528         while (1) {
2529                 if (!tag || parse_tag(tag) || !tag->tagged)
2530                         die(_("unable to pack objects reachable from tag %s"),
2531                             oid_to_hex(oid));
2532
2533                 add_object_entry(&tag->object.oid, OBJ_TAG, NULL, 0);
2534
2535                 if (tag->tagged->type != OBJ_TAG)
2536                         return;
2537
2538                 tag = (struct tag *)tag->tagged;
2539         }
2540 }
2541
2542 static int add_ref_tag(const char *path, const struct object_id *oid, int flag, void *cb_data)
2543 {
2544         struct object_id peeled;
2545
2546         if (starts_with(path, "refs/tags/") && /* is a tag? */
2547             !peel_ref(path, &peeled)    && /* peelable? */
2548             packlist_find(&to_pack, peeled.hash, NULL))      /* object packed? */
2549                 add_tag_chain(oid);
2550         return 0;
2551 }
2552
2553 static void prepare_pack(int window, int depth)
2554 {
2555         struct object_entry **delta_list;
2556         uint32_t i, nr_deltas;
2557         unsigned n;
2558
2559         get_object_details();
2560
2561         /*
2562          * If we're locally repacking then we need to be doubly careful
2563          * from now on in order to make sure no stealth corruption gets
2564          * propagated to the new pack.  Clients receiving streamed packs
2565          * should validate everything they get anyway so no need to incur
2566          * the additional cost here in that case.
2567          */
2568         if (!pack_to_stdout)
2569                 do_check_packed_object_crc = 1;
2570
2571         if (!to_pack.nr_objects || !window || !depth)
2572                 return;
2573
2574         ALLOC_ARRAY(delta_list, to_pack.nr_objects);
2575         nr_deltas = n = 0;
2576
2577         for (i = 0; i < to_pack.nr_objects; i++) {
2578                 struct object_entry *entry = to_pack.objects + i;
2579
2580                 if (DELTA(entry))
2581                         /* This happens if we decided to reuse existing
2582                          * delta from a pack.  "reuse_delta &&" is implied.
2583                          */
2584                         continue;
2585
2586                 if (!entry->type_valid ||
2587                     oe_size_less_than(&to_pack, entry, 50))
2588                         continue;
2589
2590                 if (entry->no_try_delta)
2591                         continue;
2592
2593                 if (!entry->preferred_base) {
2594                         nr_deltas++;
2595                         if (oe_type(entry) < 0)
2596                                 die(_("unable to get type of object %s"),
2597                                     oid_to_hex(&entry->idx.oid));
2598                 } else {
2599                         if (oe_type(entry) < 0) {
2600                                 /*
2601                                  * This object is not found, but we
2602                                  * don't have to include it anyway.
2603                                  */
2604                                 continue;
2605                         }
2606                 }
2607
2608                 delta_list[n++] = entry;
2609         }
2610
2611         if (nr_deltas && n > 1) {
2612                 unsigned nr_done = 0;
2613                 if (progress)
2614                         progress_state = start_progress(_("Compressing objects"),
2615                                                         nr_deltas);
2616                 QSORT(delta_list, n, type_size_sort);
2617                 ll_find_deltas(delta_list, n, window+1, depth, &nr_done);
2618                 stop_progress(&progress_state);
2619                 if (nr_done != nr_deltas)
2620                         die(_("inconsistency with delta count"));
2621         }
2622         free(delta_list);
2623 }
2624
2625 static int git_pack_config(const char *k, const char *v, void *cb)
2626 {
2627         if (!strcmp(k, "pack.window")) {
2628                 window = git_config_int(k, v);
2629                 return 0;
2630         }
2631         if (!strcmp(k, "pack.windowmemory")) {
2632                 window_memory_limit = git_config_ulong(k, v);
2633                 return 0;
2634         }
2635         if (!strcmp(k, "pack.depth")) {
2636                 depth = git_config_int(k, v);
2637                 return 0;
2638         }
2639         if (!strcmp(k, "pack.deltacachesize")) {
2640                 max_delta_cache_size = git_config_int(k, v);
2641                 return 0;
2642         }
2643         if (!strcmp(k, "pack.deltacachelimit")) {
2644                 cache_max_small_delta_size = git_config_int(k, v);
2645                 return 0;
2646         }
2647         if (!strcmp(k, "pack.writebitmaphashcache")) {
2648                 if (git_config_bool(k, v))
2649                         write_bitmap_options |= BITMAP_OPT_HASH_CACHE;
2650                 else
2651                         write_bitmap_options &= ~BITMAP_OPT_HASH_CACHE;
2652         }
2653         if (!strcmp(k, "pack.usebitmaps")) {
2654                 use_bitmap_index_default = git_config_bool(k, v);
2655                 return 0;
2656         }
2657         if (!strcmp(k, "pack.threads")) {
2658                 delta_search_threads = git_config_int(k, v);
2659                 if (delta_search_threads < 0)
2660                         die(_("invalid number of threads specified (%d)"),
2661                             delta_search_threads);
2662 #ifdef NO_PTHREADS
2663                 if (delta_search_threads != 1) {
2664                         warning(_("no threads support, ignoring %s"), k);
2665                         delta_search_threads = 0;
2666                 }
2667 #endif
2668                 return 0;
2669         }
2670         if (!strcmp(k, "pack.indexversion")) {
2671                 pack_idx_opts.version = git_config_int(k, v);
2672                 if (pack_idx_opts.version > 2)
2673                         die(_("bad pack.indexversion=%"PRIu32),
2674                             pack_idx_opts.version);
2675                 return 0;
2676         }
2677         return git_default_config(k, v, cb);
2678 }
2679
2680 static void read_object_list_from_stdin(void)
2681 {
2682         char line[GIT_MAX_HEXSZ + 1 + PATH_MAX + 2];
2683         struct object_id oid;
2684         const char *p;
2685
2686         for (;;) {
2687                 if (!fgets(line, sizeof(line), stdin)) {
2688                         if (feof(stdin))
2689                                 break;
2690                         if (!ferror(stdin))
2691                                 die("BUG: fgets returned NULL, not EOF, not error!");
2692                         if (errno != EINTR)
2693                                 die_errno("fgets");
2694                         clearerr(stdin);
2695                         continue;
2696                 }
2697                 if (line[0] == '-') {
2698                         if (get_oid_hex(line+1, &oid))
2699                                 die(_("expected edge object ID, got garbage:\n %s"),
2700                                     line);
2701                         add_preferred_base(&oid);
2702                         continue;
2703                 }
2704                 if (parse_oid_hex(line, &oid, &p))
2705                         die(_("expected object ID, got garbage:\n %s"), line);
2706
2707                 add_preferred_base_object(p + 1);
2708                 add_object_entry(&oid, OBJ_NONE, p + 1, 0);
2709         }
2710 }
2711
2712 /* Remember to update object flag allocation in object.h */
2713 #define OBJECT_ADDED (1u<<20)
2714
2715 static void show_commit(struct commit *commit, void *data)
2716 {
2717         add_object_entry(&commit->object.oid, OBJ_COMMIT, NULL, 0);
2718         commit->object.flags |= OBJECT_ADDED;
2719
2720         if (write_bitmap_index)
2721                 index_commit_for_bitmap(commit);
2722 }
2723
2724 static void show_object(struct object *obj, const char *name, void *data)
2725 {
2726         add_preferred_base_object(name);
2727         add_object_entry(&obj->oid, obj->type, name, 0);
2728         obj->flags |= OBJECT_ADDED;
2729 }
2730
2731 static void show_object__ma_allow_any(struct object *obj, const char *name, void *data)
2732 {
2733         assert(arg_missing_action == MA_ALLOW_ANY);
2734
2735         /*
2736          * Quietly ignore ALL missing objects.  This avoids problems with
2737          * staging them now and getting an odd error later.
2738          */
2739         if (!has_object_file(&obj->oid))
2740                 return;
2741
2742         show_object(obj, name, data);
2743 }
2744
2745 static void show_object__ma_allow_promisor(struct object *obj, const char *name, void *data)
2746 {
2747         assert(arg_missing_action == MA_ALLOW_PROMISOR);
2748
2749         /*
2750          * Quietly ignore EXPECTED missing objects.  This avoids problems with
2751          * staging them now and getting an odd error later.
2752          */
2753         if (!has_object_file(&obj->oid) && is_promisor_object(&obj->oid))
2754                 return;
2755
2756         show_object(obj, name, data);
2757 }
2758
2759 static int option_parse_missing_action(const struct option *opt,
2760                                        const char *arg, int unset)
2761 {
2762         assert(arg);
2763         assert(!unset);
2764
2765         if (!strcmp(arg, "error")) {
2766                 arg_missing_action = MA_ERROR;
2767                 fn_show_object = show_object;
2768                 return 0;
2769         }
2770
2771         if (!strcmp(arg, "allow-any")) {
2772                 arg_missing_action = MA_ALLOW_ANY;
2773                 fetch_if_missing = 0;
2774                 fn_show_object = show_object__ma_allow_any;
2775                 return 0;
2776         }
2777
2778         if (!strcmp(arg, "allow-promisor")) {
2779                 arg_missing_action = MA_ALLOW_PROMISOR;
2780                 fetch_if_missing = 0;
2781                 fn_show_object = show_object__ma_allow_promisor;
2782                 return 0;
2783         }
2784
2785         die(_("invalid value for --missing"));
2786         return 0;
2787 }
2788
2789 static void show_edge(struct commit *commit)
2790 {
2791         add_preferred_base(&commit->object.oid);
2792 }
2793
2794 struct in_pack_object {
2795         off_t offset;
2796         struct object *object;
2797 };
2798
2799 struct in_pack {
2800         unsigned int alloc;
2801         unsigned int nr;
2802         struct in_pack_object *array;
2803 };
2804
2805 static void mark_in_pack_object(struct object *object, struct packed_git *p, struct in_pack *in_pack)
2806 {
2807         in_pack->array[in_pack->nr].offset = find_pack_entry_one(object->oid.hash, p);
2808         in_pack->array[in_pack->nr].object = object;
2809         in_pack->nr++;
2810 }
2811
2812 /*
2813  * Compare the objects in the offset order, in order to emulate the
2814  * "git rev-list --objects" output that produced the pack originally.
2815  */
2816 static int ofscmp(const void *a_, const void *b_)
2817 {
2818         struct in_pack_object *a = (struct in_pack_object *)a_;
2819         struct in_pack_object *b = (struct in_pack_object *)b_;
2820
2821         if (a->offset < b->offset)
2822                 return -1;
2823         else if (a->offset > b->offset)
2824                 return 1;
2825         else
2826                 return oidcmp(&a->object->oid, &b->object->oid);
2827 }
2828
2829 static void add_objects_in_unpacked_packs(struct rev_info *revs)
2830 {
2831         struct packed_git *p;
2832         struct in_pack in_pack;
2833         uint32_t i;
2834
2835         memset(&in_pack, 0, sizeof(in_pack));
2836
2837         for (p = get_all_packs(the_repository); p; p = p->next) {
2838                 struct object_id oid;
2839                 struct object *o;
2840
2841                 if (!p->pack_local || p->pack_keep || p->pack_keep_in_core)
2842                         continue;
2843                 if (open_pack_index(p))
2844                         die(_("cannot open pack index"));
2845
2846                 ALLOC_GROW(in_pack.array,
2847                            in_pack.nr + p->num_objects,
2848                            in_pack.alloc);
2849
2850                 for (i = 0; i < p->num_objects; i++) {
2851                         nth_packed_object_oid(&oid, p, i);
2852                         o = lookup_unknown_object(oid.hash);
2853                         if (!(o->flags & OBJECT_ADDED))
2854                                 mark_in_pack_object(o, p, &in_pack);
2855                         o->flags |= OBJECT_ADDED;
2856                 }
2857         }
2858
2859         if (in_pack.nr) {
2860                 QSORT(in_pack.array, in_pack.nr, ofscmp);
2861                 for (i = 0; i < in_pack.nr; i++) {
2862                         struct object *o = in_pack.array[i].object;
2863                         add_object_entry(&o->oid, o->type, "", 0);
2864                 }
2865         }
2866         free(in_pack.array);
2867 }
2868
2869 static int add_loose_object(const struct object_id *oid, const char *path,
2870                             void *data)
2871 {
2872         enum object_type type = oid_object_info(the_repository, oid, NULL);
2873
2874         if (type < 0) {
2875                 warning(_("loose object at %s could not be examined"), path);
2876                 return 0;
2877         }
2878
2879         add_object_entry(oid, type, "", 0);
2880         return 0;
2881 }
2882
2883 /*
2884  * We actually don't even have to worry about reachability here.
2885  * add_object_entry will weed out duplicates, so we just add every
2886  * loose object we find.
2887  */
2888 static void add_unreachable_loose_objects(void)
2889 {
2890         for_each_loose_file_in_objdir(get_object_directory(),
2891                                       add_loose_object,
2892                                       NULL, NULL, NULL);
2893 }
2894
2895 static int has_sha1_pack_kept_or_nonlocal(const struct object_id *oid)
2896 {
2897         static struct packed_git *last_found = (void *)1;
2898         struct packed_git *p;
2899
2900         p = (last_found != (void *)1) ? last_found :
2901                                         get_all_packs(the_repository);
2902
2903         while (p) {
2904                 if ((!p->pack_local || p->pack_keep ||
2905                                 p->pack_keep_in_core) &&
2906                         find_pack_entry_one(oid->hash, p)) {
2907                         last_found = p;
2908                         return 1;
2909                 }
2910                 if (p == last_found)
2911                         p = get_all_packs(the_repository);
2912                 else
2913                         p = p->next;
2914                 if (p == last_found)
2915                         p = p->next;
2916         }
2917         return 0;
2918 }
2919
2920 /*
2921  * Store a list of sha1s that are should not be discarded
2922  * because they are either written too recently, or are
2923  * reachable from another object that was.
2924  *
2925  * This is filled by get_object_list.
2926  */
2927 static struct oid_array recent_objects;
2928
2929 static int loosened_object_can_be_discarded(const struct object_id *oid,
2930                                             timestamp_t mtime)
2931 {
2932         if (!unpack_unreachable_expiration)
2933                 return 0;
2934         if (mtime > unpack_unreachable_expiration)
2935                 return 0;
2936         if (oid_array_lookup(&recent_objects, oid) >= 0)
2937                 return 0;
2938         return 1;
2939 }
2940
2941 static void loosen_unused_packed_objects(struct rev_info *revs)
2942 {
2943         struct packed_git *p;
2944         uint32_t i;
2945         struct object_id oid;
2946
2947         for (p = get_all_packs(the_repository); p; p = p->next) {
2948                 if (!p->pack_local || p->pack_keep || p->pack_keep_in_core)
2949                         continue;
2950
2951                 if (open_pack_index(p))
2952                         die(_("cannot open pack index"));
2953
2954                 for (i = 0; i < p->num_objects; i++) {
2955                         nth_packed_object_oid(&oid, p, i);
2956                         if (!packlist_find(&to_pack, oid.hash, NULL) &&
2957                             !has_sha1_pack_kept_or_nonlocal(&oid) &&
2958                             !loosened_object_can_be_discarded(&oid, p->mtime))
2959                                 if (force_object_loose(&oid, p->mtime))
2960                                         die(_("unable to force loose object"));
2961                 }
2962         }
2963 }
2964
2965 /*
2966  * This tracks any options which pack-reuse code expects to be on, or which a
2967  * reader of the pack might not understand, and which would therefore prevent
2968  * blind reuse of what we have on disk.
2969  */
2970 static int pack_options_allow_reuse(void)
2971 {
2972         return pack_to_stdout &&
2973                allow_ofs_delta &&
2974                !ignore_packed_keep_on_disk &&
2975                !ignore_packed_keep_in_core &&
2976                (!local || !have_non_local_packs) &&
2977                !incremental;
2978 }
2979
2980 static int get_object_list_from_bitmap(struct rev_info *revs)
2981 {
2982         struct bitmap_index *bitmap_git;
2983         if (!(bitmap_git = prepare_bitmap_walk(revs)))
2984                 return -1;
2985
2986         if (pack_options_allow_reuse() &&
2987             !reuse_partial_packfile_from_bitmap(
2988                         bitmap_git,
2989                         &reuse_packfile,
2990                         &reuse_packfile_objects,
2991                         &reuse_packfile_offset)) {
2992                 assert(reuse_packfile_objects);
2993                 nr_result += reuse_packfile_objects;
2994                 display_progress(progress_state, nr_result);
2995         }
2996
2997         traverse_bitmap_commit_list(bitmap_git, &add_object_entry_from_bitmap);
2998         free_bitmap_index(bitmap_git);
2999         return 0;
3000 }
3001
3002 static void record_recent_object(struct object *obj,
3003                                  const char *name,
3004                                  void *data)
3005 {
3006         oid_array_append(&recent_objects, &obj->oid);
3007 }
3008
3009 static void record_recent_commit(struct commit *commit, void *data)
3010 {
3011         oid_array_append(&recent_objects, &commit->object.oid);
3012 }
3013
3014 static void get_object_list(int ac, const char **av)
3015 {
3016         struct rev_info revs;
3017         char line[1000];
3018         int flags = 0;
3019
3020         init_revisions(&revs, NULL);
3021         save_commit_buffer = 0;
3022         setup_revisions(ac, av, &revs, NULL);
3023
3024         /* make sure shallows are read */
3025         is_repository_shallow(the_repository);
3026
3027         while (fgets(line, sizeof(line), stdin) != NULL) {
3028                 int len = strlen(line);
3029                 if (len && line[len - 1] == '\n')
3030                         line[--len] = 0;
3031                 if (!len)
3032                         break;
3033                 if (*line == '-') {
3034                         if (!strcmp(line, "--not")) {
3035                                 flags ^= UNINTERESTING;
3036                                 write_bitmap_index = 0;
3037                                 continue;
3038                         }
3039                         if (starts_with(line, "--shallow ")) {
3040                                 struct object_id oid;
3041                                 if (get_oid_hex(line + 10, &oid))
3042                                         die("not an SHA-1 '%s'", line + 10);
3043                                 register_shallow(the_repository, &oid);
3044                                 use_bitmap_index = 0;
3045                                 continue;
3046                         }
3047                         die(_("not a rev '%s'"), line);
3048                 }
3049                 if (handle_revision_arg(line, &revs, flags, REVARG_CANNOT_BE_FILENAME))
3050                         die(_("bad revision '%s'"), line);
3051         }
3052
3053         if (use_bitmap_index && !get_object_list_from_bitmap(&revs))
3054                 return;
3055
3056         if (prepare_revision_walk(&revs))
3057                 die(_("revision walk setup failed"));
3058         mark_edges_uninteresting(&revs, show_edge);
3059
3060         if (!fn_show_object)
3061                 fn_show_object = show_object;
3062         traverse_commit_list_filtered(&filter_options, &revs,
3063                                       show_commit, fn_show_object, NULL,
3064                                       NULL);
3065
3066         if (unpack_unreachable_expiration) {
3067                 revs.ignore_missing_links = 1;
3068                 if (add_unseen_recent_objects_to_traversal(&revs,
3069                                 unpack_unreachable_expiration))
3070                         die(_("unable to add recent objects"));
3071                 if (prepare_revision_walk(&revs))
3072                         die(_("revision walk setup failed"));
3073                 traverse_commit_list(&revs, record_recent_commit,
3074                                      record_recent_object, NULL);
3075         }
3076
3077         if (keep_unreachable)
3078                 add_objects_in_unpacked_packs(&revs);
3079         if (pack_loose_unreachable)
3080                 add_unreachable_loose_objects();
3081         if (unpack_unreachable)
3082                 loosen_unused_packed_objects(&revs);
3083
3084         oid_array_clear(&recent_objects);
3085 }
3086
3087 static void add_extra_kept_packs(const struct string_list *names)
3088 {
3089         struct packed_git *p;
3090
3091         if (!names->nr)
3092                 return;
3093
3094         for (p = get_all_packs(the_repository); p; p = p->next) {
3095                 const char *name = basename(p->pack_name);
3096                 int i;
3097
3098                 if (!p->pack_local)
3099                         continue;
3100
3101                 for (i = 0; i < names->nr; i++)
3102                         if (!fspathcmp(name, names->items[i].string))
3103                                 break;
3104
3105                 if (i < names->nr) {
3106                         p->pack_keep_in_core = 1;
3107                         ignore_packed_keep_in_core = 1;
3108                         continue;
3109                 }
3110         }
3111 }
3112
3113 static int option_parse_index_version(const struct option *opt,
3114                                       const char *arg, int unset)
3115 {
3116         char *c;
3117         const char *val = arg;
3118         pack_idx_opts.version = strtoul(val, &c, 10);
3119         if (pack_idx_opts.version > 2)
3120                 die(_("unsupported index version %s"), val);
3121         if (*c == ',' && c[1])
3122                 pack_idx_opts.off32_limit = strtoul(c+1, &c, 0);
3123         if (*c || pack_idx_opts.off32_limit & 0x80000000)
3124                 die(_("bad index version '%s'"), val);
3125         return 0;
3126 }
3127
3128 static int option_parse_unpack_unreachable(const struct option *opt,
3129                                            const char *arg, int unset)
3130 {
3131         if (unset) {
3132                 unpack_unreachable = 0;
3133                 unpack_unreachable_expiration = 0;
3134         }
3135         else {
3136                 unpack_unreachable = 1;
3137                 if (arg)
3138                         unpack_unreachable_expiration = approxidate(arg);
3139         }
3140         return 0;
3141 }
3142
3143 int cmd_pack_objects(int argc, const char **argv, const char *prefix)
3144 {
3145         int use_internal_rev_list = 0;
3146         int thin = 0;
3147         int shallow = 0;
3148         int all_progress_implied = 0;
3149         struct argv_array rp = ARGV_ARRAY_INIT;
3150         int rev_list_unpacked = 0, rev_list_all = 0, rev_list_reflog = 0;
3151         int rev_list_index = 0;
3152         struct string_list keep_pack_list = STRING_LIST_INIT_NODUP;
3153         struct option pack_objects_options[] = {
3154                 OPT_SET_INT('q', "quiet", &progress,
3155                             N_("do not show progress meter"), 0),
3156                 OPT_SET_INT(0, "progress", &progress,
3157                             N_("show progress meter"), 1),
3158                 OPT_SET_INT(0, "all-progress", &progress,
3159                             N_("show progress meter during object writing phase"), 2),
3160                 OPT_BOOL(0, "all-progress-implied",
3161                          &all_progress_implied,
3162                          N_("similar to --all-progress when progress meter is shown")),
3163                 { OPTION_CALLBACK, 0, "index-version", NULL, N_("<version>[,<offset>]"),
3164                   N_("write the pack index file in the specified idx format version"),
3165                   0, option_parse_index_version },
3166                 OPT_MAGNITUDE(0, "max-pack-size", &pack_size_limit,
3167                               N_("maximum size of each output pack file")),
3168                 OPT_BOOL(0, "local", &local,
3169                          N_("ignore borrowed objects from alternate object store")),
3170                 OPT_BOOL(0, "incremental", &incremental,
3171                          N_("ignore packed objects")),
3172                 OPT_INTEGER(0, "window", &window,
3173                             N_("limit pack window by objects")),
3174                 OPT_MAGNITUDE(0, "window-memory", &window_memory_limit,
3175                               N_("limit pack window by memory in addition to object limit")),
3176                 OPT_INTEGER(0, "depth", &depth,
3177                             N_("maximum length of delta chain allowed in the resulting pack")),
3178                 OPT_BOOL(0, "reuse-delta", &reuse_delta,
3179                          N_("reuse existing deltas")),
3180                 OPT_BOOL(0, "reuse-object", &reuse_object,
3181                          N_("reuse existing objects")),
3182                 OPT_BOOL(0, "delta-base-offset", &allow_ofs_delta,
3183                          N_("use OFS_DELTA objects")),
3184                 OPT_INTEGER(0, "threads", &delta_search_threads,
3185                             N_("use threads when searching for best delta matches")),
3186                 OPT_BOOL(0, "non-empty", &non_empty,
3187                          N_("do not create an empty pack output")),
3188                 OPT_BOOL(0, "revs", &use_internal_rev_list,
3189                          N_("read revision arguments from standard input")),
3190                 OPT_SET_INT_F(0, "unpacked", &rev_list_unpacked,
3191                               N_("limit the objects to those that are not yet packed"),
3192                               1, PARSE_OPT_NONEG),
3193                 OPT_SET_INT_F(0, "all", &rev_list_all,
3194                               N_("include objects reachable from any reference"),
3195                               1, PARSE_OPT_NONEG),
3196                 OPT_SET_INT_F(0, "reflog", &rev_list_reflog,
3197                               N_("include objects referred by reflog entries"),
3198                               1, PARSE_OPT_NONEG),
3199                 OPT_SET_INT_F(0, "indexed-objects", &rev_list_index,
3200                               N_("include objects referred to by the index"),
3201                               1, PARSE_OPT_NONEG),
3202                 OPT_BOOL(0, "stdout", &pack_to_stdout,
3203                          N_("output pack to stdout")),
3204                 OPT_BOOL(0, "include-tag", &include_tag,
3205                          N_("include tag objects that refer to objects to be packed")),
3206                 OPT_BOOL(0, "keep-unreachable", &keep_unreachable,
3207                          N_("keep unreachable objects")),
3208                 OPT_BOOL(0, "pack-loose-unreachable", &pack_loose_unreachable,
3209                          N_("pack loose unreachable objects")),
3210                 { OPTION_CALLBACK, 0, "unpack-unreachable", NULL, N_("time"),
3211                   N_("unpack unreachable objects newer than <time>"),
3212                   PARSE_OPT_OPTARG, option_parse_unpack_unreachable },
3213                 OPT_BOOL(0, "thin", &thin,
3214                          N_("create thin packs")),
3215                 OPT_BOOL(0, "shallow", &shallow,
3216                          N_("create packs suitable for shallow fetches")),
3217                 OPT_BOOL(0, "honor-pack-keep", &ignore_packed_keep_on_disk,
3218                          N_("ignore packs that have companion .keep file")),
3219                 OPT_STRING_LIST(0, "keep-pack", &keep_pack_list, N_("name"),
3220                                 N_("ignore this pack")),
3221                 OPT_INTEGER(0, "compression", &pack_compression_level,
3222                             N_("pack compression level")),
3223                 OPT_SET_INT(0, "keep-true-parents", &grafts_replace_parents,
3224                             N_("do not hide commits by grafts"), 0),
3225                 OPT_BOOL(0, "use-bitmap-index", &use_bitmap_index,
3226                          N_("use a bitmap index if available to speed up counting objects")),
3227                 OPT_BOOL(0, "write-bitmap-index", &write_bitmap_index,
3228                          N_("write a bitmap index together with the pack index")),
3229                 OPT_PARSE_LIST_OBJECTS_FILTER(&filter_options),
3230                 { OPTION_CALLBACK, 0, "missing", NULL, N_("action"),
3231                   N_("handling for missing objects"), PARSE_OPT_NONEG,
3232                   option_parse_missing_action },
3233                 OPT_BOOL(0, "exclude-promisor-objects", &exclude_promisor_objects,
3234                          N_("do not pack objects in promisor packfiles")),
3235                 OPT_END(),
3236         };
3237
3238         if (DFS_NUM_STATES > (1 << OE_DFS_STATE_BITS))
3239                 BUG("too many dfs states, increase OE_DFS_STATE_BITS");
3240
3241         read_replace_refs = 0;
3242
3243         reset_pack_idx_option(&pack_idx_opts);
3244         git_config(git_pack_config, NULL);
3245
3246         progress = isatty(2);
3247         argc = parse_options(argc, argv, prefix, pack_objects_options,
3248                              pack_usage, 0);
3249
3250         if (argc) {
3251                 base_name = argv[0];
3252                 argc--;
3253         }
3254         if (pack_to_stdout != !base_name || argc)
3255                 usage_with_options(pack_usage, pack_objects_options);
3256
3257         if (depth >= (1 << OE_DEPTH_BITS)) {
3258                 warning(_("delta chain depth %d is too deep, forcing %d"),
3259                         depth, (1 << OE_DEPTH_BITS) - 1);
3260                 depth = (1 << OE_DEPTH_BITS) - 1;
3261         }
3262         if (cache_max_small_delta_size >= (1U << OE_Z_DELTA_BITS)) {
3263                 warning(_("pack.deltaCacheLimit is too high, forcing %d"),
3264                         (1U << OE_Z_DELTA_BITS) - 1);
3265                 cache_max_small_delta_size = (1U << OE_Z_DELTA_BITS) - 1;
3266         }
3267
3268         argv_array_push(&rp, "pack-objects");
3269         if (thin) {
3270                 use_internal_rev_list = 1;
3271                 argv_array_push(&rp, shallow
3272                                 ? "--objects-edge-aggressive"
3273                                 : "--objects-edge");
3274         } else
3275                 argv_array_push(&rp, "--objects");
3276
3277         if (rev_list_all) {
3278                 use_internal_rev_list = 1;
3279                 argv_array_push(&rp, "--all");
3280         }
3281         if (rev_list_reflog) {
3282                 use_internal_rev_list = 1;
3283                 argv_array_push(&rp, "--reflog");
3284         }
3285         if (rev_list_index) {
3286                 use_internal_rev_list = 1;
3287                 argv_array_push(&rp, "--indexed-objects");
3288         }
3289         if (rev_list_unpacked) {
3290                 use_internal_rev_list = 1;
3291                 argv_array_push(&rp, "--unpacked");
3292         }
3293
3294         if (exclude_promisor_objects) {
3295                 use_internal_rev_list = 1;
3296                 fetch_if_missing = 0;
3297                 argv_array_push(&rp, "--exclude-promisor-objects");
3298         }
3299         if (unpack_unreachable || keep_unreachable || pack_loose_unreachable)
3300                 use_internal_rev_list = 1;
3301
3302         if (!reuse_object)
3303                 reuse_delta = 0;
3304         if (pack_compression_level == -1)
3305                 pack_compression_level = Z_DEFAULT_COMPRESSION;
3306         else if (pack_compression_level < 0 || pack_compression_level > Z_BEST_COMPRESSION)
3307                 die(_("bad pack compression level %d"), pack_compression_level);
3308
3309         if (!delta_search_threads)      /* --threads=0 means autodetect */
3310                 delta_search_threads = online_cpus();
3311
3312 #ifdef NO_PTHREADS
3313         if (delta_search_threads != 1)
3314                 warning(_("no threads support, ignoring --threads"));
3315 #endif
3316         if (!pack_to_stdout && !pack_size_limit)
3317                 pack_size_limit = pack_size_limit_cfg;
3318         if (pack_to_stdout && pack_size_limit)
3319                 die(_("--max-pack-size cannot be used to build a pack for transfer"));
3320         if (pack_size_limit && pack_size_limit < 1024*1024) {
3321                 warning(_("minimum pack size limit is 1 MiB"));
3322                 pack_size_limit = 1024*1024;
3323         }
3324
3325         if (!pack_to_stdout && thin)
3326                 die(_("--thin cannot be used to build an indexable pack"));
3327
3328         if (keep_unreachable && unpack_unreachable)
3329                 die(_("--keep-unreachable and --unpack-unreachable are incompatible"));
3330         if (!rev_list_all || !rev_list_reflog || !rev_list_index)
3331                 unpack_unreachable_expiration = 0;
3332
3333         if (filter_options.choice) {
3334                 if (!pack_to_stdout)
3335                         die(_("cannot use --filter without --stdout"));
3336                 use_bitmap_index = 0;
3337         }
3338
3339         /*
3340          * "soft" reasons not to use bitmaps - for on-disk repack by default we want
3341          *
3342          * - to produce good pack (with bitmap index not-yet-packed objects are
3343          *   packed in suboptimal order).
3344          *
3345          * - to use more robust pack-generation codepath (avoiding possible
3346          *   bugs in bitmap code and possible bitmap index corruption).
3347          */
3348         if (!pack_to_stdout)
3349                 use_bitmap_index_default = 0;
3350
3351         if (use_bitmap_index < 0)
3352                 use_bitmap_index = use_bitmap_index_default;
3353
3354         /* "hard" reasons not to use bitmaps; these just won't work at all */
3355         if (!use_internal_rev_list || (!pack_to_stdout && write_bitmap_index) || is_repository_shallow(the_repository))
3356                 use_bitmap_index = 0;
3357
3358         if (pack_to_stdout || !rev_list_all)
3359                 write_bitmap_index = 0;
3360
3361         if (progress && all_progress_implied)
3362                 progress = 2;
3363
3364         add_extra_kept_packs(&keep_pack_list);
3365         if (ignore_packed_keep_on_disk) {
3366                 struct packed_git *p;
3367                 for (p = get_all_packs(the_repository); p; p = p->next)
3368                         if (p->pack_local && p->pack_keep)
3369                                 break;
3370                 if (!p) /* no keep-able packs found */
3371                         ignore_packed_keep_on_disk = 0;
3372         }
3373         if (local) {
3374                 /*
3375                  * unlike ignore_packed_keep_on_disk above, we do not
3376                  * want to unset "local" based on looking at packs, as
3377                  * it also covers non-local objects
3378                  */
3379                 struct packed_git *p;
3380                 for (p = get_all_packs(the_repository); p; p = p->next) {
3381                         if (!p->pack_local) {
3382                                 have_non_local_packs = 1;
3383                                 break;
3384                         }
3385                 }
3386         }
3387
3388         prepare_packing_data(&to_pack);
3389
3390         if (progress)
3391                 progress_state = start_progress(_("Enumerating objects"), 0);
3392         if (!use_internal_rev_list)
3393                 read_object_list_from_stdin();
3394         else {
3395                 get_object_list(rp.argc, rp.argv);
3396                 argv_array_clear(&rp);
3397         }
3398         cleanup_preferred_base();
3399         if (include_tag && nr_result)
3400                 for_each_ref(add_ref_tag, NULL);
3401         stop_progress(&progress_state);
3402
3403         if (non_empty && !nr_result)
3404                 return 0;
3405         if (nr_result)
3406                 prepare_pack(window, depth);
3407         write_pack_file();
3408         if (progress)
3409                 fprintf_ln(stderr,
3410                            _("Total %"PRIu32" (delta %"PRIu32"),"
3411                              " reused %"PRIu32" (delta %"PRIu32")"),
3412                            written, written_delta, reused, reused_delta);
3413         return 0;
3414 }