Merge branch 'kw/fsmonitor-watchman-racefix'
[git] / builtin / pack-objects.c
1 #include "builtin.h"
2 #include "cache.h"
3 #include "repository.h"
4 #include "config.h"
5 #include "attr.h"
6 #include "object.h"
7 #include "blob.h"
8 #include "commit.h"
9 #include "tag.h"
10 #include "tree.h"
11 #include "delta.h"
12 #include "pack.h"
13 #include "pack-revindex.h"
14 #include "csum-file.h"
15 #include "tree-walk.h"
16 #include "diff.h"
17 #include "revision.h"
18 #include "list-objects.h"
19 #include "list-objects-filter.h"
20 #include "list-objects-filter-options.h"
21 #include "pack-objects.h"
22 #include "progress.h"
23 #include "refs.h"
24 #include "streaming.h"
25 #include "thread-utils.h"
26 #include "pack-bitmap.h"
27 #include "delta-islands.h"
28 #include "reachable.h"
29 #include "sha1-array.h"
30 #include "argv-array.h"
31 #include "list.h"
32 #include "packfile.h"
33 #include "object-store.h"
34 #include "dir.h"
35 #include "midx.h"
36 #include "trace2.h"
37
38 #define IN_PACK(obj) oe_in_pack(&to_pack, obj)
39 #define SIZE(obj) oe_size(&to_pack, obj)
40 #define SET_SIZE(obj,size) oe_set_size(&to_pack, obj, size)
41 #define DELTA_SIZE(obj) oe_delta_size(&to_pack, obj)
42 #define DELTA(obj) oe_delta(&to_pack, obj)
43 #define DELTA_CHILD(obj) oe_delta_child(&to_pack, obj)
44 #define DELTA_SIBLING(obj) oe_delta_sibling(&to_pack, obj)
45 #define SET_DELTA(obj, val) oe_set_delta(&to_pack, obj, val)
46 #define SET_DELTA_EXT(obj, oid) oe_set_delta_ext(&to_pack, obj, oid)
47 #define SET_DELTA_SIZE(obj, val) oe_set_delta_size(&to_pack, obj, val)
48 #define SET_DELTA_CHILD(obj, val) oe_set_delta_child(&to_pack, obj, val)
49 #define SET_DELTA_SIBLING(obj, val) oe_set_delta_sibling(&to_pack, obj, val)
50
51 static const char *pack_usage[] = {
52         N_("git pack-objects --stdout [<options>...] [< <ref-list> | < <object-list>]"),
53         N_("git pack-objects [<options>...] <base-name> [< <ref-list> | < <object-list>]"),
54         NULL
55 };
56
57 /*
58  * Objects we are going to pack are collected in the `to_pack` structure.
59  * It contains an array (dynamically expanded) of the object data, and a map
60  * that can resolve SHA1s to their position in the array.
61  */
62 static struct packing_data to_pack;
63
64 static struct pack_idx_entry **written_list;
65 static uint32_t nr_result, nr_written, nr_seen;
66 static struct bitmap_index *bitmap_git;
67 static uint32_t write_layer;
68
69 static int non_empty;
70 static int reuse_delta = 1, reuse_object = 1;
71 static int keep_unreachable, unpack_unreachable, include_tag;
72 static timestamp_t unpack_unreachable_expiration;
73 static int pack_loose_unreachable;
74 static int local;
75 static int have_non_local_packs;
76 static int incremental;
77 static int ignore_packed_keep_on_disk;
78 static int ignore_packed_keep_in_core;
79 static int allow_ofs_delta;
80 static struct pack_idx_option pack_idx_opts;
81 static const char *base_name;
82 static int progress = 1;
83 static int window = 10;
84 static unsigned long pack_size_limit;
85 static int depth = 50;
86 static int delta_search_threads;
87 static int pack_to_stdout;
88 static int sparse;
89 static int thin;
90 static int num_preferred_base;
91 static struct progress *progress_state;
92
93 static struct packed_git *reuse_packfile;
94 static uint32_t reuse_packfile_objects;
95 static struct bitmap *reuse_packfile_bitmap;
96
97 static int use_bitmap_index_default = 1;
98 static int use_bitmap_index = -1;
99 static int allow_pack_reuse = 1;
100 static enum {
101         WRITE_BITMAP_FALSE = 0,
102         WRITE_BITMAP_QUIET,
103         WRITE_BITMAP_TRUE,
104 } write_bitmap_index;
105 static uint16_t write_bitmap_options = BITMAP_OPT_HASH_CACHE;
106
107 static int exclude_promisor_objects;
108
109 static int use_delta_islands;
110
111 static unsigned long delta_cache_size = 0;
112 static unsigned long max_delta_cache_size = DEFAULT_DELTA_CACHE_SIZE;
113 static unsigned long cache_max_small_delta_size = 1000;
114
115 static unsigned long window_memory_limit = 0;
116
117 static struct list_objects_filter_options filter_options;
118
119 enum missing_action {
120         MA_ERROR = 0,      /* fail if any missing objects are encountered */
121         MA_ALLOW_ANY,      /* silently allow ALL missing objects */
122         MA_ALLOW_PROMISOR, /* silently allow all missing PROMISOR objects */
123 };
124 static enum missing_action arg_missing_action;
125 static show_object_fn fn_show_object;
126
127 /*
128  * stats
129  */
130 static uint32_t written, written_delta;
131 static uint32_t reused, reused_delta;
132
133 /*
134  * Indexed commits
135  */
136 static struct commit **indexed_commits;
137 static unsigned int indexed_commits_nr;
138 static unsigned int indexed_commits_alloc;
139
140 static void index_commit_for_bitmap(struct commit *commit)
141 {
142         if (indexed_commits_nr >= indexed_commits_alloc) {
143                 indexed_commits_alloc = (indexed_commits_alloc + 32) * 2;
144                 REALLOC_ARRAY(indexed_commits, indexed_commits_alloc);
145         }
146
147         indexed_commits[indexed_commits_nr++] = commit;
148 }
149
150 static void *get_delta(struct object_entry *entry)
151 {
152         unsigned long size, base_size, delta_size;
153         void *buf, *base_buf, *delta_buf;
154         enum object_type type;
155
156         buf = read_object_file(&entry->idx.oid, &type, &size);
157         if (!buf)
158                 die(_("unable to read %s"), oid_to_hex(&entry->idx.oid));
159         base_buf = read_object_file(&DELTA(entry)->idx.oid, &type,
160                                     &base_size);
161         if (!base_buf)
162                 die("unable to read %s",
163                     oid_to_hex(&DELTA(entry)->idx.oid));
164         delta_buf = diff_delta(base_buf, base_size,
165                                buf, size, &delta_size, 0);
166         /*
167          * We successfully computed this delta once but dropped it for
168          * memory reasons. Something is very wrong if this time we
169          * recompute and create a different delta.
170          */
171         if (!delta_buf || delta_size != DELTA_SIZE(entry))
172                 BUG("delta size changed");
173         free(buf);
174         free(base_buf);
175         return delta_buf;
176 }
177
178 static unsigned long do_compress(void **pptr, unsigned long size)
179 {
180         git_zstream stream;
181         void *in, *out;
182         unsigned long maxsize;
183
184         git_deflate_init(&stream, pack_compression_level);
185         maxsize = git_deflate_bound(&stream, size);
186
187         in = *pptr;
188         out = xmalloc(maxsize);
189         *pptr = out;
190
191         stream.next_in = in;
192         stream.avail_in = size;
193         stream.next_out = out;
194         stream.avail_out = maxsize;
195         while (git_deflate(&stream, Z_FINISH) == Z_OK)
196                 ; /* nothing */
197         git_deflate_end(&stream);
198
199         free(in);
200         return stream.total_out;
201 }
202
203 static unsigned long write_large_blob_data(struct git_istream *st, struct hashfile *f,
204                                            const struct object_id *oid)
205 {
206         git_zstream stream;
207         unsigned char ibuf[1024 * 16];
208         unsigned char obuf[1024 * 16];
209         unsigned long olen = 0;
210
211         git_deflate_init(&stream, pack_compression_level);
212
213         for (;;) {
214                 ssize_t readlen;
215                 int zret = Z_OK;
216                 readlen = read_istream(st, ibuf, sizeof(ibuf));
217                 if (readlen == -1)
218                         die(_("unable to read %s"), oid_to_hex(oid));
219
220                 stream.next_in = ibuf;
221                 stream.avail_in = readlen;
222                 while ((stream.avail_in || readlen == 0) &&
223                        (zret == Z_OK || zret == Z_BUF_ERROR)) {
224                         stream.next_out = obuf;
225                         stream.avail_out = sizeof(obuf);
226                         zret = git_deflate(&stream, readlen ? 0 : Z_FINISH);
227                         hashwrite(f, obuf, stream.next_out - obuf);
228                         olen += stream.next_out - obuf;
229                 }
230                 if (stream.avail_in)
231                         die(_("deflate error (%d)"), zret);
232                 if (readlen == 0) {
233                         if (zret != Z_STREAM_END)
234                                 die(_("deflate error (%d)"), zret);
235                         break;
236                 }
237         }
238         git_deflate_end(&stream);
239         return olen;
240 }
241
242 /*
243  * we are going to reuse the existing object data as is.  make
244  * sure it is not corrupt.
245  */
246 static int check_pack_inflate(struct packed_git *p,
247                 struct pack_window **w_curs,
248                 off_t offset,
249                 off_t len,
250                 unsigned long expect)
251 {
252         git_zstream stream;
253         unsigned char fakebuf[4096], *in;
254         int st;
255
256         memset(&stream, 0, sizeof(stream));
257         git_inflate_init(&stream);
258         do {
259                 in = use_pack(p, w_curs, offset, &stream.avail_in);
260                 stream.next_in = in;
261                 stream.next_out = fakebuf;
262                 stream.avail_out = sizeof(fakebuf);
263                 st = git_inflate(&stream, Z_FINISH);
264                 offset += stream.next_in - in;
265         } while (st == Z_OK || st == Z_BUF_ERROR);
266         git_inflate_end(&stream);
267         return (st == Z_STREAM_END &&
268                 stream.total_out == expect &&
269                 stream.total_in == len) ? 0 : -1;
270 }
271
272 static void copy_pack_data(struct hashfile *f,
273                 struct packed_git *p,
274                 struct pack_window **w_curs,
275                 off_t offset,
276                 off_t len)
277 {
278         unsigned char *in;
279         unsigned long avail;
280
281         while (len) {
282                 in = use_pack(p, w_curs, offset, &avail);
283                 if (avail > len)
284                         avail = (unsigned long)len;
285                 hashwrite(f, in, avail);
286                 offset += avail;
287                 len -= avail;
288         }
289 }
290
291 /* Return 0 if we will bust the pack-size limit */
292 static unsigned long write_no_reuse_object(struct hashfile *f, struct object_entry *entry,
293                                            unsigned long limit, int usable_delta)
294 {
295         unsigned long size, datalen;
296         unsigned char header[MAX_PACK_OBJECT_HEADER],
297                       dheader[MAX_PACK_OBJECT_HEADER];
298         unsigned hdrlen;
299         enum object_type type;
300         void *buf;
301         struct git_istream *st = NULL;
302         const unsigned hashsz = the_hash_algo->rawsz;
303
304         if (!usable_delta) {
305                 if (oe_type(entry) == OBJ_BLOB &&
306                     oe_size_greater_than(&to_pack, entry, big_file_threshold) &&
307                     (st = open_istream(&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);
615
616         if (entry)
617                 entry->tagged = 1;
618         if (!peel_ref(path, &peeled)) {
619                 entry = packlist_find(&to_pack, &peeled);
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 {
1128         struct object_entry *entry;
1129
1130         if (reuse_packfile_bitmap &&
1131             bitmap_walk_contains(bitmap_git, reuse_packfile_bitmap, oid))
1132                 return 1;
1133
1134         entry = packlist_find(&to_pack, oid);
1135         if (!entry)
1136                 return 0;
1137
1138         if (exclude) {
1139                 if (!entry->preferred_base)
1140                         nr_result--;
1141                 entry->preferred_base = 1;
1142         }
1143
1144         return 1;
1145 }
1146
1147 static int want_found_object(int exclude, struct packed_git *p)
1148 {
1149         if (exclude)
1150                 return 1;
1151         if (incremental)
1152                 return 0;
1153
1154         /*
1155          * When asked to do --local (do not include an object that appears in a
1156          * pack we borrow from elsewhere) or --honor-pack-keep (do not include
1157          * an object that appears in a pack marked with .keep), finding a pack
1158          * that matches the criteria is sufficient for us to decide to omit it.
1159          * However, even if this pack does not satisfy the criteria, we need to
1160          * make sure no copy of this object appears in _any_ pack that makes us
1161          * to omit the object, so we need to check all the packs.
1162          *
1163          * We can however first check whether these options can possible matter;
1164          * if they do not matter we know we want the object in generated pack.
1165          * Otherwise, we signal "-1" at the end to tell the caller that we do
1166          * not know either way, and it needs to check more packs.
1167          */
1168         if (!ignore_packed_keep_on_disk &&
1169             !ignore_packed_keep_in_core &&
1170             (!local || !have_non_local_packs))
1171                 return 1;
1172
1173         if (local && !p->pack_local)
1174                 return 0;
1175         if (p->pack_local &&
1176             ((ignore_packed_keep_on_disk && p->pack_keep) ||
1177              (ignore_packed_keep_in_core && p->pack_keep_in_core)))
1178                 return 0;
1179
1180         /* we don't know yet; keep looking for more packs */
1181         return -1;
1182 }
1183
1184 /*
1185  * Check whether we want the object in the pack (e.g., we do not want
1186  * objects found in non-local stores if the "--local" option was used).
1187  *
1188  * If the caller already knows an existing pack it wants to take the object
1189  * from, that is passed in *found_pack and *found_offset; otherwise this
1190  * function finds if there is any pack that has the object and returns the pack
1191  * and its offset in these variables.
1192  */
1193 static int want_object_in_pack(const struct object_id *oid,
1194                                int exclude,
1195                                struct packed_git **found_pack,
1196                                off_t *found_offset)
1197 {
1198         int want;
1199         struct list_head *pos;
1200         struct multi_pack_index *m;
1201
1202         if (!exclude && local && has_loose_object_nonlocal(oid))
1203                 return 0;
1204
1205         /*
1206          * If we already know the pack object lives in, start checks from that
1207          * pack - in the usual case when neither --local was given nor .keep files
1208          * are present we will determine the answer right now.
1209          */
1210         if (*found_pack) {
1211                 want = want_found_object(exclude, *found_pack);
1212                 if (want != -1)
1213                         return want;
1214         }
1215
1216         for (m = get_multi_pack_index(the_repository); m; m = m->next) {
1217                 struct pack_entry e;
1218                 if (fill_midx_entry(the_repository, oid, &e, m)) {
1219                         struct packed_git *p = e.p;
1220                         off_t offset;
1221
1222                         if (p == *found_pack)
1223                                 offset = *found_offset;
1224                         else
1225                                 offset = find_pack_entry_one(oid->hash, p);
1226
1227                         if (offset) {
1228                                 if (!*found_pack) {
1229                                         if (!is_pack_valid(p))
1230                                                 continue;
1231                                         *found_offset = offset;
1232                                         *found_pack = p;
1233                                 }
1234                                 want = want_found_object(exclude, p);
1235                                 if (want != -1)
1236                                         return want;
1237                         }
1238                 }
1239         }
1240
1241         list_for_each(pos, get_packed_git_mru(the_repository)) {
1242                 struct packed_git *p = list_entry(pos, struct packed_git, mru);
1243                 off_t offset;
1244
1245                 if (p == *found_pack)
1246                         offset = *found_offset;
1247                 else
1248                         offset = find_pack_entry_one(oid->hash, p);
1249
1250                 if (offset) {
1251                         if (!*found_pack) {
1252                                 if (!is_pack_valid(p))
1253                                         continue;
1254                                 *found_offset = offset;
1255                                 *found_pack = p;
1256                         }
1257                         want = want_found_object(exclude, p);
1258                         if (!exclude && want > 0)
1259                                 list_move(&p->mru,
1260                                           get_packed_git_mru(the_repository));
1261                         if (want != -1)
1262                                 return want;
1263                 }
1264         }
1265
1266         return 1;
1267 }
1268
1269 static void create_object_entry(const struct object_id *oid,
1270                                 enum object_type type,
1271                                 uint32_t hash,
1272                                 int exclude,
1273                                 int no_try_delta,
1274                                 struct packed_git *found_pack,
1275                                 off_t found_offset)
1276 {
1277         struct object_entry *entry;
1278
1279         entry = packlist_alloc(&to_pack, oid);
1280         entry->hash = hash;
1281         oe_set_type(entry, type);
1282         if (exclude)
1283                 entry->preferred_base = 1;
1284         else
1285                 nr_result++;
1286         if (found_pack) {
1287                 oe_set_in_pack(&to_pack, entry, found_pack);
1288                 entry->in_pack_offset = found_offset;
1289         }
1290
1291         entry->no_try_delta = no_try_delta;
1292 }
1293
1294 static const char no_closure_warning[] = N_(
1295 "disabling bitmap writing, as some objects are not being packed"
1296 );
1297
1298 static int add_object_entry(const struct object_id *oid, enum object_type type,
1299                             const char *name, int exclude)
1300 {
1301         struct packed_git *found_pack = NULL;
1302         off_t found_offset = 0;
1303
1304         display_progress(progress_state, ++nr_seen);
1305
1306         if (have_duplicate_entry(oid, exclude))
1307                 return 0;
1308
1309         if (!want_object_in_pack(oid, exclude, &found_pack, &found_offset)) {
1310                 /* The pack is missing an object, so it will not have closure */
1311                 if (write_bitmap_index) {
1312                         if (write_bitmap_index != WRITE_BITMAP_QUIET)
1313                                 warning(_(no_closure_warning));
1314                         write_bitmap_index = 0;
1315                 }
1316                 return 0;
1317         }
1318
1319         create_object_entry(oid, type, pack_name_hash(name),
1320                             exclude, name && no_try_delta(name),
1321                             found_pack, found_offset);
1322         return 1;
1323 }
1324
1325 static int add_object_entry_from_bitmap(const struct object_id *oid,
1326                                         enum object_type type,
1327                                         int flags, uint32_t name_hash,
1328                                         struct packed_git *pack, off_t offset)
1329 {
1330         display_progress(progress_state, ++nr_seen);
1331
1332         if (have_duplicate_entry(oid, 0))
1333                 return 0;
1334
1335         if (!want_object_in_pack(oid, 0, &pack, &offset))
1336                 return 0;
1337
1338         create_object_entry(oid, type, name_hash, 0, 0, pack, offset);
1339         return 1;
1340 }
1341
1342 struct pbase_tree_cache {
1343         struct object_id oid;
1344         int ref;
1345         int temporary;
1346         void *tree_data;
1347         unsigned long tree_size;
1348 };
1349
1350 static struct pbase_tree_cache *(pbase_tree_cache[256]);
1351 static int pbase_tree_cache_ix(const struct object_id *oid)
1352 {
1353         return oid->hash[0] % ARRAY_SIZE(pbase_tree_cache);
1354 }
1355 static int pbase_tree_cache_ix_incr(int ix)
1356 {
1357         return (ix+1) % ARRAY_SIZE(pbase_tree_cache);
1358 }
1359
1360 static struct pbase_tree {
1361         struct pbase_tree *next;
1362         /* This is a phony "cache" entry; we are not
1363          * going to evict it or find it through _get()
1364          * mechanism -- this is for the toplevel node that
1365          * would almost always change with any commit.
1366          */
1367         struct pbase_tree_cache pcache;
1368 } *pbase_tree;
1369
1370 static struct pbase_tree_cache *pbase_tree_get(const struct object_id *oid)
1371 {
1372         struct pbase_tree_cache *ent, *nent;
1373         void *data;
1374         unsigned long size;
1375         enum object_type type;
1376         int neigh;
1377         int my_ix = pbase_tree_cache_ix(oid);
1378         int available_ix = -1;
1379
1380         /* pbase-tree-cache acts as a limited hashtable.
1381          * your object will be found at your index or within a few
1382          * slots after that slot if it is cached.
1383          */
1384         for (neigh = 0; neigh < 8; neigh++) {
1385                 ent = pbase_tree_cache[my_ix];
1386                 if (ent && oideq(&ent->oid, oid)) {
1387                         ent->ref++;
1388                         return ent;
1389                 }
1390                 else if (((available_ix < 0) && (!ent || !ent->ref)) ||
1391                          ((0 <= available_ix) &&
1392                           (!ent && pbase_tree_cache[available_ix])))
1393                         available_ix = my_ix;
1394                 if (!ent)
1395                         break;
1396                 my_ix = pbase_tree_cache_ix_incr(my_ix);
1397         }
1398
1399         /* Did not find one.  Either we got a bogus request or
1400          * we need to read and perhaps cache.
1401          */
1402         data = read_object_file(oid, &type, &size);
1403         if (!data)
1404                 return NULL;
1405         if (type != OBJ_TREE) {
1406                 free(data);
1407                 return NULL;
1408         }
1409
1410         /* We need to either cache or return a throwaway copy */
1411
1412         if (available_ix < 0)
1413                 ent = NULL;
1414         else {
1415                 ent = pbase_tree_cache[available_ix];
1416                 my_ix = available_ix;
1417         }
1418
1419         if (!ent) {
1420                 nent = xmalloc(sizeof(*nent));
1421                 nent->temporary = (available_ix < 0);
1422         }
1423         else {
1424                 /* evict and reuse */
1425                 free(ent->tree_data);
1426                 nent = ent;
1427         }
1428         oidcpy(&nent->oid, oid);
1429         nent->tree_data = data;
1430         nent->tree_size = size;
1431         nent->ref = 1;
1432         if (!nent->temporary)
1433                 pbase_tree_cache[my_ix] = nent;
1434         return nent;
1435 }
1436
1437 static void pbase_tree_put(struct pbase_tree_cache *cache)
1438 {
1439         if (!cache->temporary) {
1440                 cache->ref--;
1441                 return;
1442         }
1443         free(cache->tree_data);
1444         free(cache);
1445 }
1446
1447 static int name_cmp_len(const char *name)
1448 {
1449         int i;
1450         for (i = 0; name[i] && name[i] != '\n' && name[i] != '/'; i++)
1451                 ;
1452         return i;
1453 }
1454
1455 static void add_pbase_object(struct tree_desc *tree,
1456                              const char *name,
1457                              int cmplen,
1458                              const char *fullname)
1459 {
1460         struct name_entry entry;
1461         int cmp;
1462
1463         while (tree_entry(tree,&entry)) {
1464                 if (S_ISGITLINK(entry.mode))
1465                         continue;
1466                 cmp = tree_entry_len(&entry) != cmplen ? 1 :
1467                       memcmp(name, entry.path, cmplen);
1468                 if (cmp > 0)
1469                         continue;
1470                 if (cmp < 0)
1471                         return;
1472                 if (name[cmplen] != '/') {
1473                         add_object_entry(&entry.oid,
1474                                          object_type(entry.mode),
1475                                          fullname, 1);
1476                         return;
1477                 }
1478                 if (S_ISDIR(entry.mode)) {
1479                         struct tree_desc sub;
1480                         struct pbase_tree_cache *tree;
1481                         const char *down = name+cmplen+1;
1482                         int downlen = name_cmp_len(down);
1483
1484                         tree = pbase_tree_get(&entry.oid);
1485                         if (!tree)
1486                                 return;
1487                         init_tree_desc(&sub, tree->tree_data, tree->tree_size);
1488
1489                         add_pbase_object(&sub, down, downlen, fullname);
1490                         pbase_tree_put(tree);
1491                 }
1492         }
1493 }
1494
1495 static unsigned *done_pbase_paths;
1496 static int done_pbase_paths_num;
1497 static int done_pbase_paths_alloc;
1498 static int done_pbase_path_pos(unsigned hash)
1499 {
1500         int lo = 0;
1501         int hi = done_pbase_paths_num;
1502         while (lo < hi) {
1503                 int mi = lo + (hi - lo) / 2;
1504                 if (done_pbase_paths[mi] == hash)
1505                         return mi;
1506                 if (done_pbase_paths[mi] < hash)
1507                         hi = mi;
1508                 else
1509                         lo = mi + 1;
1510         }
1511         return -lo-1;
1512 }
1513
1514 static int check_pbase_path(unsigned hash)
1515 {
1516         int pos = done_pbase_path_pos(hash);
1517         if (0 <= pos)
1518                 return 1;
1519         pos = -pos - 1;
1520         ALLOC_GROW(done_pbase_paths,
1521                    done_pbase_paths_num + 1,
1522                    done_pbase_paths_alloc);
1523         done_pbase_paths_num++;
1524         if (pos < done_pbase_paths_num)
1525                 MOVE_ARRAY(done_pbase_paths + pos + 1, done_pbase_paths + pos,
1526                            done_pbase_paths_num - pos - 1);
1527         done_pbase_paths[pos] = hash;
1528         return 0;
1529 }
1530
1531 static void add_preferred_base_object(const char *name)
1532 {
1533         struct pbase_tree *it;
1534         int cmplen;
1535         unsigned hash = pack_name_hash(name);
1536
1537         if (!num_preferred_base || check_pbase_path(hash))
1538                 return;
1539
1540         cmplen = name_cmp_len(name);
1541         for (it = pbase_tree; it; it = it->next) {
1542                 if (cmplen == 0) {
1543                         add_object_entry(&it->pcache.oid, OBJ_TREE, NULL, 1);
1544                 }
1545                 else {
1546                         struct tree_desc tree;
1547                         init_tree_desc(&tree, it->pcache.tree_data, it->pcache.tree_size);
1548                         add_pbase_object(&tree, name, cmplen, name);
1549                 }
1550         }
1551 }
1552
1553 static void add_preferred_base(struct object_id *oid)
1554 {
1555         struct pbase_tree *it;
1556         void *data;
1557         unsigned long size;
1558         struct object_id tree_oid;
1559
1560         if (window <= num_preferred_base++)
1561                 return;
1562
1563         data = read_object_with_reference(the_repository, oid,
1564                                           tree_type, &size, &tree_oid);
1565         if (!data)
1566                 return;
1567
1568         for (it = pbase_tree; it; it = it->next) {
1569                 if (oideq(&it->pcache.oid, &tree_oid)) {
1570                         free(data);
1571                         return;
1572                 }
1573         }
1574
1575         it = xcalloc(1, sizeof(*it));
1576         it->next = pbase_tree;
1577         pbase_tree = it;
1578
1579         oidcpy(&it->pcache.oid, &tree_oid);
1580         it->pcache.tree_data = data;
1581         it->pcache.tree_size = size;
1582 }
1583
1584 static void cleanup_preferred_base(void)
1585 {
1586         struct pbase_tree *it;
1587         unsigned i;
1588
1589         it = pbase_tree;
1590         pbase_tree = NULL;
1591         while (it) {
1592                 struct pbase_tree *tmp = it;
1593                 it = tmp->next;
1594                 free(tmp->pcache.tree_data);
1595                 free(tmp);
1596         }
1597
1598         for (i = 0; i < ARRAY_SIZE(pbase_tree_cache); i++) {
1599                 if (!pbase_tree_cache[i])
1600                         continue;
1601                 free(pbase_tree_cache[i]->tree_data);
1602                 FREE_AND_NULL(pbase_tree_cache[i]);
1603         }
1604
1605         FREE_AND_NULL(done_pbase_paths);
1606         done_pbase_paths_num = done_pbase_paths_alloc = 0;
1607 }
1608
1609 /*
1610  * Return 1 iff the object specified by "delta" can be sent
1611  * literally as a delta against the base in "base_sha1". If
1612  * so, then *base_out will point to the entry in our packing
1613  * list, or NULL if we must use the external-base list.
1614  *
1615  * Depth value does not matter - find_deltas() will
1616  * never consider reused delta as the base object to
1617  * deltify other objects against, in order to avoid
1618  * circular deltas.
1619  */
1620 static int can_reuse_delta(const unsigned char *base_sha1,
1621                            struct object_entry *delta,
1622                            struct object_entry **base_out)
1623 {
1624         struct object_entry *base;
1625         struct object_id base_oid;
1626
1627         if (!base_sha1)
1628                 return 0;
1629
1630         oidread(&base_oid, base_sha1);
1631
1632         /*
1633          * First see if we're already sending the base (or it's explicitly in
1634          * our "excluded" list).
1635          */
1636         base = packlist_find(&to_pack, &base_oid);
1637         if (base) {
1638                 if (!in_same_island(&delta->idx.oid, &base->idx.oid))
1639                         return 0;
1640                 *base_out = base;
1641                 return 1;
1642         }
1643
1644         /*
1645          * Otherwise, reachability bitmaps may tell us if the receiver has it,
1646          * even if it was buried too deep in history to make it into the
1647          * packing list.
1648          */
1649         if (thin && bitmap_has_oid_in_uninteresting(bitmap_git, &base_oid)) {
1650                 if (use_delta_islands) {
1651                         if (!in_same_island(&delta->idx.oid, &base_oid))
1652                                 return 0;
1653                 }
1654                 *base_out = NULL;
1655                 return 1;
1656         }
1657
1658         return 0;
1659 }
1660
1661 static void check_object(struct object_entry *entry)
1662 {
1663         unsigned long canonical_size;
1664
1665         if (IN_PACK(entry)) {
1666                 struct packed_git *p = IN_PACK(entry);
1667                 struct pack_window *w_curs = NULL;
1668                 const unsigned char *base_ref = NULL;
1669                 struct object_entry *base_entry;
1670                 unsigned long used, used_0;
1671                 unsigned long avail;
1672                 off_t ofs;
1673                 unsigned char *buf, c;
1674                 enum object_type type;
1675                 unsigned long in_pack_size;
1676
1677                 buf = use_pack(p, &w_curs, entry->in_pack_offset, &avail);
1678
1679                 /*
1680                  * We want in_pack_type even if we do not reuse delta
1681                  * since non-delta representations could still be reused.
1682                  */
1683                 used = unpack_object_header_buffer(buf, avail,
1684                                                    &type,
1685                                                    &in_pack_size);
1686                 if (used == 0)
1687                         goto give_up;
1688
1689                 if (type < 0)
1690                         BUG("invalid type %d", type);
1691                 entry->in_pack_type = type;
1692
1693                 /*
1694                  * Determine if this is a delta and if so whether we can
1695                  * reuse it or not.  Otherwise let's find out as cheaply as
1696                  * possible what the actual type and size for this object is.
1697                  */
1698                 switch (entry->in_pack_type) {
1699                 default:
1700                         /* Not a delta hence we've already got all we need. */
1701                         oe_set_type(entry, entry->in_pack_type);
1702                         SET_SIZE(entry, in_pack_size);
1703                         entry->in_pack_header_size = used;
1704                         if (oe_type(entry) < OBJ_COMMIT || oe_type(entry) > OBJ_BLOB)
1705                                 goto give_up;
1706                         unuse_pack(&w_curs);
1707                         return;
1708                 case OBJ_REF_DELTA:
1709                         if (reuse_delta && !entry->preferred_base)
1710                                 base_ref = use_pack(p, &w_curs,
1711                                                 entry->in_pack_offset + used, NULL);
1712                         entry->in_pack_header_size = used + the_hash_algo->rawsz;
1713                         break;
1714                 case OBJ_OFS_DELTA:
1715                         buf = use_pack(p, &w_curs,
1716                                        entry->in_pack_offset + used, NULL);
1717                         used_0 = 0;
1718                         c = buf[used_0++];
1719                         ofs = c & 127;
1720                         while (c & 128) {
1721                                 ofs += 1;
1722                                 if (!ofs || MSB(ofs, 7)) {
1723                                         error(_("delta base offset overflow in pack for %s"),
1724                                               oid_to_hex(&entry->idx.oid));
1725                                         goto give_up;
1726                                 }
1727                                 c = buf[used_0++];
1728                                 ofs = (ofs << 7) + (c & 127);
1729                         }
1730                         ofs = entry->in_pack_offset - ofs;
1731                         if (ofs <= 0 || ofs >= entry->in_pack_offset) {
1732                                 error(_("delta base offset out of bound for %s"),
1733                                       oid_to_hex(&entry->idx.oid));
1734                                 goto give_up;
1735                         }
1736                         if (reuse_delta && !entry->preferred_base) {
1737                                 struct revindex_entry *revidx;
1738                                 revidx = find_pack_revindex(p, ofs);
1739                                 if (!revidx)
1740                                         goto give_up;
1741                                 base_ref = nth_packed_object_sha1(p, revidx->nr);
1742                         }
1743                         entry->in_pack_header_size = used + used_0;
1744                         break;
1745                 }
1746
1747                 if (can_reuse_delta(base_ref, entry, &base_entry)) {
1748                         oe_set_type(entry, entry->in_pack_type);
1749                         SET_SIZE(entry, in_pack_size); /* delta size */
1750                         SET_DELTA_SIZE(entry, in_pack_size);
1751
1752                         if (base_entry) {
1753                                 SET_DELTA(entry, base_entry);
1754                                 entry->delta_sibling_idx = base_entry->delta_child_idx;
1755                                 SET_DELTA_CHILD(base_entry, entry);
1756                         } else {
1757                                 SET_DELTA_EXT(entry, base_ref);
1758                         }
1759
1760                         unuse_pack(&w_curs);
1761                         return;
1762                 }
1763
1764                 if (oe_type(entry)) {
1765                         off_t delta_pos;
1766
1767                         /*
1768                          * This must be a delta and we already know what the
1769                          * final object type is.  Let's extract the actual
1770                          * object size from the delta header.
1771                          */
1772                         delta_pos = entry->in_pack_offset + entry->in_pack_header_size;
1773                         canonical_size = get_size_from_delta(p, &w_curs, delta_pos);
1774                         if (canonical_size == 0)
1775                                 goto give_up;
1776                         SET_SIZE(entry, canonical_size);
1777                         unuse_pack(&w_curs);
1778                         return;
1779                 }
1780
1781                 /*
1782                  * No choice but to fall back to the recursive delta walk
1783                  * with oid_object_info() to find about the object type
1784                  * at this point...
1785                  */
1786                 give_up:
1787                 unuse_pack(&w_curs);
1788         }
1789
1790         oe_set_type(entry,
1791                     oid_object_info(the_repository, &entry->idx.oid, &canonical_size));
1792         if (entry->type_valid) {
1793                 SET_SIZE(entry, canonical_size);
1794         } else {
1795                 /*
1796                  * Bad object type is checked in prepare_pack().  This is
1797                  * to permit a missing preferred base object to be ignored
1798                  * as a preferred base.  Doing so can result in a larger
1799                  * pack file, but the transfer will still take place.
1800                  */
1801         }
1802 }
1803
1804 static int pack_offset_sort(const void *_a, const void *_b)
1805 {
1806         const struct object_entry *a = *(struct object_entry **)_a;
1807         const struct object_entry *b = *(struct object_entry **)_b;
1808         const struct packed_git *a_in_pack = IN_PACK(a);
1809         const struct packed_git *b_in_pack = IN_PACK(b);
1810
1811         /* avoid filesystem trashing with loose objects */
1812         if (!a_in_pack && !b_in_pack)
1813                 return oidcmp(&a->idx.oid, &b->idx.oid);
1814
1815         if (a_in_pack < b_in_pack)
1816                 return -1;
1817         if (a_in_pack > b_in_pack)
1818                 return 1;
1819         return a->in_pack_offset < b->in_pack_offset ? -1 :
1820                         (a->in_pack_offset > b->in_pack_offset);
1821 }
1822
1823 /*
1824  * Drop an on-disk delta we were planning to reuse. Naively, this would
1825  * just involve blanking out the "delta" field, but we have to deal
1826  * with some extra book-keeping:
1827  *
1828  *   1. Removing ourselves from the delta_sibling linked list.
1829  *
1830  *   2. Updating our size/type to the non-delta representation. These were
1831  *      either not recorded initially (size) or overwritten with the delta type
1832  *      (type) when check_object() decided to reuse the delta.
1833  *
1834  *   3. Resetting our delta depth, as we are now a base object.
1835  */
1836 static void drop_reused_delta(struct object_entry *entry)
1837 {
1838         unsigned *idx = &to_pack.objects[entry->delta_idx - 1].delta_child_idx;
1839         struct object_info oi = OBJECT_INFO_INIT;
1840         enum object_type type;
1841         unsigned long size;
1842
1843         while (*idx) {
1844                 struct object_entry *oe = &to_pack.objects[*idx - 1];
1845
1846                 if (oe == entry)
1847                         *idx = oe->delta_sibling_idx;
1848                 else
1849                         idx = &oe->delta_sibling_idx;
1850         }
1851         SET_DELTA(entry, NULL);
1852         entry->depth = 0;
1853
1854         oi.sizep = &size;
1855         oi.typep = &type;
1856         if (packed_object_info(the_repository, IN_PACK(entry), entry->in_pack_offset, &oi) < 0) {
1857                 /*
1858                  * We failed to get the info from this pack for some reason;
1859                  * fall back to oid_object_info, which may find another copy.
1860                  * And if that fails, the error will be recorded in oe_type(entry)
1861                  * and dealt with in prepare_pack().
1862                  */
1863                 oe_set_type(entry,
1864                             oid_object_info(the_repository, &entry->idx.oid, &size));
1865         } else {
1866                 oe_set_type(entry, type);
1867         }
1868         SET_SIZE(entry, size);
1869 }
1870
1871 /*
1872  * Follow the chain of deltas from this entry onward, throwing away any links
1873  * that cause us to hit a cycle (as determined by the DFS state flags in
1874  * the entries).
1875  *
1876  * We also detect too-long reused chains that would violate our --depth
1877  * limit.
1878  */
1879 static void break_delta_chains(struct object_entry *entry)
1880 {
1881         /*
1882          * The actual depth of each object we will write is stored as an int,
1883          * as it cannot exceed our int "depth" limit. But before we break
1884          * changes based no that limit, we may potentially go as deep as the
1885          * number of objects, which is elsewhere bounded to a uint32_t.
1886          */
1887         uint32_t total_depth;
1888         struct object_entry *cur, *next;
1889
1890         for (cur = entry, total_depth = 0;
1891              cur;
1892              cur = DELTA(cur), total_depth++) {
1893                 if (cur->dfs_state == DFS_DONE) {
1894                         /*
1895                          * We've already seen this object and know it isn't
1896                          * part of a cycle. We do need to append its depth
1897                          * to our count.
1898                          */
1899                         total_depth += cur->depth;
1900                         break;
1901                 }
1902
1903                 /*
1904                  * We break cycles before looping, so an ACTIVE state (or any
1905                  * other cruft which made its way into the state variable)
1906                  * is a bug.
1907                  */
1908                 if (cur->dfs_state != DFS_NONE)
1909                         BUG("confusing delta dfs state in first pass: %d",
1910                             cur->dfs_state);
1911
1912                 /*
1913                  * Now we know this is the first time we've seen the object. If
1914                  * it's not a delta, we're done traversing, but we'll mark it
1915                  * done to save time on future traversals.
1916                  */
1917                 if (!DELTA(cur)) {
1918                         cur->dfs_state = DFS_DONE;
1919                         break;
1920                 }
1921
1922                 /*
1923                  * Mark ourselves as active and see if the next step causes
1924                  * us to cycle to another active object. It's important to do
1925                  * this _before_ we loop, because it impacts where we make the
1926                  * cut, and thus how our total_depth counter works.
1927                  * E.g., We may see a partial loop like:
1928                  *
1929                  *   A -> B -> C -> D -> B
1930                  *
1931                  * Cutting B->C breaks the cycle. But now the depth of A is
1932                  * only 1, and our total_depth counter is at 3. The size of the
1933                  * error is always one less than the size of the cycle we
1934                  * broke. Commits C and D were "lost" from A's chain.
1935                  *
1936                  * If we instead cut D->B, then the depth of A is correct at 3.
1937                  * We keep all commits in the chain that we examined.
1938                  */
1939                 cur->dfs_state = DFS_ACTIVE;
1940                 if (DELTA(cur)->dfs_state == DFS_ACTIVE) {
1941                         drop_reused_delta(cur);
1942                         cur->dfs_state = DFS_DONE;
1943                         break;
1944                 }
1945         }
1946
1947         /*
1948          * And now that we've gone all the way to the bottom of the chain, we
1949          * need to clear the active flags and set the depth fields as
1950          * appropriate. Unlike the loop above, which can quit when it drops a
1951          * delta, we need to keep going to look for more depth cuts. So we need
1952          * an extra "next" pointer to keep going after we reset cur->delta.
1953          */
1954         for (cur = entry; cur; cur = next) {
1955                 next = DELTA(cur);
1956
1957                 /*
1958                  * We should have a chain of zero or more ACTIVE states down to
1959                  * a final DONE. We can quit after the DONE, because either it
1960                  * has no bases, or we've already handled them in a previous
1961                  * call.
1962                  */
1963                 if (cur->dfs_state == DFS_DONE)
1964                         break;
1965                 else if (cur->dfs_state != DFS_ACTIVE)
1966                         BUG("confusing delta dfs state in second pass: %d",
1967                             cur->dfs_state);
1968
1969                 /*
1970                  * If the total_depth is more than depth, then we need to snip
1971                  * the chain into two or more smaller chains that don't exceed
1972                  * the maximum depth. Most of the resulting chains will contain
1973                  * (depth + 1) entries (i.e., depth deltas plus one base), and
1974                  * the last chain (i.e., the one containing entry) will contain
1975                  * whatever entries are left over, namely
1976                  * (total_depth % (depth + 1)) of them.
1977                  *
1978                  * Since we are iterating towards decreasing depth, we need to
1979                  * decrement total_depth as we go, and we need to write to the
1980                  * entry what its final depth will be after all of the
1981                  * snipping. Since we're snipping into chains of length (depth
1982                  * + 1) entries, the final depth of an entry will be its
1983                  * original depth modulo (depth + 1). Any time we encounter an
1984                  * entry whose final depth is supposed to be zero, we snip it
1985                  * from its delta base, thereby making it so.
1986                  */
1987                 cur->depth = (total_depth--) % (depth + 1);
1988                 if (!cur->depth)
1989                         drop_reused_delta(cur);
1990
1991                 cur->dfs_state = DFS_DONE;
1992         }
1993 }
1994
1995 static void get_object_details(void)
1996 {
1997         uint32_t i;
1998         struct object_entry **sorted_by_offset;
1999
2000         if (progress)
2001                 progress_state = start_progress(_("Counting objects"),
2002                                                 to_pack.nr_objects);
2003
2004         sorted_by_offset = xcalloc(to_pack.nr_objects, sizeof(struct object_entry *));
2005         for (i = 0; i < to_pack.nr_objects; i++)
2006                 sorted_by_offset[i] = to_pack.objects + i;
2007         QSORT(sorted_by_offset, to_pack.nr_objects, pack_offset_sort);
2008
2009         for (i = 0; i < to_pack.nr_objects; i++) {
2010                 struct object_entry *entry = sorted_by_offset[i];
2011                 check_object(entry);
2012                 if (entry->type_valid &&
2013                     oe_size_greater_than(&to_pack, entry, big_file_threshold))
2014                         entry->no_try_delta = 1;
2015                 display_progress(progress_state, i + 1);
2016         }
2017         stop_progress(&progress_state);
2018
2019         /*
2020          * This must happen in a second pass, since we rely on the delta
2021          * information for the whole list being completed.
2022          */
2023         for (i = 0; i < to_pack.nr_objects; i++)
2024                 break_delta_chains(&to_pack.objects[i]);
2025
2026         free(sorted_by_offset);
2027 }
2028
2029 /*
2030  * We search for deltas in a list sorted by type, by filename hash, and then
2031  * by size, so that we see progressively smaller and smaller files.
2032  * That's because we prefer deltas to be from the bigger file
2033  * to the smaller -- deletes are potentially cheaper, but perhaps
2034  * more importantly, the bigger file is likely the more recent
2035  * one.  The deepest deltas are therefore the oldest objects which are
2036  * less susceptible to be accessed often.
2037  */
2038 static int type_size_sort(const void *_a, const void *_b)
2039 {
2040         const struct object_entry *a = *(struct object_entry **)_a;
2041         const struct object_entry *b = *(struct object_entry **)_b;
2042         const enum object_type a_type = oe_type(a);
2043         const enum object_type b_type = oe_type(b);
2044         const unsigned long a_size = SIZE(a);
2045         const unsigned long b_size = SIZE(b);
2046
2047         if (a_type > b_type)
2048                 return -1;
2049         if (a_type < b_type)
2050                 return 1;
2051         if (a->hash > b->hash)
2052                 return -1;
2053         if (a->hash < b->hash)
2054                 return 1;
2055         if (a->preferred_base > b->preferred_base)
2056                 return -1;
2057         if (a->preferred_base < b->preferred_base)
2058                 return 1;
2059         if (use_delta_islands) {
2060                 const int island_cmp = island_delta_cmp(&a->idx.oid, &b->idx.oid);
2061                 if (island_cmp)
2062                         return island_cmp;
2063         }
2064         if (a_size > b_size)
2065                 return -1;
2066         if (a_size < b_size)
2067                 return 1;
2068         return a < b ? -1 : (a > b);  /* newest first */
2069 }
2070
2071 struct unpacked {
2072         struct object_entry *entry;
2073         void *data;
2074         struct delta_index *index;
2075         unsigned depth;
2076 };
2077
2078 static int delta_cacheable(unsigned long src_size, unsigned long trg_size,
2079                            unsigned long delta_size)
2080 {
2081         if (max_delta_cache_size && delta_cache_size + delta_size > max_delta_cache_size)
2082                 return 0;
2083
2084         if (delta_size < cache_max_small_delta_size)
2085                 return 1;
2086
2087         /* cache delta, if objects are large enough compared to delta size */
2088         if ((src_size >> 20) + (trg_size >> 21) > (delta_size >> 10))
2089                 return 1;
2090
2091         return 0;
2092 }
2093
2094 /* Protect delta_cache_size */
2095 static pthread_mutex_t cache_mutex;
2096 #define cache_lock()            pthread_mutex_lock(&cache_mutex)
2097 #define cache_unlock()          pthread_mutex_unlock(&cache_mutex)
2098
2099 /*
2100  * Protect object list partitioning (e.g. struct thread_param) and
2101  * progress_state
2102  */
2103 static pthread_mutex_t progress_mutex;
2104 #define progress_lock()         pthread_mutex_lock(&progress_mutex)
2105 #define progress_unlock()       pthread_mutex_unlock(&progress_mutex)
2106
2107 /*
2108  * Access to struct object_entry is unprotected since each thread owns
2109  * a portion of the main object list. Just don't access object entries
2110  * ahead in the list because they can be stolen and would need
2111  * progress_mutex for protection.
2112  */
2113
2114 /*
2115  * Return the size of the object without doing any delta
2116  * reconstruction (so non-deltas are true object sizes, but deltas
2117  * return the size of the delta data).
2118  */
2119 unsigned long oe_get_size_slow(struct packing_data *pack,
2120                                const struct object_entry *e)
2121 {
2122         struct packed_git *p;
2123         struct pack_window *w_curs;
2124         unsigned char *buf;
2125         enum object_type type;
2126         unsigned long used, avail, size;
2127
2128         if (e->type_ != OBJ_OFS_DELTA && e->type_ != OBJ_REF_DELTA) {
2129                 packing_data_lock(&to_pack);
2130                 if (oid_object_info(the_repository, &e->idx.oid, &size) < 0)
2131                         die(_("unable to get size of %s"),
2132                             oid_to_hex(&e->idx.oid));
2133                 packing_data_unlock(&to_pack);
2134                 return size;
2135         }
2136
2137         p = oe_in_pack(pack, e);
2138         if (!p)
2139                 BUG("when e->type is a delta, it must belong to a pack");
2140
2141         packing_data_lock(&to_pack);
2142         w_curs = NULL;
2143         buf = use_pack(p, &w_curs, e->in_pack_offset, &avail);
2144         used = unpack_object_header_buffer(buf, avail, &type, &size);
2145         if (used == 0)
2146                 die(_("unable to parse object header of %s"),
2147                     oid_to_hex(&e->idx.oid));
2148
2149         unuse_pack(&w_curs);
2150         packing_data_unlock(&to_pack);
2151         return size;
2152 }
2153
2154 static int try_delta(struct unpacked *trg, struct unpacked *src,
2155                      unsigned max_depth, unsigned long *mem_usage)
2156 {
2157         struct object_entry *trg_entry = trg->entry;
2158         struct object_entry *src_entry = src->entry;
2159         unsigned long trg_size, src_size, delta_size, sizediff, max_size, sz;
2160         unsigned ref_depth;
2161         enum object_type type;
2162         void *delta_buf;
2163
2164         /* Don't bother doing diffs between different types */
2165         if (oe_type(trg_entry) != oe_type(src_entry))
2166                 return -1;
2167
2168         /*
2169          * We do not bother to try a delta that we discarded on an
2170          * earlier try, but only when reusing delta data.  Note that
2171          * src_entry that is marked as the preferred_base should always
2172          * be considered, as even if we produce a suboptimal delta against
2173          * it, we will still save the transfer cost, as we already know
2174          * the other side has it and we won't send src_entry at all.
2175          */
2176         if (reuse_delta && IN_PACK(trg_entry) &&
2177             IN_PACK(trg_entry) == IN_PACK(src_entry) &&
2178             !src_entry->preferred_base &&
2179             trg_entry->in_pack_type != OBJ_REF_DELTA &&
2180             trg_entry->in_pack_type != OBJ_OFS_DELTA)
2181                 return 0;
2182
2183         /* Let's not bust the allowed depth. */
2184         if (src->depth >= max_depth)
2185                 return 0;
2186
2187         /* Now some size filtering heuristics. */
2188         trg_size = SIZE(trg_entry);
2189         if (!DELTA(trg_entry)) {
2190                 max_size = trg_size/2 - the_hash_algo->rawsz;
2191                 ref_depth = 1;
2192         } else {
2193                 max_size = DELTA_SIZE(trg_entry);
2194                 ref_depth = trg->depth;
2195         }
2196         max_size = (uint64_t)max_size * (max_depth - src->depth) /
2197                                                 (max_depth - ref_depth + 1);
2198         if (max_size == 0)
2199                 return 0;
2200         src_size = SIZE(src_entry);
2201         sizediff = src_size < trg_size ? trg_size - src_size : 0;
2202         if (sizediff >= max_size)
2203                 return 0;
2204         if (trg_size < src_size / 32)
2205                 return 0;
2206
2207         if (!in_same_island(&trg->entry->idx.oid, &src->entry->idx.oid))
2208                 return 0;
2209
2210         /* Load data if not already done */
2211         if (!trg->data) {
2212                 packing_data_lock(&to_pack);
2213                 trg->data = read_object_file(&trg_entry->idx.oid, &type, &sz);
2214                 packing_data_unlock(&to_pack);
2215                 if (!trg->data)
2216                         die(_("object %s cannot be read"),
2217                             oid_to_hex(&trg_entry->idx.oid));
2218                 if (sz != trg_size)
2219                         die(_("object %s inconsistent object length (%"PRIuMAX" vs %"PRIuMAX")"),
2220                             oid_to_hex(&trg_entry->idx.oid), (uintmax_t)sz,
2221                             (uintmax_t)trg_size);
2222                 *mem_usage += sz;
2223         }
2224         if (!src->data) {
2225                 packing_data_lock(&to_pack);
2226                 src->data = read_object_file(&src_entry->idx.oid, &type, &sz);
2227                 packing_data_unlock(&to_pack);
2228                 if (!src->data) {
2229                         if (src_entry->preferred_base) {
2230                                 static int warned = 0;
2231                                 if (!warned++)
2232                                         warning(_("object %s cannot be read"),
2233                                                 oid_to_hex(&src_entry->idx.oid));
2234                                 /*
2235                                  * Those objects are not included in the
2236                                  * resulting pack.  Be resilient and ignore
2237                                  * them if they can't be read, in case the
2238                                  * pack could be created nevertheless.
2239                                  */
2240                                 return 0;
2241                         }
2242                         die(_("object %s cannot be read"),
2243                             oid_to_hex(&src_entry->idx.oid));
2244                 }
2245                 if (sz != src_size)
2246                         die(_("object %s inconsistent object length (%"PRIuMAX" vs %"PRIuMAX")"),
2247                             oid_to_hex(&src_entry->idx.oid), (uintmax_t)sz,
2248                             (uintmax_t)src_size);
2249                 *mem_usage += sz;
2250         }
2251         if (!src->index) {
2252                 src->index = create_delta_index(src->data, src_size);
2253                 if (!src->index) {
2254                         static int warned = 0;
2255                         if (!warned++)
2256                                 warning(_("suboptimal pack - out of memory"));
2257                         return 0;
2258                 }
2259                 *mem_usage += sizeof_delta_index(src->index);
2260         }
2261
2262         delta_buf = create_delta(src->index, trg->data, trg_size, &delta_size, max_size);
2263         if (!delta_buf)
2264                 return 0;
2265
2266         if (DELTA(trg_entry)) {
2267                 /* Prefer only shallower same-sized deltas. */
2268                 if (delta_size == DELTA_SIZE(trg_entry) &&
2269                     src->depth + 1 >= trg->depth) {
2270                         free(delta_buf);
2271                         return 0;
2272                 }
2273         }
2274
2275         /*
2276          * Handle memory allocation outside of the cache
2277          * accounting lock.  Compiler will optimize the strangeness
2278          * away when NO_PTHREADS is defined.
2279          */
2280         free(trg_entry->delta_data);
2281         cache_lock();
2282         if (trg_entry->delta_data) {
2283                 delta_cache_size -= DELTA_SIZE(trg_entry);
2284                 trg_entry->delta_data = NULL;
2285         }
2286         if (delta_cacheable(src_size, trg_size, delta_size)) {
2287                 delta_cache_size += delta_size;
2288                 cache_unlock();
2289                 trg_entry->delta_data = xrealloc(delta_buf, delta_size);
2290         } else {
2291                 cache_unlock();
2292                 free(delta_buf);
2293         }
2294
2295         SET_DELTA(trg_entry, src_entry);
2296         SET_DELTA_SIZE(trg_entry, delta_size);
2297         trg->depth = src->depth + 1;
2298
2299         return 1;
2300 }
2301
2302 static unsigned int check_delta_limit(struct object_entry *me, unsigned int n)
2303 {
2304         struct object_entry *child = DELTA_CHILD(me);
2305         unsigned int m = n;
2306         while (child) {
2307                 const unsigned int c = check_delta_limit(child, n + 1);
2308                 if (m < c)
2309                         m = c;
2310                 child = DELTA_SIBLING(child);
2311         }
2312         return m;
2313 }
2314
2315 static unsigned long free_unpacked(struct unpacked *n)
2316 {
2317         unsigned long freed_mem = sizeof_delta_index(n->index);
2318         free_delta_index(n->index);
2319         n->index = NULL;
2320         if (n->data) {
2321                 freed_mem += SIZE(n->entry);
2322                 FREE_AND_NULL(n->data);
2323         }
2324         n->entry = NULL;
2325         n->depth = 0;
2326         return freed_mem;
2327 }
2328
2329 static void find_deltas(struct object_entry **list, unsigned *list_size,
2330                         int window, int depth, unsigned *processed)
2331 {
2332         uint32_t i, idx = 0, count = 0;
2333         struct unpacked *array;
2334         unsigned long mem_usage = 0;
2335
2336         array = xcalloc(window, sizeof(struct unpacked));
2337
2338         for (;;) {
2339                 struct object_entry *entry;
2340                 struct unpacked *n = array + idx;
2341                 int j, max_depth, best_base = -1;
2342
2343                 progress_lock();
2344                 if (!*list_size) {
2345                         progress_unlock();
2346                         break;
2347                 }
2348                 entry = *list++;
2349                 (*list_size)--;
2350                 if (!entry->preferred_base) {
2351                         (*processed)++;
2352                         display_progress(progress_state, *processed);
2353                 }
2354                 progress_unlock();
2355
2356                 mem_usage -= free_unpacked(n);
2357                 n->entry = entry;
2358
2359                 while (window_memory_limit &&
2360                        mem_usage > window_memory_limit &&
2361                        count > 1) {
2362                         const uint32_t tail = (idx + window - count) % window;
2363                         mem_usage -= free_unpacked(array + tail);
2364                         count--;
2365                 }
2366
2367                 /* We do not compute delta to *create* objects we are not
2368                  * going to pack.
2369                  */
2370                 if (entry->preferred_base)
2371                         goto next;
2372
2373                 /*
2374                  * If the current object is at pack edge, take the depth the
2375                  * objects that depend on the current object into account
2376                  * otherwise they would become too deep.
2377                  */
2378                 max_depth = depth;
2379                 if (DELTA_CHILD(entry)) {
2380                         max_depth -= check_delta_limit(entry, 0);
2381                         if (max_depth <= 0)
2382                                 goto next;
2383                 }
2384
2385                 j = window;
2386                 while (--j > 0) {
2387                         int ret;
2388                         uint32_t other_idx = idx + j;
2389                         struct unpacked *m;
2390                         if (other_idx >= window)
2391                                 other_idx -= window;
2392                         m = array + other_idx;
2393                         if (!m->entry)
2394                                 break;
2395                         ret = try_delta(n, m, max_depth, &mem_usage);
2396                         if (ret < 0)
2397                                 break;
2398                         else if (ret > 0)
2399                                 best_base = other_idx;
2400                 }
2401
2402                 /*
2403                  * If we decided to cache the delta data, then it is best
2404                  * to compress it right away.  First because we have to do
2405                  * it anyway, and doing it here while we're threaded will
2406                  * save a lot of time in the non threaded write phase,
2407                  * as well as allow for caching more deltas within
2408                  * the same cache size limit.
2409                  * ...
2410                  * But only if not writing to stdout, since in that case
2411                  * the network is most likely throttling writes anyway,
2412                  * and therefore it is best to go to the write phase ASAP
2413                  * instead, as we can afford spending more time compressing
2414                  * between writes at that moment.
2415                  */
2416                 if (entry->delta_data && !pack_to_stdout) {
2417                         unsigned long size;
2418
2419                         size = do_compress(&entry->delta_data, DELTA_SIZE(entry));
2420                         if (size < (1U << OE_Z_DELTA_BITS)) {
2421                                 entry->z_delta_size = size;
2422                                 cache_lock();
2423                                 delta_cache_size -= DELTA_SIZE(entry);
2424                                 delta_cache_size += entry->z_delta_size;
2425                                 cache_unlock();
2426                         } else {
2427                                 FREE_AND_NULL(entry->delta_data);
2428                                 entry->z_delta_size = 0;
2429                         }
2430                 }
2431
2432                 /* if we made n a delta, and if n is already at max
2433                  * depth, leaving it in the window is pointless.  we
2434                  * should evict it first.
2435                  */
2436                 if (DELTA(entry) && max_depth <= n->depth)
2437                         continue;
2438
2439                 /*
2440                  * Move the best delta base up in the window, after the
2441                  * currently deltified object, to keep it longer.  It will
2442                  * be the first base object to be attempted next.
2443                  */
2444                 if (DELTA(entry)) {
2445                         struct unpacked swap = array[best_base];
2446                         int dist = (window + idx - best_base) % window;
2447                         int dst = best_base;
2448                         while (dist--) {
2449                                 int src = (dst + 1) % window;
2450                                 array[dst] = array[src];
2451                                 dst = src;
2452                         }
2453                         array[dst] = swap;
2454                 }
2455
2456                 next:
2457                 idx++;
2458                 if (count + 1 < window)
2459                         count++;
2460                 if (idx >= window)
2461                         idx = 0;
2462         }
2463
2464         for (i = 0; i < window; ++i) {
2465                 free_delta_index(array[i].index);
2466                 free(array[i].data);
2467         }
2468         free(array);
2469 }
2470
2471 /*
2472  * The main object list is split into smaller lists, each is handed to
2473  * one worker.
2474  *
2475  * The main thread waits on the condition that (at least) one of the workers
2476  * has stopped working (which is indicated in the .working member of
2477  * struct thread_params).
2478  *
2479  * When a work thread has completed its work, it sets .working to 0 and
2480  * signals the main thread and waits on the condition that .data_ready
2481  * becomes 1.
2482  *
2483  * The main thread steals half of the work from the worker that has
2484  * most work left to hand it to the idle worker.
2485  */
2486
2487 struct thread_params {
2488         pthread_t thread;
2489         struct object_entry **list;
2490         unsigned list_size;
2491         unsigned remaining;
2492         int window;
2493         int depth;
2494         int working;
2495         int data_ready;
2496         pthread_mutex_t mutex;
2497         pthread_cond_t cond;
2498         unsigned *processed;
2499 };
2500
2501 static pthread_cond_t progress_cond;
2502
2503 /*
2504  * Mutex and conditional variable can't be statically-initialized on Windows.
2505  */
2506 static void init_threaded_search(void)
2507 {
2508         pthread_mutex_init(&cache_mutex, NULL);
2509         pthread_mutex_init(&progress_mutex, NULL);
2510         pthread_cond_init(&progress_cond, NULL);
2511 }
2512
2513 static void cleanup_threaded_search(void)
2514 {
2515         pthread_cond_destroy(&progress_cond);
2516         pthread_mutex_destroy(&cache_mutex);
2517         pthread_mutex_destroy(&progress_mutex);
2518 }
2519
2520 static void *threaded_find_deltas(void *arg)
2521 {
2522         struct thread_params *me = arg;
2523
2524         progress_lock();
2525         while (me->remaining) {
2526                 progress_unlock();
2527
2528                 find_deltas(me->list, &me->remaining,
2529                             me->window, me->depth, me->processed);
2530
2531                 progress_lock();
2532                 me->working = 0;
2533                 pthread_cond_signal(&progress_cond);
2534                 progress_unlock();
2535
2536                 /*
2537                  * We must not set ->data_ready before we wait on the
2538                  * condition because the main thread may have set it to 1
2539                  * before we get here. In order to be sure that new
2540                  * work is available if we see 1 in ->data_ready, it
2541                  * was initialized to 0 before this thread was spawned
2542                  * and we reset it to 0 right away.
2543                  */
2544                 pthread_mutex_lock(&me->mutex);
2545                 while (!me->data_ready)
2546                         pthread_cond_wait(&me->cond, &me->mutex);
2547                 me->data_ready = 0;
2548                 pthread_mutex_unlock(&me->mutex);
2549
2550                 progress_lock();
2551         }
2552         progress_unlock();
2553         /* leave ->working 1 so that this doesn't get more work assigned */
2554         return NULL;
2555 }
2556
2557 static void ll_find_deltas(struct object_entry **list, unsigned list_size,
2558                            int window, int depth, unsigned *processed)
2559 {
2560         struct thread_params *p;
2561         int i, ret, active_threads = 0;
2562
2563         init_threaded_search();
2564
2565         if (delta_search_threads <= 1) {
2566                 find_deltas(list, &list_size, window, depth, processed);
2567                 cleanup_threaded_search();
2568                 return;
2569         }
2570         if (progress > pack_to_stdout)
2571                 fprintf_ln(stderr, _("Delta compression using up to %d threads"),
2572                            delta_search_threads);
2573         p = xcalloc(delta_search_threads, sizeof(*p));
2574
2575         /* Partition the work amongst work threads. */
2576         for (i = 0; i < delta_search_threads; i++) {
2577                 unsigned sub_size = list_size / (delta_search_threads - i);
2578
2579                 /* don't use too small segments or no deltas will be found */
2580                 if (sub_size < 2*window && i+1 < delta_search_threads)
2581                         sub_size = 0;
2582
2583                 p[i].window = window;
2584                 p[i].depth = depth;
2585                 p[i].processed = processed;
2586                 p[i].working = 1;
2587                 p[i].data_ready = 0;
2588
2589                 /* try to split chunks on "path" boundaries */
2590                 while (sub_size && sub_size < list_size &&
2591                        list[sub_size]->hash &&
2592                        list[sub_size]->hash == list[sub_size-1]->hash)
2593                         sub_size++;
2594
2595                 p[i].list = list;
2596                 p[i].list_size = sub_size;
2597                 p[i].remaining = sub_size;
2598
2599                 list += sub_size;
2600                 list_size -= sub_size;
2601         }
2602
2603         /* Start work threads. */
2604         for (i = 0; i < delta_search_threads; i++) {
2605                 if (!p[i].list_size)
2606                         continue;
2607                 pthread_mutex_init(&p[i].mutex, NULL);
2608                 pthread_cond_init(&p[i].cond, NULL);
2609                 ret = pthread_create(&p[i].thread, NULL,
2610                                      threaded_find_deltas, &p[i]);
2611                 if (ret)
2612                         die(_("unable to create thread: %s"), strerror(ret));
2613                 active_threads++;
2614         }
2615
2616         /*
2617          * Now let's wait for work completion.  Each time a thread is done
2618          * with its work, we steal half of the remaining work from the
2619          * thread with the largest number of unprocessed objects and give
2620          * it to that newly idle thread.  This ensure good load balancing
2621          * until the remaining object list segments are simply too short
2622          * to be worth splitting anymore.
2623          */
2624         while (active_threads) {
2625                 struct thread_params *target = NULL;
2626                 struct thread_params *victim = NULL;
2627                 unsigned sub_size = 0;
2628
2629                 progress_lock();
2630                 for (;;) {
2631                         for (i = 0; !target && i < delta_search_threads; i++)
2632                                 if (!p[i].working)
2633                                         target = &p[i];
2634                         if (target)
2635                                 break;
2636                         pthread_cond_wait(&progress_cond, &progress_mutex);
2637                 }
2638
2639                 for (i = 0; i < delta_search_threads; i++)
2640                         if (p[i].remaining > 2*window &&
2641                             (!victim || victim->remaining < p[i].remaining))
2642                                 victim = &p[i];
2643                 if (victim) {
2644                         sub_size = victim->remaining / 2;
2645                         list = victim->list + victim->list_size - sub_size;
2646                         while (sub_size && list[0]->hash &&
2647                                list[0]->hash == list[-1]->hash) {
2648                                 list++;
2649                                 sub_size--;
2650                         }
2651                         if (!sub_size) {
2652                                 /*
2653                                  * It is possible for some "paths" to have
2654                                  * so many objects that no hash boundary
2655                                  * might be found.  Let's just steal the
2656                                  * exact half in that case.
2657                                  */
2658                                 sub_size = victim->remaining / 2;
2659                                 list -= sub_size;
2660                         }
2661                         target->list = list;
2662                         victim->list_size -= sub_size;
2663                         victim->remaining -= sub_size;
2664                 }
2665                 target->list_size = sub_size;
2666                 target->remaining = sub_size;
2667                 target->working = 1;
2668                 progress_unlock();
2669
2670                 pthread_mutex_lock(&target->mutex);
2671                 target->data_ready = 1;
2672                 pthread_cond_signal(&target->cond);
2673                 pthread_mutex_unlock(&target->mutex);
2674
2675                 if (!sub_size) {
2676                         pthread_join(target->thread, NULL);
2677                         pthread_cond_destroy(&target->cond);
2678                         pthread_mutex_destroy(&target->mutex);
2679                         active_threads--;
2680                 }
2681         }
2682         cleanup_threaded_search();
2683         free(p);
2684 }
2685
2686 static int obj_is_packed(const struct object_id *oid)
2687 {
2688         return packlist_find(&to_pack, oid) ||
2689                 (reuse_packfile_bitmap &&
2690                  bitmap_walk_contains(bitmap_git, reuse_packfile_bitmap, oid));
2691 }
2692
2693 static void add_tag_chain(const struct object_id *oid)
2694 {
2695         struct tag *tag;
2696
2697         /*
2698          * We catch duplicates already in add_object_entry(), but we'd
2699          * prefer to do this extra check to avoid having to parse the
2700          * tag at all if we already know that it's being packed (e.g., if
2701          * it was included via bitmaps, we would not have parsed it
2702          * previously).
2703          */
2704         if (obj_is_packed(oid))
2705                 return;
2706
2707         tag = lookup_tag(the_repository, oid);
2708         while (1) {
2709                 if (!tag || parse_tag(tag) || !tag->tagged)
2710                         die(_("unable to pack objects reachable from tag %s"),
2711                             oid_to_hex(oid));
2712
2713                 add_object_entry(&tag->object.oid, OBJ_TAG, NULL, 0);
2714
2715                 if (tag->tagged->type != OBJ_TAG)
2716                         return;
2717
2718                 tag = (struct tag *)tag->tagged;
2719         }
2720 }
2721
2722 static int add_ref_tag(const char *path, const struct object_id *oid, int flag, void *cb_data)
2723 {
2724         struct object_id peeled;
2725
2726         if (starts_with(path, "refs/tags/") && /* is a tag? */
2727             !peel_ref(path, &peeled)    && /* peelable? */
2728             obj_is_packed(&peeled)) /* object packed? */
2729                 add_tag_chain(oid);
2730         return 0;
2731 }
2732
2733 static void prepare_pack(int window, int depth)
2734 {
2735         struct object_entry **delta_list;
2736         uint32_t i, nr_deltas;
2737         unsigned n;
2738
2739         if (use_delta_islands)
2740                 resolve_tree_islands(the_repository, progress, &to_pack);
2741
2742         get_object_details();
2743
2744         /*
2745          * If we're locally repacking then we need to be doubly careful
2746          * from now on in order to make sure no stealth corruption gets
2747          * propagated to the new pack.  Clients receiving streamed packs
2748          * should validate everything they get anyway so no need to incur
2749          * the additional cost here in that case.
2750          */
2751         if (!pack_to_stdout)
2752                 do_check_packed_object_crc = 1;
2753
2754         if (!to_pack.nr_objects || !window || !depth)
2755                 return;
2756
2757         ALLOC_ARRAY(delta_list, to_pack.nr_objects);
2758         nr_deltas = n = 0;
2759
2760         for (i = 0; i < to_pack.nr_objects; i++) {
2761                 struct object_entry *entry = to_pack.objects + i;
2762
2763                 if (DELTA(entry))
2764                         /* This happens if we decided to reuse existing
2765                          * delta from a pack.  "reuse_delta &&" is implied.
2766                          */
2767                         continue;
2768
2769                 if (!entry->type_valid ||
2770                     oe_size_less_than(&to_pack, entry, 50))
2771                         continue;
2772
2773                 if (entry->no_try_delta)
2774                         continue;
2775
2776                 if (!entry->preferred_base) {
2777                         nr_deltas++;
2778                         if (oe_type(entry) < 0)
2779                                 die(_("unable to get type of object %s"),
2780                                     oid_to_hex(&entry->idx.oid));
2781                 } else {
2782                         if (oe_type(entry) < 0) {
2783                                 /*
2784                                  * This object is not found, but we
2785                                  * don't have to include it anyway.
2786                                  */
2787                                 continue;
2788                         }
2789                 }
2790
2791                 delta_list[n++] = entry;
2792         }
2793
2794         if (nr_deltas && n > 1) {
2795                 unsigned nr_done = 0;
2796
2797                 if (progress)
2798                         progress_state = start_progress(_("Compressing objects"),
2799                                                         nr_deltas);
2800                 QSORT(delta_list, n, type_size_sort);
2801                 ll_find_deltas(delta_list, n, window+1, depth, &nr_done);
2802                 stop_progress(&progress_state);
2803                 if (nr_done != nr_deltas)
2804                         die(_("inconsistency with delta count"));
2805         }
2806         free(delta_list);
2807 }
2808
2809 static int git_pack_config(const char *k, const char *v, void *cb)
2810 {
2811         if (!strcmp(k, "pack.window")) {
2812                 window = git_config_int(k, v);
2813                 return 0;
2814         }
2815         if (!strcmp(k, "pack.windowmemory")) {
2816                 window_memory_limit = git_config_ulong(k, v);
2817                 return 0;
2818         }
2819         if (!strcmp(k, "pack.depth")) {
2820                 depth = git_config_int(k, v);
2821                 return 0;
2822         }
2823         if (!strcmp(k, "pack.deltacachesize")) {
2824                 max_delta_cache_size = git_config_int(k, v);
2825                 return 0;
2826         }
2827         if (!strcmp(k, "pack.deltacachelimit")) {
2828                 cache_max_small_delta_size = git_config_int(k, v);
2829                 return 0;
2830         }
2831         if (!strcmp(k, "pack.writebitmaphashcache")) {
2832                 if (git_config_bool(k, v))
2833                         write_bitmap_options |= BITMAP_OPT_HASH_CACHE;
2834                 else
2835                         write_bitmap_options &= ~BITMAP_OPT_HASH_CACHE;
2836         }
2837         if (!strcmp(k, "pack.usebitmaps")) {
2838                 use_bitmap_index_default = git_config_bool(k, v);
2839                 return 0;
2840         }
2841         if (!strcmp(k, "pack.allowpackreuse")) {
2842                 allow_pack_reuse = git_config_bool(k, v);
2843                 return 0;
2844         }
2845         if (!strcmp(k, "pack.threads")) {
2846                 delta_search_threads = git_config_int(k, v);
2847                 if (delta_search_threads < 0)
2848                         die(_("invalid number of threads specified (%d)"),
2849                             delta_search_threads);
2850                 if (!HAVE_THREADS && delta_search_threads != 1) {
2851                         warning(_("no threads support, ignoring %s"), k);
2852                         delta_search_threads = 0;
2853                 }
2854                 return 0;
2855         }
2856         if (!strcmp(k, "pack.indexversion")) {
2857                 pack_idx_opts.version = git_config_int(k, v);
2858                 if (pack_idx_opts.version > 2)
2859                         die(_("bad pack.indexversion=%"PRIu32),
2860                             pack_idx_opts.version);
2861                 return 0;
2862         }
2863         return git_default_config(k, v, cb);
2864 }
2865
2866 static void read_object_list_from_stdin(void)
2867 {
2868         char line[GIT_MAX_HEXSZ + 1 + PATH_MAX + 2];
2869         struct object_id oid;
2870         const char *p;
2871
2872         for (;;) {
2873                 if (!fgets(line, sizeof(line), stdin)) {
2874                         if (feof(stdin))
2875                                 break;
2876                         if (!ferror(stdin))
2877                                 die("BUG: fgets returned NULL, not EOF, not error!");
2878                         if (errno != EINTR)
2879                                 die_errno("fgets");
2880                         clearerr(stdin);
2881                         continue;
2882                 }
2883                 if (line[0] == '-') {
2884                         if (get_oid_hex(line+1, &oid))
2885                                 die(_("expected edge object ID, got garbage:\n %s"),
2886                                     line);
2887                         add_preferred_base(&oid);
2888                         continue;
2889                 }
2890                 if (parse_oid_hex(line, &oid, &p))
2891                         die(_("expected object ID, got garbage:\n %s"), line);
2892
2893                 add_preferred_base_object(p + 1);
2894                 add_object_entry(&oid, OBJ_NONE, p + 1, 0);
2895         }
2896 }
2897
2898 /* Remember to update object flag allocation in object.h */
2899 #define OBJECT_ADDED (1u<<20)
2900
2901 static void show_commit(struct commit *commit, void *data)
2902 {
2903         add_object_entry(&commit->object.oid, OBJ_COMMIT, NULL, 0);
2904         commit->object.flags |= OBJECT_ADDED;
2905
2906         if (write_bitmap_index)
2907                 index_commit_for_bitmap(commit);
2908
2909         if (use_delta_islands)
2910                 propagate_island_marks(commit);
2911 }
2912
2913 static void show_object(struct object *obj, const char *name, void *data)
2914 {
2915         add_preferred_base_object(name);
2916         add_object_entry(&obj->oid, obj->type, name, 0);
2917         obj->flags |= OBJECT_ADDED;
2918
2919         if (use_delta_islands) {
2920                 const char *p;
2921                 unsigned depth;
2922                 struct object_entry *ent;
2923
2924                 /* the empty string is a root tree, which is depth 0 */
2925                 depth = *name ? 1 : 0;
2926                 for (p = strchr(name, '/'); p; p = strchr(p + 1, '/'))
2927                         depth++;
2928
2929                 ent = packlist_find(&to_pack, &obj->oid);
2930                 if (ent && depth > oe_tree_depth(&to_pack, ent))
2931                         oe_set_tree_depth(&to_pack, ent, depth);
2932         }
2933 }
2934
2935 static void show_object__ma_allow_any(struct object *obj, const char *name, void *data)
2936 {
2937         assert(arg_missing_action == MA_ALLOW_ANY);
2938
2939         /*
2940          * Quietly ignore ALL missing objects.  This avoids problems with
2941          * staging them now and getting an odd error later.
2942          */
2943         if (!has_object_file(&obj->oid))
2944                 return;
2945
2946         show_object(obj, name, data);
2947 }
2948
2949 static void show_object__ma_allow_promisor(struct object *obj, const char *name, void *data)
2950 {
2951         assert(arg_missing_action == MA_ALLOW_PROMISOR);
2952
2953         /*
2954          * Quietly ignore EXPECTED missing objects.  This avoids problems with
2955          * staging them now and getting an odd error later.
2956          */
2957         if (!has_object_file(&obj->oid) && is_promisor_object(&obj->oid))
2958                 return;
2959
2960         show_object(obj, name, data);
2961 }
2962
2963 static int option_parse_missing_action(const struct option *opt,
2964                                        const char *arg, int unset)
2965 {
2966         assert(arg);
2967         assert(!unset);
2968
2969         if (!strcmp(arg, "error")) {
2970                 arg_missing_action = MA_ERROR;
2971                 fn_show_object = show_object;
2972                 return 0;
2973         }
2974
2975         if (!strcmp(arg, "allow-any")) {
2976                 arg_missing_action = MA_ALLOW_ANY;
2977                 fetch_if_missing = 0;
2978                 fn_show_object = show_object__ma_allow_any;
2979                 return 0;
2980         }
2981
2982         if (!strcmp(arg, "allow-promisor")) {
2983                 arg_missing_action = MA_ALLOW_PROMISOR;
2984                 fetch_if_missing = 0;
2985                 fn_show_object = show_object__ma_allow_promisor;
2986                 return 0;
2987         }
2988
2989         die(_("invalid value for --missing"));
2990         return 0;
2991 }
2992
2993 static void show_edge(struct commit *commit)
2994 {
2995         add_preferred_base(&commit->object.oid);
2996 }
2997
2998 struct in_pack_object {
2999         off_t offset;
3000         struct object *object;
3001 };
3002
3003 struct in_pack {
3004         unsigned int alloc;
3005         unsigned int nr;
3006         struct in_pack_object *array;
3007 };
3008
3009 static void mark_in_pack_object(struct object *object, struct packed_git *p, struct in_pack *in_pack)
3010 {
3011         in_pack->array[in_pack->nr].offset = find_pack_entry_one(object->oid.hash, p);
3012         in_pack->array[in_pack->nr].object = object;
3013         in_pack->nr++;
3014 }
3015
3016 /*
3017  * Compare the objects in the offset order, in order to emulate the
3018  * "git rev-list --objects" output that produced the pack originally.
3019  */
3020 static int ofscmp(const void *a_, const void *b_)
3021 {
3022         struct in_pack_object *a = (struct in_pack_object *)a_;
3023         struct in_pack_object *b = (struct in_pack_object *)b_;
3024
3025         if (a->offset < b->offset)
3026                 return -1;
3027         else if (a->offset > b->offset)
3028                 return 1;
3029         else
3030                 return oidcmp(&a->object->oid, &b->object->oid);
3031 }
3032
3033 static void add_objects_in_unpacked_packs(void)
3034 {
3035         struct packed_git *p;
3036         struct in_pack in_pack;
3037         uint32_t i;
3038
3039         memset(&in_pack, 0, sizeof(in_pack));
3040
3041         for (p = get_all_packs(the_repository); p; p = p->next) {
3042                 struct object_id oid;
3043                 struct object *o;
3044
3045                 if (!p->pack_local || p->pack_keep || p->pack_keep_in_core)
3046                         continue;
3047                 if (open_pack_index(p))
3048                         die(_("cannot open pack index"));
3049
3050                 ALLOC_GROW(in_pack.array,
3051                            in_pack.nr + p->num_objects,
3052                            in_pack.alloc);
3053
3054                 for (i = 0; i < p->num_objects; i++) {
3055                         nth_packed_object_oid(&oid, p, i);
3056                         o = lookup_unknown_object(&oid);
3057                         if (!(o->flags & OBJECT_ADDED))
3058                                 mark_in_pack_object(o, p, &in_pack);
3059                         o->flags |= OBJECT_ADDED;
3060                 }
3061         }
3062
3063         if (in_pack.nr) {
3064                 QSORT(in_pack.array, in_pack.nr, ofscmp);
3065                 for (i = 0; i < in_pack.nr; i++) {
3066                         struct object *o = in_pack.array[i].object;
3067                         add_object_entry(&o->oid, o->type, "", 0);
3068                 }
3069         }
3070         free(in_pack.array);
3071 }
3072
3073 static int add_loose_object(const struct object_id *oid, const char *path,
3074                             void *data)
3075 {
3076         enum object_type type = oid_object_info(the_repository, oid, NULL);
3077
3078         if (type < 0) {
3079                 warning(_("loose object at %s could not be examined"), path);
3080                 return 0;
3081         }
3082
3083         add_object_entry(oid, type, "", 0);
3084         return 0;
3085 }
3086
3087 /*
3088  * We actually don't even have to worry about reachability here.
3089  * add_object_entry will weed out duplicates, so we just add every
3090  * loose object we find.
3091  */
3092 static void add_unreachable_loose_objects(void)
3093 {
3094         for_each_loose_file_in_objdir(get_object_directory(),
3095                                       add_loose_object,
3096                                       NULL, NULL, NULL);
3097 }
3098
3099 static int has_sha1_pack_kept_or_nonlocal(const struct object_id *oid)
3100 {
3101         static struct packed_git *last_found = (void *)1;
3102         struct packed_git *p;
3103
3104         p = (last_found != (void *)1) ? last_found :
3105                                         get_all_packs(the_repository);
3106
3107         while (p) {
3108                 if ((!p->pack_local || p->pack_keep ||
3109                                 p->pack_keep_in_core) &&
3110                         find_pack_entry_one(oid->hash, p)) {
3111                         last_found = p;
3112                         return 1;
3113                 }
3114                 if (p == last_found)
3115                         p = get_all_packs(the_repository);
3116                 else
3117                         p = p->next;
3118                 if (p == last_found)
3119                         p = p->next;
3120         }
3121         return 0;
3122 }
3123
3124 /*
3125  * Store a list of sha1s that are should not be discarded
3126  * because they are either written too recently, or are
3127  * reachable from another object that was.
3128  *
3129  * This is filled by get_object_list.
3130  */
3131 static struct oid_array recent_objects;
3132
3133 static int loosened_object_can_be_discarded(const struct object_id *oid,
3134                                             timestamp_t mtime)
3135 {
3136         if (!unpack_unreachable_expiration)
3137                 return 0;
3138         if (mtime > unpack_unreachable_expiration)
3139                 return 0;
3140         if (oid_array_lookup(&recent_objects, oid) >= 0)
3141                 return 0;
3142         return 1;
3143 }
3144
3145 static void loosen_unused_packed_objects(void)
3146 {
3147         struct packed_git *p;
3148         uint32_t i;
3149         struct object_id oid;
3150
3151         for (p = get_all_packs(the_repository); p; p = p->next) {
3152                 if (!p->pack_local || p->pack_keep || p->pack_keep_in_core)
3153                         continue;
3154
3155                 if (open_pack_index(p))
3156                         die(_("cannot open pack index"));
3157
3158                 for (i = 0; i < p->num_objects; i++) {
3159                         nth_packed_object_oid(&oid, p, i);
3160                         if (!packlist_find(&to_pack, &oid) &&
3161                             !has_sha1_pack_kept_or_nonlocal(&oid) &&
3162                             !loosened_object_can_be_discarded(&oid, p->mtime))
3163                                 if (force_object_loose(&oid, p->mtime))
3164                                         die(_("unable to force loose object"));
3165                 }
3166         }
3167 }
3168
3169 /*
3170  * This tracks any options which pack-reuse code expects to be on, or which a
3171  * reader of the pack might not understand, and which would therefore prevent
3172  * blind reuse of what we have on disk.
3173  */
3174 static int pack_options_allow_reuse(void)
3175 {
3176         return allow_pack_reuse &&
3177                pack_to_stdout &&
3178                !ignore_packed_keep_on_disk &&
3179                !ignore_packed_keep_in_core &&
3180                (!local || !have_non_local_packs) &&
3181                !incremental;
3182 }
3183
3184 static int get_object_list_from_bitmap(struct rev_info *revs)
3185 {
3186         if (!(bitmap_git = prepare_bitmap_walk(revs)))
3187                 return -1;
3188
3189         if (pack_options_allow_reuse() &&
3190             !reuse_partial_packfile_from_bitmap(
3191                         bitmap_git,
3192                         &reuse_packfile,
3193                         &reuse_packfile_objects,
3194                         &reuse_packfile_bitmap)) {
3195                 assert(reuse_packfile_objects);
3196                 nr_result += reuse_packfile_objects;
3197                 display_progress(progress_state, nr_result);
3198         }
3199
3200         traverse_bitmap_commit_list(bitmap_git, &add_object_entry_from_bitmap);
3201         return 0;
3202 }
3203
3204 static void record_recent_object(struct object *obj,
3205                                  const char *name,
3206                                  void *data)
3207 {
3208         oid_array_append(&recent_objects, &obj->oid);
3209 }
3210
3211 static void record_recent_commit(struct commit *commit, void *data)
3212 {
3213         oid_array_append(&recent_objects, &commit->object.oid);
3214 }
3215
3216 static void get_object_list(int ac, const char **av)
3217 {
3218         struct rev_info revs;
3219         struct setup_revision_opt s_r_opt = {
3220                 .allow_exclude_promisor_objects = 1,
3221         };
3222         char line[1000];
3223         int flags = 0;
3224         int save_warning;
3225
3226         repo_init_revisions(the_repository, &revs, NULL);
3227         save_commit_buffer = 0;
3228         setup_revisions(ac, av, &revs, &s_r_opt);
3229
3230         /* make sure shallows are read */
3231         is_repository_shallow(the_repository);
3232
3233         save_warning = warn_on_object_refname_ambiguity;
3234         warn_on_object_refname_ambiguity = 0;
3235
3236         while (fgets(line, sizeof(line), stdin) != NULL) {
3237                 int len = strlen(line);
3238                 if (len && line[len - 1] == '\n')
3239                         line[--len] = 0;
3240                 if (!len)
3241                         break;
3242                 if (*line == '-') {
3243                         if (!strcmp(line, "--not")) {
3244                                 flags ^= UNINTERESTING;
3245                                 write_bitmap_index = 0;
3246                                 continue;
3247                         }
3248                         if (starts_with(line, "--shallow ")) {
3249                                 struct object_id oid;
3250                                 if (get_oid_hex(line + 10, &oid))
3251                                         die("not an SHA-1 '%s'", line + 10);
3252                                 register_shallow(the_repository, &oid);
3253                                 use_bitmap_index = 0;
3254                                 continue;
3255                         }
3256                         die(_("not a rev '%s'"), line);
3257                 }
3258                 if (handle_revision_arg(line, &revs, flags, REVARG_CANNOT_BE_FILENAME))
3259                         die(_("bad revision '%s'"), line);
3260         }
3261
3262         warn_on_object_refname_ambiguity = save_warning;
3263
3264         if (use_bitmap_index && !get_object_list_from_bitmap(&revs))
3265                 return;
3266
3267         if (use_delta_islands)
3268                 load_delta_islands(the_repository, progress);
3269
3270         if (prepare_revision_walk(&revs))
3271                 die(_("revision walk setup failed"));
3272         mark_edges_uninteresting(&revs, show_edge, sparse);
3273
3274         if (!fn_show_object)
3275                 fn_show_object = show_object;
3276         traverse_commit_list_filtered(&filter_options, &revs,
3277                                       show_commit, fn_show_object, NULL,
3278                                       NULL);
3279
3280         if (unpack_unreachable_expiration) {
3281                 revs.ignore_missing_links = 1;
3282                 if (add_unseen_recent_objects_to_traversal(&revs,
3283                                 unpack_unreachable_expiration))
3284                         die(_("unable to add recent objects"));
3285                 if (prepare_revision_walk(&revs))
3286                         die(_("revision walk setup failed"));
3287                 traverse_commit_list(&revs, record_recent_commit,
3288                                      record_recent_object, NULL);
3289         }
3290
3291         if (keep_unreachable)
3292                 add_objects_in_unpacked_packs();
3293         if (pack_loose_unreachable)
3294                 add_unreachable_loose_objects();
3295         if (unpack_unreachable)
3296                 loosen_unused_packed_objects();
3297
3298         oid_array_clear(&recent_objects);
3299 }
3300
3301 static void add_extra_kept_packs(const struct string_list *names)
3302 {
3303         struct packed_git *p;
3304
3305         if (!names->nr)
3306                 return;
3307
3308         for (p = get_all_packs(the_repository); p; p = p->next) {
3309                 const char *name = basename(p->pack_name);
3310                 int i;
3311
3312                 if (!p->pack_local)
3313                         continue;
3314
3315                 for (i = 0; i < names->nr; i++)
3316                         if (!fspathcmp(name, names->items[i].string))
3317                                 break;
3318
3319                 if (i < names->nr) {
3320                         p->pack_keep_in_core = 1;
3321                         ignore_packed_keep_in_core = 1;
3322                         continue;
3323                 }
3324         }
3325 }
3326
3327 static int option_parse_index_version(const struct option *opt,
3328                                       const char *arg, int unset)
3329 {
3330         char *c;
3331         const char *val = arg;
3332
3333         BUG_ON_OPT_NEG(unset);
3334
3335         pack_idx_opts.version = strtoul(val, &c, 10);
3336         if (pack_idx_opts.version > 2)
3337                 die(_("unsupported index version %s"), val);
3338         if (*c == ',' && c[1])
3339                 pack_idx_opts.off32_limit = strtoul(c+1, &c, 0);
3340         if (*c || pack_idx_opts.off32_limit & 0x80000000)
3341                 die(_("bad index version '%s'"), val);
3342         return 0;
3343 }
3344
3345 static int option_parse_unpack_unreachable(const struct option *opt,
3346                                            const char *arg, int unset)
3347 {
3348         if (unset) {
3349                 unpack_unreachable = 0;
3350                 unpack_unreachable_expiration = 0;
3351         }
3352         else {
3353                 unpack_unreachable = 1;
3354                 if (arg)
3355                         unpack_unreachable_expiration = approxidate(arg);
3356         }
3357         return 0;
3358 }
3359
3360 int cmd_pack_objects(int argc, const char **argv, const char *prefix)
3361 {
3362         int use_internal_rev_list = 0;
3363         int shallow = 0;
3364         int all_progress_implied = 0;
3365         struct argv_array rp = ARGV_ARRAY_INIT;
3366         int rev_list_unpacked = 0, rev_list_all = 0, rev_list_reflog = 0;
3367         int rev_list_index = 0;
3368         struct string_list keep_pack_list = STRING_LIST_INIT_NODUP;
3369         struct option pack_objects_options[] = {
3370                 OPT_SET_INT('q', "quiet", &progress,
3371                             N_("do not show progress meter"), 0),
3372                 OPT_SET_INT(0, "progress", &progress,
3373                             N_("show progress meter"), 1),
3374                 OPT_SET_INT(0, "all-progress", &progress,
3375                             N_("show progress meter during object writing phase"), 2),
3376                 OPT_BOOL(0, "all-progress-implied",
3377                          &all_progress_implied,
3378                          N_("similar to --all-progress when progress meter is shown")),
3379                 { OPTION_CALLBACK, 0, "index-version", NULL, N_("<version>[,<offset>]"),
3380                   N_("write the pack index file in the specified idx format version"),
3381                   PARSE_OPT_NONEG, option_parse_index_version },
3382                 OPT_MAGNITUDE(0, "max-pack-size", &pack_size_limit,
3383                               N_("maximum size of each output pack file")),
3384                 OPT_BOOL(0, "local", &local,
3385                          N_("ignore borrowed objects from alternate object store")),
3386                 OPT_BOOL(0, "incremental", &incremental,
3387                          N_("ignore packed objects")),
3388                 OPT_INTEGER(0, "window", &window,
3389                             N_("limit pack window by objects")),
3390                 OPT_MAGNITUDE(0, "window-memory", &window_memory_limit,
3391                               N_("limit pack window by memory in addition to object limit")),
3392                 OPT_INTEGER(0, "depth", &depth,
3393                             N_("maximum length of delta chain allowed in the resulting pack")),
3394                 OPT_BOOL(0, "reuse-delta", &reuse_delta,
3395                          N_("reuse existing deltas")),
3396                 OPT_BOOL(0, "reuse-object", &reuse_object,
3397                          N_("reuse existing objects")),
3398                 OPT_BOOL(0, "delta-base-offset", &allow_ofs_delta,
3399                          N_("use OFS_DELTA objects")),
3400                 OPT_INTEGER(0, "threads", &delta_search_threads,
3401                             N_("use threads when searching for best delta matches")),
3402                 OPT_BOOL(0, "non-empty", &non_empty,
3403                          N_("do not create an empty pack output")),
3404                 OPT_BOOL(0, "revs", &use_internal_rev_list,
3405                          N_("read revision arguments from standard input")),
3406                 OPT_SET_INT_F(0, "unpacked", &rev_list_unpacked,
3407                               N_("limit the objects to those that are not yet packed"),
3408                               1, PARSE_OPT_NONEG),
3409                 OPT_SET_INT_F(0, "all", &rev_list_all,
3410                               N_("include objects reachable from any reference"),
3411                               1, PARSE_OPT_NONEG),
3412                 OPT_SET_INT_F(0, "reflog", &rev_list_reflog,
3413                               N_("include objects referred by reflog entries"),
3414                               1, PARSE_OPT_NONEG),
3415                 OPT_SET_INT_F(0, "indexed-objects", &rev_list_index,
3416                               N_("include objects referred to by the index"),
3417                               1, PARSE_OPT_NONEG),
3418                 OPT_BOOL(0, "stdout", &pack_to_stdout,
3419                          N_("output pack to stdout")),
3420                 OPT_BOOL(0, "include-tag", &include_tag,
3421                          N_("include tag objects that refer to objects to be packed")),
3422                 OPT_BOOL(0, "keep-unreachable", &keep_unreachable,
3423                          N_("keep unreachable objects")),
3424                 OPT_BOOL(0, "pack-loose-unreachable", &pack_loose_unreachable,
3425                          N_("pack loose unreachable objects")),
3426                 { OPTION_CALLBACK, 0, "unpack-unreachable", NULL, N_("time"),
3427                   N_("unpack unreachable objects newer than <time>"),
3428                   PARSE_OPT_OPTARG, option_parse_unpack_unreachable },
3429                 OPT_BOOL(0, "sparse", &sparse,
3430                          N_("use the sparse reachability algorithm")),
3431                 OPT_BOOL(0, "thin", &thin,
3432                          N_("create thin packs")),
3433                 OPT_BOOL(0, "shallow", &shallow,
3434                          N_("create packs suitable for shallow fetches")),
3435                 OPT_BOOL(0, "honor-pack-keep", &ignore_packed_keep_on_disk,
3436                          N_("ignore packs that have companion .keep file")),
3437                 OPT_STRING_LIST(0, "keep-pack", &keep_pack_list, N_("name"),
3438                                 N_("ignore this pack")),
3439                 OPT_INTEGER(0, "compression", &pack_compression_level,
3440                             N_("pack compression level")),
3441                 OPT_SET_INT(0, "keep-true-parents", &grafts_replace_parents,
3442                             N_("do not hide commits by grafts"), 0),
3443                 OPT_BOOL(0, "use-bitmap-index", &use_bitmap_index,
3444                          N_("use a bitmap index if available to speed up counting objects")),
3445                 OPT_SET_INT(0, "write-bitmap-index", &write_bitmap_index,
3446                             N_("write a bitmap index together with the pack index"),
3447                             WRITE_BITMAP_TRUE),
3448                 OPT_SET_INT_F(0, "write-bitmap-index-quiet",
3449                               &write_bitmap_index,
3450                               N_("write a bitmap index if possible"),
3451                               WRITE_BITMAP_QUIET, PARSE_OPT_HIDDEN),
3452                 OPT_PARSE_LIST_OBJECTS_FILTER(&filter_options),
3453                 { OPTION_CALLBACK, 0, "missing", NULL, N_("action"),
3454                   N_("handling for missing objects"), PARSE_OPT_NONEG,
3455                   option_parse_missing_action },
3456                 OPT_BOOL(0, "exclude-promisor-objects", &exclude_promisor_objects,
3457                          N_("do not pack objects in promisor packfiles")),
3458                 OPT_BOOL(0, "delta-islands", &use_delta_islands,
3459                          N_("respect islands during delta compression")),
3460                 OPT_END(),
3461         };
3462
3463         if (DFS_NUM_STATES > (1 << OE_DFS_STATE_BITS))
3464                 BUG("too many dfs states, increase OE_DFS_STATE_BITS");
3465
3466         read_replace_refs = 0;
3467
3468         sparse = git_env_bool("GIT_TEST_PACK_SPARSE", 0);
3469         prepare_repo_settings(the_repository);
3470         if (!sparse && the_repository->settings.pack_use_sparse != -1)
3471                 sparse = the_repository->settings.pack_use_sparse;
3472
3473         reset_pack_idx_option(&pack_idx_opts);
3474         git_config(git_pack_config, NULL);
3475
3476         progress = isatty(2);
3477         argc = parse_options(argc, argv, prefix, pack_objects_options,
3478                              pack_usage, 0);
3479
3480         if (argc) {
3481                 base_name = argv[0];
3482                 argc--;
3483         }
3484         if (pack_to_stdout != !base_name || argc)
3485                 usage_with_options(pack_usage, pack_objects_options);
3486
3487         if (depth >= (1 << OE_DEPTH_BITS)) {
3488                 warning(_("delta chain depth %d is too deep, forcing %d"),
3489                         depth, (1 << OE_DEPTH_BITS) - 1);
3490                 depth = (1 << OE_DEPTH_BITS) - 1;
3491         }
3492         if (cache_max_small_delta_size >= (1U << OE_Z_DELTA_BITS)) {
3493                 warning(_("pack.deltaCacheLimit is too high, forcing %d"),
3494                         (1U << OE_Z_DELTA_BITS) - 1);
3495                 cache_max_small_delta_size = (1U << OE_Z_DELTA_BITS) - 1;
3496         }
3497
3498         argv_array_push(&rp, "pack-objects");
3499         if (thin) {
3500                 use_internal_rev_list = 1;
3501                 argv_array_push(&rp, shallow
3502                                 ? "--objects-edge-aggressive"
3503                                 : "--objects-edge");
3504         } else
3505                 argv_array_push(&rp, "--objects");
3506
3507         if (rev_list_all) {
3508                 use_internal_rev_list = 1;
3509                 argv_array_push(&rp, "--all");
3510         }
3511         if (rev_list_reflog) {
3512                 use_internal_rev_list = 1;
3513                 argv_array_push(&rp, "--reflog");
3514         }
3515         if (rev_list_index) {
3516                 use_internal_rev_list = 1;
3517                 argv_array_push(&rp, "--indexed-objects");
3518         }
3519         if (rev_list_unpacked) {
3520                 use_internal_rev_list = 1;
3521                 argv_array_push(&rp, "--unpacked");
3522         }
3523
3524         if (exclude_promisor_objects) {
3525                 use_internal_rev_list = 1;
3526                 fetch_if_missing = 0;
3527                 argv_array_push(&rp, "--exclude-promisor-objects");
3528         }
3529         if (unpack_unreachable || keep_unreachable || pack_loose_unreachable)
3530                 use_internal_rev_list = 1;
3531
3532         if (!reuse_object)
3533                 reuse_delta = 0;
3534         if (pack_compression_level == -1)
3535                 pack_compression_level = Z_DEFAULT_COMPRESSION;
3536         else if (pack_compression_level < 0 || pack_compression_level > Z_BEST_COMPRESSION)
3537                 die(_("bad pack compression level %d"), pack_compression_level);
3538
3539         if (!delta_search_threads)      /* --threads=0 means autodetect */
3540                 delta_search_threads = online_cpus();
3541
3542         if (!HAVE_THREADS && delta_search_threads != 1)
3543                 warning(_("no threads support, ignoring --threads"));
3544         if (!pack_to_stdout && !pack_size_limit)
3545                 pack_size_limit = pack_size_limit_cfg;
3546         if (pack_to_stdout && pack_size_limit)
3547                 die(_("--max-pack-size cannot be used to build a pack for transfer"));
3548         if (pack_size_limit && pack_size_limit < 1024*1024) {
3549                 warning(_("minimum pack size limit is 1 MiB"));
3550                 pack_size_limit = 1024*1024;
3551         }
3552
3553         if (!pack_to_stdout && thin)
3554                 die(_("--thin cannot be used to build an indexable pack"));
3555
3556         if (keep_unreachable && unpack_unreachable)
3557                 die(_("--keep-unreachable and --unpack-unreachable are incompatible"));
3558         if (!rev_list_all || !rev_list_reflog || !rev_list_index)
3559                 unpack_unreachable_expiration = 0;
3560
3561         if (filter_options.choice) {
3562                 if (!pack_to_stdout)
3563                         die(_("cannot use --filter without --stdout"));
3564                 use_bitmap_index = 0;
3565         }
3566
3567         /*
3568          * "soft" reasons not to use bitmaps - for on-disk repack by default we want
3569          *
3570          * - to produce good pack (with bitmap index not-yet-packed objects are
3571          *   packed in suboptimal order).
3572          *
3573          * - to use more robust pack-generation codepath (avoiding possible
3574          *   bugs in bitmap code and possible bitmap index corruption).
3575          */
3576         if (!pack_to_stdout)
3577                 use_bitmap_index_default = 0;
3578
3579         if (use_bitmap_index < 0)
3580                 use_bitmap_index = use_bitmap_index_default;
3581
3582         /* "hard" reasons not to use bitmaps; these just won't work at all */
3583         if (!use_internal_rev_list || (!pack_to_stdout && write_bitmap_index) || is_repository_shallow(the_repository))
3584                 use_bitmap_index = 0;
3585
3586         if (pack_to_stdout || !rev_list_all)
3587                 write_bitmap_index = 0;
3588
3589         if (use_delta_islands)
3590                 argv_array_push(&rp, "--topo-order");
3591
3592         if (progress && all_progress_implied)
3593                 progress = 2;
3594
3595         add_extra_kept_packs(&keep_pack_list);
3596         if (ignore_packed_keep_on_disk) {
3597                 struct packed_git *p;
3598                 for (p = get_all_packs(the_repository); p; p = p->next)
3599                         if (p->pack_local && p->pack_keep)
3600                                 break;
3601                 if (!p) /* no keep-able packs found */
3602                         ignore_packed_keep_on_disk = 0;
3603         }
3604         if (local) {
3605                 /*
3606                  * unlike ignore_packed_keep_on_disk above, we do not
3607                  * want to unset "local" based on looking at packs, as
3608                  * it also covers non-local objects
3609                  */
3610                 struct packed_git *p;
3611                 for (p = get_all_packs(the_repository); p; p = p->next) {
3612                         if (!p->pack_local) {
3613                                 have_non_local_packs = 1;
3614                                 break;
3615                         }
3616                 }
3617         }
3618
3619         trace2_region_enter("pack-objects", "enumerate-objects",
3620                             the_repository);
3621         prepare_packing_data(the_repository, &to_pack);
3622
3623         if (progress)
3624                 progress_state = start_progress(_("Enumerating objects"), 0);
3625         if (!use_internal_rev_list)
3626                 read_object_list_from_stdin();
3627         else {
3628                 get_object_list(rp.argc, rp.argv);
3629                 argv_array_clear(&rp);
3630         }
3631         cleanup_preferred_base();
3632         if (include_tag && nr_result)
3633                 for_each_ref(add_ref_tag, NULL);
3634         stop_progress(&progress_state);
3635         trace2_region_leave("pack-objects", "enumerate-objects",
3636                             the_repository);
3637
3638         if (non_empty && !nr_result)
3639                 return 0;
3640         if (nr_result) {
3641                 trace2_region_enter("pack-objects", "prepare-pack",
3642                                     the_repository);
3643                 prepare_pack(window, depth);
3644                 trace2_region_leave("pack-objects", "prepare-pack",
3645                                     the_repository);
3646         }
3647
3648         trace2_region_enter("pack-objects", "write-pack-file", the_repository);
3649         write_pack_file();
3650         trace2_region_leave("pack-objects", "write-pack-file", the_repository);
3651
3652         if (progress)
3653                 fprintf_ln(stderr,
3654                            _("Total %"PRIu32" (delta %"PRIu32"),"
3655                              " reused %"PRIu32" (delta %"PRIu32"),"
3656                              " pack-reused %"PRIu32),
3657                            written, written_delta, reused, reused_delta,
3658                            reuse_packfile_objects);
3659         return 0;
3660 }