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