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