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