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