upload-pack: send part of packfile response as uri
[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
1711         if (IN_PACK(entry)) {
1712                 struct packed_git *p = IN_PACK(entry);
1713                 struct pack_window *w_curs = NULL;
1714                 int have_base = 0;
1715                 struct object_id base_ref;
1716                 struct object_entry *base_entry;
1717                 unsigned long used, used_0;
1718                 unsigned long avail;
1719                 off_t ofs;
1720                 unsigned char *buf, c;
1721                 enum object_type type;
1722                 unsigned long in_pack_size;
1723
1724                 buf = use_pack(p, &w_curs, entry->in_pack_offset, &avail);
1725
1726                 /*
1727                  * We want in_pack_type even if we do not reuse delta
1728                  * since non-delta representations could still be reused.
1729                  */
1730                 used = unpack_object_header_buffer(buf, avail,
1731                                                    &type,
1732                                                    &in_pack_size);
1733                 if (used == 0)
1734                         goto give_up;
1735
1736                 if (type < 0)
1737                         BUG("invalid type %d", type);
1738                 entry->in_pack_type = type;
1739
1740                 /*
1741                  * Determine if this is a delta and if so whether we can
1742                  * reuse it or not.  Otherwise let's find out as cheaply as
1743                  * possible what the actual type and size for this object is.
1744                  */
1745                 switch (entry->in_pack_type) {
1746                 default:
1747                         /* Not a delta hence we've already got all we need. */
1748                         oe_set_type(entry, entry->in_pack_type);
1749                         SET_SIZE(entry, in_pack_size);
1750                         entry->in_pack_header_size = used;
1751                         if (oe_type(entry) < OBJ_COMMIT || oe_type(entry) > OBJ_BLOB)
1752                                 goto give_up;
1753                         unuse_pack(&w_curs);
1754                         return;
1755                 case OBJ_REF_DELTA:
1756                         if (reuse_delta && !entry->preferred_base) {
1757                                 oidread(&base_ref,
1758                                         use_pack(p, &w_curs,
1759                                                  entry->in_pack_offset + used,
1760                                                  NULL));
1761                                 have_base = 1;
1762                         }
1763                         entry->in_pack_header_size = used + the_hash_algo->rawsz;
1764                         break;
1765                 case OBJ_OFS_DELTA:
1766                         buf = use_pack(p, &w_curs,
1767                                        entry->in_pack_offset + used, NULL);
1768                         used_0 = 0;
1769                         c = buf[used_0++];
1770                         ofs = c & 127;
1771                         while (c & 128) {
1772                                 ofs += 1;
1773                                 if (!ofs || MSB(ofs, 7)) {
1774                                         error(_("delta base offset overflow in pack for %s"),
1775                                               oid_to_hex(&entry->idx.oid));
1776                                         goto give_up;
1777                                 }
1778                                 c = buf[used_0++];
1779                                 ofs = (ofs << 7) + (c & 127);
1780                         }
1781                         ofs = entry->in_pack_offset - ofs;
1782                         if (ofs <= 0 || ofs >= entry->in_pack_offset) {
1783                                 error(_("delta base offset out of bound for %s"),
1784                                       oid_to_hex(&entry->idx.oid));
1785                                 goto give_up;
1786                         }
1787                         if (reuse_delta && !entry->preferred_base) {
1788                                 struct revindex_entry *revidx;
1789                                 revidx = find_pack_revindex(p, ofs);
1790                                 if (!revidx)
1791                                         goto give_up;
1792                                 if (!nth_packed_object_id(&base_ref, p, revidx->nr))
1793                                         have_base = 1;
1794                         }
1795                         entry->in_pack_header_size = used + used_0;
1796                         break;
1797                 }
1798
1799                 if (have_base &&
1800                     can_reuse_delta(&base_ref, entry, &base_entry)) {
1801                         oe_set_type(entry, entry->in_pack_type);
1802                         SET_SIZE(entry, in_pack_size); /* delta size */
1803                         SET_DELTA_SIZE(entry, in_pack_size);
1804
1805                         if (base_entry) {
1806                                 SET_DELTA(entry, base_entry);
1807                                 entry->delta_sibling_idx = base_entry->delta_child_idx;
1808                                 SET_DELTA_CHILD(base_entry, entry);
1809                         } else {
1810                                 SET_DELTA_EXT(entry, &base_ref);
1811                         }
1812
1813                         unuse_pack(&w_curs);
1814                         return;
1815                 }
1816
1817                 if (oe_type(entry)) {
1818                         off_t delta_pos;
1819
1820                         /*
1821                          * This must be a delta and we already know what the
1822                          * final object type is.  Let's extract the actual
1823                          * object size from the delta header.
1824                          */
1825                         delta_pos = entry->in_pack_offset + entry->in_pack_header_size;
1826                         canonical_size = get_size_from_delta(p, &w_curs, delta_pos);
1827                         if (canonical_size == 0)
1828                                 goto give_up;
1829                         SET_SIZE(entry, canonical_size);
1830                         unuse_pack(&w_curs);
1831                         return;
1832                 }
1833
1834                 /*
1835                  * No choice but to fall back to the recursive delta walk
1836                  * with oid_object_info() to find about the object type
1837                  * at this point...
1838                  */
1839                 give_up:
1840                 unuse_pack(&w_curs);
1841         }
1842
1843         oe_set_type(entry,
1844                     oid_object_info(the_repository, &entry->idx.oid, &canonical_size));
1845         if (entry->type_valid) {
1846                 SET_SIZE(entry, canonical_size);
1847         } else {
1848                 /*
1849                  * Bad object type is checked in prepare_pack().  This is
1850                  * to permit a missing preferred base object to be ignored
1851                  * as a preferred base.  Doing so can result in a larger
1852                  * pack file, but the transfer will still take place.
1853                  */
1854         }
1855 }
1856
1857 static int pack_offset_sort(const void *_a, const void *_b)
1858 {
1859         const struct object_entry *a = *(struct object_entry **)_a;
1860         const struct object_entry *b = *(struct object_entry **)_b;
1861         const struct packed_git *a_in_pack = IN_PACK(a);
1862         const struct packed_git *b_in_pack = IN_PACK(b);
1863
1864         /* avoid filesystem trashing with loose objects */
1865         if (!a_in_pack && !b_in_pack)
1866                 return oidcmp(&a->idx.oid, &b->idx.oid);
1867
1868         if (a_in_pack < b_in_pack)
1869                 return -1;
1870         if (a_in_pack > b_in_pack)
1871                 return 1;
1872         return a->in_pack_offset < b->in_pack_offset ? -1 :
1873                         (a->in_pack_offset > b->in_pack_offset);
1874 }
1875
1876 /*
1877  * Drop an on-disk delta we were planning to reuse. Naively, this would
1878  * just involve blanking out the "delta" field, but we have to deal
1879  * with some extra book-keeping:
1880  *
1881  *   1. Removing ourselves from the delta_sibling linked list.
1882  *
1883  *   2. Updating our size/type to the non-delta representation. These were
1884  *      either not recorded initially (size) or overwritten with the delta type
1885  *      (type) when check_object() decided to reuse the delta.
1886  *
1887  *   3. Resetting our delta depth, as we are now a base object.
1888  */
1889 static void drop_reused_delta(struct object_entry *entry)
1890 {
1891         unsigned *idx = &to_pack.objects[entry->delta_idx - 1].delta_child_idx;
1892         struct object_info oi = OBJECT_INFO_INIT;
1893         enum object_type type;
1894         unsigned long size;
1895
1896         while (*idx) {
1897                 struct object_entry *oe = &to_pack.objects[*idx - 1];
1898
1899                 if (oe == entry)
1900                         *idx = oe->delta_sibling_idx;
1901                 else
1902                         idx = &oe->delta_sibling_idx;
1903         }
1904         SET_DELTA(entry, NULL);
1905         entry->depth = 0;
1906
1907         oi.sizep = &size;
1908         oi.typep = &type;
1909         if (packed_object_info(the_repository, IN_PACK(entry), entry->in_pack_offset, &oi) < 0) {
1910                 /*
1911                  * We failed to get the info from this pack for some reason;
1912                  * fall back to oid_object_info, which may find another copy.
1913                  * And if that fails, the error will be recorded in oe_type(entry)
1914                  * and dealt with in prepare_pack().
1915                  */
1916                 oe_set_type(entry,
1917                             oid_object_info(the_repository, &entry->idx.oid, &size));
1918         } else {
1919                 oe_set_type(entry, type);
1920         }
1921         SET_SIZE(entry, size);
1922 }
1923
1924 /*
1925  * Follow the chain of deltas from this entry onward, throwing away any links
1926  * that cause us to hit a cycle (as determined by the DFS state flags in
1927  * the entries).
1928  *
1929  * We also detect too-long reused chains that would violate our --depth
1930  * limit.
1931  */
1932 static void break_delta_chains(struct object_entry *entry)
1933 {
1934         /*
1935          * The actual depth of each object we will write is stored as an int,
1936          * as it cannot exceed our int "depth" limit. But before we break
1937          * changes based no that limit, we may potentially go as deep as the
1938          * number of objects, which is elsewhere bounded to a uint32_t.
1939          */
1940         uint32_t total_depth;
1941         struct object_entry *cur, *next;
1942
1943         for (cur = entry, total_depth = 0;
1944              cur;
1945              cur = DELTA(cur), total_depth++) {
1946                 if (cur->dfs_state == DFS_DONE) {
1947                         /*
1948                          * We've already seen this object and know it isn't
1949                          * part of a cycle. We do need to append its depth
1950                          * to our count.
1951                          */
1952                         total_depth += cur->depth;
1953                         break;
1954                 }
1955
1956                 /*
1957                  * We break cycles before looping, so an ACTIVE state (or any
1958                  * other cruft which made its way into the state variable)
1959                  * is a bug.
1960                  */
1961                 if (cur->dfs_state != DFS_NONE)
1962                         BUG("confusing delta dfs state in first pass: %d",
1963                             cur->dfs_state);
1964
1965                 /*
1966                  * Now we know this is the first time we've seen the object. If
1967                  * it's not a delta, we're done traversing, but we'll mark it
1968                  * done to save time on future traversals.
1969                  */
1970                 if (!DELTA(cur)) {
1971                         cur->dfs_state = DFS_DONE;
1972                         break;
1973                 }
1974
1975                 /*
1976                  * Mark ourselves as active and see if the next step causes
1977                  * us to cycle to another active object. It's important to do
1978                  * this _before_ we loop, because it impacts where we make the
1979                  * cut, and thus how our total_depth counter works.
1980                  * E.g., We may see a partial loop like:
1981                  *
1982                  *   A -> B -> C -> D -> B
1983                  *
1984                  * Cutting B->C breaks the cycle. But now the depth of A is
1985                  * only 1, and our total_depth counter is at 3. The size of the
1986                  * error is always one less than the size of the cycle we
1987                  * broke. Commits C and D were "lost" from A's chain.
1988                  *
1989                  * If we instead cut D->B, then the depth of A is correct at 3.
1990                  * We keep all commits in the chain that we examined.
1991                  */
1992                 cur->dfs_state = DFS_ACTIVE;
1993                 if (DELTA(cur)->dfs_state == DFS_ACTIVE) {
1994                         drop_reused_delta(cur);
1995                         cur->dfs_state = DFS_DONE;
1996                         break;
1997                 }
1998         }
1999
2000         /*
2001          * And now that we've gone all the way to the bottom of the chain, we
2002          * need to clear the active flags and set the depth fields as
2003          * appropriate. Unlike the loop above, which can quit when it drops a
2004          * delta, we need to keep going to look for more depth cuts. So we need
2005          * an extra "next" pointer to keep going after we reset cur->delta.
2006          */
2007         for (cur = entry; cur; cur = next) {
2008                 next = DELTA(cur);
2009
2010                 /*
2011                  * We should have a chain of zero or more ACTIVE states down to
2012                  * a final DONE. We can quit after the DONE, because either it
2013                  * has no bases, or we've already handled them in a previous
2014                  * call.
2015                  */
2016                 if (cur->dfs_state == DFS_DONE)
2017                         break;
2018                 else if (cur->dfs_state != DFS_ACTIVE)
2019                         BUG("confusing delta dfs state in second pass: %d",
2020                             cur->dfs_state);
2021
2022                 /*
2023                  * If the total_depth is more than depth, then we need to snip
2024                  * the chain into two or more smaller chains that don't exceed
2025                  * the maximum depth. Most of the resulting chains will contain
2026                  * (depth + 1) entries (i.e., depth deltas plus one base), and
2027                  * the last chain (i.e., the one containing entry) will contain
2028                  * whatever entries are left over, namely
2029                  * (total_depth % (depth + 1)) of them.
2030                  *
2031                  * Since we are iterating towards decreasing depth, we need to
2032                  * decrement total_depth as we go, and we need to write to the
2033                  * entry what its final depth will be after all of the
2034                  * snipping. Since we're snipping into chains of length (depth
2035                  * + 1) entries, the final depth of an entry will be its
2036                  * original depth modulo (depth + 1). Any time we encounter an
2037                  * entry whose final depth is supposed to be zero, we snip it
2038                  * from its delta base, thereby making it so.
2039                  */
2040                 cur->depth = (total_depth--) % (depth + 1);
2041                 if (!cur->depth)
2042                         drop_reused_delta(cur);
2043
2044                 cur->dfs_state = DFS_DONE;
2045         }
2046 }
2047
2048 static void get_object_details(void)
2049 {
2050         uint32_t i;
2051         struct object_entry **sorted_by_offset;
2052
2053         if (progress)
2054                 progress_state = start_progress(_("Counting objects"),
2055                                                 to_pack.nr_objects);
2056
2057         sorted_by_offset = xcalloc(to_pack.nr_objects, sizeof(struct object_entry *));
2058         for (i = 0; i < to_pack.nr_objects; i++)
2059                 sorted_by_offset[i] = to_pack.objects + i;
2060         QSORT(sorted_by_offset, to_pack.nr_objects, pack_offset_sort);
2061
2062         for (i = 0; i < to_pack.nr_objects; i++) {
2063                 struct object_entry *entry = sorted_by_offset[i];
2064                 check_object(entry);
2065                 if (entry->type_valid &&
2066                     oe_size_greater_than(&to_pack, entry, big_file_threshold))
2067                         entry->no_try_delta = 1;
2068                 display_progress(progress_state, i + 1);
2069         }
2070         stop_progress(&progress_state);
2071
2072         /*
2073          * This must happen in a second pass, since we rely on the delta
2074          * information for the whole list being completed.
2075          */
2076         for (i = 0; i < to_pack.nr_objects; i++)
2077                 break_delta_chains(&to_pack.objects[i]);
2078
2079         free(sorted_by_offset);
2080 }
2081
2082 /*
2083  * We search for deltas in a list sorted by type, by filename hash, and then
2084  * by size, so that we see progressively smaller and smaller files.
2085  * That's because we prefer deltas to be from the bigger file
2086  * to the smaller -- deletes are potentially cheaper, but perhaps
2087  * more importantly, the bigger file is likely the more recent
2088  * one.  The deepest deltas are therefore the oldest objects which are
2089  * less susceptible to be accessed often.
2090  */
2091 static int type_size_sort(const void *_a, const void *_b)
2092 {
2093         const struct object_entry *a = *(struct object_entry **)_a;
2094         const struct object_entry *b = *(struct object_entry **)_b;
2095         const enum object_type a_type = oe_type(a);
2096         const enum object_type b_type = oe_type(b);
2097         const unsigned long a_size = SIZE(a);
2098         const unsigned long b_size = SIZE(b);
2099
2100         if (a_type > b_type)
2101                 return -1;
2102         if (a_type < b_type)
2103                 return 1;
2104         if (a->hash > b->hash)
2105                 return -1;
2106         if (a->hash < b->hash)
2107                 return 1;
2108         if (a->preferred_base > b->preferred_base)
2109                 return -1;
2110         if (a->preferred_base < b->preferred_base)
2111                 return 1;
2112         if (use_delta_islands) {
2113                 const int island_cmp = island_delta_cmp(&a->idx.oid, &b->idx.oid);
2114                 if (island_cmp)
2115                         return island_cmp;
2116         }
2117         if (a_size > b_size)
2118                 return -1;
2119         if (a_size < b_size)
2120                 return 1;
2121         return a < b ? -1 : (a > b);  /* newest first */
2122 }
2123
2124 struct unpacked {
2125         struct object_entry *entry;
2126         void *data;
2127         struct delta_index *index;
2128         unsigned depth;
2129 };
2130
2131 static int delta_cacheable(unsigned long src_size, unsigned long trg_size,
2132                            unsigned long delta_size)
2133 {
2134         if (max_delta_cache_size && delta_cache_size + delta_size > max_delta_cache_size)
2135                 return 0;
2136
2137         if (delta_size < cache_max_small_delta_size)
2138                 return 1;
2139
2140         /* cache delta, if objects are large enough compared to delta size */
2141         if ((src_size >> 20) + (trg_size >> 21) > (delta_size >> 10))
2142                 return 1;
2143
2144         return 0;
2145 }
2146
2147 /* Protect delta_cache_size */
2148 static pthread_mutex_t cache_mutex;
2149 #define cache_lock()            pthread_mutex_lock(&cache_mutex)
2150 #define cache_unlock()          pthread_mutex_unlock(&cache_mutex)
2151
2152 /*
2153  * Protect object list partitioning (e.g. struct thread_param) and
2154  * progress_state
2155  */
2156 static pthread_mutex_t progress_mutex;
2157 #define progress_lock()         pthread_mutex_lock(&progress_mutex)
2158 #define progress_unlock()       pthread_mutex_unlock(&progress_mutex)
2159
2160 /*
2161  * Access to struct object_entry is unprotected since each thread owns
2162  * a portion of the main object list. Just don't access object entries
2163  * ahead in the list because they can be stolen and would need
2164  * progress_mutex for protection.
2165  */
2166
2167 /*
2168  * Return the size of the object without doing any delta
2169  * reconstruction (so non-deltas are true object sizes, but deltas
2170  * return the size of the delta data).
2171  */
2172 unsigned long oe_get_size_slow(struct packing_data *pack,
2173                                const struct object_entry *e)
2174 {
2175         struct packed_git *p;
2176         struct pack_window *w_curs;
2177         unsigned char *buf;
2178         enum object_type type;
2179         unsigned long used, avail, size;
2180
2181         if (e->type_ != OBJ_OFS_DELTA && e->type_ != OBJ_REF_DELTA) {
2182                 packing_data_lock(&to_pack);
2183                 if (oid_object_info(the_repository, &e->idx.oid, &size) < 0)
2184                         die(_("unable to get size of %s"),
2185                             oid_to_hex(&e->idx.oid));
2186                 packing_data_unlock(&to_pack);
2187                 return size;
2188         }
2189
2190         p = oe_in_pack(pack, e);
2191         if (!p)
2192                 BUG("when e->type is a delta, it must belong to a pack");
2193
2194         packing_data_lock(&to_pack);
2195         w_curs = NULL;
2196         buf = use_pack(p, &w_curs, e->in_pack_offset, &avail);
2197         used = unpack_object_header_buffer(buf, avail, &type, &size);
2198         if (used == 0)
2199                 die(_("unable to parse object header of %s"),
2200                     oid_to_hex(&e->idx.oid));
2201
2202         unuse_pack(&w_curs);
2203         packing_data_unlock(&to_pack);
2204         return size;
2205 }
2206
2207 static int try_delta(struct unpacked *trg, struct unpacked *src,
2208                      unsigned max_depth, unsigned long *mem_usage)
2209 {
2210         struct object_entry *trg_entry = trg->entry;
2211         struct object_entry *src_entry = src->entry;
2212         unsigned long trg_size, src_size, delta_size, sizediff, max_size, sz;
2213         unsigned ref_depth;
2214         enum object_type type;
2215         void *delta_buf;
2216
2217         /* Don't bother doing diffs between different types */
2218         if (oe_type(trg_entry) != oe_type(src_entry))
2219                 return -1;
2220
2221         /*
2222          * We do not bother to try a delta that we discarded on an
2223          * earlier try, but only when reusing delta data.  Note that
2224          * src_entry that is marked as the preferred_base should always
2225          * be considered, as even if we produce a suboptimal delta against
2226          * it, we will still save the transfer cost, as we already know
2227          * the other side has it and we won't send src_entry at all.
2228          */
2229         if (reuse_delta && IN_PACK(trg_entry) &&
2230             IN_PACK(trg_entry) == IN_PACK(src_entry) &&
2231             !src_entry->preferred_base &&
2232             trg_entry->in_pack_type != OBJ_REF_DELTA &&
2233             trg_entry->in_pack_type != OBJ_OFS_DELTA)
2234                 return 0;
2235
2236         /* Let's not bust the allowed depth. */
2237         if (src->depth >= max_depth)
2238                 return 0;
2239
2240         /* Now some size filtering heuristics. */
2241         trg_size = SIZE(trg_entry);
2242         if (!DELTA(trg_entry)) {
2243                 max_size = trg_size/2 - the_hash_algo->rawsz;
2244                 ref_depth = 1;
2245         } else {
2246                 max_size = DELTA_SIZE(trg_entry);
2247                 ref_depth = trg->depth;
2248         }
2249         max_size = (uint64_t)max_size * (max_depth - src->depth) /
2250                                                 (max_depth - ref_depth + 1);
2251         if (max_size == 0)
2252                 return 0;
2253         src_size = SIZE(src_entry);
2254         sizediff = src_size < trg_size ? trg_size - src_size : 0;
2255         if (sizediff >= max_size)
2256                 return 0;
2257         if (trg_size < src_size / 32)
2258                 return 0;
2259
2260         if (!in_same_island(&trg->entry->idx.oid, &src->entry->idx.oid))
2261                 return 0;
2262
2263         /* Load data if not already done */
2264         if (!trg->data) {
2265                 packing_data_lock(&to_pack);
2266                 trg->data = read_object_file(&trg_entry->idx.oid, &type, &sz);
2267                 packing_data_unlock(&to_pack);
2268                 if (!trg->data)
2269                         die(_("object %s cannot be read"),
2270                             oid_to_hex(&trg_entry->idx.oid));
2271                 if (sz != trg_size)
2272                         die(_("object %s inconsistent object length (%"PRIuMAX" vs %"PRIuMAX")"),
2273                             oid_to_hex(&trg_entry->idx.oid), (uintmax_t)sz,
2274                             (uintmax_t)trg_size);
2275                 *mem_usage += sz;
2276         }
2277         if (!src->data) {
2278                 packing_data_lock(&to_pack);
2279                 src->data = read_object_file(&src_entry->idx.oid, &type, &sz);
2280                 packing_data_unlock(&to_pack);
2281                 if (!src->data) {
2282                         if (src_entry->preferred_base) {
2283                                 static int warned = 0;
2284                                 if (!warned++)
2285                                         warning(_("object %s cannot be read"),
2286                                                 oid_to_hex(&src_entry->idx.oid));
2287                                 /*
2288                                  * Those objects are not included in the
2289                                  * resulting pack.  Be resilient and ignore
2290                                  * them if they can't be read, in case the
2291                                  * pack could be created nevertheless.
2292                                  */
2293                                 return 0;
2294                         }
2295                         die(_("object %s cannot be read"),
2296                             oid_to_hex(&src_entry->idx.oid));
2297                 }
2298                 if (sz != src_size)
2299                         die(_("object %s inconsistent object length (%"PRIuMAX" vs %"PRIuMAX")"),
2300                             oid_to_hex(&src_entry->idx.oid), (uintmax_t)sz,
2301                             (uintmax_t)src_size);
2302                 *mem_usage += sz;
2303         }
2304         if (!src->index) {
2305                 src->index = create_delta_index(src->data, src_size);
2306                 if (!src->index) {
2307                         static int warned = 0;
2308                         if (!warned++)
2309                                 warning(_("suboptimal pack - out of memory"));
2310                         return 0;
2311                 }
2312                 *mem_usage += sizeof_delta_index(src->index);
2313         }
2314
2315         delta_buf = create_delta(src->index, trg->data, trg_size, &delta_size, max_size);
2316         if (!delta_buf)
2317                 return 0;
2318
2319         if (DELTA(trg_entry)) {
2320                 /* Prefer only shallower same-sized deltas. */
2321                 if (delta_size == DELTA_SIZE(trg_entry) &&
2322                     src->depth + 1 >= trg->depth) {
2323                         free(delta_buf);
2324                         return 0;
2325                 }
2326         }
2327
2328         /*
2329          * Handle memory allocation outside of the cache
2330          * accounting lock.  Compiler will optimize the strangeness
2331          * away when NO_PTHREADS is defined.
2332          */
2333         free(trg_entry->delta_data);
2334         cache_lock();
2335         if (trg_entry->delta_data) {
2336                 delta_cache_size -= DELTA_SIZE(trg_entry);
2337                 trg_entry->delta_data = NULL;
2338         }
2339         if (delta_cacheable(src_size, trg_size, delta_size)) {
2340                 delta_cache_size += delta_size;
2341                 cache_unlock();
2342                 trg_entry->delta_data = xrealloc(delta_buf, delta_size);
2343         } else {
2344                 cache_unlock();
2345                 free(delta_buf);
2346         }
2347
2348         SET_DELTA(trg_entry, src_entry);
2349         SET_DELTA_SIZE(trg_entry, delta_size);
2350         trg->depth = src->depth + 1;
2351
2352         return 1;
2353 }
2354
2355 static unsigned int check_delta_limit(struct object_entry *me, unsigned int n)
2356 {
2357         struct object_entry *child = DELTA_CHILD(me);
2358         unsigned int m = n;
2359         while (child) {
2360                 const unsigned int c = check_delta_limit(child, n + 1);
2361                 if (m < c)
2362                         m = c;
2363                 child = DELTA_SIBLING(child);
2364         }
2365         return m;
2366 }
2367
2368 static unsigned long free_unpacked(struct unpacked *n)
2369 {
2370         unsigned long freed_mem = sizeof_delta_index(n->index);
2371         free_delta_index(n->index);
2372         n->index = NULL;
2373         if (n->data) {
2374                 freed_mem += SIZE(n->entry);
2375                 FREE_AND_NULL(n->data);
2376         }
2377         n->entry = NULL;
2378         n->depth = 0;
2379         return freed_mem;
2380 }
2381
2382 static void find_deltas(struct object_entry **list, unsigned *list_size,
2383                         int window, int depth, unsigned *processed)
2384 {
2385         uint32_t i, idx = 0, count = 0;
2386         struct unpacked *array;
2387         unsigned long mem_usage = 0;
2388
2389         array = xcalloc(window, sizeof(struct unpacked));
2390
2391         for (;;) {
2392                 struct object_entry *entry;
2393                 struct unpacked *n = array + idx;
2394                 int j, max_depth, best_base = -1;
2395
2396                 progress_lock();
2397                 if (!*list_size) {
2398                         progress_unlock();
2399                         break;
2400                 }
2401                 entry = *list++;
2402                 (*list_size)--;
2403                 if (!entry->preferred_base) {
2404                         (*processed)++;
2405                         display_progress(progress_state, *processed);
2406                 }
2407                 progress_unlock();
2408
2409                 mem_usage -= free_unpacked(n);
2410                 n->entry = entry;
2411
2412                 while (window_memory_limit &&
2413                        mem_usage > window_memory_limit &&
2414                        count > 1) {
2415                         const uint32_t tail = (idx + window - count) % window;
2416                         mem_usage -= free_unpacked(array + tail);
2417                         count--;
2418                 }
2419
2420                 /* We do not compute delta to *create* objects we are not
2421                  * going to pack.
2422                  */
2423                 if (entry->preferred_base)
2424                         goto next;
2425
2426                 /*
2427                  * If the current object is at pack edge, take the depth the
2428                  * objects that depend on the current object into account
2429                  * otherwise they would become too deep.
2430                  */
2431                 max_depth = depth;
2432                 if (DELTA_CHILD(entry)) {
2433                         max_depth -= check_delta_limit(entry, 0);
2434                         if (max_depth <= 0)
2435                                 goto next;
2436                 }
2437
2438                 j = window;
2439                 while (--j > 0) {
2440                         int ret;
2441                         uint32_t other_idx = idx + j;
2442                         struct unpacked *m;
2443                         if (other_idx >= window)
2444                                 other_idx -= window;
2445                         m = array + other_idx;
2446                         if (!m->entry)
2447                                 break;
2448                         ret = try_delta(n, m, max_depth, &mem_usage);
2449                         if (ret < 0)
2450                                 break;
2451                         else if (ret > 0)
2452                                 best_base = other_idx;
2453                 }
2454
2455                 /*
2456                  * If we decided to cache the delta data, then it is best
2457                  * to compress it right away.  First because we have to do
2458                  * it anyway, and doing it here while we're threaded will
2459                  * save a lot of time in the non threaded write phase,
2460                  * as well as allow for caching more deltas within
2461                  * the same cache size limit.
2462                  * ...
2463                  * But only if not writing to stdout, since in that case
2464                  * the network is most likely throttling writes anyway,
2465                  * and therefore it is best to go to the write phase ASAP
2466                  * instead, as we can afford spending more time compressing
2467                  * between writes at that moment.
2468                  */
2469                 if (entry->delta_data && !pack_to_stdout) {
2470                         unsigned long size;
2471
2472                         size = do_compress(&entry->delta_data, DELTA_SIZE(entry));
2473                         if (size < (1U << OE_Z_DELTA_BITS)) {
2474                                 entry->z_delta_size = size;
2475                                 cache_lock();
2476                                 delta_cache_size -= DELTA_SIZE(entry);
2477                                 delta_cache_size += entry->z_delta_size;
2478                                 cache_unlock();
2479                         } else {
2480                                 FREE_AND_NULL(entry->delta_data);
2481                                 entry->z_delta_size = 0;
2482                         }
2483                 }
2484
2485                 /* if we made n a delta, and if n is already at max
2486                  * depth, leaving it in the window is pointless.  we
2487                  * should evict it first.
2488                  */
2489                 if (DELTA(entry) && max_depth <= n->depth)
2490                         continue;
2491
2492                 /*
2493                  * Move the best delta base up in the window, after the
2494                  * currently deltified object, to keep it longer.  It will
2495                  * be the first base object to be attempted next.
2496                  */
2497                 if (DELTA(entry)) {
2498                         struct unpacked swap = array[best_base];
2499                         int dist = (window + idx - best_base) % window;
2500                         int dst = best_base;
2501                         while (dist--) {
2502                                 int src = (dst + 1) % window;
2503                                 array[dst] = array[src];
2504                                 dst = src;
2505                         }
2506                         array[dst] = swap;
2507                 }
2508
2509                 next:
2510                 idx++;
2511                 if (count + 1 < window)
2512                         count++;
2513                 if (idx >= window)
2514                         idx = 0;
2515         }
2516
2517         for (i = 0; i < window; ++i) {
2518                 free_delta_index(array[i].index);
2519                 free(array[i].data);
2520         }
2521         free(array);
2522 }
2523
2524 /*
2525  * The main object list is split into smaller lists, each is handed to
2526  * one worker.
2527  *
2528  * The main thread waits on the condition that (at least) one of the workers
2529  * has stopped working (which is indicated in the .working member of
2530  * struct thread_params).
2531  *
2532  * When a work thread has completed its work, it sets .working to 0 and
2533  * signals the main thread and waits on the condition that .data_ready
2534  * becomes 1.
2535  *
2536  * The main thread steals half of the work from the worker that has
2537  * most work left to hand it to the idle worker.
2538  */
2539
2540 struct thread_params {
2541         pthread_t thread;
2542         struct object_entry **list;
2543         unsigned list_size;
2544         unsigned remaining;
2545         int window;
2546         int depth;
2547         int working;
2548         int data_ready;
2549         pthread_mutex_t mutex;
2550         pthread_cond_t cond;
2551         unsigned *processed;
2552 };
2553
2554 static pthread_cond_t progress_cond;
2555
2556 /*
2557  * Mutex and conditional variable can't be statically-initialized on Windows.
2558  */
2559 static void init_threaded_search(void)
2560 {
2561         pthread_mutex_init(&cache_mutex, NULL);
2562         pthread_mutex_init(&progress_mutex, NULL);
2563         pthread_cond_init(&progress_cond, NULL);
2564 }
2565
2566 static void cleanup_threaded_search(void)
2567 {
2568         pthread_cond_destroy(&progress_cond);
2569         pthread_mutex_destroy(&cache_mutex);
2570         pthread_mutex_destroy(&progress_mutex);
2571 }
2572
2573 static void *threaded_find_deltas(void *arg)
2574 {
2575         struct thread_params *me = arg;
2576
2577         progress_lock();
2578         while (me->remaining) {
2579                 progress_unlock();
2580
2581                 find_deltas(me->list, &me->remaining,
2582                             me->window, me->depth, me->processed);
2583
2584                 progress_lock();
2585                 me->working = 0;
2586                 pthread_cond_signal(&progress_cond);
2587                 progress_unlock();
2588
2589                 /*
2590                  * We must not set ->data_ready before we wait on the
2591                  * condition because the main thread may have set it to 1
2592                  * before we get here. In order to be sure that new
2593                  * work is available if we see 1 in ->data_ready, it
2594                  * was initialized to 0 before this thread was spawned
2595                  * and we reset it to 0 right away.
2596                  */
2597                 pthread_mutex_lock(&me->mutex);
2598                 while (!me->data_ready)
2599                         pthread_cond_wait(&me->cond, &me->mutex);
2600                 me->data_ready = 0;
2601                 pthread_mutex_unlock(&me->mutex);
2602
2603                 progress_lock();
2604         }
2605         progress_unlock();
2606         /* leave ->working 1 so that this doesn't get more work assigned */
2607         return NULL;
2608 }
2609
2610 static void ll_find_deltas(struct object_entry **list, unsigned list_size,
2611                            int window, int depth, unsigned *processed)
2612 {
2613         struct thread_params *p;
2614         int i, ret, active_threads = 0;
2615
2616         init_threaded_search();
2617
2618         if (delta_search_threads <= 1) {
2619                 find_deltas(list, &list_size, window, depth, processed);
2620                 cleanup_threaded_search();
2621                 return;
2622         }
2623         if (progress > pack_to_stdout)
2624                 fprintf_ln(stderr, _("Delta compression using up to %d threads"),
2625                            delta_search_threads);
2626         p = xcalloc(delta_search_threads, sizeof(*p));
2627
2628         /* Partition the work amongst work threads. */
2629         for (i = 0; i < delta_search_threads; i++) {
2630                 unsigned sub_size = list_size / (delta_search_threads - i);
2631
2632                 /* don't use too small segments or no deltas will be found */
2633                 if (sub_size < 2*window && i+1 < delta_search_threads)
2634                         sub_size = 0;
2635
2636                 p[i].window = window;
2637                 p[i].depth = depth;
2638                 p[i].processed = processed;
2639                 p[i].working = 1;
2640                 p[i].data_ready = 0;
2641
2642                 /* try to split chunks on "path" boundaries */
2643                 while (sub_size && sub_size < list_size &&
2644                        list[sub_size]->hash &&
2645                        list[sub_size]->hash == list[sub_size-1]->hash)
2646                         sub_size++;
2647
2648                 p[i].list = list;
2649                 p[i].list_size = sub_size;
2650                 p[i].remaining = sub_size;
2651
2652                 list += sub_size;
2653                 list_size -= sub_size;
2654         }
2655
2656         /* Start work threads. */
2657         for (i = 0; i < delta_search_threads; i++) {
2658                 if (!p[i].list_size)
2659                         continue;
2660                 pthread_mutex_init(&p[i].mutex, NULL);
2661                 pthread_cond_init(&p[i].cond, NULL);
2662                 ret = pthread_create(&p[i].thread, NULL,
2663                                      threaded_find_deltas, &p[i]);
2664                 if (ret)
2665                         die(_("unable to create thread: %s"), strerror(ret));
2666                 active_threads++;
2667         }
2668
2669         /*
2670          * Now let's wait for work completion.  Each time a thread is done
2671          * with its work, we steal half of the remaining work from the
2672          * thread with the largest number of unprocessed objects and give
2673          * it to that newly idle thread.  This ensure good load balancing
2674          * until the remaining object list segments are simply too short
2675          * to be worth splitting anymore.
2676          */
2677         while (active_threads) {
2678                 struct thread_params *target = NULL;
2679                 struct thread_params *victim = NULL;
2680                 unsigned sub_size = 0;
2681
2682                 progress_lock();
2683                 for (;;) {
2684                         for (i = 0; !target && i < delta_search_threads; i++)
2685                                 if (!p[i].working)
2686                                         target = &p[i];
2687                         if (target)
2688                                 break;
2689                         pthread_cond_wait(&progress_cond, &progress_mutex);
2690                 }
2691
2692                 for (i = 0; i < delta_search_threads; i++)
2693                         if (p[i].remaining > 2*window &&
2694                             (!victim || victim->remaining < p[i].remaining))
2695                                 victim = &p[i];
2696                 if (victim) {
2697                         sub_size = victim->remaining / 2;
2698                         list = victim->list + victim->list_size - sub_size;
2699                         while (sub_size && list[0]->hash &&
2700                                list[0]->hash == list[-1]->hash) {
2701                                 list++;
2702                                 sub_size--;
2703                         }
2704                         if (!sub_size) {
2705                                 /*
2706                                  * It is possible for some "paths" to have
2707                                  * so many objects that no hash boundary
2708                                  * might be found.  Let's just steal the
2709                                  * exact half in that case.
2710                                  */
2711                                 sub_size = victim->remaining / 2;
2712                                 list -= sub_size;
2713                         }
2714                         target->list = list;
2715                         victim->list_size -= sub_size;
2716                         victim->remaining -= sub_size;
2717                 }
2718                 target->list_size = sub_size;
2719                 target->remaining = sub_size;
2720                 target->working = 1;
2721                 progress_unlock();
2722
2723                 pthread_mutex_lock(&target->mutex);
2724                 target->data_ready = 1;
2725                 pthread_cond_signal(&target->cond);
2726                 pthread_mutex_unlock(&target->mutex);
2727
2728                 if (!sub_size) {
2729                         pthread_join(target->thread, NULL);
2730                         pthread_cond_destroy(&target->cond);
2731                         pthread_mutex_destroy(&target->mutex);
2732                         active_threads--;
2733                 }
2734         }
2735         cleanup_threaded_search();
2736         free(p);
2737 }
2738
2739 static int obj_is_packed(const struct object_id *oid)
2740 {
2741         return packlist_find(&to_pack, oid) ||
2742                 (reuse_packfile_bitmap &&
2743                  bitmap_walk_contains(bitmap_git, reuse_packfile_bitmap, oid));
2744 }
2745
2746 static void add_tag_chain(const struct object_id *oid)
2747 {
2748         struct tag *tag;
2749
2750         /*
2751          * We catch duplicates already in add_object_entry(), but we'd
2752          * prefer to do this extra check to avoid having to parse the
2753          * tag at all if we already know that it's being packed (e.g., if
2754          * it was included via bitmaps, we would not have parsed it
2755          * previously).
2756          */
2757         if (obj_is_packed(oid))
2758                 return;
2759
2760         tag = lookup_tag(the_repository, oid);
2761         while (1) {
2762                 if (!tag || parse_tag(tag) || !tag->tagged)
2763                         die(_("unable to pack objects reachable from tag %s"),
2764                             oid_to_hex(oid));
2765
2766                 add_object_entry(&tag->object.oid, OBJ_TAG, NULL, 0);
2767
2768                 if (tag->tagged->type != OBJ_TAG)
2769                         return;
2770
2771                 tag = (struct tag *)tag->tagged;
2772         }
2773 }
2774
2775 static int add_ref_tag(const char *path, const struct object_id *oid, int flag, void *cb_data)
2776 {
2777         struct object_id peeled;
2778
2779         if (starts_with(path, "refs/tags/") && /* is a tag? */
2780             !peel_ref(path, &peeled)    && /* peelable? */
2781             obj_is_packed(&peeled)) /* object packed? */
2782                 add_tag_chain(oid);
2783         return 0;
2784 }
2785
2786 static void prepare_pack(int window, int depth)
2787 {
2788         struct object_entry **delta_list;
2789         uint32_t i, nr_deltas;
2790         unsigned n;
2791
2792         if (use_delta_islands)
2793                 resolve_tree_islands(the_repository, progress, &to_pack);
2794
2795         get_object_details();
2796
2797         /*
2798          * If we're locally repacking then we need to be doubly careful
2799          * from now on in order to make sure no stealth corruption gets
2800          * propagated to the new pack.  Clients receiving streamed packs
2801          * should validate everything they get anyway so no need to incur
2802          * the additional cost here in that case.
2803          */
2804         if (!pack_to_stdout)
2805                 do_check_packed_object_crc = 1;
2806
2807         if (!to_pack.nr_objects || !window || !depth)
2808                 return;
2809
2810         ALLOC_ARRAY(delta_list, to_pack.nr_objects);
2811         nr_deltas = n = 0;
2812
2813         for (i = 0; i < to_pack.nr_objects; i++) {
2814                 struct object_entry *entry = to_pack.objects + i;
2815
2816                 if (DELTA(entry))
2817                         /* This happens if we decided to reuse existing
2818                          * delta from a pack.  "reuse_delta &&" is implied.
2819                          */
2820                         continue;
2821
2822                 if (!entry->type_valid ||
2823                     oe_size_less_than(&to_pack, entry, 50))
2824                         continue;
2825
2826                 if (entry->no_try_delta)
2827                         continue;
2828
2829                 if (!entry->preferred_base) {
2830                         nr_deltas++;
2831                         if (oe_type(entry) < 0)
2832                                 die(_("unable to get type of object %s"),
2833                                     oid_to_hex(&entry->idx.oid));
2834                 } else {
2835                         if (oe_type(entry) < 0) {
2836                                 /*
2837                                  * This object is not found, but we
2838                                  * don't have to include it anyway.
2839                                  */
2840                                 continue;
2841                         }
2842                 }
2843
2844                 delta_list[n++] = entry;
2845         }
2846
2847         if (nr_deltas && n > 1) {
2848                 unsigned nr_done = 0;
2849
2850                 if (progress)
2851                         progress_state = start_progress(_("Compressing objects"),
2852                                                         nr_deltas);
2853                 QSORT(delta_list, n, type_size_sort);
2854                 ll_find_deltas(delta_list, n, window+1, depth, &nr_done);
2855                 stop_progress(&progress_state);
2856                 if (nr_done != nr_deltas)
2857                         die(_("inconsistency with delta count"));
2858         }
2859         free(delta_list);
2860 }
2861
2862 static int git_pack_config(const char *k, const char *v, void *cb)
2863 {
2864         if (!strcmp(k, "pack.window")) {
2865                 window = git_config_int(k, v);
2866                 return 0;
2867         }
2868         if (!strcmp(k, "pack.windowmemory")) {
2869                 window_memory_limit = git_config_ulong(k, v);
2870                 return 0;
2871         }
2872         if (!strcmp(k, "pack.depth")) {
2873                 depth = git_config_int(k, v);
2874                 return 0;
2875         }
2876         if (!strcmp(k, "pack.deltacachesize")) {
2877                 max_delta_cache_size = git_config_int(k, v);
2878                 return 0;
2879         }
2880         if (!strcmp(k, "pack.deltacachelimit")) {
2881                 cache_max_small_delta_size = git_config_int(k, v);
2882                 return 0;
2883         }
2884         if (!strcmp(k, "pack.writebitmaphashcache")) {
2885                 if (git_config_bool(k, v))
2886                         write_bitmap_options |= BITMAP_OPT_HASH_CACHE;
2887                 else
2888                         write_bitmap_options &= ~BITMAP_OPT_HASH_CACHE;
2889         }
2890         if (!strcmp(k, "pack.usebitmaps")) {
2891                 use_bitmap_index_default = git_config_bool(k, v);
2892                 return 0;
2893         }
2894         if (!strcmp(k, "pack.allowpackreuse")) {
2895                 allow_pack_reuse = git_config_bool(k, v);
2896                 return 0;
2897         }
2898         if (!strcmp(k, "pack.threads")) {
2899                 delta_search_threads = git_config_int(k, v);
2900                 if (delta_search_threads < 0)
2901                         die(_("invalid number of threads specified (%d)"),
2902                             delta_search_threads);
2903                 if (!HAVE_THREADS && delta_search_threads != 1) {
2904                         warning(_("no threads support, ignoring %s"), k);
2905                         delta_search_threads = 0;
2906                 }
2907                 return 0;
2908         }
2909         if (!strcmp(k, "pack.indexversion")) {
2910                 pack_idx_opts.version = git_config_int(k, v);
2911                 if (pack_idx_opts.version > 2)
2912                         die(_("bad pack.indexversion=%"PRIu32),
2913                             pack_idx_opts.version);
2914                 return 0;
2915         }
2916         if (!strcmp(k, "uploadpack.blobpackfileuri")) {
2917                 struct configured_exclusion *ex = xmalloc(sizeof(*ex));
2918                 const char *oid_end, *pack_end;
2919                 /*
2920                  * Stores the pack hash. This is not a true object ID, but is
2921                  * of the same form.
2922                  */
2923                 struct object_id pack_hash;
2924
2925                 if (parse_oid_hex(v, &ex->e.oid, &oid_end) ||
2926                     *oid_end != ' ' ||
2927                     parse_oid_hex(oid_end + 1, &pack_hash, &pack_end) ||
2928                     *pack_end != ' ')
2929                         die(_("value of uploadpack.blobpackfileuri must be "
2930                               "of the form '<object-hash> <pack-hash> <uri>' (got '%s')"), v);
2931                 if (oidmap_get(&configured_exclusions, &ex->e.oid))
2932                         die(_("object already configured in another "
2933                               "uploadpack.blobpackfileuri (got '%s')"), v);
2934                 ex->pack_hash_hex = xcalloc(1, pack_end - oid_end);
2935                 memcpy(ex->pack_hash_hex, oid_end + 1, pack_end - oid_end - 1);
2936                 ex->uri = xstrdup(pack_end + 1);
2937                 oidmap_put(&configured_exclusions, ex);
2938         }
2939         return git_default_config(k, v, cb);
2940 }
2941
2942 static void read_object_list_from_stdin(void)
2943 {
2944         char line[GIT_MAX_HEXSZ + 1 + PATH_MAX + 2];
2945         struct object_id oid;
2946         const char *p;
2947
2948         for (;;) {
2949                 if (!fgets(line, sizeof(line), stdin)) {
2950                         if (feof(stdin))
2951                                 break;
2952                         if (!ferror(stdin))
2953                                 die("BUG: fgets returned NULL, not EOF, not error!");
2954                         if (errno != EINTR)
2955                                 die_errno("fgets");
2956                         clearerr(stdin);
2957                         continue;
2958                 }
2959                 if (line[0] == '-') {
2960                         if (get_oid_hex(line+1, &oid))
2961                                 die(_("expected edge object ID, got garbage:\n %s"),
2962                                     line);
2963                         add_preferred_base(&oid);
2964                         continue;
2965                 }
2966                 if (parse_oid_hex(line, &oid, &p))
2967                         die(_("expected object ID, got garbage:\n %s"), line);
2968
2969                 add_preferred_base_object(p + 1);
2970                 add_object_entry(&oid, OBJ_NONE, p + 1, 0);
2971         }
2972 }
2973
2974 /* Remember to update object flag allocation in object.h */
2975 #define OBJECT_ADDED (1u<<20)
2976
2977 static void show_commit(struct commit *commit, void *data)
2978 {
2979         add_object_entry(&commit->object.oid, OBJ_COMMIT, NULL, 0);
2980         commit->object.flags |= OBJECT_ADDED;
2981
2982         if (write_bitmap_index)
2983                 index_commit_for_bitmap(commit);
2984
2985         if (use_delta_islands)
2986                 propagate_island_marks(commit);
2987 }
2988
2989 static void show_object(struct object *obj, const char *name, void *data)
2990 {
2991         add_preferred_base_object(name);
2992         add_object_entry(&obj->oid, obj->type, name, 0);
2993         obj->flags |= OBJECT_ADDED;
2994
2995         if (use_delta_islands) {
2996                 const char *p;
2997                 unsigned depth;
2998                 struct object_entry *ent;
2999
3000                 /* the empty string is a root tree, which is depth 0 */
3001                 depth = *name ? 1 : 0;
3002                 for (p = strchr(name, '/'); p; p = strchr(p + 1, '/'))
3003                         depth++;
3004
3005                 ent = packlist_find(&to_pack, &obj->oid);
3006                 if (ent && depth > oe_tree_depth(&to_pack, ent))
3007                         oe_set_tree_depth(&to_pack, ent, depth);
3008         }
3009 }
3010
3011 static void show_object__ma_allow_any(struct object *obj, const char *name, void *data)
3012 {
3013         assert(arg_missing_action == MA_ALLOW_ANY);
3014
3015         /*
3016          * Quietly ignore ALL missing objects.  This avoids problems with
3017          * staging them now and getting an odd error later.
3018          */
3019         if (!has_object_file(&obj->oid))
3020                 return;
3021
3022         show_object(obj, name, data);
3023 }
3024
3025 static void show_object__ma_allow_promisor(struct object *obj, const char *name, void *data)
3026 {
3027         assert(arg_missing_action == MA_ALLOW_PROMISOR);
3028
3029         /*
3030          * Quietly ignore EXPECTED missing objects.  This avoids problems with
3031          * staging them now and getting an odd error later.
3032          */
3033         if (!has_object_file(&obj->oid) && is_promisor_object(&obj->oid))
3034                 return;
3035
3036         show_object(obj, name, data);
3037 }
3038
3039 static int option_parse_missing_action(const struct option *opt,
3040                                        const char *arg, int unset)
3041 {
3042         assert(arg);
3043         assert(!unset);
3044
3045         if (!strcmp(arg, "error")) {
3046                 arg_missing_action = MA_ERROR;
3047                 fn_show_object = show_object;
3048                 return 0;
3049         }
3050
3051         if (!strcmp(arg, "allow-any")) {
3052                 arg_missing_action = MA_ALLOW_ANY;
3053                 fetch_if_missing = 0;
3054                 fn_show_object = show_object__ma_allow_any;
3055                 return 0;
3056         }
3057
3058         if (!strcmp(arg, "allow-promisor")) {
3059                 arg_missing_action = MA_ALLOW_PROMISOR;
3060                 fetch_if_missing = 0;
3061                 fn_show_object = show_object__ma_allow_promisor;
3062                 return 0;
3063         }
3064
3065         die(_("invalid value for --missing"));
3066         return 0;
3067 }
3068
3069 static void show_edge(struct commit *commit)
3070 {
3071         add_preferred_base(&commit->object.oid);
3072 }
3073
3074 struct in_pack_object {
3075         off_t offset;
3076         struct object *object;
3077 };
3078
3079 struct in_pack {
3080         unsigned int alloc;
3081         unsigned int nr;
3082         struct in_pack_object *array;
3083 };
3084
3085 static void mark_in_pack_object(struct object *object, struct packed_git *p, struct in_pack *in_pack)
3086 {
3087         in_pack->array[in_pack->nr].offset = find_pack_entry_one(object->oid.hash, p);
3088         in_pack->array[in_pack->nr].object = object;
3089         in_pack->nr++;
3090 }
3091
3092 /*
3093  * Compare the objects in the offset order, in order to emulate the
3094  * "git rev-list --objects" output that produced the pack originally.
3095  */
3096 static int ofscmp(const void *a_, const void *b_)
3097 {
3098         struct in_pack_object *a = (struct in_pack_object *)a_;
3099         struct in_pack_object *b = (struct in_pack_object *)b_;
3100
3101         if (a->offset < b->offset)
3102                 return -1;
3103         else if (a->offset > b->offset)
3104                 return 1;
3105         else
3106                 return oidcmp(&a->object->oid, &b->object->oid);
3107 }
3108
3109 static void add_objects_in_unpacked_packs(void)
3110 {
3111         struct packed_git *p;
3112         struct in_pack in_pack;
3113         uint32_t i;
3114
3115         memset(&in_pack, 0, sizeof(in_pack));
3116
3117         for (p = get_all_packs(the_repository); p; p = p->next) {
3118                 struct object_id oid;
3119                 struct object *o;
3120
3121                 if (!p->pack_local || p->pack_keep || p->pack_keep_in_core)
3122                         continue;
3123                 if (open_pack_index(p))
3124                         die(_("cannot open pack index"));
3125
3126                 ALLOC_GROW(in_pack.array,
3127                            in_pack.nr + p->num_objects,
3128                            in_pack.alloc);
3129
3130                 for (i = 0; i < p->num_objects; i++) {
3131                         nth_packed_object_id(&oid, p, i);
3132                         o = lookup_unknown_object(&oid);
3133                         if (!(o->flags & OBJECT_ADDED))
3134                                 mark_in_pack_object(o, p, &in_pack);
3135                         o->flags |= OBJECT_ADDED;
3136                 }
3137         }
3138
3139         if (in_pack.nr) {
3140                 QSORT(in_pack.array, in_pack.nr, ofscmp);
3141                 for (i = 0; i < in_pack.nr; i++) {
3142                         struct object *o = in_pack.array[i].object;
3143                         add_object_entry(&o->oid, o->type, "", 0);
3144                 }
3145         }
3146         free(in_pack.array);
3147 }
3148
3149 static int add_loose_object(const struct object_id *oid, const char *path,
3150                             void *data)
3151 {
3152         enum object_type type = oid_object_info(the_repository, oid, NULL);
3153
3154         if (type < 0) {
3155                 warning(_("loose object at %s could not be examined"), path);
3156                 return 0;
3157         }
3158
3159         add_object_entry(oid, type, "", 0);
3160         return 0;
3161 }
3162
3163 /*
3164  * We actually don't even have to worry about reachability here.
3165  * add_object_entry will weed out duplicates, so we just add every
3166  * loose object we find.
3167  */
3168 static void add_unreachable_loose_objects(void)
3169 {
3170         for_each_loose_file_in_objdir(get_object_directory(),
3171                                       add_loose_object,
3172                                       NULL, NULL, NULL);
3173 }
3174
3175 static int has_sha1_pack_kept_or_nonlocal(const struct object_id *oid)
3176 {
3177         static struct packed_git *last_found = (void *)1;
3178         struct packed_git *p;
3179
3180         p = (last_found != (void *)1) ? last_found :
3181                                         get_all_packs(the_repository);
3182
3183         while (p) {
3184                 if ((!p->pack_local || p->pack_keep ||
3185                                 p->pack_keep_in_core) &&
3186                         find_pack_entry_one(oid->hash, p)) {
3187                         last_found = p;
3188                         return 1;
3189                 }
3190                 if (p == last_found)
3191                         p = get_all_packs(the_repository);
3192                 else
3193                         p = p->next;
3194                 if (p == last_found)
3195                         p = p->next;
3196         }
3197         return 0;
3198 }
3199
3200 /*
3201  * Store a list of sha1s that are should not be discarded
3202  * because they are either written too recently, or are
3203  * reachable from another object that was.
3204  *
3205  * This is filled by get_object_list.
3206  */
3207 static struct oid_array recent_objects;
3208
3209 static int loosened_object_can_be_discarded(const struct object_id *oid,
3210                                             timestamp_t mtime)
3211 {
3212         if (!unpack_unreachable_expiration)
3213                 return 0;
3214         if (mtime > unpack_unreachable_expiration)
3215                 return 0;
3216         if (oid_array_lookup(&recent_objects, oid) >= 0)
3217                 return 0;
3218         return 1;
3219 }
3220
3221 static void loosen_unused_packed_objects(void)
3222 {
3223         struct packed_git *p;
3224         uint32_t i;
3225         struct object_id oid;
3226
3227         for (p = get_all_packs(the_repository); p; p = p->next) {
3228                 if (!p->pack_local || p->pack_keep || p->pack_keep_in_core)
3229                         continue;
3230
3231                 if (open_pack_index(p))
3232                         die(_("cannot open pack index"));
3233
3234                 for (i = 0; i < p->num_objects; i++) {
3235                         nth_packed_object_id(&oid, p, i);
3236                         if (!packlist_find(&to_pack, &oid) &&
3237                             !has_sha1_pack_kept_or_nonlocal(&oid) &&
3238                             !loosened_object_can_be_discarded(&oid, p->mtime))
3239                                 if (force_object_loose(&oid, p->mtime))
3240                                         die(_("unable to force loose object"));
3241                 }
3242         }
3243 }
3244
3245 /*
3246  * This tracks any options which pack-reuse code expects to be on, or which a
3247  * reader of the pack might not understand, and which would therefore prevent
3248  * blind reuse of what we have on disk.
3249  */
3250 static int pack_options_allow_reuse(void)
3251 {
3252         return allow_pack_reuse &&
3253                pack_to_stdout &&
3254                !ignore_packed_keep_on_disk &&
3255                !ignore_packed_keep_in_core &&
3256                (!local || !have_non_local_packs) &&
3257                !incremental;
3258 }
3259
3260 static int get_object_list_from_bitmap(struct rev_info *revs)
3261 {
3262         if (!(bitmap_git = prepare_bitmap_walk(revs, &filter_options)))
3263                 return -1;
3264
3265         if (pack_options_allow_reuse() &&
3266             !reuse_partial_packfile_from_bitmap(
3267                         bitmap_git,
3268                         &reuse_packfile,
3269                         &reuse_packfile_objects,
3270                         &reuse_packfile_bitmap)) {
3271                 assert(reuse_packfile_objects);
3272                 nr_result += reuse_packfile_objects;
3273                 display_progress(progress_state, nr_result);
3274         }
3275
3276         traverse_bitmap_commit_list(bitmap_git, revs,
3277                                     &add_object_entry_from_bitmap);
3278         return 0;
3279 }
3280
3281 static void record_recent_object(struct object *obj,
3282                                  const char *name,
3283                                  void *data)
3284 {
3285         oid_array_append(&recent_objects, &obj->oid);
3286 }
3287
3288 static void record_recent_commit(struct commit *commit, void *data)
3289 {
3290         oid_array_append(&recent_objects, &commit->object.oid);
3291 }
3292
3293 static void get_object_list(int ac, const char **av)
3294 {
3295         struct rev_info revs;
3296         struct setup_revision_opt s_r_opt = {
3297                 .allow_exclude_promisor_objects = 1,
3298         };
3299         char line[1000];
3300         int flags = 0;
3301         int save_warning;
3302
3303         repo_init_revisions(the_repository, &revs, NULL);
3304         save_commit_buffer = 0;
3305         setup_revisions(ac, av, &revs, &s_r_opt);
3306
3307         /* make sure shallows are read */
3308         is_repository_shallow(the_repository);
3309
3310         save_warning = warn_on_object_refname_ambiguity;
3311         warn_on_object_refname_ambiguity = 0;
3312
3313         while (fgets(line, sizeof(line), stdin) != NULL) {
3314                 int len = strlen(line);
3315                 if (len && line[len - 1] == '\n')
3316                         line[--len] = 0;
3317                 if (!len)
3318                         break;
3319                 if (*line == '-') {
3320                         if (!strcmp(line, "--not")) {
3321                                 flags ^= UNINTERESTING;
3322                                 write_bitmap_index = 0;
3323                                 continue;
3324                         }
3325                         if (starts_with(line, "--shallow ")) {
3326                                 struct object_id oid;
3327                                 if (get_oid_hex(line + 10, &oid))
3328                                         die("not an SHA-1 '%s'", line + 10);
3329                                 register_shallow(the_repository, &oid);
3330                                 use_bitmap_index = 0;
3331                                 continue;
3332                         }
3333                         die(_("not a rev '%s'"), line);
3334                 }
3335                 if (handle_revision_arg(line, &revs, flags, REVARG_CANNOT_BE_FILENAME))
3336                         die(_("bad revision '%s'"), line);
3337         }
3338
3339         warn_on_object_refname_ambiguity = save_warning;
3340
3341         if (use_bitmap_index && !get_object_list_from_bitmap(&revs))
3342                 return;
3343
3344         if (use_delta_islands)
3345                 load_delta_islands(the_repository, progress);
3346
3347         if (prepare_revision_walk(&revs))
3348                 die(_("revision walk setup failed"));
3349         mark_edges_uninteresting(&revs, show_edge, sparse);
3350
3351         if (!fn_show_object)
3352                 fn_show_object = show_object;
3353         traverse_commit_list_filtered(&filter_options, &revs,
3354                                       show_commit, fn_show_object, NULL,
3355                                       NULL);
3356
3357         if (unpack_unreachable_expiration) {
3358                 revs.ignore_missing_links = 1;
3359                 if (add_unseen_recent_objects_to_traversal(&revs,
3360                                 unpack_unreachable_expiration))
3361                         die(_("unable to add recent objects"));
3362                 if (prepare_revision_walk(&revs))
3363                         die(_("revision walk setup failed"));
3364                 traverse_commit_list(&revs, record_recent_commit,
3365                                      record_recent_object, NULL);
3366         }
3367
3368         if (keep_unreachable)
3369                 add_objects_in_unpacked_packs();
3370         if (pack_loose_unreachable)
3371                 add_unreachable_loose_objects();
3372         if (unpack_unreachable)
3373                 loosen_unused_packed_objects();
3374
3375         oid_array_clear(&recent_objects);
3376 }
3377
3378 static void add_extra_kept_packs(const struct string_list *names)
3379 {
3380         struct packed_git *p;
3381
3382         if (!names->nr)
3383                 return;
3384
3385         for (p = get_all_packs(the_repository); p; p = p->next) {
3386                 const char *name = basename(p->pack_name);
3387                 int i;
3388
3389                 if (!p->pack_local)
3390                         continue;
3391
3392                 for (i = 0; i < names->nr; i++)
3393                         if (!fspathcmp(name, names->items[i].string))
3394                                 break;
3395
3396                 if (i < names->nr) {
3397                         p->pack_keep_in_core = 1;
3398                         ignore_packed_keep_in_core = 1;
3399                         continue;
3400                 }
3401         }
3402 }
3403
3404 static int option_parse_index_version(const struct option *opt,
3405                                       const char *arg, int unset)
3406 {
3407         char *c;
3408         const char *val = arg;
3409
3410         BUG_ON_OPT_NEG(unset);
3411
3412         pack_idx_opts.version = strtoul(val, &c, 10);
3413         if (pack_idx_opts.version > 2)
3414                 die(_("unsupported index version %s"), val);
3415         if (*c == ',' && c[1])
3416                 pack_idx_opts.off32_limit = strtoul(c+1, &c, 0);
3417         if (*c || pack_idx_opts.off32_limit & 0x80000000)
3418                 die(_("bad index version '%s'"), val);
3419         return 0;
3420 }
3421
3422 static int option_parse_unpack_unreachable(const struct option *opt,
3423                                            const char *arg, int unset)
3424 {
3425         if (unset) {
3426                 unpack_unreachable = 0;
3427                 unpack_unreachable_expiration = 0;
3428         }
3429         else {
3430                 unpack_unreachable = 1;
3431                 if (arg)
3432                         unpack_unreachable_expiration = approxidate(arg);
3433         }
3434         return 0;
3435 }
3436
3437 int cmd_pack_objects(int argc, const char **argv, const char *prefix)
3438 {
3439         int use_internal_rev_list = 0;
3440         int shallow = 0;
3441         int all_progress_implied = 0;
3442         struct argv_array rp = ARGV_ARRAY_INIT;
3443         int rev_list_unpacked = 0, rev_list_all = 0, rev_list_reflog = 0;
3444         int rev_list_index = 0;
3445         struct string_list keep_pack_list = STRING_LIST_INIT_NODUP;
3446         struct option pack_objects_options[] = {
3447                 OPT_SET_INT('q', "quiet", &progress,
3448                             N_("do not show progress meter"), 0),
3449                 OPT_SET_INT(0, "progress", &progress,
3450                             N_("show progress meter"), 1),
3451                 OPT_SET_INT(0, "all-progress", &progress,
3452                             N_("show progress meter during object writing phase"), 2),
3453                 OPT_BOOL(0, "all-progress-implied",
3454                          &all_progress_implied,
3455                          N_("similar to --all-progress when progress meter is shown")),
3456                 OPT_CALLBACK_F(0, "index-version", NULL, N_("<version>[,<offset>]"),
3457                   N_("write the pack index file in the specified idx format version"),
3458                   PARSE_OPT_NONEG, option_parse_index_version),
3459                 OPT_MAGNITUDE(0, "max-pack-size", &pack_size_limit,
3460                               N_("maximum size of each output pack file")),
3461                 OPT_BOOL(0, "local", &local,
3462                          N_("ignore borrowed objects from alternate object store")),
3463                 OPT_BOOL(0, "incremental", &incremental,
3464                          N_("ignore packed objects")),
3465                 OPT_INTEGER(0, "window", &window,
3466                             N_("limit pack window by objects")),
3467                 OPT_MAGNITUDE(0, "window-memory", &window_memory_limit,
3468                               N_("limit pack window by memory in addition to object limit")),
3469                 OPT_INTEGER(0, "depth", &depth,
3470                             N_("maximum length of delta chain allowed in the resulting pack")),
3471                 OPT_BOOL(0, "reuse-delta", &reuse_delta,
3472                          N_("reuse existing deltas")),
3473                 OPT_BOOL(0, "reuse-object", &reuse_object,
3474                          N_("reuse existing objects")),
3475                 OPT_BOOL(0, "delta-base-offset", &allow_ofs_delta,
3476                          N_("use OFS_DELTA objects")),
3477                 OPT_INTEGER(0, "threads", &delta_search_threads,
3478                             N_("use threads when searching for best delta matches")),
3479                 OPT_BOOL(0, "non-empty", &non_empty,
3480                          N_("do not create an empty pack output")),
3481                 OPT_BOOL(0, "revs", &use_internal_rev_list,
3482                          N_("read revision arguments from standard input")),
3483                 OPT_SET_INT_F(0, "unpacked", &rev_list_unpacked,
3484                               N_("limit the objects to those that are not yet packed"),
3485                               1, PARSE_OPT_NONEG),
3486                 OPT_SET_INT_F(0, "all", &rev_list_all,
3487                               N_("include objects reachable from any reference"),
3488                               1, PARSE_OPT_NONEG),
3489                 OPT_SET_INT_F(0, "reflog", &rev_list_reflog,
3490                               N_("include objects referred by reflog entries"),
3491                               1, PARSE_OPT_NONEG),
3492                 OPT_SET_INT_F(0, "indexed-objects", &rev_list_index,
3493                               N_("include objects referred to by the index"),
3494                               1, PARSE_OPT_NONEG),
3495                 OPT_BOOL(0, "stdout", &pack_to_stdout,
3496                          N_("output pack to stdout")),
3497                 OPT_BOOL(0, "include-tag", &include_tag,
3498                          N_("include tag objects that refer to objects to be packed")),
3499                 OPT_BOOL(0, "keep-unreachable", &keep_unreachable,
3500                          N_("keep unreachable objects")),
3501                 OPT_BOOL(0, "pack-loose-unreachable", &pack_loose_unreachable,
3502                          N_("pack loose unreachable objects")),
3503                 OPT_CALLBACK_F(0, "unpack-unreachable", NULL, N_("time"),
3504                   N_("unpack unreachable objects newer than <time>"),
3505                   PARSE_OPT_OPTARG, option_parse_unpack_unreachable),
3506                 OPT_BOOL(0, "sparse", &sparse,
3507                          N_("use the sparse reachability algorithm")),
3508                 OPT_BOOL(0, "thin", &thin,
3509                          N_("create thin packs")),
3510                 OPT_BOOL(0, "shallow", &shallow,
3511                          N_("create packs suitable for shallow fetches")),
3512                 OPT_BOOL(0, "honor-pack-keep", &ignore_packed_keep_on_disk,
3513                          N_("ignore packs that have companion .keep file")),
3514                 OPT_STRING_LIST(0, "keep-pack", &keep_pack_list, N_("name"),
3515                                 N_("ignore this pack")),
3516                 OPT_INTEGER(0, "compression", &pack_compression_level,
3517                             N_("pack compression level")),
3518                 OPT_SET_INT(0, "keep-true-parents", &grafts_replace_parents,
3519                             N_("do not hide commits by grafts"), 0),
3520                 OPT_BOOL(0, "use-bitmap-index", &use_bitmap_index,
3521                          N_("use a bitmap index if available to speed up counting objects")),
3522                 OPT_SET_INT(0, "write-bitmap-index", &write_bitmap_index,
3523                             N_("write a bitmap index together with the pack index"),
3524                             WRITE_BITMAP_TRUE),
3525                 OPT_SET_INT_F(0, "write-bitmap-index-quiet",
3526                               &write_bitmap_index,
3527                               N_("write a bitmap index if possible"),
3528                               WRITE_BITMAP_QUIET, PARSE_OPT_HIDDEN),
3529                 OPT_PARSE_LIST_OBJECTS_FILTER(&filter_options),
3530                 OPT_CALLBACK_F(0, "missing", NULL, N_("action"),
3531                   N_("handling for missing objects"), PARSE_OPT_NONEG,
3532                   option_parse_missing_action),
3533                 OPT_BOOL(0, "exclude-promisor-objects", &exclude_promisor_objects,
3534                          N_("do not pack objects in promisor packfiles")),
3535                 OPT_BOOL(0, "delta-islands", &use_delta_islands,
3536                          N_("respect islands during delta compression")),
3537                 OPT_STRING_LIST(0, "uri-protocol", &uri_protocols,
3538                                 N_("protocol"),
3539                                 N_("exclude any configured uploadpack.blobpackfileuri with this protocol")),
3540                 OPT_END(),
3541         };
3542
3543         if (DFS_NUM_STATES > (1 << OE_DFS_STATE_BITS))
3544                 BUG("too many dfs states, increase OE_DFS_STATE_BITS");
3545
3546         read_replace_refs = 0;
3547
3548         sparse = git_env_bool("GIT_TEST_PACK_SPARSE", -1);
3549         prepare_repo_settings(the_repository);
3550         if (sparse < 0)
3551                 sparse = the_repository->settings.pack_use_sparse;
3552
3553         reset_pack_idx_option(&pack_idx_opts);
3554         git_config(git_pack_config, NULL);
3555
3556         progress = isatty(2);
3557         argc = parse_options(argc, argv, prefix, pack_objects_options,
3558                              pack_usage, 0);
3559
3560         if (argc) {
3561                 base_name = argv[0];
3562                 argc--;
3563         }
3564         if (pack_to_stdout != !base_name || argc)
3565                 usage_with_options(pack_usage, pack_objects_options);
3566
3567         if (depth >= (1 << OE_DEPTH_BITS)) {
3568                 warning(_("delta chain depth %d is too deep, forcing %d"),
3569                         depth, (1 << OE_DEPTH_BITS) - 1);
3570                 depth = (1 << OE_DEPTH_BITS) - 1;
3571         }
3572         if (cache_max_small_delta_size >= (1U << OE_Z_DELTA_BITS)) {
3573                 warning(_("pack.deltaCacheLimit is too high, forcing %d"),
3574                         (1U << OE_Z_DELTA_BITS) - 1);
3575                 cache_max_small_delta_size = (1U << OE_Z_DELTA_BITS) - 1;
3576         }
3577
3578         argv_array_push(&rp, "pack-objects");
3579         if (thin) {
3580                 use_internal_rev_list = 1;
3581                 argv_array_push(&rp, shallow
3582                                 ? "--objects-edge-aggressive"
3583                                 : "--objects-edge");
3584         } else
3585                 argv_array_push(&rp, "--objects");
3586
3587         if (rev_list_all) {
3588                 use_internal_rev_list = 1;
3589                 argv_array_push(&rp, "--all");
3590         }
3591         if (rev_list_reflog) {
3592                 use_internal_rev_list = 1;
3593                 argv_array_push(&rp, "--reflog");
3594         }
3595         if (rev_list_index) {
3596                 use_internal_rev_list = 1;
3597                 argv_array_push(&rp, "--indexed-objects");
3598         }
3599         if (rev_list_unpacked) {
3600                 use_internal_rev_list = 1;
3601                 argv_array_push(&rp, "--unpacked");
3602         }
3603
3604         if (exclude_promisor_objects) {
3605                 use_internal_rev_list = 1;
3606                 fetch_if_missing = 0;
3607                 argv_array_push(&rp, "--exclude-promisor-objects");
3608         }
3609         if (unpack_unreachable || keep_unreachable || pack_loose_unreachable)
3610                 use_internal_rev_list = 1;
3611
3612         if (!reuse_object)
3613                 reuse_delta = 0;
3614         if (pack_compression_level == -1)
3615                 pack_compression_level = Z_DEFAULT_COMPRESSION;
3616         else if (pack_compression_level < 0 || pack_compression_level > Z_BEST_COMPRESSION)
3617                 die(_("bad pack compression level %d"), pack_compression_level);
3618
3619         if (!delta_search_threads)      /* --threads=0 means autodetect */
3620                 delta_search_threads = online_cpus();
3621
3622         if (!HAVE_THREADS && delta_search_threads != 1)
3623                 warning(_("no threads support, ignoring --threads"));
3624         if (!pack_to_stdout && !pack_size_limit)
3625                 pack_size_limit = pack_size_limit_cfg;
3626         if (pack_to_stdout && pack_size_limit)
3627                 die(_("--max-pack-size cannot be used to build a pack for transfer"));
3628         if (pack_size_limit && pack_size_limit < 1024*1024) {
3629                 warning(_("minimum pack size limit is 1 MiB"));
3630                 pack_size_limit = 1024*1024;
3631         }
3632
3633         if (!pack_to_stdout && thin)
3634                 die(_("--thin cannot be used to build an indexable pack"));
3635
3636         if (keep_unreachable && unpack_unreachable)
3637                 die(_("--keep-unreachable and --unpack-unreachable are incompatible"));
3638         if (!rev_list_all || !rev_list_reflog || !rev_list_index)
3639                 unpack_unreachable_expiration = 0;
3640
3641         if (filter_options.choice) {
3642                 if (!pack_to_stdout)
3643                         die(_("cannot use --filter without --stdout"));
3644         }
3645
3646         /*
3647          * "soft" reasons not to use bitmaps - for on-disk repack by default we want
3648          *
3649          * - to produce good pack (with bitmap index not-yet-packed objects are
3650          *   packed in suboptimal order).
3651          *
3652          * - to use more robust pack-generation codepath (avoiding possible
3653          *   bugs in bitmap code and possible bitmap index corruption).
3654          */
3655         if (!pack_to_stdout)
3656                 use_bitmap_index_default = 0;
3657
3658         if (use_bitmap_index < 0)
3659                 use_bitmap_index = use_bitmap_index_default;
3660
3661         /* "hard" reasons not to use bitmaps; these just won't work at all */
3662         if (!use_internal_rev_list || (!pack_to_stdout && write_bitmap_index) || is_repository_shallow(the_repository))
3663                 use_bitmap_index = 0;
3664
3665         if (pack_to_stdout || !rev_list_all)
3666                 write_bitmap_index = 0;
3667
3668         if (use_delta_islands)
3669                 argv_array_push(&rp, "--topo-order");
3670
3671         if (progress && all_progress_implied)
3672                 progress = 2;
3673
3674         add_extra_kept_packs(&keep_pack_list);
3675         if (ignore_packed_keep_on_disk) {
3676                 struct packed_git *p;
3677                 for (p = get_all_packs(the_repository); p; p = p->next)
3678                         if (p->pack_local && p->pack_keep)
3679                                 break;
3680                 if (!p) /* no keep-able packs found */
3681                         ignore_packed_keep_on_disk = 0;
3682         }
3683         if (local) {
3684                 /*
3685                  * unlike ignore_packed_keep_on_disk above, we do not
3686                  * want to unset "local" based on looking at packs, as
3687                  * it also covers non-local objects
3688                  */
3689                 struct packed_git *p;
3690                 for (p = get_all_packs(the_repository); p; p = p->next) {
3691                         if (!p->pack_local) {
3692                                 have_non_local_packs = 1;
3693                                 break;
3694                         }
3695                 }
3696         }
3697
3698         trace2_region_enter("pack-objects", "enumerate-objects",
3699                             the_repository);
3700         prepare_packing_data(the_repository, &to_pack);
3701
3702         if (progress)
3703                 progress_state = start_progress(_("Enumerating objects"), 0);
3704         if (!use_internal_rev_list)
3705                 read_object_list_from_stdin();
3706         else {
3707                 get_object_list(rp.argc, rp.argv);
3708                 argv_array_clear(&rp);
3709         }
3710         cleanup_preferred_base();
3711         if (include_tag && nr_result)
3712                 for_each_ref(add_ref_tag, NULL);
3713         stop_progress(&progress_state);
3714         trace2_region_leave("pack-objects", "enumerate-objects",
3715                             the_repository);
3716
3717         if (non_empty && !nr_result)
3718                 return 0;
3719         if (nr_result) {
3720                 trace2_region_enter("pack-objects", "prepare-pack",
3721                                     the_repository);
3722                 prepare_pack(window, depth);
3723                 trace2_region_leave("pack-objects", "prepare-pack",
3724                                     the_repository);
3725         }
3726
3727         trace2_region_enter("pack-objects", "write-pack-file", the_repository);
3728         write_excluded_by_configs();
3729         write_pack_file();
3730         trace2_region_leave("pack-objects", "write-pack-file", the_repository);
3731
3732         if (progress)
3733                 fprintf_ln(stderr,
3734                            _("Total %"PRIu32" (delta %"PRIu32"),"
3735                              " reused %"PRIu32" (delta %"PRIu32"),"
3736                              " pack-reused %"PRIu32),
3737                            written, written_delta, reused, reused_delta,
3738                            reuse_packfile_objects);
3739         return 0;
3740 }