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