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