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