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