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