Code

638d43da0e61c67a374ee124faf9391180171b21
[git.git] / builtin / pack-objects.c
1 #include "builtin.h"
2 #include "cache.h"
3 #include "attr.h"
4 #include "object.h"
5 #include "blob.h"
6 #include "commit.h"
7 #include "tag.h"
8 #include "tree.h"
9 #include "delta.h"
10 #include "pack.h"
11 #include "pack-revindex.h"
12 #include "csum-file.h"
13 #include "tree-walk.h"
14 #include "diff.h"
15 #include "revision.h"
16 #include "list-objects.h"
17 #include "progress.h"
18 #include "refs.h"
19 #include "thread-utils.h"
21 static const char pack_usage[] =
22   "git pack-objects [ -q | --progress | --all-progress ]\n"
23   "        [--all-progress-implied]\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]]\n"
28   "        [--reflog] [--stdout | base-name] [--include-tag]\n"
29   "        [--keep-unreachable | --unpack-unreachable]\n"
30   "        [< ref-list | < object-list]";
32 struct object_entry {
33         struct pack_idx_entry idx;
34         unsigned long size;     /* uncompressed size */
35         struct packed_git *in_pack;     /* already in pack */
36         off_t in_pack_offset;
37         struct object_entry *delta;     /* delta base object */
38         struct object_entry *delta_child; /* deltified objects who bases me */
39         struct object_entry *delta_sibling; /* other deltified objects who
40                                              * uses the same base as me
41                                              */
42         void *delta_data;       /* cached delta (uncompressed) */
43         unsigned long delta_size;       /* delta data size (uncompressed) */
44         unsigned long z_delta_size;     /* delta data size (compressed) */
45         unsigned int hash;      /* name hint hash */
46         enum object_type type;
47         enum object_type in_pack_type;  /* could be delta */
48         unsigned char in_pack_header_size;
49         unsigned char preferred_base; /* we do not pack this, but is available
50                                        * to be used as the base object to delta
51                                        * objects against.
52                                        */
53         unsigned char no_try_delta;
54         unsigned char tagged; /* near the very tip of refs */
55         unsigned char filled; /* assigned write-order */
56 };
58 /*
59  * Objects we are going to pack are collected in objects array (dynamically
60  * expanded).  nr_objects & nr_alloc controls this array.  They are stored
61  * in the order we see -- typically rev-list --objects order that gives us
62  * nice "minimum seek" order.
63  */
64 static struct object_entry *objects;
65 static struct pack_idx_entry **written_list;
66 static uint32_t nr_objects, nr_alloc, nr_result, nr_written;
68 static int non_empty;
69 static int reuse_delta = 1, reuse_object = 1;
70 static int keep_unreachable, unpack_unreachable, include_tag;
71 static int local;
72 static int incremental;
73 static int ignore_packed_keep;
74 static int allow_ofs_delta;
75 static struct pack_idx_option pack_idx_opts;
76 static const char *base_name;
77 static int progress = 1;
78 static int window = 10;
79 static unsigned long pack_size_limit, pack_size_limit_cfg;
80 static int depth = 50;
81 static int delta_search_threads;
82 static int pack_to_stdout;
83 static int num_preferred_base;
84 static struct progress *progress_state;
85 static int pack_compression_level = Z_DEFAULT_COMPRESSION;
86 static int pack_compression_seen;
88 static unsigned long delta_cache_size = 0;
89 static unsigned long max_delta_cache_size = 256 * 1024 * 1024;
90 static unsigned long cache_max_small_delta_size = 1000;
92 static unsigned long window_memory_limit = 0;
94 /*
95  * The object names in objects array are hashed with this hashtable,
96  * to help looking up the entry by object name.
97  * This hashtable is built after all the objects are seen.
98  */
99 static int *object_ix;
100 static int object_ix_hashsz;
101 static struct object_entry *locate_object_entry(const unsigned char *sha1);
103 /*
104  * stats
105  */
106 static uint32_t written, written_delta;
107 static uint32_t reused, reused_delta;
110 static void *get_delta(struct object_entry *entry)
112         unsigned long size, base_size, delta_size;
113         void *buf, *base_buf, *delta_buf;
114         enum object_type type;
116         buf = read_sha1_file(entry->idx.sha1, &type, &size);
117         if (!buf)
118                 die("unable to read %s", sha1_to_hex(entry->idx.sha1));
119         base_buf = read_sha1_file(entry->delta->idx.sha1, &type, &base_size);
120         if (!base_buf)
121                 die("unable to read %s", sha1_to_hex(entry->delta->idx.sha1));
122         delta_buf = diff_delta(base_buf, base_size,
123                                buf, size, &delta_size, 0);
124         if (!delta_buf || delta_size != entry->delta_size)
125                 die("delta size changed");
126         free(buf);
127         free(base_buf);
128         return delta_buf;
131 static unsigned long do_compress(void **pptr, unsigned long size)
133         git_zstream stream;
134         void *in, *out;
135         unsigned long maxsize;
137         memset(&stream, 0, sizeof(stream));
138         git_deflate_init(&stream, pack_compression_level);
139         maxsize = git_deflate_bound(&stream, size);
141         in = *pptr;
142         out = xmalloc(maxsize);
143         *pptr = out;
145         stream.next_in = in;
146         stream.avail_in = size;
147         stream.next_out = out;
148         stream.avail_out = maxsize;
149         while (git_deflate(&stream, Z_FINISH) == Z_OK)
150                 ; /* nothing */
151         git_deflate_end(&stream);
153         free(in);
154         return stream.total_out;
157 /*
158  * we are going to reuse the existing object data as is.  make
159  * sure it is not corrupt.
160  */
161 static int check_pack_inflate(struct packed_git *p,
162                 struct pack_window **w_curs,
163                 off_t offset,
164                 off_t len,
165                 unsigned long expect)
167         git_zstream stream;
168         unsigned char fakebuf[4096], *in;
169         int st;
171         memset(&stream, 0, sizeof(stream));
172         git_inflate_init(&stream);
173         do {
174                 in = use_pack(p, w_curs, offset, &stream.avail_in);
175                 stream.next_in = in;
176                 stream.next_out = fakebuf;
177                 stream.avail_out = sizeof(fakebuf);
178                 st = git_inflate(&stream, Z_FINISH);
179                 offset += stream.next_in - in;
180         } while (st == Z_OK || st == Z_BUF_ERROR);
181         git_inflate_end(&stream);
182         return (st == Z_STREAM_END &&
183                 stream.total_out == expect &&
184                 stream.total_in == len) ? 0 : -1;
187 static void copy_pack_data(struct sha1file *f,
188                 struct packed_git *p,
189                 struct pack_window **w_curs,
190                 off_t offset,
191                 off_t len)
193         unsigned char *in;
194         unsigned long avail;
196         while (len) {
197                 in = use_pack(p, w_curs, offset, &avail);
198                 if (avail > len)
199                         avail = (unsigned long)len;
200                 sha1write(f, in, avail);
201                 offset += avail;
202                 len -= avail;
203         }
206 /* Return 0 if we will bust the pack-size limit */
207 static unsigned long write_object(struct sha1file *f,
208                                   struct object_entry *entry,
209                                   off_t write_offset)
211         unsigned long size, limit, datalen;
212         void *buf;
213         unsigned char header[10], dheader[10];
214         unsigned hdrlen;
215         enum object_type type;
216         int usable_delta, to_reuse;
218         if (!pack_to_stdout)
219                 crc32_begin(f);
221         type = entry->type;
223         /* apply size limit if limited packsize and not first object */
224         if (!pack_size_limit || !nr_written)
225                 limit = 0;
226         else if (pack_size_limit <= write_offset)
227                 /*
228                  * the earlier object did not fit the limit; avoid
229                  * mistaking this with unlimited (i.e. limit = 0).
230                  */
231                 limit = 1;
232         else
233                 limit = pack_size_limit - write_offset;
235         if (!entry->delta)
236                 usable_delta = 0;       /* no delta */
237         else if (!pack_size_limit)
238                usable_delta = 1;        /* unlimited packfile */
239         else if (entry->delta->idx.offset == (off_t)-1)
240                 usable_delta = 0;       /* base was written to another pack */
241         else if (entry->delta->idx.offset)
242                 usable_delta = 1;       /* base already exists in this pack */
243         else
244                 usable_delta = 0;       /* base could end up in another pack */
246         if (!reuse_object)
247                 to_reuse = 0;   /* explicit */
248         else if (!entry->in_pack)
249                 to_reuse = 0;   /* can't reuse what we don't have */
250         else if (type == OBJ_REF_DELTA || type == OBJ_OFS_DELTA)
251                                 /* check_object() decided it for us ... */
252                 to_reuse = usable_delta;
253                                 /* ... but pack split may override that */
254         else if (type != entry->in_pack_type)
255                 to_reuse = 0;   /* pack has delta which is unusable */
256         else if (entry->delta)
257                 to_reuse = 0;   /* we want to pack afresh */
258         else
259                 to_reuse = 1;   /* we have it in-pack undeltified,
260                                  * and we do not need to deltify it.
261                                  */
263         if (!to_reuse) {
264                 no_reuse:
265                 if (!usable_delta) {
266                         buf = read_sha1_file(entry->idx.sha1, &type, &size);
267                         if (!buf)
268                                 die("unable to read %s", sha1_to_hex(entry->idx.sha1));
269                         /*
270                          * make sure no cached delta data remains from a
271                          * previous attempt before a pack split occurred.
272                          */
273                         free(entry->delta_data);
274                         entry->delta_data = NULL;
275                         entry->z_delta_size = 0;
276                 } else if (entry->delta_data) {
277                         size = entry->delta_size;
278                         buf = entry->delta_data;
279                         entry->delta_data = NULL;
280                         type = (allow_ofs_delta && entry->delta->idx.offset) ?
281                                 OBJ_OFS_DELTA : OBJ_REF_DELTA;
282                 } else {
283                         buf = get_delta(entry);
284                         size = entry->delta_size;
285                         type = (allow_ofs_delta && entry->delta->idx.offset) ?
286                                 OBJ_OFS_DELTA : OBJ_REF_DELTA;
287                 }
289                 if (entry->z_delta_size)
290                         datalen = entry->z_delta_size;
291                 else
292                         datalen = do_compress(&buf, size);
294                 /*
295                  * The object header is a byte of 'type' followed by zero or
296                  * more bytes of length.
297                  */
298                 hdrlen = encode_in_pack_object_header(type, size, header);
300                 if (type == OBJ_OFS_DELTA) {
301                         /*
302                          * Deltas with relative base contain an additional
303                          * encoding of the relative offset for the delta
304                          * base from this object's position in the pack.
305                          */
306                         off_t ofs = entry->idx.offset - entry->delta->idx.offset;
307                         unsigned pos = sizeof(dheader) - 1;
308                         dheader[pos] = ofs & 127;
309                         while (ofs >>= 7)
310                                 dheader[--pos] = 128 | (--ofs & 127);
311                         if (limit && hdrlen + sizeof(dheader) - pos + datalen + 20 >= limit) {
312                                 free(buf);
313                                 return 0;
314                         }
315                         sha1write(f, header, hdrlen);
316                         sha1write(f, dheader + pos, sizeof(dheader) - pos);
317                         hdrlen += sizeof(dheader) - pos;
318                 } else if (type == OBJ_REF_DELTA) {
319                         /*
320                          * Deltas with a base reference contain
321                          * an additional 20 bytes for the base sha1.
322                          */
323                         if (limit && hdrlen + 20 + datalen + 20 >= limit) {
324                                 free(buf);
325                                 return 0;
326                         }
327                         sha1write(f, header, hdrlen);
328                         sha1write(f, entry->delta->idx.sha1, 20);
329                         hdrlen += 20;
330                 } else {
331                         if (limit && hdrlen + datalen + 20 >= limit) {
332                                 free(buf);
333                                 return 0;
334                         }
335                         sha1write(f, header, hdrlen);
336                 }
337                 sha1write(f, buf, datalen);
338                 free(buf);
339         }
340         else {
341                 struct packed_git *p = entry->in_pack;
342                 struct pack_window *w_curs = NULL;
343                 struct revindex_entry *revidx;
344                 off_t offset;
346                 if (entry->delta)
347                         type = (allow_ofs_delta && entry->delta->idx.offset) ?
348                                 OBJ_OFS_DELTA : OBJ_REF_DELTA;
349                 hdrlen = encode_in_pack_object_header(type, entry->size, header);
351                 offset = entry->in_pack_offset;
352                 revidx = find_pack_revindex(p, offset);
353                 datalen = revidx[1].offset - offset;
354                 if (!pack_to_stdout && p->index_version > 1 &&
355                     check_pack_crc(p, &w_curs, offset, datalen, revidx->nr)) {
356                         error("bad packed object CRC for %s", sha1_to_hex(entry->idx.sha1));
357                         unuse_pack(&w_curs);
358                         goto no_reuse;
359                 }
361                 offset += entry->in_pack_header_size;
362                 datalen -= entry->in_pack_header_size;
363                 if (!pack_to_stdout && p->index_version == 1 &&
364                     check_pack_inflate(p, &w_curs, offset, datalen, entry->size)) {
365                         error("corrupt packed object for %s", sha1_to_hex(entry->idx.sha1));
366                         unuse_pack(&w_curs);
367                         goto no_reuse;
368                 }
370                 if (type == OBJ_OFS_DELTA) {
371                         off_t ofs = entry->idx.offset - entry->delta->idx.offset;
372                         unsigned pos = sizeof(dheader) - 1;
373                         dheader[pos] = ofs & 127;
374                         while (ofs >>= 7)
375                                 dheader[--pos] = 128 | (--ofs & 127);
376                         if (limit && hdrlen + sizeof(dheader) - pos + datalen + 20 >= limit) {
377                                 unuse_pack(&w_curs);
378                                 return 0;
379                         }
380                         sha1write(f, header, hdrlen);
381                         sha1write(f, dheader + pos, sizeof(dheader) - pos);
382                         hdrlen += sizeof(dheader) - pos;
383                         reused_delta++;
384                 } else if (type == OBJ_REF_DELTA) {
385                         if (limit && hdrlen + 20 + datalen + 20 >= limit) {
386                                 unuse_pack(&w_curs);
387                                 return 0;
388                         }
389                         sha1write(f, header, hdrlen);
390                         sha1write(f, entry->delta->idx.sha1, 20);
391                         hdrlen += 20;
392                         reused_delta++;
393                 } else {
394                         if (limit && hdrlen + datalen + 20 >= limit) {
395                                 unuse_pack(&w_curs);
396                                 return 0;
397                         }
398                         sha1write(f, header, hdrlen);
399                 }
400                 copy_pack_data(f, p, &w_curs, offset, datalen);
401                 unuse_pack(&w_curs);
402                 reused++;
403         }
404         if (usable_delta)
405                 written_delta++;
406         written++;
407         if (!pack_to_stdout)
408                 entry->idx.crc32 = crc32_end(f);
409         return hdrlen + datalen;
412 static int write_one(struct sha1file *f,
413                                struct object_entry *e,
414                                off_t *offset)
416         unsigned long size;
418         /* offset is non zero if object is written already. */
419         if (e->idx.offset || e->preferred_base)
420                 return -1;
422         /* if we are deltified, write out base object first. */
423         if (e->delta && !write_one(f, e->delta, offset))
424                 return 0;
426         e->idx.offset = *offset;
427         size = write_object(f, e, *offset);
428         if (!size) {
429                 e->idx.offset = 0;
430                 return 0;
431         }
432         written_list[nr_written++] = &e->idx;
434         /* make sure off_t is sufficiently large not to wrap */
435         if (signed_add_overflows(*offset, size))
436                 die("pack too large for current definition of off_t");
437         *offset += size;
438         return 1;
441 static int mark_tagged(const char *path, const unsigned char *sha1, int flag,
442                        void *cb_data)
444         unsigned char peeled[20];
445         struct object_entry *entry = locate_object_entry(sha1);
447         if (entry)
448                 entry->tagged = 1;
449         if (!peel_ref(path, peeled)) {
450                 entry = locate_object_entry(peeled);
451                 if (entry)
452                         entry->tagged = 1;
453         }
454         return 0;
457 static inline void add_to_write_order(struct object_entry **wo,
458                                unsigned int *endp,
459                                struct object_entry *e)
461         if (e->filled)
462                 return;
463         wo[(*endp)++] = e;
464         e->filled = 1;
467 static void add_descendants_to_write_order(struct object_entry **wo,
468                                            unsigned int *endp,
469                                            struct object_entry *e)
471         int add_to_order = 1;
472         while (e) {
473                 if (add_to_order) {
474                         struct object_entry *s;
475                         /* add this node... */
476                         add_to_write_order(wo, endp, e);
477                         /* all its siblings... */
478                         for (s = e->delta_sibling; s; s = s->delta_sibling) {
479                                 add_to_write_order(wo, endp, s);
480                         }
481                 }
482                 /* drop down a level to add left subtree nodes if possible */
483                 if (e->delta_child) {
484                         add_to_order = 1;
485                         e = e->delta_child;
486                 } else {
487                         add_to_order = 0;
488                         /* our sibling might have some children, it is next */
489                         if (e->delta_sibling) {
490                                 e = e->delta_sibling;
491                                 continue;
492                         }
493                         /* go back to our parent node */
494                         e = e->delta;
495                         while (e && !e->delta_sibling) {
496                                 /* we're on the right side of a subtree, keep
497                                  * going up until we can go right again */
498                                 e = e->delta;
499                         }
500                         if (!e) {
501                                 /* done- we hit our original root node */
502                                 return;
503                         }
504                         /* pass it off to sibling at this level */
505                         e = e->delta_sibling;
506                 }
507         };
510 static void add_family_to_write_order(struct object_entry **wo,
511                                       unsigned int *endp,
512                                       struct object_entry *e)
514         struct object_entry *root;
516         for (root = e; root->delta; root = root->delta)
517                 ; /* nothing */
518         add_descendants_to_write_order(wo, endp, root);
521 static struct object_entry **compute_write_order(void)
523         unsigned int i, wo_end, last_untagged;
525         struct object_entry **wo = xmalloc(nr_objects * sizeof(*wo));
527         for (i = 0; i < nr_objects; i++) {
528                 objects[i].tagged = 0;
529                 objects[i].filled = 0;
530                 objects[i].delta_child = NULL;
531                 objects[i].delta_sibling = NULL;
532         }
534         /*
535          * Fully connect delta_child/delta_sibling network.
536          * Make sure delta_sibling is sorted in the original
537          * recency order.
538          */
539         for (i = nr_objects; i > 0;) {
540                 struct object_entry *e = &objects[--i];
541                 if (!e->delta)
542                         continue;
543                 /* Mark me as the first child */
544                 e->delta_sibling = e->delta->delta_child;
545                 e->delta->delta_child = e;
546         }
548         /*
549          * Mark objects that are at the tip of tags.
550          */
551         for_each_tag_ref(mark_tagged, NULL);
553         /*
554          * Give the objects in the original recency order until
555          * we see a tagged tip.
556          */
557         for (i = wo_end = 0; i < nr_objects; i++) {
558                 if (objects[i].tagged)
559                         break;
560                 add_to_write_order(wo, &wo_end, &objects[i]);
561         }
562         last_untagged = i;
564         /*
565          * Then fill all the tagged tips.
566          */
567         for (; i < nr_objects; i++) {
568                 if (objects[i].tagged)
569                         add_to_write_order(wo, &wo_end, &objects[i]);
570         }
572         /*
573          * And then all remaining commits and tags.
574          */
575         for (i = last_untagged; i < nr_objects; i++) {
576                 if (objects[i].type != OBJ_COMMIT &&
577                     objects[i].type != OBJ_TAG)
578                         continue;
579                 add_to_write_order(wo, &wo_end, &objects[i]);
580         }
582         /*
583          * And then all the trees.
584          */
585         for (i = last_untagged; i < nr_objects; i++) {
586                 if (objects[i].type != OBJ_TREE)
587                         continue;
588                 add_to_write_order(wo, &wo_end, &objects[i]);
589         }
591         /*
592          * Finally all the rest in really tight order
593          */
594         for (i = last_untagged; i < nr_objects; i++) {
595                 if (!objects[i].filled)
596                         add_family_to_write_order(wo, &wo_end, &objects[i]);
597         }
599         if (wo_end != nr_objects)
600                 die("ordered %u objects, expected %"PRIu32, wo_end, nr_objects);
602         return wo;
605 static void write_pack_file(void)
607         uint32_t i = 0, j;
608         struct sha1file *f;
609         off_t offset;
610         struct pack_header hdr;
611         uint32_t nr_remaining = nr_result;
612         time_t last_mtime = 0;
613         struct object_entry **write_order;
615         if (progress > pack_to_stdout)
616                 progress_state = start_progress("Writing objects", nr_result);
617         written_list = xmalloc(nr_objects * sizeof(*written_list));
618         write_order = compute_write_order();
620         do {
621                 unsigned char sha1[20];
622                 char *pack_tmp_name = NULL;
624                 if (pack_to_stdout) {
625                         f = sha1fd_throughput(1, "<stdout>", progress_state);
626                 } else {
627                         char tmpname[PATH_MAX];
628                         int fd;
629                         fd = odb_mkstemp(tmpname, sizeof(tmpname),
630                                          "pack/tmp_pack_XXXXXX");
631                         pack_tmp_name = xstrdup(tmpname);
632                         f = sha1fd(fd, pack_tmp_name);
633                 }
635                 hdr.hdr_signature = htonl(PACK_SIGNATURE);
636                 hdr.hdr_version = htonl(PACK_VERSION);
637                 hdr.hdr_entries = htonl(nr_remaining);
638                 sha1write(f, &hdr, sizeof(hdr));
639                 offset = sizeof(hdr);
640                 nr_written = 0;
641                 for (; i < nr_objects; i++) {
642                         struct object_entry *e = write_order[i];
643                         if (!write_one(f, e, &offset))
644                                 break;
645                         display_progress(progress_state, written);
646                 }
648                 /*
649                  * Did we write the wrong # entries in the header?
650                  * If so, rewrite it like in fast-import
651                  */
652                 if (pack_to_stdout) {
653                         sha1close(f, sha1, CSUM_CLOSE);
654                 } else if (nr_written == nr_remaining) {
655                         sha1close(f, sha1, CSUM_FSYNC);
656                 } else {
657                         int fd = sha1close(f, sha1, 0);
658                         fixup_pack_header_footer(fd, sha1, pack_tmp_name,
659                                                  nr_written, sha1, offset);
660                         close(fd);
661                 }
663                 if (!pack_to_stdout) {
664                         struct stat st;
665                         const char *idx_tmp_name;
666                         char tmpname[PATH_MAX];
668                         idx_tmp_name = write_idx_file(NULL, written_list, nr_written,
669                                                       &pack_idx_opts, sha1);
671                         snprintf(tmpname, sizeof(tmpname), "%s-%s.pack",
672                                  base_name, sha1_to_hex(sha1));
673                         free_pack_by_name(tmpname);
674                         if (adjust_shared_perm(pack_tmp_name))
675                                 die_errno("unable to make temporary pack file readable");
676                         if (rename(pack_tmp_name, tmpname))
677                                 die_errno("unable to rename temporary pack file");
679                         /*
680                          * Packs are runtime accessed in their mtime
681                          * order since newer packs are more likely to contain
682                          * younger objects.  So if we are creating multiple
683                          * packs then we should modify the mtime of later ones
684                          * to preserve this property.
685                          */
686                         if (stat(tmpname, &st) < 0) {
687                                 warning("failed to stat %s: %s",
688                                         tmpname, strerror(errno));
689                         } else if (!last_mtime) {
690                                 last_mtime = st.st_mtime;
691                         } else {
692                                 struct utimbuf utb;
693                                 utb.actime = st.st_atime;
694                                 utb.modtime = --last_mtime;
695                                 if (utime(tmpname, &utb) < 0)
696                                         warning("failed utime() on %s: %s",
697                                                 tmpname, strerror(errno));
698                         }
700                         snprintf(tmpname, sizeof(tmpname), "%s-%s.idx",
701                                  base_name, sha1_to_hex(sha1));
702                         if (adjust_shared_perm(idx_tmp_name))
703                                 die_errno("unable to make temporary index file readable");
704                         if (rename(idx_tmp_name, tmpname))
705                                 die_errno("unable to rename temporary index file");
707                         free((void *) idx_tmp_name);
708                         free(pack_tmp_name);
709                         puts(sha1_to_hex(sha1));
710                 }
712                 /* mark written objects as written to previous pack */
713                 for (j = 0; j < nr_written; j++) {
714                         written_list[j]->offset = (off_t)-1;
715                 }
716                 nr_remaining -= nr_written;
717         } while (nr_remaining && i < nr_objects);
719         free(written_list);
720         free(write_order);
721         stop_progress(&progress_state);
722         if (written != nr_result)
723                 die("wrote %"PRIu32" objects while expecting %"PRIu32,
724                         written, nr_result);
727 static int locate_object_entry_hash(const unsigned char *sha1)
729         int i;
730         unsigned int ui;
731         memcpy(&ui, sha1, sizeof(unsigned int));
732         i = ui % object_ix_hashsz;
733         while (0 < object_ix[i]) {
734                 if (!hashcmp(sha1, objects[object_ix[i] - 1].idx.sha1))
735                         return i;
736                 if (++i == object_ix_hashsz)
737                         i = 0;
738         }
739         return -1 - i;
742 static struct object_entry *locate_object_entry(const unsigned char *sha1)
744         int i;
746         if (!object_ix_hashsz)
747                 return NULL;
749         i = locate_object_entry_hash(sha1);
750         if (0 <= i)
751                 return &objects[object_ix[i]-1];
752         return NULL;
755 static void rehash_objects(void)
757         uint32_t i;
758         struct object_entry *oe;
760         object_ix_hashsz = nr_objects * 3;
761         if (object_ix_hashsz < 1024)
762                 object_ix_hashsz = 1024;
763         object_ix = xrealloc(object_ix, sizeof(int) * object_ix_hashsz);
764         memset(object_ix, 0, sizeof(int) * object_ix_hashsz);
765         for (i = 0, oe = objects; i < nr_objects; i++, oe++) {
766                 int ix = locate_object_entry_hash(oe->idx.sha1);
767                 if (0 <= ix)
768                         continue;
769                 ix = -1 - ix;
770                 object_ix[ix] = i + 1;
771         }
774 static unsigned name_hash(const char *name)
776         unsigned c, hash = 0;
778         if (!name)
779                 return 0;
781         /*
782          * This effectively just creates a sortable number from the
783          * last sixteen non-whitespace characters. Last characters
784          * count "most", so things that end in ".c" sort together.
785          */
786         while ((c = *name++) != 0) {
787                 if (isspace(c))
788                         continue;
789                 hash = (hash >> 2) + (c << 24);
790         }
791         return hash;
794 static void setup_delta_attr_check(struct git_attr_check *check)
796         static struct git_attr *attr_delta;
798         if (!attr_delta)
799                 attr_delta = git_attr("delta");
801         check[0].attr = attr_delta;
804 static int no_try_delta(const char *path)
806         struct git_attr_check check[1];
808         setup_delta_attr_check(check);
809         if (git_check_attr(path, ARRAY_SIZE(check), check))
810                 return 0;
811         if (ATTR_FALSE(check->value))
812                 return 1;
813         return 0;
816 static int add_object_entry(const unsigned char *sha1, enum object_type type,
817                             const char *name, int exclude)
819         struct object_entry *entry;
820         struct packed_git *p, *found_pack = NULL;
821         off_t found_offset = 0;
822         int ix;
823         unsigned hash = name_hash(name);
825         ix = nr_objects ? locate_object_entry_hash(sha1) : -1;
826         if (ix >= 0) {
827                 if (exclude) {
828                         entry = objects + object_ix[ix] - 1;
829                         if (!entry->preferred_base)
830                                 nr_result--;
831                         entry->preferred_base = 1;
832                 }
833                 return 0;
834         }
836         if (!exclude && local && has_loose_object_nonlocal(sha1))
837                 return 0;
839         for (p = packed_git; p; p = p->next) {
840                 off_t offset = find_pack_entry_one(sha1, p);
841                 if (offset) {
842                         if (!found_pack) {
843                                 found_offset = offset;
844                                 found_pack = p;
845                         }
846                         if (exclude)
847                                 break;
848                         if (incremental)
849                                 return 0;
850                         if (local && !p->pack_local)
851                                 return 0;
852                         if (ignore_packed_keep && p->pack_local && p->pack_keep)
853                                 return 0;
854                 }
855         }
857         if (nr_objects >= nr_alloc) {
858                 nr_alloc = (nr_alloc  + 1024) * 3 / 2;
859                 objects = xrealloc(objects, nr_alloc * sizeof(*entry));
860         }
862         entry = objects + nr_objects++;
863         memset(entry, 0, sizeof(*entry));
864         hashcpy(entry->idx.sha1, sha1);
865         entry->hash = hash;
866         if (type)
867                 entry->type = type;
868         if (exclude)
869                 entry->preferred_base = 1;
870         else
871                 nr_result++;
872         if (found_pack) {
873                 entry->in_pack = found_pack;
874                 entry->in_pack_offset = found_offset;
875         }
877         if (object_ix_hashsz * 3 <= nr_objects * 4)
878                 rehash_objects();
879         else
880                 object_ix[-1 - ix] = nr_objects;
882         display_progress(progress_state, nr_objects);
884         if (name && no_try_delta(name))
885                 entry->no_try_delta = 1;
887         return 1;
890 struct pbase_tree_cache {
891         unsigned char sha1[20];
892         int ref;
893         int temporary;
894         void *tree_data;
895         unsigned long tree_size;
896 };
898 static struct pbase_tree_cache *(pbase_tree_cache[256]);
899 static int pbase_tree_cache_ix(const unsigned char *sha1)
901         return sha1[0] % ARRAY_SIZE(pbase_tree_cache);
903 static int pbase_tree_cache_ix_incr(int ix)
905         return (ix+1) % ARRAY_SIZE(pbase_tree_cache);
908 static struct pbase_tree {
909         struct pbase_tree *next;
910         /* This is a phony "cache" entry; we are not
911          * going to evict it nor find it through _get()
912          * mechanism -- this is for the toplevel node that
913          * would almost always change with any commit.
914          */
915         struct pbase_tree_cache pcache;
916 } *pbase_tree;
918 static struct pbase_tree_cache *pbase_tree_get(const unsigned char *sha1)
920         struct pbase_tree_cache *ent, *nent;
921         void *data;
922         unsigned long size;
923         enum object_type type;
924         int neigh;
925         int my_ix = pbase_tree_cache_ix(sha1);
926         int available_ix = -1;
928         /* pbase-tree-cache acts as a limited hashtable.
929          * your object will be found at your index or within a few
930          * slots after that slot if it is cached.
931          */
932         for (neigh = 0; neigh < 8; neigh++) {
933                 ent = pbase_tree_cache[my_ix];
934                 if (ent && !hashcmp(ent->sha1, sha1)) {
935                         ent->ref++;
936                         return ent;
937                 }
938                 else if (((available_ix < 0) && (!ent || !ent->ref)) ||
939                          ((0 <= available_ix) &&
940                           (!ent && pbase_tree_cache[available_ix])))
941                         available_ix = my_ix;
942                 if (!ent)
943                         break;
944                 my_ix = pbase_tree_cache_ix_incr(my_ix);
945         }
947         /* Did not find one.  Either we got a bogus request or
948          * we need to read and perhaps cache.
949          */
950         data = read_sha1_file(sha1, &type, &size);
951         if (!data)
952                 return NULL;
953         if (type != OBJ_TREE) {
954                 free(data);
955                 return NULL;
956         }
958         /* We need to either cache or return a throwaway copy */
960         if (available_ix < 0)
961                 ent = NULL;
962         else {
963                 ent = pbase_tree_cache[available_ix];
964                 my_ix = available_ix;
965         }
967         if (!ent) {
968                 nent = xmalloc(sizeof(*nent));
969                 nent->temporary = (available_ix < 0);
970         }
971         else {
972                 /* evict and reuse */
973                 free(ent->tree_data);
974                 nent = ent;
975         }
976         hashcpy(nent->sha1, sha1);
977         nent->tree_data = data;
978         nent->tree_size = size;
979         nent->ref = 1;
980         if (!nent->temporary)
981                 pbase_tree_cache[my_ix] = nent;
982         return nent;
985 static void pbase_tree_put(struct pbase_tree_cache *cache)
987         if (!cache->temporary) {
988                 cache->ref--;
989                 return;
990         }
991         free(cache->tree_data);
992         free(cache);
995 static int name_cmp_len(const char *name)
997         int i;
998         for (i = 0; name[i] && name[i] != '\n' && name[i] != '/'; i++)
999                 ;
1000         return i;
1003 static void add_pbase_object(struct tree_desc *tree,
1004                              const char *name,
1005                              int cmplen,
1006                              const char *fullname)
1008         struct name_entry entry;
1009         int cmp;
1011         while (tree_entry(tree,&entry)) {
1012                 if (S_ISGITLINK(entry.mode))
1013                         continue;
1014                 cmp = tree_entry_len(entry.path, entry.sha1) != cmplen ? 1 :
1015                       memcmp(name, entry.path, cmplen);
1016                 if (cmp > 0)
1017                         continue;
1018                 if (cmp < 0)
1019                         return;
1020                 if (name[cmplen] != '/') {
1021                         add_object_entry(entry.sha1,
1022                                          object_type(entry.mode),
1023                                          fullname, 1);
1024                         return;
1025                 }
1026                 if (S_ISDIR(entry.mode)) {
1027                         struct tree_desc sub;
1028                         struct pbase_tree_cache *tree;
1029                         const char *down = name+cmplen+1;
1030                         int downlen = name_cmp_len(down);
1032                         tree = pbase_tree_get(entry.sha1);
1033                         if (!tree)
1034                                 return;
1035                         init_tree_desc(&sub, tree->tree_data, tree->tree_size);
1037                         add_pbase_object(&sub, down, downlen, fullname);
1038                         pbase_tree_put(tree);
1039                 }
1040         }
1043 static unsigned *done_pbase_paths;
1044 static int done_pbase_paths_num;
1045 static int done_pbase_paths_alloc;
1046 static int done_pbase_path_pos(unsigned hash)
1048         int lo = 0;
1049         int hi = done_pbase_paths_num;
1050         while (lo < hi) {
1051                 int mi = (hi + lo) / 2;
1052                 if (done_pbase_paths[mi] == hash)
1053                         return mi;
1054                 if (done_pbase_paths[mi] < hash)
1055                         hi = mi;
1056                 else
1057                         lo = mi + 1;
1058         }
1059         return -lo-1;
1062 static int check_pbase_path(unsigned hash)
1064         int pos = (!done_pbase_paths) ? -1 : done_pbase_path_pos(hash);
1065         if (0 <= pos)
1066                 return 1;
1067         pos = -pos - 1;
1068         if (done_pbase_paths_alloc <= done_pbase_paths_num) {
1069                 done_pbase_paths_alloc = alloc_nr(done_pbase_paths_alloc);
1070                 done_pbase_paths = xrealloc(done_pbase_paths,
1071                                             done_pbase_paths_alloc *
1072                                             sizeof(unsigned));
1073         }
1074         done_pbase_paths_num++;
1075         if (pos < done_pbase_paths_num)
1076                 memmove(done_pbase_paths + pos + 1,
1077                         done_pbase_paths + pos,
1078                         (done_pbase_paths_num - pos - 1) * sizeof(unsigned));
1079         done_pbase_paths[pos] = hash;
1080         return 0;
1083 static void add_preferred_base_object(const char *name)
1085         struct pbase_tree *it;
1086         int cmplen;
1087         unsigned hash = name_hash(name);
1089         if (!num_preferred_base || check_pbase_path(hash))
1090                 return;
1092         cmplen = name_cmp_len(name);
1093         for (it = pbase_tree; it; it = it->next) {
1094                 if (cmplen == 0) {
1095                         add_object_entry(it->pcache.sha1, OBJ_TREE, NULL, 1);
1096                 }
1097                 else {
1098                         struct tree_desc tree;
1099                         init_tree_desc(&tree, it->pcache.tree_data, it->pcache.tree_size);
1100                         add_pbase_object(&tree, name, cmplen, name);
1101                 }
1102         }
1105 static void add_preferred_base(unsigned char *sha1)
1107         struct pbase_tree *it;
1108         void *data;
1109         unsigned long size;
1110         unsigned char tree_sha1[20];
1112         if (window <= num_preferred_base++)
1113                 return;
1115         data = read_object_with_reference(sha1, tree_type, &size, tree_sha1);
1116         if (!data)
1117                 return;
1119         for (it = pbase_tree; it; it = it->next) {
1120                 if (!hashcmp(it->pcache.sha1, tree_sha1)) {
1121                         free(data);
1122                         return;
1123                 }
1124         }
1126         it = xcalloc(1, sizeof(*it));
1127         it->next = pbase_tree;
1128         pbase_tree = it;
1130         hashcpy(it->pcache.sha1, tree_sha1);
1131         it->pcache.tree_data = data;
1132         it->pcache.tree_size = size;
1135 static void cleanup_preferred_base(void)
1137         struct pbase_tree *it;
1138         unsigned i;
1140         it = pbase_tree;
1141         pbase_tree = NULL;
1142         while (it) {
1143                 struct pbase_tree *this = it;
1144                 it = this->next;
1145                 free(this->pcache.tree_data);
1146                 free(this);
1147         }
1149         for (i = 0; i < ARRAY_SIZE(pbase_tree_cache); i++) {
1150                 if (!pbase_tree_cache[i])
1151                         continue;
1152                 free(pbase_tree_cache[i]->tree_data);
1153                 free(pbase_tree_cache[i]);
1154                 pbase_tree_cache[i] = NULL;
1155         }
1157         free(done_pbase_paths);
1158         done_pbase_paths = NULL;
1159         done_pbase_paths_num = done_pbase_paths_alloc = 0;
1162 static void check_object(struct object_entry *entry)
1164         if (entry->in_pack) {
1165                 struct packed_git *p = entry->in_pack;
1166                 struct pack_window *w_curs = NULL;
1167                 const unsigned char *base_ref = NULL;
1168                 struct object_entry *base_entry;
1169                 unsigned long used, used_0;
1170                 unsigned long avail;
1171                 off_t ofs;
1172                 unsigned char *buf, c;
1174                 buf = use_pack(p, &w_curs, entry->in_pack_offset, &avail);
1176                 /*
1177                  * We want in_pack_type even if we do not reuse delta
1178                  * since non-delta representations could still be reused.
1179                  */
1180                 used = unpack_object_header_buffer(buf, avail,
1181                                                    &entry->in_pack_type,
1182                                                    &entry->size);
1183                 if (used == 0)
1184                         goto give_up;
1186                 /*
1187                  * Determine if this is a delta and if so whether we can
1188                  * reuse it or not.  Otherwise let's find out as cheaply as
1189                  * possible what the actual type and size for this object is.
1190                  */
1191                 switch (entry->in_pack_type) {
1192                 default:
1193                         /* Not a delta hence we've already got all we need. */
1194                         entry->type = entry->in_pack_type;
1195                         entry->in_pack_header_size = used;
1196                         if (entry->type < OBJ_COMMIT || entry->type > OBJ_BLOB)
1197                                 goto give_up;
1198                         unuse_pack(&w_curs);
1199                         return;
1200                 case OBJ_REF_DELTA:
1201                         if (reuse_delta && !entry->preferred_base)
1202                                 base_ref = use_pack(p, &w_curs,
1203                                                 entry->in_pack_offset + used, NULL);
1204                         entry->in_pack_header_size = used + 20;
1205                         break;
1206                 case OBJ_OFS_DELTA:
1207                         buf = use_pack(p, &w_curs,
1208                                        entry->in_pack_offset + used, NULL);
1209                         used_0 = 0;
1210                         c = buf[used_0++];
1211                         ofs = c & 127;
1212                         while (c & 128) {
1213                                 ofs += 1;
1214                                 if (!ofs || MSB(ofs, 7)) {
1215                                         error("delta base offset overflow in pack for %s",
1216                                               sha1_to_hex(entry->idx.sha1));
1217                                         goto give_up;
1218                                 }
1219                                 c = buf[used_0++];
1220                                 ofs = (ofs << 7) + (c & 127);
1221                         }
1222                         ofs = entry->in_pack_offset - ofs;
1223                         if (ofs <= 0 || ofs >= entry->in_pack_offset) {
1224                                 error("delta base offset out of bound for %s",
1225                                       sha1_to_hex(entry->idx.sha1));
1226                                 goto give_up;
1227                         }
1228                         if (reuse_delta && !entry->preferred_base) {
1229                                 struct revindex_entry *revidx;
1230                                 revidx = find_pack_revindex(p, ofs);
1231                                 if (!revidx)
1232                                         goto give_up;
1233                                 base_ref = nth_packed_object_sha1(p, revidx->nr);
1234                         }
1235                         entry->in_pack_header_size = used + used_0;
1236                         break;
1237                 }
1239                 if (base_ref && (base_entry = locate_object_entry(base_ref))) {
1240                         /*
1241                          * If base_ref was set above that means we wish to
1242                          * reuse delta data, and we even found that base
1243                          * in the list of objects we want to pack. Goodie!
1244                          *
1245                          * Depth value does not matter - find_deltas() will
1246                          * never consider reused delta as the base object to
1247                          * deltify other objects against, in order to avoid
1248                          * circular deltas.
1249                          */
1250                         entry->type = entry->in_pack_type;
1251                         entry->delta = base_entry;
1252                         entry->delta_size = entry->size;
1253                         entry->delta_sibling = base_entry->delta_child;
1254                         base_entry->delta_child = entry;
1255                         unuse_pack(&w_curs);
1256                         return;
1257                 }
1259                 if (entry->type) {
1260                         /*
1261                          * This must be a delta and we already know what the
1262                          * final object type is.  Let's extract the actual
1263                          * object size from the delta header.
1264                          */
1265                         entry->size = get_size_from_delta(p, &w_curs,
1266                                         entry->in_pack_offset + entry->in_pack_header_size);
1267                         if (entry->size == 0)
1268                                 goto give_up;
1269                         unuse_pack(&w_curs);
1270                         return;
1271                 }
1273                 /*
1274                  * No choice but to fall back to the recursive delta walk
1275                  * with sha1_object_info() to find about the object type
1276                  * at this point...
1277                  */
1278                 give_up:
1279                 unuse_pack(&w_curs);
1280         }
1282         entry->type = sha1_object_info(entry->idx.sha1, &entry->size);
1283         /*
1284          * The error condition is checked in prepare_pack().  This is
1285          * to permit a missing preferred base object to be ignored
1286          * as a preferred base.  Doing so can result in a larger
1287          * pack file, but the transfer will still take place.
1288          */
1291 static int pack_offset_sort(const void *_a, const void *_b)
1293         const struct object_entry *a = *(struct object_entry **)_a;
1294         const struct object_entry *b = *(struct object_entry **)_b;
1296         /* avoid filesystem trashing with loose objects */
1297         if (!a->in_pack && !b->in_pack)
1298                 return hashcmp(a->idx.sha1, b->idx.sha1);
1300         if (a->in_pack < b->in_pack)
1301                 return -1;
1302         if (a->in_pack > b->in_pack)
1303                 return 1;
1304         return a->in_pack_offset < b->in_pack_offset ? -1 :
1305                         (a->in_pack_offset > b->in_pack_offset);
1308 static void get_object_details(void)
1310         uint32_t i;
1311         struct object_entry **sorted_by_offset;
1313         sorted_by_offset = xcalloc(nr_objects, sizeof(struct object_entry *));
1314         for (i = 0; i < nr_objects; i++)
1315                 sorted_by_offset[i] = objects + i;
1316         qsort(sorted_by_offset, nr_objects, sizeof(*sorted_by_offset), pack_offset_sort);
1318         for (i = 0; i < nr_objects; i++) {
1319                 struct object_entry *entry = sorted_by_offset[i];
1320                 check_object(entry);
1321                 if (big_file_threshold <= entry->size)
1322                         entry->no_try_delta = 1;
1323         }
1325         free(sorted_by_offset);
1328 /*
1329  * We search for deltas in a list sorted by type, by filename hash, and then
1330  * by size, so that we see progressively smaller and smaller files.
1331  * That's because we prefer deltas to be from the bigger file
1332  * to the smaller -- deletes are potentially cheaper, but perhaps
1333  * more importantly, the bigger file is likely the more recent
1334  * one.  The deepest deltas are therefore the oldest objects which are
1335  * less susceptible to be accessed often.
1336  */
1337 static int type_size_sort(const void *_a, const void *_b)
1339         const struct object_entry *a = *(struct object_entry **)_a;
1340         const struct object_entry *b = *(struct object_entry **)_b;
1342         if (a->type > b->type)
1343                 return -1;
1344         if (a->type < b->type)
1345                 return 1;
1346         if (a->hash > b->hash)
1347                 return -1;
1348         if (a->hash < b->hash)
1349                 return 1;
1350         if (a->preferred_base > b->preferred_base)
1351                 return -1;
1352         if (a->preferred_base < b->preferred_base)
1353                 return 1;
1354         if (a->size > b->size)
1355                 return -1;
1356         if (a->size < b->size)
1357                 return 1;
1358         return a < b ? -1 : (a > b);  /* newest first */
1361 struct unpacked {
1362         struct object_entry *entry;
1363         void *data;
1364         struct delta_index *index;
1365         unsigned depth;
1366 };
1368 static int delta_cacheable(unsigned long src_size, unsigned long trg_size,
1369                            unsigned long delta_size)
1371         if (max_delta_cache_size && delta_cache_size + delta_size > max_delta_cache_size)
1372                 return 0;
1374         if (delta_size < cache_max_small_delta_size)
1375                 return 1;
1377         /* cache delta, if objects are large enough compared to delta size */
1378         if ((src_size >> 20) + (trg_size >> 21) > (delta_size >> 10))
1379                 return 1;
1381         return 0;
1384 #ifndef NO_PTHREADS
1386 static pthread_mutex_t read_mutex;
1387 #define read_lock()             pthread_mutex_lock(&read_mutex)
1388 #define read_unlock()           pthread_mutex_unlock(&read_mutex)
1390 static pthread_mutex_t cache_mutex;
1391 #define cache_lock()            pthread_mutex_lock(&cache_mutex)
1392 #define cache_unlock()          pthread_mutex_unlock(&cache_mutex)
1394 static pthread_mutex_t progress_mutex;
1395 #define progress_lock()         pthread_mutex_lock(&progress_mutex)
1396 #define progress_unlock()       pthread_mutex_unlock(&progress_mutex)
1398 #else
1400 #define read_lock()             (void)0
1401 #define read_unlock()           (void)0
1402 #define cache_lock()            (void)0
1403 #define cache_unlock()          (void)0
1404 #define progress_lock()         (void)0
1405 #define progress_unlock()       (void)0
1407 #endif
1409 static int try_delta(struct unpacked *trg, struct unpacked *src,
1410                      unsigned max_depth, unsigned long *mem_usage)
1412         struct object_entry *trg_entry = trg->entry;
1413         struct object_entry *src_entry = src->entry;
1414         unsigned long trg_size, src_size, delta_size, sizediff, max_size, sz;
1415         unsigned ref_depth;
1416         enum object_type type;
1417         void *delta_buf;
1419         /* Don't bother doing diffs between different types */
1420         if (trg_entry->type != src_entry->type)
1421                 return -1;
1423         /*
1424          * We do not bother to try a delta that we discarded on an
1425          * earlier try, but only when reusing delta data.  Note that
1426          * src_entry that is marked as the preferred_base should always
1427          * be considered, as even if we produce a suboptimal delta against
1428          * it, we will still save the transfer cost, as we already know
1429          * the other side has it and we won't send src_entry at all.
1430          */
1431         if (reuse_delta && trg_entry->in_pack &&
1432             trg_entry->in_pack == src_entry->in_pack &&
1433             !src_entry->preferred_base &&
1434             trg_entry->in_pack_type != OBJ_REF_DELTA &&
1435             trg_entry->in_pack_type != OBJ_OFS_DELTA)
1436                 return 0;
1438         /* Let's not bust the allowed depth. */
1439         if (src->depth >= max_depth)
1440                 return 0;
1442         /* Now some size filtering heuristics. */
1443         trg_size = trg_entry->size;
1444         if (!trg_entry->delta) {
1445                 max_size = trg_size/2 - 20;
1446                 ref_depth = 1;
1447         } else {
1448                 max_size = trg_entry->delta_size;
1449                 ref_depth = trg->depth;
1450         }
1451         max_size = (uint64_t)max_size * (max_depth - src->depth) /
1452                                                 (max_depth - ref_depth + 1);
1453         if (max_size == 0)
1454                 return 0;
1455         src_size = src_entry->size;
1456         sizediff = src_size < trg_size ? trg_size - src_size : 0;
1457         if (sizediff >= max_size)
1458                 return 0;
1459         if (trg_size < src_size / 32)
1460                 return 0;
1462         /* Load data if not already done */
1463         if (!trg->data) {
1464                 read_lock();
1465                 trg->data = read_sha1_file(trg_entry->idx.sha1, &type, &sz);
1466                 read_unlock();
1467                 if (!trg->data)
1468                         die("object %s cannot be read",
1469                             sha1_to_hex(trg_entry->idx.sha1));
1470                 if (sz != trg_size)
1471                         die("object %s inconsistent object length (%lu vs %lu)",
1472                             sha1_to_hex(trg_entry->idx.sha1), sz, trg_size);
1473                 *mem_usage += sz;
1474         }
1475         if (!src->data) {
1476                 read_lock();
1477                 src->data = read_sha1_file(src_entry->idx.sha1, &type, &sz);
1478                 read_unlock();
1479                 if (!src->data) {
1480                         if (src_entry->preferred_base) {
1481                                 static int warned = 0;
1482                                 if (!warned++)
1483                                         warning("object %s cannot be read",
1484                                                 sha1_to_hex(src_entry->idx.sha1));
1485                                 /*
1486                                  * Those objects are not included in the
1487                                  * resulting pack.  Be resilient and ignore
1488                                  * them if they can't be read, in case the
1489                                  * pack could be created nevertheless.
1490                                  */
1491                                 return 0;
1492                         }
1493                         die("object %s cannot be read",
1494                             sha1_to_hex(src_entry->idx.sha1));
1495                 }
1496                 if (sz != src_size)
1497                         die("object %s inconsistent object length (%lu vs %lu)",
1498                             sha1_to_hex(src_entry->idx.sha1), sz, src_size);
1499                 *mem_usage += sz;
1500         }
1501         if (!src->index) {
1502                 src->index = create_delta_index(src->data, src_size);
1503                 if (!src->index) {
1504                         static int warned = 0;
1505                         if (!warned++)
1506                                 warning("suboptimal pack - out of memory");
1507                         return 0;
1508                 }
1509                 *mem_usage += sizeof_delta_index(src->index);
1510         }
1512         delta_buf = create_delta(src->index, trg->data, trg_size, &delta_size, max_size);
1513         if (!delta_buf)
1514                 return 0;
1516         if (trg_entry->delta) {
1517                 /* Prefer only shallower same-sized deltas. */
1518                 if (delta_size == trg_entry->delta_size &&
1519                     src->depth + 1 >= trg->depth) {
1520                         free(delta_buf);
1521                         return 0;
1522                 }
1523         }
1525         /*
1526          * Handle memory allocation outside of the cache
1527          * accounting lock.  Compiler will optimize the strangeness
1528          * away when NO_PTHREADS is defined.
1529          */
1530         free(trg_entry->delta_data);
1531         cache_lock();
1532         if (trg_entry->delta_data) {
1533                 delta_cache_size -= trg_entry->delta_size;
1534                 trg_entry->delta_data = NULL;
1535         }
1536         if (delta_cacheable(src_size, trg_size, delta_size)) {
1537                 delta_cache_size += delta_size;
1538                 cache_unlock();
1539                 trg_entry->delta_data = xrealloc(delta_buf, delta_size);
1540         } else {
1541                 cache_unlock();
1542                 free(delta_buf);
1543         }
1545         trg_entry->delta = src_entry;
1546         trg_entry->delta_size = delta_size;
1547         trg->depth = src->depth + 1;
1549         return 1;
1552 static unsigned int check_delta_limit(struct object_entry *me, unsigned int n)
1554         struct object_entry *child = me->delta_child;
1555         unsigned int m = n;
1556         while (child) {
1557                 unsigned int c = check_delta_limit(child, n + 1);
1558                 if (m < c)
1559                         m = c;
1560                 child = child->delta_sibling;
1561         }
1562         return m;
1565 static unsigned long free_unpacked(struct unpacked *n)
1567         unsigned long freed_mem = sizeof_delta_index(n->index);
1568         free_delta_index(n->index);
1569         n->index = NULL;
1570         if (n->data) {
1571                 freed_mem += n->entry->size;
1572                 free(n->data);
1573                 n->data = NULL;
1574         }
1575         n->entry = NULL;
1576         n->depth = 0;
1577         return freed_mem;
1580 static void find_deltas(struct object_entry **list, unsigned *list_size,
1581                         int window, int depth, unsigned *processed)
1583         uint32_t i, idx = 0, count = 0;
1584         struct unpacked *array;
1585         unsigned long mem_usage = 0;
1587         array = xcalloc(window, sizeof(struct unpacked));
1589         for (;;) {
1590                 struct object_entry *entry;
1591                 struct unpacked *n = array + idx;
1592                 int j, max_depth, best_base = -1;
1594                 progress_lock();
1595                 if (!*list_size) {
1596                         progress_unlock();
1597                         break;
1598                 }
1599                 entry = *list++;
1600                 (*list_size)--;
1601                 if (!entry->preferred_base) {
1602                         (*processed)++;
1603                         display_progress(progress_state, *processed);
1604                 }
1605                 progress_unlock();
1607                 mem_usage -= free_unpacked(n);
1608                 n->entry = entry;
1610                 while (window_memory_limit &&
1611                        mem_usage > window_memory_limit &&
1612                        count > 1) {
1613                         uint32_t tail = (idx + window - count) % window;
1614                         mem_usage -= free_unpacked(array + tail);
1615                         count--;
1616                 }
1618                 /* We do not compute delta to *create* objects we are not
1619                  * going to pack.
1620                  */
1621                 if (entry->preferred_base)
1622                         goto next;
1624                 /*
1625                  * If the current object is at pack edge, take the depth the
1626                  * objects that depend on the current object into account
1627                  * otherwise they would become too deep.
1628                  */
1629                 max_depth = depth;
1630                 if (entry->delta_child) {
1631                         max_depth -= check_delta_limit(entry, 0);
1632                         if (max_depth <= 0)
1633                                 goto next;
1634                 }
1636                 j = window;
1637                 while (--j > 0) {
1638                         int ret;
1639                         uint32_t other_idx = idx + j;
1640                         struct unpacked *m;
1641                         if (other_idx >= window)
1642                                 other_idx -= window;
1643                         m = array + other_idx;
1644                         if (!m->entry)
1645                                 break;
1646                         ret = try_delta(n, m, max_depth, &mem_usage);
1647                         if (ret < 0)
1648                                 break;
1649                         else if (ret > 0)
1650                                 best_base = other_idx;
1651                 }
1653                 /*
1654                  * If we decided to cache the delta data, then it is best
1655                  * to compress it right away.  First because we have to do
1656                  * it anyway, and doing it here while we're threaded will
1657                  * save a lot of time in the non threaded write phase,
1658                  * as well as allow for caching more deltas within
1659                  * the same cache size limit.
1660                  * ...
1661                  * But only if not writing to stdout, since in that case
1662                  * the network is most likely throttling writes anyway,
1663                  * and therefore it is best to go to the write phase ASAP
1664                  * instead, as we can afford spending more time compressing
1665                  * between writes at that moment.
1666                  */
1667                 if (entry->delta_data && !pack_to_stdout) {
1668                         entry->z_delta_size = do_compress(&entry->delta_data,
1669                                                           entry->delta_size);
1670                         cache_lock();
1671                         delta_cache_size -= entry->delta_size;
1672                         delta_cache_size += entry->z_delta_size;
1673                         cache_unlock();
1674                 }
1676                 /* if we made n a delta, and if n is already at max
1677                  * depth, leaving it in the window is pointless.  we
1678                  * should evict it first.
1679                  */
1680                 if (entry->delta && max_depth <= n->depth)
1681                         continue;
1683                 /*
1684                  * Move the best delta base up in the window, after the
1685                  * currently deltified object, to keep it longer.  It will
1686                  * be the first base object to be attempted next.
1687                  */
1688                 if (entry->delta) {
1689                         struct unpacked swap = array[best_base];
1690                         int dist = (window + idx - best_base) % window;
1691                         int dst = best_base;
1692                         while (dist--) {
1693                                 int src = (dst + 1) % window;
1694                                 array[dst] = array[src];
1695                                 dst = src;
1696                         }
1697                         array[dst] = swap;
1698                 }
1700                 next:
1701                 idx++;
1702                 if (count + 1 < window)
1703                         count++;
1704                 if (idx >= window)
1705                         idx = 0;
1706         }
1708         for (i = 0; i < window; ++i) {
1709                 free_delta_index(array[i].index);
1710                 free(array[i].data);
1711         }
1712         free(array);
1715 #ifndef NO_PTHREADS
1717 static void try_to_free_from_threads(size_t size)
1719         read_lock();
1720         release_pack_memory(size, -1);
1721         read_unlock();
1724 static try_to_free_t old_try_to_free_routine;
1726 /*
1727  * The main thread waits on the condition that (at least) one of the workers
1728  * has stopped working (which is indicated in the .working member of
1729  * struct thread_params).
1730  * When a work thread has completed its work, it sets .working to 0 and
1731  * signals the main thread and waits on the condition that .data_ready
1732  * becomes 1.
1733  */
1735 struct thread_params {
1736         pthread_t thread;
1737         struct object_entry **list;
1738         unsigned list_size;
1739         unsigned remaining;
1740         int window;
1741         int depth;
1742         int working;
1743         int data_ready;
1744         pthread_mutex_t mutex;
1745         pthread_cond_t cond;
1746         unsigned *processed;
1747 };
1749 static pthread_cond_t progress_cond;
1751 /*
1752  * Mutex and conditional variable can't be statically-initialized on Windows.
1753  */
1754 static void init_threaded_search(void)
1756         init_recursive_mutex(&read_mutex);
1757         pthread_mutex_init(&cache_mutex, NULL);
1758         pthread_mutex_init(&progress_mutex, NULL);
1759         pthread_cond_init(&progress_cond, NULL);
1760         old_try_to_free_routine = set_try_to_free_routine(try_to_free_from_threads);
1763 static void cleanup_threaded_search(void)
1765         set_try_to_free_routine(old_try_to_free_routine);
1766         pthread_cond_destroy(&progress_cond);
1767         pthread_mutex_destroy(&read_mutex);
1768         pthread_mutex_destroy(&cache_mutex);
1769         pthread_mutex_destroy(&progress_mutex);
1772 static void *threaded_find_deltas(void *arg)
1774         struct thread_params *me = arg;
1776         while (me->remaining) {
1777                 find_deltas(me->list, &me->remaining,
1778                             me->window, me->depth, me->processed);
1780                 progress_lock();
1781                 me->working = 0;
1782                 pthread_cond_signal(&progress_cond);
1783                 progress_unlock();
1785                 /*
1786                  * We must not set ->data_ready before we wait on the
1787                  * condition because the main thread may have set it to 1
1788                  * before we get here. In order to be sure that new
1789                  * work is available if we see 1 in ->data_ready, it
1790                  * was initialized to 0 before this thread was spawned
1791                  * and we reset it to 0 right away.
1792                  */
1793                 pthread_mutex_lock(&me->mutex);
1794                 while (!me->data_ready)
1795                         pthread_cond_wait(&me->cond, &me->mutex);
1796                 me->data_ready = 0;
1797                 pthread_mutex_unlock(&me->mutex);
1798         }
1799         /* leave ->working 1 so that this doesn't get more work assigned */
1800         return NULL;
1803 static void ll_find_deltas(struct object_entry **list, unsigned list_size,
1804                            int window, int depth, unsigned *processed)
1806         struct thread_params *p;
1807         int i, ret, active_threads = 0;
1809         init_threaded_search();
1811         if (!delta_search_threads)      /* --threads=0 means autodetect */
1812                 delta_search_threads = online_cpus();
1813         if (delta_search_threads <= 1) {
1814                 find_deltas(list, &list_size, window, depth, processed);
1815                 cleanup_threaded_search();
1816                 return;
1817         }
1818         if (progress > pack_to_stdout)
1819                 fprintf(stderr, "Delta compression using up to %d threads.\n",
1820                                 delta_search_threads);
1821         p = xcalloc(delta_search_threads, sizeof(*p));
1823         /* Partition the work amongst work threads. */
1824         for (i = 0; i < delta_search_threads; i++) {
1825                 unsigned sub_size = list_size / (delta_search_threads - i);
1827                 /* don't use too small segments or no deltas will be found */
1828                 if (sub_size < 2*window && i+1 < delta_search_threads)
1829                         sub_size = 0;
1831                 p[i].window = window;
1832                 p[i].depth = depth;
1833                 p[i].processed = processed;
1834                 p[i].working = 1;
1835                 p[i].data_ready = 0;
1837                 /* try to split chunks on "path" boundaries */
1838                 while (sub_size && sub_size < list_size &&
1839                        list[sub_size]->hash &&
1840                        list[sub_size]->hash == list[sub_size-1]->hash)
1841                         sub_size++;
1843                 p[i].list = list;
1844                 p[i].list_size = sub_size;
1845                 p[i].remaining = sub_size;
1847                 list += sub_size;
1848                 list_size -= sub_size;
1849         }
1851         /* Start work threads. */
1852         for (i = 0; i < delta_search_threads; i++) {
1853                 if (!p[i].list_size)
1854                         continue;
1855                 pthread_mutex_init(&p[i].mutex, NULL);
1856                 pthread_cond_init(&p[i].cond, NULL);
1857                 ret = pthread_create(&p[i].thread, NULL,
1858                                      threaded_find_deltas, &p[i]);
1859                 if (ret)
1860                         die("unable to create thread: %s", strerror(ret));
1861                 active_threads++;
1862         }
1864         /*
1865          * Now let's wait for work completion.  Each time a thread is done
1866          * with its work, we steal half of the remaining work from the
1867          * thread with the largest number of unprocessed objects and give
1868          * it to that newly idle thread.  This ensure good load balancing
1869          * until the remaining object list segments are simply too short
1870          * to be worth splitting anymore.
1871          */
1872         while (active_threads) {
1873                 struct thread_params *target = NULL;
1874                 struct thread_params *victim = NULL;
1875                 unsigned sub_size = 0;
1877                 progress_lock();
1878                 for (;;) {
1879                         for (i = 0; !target && i < delta_search_threads; i++)
1880                                 if (!p[i].working)
1881                                         target = &p[i];
1882                         if (target)
1883                                 break;
1884                         pthread_cond_wait(&progress_cond, &progress_mutex);
1885                 }
1887                 for (i = 0; i < delta_search_threads; i++)
1888                         if (p[i].remaining > 2*window &&
1889                             (!victim || victim->remaining < p[i].remaining))
1890                                 victim = &p[i];
1891                 if (victim) {
1892                         sub_size = victim->remaining / 2;
1893                         list = victim->list + victim->list_size - sub_size;
1894                         while (sub_size && list[0]->hash &&
1895                                list[0]->hash == list[-1]->hash) {
1896                                 list++;
1897                                 sub_size--;
1898                         }
1899                         if (!sub_size) {
1900                                 /*
1901                                  * It is possible for some "paths" to have
1902                                  * so many objects that no hash boundary
1903                                  * might be found.  Let's just steal the
1904                                  * exact half in that case.
1905                                  */
1906                                 sub_size = victim->remaining / 2;
1907                                 list -= sub_size;
1908                         }
1909                         target->list = list;
1910                         victim->list_size -= sub_size;
1911                         victim->remaining -= sub_size;
1912                 }
1913                 target->list_size = sub_size;
1914                 target->remaining = sub_size;
1915                 target->working = 1;
1916                 progress_unlock();
1918                 pthread_mutex_lock(&target->mutex);
1919                 target->data_ready = 1;
1920                 pthread_cond_signal(&target->cond);
1921                 pthread_mutex_unlock(&target->mutex);
1923                 if (!sub_size) {
1924                         pthread_join(target->thread, NULL);
1925                         pthread_cond_destroy(&target->cond);
1926                         pthread_mutex_destroy(&target->mutex);
1927                         active_threads--;
1928                 }
1929         }
1930         cleanup_threaded_search();
1931         free(p);
1934 #else
1935 #define ll_find_deltas(l, s, w, d, p)   find_deltas(l, &s, w, d, p)
1936 #endif
1938 static int add_ref_tag(const char *path, const unsigned char *sha1, int flag, void *cb_data)
1940         unsigned char peeled[20];
1942         if (!prefixcmp(path, "refs/tags/") && /* is a tag? */
1943             !peel_ref(path, peeled)        && /* peelable? */
1944             !is_null_sha1(peeled)          && /* annotated tag? */
1945             locate_object_entry(peeled))      /* object packed? */
1946                 add_object_entry(sha1, OBJ_TAG, NULL, 0);
1947         return 0;
1950 static void prepare_pack(int window, int depth)
1952         struct object_entry **delta_list;
1953         uint32_t i, nr_deltas;
1954         unsigned n;
1956         get_object_details();
1958         /*
1959          * If we're locally repacking then we need to be doubly careful
1960          * from now on in order to make sure no stealth corruption gets
1961          * propagated to the new pack.  Clients receiving streamed packs
1962          * should validate everything they get anyway so no need to incur
1963          * the additional cost here in that case.
1964          */
1965         if (!pack_to_stdout)
1966                 do_check_packed_object_crc = 1;
1968         if (!nr_objects || !window || !depth)
1969                 return;
1971         delta_list = xmalloc(nr_objects * sizeof(*delta_list));
1972         nr_deltas = n = 0;
1974         for (i = 0; i < nr_objects; i++) {
1975                 struct object_entry *entry = objects + i;
1977                 if (entry->delta)
1978                         /* This happens if we decided to reuse existing
1979                          * delta from a pack.  "reuse_delta &&" is implied.
1980                          */
1981                         continue;
1983                 if (entry->size < 50)
1984                         continue;
1986                 if (entry->no_try_delta)
1987                         continue;
1989                 if (!entry->preferred_base) {
1990                         nr_deltas++;
1991                         if (entry->type < 0)
1992                                 die("unable to get type of object %s",
1993                                     sha1_to_hex(entry->idx.sha1));
1994                 } else {
1995                         if (entry->type < 0) {
1996                                 /*
1997                                  * This object is not found, but we
1998                                  * don't have to include it anyway.
1999                                  */
2000                                 continue;
2001                         }
2002                 }
2004                 delta_list[n++] = entry;
2005         }
2007         if (nr_deltas && n > 1) {
2008                 unsigned nr_done = 0;
2009                 if (progress)
2010                         progress_state = start_progress("Compressing objects",
2011                                                         nr_deltas);
2012                 qsort(delta_list, n, sizeof(*delta_list), type_size_sort);
2013                 ll_find_deltas(delta_list, n, window+1, depth, &nr_done);
2014                 stop_progress(&progress_state);
2015                 if (nr_done != nr_deltas)
2016                         die("inconsistency with delta count");
2017         }
2018         free(delta_list);
2021 static int git_pack_config(const char *k, const char *v, void *cb)
2023         if (!strcmp(k, "pack.window")) {
2024                 window = git_config_int(k, v);
2025                 return 0;
2026         }
2027         if (!strcmp(k, "pack.windowmemory")) {
2028                 window_memory_limit = git_config_ulong(k, v);
2029                 return 0;
2030         }
2031         if (!strcmp(k, "pack.depth")) {
2032                 depth = git_config_int(k, v);
2033                 return 0;
2034         }
2035         if (!strcmp(k, "pack.compression")) {
2036                 int level = git_config_int(k, v);
2037                 if (level == -1)
2038                         level = Z_DEFAULT_COMPRESSION;
2039                 else if (level < 0 || level > Z_BEST_COMPRESSION)
2040                         die("bad pack compression level %d", level);
2041                 pack_compression_level = level;
2042                 pack_compression_seen = 1;
2043                 return 0;
2044         }
2045         if (!strcmp(k, "pack.deltacachesize")) {
2046                 max_delta_cache_size = git_config_int(k, v);
2047                 return 0;
2048         }
2049         if (!strcmp(k, "pack.deltacachelimit")) {
2050                 cache_max_small_delta_size = git_config_int(k, v);
2051                 return 0;
2052         }
2053         if (!strcmp(k, "pack.threads")) {
2054                 delta_search_threads = git_config_int(k, v);
2055                 if (delta_search_threads < 0)
2056                         die("invalid number of threads specified (%d)",
2057                             delta_search_threads);
2058 #ifdef NO_PTHREADS
2059                 if (delta_search_threads != 1)
2060                         warning("no threads support, ignoring %s", k);
2061 #endif
2062                 return 0;
2063         }
2064         if (!strcmp(k, "pack.indexversion")) {
2065                 pack_idx_opts.version = git_config_int(k, v);
2066                 if (pack_idx_opts.version > 2)
2067                         die("bad pack.indexversion=%"PRIu32,
2068                             pack_idx_opts.version);
2069                 return 0;
2070         }
2071         if (!strcmp(k, "pack.packsizelimit")) {
2072                 pack_size_limit_cfg = git_config_ulong(k, v);
2073                 return 0;
2074         }
2075         return git_default_config(k, v, cb);
2078 static void read_object_list_from_stdin(void)
2080         char line[40 + 1 + PATH_MAX + 2];
2081         unsigned char sha1[20];
2083         for (;;) {
2084                 if (!fgets(line, sizeof(line), stdin)) {
2085                         if (feof(stdin))
2086                                 break;
2087                         if (!ferror(stdin))
2088                                 die("fgets returned NULL, not EOF, not error!");
2089                         if (errno != EINTR)
2090                                 die_errno("fgets");
2091                         clearerr(stdin);
2092                         continue;
2093                 }
2094                 if (line[0] == '-') {
2095                         if (get_sha1_hex(line+1, sha1))
2096                                 die("expected edge sha1, got garbage:\n %s",
2097                                     line);
2098                         add_preferred_base(sha1);
2099                         continue;
2100                 }
2101                 if (get_sha1_hex(line, sha1))
2102                         die("expected sha1, got garbage:\n %s", line);
2104                 add_preferred_base_object(line+41);
2105                 add_object_entry(sha1, 0, line+41, 0);
2106         }
2109 #define OBJECT_ADDED (1u<<20)
2111 static void show_commit(struct commit *commit, void *data)
2113         add_object_entry(commit->object.sha1, OBJ_COMMIT, NULL, 0);
2114         commit->object.flags |= OBJECT_ADDED;
2117 static void show_object(struct object *obj, const struct name_path *path, const char *last)
2119         char *name = path_name(path, last);
2121         add_preferred_base_object(name);
2122         add_object_entry(obj->sha1, obj->type, name, 0);
2123         obj->flags |= OBJECT_ADDED;
2125         /*
2126          * We will have generated the hash from the name,
2127          * but not saved a pointer to it - we can free it
2128          */
2129         free((char *)name);
2132 static void show_edge(struct commit *commit)
2134         add_preferred_base(commit->object.sha1);
2137 struct in_pack_object {
2138         off_t offset;
2139         struct object *object;
2140 };
2142 struct in_pack {
2143         int alloc;
2144         int nr;
2145         struct in_pack_object *array;
2146 };
2148 static void mark_in_pack_object(struct object *object, struct packed_git *p, struct in_pack *in_pack)
2150         in_pack->array[in_pack->nr].offset = find_pack_entry_one(object->sha1, p);
2151         in_pack->array[in_pack->nr].object = object;
2152         in_pack->nr++;
2155 /*
2156  * Compare the objects in the offset order, in order to emulate the
2157  * "git rev-list --objects" output that produced the pack originally.
2158  */
2159 static int ofscmp(const void *a_, const void *b_)
2161         struct in_pack_object *a = (struct in_pack_object *)a_;
2162         struct in_pack_object *b = (struct in_pack_object *)b_;
2164         if (a->offset < b->offset)
2165                 return -1;
2166         else if (a->offset > b->offset)
2167                 return 1;
2168         else
2169                 return hashcmp(a->object->sha1, b->object->sha1);
2172 static void add_objects_in_unpacked_packs(struct rev_info *revs)
2174         struct packed_git *p;
2175         struct in_pack in_pack;
2176         uint32_t i;
2178         memset(&in_pack, 0, sizeof(in_pack));
2180         for (p = packed_git; p; p = p->next) {
2181                 const unsigned char *sha1;
2182                 struct object *o;
2184                 if (!p->pack_local || p->pack_keep)
2185                         continue;
2186                 if (open_pack_index(p))
2187                         die("cannot open pack index");
2189                 ALLOC_GROW(in_pack.array,
2190                            in_pack.nr + p->num_objects,
2191                            in_pack.alloc);
2193                 for (i = 0; i < p->num_objects; i++) {
2194                         sha1 = nth_packed_object_sha1(p, i);
2195                         o = lookup_unknown_object(sha1);
2196                         if (!(o->flags & OBJECT_ADDED))
2197                                 mark_in_pack_object(o, p, &in_pack);
2198                         o->flags |= OBJECT_ADDED;
2199                 }
2200         }
2202         if (in_pack.nr) {
2203                 qsort(in_pack.array, in_pack.nr, sizeof(in_pack.array[0]),
2204                       ofscmp);
2205                 for (i = 0; i < in_pack.nr; i++) {
2206                         struct object *o = in_pack.array[i].object;
2207                         add_object_entry(o->sha1, o->type, "", 0);
2208                 }
2209         }
2210         free(in_pack.array);
2213 static int has_sha1_pack_kept_or_nonlocal(const unsigned char *sha1)
2215         static struct packed_git *last_found = (void *)1;
2216         struct packed_git *p;
2218         p = (last_found != (void *)1) ? last_found : packed_git;
2220         while (p) {
2221                 if ((!p->pack_local || p->pack_keep) &&
2222                         find_pack_entry_one(sha1, p)) {
2223                         last_found = p;
2224                         return 1;
2225                 }
2226                 if (p == last_found)
2227                         p = packed_git;
2228                 else
2229                         p = p->next;
2230                 if (p == last_found)
2231                         p = p->next;
2232         }
2233         return 0;
2236 static void loosen_unused_packed_objects(struct rev_info *revs)
2238         struct packed_git *p;
2239         uint32_t i;
2240         const unsigned char *sha1;
2242         for (p = packed_git; p; p = p->next) {
2243                 if (!p->pack_local || p->pack_keep)
2244                         continue;
2246                 if (open_pack_index(p))
2247                         die("cannot open pack index");
2249                 for (i = 0; i < p->num_objects; i++) {
2250                         sha1 = nth_packed_object_sha1(p, i);
2251                         if (!locate_object_entry(sha1) &&
2252                                 !has_sha1_pack_kept_or_nonlocal(sha1))
2253                                 if (force_object_loose(sha1, p->mtime))
2254                                         die("unable to force loose object");
2255                 }
2256         }
2259 static void get_object_list(int ac, const char **av)
2261         struct rev_info revs;
2262         char line[1000];
2263         int flags = 0;
2265         init_revisions(&revs, NULL);
2266         save_commit_buffer = 0;
2267         setup_revisions(ac, av, &revs, NULL);
2269         while (fgets(line, sizeof(line), stdin) != NULL) {
2270                 int len = strlen(line);
2271                 if (len && line[len - 1] == '\n')
2272                         line[--len] = 0;
2273                 if (!len)
2274                         break;
2275                 if (*line == '-') {
2276                         if (!strcmp(line, "--not")) {
2277                                 flags ^= UNINTERESTING;
2278                                 continue;
2279                         }
2280                         die("not a rev '%s'", line);
2281                 }
2282                 if (handle_revision_arg(line, &revs, flags, 1))
2283                         die("bad revision '%s'", line);
2284         }
2286         if (prepare_revision_walk(&revs))
2287                 die("revision walk setup failed");
2288         mark_edges_uninteresting(revs.commits, &revs, show_edge);
2289         traverse_commit_list(&revs, show_commit, show_object, NULL);
2291         if (keep_unreachable)
2292                 add_objects_in_unpacked_packs(&revs);
2293         if (unpack_unreachable)
2294                 loosen_unused_packed_objects(&revs);
2297 int cmd_pack_objects(int argc, const char **argv, const char *prefix)
2299         int use_internal_rev_list = 0;
2300         int thin = 0;
2301         int all_progress_implied = 0;
2302         uint32_t i;
2303         const char **rp_av;
2304         int rp_ac_alloc = 64;
2305         int rp_ac;
2307         read_replace_refs = 0;
2309         rp_av = xcalloc(rp_ac_alloc, sizeof(*rp_av));
2311         rp_av[0] = "pack-objects";
2312         rp_av[1] = "--objects"; /* --thin will make it --objects-edge */
2313         rp_ac = 2;
2315         reset_pack_idx_option(&pack_idx_opts);
2316         git_config(git_pack_config, NULL);
2317         if (!pack_compression_seen && core_compression_seen)
2318                 pack_compression_level = core_compression_level;
2320         progress = isatty(2);
2321         for (i = 1; i < argc; i++) {
2322                 const char *arg = argv[i];
2324                 if (*arg != '-')
2325                         break;
2327                 if (!strcmp("--non-empty", arg)) {
2328                         non_empty = 1;
2329                         continue;
2330                 }
2331                 if (!strcmp("--local", arg)) {
2332                         local = 1;
2333                         continue;
2334                 }
2335                 if (!strcmp("--incremental", arg)) {
2336                         incremental = 1;
2337                         continue;
2338                 }
2339                 if (!strcmp("--honor-pack-keep", arg)) {
2340                         ignore_packed_keep = 1;
2341                         continue;
2342                 }
2343                 if (!prefixcmp(arg, "--compression=")) {
2344                         char *end;
2345                         int level = strtoul(arg+14, &end, 0);
2346                         if (!arg[14] || *end)
2347                                 usage(pack_usage);
2348                         if (level == -1)
2349                                 level = Z_DEFAULT_COMPRESSION;
2350                         else if (level < 0 || level > Z_BEST_COMPRESSION)
2351                                 die("bad pack compression level %d", level);
2352                         pack_compression_level = level;
2353                         continue;
2354                 }
2355                 if (!prefixcmp(arg, "--max-pack-size=")) {
2356                         pack_size_limit_cfg = 0;
2357                         if (!git_parse_ulong(arg+16, &pack_size_limit))
2358                                 usage(pack_usage);
2359                         continue;
2360                 }
2361                 if (!prefixcmp(arg, "--window=")) {
2362                         char *end;
2363                         window = strtoul(arg+9, &end, 0);
2364                         if (!arg[9] || *end)
2365                                 usage(pack_usage);
2366                         continue;
2367                 }
2368                 if (!prefixcmp(arg, "--window-memory=")) {
2369                         if (!git_parse_ulong(arg+16, &window_memory_limit))
2370                                 usage(pack_usage);
2371                         continue;
2372                 }
2373                 if (!prefixcmp(arg, "--threads=")) {
2374                         char *end;
2375                         delta_search_threads = strtoul(arg+10, &end, 0);
2376                         if (!arg[10] || *end || delta_search_threads < 0)
2377                                 usage(pack_usage);
2378 #ifdef NO_PTHREADS
2379                         if (delta_search_threads != 1)
2380                                 warning("no threads support, "
2381                                         "ignoring %s", arg);
2382 #endif
2383                         continue;
2384                 }
2385                 if (!prefixcmp(arg, "--depth=")) {
2386                         char *end;
2387                         depth = strtoul(arg+8, &end, 0);
2388                         if (!arg[8] || *end)
2389                                 usage(pack_usage);
2390                         continue;
2391                 }
2392                 if (!strcmp("--progress", arg)) {
2393                         progress = 1;
2394                         continue;
2395                 }
2396                 if (!strcmp("--all-progress", arg)) {
2397                         progress = 2;
2398                         continue;
2399                 }
2400                 if (!strcmp("--all-progress-implied", arg)) {
2401                         all_progress_implied = 1;
2402                         continue;
2403                 }
2404                 if (!strcmp("-q", arg)) {
2405                         progress = 0;
2406                         continue;
2407                 }
2408                 if (!strcmp("--no-reuse-delta", arg)) {
2409                         reuse_delta = 0;
2410                         continue;
2411                 }
2412                 if (!strcmp("--no-reuse-object", arg)) {
2413                         reuse_object = reuse_delta = 0;
2414                         continue;
2415                 }
2416                 if (!strcmp("--delta-base-offset", arg)) {
2417                         allow_ofs_delta = 1;
2418                         continue;
2419                 }
2420                 if (!strcmp("--stdout", arg)) {
2421                         pack_to_stdout = 1;
2422                         continue;
2423                 }
2424                 if (!strcmp("--revs", arg)) {
2425                         use_internal_rev_list = 1;
2426                         continue;
2427                 }
2428                 if (!strcmp("--keep-unreachable", arg)) {
2429                         keep_unreachable = 1;
2430                         continue;
2431                 }
2432                 if (!strcmp("--unpack-unreachable", arg)) {
2433                         unpack_unreachable = 1;
2434                         continue;
2435                 }
2436                 if (!strcmp("--include-tag", arg)) {
2437                         include_tag = 1;
2438                         continue;
2439                 }
2440                 if (!strcmp("--unpacked", arg) ||
2441                     !strcmp("--reflog", arg) ||
2442                     !strcmp("--all", arg)) {
2443                         use_internal_rev_list = 1;
2444                         if (rp_ac >= rp_ac_alloc - 1) {
2445                                 rp_ac_alloc = alloc_nr(rp_ac_alloc);
2446                                 rp_av = xrealloc(rp_av,
2447                                                  rp_ac_alloc * sizeof(*rp_av));
2448                         }
2449                         rp_av[rp_ac++] = arg;
2450                         continue;
2451                 }
2452                 if (!strcmp("--thin", arg)) {
2453                         use_internal_rev_list = 1;
2454                         thin = 1;
2455                         rp_av[1] = "--objects-edge";
2456                         continue;
2457                 }
2458                 if (!prefixcmp(arg, "--index-version=")) {
2459                         char *c;
2460                         pack_idx_opts.version = strtoul(arg + 16, &c, 10);
2461                         if (pack_idx_opts.version > 2)
2462                                 die("bad %s", arg);
2463                         if (*c == ',')
2464                                 pack_idx_opts.off32_limit = strtoul(c+1, &c, 0);
2465                         if (*c || pack_idx_opts.off32_limit & 0x80000000)
2466                                 die("bad %s", arg);
2467                         continue;
2468                 }
2469                 if (!strcmp(arg, "--keep-true-parents")) {
2470                         grafts_replace_parents = 0;
2471                         continue;
2472                 }
2473                 usage(pack_usage);
2474         }
2476         /* Traditionally "pack-objects [options] base extra" failed;
2477          * we would however want to take refs parameter that would
2478          * have been given to upstream rev-list ourselves, which means
2479          * we somehow want to say what the base name is.  So the
2480          * syntax would be:
2481          *
2482          * pack-objects [options] base <refs...>
2483          *
2484          * in other words, we would treat the first non-option as the
2485          * base_name and send everything else to the internal revision
2486          * walker.
2487          */
2489         if (!pack_to_stdout)
2490                 base_name = argv[i++];
2492         if (pack_to_stdout != !base_name)
2493                 usage(pack_usage);
2495         if (!pack_to_stdout && !pack_size_limit)
2496                 pack_size_limit = pack_size_limit_cfg;
2497         if (pack_to_stdout && pack_size_limit)
2498                 die("--max-pack-size cannot be used to build a pack for transfer.");
2499         if (pack_size_limit && pack_size_limit < 1024*1024) {
2500                 warning("minimum pack size limit is 1 MiB");
2501                 pack_size_limit = 1024*1024;
2502         }
2504         if (!pack_to_stdout && thin)
2505                 die("--thin cannot be used to build an indexable pack.");
2507         if (keep_unreachable && unpack_unreachable)
2508                 die("--keep-unreachable and --unpack-unreachable are incompatible.");
2510         if (progress && all_progress_implied)
2511                 progress = 2;
2513         prepare_packed_git();
2515         if (progress)
2516                 progress_state = start_progress("Counting objects", 0);
2517         if (!use_internal_rev_list)
2518                 read_object_list_from_stdin();
2519         else {
2520                 rp_av[rp_ac] = NULL;
2521                 get_object_list(rp_ac, rp_av);
2522         }
2523         cleanup_preferred_base();
2524         if (include_tag && nr_result)
2525                 for_each_ref(add_ref_tag, NULL);
2526         stop_progress(&progress_state);
2528         if (non_empty && !nr_result)
2529                 return 0;
2530         if (nr_result)
2531                 prepare_pack(window, depth);
2532         write_pack_file();
2533         if (progress)
2534                 fprintf(stderr, "Total %"PRIu32" (delta %"PRIu32"),"
2535                         " reused %"PRIu32" (delta %"PRIu32")\n",
2536                         written, written_delta, reused, reused_delta);
2537         return 0;