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