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