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