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