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