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