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