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