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