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