make struct progress an opaque type
[git/fastimport.git] / builtin-pack-objects.c
blob3ca5cc780088a7076f46cff7f968cf45764de1ec
1 #include "builtin.h"
2 #include "cache.h"
3 #include "attr.h"
4 #include "object.h"
5 #include "blob.h"
6 #include "commit.h"
7 #include "tag.h"
8 #include "tree.h"
9 #include "delta.h"
10 #include "pack.h"
11 #include "csum-file.h"
12 #include "tree-walk.h"
13 #include "diff.h"
14 #include "revision.h"
15 #include "list-objects.h"
16 #include "progress.h"
18 #ifdef THREADED_DELTA_SEARCH
19 #include <pthread.h>
20 #endif
22 static const char pack_usage[] = "\
23 git-pack-objects [{ -q | --progress | --all-progress }] \n\
24 [--max-pack-size=N] [--local] [--incremental] \n\
25 [--window=N] [--window-memory=N] [--depth=N] \n\
26 [--no-reuse-delta] [--no-reuse-object] [--delta-base-offset] \n\
27 [--threads=N] [--non-empty] [--revs [--unpacked | --all]*] [--reflog] \n\
28 [--stdout | base-name] [--keep-unreachable] [<ref-list | <object-list]";
30 struct object_entry {
31 struct pack_idx_entry idx;
32 unsigned long size; /* uncompressed size */
33 struct packed_git *in_pack; /* already in pack */
34 off_t in_pack_offset;
35 struct object_entry *delta; /* delta base object */
36 struct object_entry *delta_child; /* deltified objects who bases me */
37 struct object_entry *delta_sibling; /* other deltified objects who
38 * uses the same base as me
40 void *delta_data; /* cached delta (uncompressed) */
41 unsigned long delta_size; /* delta data size (uncompressed) */
42 unsigned int hash; /* name hint hash */
43 enum object_type type;
44 enum object_type in_pack_type; /* could be delta */
45 unsigned char in_pack_header_size;
46 unsigned char preferred_base; /* we do not pack this, but is available
47 * to be used as the base object to delta
48 * objects against.
50 unsigned char no_try_delta;
54 * Objects we are going to pack are collected in objects array (dynamically
55 * expanded). nr_objects & nr_alloc controls this array. They are stored
56 * in the order we see -- typically rev-list --objects order that gives us
57 * nice "minimum seek" order.
59 static struct object_entry *objects;
60 static struct object_entry **written_list;
61 static uint32_t nr_objects, nr_alloc, nr_result, nr_written;
63 static int non_empty;
64 static int no_reuse_delta, no_reuse_object, keep_unreachable;
65 static int local;
66 static int incremental;
67 static int allow_ofs_delta;
68 static const char *base_name;
69 static int progress = 1;
70 static int window = 10;
71 static uint32_t pack_size_limit;
72 static int depth = 50;
73 static int delta_search_threads = 1;
74 static int pack_to_stdout;
75 static int num_preferred_base;
76 static struct progress *progress_state;
77 static int pack_compression_level = Z_DEFAULT_COMPRESSION;
78 static int pack_compression_seen;
80 static unsigned long delta_cache_size = 0;
81 static unsigned long max_delta_cache_size = 0;
82 static unsigned long cache_max_small_delta_size = 1000;
84 static unsigned long window_memory_limit = 0;
87 * The object names in objects array are hashed with this hashtable,
88 * to help looking up the entry by object name.
89 * This hashtable is built after all the objects are seen.
91 static int *object_ix;
92 static int object_ix_hashsz;
95 * Pack index for existing packs give us easy access to the offsets into
96 * corresponding pack file where each object's data starts, but the entries
97 * do not store the size of the compressed representation (uncompressed
98 * size is easily available by examining the pack entry header). It is
99 * also rather expensive to find the sha1 for an object given its offset.
101 * We build a hashtable of existing packs (pack_revindex), and keep reverse
102 * index here -- pack index file is sorted by object name mapping to offset;
103 * this pack_revindex[].revindex array is a list of offset/index_nr pairs
104 * ordered by offset, so if you know the offset of an object, next offset
105 * is where its packed representation ends and the index_nr can be used to
106 * get the object sha1 from the main index.
108 struct revindex_entry {
109 off_t offset;
110 unsigned int nr;
112 struct pack_revindex {
113 struct packed_git *p;
114 struct revindex_entry *revindex;
116 static struct pack_revindex *pack_revindex;
117 static int pack_revindex_hashsz;
120 * stats
122 static uint32_t written, written_delta;
123 static uint32_t reused, reused_delta;
125 static int pack_revindex_ix(struct packed_git *p)
127 unsigned long ui = (unsigned long)p;
128 int i;
130 ui = ui ^ (ui >> 16); /* defeat structure alignment */
131 i = (int)(ui % pack_revindex_hashsz);
132 while (pack_revindex[i].p) {
133 if (pack_revindex[i].p == p)
134 return i;
135 if (++i == pack_revindex_hashsz)
136 i = 0;
138 return -1 - i;
141 static void prepare_pack_ix(void)
143 int num;
144 struct packed_git *p;
145 for (num = 0, p = packed_git; p; p = p->next)
146 num++;
147 if (!num)
148 return;
149 pack_revindex_hashsz = num * 11;
150 pack_revindex = xcalloc(sizeof(*pack_revindex), pack_revindex_hashsz);
151 for (p = packed_git; p; p = p->next) {
152 num = pack_revindex_ix(p);
153 num = - 1 - num;
154 pack_revindex[num].p = p;
156 /* revindex elements are lazily initialized */
159 static int cmp_offset(const void *a_, const void *b_)
161 const struct revindex_entry *a = a_;
162 const struct revindex_entry *b = b_;
163 return (a->offset < b->offset) ? -1 : (a->offset > b->offset) ? 1 : 0;
167 * Ordered list of offsets of objects in the pack.
169 static void prepare_pack_revindex(struct pack_revindex *rix)
171 struct packed_git *p = rix->p;
172 int num_ent = p->num_objects;
173 int i;
174 const char *index = p->index_data;
176 rix->revindex = xmalloc(sizeof(*rix->revindex) * (num_ent + 1));
177 index += 4 * 256;
179 if (p->index_version > 1) {
180 const uint32_t *off_32 =
181 (uint32_t *)(index + 8 + p->num_objects * (20 + 4));
182 const uint32_t *off_64 = off_32 + p->num_objects;
183 for (i = 0; i < num_ent; i++) {
184 uint32_t off = ntohl(*off_32++);
185 if (!(off & 0x80000000)) {
186 rix->revindex[i].offset = off;
187 } else {
188 rix->revindex[i].offset =
189 ((uint64_t)ntohl(*off_64++)) << 32;
190 rix->revindex[i].offset |=
191 ntohl(*off_64++);
193 rix->revindex[i].nr = i;
195 } else {
196 for (i = 0; i < num_ent; i++) {
197 uint32_t hl = *((uint32_t *)(index + 24 * i));
198 rix->revindex[i].offset = ntohl(hl);
199 rix->revindex[i].nr = i;
203 /* This knows the pack format -- the 20-byte trailer
204 * follows immediately after the last object data.
206 rix->revindex[num_ent].offset = p->pack_size - 20;
207 rix->revindex[num_ent].nr = -1;
208 qsort(rix->revindex, num_ent, sizeof(*rix->revindex), cmp_offset);
211 static struct revindex_entry * find_packed_object(struct packed_git *p,
212 off_t ofs)
214 int num;
215 int lo, hi;
216 struct pack_revindex *rix;
217 struct revindex_entry *revindex;
218 num = pack_revindex_ix(p);
219 if (num < 0)
220 die("internal error: pack revindex uninitialized");
221 rix = &pack_revindex[num];
222 if (!rix->revindex)
223 prepare_pack_revindex(rix);
224 revindex = rix->revindex;
225 lo = 0;
226 hi = p->num_objects + 1;
227 do {
228 int mi = (lo + hi) / 2;
229 if (revindex[mi].offset == ofs) {
230 return revindex + mi;
232 else if (ofs < revindex[mi].offset)
233 hi = mi;
234 else
235 lo = mi + 1;
236 } while (lo < hi);
237 die("internal error: pack revindex corrupt");
240 static const unsigned char *find_packed_object_name(struct packed_git *p,
241 off_t ofs)
243 struct revindex_entry *entry = find_packed_object(p, ofs);
244 return nth_packed_object_sha1(p, entry->nr);
247 static void *delta_against(void *buf, unsigned long size, struct object_entry *entry)
249 unsigned long othersize, delta_size;
250 enum object_type type;
251 void *otherbuf = read_sha1_file(entry->delta->idx.sha1, &type, &othersize);
252 void *delta_buf;
254 if (!otherbuf)
255 die("unable to read %s", sha1_to_hex(entry->delta->idx.sha1));
256 delta_buf = diff_delta(otherbuf, othersize,
257 buf, size, &delta_size, 0);
258 if (!delta_buf || delta_size != entry->delta_size)
259 die("delta size changed");
260 free(buf);
261 free(otherbuf);
262 return delta_buf;
266 * The per-object header is a pretty dense thing, which is
267 * - first byte: low four bits are "size", then three bits of "type",
268 * and the high bit is "size continues".
269 * - each byte afterwards: low seven bits are size continuation,
270 * with the high bit being "size continues"
272 static int encode_header(enum object_type type, unsigned long size, unsigned char *hdr)
274 int n = 1;
275 unsigned char c;
277 if (type < OBJ_COMMIT || type > OBJ_REF_DELTA)
278 die("bad type %d", type);
280 c = (type << 4) | (size & 15);
281 size >>= 4;
282 while (size) {
283 *hdr++ = c | 0x80;
284 c = size & 0x7f;
285 size >>= 7;
286 n++;
288 *hdr = c;
289 return n;
293 * we are going to reuse the existing object data as is. make
294 * sure it is not corrupt.
296 static int check_pack_inflate(struct packed_git *p,
297 struct pack_window **w_curs,
298 off_t offset,
299 off_t len,
300 unsigned long expect)
302 z_stream stream;
303 unsigned char fakebuf[4096], *in;
304 int st;
306 memset(&stream, 0, sizeof(stream));
307 inflateInit(&stream);
308 do {
309 in = use_pack(p, w_curs, offset, &stream.avail_in);
310 stream.next_in = in;
311 stream.next_out = fakebuf;
312 stream.avail_out = sizeof(fakebuf);
313 st = inflate(&stream, Z_FINISH);
314 offset += stream.next_in - in;
315 } while (st == Z_OK || st == Z_BUF_ERROR);
316 inflateEnd(&stream);
317 return (st == Z_STREAM_END &&
318 stream.total_out == expect &&
319 stream.total_in == len) ? 0 : -1;
322 static int check_pack_crc(struct packed_git *p, struct pack_window **w_curs,
323 off_t offset, off_t len, unsigned int nr)
325 const uint32_t *index_crc;
326 uint32_t data_crc = crc32(0, Z_NULL, 0);
328 do {
329 unsigned int avail;
330 void *data = use_pack(p, w_curs, offset, &avail);
331 if (avail > len)
332 avail = len;
333 data_crc = crc32(data_crc, data, avail);
334 offset += avail;
335 len -= avail;
336 } while (len);
338 index_crc = p->index_data;
339 index_crc += 2 + 256 + p->num_objects * (20/4) + nr;
341 return data_crc != ntohl(*index_crc);
344 static void copy_pack_data(struct sha1file *f,
345 struct packed_git *p,
346 struct pack_window **w_curs,
347 off_t offset,
348 off_t len)
350 unsigned char *in;
351 unsigned int avail;
353 while (len) {
354 in = use_pack(p, w_curs, offset, &avail);
355 if (avail > len)
356 avail = (unsigned int)len;
357 sha1write(f, in, avail);
358 offset += avail;
359 len -= avail;
363 static unsigned long write_object(struct sha1file *f,
364 struct object_entry *entry,
365 off_t write_offset)
367 unsigned long size;
368 enum object_type type;
369 void *buf;
370 unsigned char header[10];
371 unsigned char dheader[10];
372 unsigned hdrlen;
373 off_t datalen;
374 enum object_type obj_type;
375 int to_reuse = 0;
376 /* write limit if limited packsize and not first object */
377 unsigned long limit = pack_size_limit && nr_written ?
378 pack_size_limit - write_offset : 0;
379 /* no if no delta */
380 int usable_delta = !entry->delta ? 0 :
381 /* yes if unlimited packfile */
382 !pack_size_limit ? 1 :
383 /* no if base written to previous pack */
384 entry->delta->idx.offset == (off_t)-1 ? 0 :
385 /* otherwise double-check written to this
386 * pack, like we do below
388 entry->delta->idx.offset ? 1 : 0;
390 if (!pack_to_stdout)
391 crc32_begin(f);
393 obj_type = entry->type;
394 if (no_reuse_object)
395 to_reuse = 0; /* explicit */
396 else if (!entry->in_pack)
397 to_reuse = 0; /* can't reuse what we don't have */
398 else if (obj_type == OBJ_REF_DELTA || obj_type == OBJ_OFS_DELTA)
399 /* check_object() decided it for us ... */
400 to_reuse = usable_delta;
401 /* ... but pack split may override that */
402 else if (obj_type != entry->in_pack_type)
403 to_reuse = 0; /* pack has delta which is unusable */
404 else if (entry->delta)
405 to_reuse = 0; /* we want to pack afresh */
406 else
407 to_reuse = 1; /* we have it in-pack undeltified,
408 * and we do not need to deltify it.
411 if (!to_reuse) {
412 z_stream stream;
413 unsigned long maxsize;
414 void *out;
415 if (!usable_delta) {
416 buf = read_sha1_file(entry->idx.sha1, &obj_type, &size);
417 if (!buf)
418 die("unable to read %s", sha1_to_hex(entry->idx.sha1));
419 } else if (entry->delta_data) {
420 size = entry->delta_size;
421 buf = entry->delta_data;
422 entry->delta_data = NULL;
423 obj_type = (allow_ofs_delta && entry->delta->idx.offset) ?
424 OBJ_OFS_DELTA : OBJ_REF_DELTA;
425 } else {
426 buf = read_sha1_file(entry->idx.sha1, &type, &size);
427 if (!buf)
428 die("unable to read %s", sha1_to_hex(entry->idx.sha1));
429 buf = delta_against(buf, size, entry);
430 size = entry->delta_size;
431 obj_type = (allow_ofs_delta && entry->delta->idx.offset) ?
432 OBJ_OFS_DELTA : OBJ_REF_DELTA;
434 /* compress the data to store and put compressed length in datalen */
435 memset(&stream, 0, sizeof(stream));
436 deflateInit(&stream, pack_compression_level);
437 maxsize = deflateBound(&stream, size);
438 out = xmalloc(maxsize);
439 /* Compress it */
440 stream.next_in = buf;
441 stream.avail_in = size;
442 stream.next_out = out;
443 stream.avail_out = maxsize;
444 while (deflate(&stream, Z_FINISH) == Z_OK)
445 /* nothing */;
446 deflateEnd(&stream);
447 datalen = stream.total_out;
448 deflateEnd(&stream);
450 * The object header is a byte of 'type' followed by zero or
451 * more bytes of length.
453 hdrlen = encode_header(obj_type, size, header);
455 if (obj_type == OBJ_OFS_DELTA) {
457 * Deltas with relative base contain an additional
458 * encoding of the relative offset for the delta
459 * base from this object's position in the pack.
461 off_t ofs = entry->idx.offset - entry->delta->idx.offset;
462 unsigned pos = sizeof(dheader) - 1;
463 dheader[pos] = ofs & 127;
464 while (ofs >>= 7)
465 dheader[--pos] = 128 | (--ofs & 127);
466 if (limit && hdrlen + sizeof(dheader) - pos + datalen + 20 >= limit) {
467 free(out);
468 free(buf);
469 return 0;
471 sha1write(f, header, hdrlen);
472 sha1write(f, dheader + pos, sizeof(dheader) - pos);
473 hdrlen += sizeof(dheader) - pos;
474 } else if (obj_type == OBJ_REF_DELTA) {
476 * Deltas with a base reference contain
477 * an additional 20 bytes for the base sha1.
479 if (limit && hdrlen + 20 + datalen + 20 >= limit) {
480 free(out);
481 free(buf);
482 return 0;
484 sha1write(f, header, hdrlen);
485 sha1write(f, entry->delta->idx.sha1, 20);
486 hdrlen += 20;
487 } else {
488 if (limit && hdrlen + datalen + 20 >= limit) {
489 free(out);
490 free(buf);
491 return 0;
493 sha1write(f, header, hdrlen);
495 sha1write(f, out, datalen);
496 free(out);
497 free(buf);
499 else {
500 struct packed_git *p = entry->in_pack;
501 struct pack_window *w_curs = NULL;
502 struct revindex_entry *revidx;
503 off_t offset;
505 if (entry->delta) {
506 obj_type = (allow_ofs_delta && entry->delta->idx.offset) ?
507 OBJ_OFS_DELTA : OBJ_REF_DELTA;
508 reused_delta++;
510 hdrlen = encode_header(obj_type, entry->size, header);
511 offset = entry->in_pack_offset;
512 revidx = find_packed_object(p, offset);
513 datalen = revidx[1].offset - offset;
514 if (!pack_to_stdout && p->index_version > 1 &&
515 check_pack_crc(p, &w_curs, offset, datalen, revidx->nr))
516 die("bad packed object CRC for %s", sha1_to_hex(entry->idx.sha1));
517 offset += entry->in_pack_header_size;
518 datalen -= entry->in_pack_header_size;
519 if (obj_type == OBJ_OFS_DELTA) {
520 off_t ofs = entry->idx.offset - entry->delta->idx.offset;
521 unsigned pos = sizeof(dheader) - 1;
522 dheader[pos] = ofs & 127;
523 while (ofs >>= 7)
524 dheader[--pos] = 128 | (--ofs & 127);
525 if (limit && hdrlen + sizeof(dheader) - pos + datalen + 20 >= limit)
526 return 0;
527 sha1write(f, header, hdrlen);
528 sha1write(f, dheader + pos, sizeof(dheader) - pos);
529 hdrlen += sizeof(dheader) - pos;
530 } else if (obj_type == OBJ_REF_DELTA) {
531 if (limit && hdrlen + 20 + datalen + 20 >= limit)
532 return 0;
533 sha1write(f, header, hdrlen);
534 sha1write(f, entry->delta->idx.sha1, 20);
535 hdrlen += 20;
536 } else {
537 if (limit && hdrlen + datalen + 20 >= limit)
538 return 0;
539 sha1write(f, header, hdrlen);
542 if (!pack_to_stdout && p->index_version == 1 &&
543 check_pack_inflate(p, &w_curs, offset, datalen, entry->size))
544 die("corrupt packed object for %s", sha1_to_hex(entry->idx.sha1));
545 copy_pack_data(f, p, &w_curs, offset, datalen);
546 unuse_pack(&w_curs);
547 reused++;
549 if (usable_delta)
550 written_delta++;
551 written++;
552 if (!pack_to_stdout)
553 entry->idx.crc32 = crc32_end(f);
554 return hdrlen + datalen;
557 static off_t write_one(struct sha1file *f,
558 struct object_entry *e,
559 off_t offset)
561 unsigned long size;
563 /* offset is non zero if object is written already. */
564 if (e->idx.offset || e->preferred_base)
565 return offset;
567 /* if we are deltified, write out base object first. */
568 if (e->delta) {
569 offset = write_one(f, e->delta, offset);
570 if (!offset)
571 return 0;
574 e->idx.offset = offset;
575 size = write_object(f, e, offset);
576 if (!size) {
577 e->idx.offset = 0;
578 return 0;
580 written_list[nr_written++] = e;
582 /* make sure off_t is sufficiently large not to wrap */
583 if (offset > offset + size)
584 die("pack too large for current definition of off_t");
585 return offset + size;
588 /* forward declaration for write_pack_file */
589 static int adjust_perm(const char *path, mode_t mode);
591 static void write_pack_file(void)
593 uint32_t i = 0, j;
594 struct sha1file *f;
595 off_t offset, offset_one, last_obj_offset = 0;
596 struct pack_header hdr;
597 int do_progress = progress >> pack_to_stdout;
598 uint32_t nr_remaining = nr_result;
600 if (do_progress)
601 progress_state = start_progress("Writing objects", nr_result);
602 written_list = xmalloc(nr_objects * sizeof(struct object_entry *));
604 do {
605 unsigned char sha1[20];
606 char *pack_tmp_name = NULL;
608 if (pack_to_stdout) {
609 f = sha1fd(1, "<stdout>");
610 } else {
611 char tmpname[PATH_MAX];
612 int fd;
613 snprintf(tmpname, sizeof(tmpname),
614 "%s/tmp_pack_XXXXXX", get_object_directory());
615 fd = xmkstemp(tmpname);
616 pack_tmp_name = xstrdup(tmpname);
617 f = sha1fd(fd, pack_tmp_name);
620 hdr.hdr_signature = htonl(PACK_SIGNATURE);
621 hdr.hdr_version = htonl(PACK_VERSION);
622 hdr.hdr_entries = htonl(nr_remaining);
623 sha1write(f, &hdr, sizeof(hdr));
624 offset = sizeof(hdr);
625 nr_written = 0;
626 for (; i < nr_objects; i++) {
627 last_obj_offset = offset;
628 offset_one = write_one(f, objects + i, offset);
629 if (!offset_one)
630 break;
631 offset = offset_one;
632 if (do_progress)
633 display_progress(progress_state, written);
637 * Did we write the wrong # entries in the header?
638 * If so, rewrite it like in fast-import
640 if (pack_to_stdout || nr_written == nr_remaining) {
641 sha1close(f, sha1, 1);
642 } else {
643 int fd = sha1close(f, NULL, 0);
644 fixup_pack_header_footer(fd, sha1, pack_tmp_name, nr_written);
645 close(fd);
648 if (!pack_to_stdout) {
649 mode_t mode = umask(0);
650 char *idx_tmp_name, tmpname[PATH_MAX];
652 umask(mode);
653 mode = 0444 & ~mode;
655 idx_tmp_name = write_idx_file(NULL,
656 (struct pack_idx_entry **) written_list,
657 nr_written, sha1);
658 snprintf(tmpname, sizeof(tmpname), "%s-%s.pack",
659 base_name, sha1_to_hex(sha1));
660 if (adjust_perm(pack_tmp_name, mode))
661 die("unable to make temporary pack file readable: %s",
662 strerror(errno));
663 if (rename(pack_tmp_name, tmpname))
664 die("unable to rename temporary pack file: %s",
665 strerror(errno));
666 snprintf(tmpname, sizeof(tmpname), "%s-%s.idx",
667 base_name, sha1_to_hex(sha1));
668 if (adjust_perm(idx_tmp_name, mode))
669 die("unable to make temporary index file readable: %s",
670 strerror(errno));
671 if (rename(idx_tmp_name, tmpname))
672 die("unable to rename temporary index file: %s",
673 strerror(errno));
674 free(idx_tmp_name);
675 free(pack_tmp_name);
676 puts(sha1_to_hex(sha1));
679 /* mark written objects as written to previous pack */
680 for (j = 0; j < nr_written; j++) {
681 written_list[j]->idx.offset = (off_t)-1;
683 nr_remaining -= nr_written;
684 } while (nr_remaining && i < nr_objects);
686 free(written_list);
687 if (do_progress)
688 stop_progress(&progress_state);
689 if (written != nr_result)
690 die("wrote %u objects while expecting %u", written, nr_result);
692 * We have scanned through [0 ... i). Since we have written
693 * the correct number of objects, the remaining [i ... nr_objects)
694 * items must be either already written (due to out-of-order delta base)
695 * or a preferred base. Count those which are neither and complain if any.
697 for (j = 0; i < nr_objects; i++) {
698 struct object_entry *e = objects + i;
699 j += !e->idx.offset && !e->preferred_base;
701 if (j)
702 die("wrote %u objects as expected but %u unwritten", written, j);
705 static int locate_object_entry_hash(const unsigned char *sha1)
707 int i;
708 unsigned int ui;
709 memcpy(&ui, sha1, sizeof(unsigned int));
710 i = ui % object_ix_hashsz;
711 while (0 < object_ix[i]) {
712 if (!hashcmp(sha1, objects[object_ix[i] - 1].idx.sha1))
713 return i;
714 if (++i == object_ix_hashsz)
715 i = 0;
717 return -1 - i;
720 static struct object_entry *locate_object_entry(const unsigned char *sha1)
722 int i;
724 if (!object_ix_hashsz)
725 return NULL;
727 i = locate_object_entry_hash(sha1);
728 if (0 <= i)
729 return &objects[object_ix[i]-1];
730 return NULL;
733 static void rehash_objects(void)
735 uint32_t i;
736 struct object_entry *oe;
738 object_ix_hashsz = nr_objects * 3;
739 if (object_ix_hashsz < 1024)
740 object_ix_hashsz = 1024;
741 object_ix = xrealloc(object_ix, sizeof(int) * object_ix_hashsz);
742 memset(object_ix, 0, sizeof(int) * object_ix_hashsz);
743 for (i = 0, oe = objects; i < nr_objects; i++, oe++) {
744 int ix = locate_object_entry_hash(oe->idx.sha1);
745 if (0 <= ix)
746 continue;
747 ix = -1 - ix;
748 object_ix[ix] = i + 1;
752 static unsigned name_hash(const char *name)
754 unsigned char c;
755 unsigned hash = 0;
757 if (!name)
758 return 0;
761 * This effectively just creates a sortable number from the
762 * last sixteen non-whitespace characters. Last characters
763 * count "most", so things that end in ".c" sort together.
765 while ((c = *name++) != 0) {
766 if (isspace(c))
767 continue;
768 hash = (hash >> 2) + (c << 24);
770 return hash;
773 static void setup_delta_attr_check(struct git_attr_check *check)
775 static struct git_attr *attr_delta;
777 if (!attr_delta)
778 attr_delta = git_attr("delta", 5);
780 check[0].attr = attr_delta;
783 static int no_try_delta(const char *path)
785 struct git_attr_check check[1];
787 setup_delta_attr_check(check);
788 if (git_checkattr(path, ARRAY_SIZE(check), check))
789 return 0;
790 if (ATTR_FALSE(check->value))
791 return 1;
792 return 0;
795 static int add_object_entry(const unsigned char *sha1, enum object_type type,
796 const char *name, int exclude)
798 struct object_entry *entry;
799 struct packed_git *p, *found_pack = NULL;
800 off_t found_offset = 0;
801 int ix;
802 unsigned hash = name_hash(name);
804 ix = nr_objects ? locate_object_entry_hash(sha1) : -1;
805 if (ix >= 0) {
806 if (exclude) {
807 entry = objects + object_ix[ix] - 1;
808 if (!entry->preferred_base)
809 nr_result--;
810 entry->preferred_base = 1;
812 return 0;
815 for (p = packed_git; p; p = p->next) {
816 off_t offset = find_pack_entry_one(sha1, p);
817 if (offset) {
818 if (!found_pack) {
819 found_offset = offset;
820 found_pack = p;
822 if (exclude)
823 break;
824 if (incremental)
825 return 0;
826 if (local && !p->pack_local)
827 return 0;
831 if (nr_objects >= nr_alloc) {
832 nr_alloc = (nr_alloc + 1024) * 3 / 2;
833 objects = xrealloc(objects, nr_alloc * sizeof(*entry));
836 entry = objects + nr_objects++;
837 memset(entry, 0, sizeof(*entry));
838 hashcpy(entry->idx.sha1, sha1);
839 entry->hash = hash;
840 if (type)
841 entry->type = type;
842 if (exclude)
843 entry->preferred_base = 1;
844 else
845 nr_result++;
846 if (found_pack) {
847 entry->in_pack = found_pack;
848 entry->in_pack_offset = found_offset;
851 if (object_ix_hashsz * 3 <= nr_objects * 4)
852 rehash_objects();
853 else
854 object_ix[-1 - ix] = nr_objects;
856 if (progress)
857 display_progress(progress_state, nr_objects);
859 if (name && no_try_delta(name))
860 entry->no_try_delta = 1;
862 return 1;
865 struct pbase_tree_cache {
866 unsigned char sha1[20];
867 int ref;
868 int temporary;
869 void *tree_data;
870 unsigned long tree_size;
873 static struct pbase_tree_cache *(pbase_tree_cache[256]);
874 static int pbase_tree_cache_ix(const unsigned char *sha1)
876 return sha1[0] % ARRAY_SIZE(pbase_tree_cache);
878 static int pbase_tree_cache_ix_incr(int ix)
880 return (ix+1) % ARRAY_SIZE(pbase_tree_cache);
883 static struct pbase_tree {
884 struct pbase_tree *next;
885 /* This is a phony "cache" entry; we are not
886 * going to evict it nor find it through _get()
887 * mechanism -- this is for the toplevel node that
888 * would almost always change with any commit.
890 struct pbase_tree_cache pcache;
891 } *pbase_tree;
893 static struct pbase_tree_cache *pbase_tree_get(const unsigned char *sha1)
895 struct pbase_tree_cache *ent, *nent;
896 void *data;
897 unsigned long size;
898 enum object_type type;
899 int neigh;
900 int my_ix = pbase_tree_cache_ix(sha1);
901 int available_ix = -1;
903 /* pbase-tree-cache acts as a limited hashtable.
904 * your object will be found at your index or within a few
905 * slots after that slot if it is cached.
907 for (neigh = 0; neigh < 8; neigh++) {
908 ent = pbase_tree_cache[my_ix];
909 if (ent && !hashcmp(ent->sha1, sha1)) {
910 ent->ref++;
911 return ent;
913 else if (((available_ix < 0) && (!ent || !ent->ref)) ||
914 ((0 <= available_ix) &&
915 (!ent && pbase_tree_cache[available_ix])))
916 available_ix = my_ix;
917 if (!ent)
918 break;
919 my_ix = pbase_tree_cache_ix_incr(my_ix);
922 /* Did not find one. Either we got a bogus request or
923 * we need to read and perhaps cache.
925 data = read_sha1_file(sha1, &type, &size);
926 if (!data)
927 return NULL;
928 if (type != OBJ_TREE) {
929 free(data);
930 return NULL;
933 /* We need to either cache or return a throwaway copy */
935 if (available_ix < 0)
936 ent = NULL;
937 else {
938 ent = pbase_tree_cache[available_ix];
939 my_ix = available_ix;
942 if (!ent) {
943 nent = xmalloc(sizeof(*nent));
944 nent->temporary = (available_ix < 0);
946 else {
947 /* evict and reuse */
948 free(ent->tree_data);
949 nent = ent;
951 hashcpy(nent->sha1, sha1);
952 nent->tree_data = data;
953 nent->tree_size = size;
954 nent->ref = 1;
955 if (!nent->temporary)
956 pbase_tree_cache[my_ix] = nent;
957 return nent;
960 static void pbase_tree_put(struct pbase_tree_cache *cache)
962 if (!cache->temporary) {
963 cache->ref--;
964 return;
966 free(cache->tree_data);
967 free(cache);
970 static int name_cmp_len(const char *name)
972 int i;
973 for (i = 0; name[i] && name[i] != '\n' && name[i] != '/'; i++)
975 return i;
978 static void add_pbase_object(struct tree_desc *tree,
979 const char *name,
980 int cmplen,
981 const char *fullname)
983 struct name_entry entry;
984 int cmp;
986 while (tree_entry(tree,&entry)) {
987 if (S_ISGITLINK(entry.mode))
988 continue;
989 cmp = tree_entry_len(entry.path, entry.sha1) != cmplen ? 1 :
990 memcmp(name, entry.path, cmplen);
991 if (cmp > 0)
992 continue;
993 if (cmp < 0)
994 return;
995 if (name[cmplen] != '/') {
996 add_object_entry(entry.sha1,
997 S_ISDIR(entry.mode) ? OBJ_TREE : OBJ_BLOB,
998 fullname, 1);
999 return;
1001 if (S_ISDIR(entry.mode)) {
1002 struct tree_desc sub;
1003 struct pbase_tree_cache *tree;
1004 const char *down = name+cmplen+1;
1005 int downlen = name_cmp_len(down);
1007 tree = pbase_tree_get(entry.sha1);
1008 if (!tree)
1009 return;
1010 init_tree_desc(&sub, tree->tree_data, tree->tree_size);
1012 add_pbase_object(&sub, down, downlen, fullname);
1013 pbase_tree_put(tree);
1018 static unsigned *done_pbase_paths;
1019 static int done_pbase_paths_num;
1020 static int done_pbase_paths_alloc;
1021 static int done_pbase_path_pos(unsigned hash)
1023 int lo = 0;
1024 int hi = done_pbase_paths_num;
1025 while (lo < hi) {
1026 int mi = (hi + lo) / 2;
1027 if (done_pbase_paths[mi] == hash)
1028 return mi;
1029 if (done_pbase_paths[mi] < hash)
1030 hi = mi;
1031 else
1032 lo = mi + 1;
1034 return -lo-1;
1037 static int check_pbase_path(unsigned hash)
1039 int pos = (!done_pbase_paths) ? -1 : done_pbase_path_pos(hash);
1040 if (0 <= pos)
1041 return 1;
1042 pos = -pos - 1;
1043 if (done_pbase_paths_alloc <= done_pbase_paths_num) {
1044 done_pbase_paths_alloc = alloc_nr(done_pbase_paths_alloc);
1045 done_pbase_paths = xrealloc(done_pbase_paths,
1046 done_pbase_paths_alloc *
1047 sizeof(unsigned));
1049 done_pbase_paths_num++;
1050 if (pos < done_pbase_paths_num)
1051 memmove(done_pbase_paths + pos + 1,
1052 done_pbase_paths + pos,
1053 (done_pbase_paths_num - pos - 1) * sizeof(unsigned));
1054 done_pbase_paths[pos] = hash;
1055 return 0;
1058 static void add_preferred_base_object(const char *name)
1060 struct pbase_tree *it;
1061 int cmplen;
1062 unsigned hash = name_hash(name);
1064 if (!num_preferred_base || check_pbase_path(hash))
1065 return;
1067 cmplen = name_cmp_len(name);
1068 for (it = pbase_tree; it; it = it->next) {
1069 if (cmplen == 0) {
1070 add_object_entry(it->pcache.sha1, OBJ_TREE, NULL, 1);
1072 else {
1073 struct tree_desc tree;
1074 init_tree_desc(&tree, it->pcache.tree_data, it->pcache.tree_size);
1075 add_pbase_object(&tree, name, cmplen, name);
1080 static void add_preferred_base(unsigned char *sha1)
1082 struct pbase_tree *it;
1083 void *data;
1084 unsigned long size;
1085 unsigned char tree_sha1[20];
1087 if (window <= num_preferred_base++)
1088 return;
1090 data = read_object_with_reference(sha1, tree_type, &size, tree_sha1);
1091 if (!data)
1092 return;
1094 for (it = pbase_tree; it; it = it->next) {
1095 if (!hashcmp(it->pcache.sha1, tree_sha1)) {
1096 free(data);
1097 return;
1101 it = xcalloc(1, sizeof(*it));
1102 it->next = pbase_tree;
1103 pbase_tree = it;
1105 hashcpy(it->pcache.sha1, tree_sha1);
1106 it->pcache.tree_data = data;
1107 it->pcache.tree_size = size;
1110 static void check_object(struct object_entry *entry)
1112 if (entry->in_pack) {
1113 struct packed_git *p = entry->in_pack;
1114 struct pack_window *w_curs = NULL;
1115 const unsigned char *base_ref = NULL;
1116 struct object_entry *base_entry;
1117 unsigned long used, used_0;
1118 unsigned int avail;
1119 off_t ofs;
1120 unsigned char *buf, c;
1122 buf = use_pack(p, &w_curs, entry->in_pack_offset, &avail);
1125 * We want in_pack_type even if we do not reuse delta
1126 * since non-delta representations could still be reused.
1128 used = unpack_object_header_gently(buf, avail,
1129 &entry->in_pack_type,
1130 &entry->size);
1133 * Determine if this is a delta and if so whether we can
1134 * reuse it or not. Otherwise let's find out as cheaply as
1135 * possible what the actual type and size for this object is.
1137 switch (entry->in_pack_type) {
1138 default:
1139 /* Not a delta hence we've already got all we need. */
1140 entry->type = entry->in_pack_type;
1141 entry->in_pack_header_size = used;
1142 unuse_pack(&w_curs);
1143 return;
1144 case OBJ_REF_DELTA:
1145 if (!no_reuse_delta && !entry->preferred_base)
1146 base_ref = use_pack(p, &w_curs,
1147 entry->in_pack_offset + used, NULL);
1148 entry->in_pack_header_size = used + 20;
1149 break;
1150 case OBJ_OFS_DELTA:
1151 buf = use_pack(p, &w_curs,
1152 entry->in_pack_offset + used, NULL);
1153 used_0 = 0;
1154 c = buf[used_0++];
1155 ofs = c & 127;
1156 while (c & 128) {
1157 ofs += 1;
1158 if (!ofs || MSB(ofs, 7))
1159 die("delta base offset overflow in pack for %s",
1160 sha1_to_hex(entry->idx.sha1));
1161 c = buf[used_0++];
1162 ofs = (ofs << 7) + (c & 127);
1164 if (ofs >= entry->in_pack_offset)
1165 die("delta base offset out of bound for %s",
1166 sha1_to_hex(entry->idx.sha1));
1167 ofs = entry->in_pack_offset - ofs;
1168 if (!no_reuse_delta && !entry->preferred_base)
1169 base_ref = find_packed_object_name(p, ofs);
1170 entry->in_pack_header_size = used + used_0;
1171 break;
1174 if (base_ref && (base_entry = locate_object_entry(base_ref))) {
1176 * If base_ref was set above that means we wish to
1177 * reuse delta data, and we even found that base
1178 * in the list of objects we want to pack. Goodie!
1180 * Depth value does not matter - find_deltas() will
1181 * never consider reused delta as the base object to
1182 * deltify other objects against, in order to avoid
1183 * circular deltas.
1185 entry->type = entry->in_pack_type;
1186 entry->delta = base_entry;
1187 entry->delta_sibling = base_entry->delta_child;
1188 base_entry->delta_child = entry;
1189 unuse_pack(&w_curs);
1190 return;
1193 if (entry->type) {
1195 * This must be a delta and we already know what the
1196 * final object type is. Let's extract the actual
1197 * object size from the delta header.
1199 entry->size = get_size_from_delta(p, &w_curs,
1200 entry->in_pack_offset + entry->in_pack_header_size);
1201 unuse_pack(&w_curs);
1202 return;
1206 * No choice but to fall back to the recursive delta walk
1207 * with sha1_object_info() to find about the object type
1208 * at this point...
1210 unuse_pack(&w_curs);
1213 entry->type = sha1_object_info(entry->idx.sha1, &entry->size);
1214 if (entry->type < 0)
1215 die("unable to get type of object %s",
1216 sha1_to_hex(entry->idx.sha1));
1219 static int pack_offset_sort(const void *_a, const void *_b)
1221 const struct object_entry *a = *(struct object_entry **)_a;
1222 const struct object_entry *b = *(struct object_entry **)_b;
1224 /* avoid filesystem trashing with loose objects */
1225 if (!a->in_pack && !b->in_pack)
1226 return hashcmp(a->idx.sha1, b->idx.sha1);
1228 if (a->in_pack < b->in_pack)
1229 return -1;
1230 if (a->in_pack > b->in_pack)
1231 return 1;
1232 return a->in_pack_offset < b->in_pack_offset ? -1 :
1233 (a->in_pack_offset > b->in_pack_offset);
1236 static void get_object_details(void)
1238 uint32_t i;
1239 struct object_entry **sorted_by_offset;
1241 sorted_by_offset = xcalloc(nr_objects, sizeof(struct object_entry *));
1242 for (i = 0; i < nr_objects; i++)
1243 sorted_by_offset[i] = objects + i;
1244 qsort(sorted_by_offset, nr_objects, sizeof(*sorted_by_offset), pack_offset_sort);
1246 prepare_pack_ix();
1247 for (i = 0; i < nr_objects; i++)
1248 check_object(sorted_by_offset[i]);
1249 free(sorted_by_offset);
1252 static int type_size_sort(const void *_a, const void *_b)
1254 const struct object_entry *a = *(struct object_entry **)_a;
1255 const struct object_entry *b = *(struct object_entry **)_b;
1257 if (a->type < b->type)
1258 return -1;
1259 if (a->type > b->type)
1260 return 1;
1261 if (a->hash < b->hash)
1262 return -1;
1263 if (a->hash > b->hash)
1264 return 1;
1265 if (a->preferred_base < b->preferred_base)
1266 return -1;
1267 if (a->preferred_base > b->preferred_base)
1268 return 1;
1269 if (a->size < b->size)
1270 return -1;
1271 if (a->size > b->size)
1272 return 1;
1273 return a > b ? -1 : (a < b); /* newest last */
1276 struct unpacked {
1277 struct object_entry *entry;
1278 void *data;
1279 struct delta_index *index;
1280 unsigned depth;
1283 static int delta_cacheable(unsigned long src_size, unsigned long trg_size,
1284 unsigned long delta_size)
1286 if (max_delta_cache_size && delta_cache_size + delta_size > max_delta_cache_size)
1287 return 0;
1289 if (delta_size < cache_max_small_delta_size)
1290 return 1;
1292 /* cache delta, if objects are large enough compared to delta size */
1293 if ((src_size >> 20) + (trg_size >> 21) > (delta_size >> 10))
1294 return 1;
1296 return 0;
1299 #ifdef THREADED_DELTA_SEARCH
1301 static pthread_mutex_t read_mutex = PTHREAD_MUTEX_INITIALIZER;
1302 #define read_lock() pthread_mutex_lock(&read_mutex)
1303 #define read_unlock() pthread_mutex_unlock(&read_mutex)
1305 static pthread_mutex_t cache_mutex = PTHREAD_MUTEX_INITIALIZER;
1306 #define cache_lock() pthread_mutex_lock(&cache_mutex)
1307 #define cache_unlock() pthread_mutex_unlock(&cache_mutex)
1309 static pthread_mutex_t progress_mutex = PTHREAD_MUTEX_INITIALIZER;
1310 #define progress_lock() pthread_mutex_lock(&progress_mutex)
1311 #define progress_unlock() pthread_mutex_unlock(&progress_mutex)
1313 #else
1315 #define read_lock() (void)0
1316 #define read_unlock() (void)0
1317 #define cache_lock() (void)0
1318 #define cache_unlock() (void)0
1319 #define progress_lock() (void)0
1320 #define progress_unlock() (void)0
1322 #endif
1325 * We search for deltas _backwards_ in a list sorted by type and
1326 * by size, so that we see progressively smaller and smaller files.
1327 * That's because we prefer deltas to be from the bigger file
1328 * to the smaller - deletes are potentially cheaper, but perhaps
1329 * more importantly, the bigger file is likely the more recent
1330 * one.
1332 static int try_delta(struct unpacked *trg, struct unpacked *src,
1333 unsigned max_depth, unsigned long *mem_usage)
1335 struct object_entry *trg_entry = trg->entry;
1336 struct object_entry *src_entry = src->entry;
1337 unsigned long trg_size, src_size, delta_size, sizediff, max_size, sz;
1338 unsigned ref_depth;
1339 enum object_type type;
1340 void *delta_buf;
1342 /* Don't bother doing diffs between different types */
1343 if (trg_entry->type != src_entry->type)
1344 return -1;
1347 * We do not bother to try a delta that we discarded
1348 * on an earlier try, but only when reusing delta data.
1350 if (!no_reuse_delta && trg_entry->in_pack &&
1351 trg_entry->in_pack == src_entry->in_pack &&
1352 trg_entry->in_pack_type != OBJ_REF_DELTA &&
1353 trg_entry->in_pack_type != OBJ_OFS_DELTA)
1354 return 0;
1356 /* Let's not bust the allowed depth. */
1357 if (src->depth >= max_depth)
1358 return 0;
1360 /* Now some size filtering heuristics. */
1361 trg_size = trg_entry->size;
1362 if (!trg_entry->delta) {
1363 max_size = trg_size/2 - 20;
1364 ref_depth = 1;
1365 } else {
1366 max_size = trg_entry->delta_size;
1367 ref_depth = trg->depth;
1369 max_size = max_size * (max_depth - src->depth) /
1370 (max_depth - ref_depth + 1);
1371 if (max_size == 0)
1372 return 0;
1373 src_size = src_entry->size;
1374 sizediff = src_size < trg_size ? trg_size - src_size : 0;
1375 if (sizediff >= max_size)
1376 return 0;
1377 if (trg_size < src_size / 32)
1378 return 0;
1380 /* Load data if not already done */
1381 if (!trg->data) {
1382 read_lock();
1383 trg->data = read_sha1_file(trg_entry->idx.sha1, &type, &sz);
1384 read_unlock();
1385 if (!trg->data)
1386 die("object %s cannot be read",
1387 sha1_to_hex(trg_entry->idx.sha1));
1388 if (sz != trg_size)
1389 die("object %s inconsistent object length (%lu vs %lu)",
1390 sha1_to_hex(trg_entry->idx.sha1), sz, trg_size);
1391 *mem_usage += sz;
1393 if (!src->data) {
1394 read_lock();
1395 src->data = read_sha1_file(src_entry->idx.sha1, &type, &sz);
1396 read_unlock();
1397 if (!src->data)
1398 die("object %s cannot be read",
1399 sha1_to_hex(src_entry->idx.sha1));
1400 if (sz != src_size)
1401 die("object %s inconsistent object length (%lu vs %lu)",
1402 sha1_to_hex(src_entry->idx.sha1), sz, src_size);
1403 *mem_usage += sz;
1405 if (!src->index) {
1406 src->index = create_delta_index(src->data, src_size);
1407 if (!src->index) {
1408 static int warned = 0;
1409 if (!warned++)
1410 warning("suboptimal pack - out of memory");
1411 return 0;
1413 *mem_usage += sizeof_delta_index(src->index);
1416 delta_buf = create_delta(src->index, trg->data, trg_size, &delta_size, max_size);
1417 if (!delta_buf)
1418 return 0;
1420 if (trg_entry->delta) {
1421 /* Prefer only shallower same-sized deltas. */
1422 if (delta_size == trg_entry->delta_size &&
1423 src->depth + 1 >= trg->depth) {
1424 free(delta_buf);
1425 return 0;
1429 trg_entry->delta = src_entry;
1430 trg_entry->delta_size = delta_size;
1431 trg->depth = src->depth + 1;
1434 * Handle memory allocation outside of the cache
1435 * accounting lock. Compiler will optimize the strangeness
1436 * away when THREADED_DELTA_SEARCH is not defined.
1438 if (trg_entry->delta_data)
1439 free(trg_entry->delta_data);
1440 cache_lock();
1441 if (trg_entry->delta_data) {
1442 delta_cache_size -= trg_entry->delta_size;
1443 trg_entry->delta_data = NULL;
1445 if (delta_cacheable(src_size, trg_size, delta_size)) {
1446 delta_cache_size += trg_entry->delta_size;
1447 cache_unlock();
1448 trg_entry->delta_data = xrealloc(delta_buf, delta_size);
1449 } else {
1450 cache_unlock();
1451 free(delta_buf);
1454 return 1;
1457 static unsigned int check_delta_limit(struct object_entry *me, unsigned int n)
1459 struct object_entry *child = me->delta_child;
1460 unsigned int m = n;
1461 while (child) {
1462 unsigned int c = check_delta_limit(child, n + 1);
1463 if (m < c)
1464 m = c;
1465 child = child->delta_sibling;
1467 return m;
1470 static unsigned long free_unpacked(struct unpacked *n)
1472 unsigned long freed_mem = sizeof_delta_index(n->index);
1473 free_delta_index(n->index);
1474 n->index = NULL;
1475 if (n->data) {
1476 freed_mem += n->entry->size;
1477 free(n->data);
1478 n->data = NULL;
1480 n->entry = NULL;
1481 n->depth = 0;
1482 return freed_mem;
1485 static void find_deltas(struct object_entry **list, unsigned list_size,
1486 int window, int depth, unsigned *processed)
1488 uint32_t i = list_size, idx = 0, count = 0;
1489 unsigned int array_size = window * sizeof(struct unpacked);
1490 struct unpacked *array;
1491 unsigned long mem_usage = 0;
1493 array = xmalloc(array_size);
1494 memset(array, 0, array_size);
1496 do {
1497 struct object_entry *entry = list[--i];
1498 struct unpacked *n = array + idx;
1499 int j, max_depth, best_base = -1;
1501 mem_usage -= free_unpacked(n);
1502 n->entry = entry;
1504 while (window_memory_limit &&
1505 mem_usage > window_memory_limit &&
1506 count > 1) {
1507 uint32_t tail = (idx + window - count) % window;
1508 mem_usage -= free_unpacked(array + tail);
1509 count--;
1512 /* We do not compute delta to *create* objects we are not
1513 * going to pack.
1515 if (entry->preferred_base)
1516 goto next;
1518 progress_lock();
1519 (*processed)++;
1520 if (progress)
1521 display_progress(progress_state, *processed);
1522 progress_unlock();
1525 * If the current object is at pack edge, take the depth the
1526 * objects that depend on the current object into account
1527 * otherwise they would become too deep.
1529 max_depth = depth;
1530 if (entry->delta_child) {
1531 max_depth -= check_delta_limit(entry, 0);
1532 if (max_depth <= 0)
1533 goto next;
1536 j = window;
1537 while (--j > 0) {
1538 int ret;
1539 uint32_t other_idx = idx + j;
1540 struct unpacked *m;
1541 if (other_idx >= window)
1542 other_idx -= window;
1543 m = array + other_idx;
1544 if (!m->entry)
1545 break;
1546 ret = try_delta(n, m, max_depth, &mem_usage);
1547 if (ret < 0)
1548 break;
1549 else if (ret > 0)
1550 best_base = other_idx;
1553 /* if we made n a delta, and if n is already at max
1554 * depth, leaving it in the window is pointless. we
1555 * should evict it first.
1557 if (entry->delta && depth <= n->depth)
1558 continue;
1561 * Move the best delta base up in the window, after the
1562 * currently deltified object, to keep it longer. It will
1563 * be the first base object to be attempted next.
1565 if (entry->delta) {
1566 struct unpacked swap = array[best_base];
1567 int dist = (window + idx - best_base) % window;
1568 int dst = best_base;
1569 while (dist--) {
1570 int src = (dst + 1) % window;
1571 array[dst] = array[src];
1572 dst = src;
1574 array[dst] = swap;
1577 next:
1578 idx++;
1579 if (count + 1 < window)
1580 count++;
1581 if (idx >= window)
1582 idx = 0;
1583 } while (i > 0);
1585 for (i = 0; i < window; ++i) {
1586 free_delta_index(array[i].index);
1587 free(array[i].data);
1589 free(array);
1592 #ifdef THREADED_DELTA_SEARCH
1594 struct thread_params {
1595 pthread_t thread;
1596 struct object_entry **list;
1597 unsigned list_size;
1598 int window;
1599 int depth;
1600 unsigned *processed;
1603 static pthread_mutex_t data_request = PTHREAD_MUTEX_INITIALIZER;
1604 static pthread_mutex_t data_ready = PTHREAD_MUTEX_INITIALIZER;
1605 static pthread_mutex_t data_provider = PTHREAD_MUTEX_INITIALIZER;
1606 static struct thread_params *data_requester;
1608 static void *threaded_find_deltas(void *arg)
1610 struct thread_params *me = arg;
1612 for (;;) {
1613 pthread_mutex_lock(&data_request);
1614 data_requester = me;
1615 pthread_mutex_unlock(&data_provider);
1616 pthread_mutex_lock(&data_ready);
1617 pthread_mutex_unlock(&data_request);
1619 if (!me->list_size)
1620 return NULL;
1622 find_deltas(me->list, me->list_size,
1623 me->window, me->depth, me->processed);
1627 static void ll_find_deltas(struct object_entry **list, unsigned list_size,
1628 int window, int depth, unsigned *processed)
1630 struct thread_params *target, p[delta_search_threads];
1631 int i, ret;
1632 unsigned chunk_size;
1634 if (delta_search_threads <= 1) {
1635 find_deltas(list, list_size, window, depth, processed);
1636 return;
1639 pthread_mutex_lock(&data_provider);
1640 pthread_mutex_lock(&data_ready);
1642 for (i = 0; i < delta_search_threads; i++) {
1643 p[i].window = window;
1644 p[i].depth = depth;
1645 p[i].processed = processed;
1646 ret = pthread_create(&p[i].thread, NULL,
1647 threaded_find_deltas, &p[i]);
1648 if (ret)
1649 die("unable to create thread: %s", strerror(ret));
1652 /* this should be auto-tuned somehow */
1653 chunk_size = window * 1000;
1655 do {
1656 unsigned sublist_size = chunk_size;
1657 if (sublist_size > list_size)
1658 sublist_size = list_size;
1660 /* try to split chunks on "path" boundaries */
1661 while (sublist_size < list_size && list[sublist_size]->hash &&
1662 list[sublist_size]->hash == list[sublist_size-1]->hash)
1663 sublist_size++;
1665 pthread_mutex_lock(&data_provider);
1666 target = data_requester;
1667 target->list = list;
1668 target->list_size = sublist_size;
1669 pthread_mutex_unlock(&data_ready);
1671 list += sublist_size;
1672 list_size -= sublist_size;
1673 if (!sublist_size) {
1674 pthread_join(target->thread, NULL);
1675 i--;
1677 } while (i);
1680 #else
1681 #define ll_find_deltas find_deltas
1682 #endif
1684 static void prepare_pack(int window, int depth)
1686 struct object_entry **delta_list;
1687 uint32_t i, n, nr_deltas;
1689 get_object_details();
1691 if (!nr_objects || !window || !depth)
1692 return;
1694 delta_list = xmalloc(nr_objects * sizeof(*delta_list));
1695 nr_deltas = n = 0;
1697 for (i = 0; i < nr_objects; i++) {
1698 struct object_entry *entry = objects + i;
1700 if (entry->delta)
1701 /* This happens if we decided to reuse existing
1702 * delta from a pack. "!no_reuse_delta &&" is implied.
1704 continue;
1706 if (entry->size < 50)
1707 continue;
1709 if (entry->no_try_delta)
1710 continue;
1712 if (!entry->preferred_base)
1713 nr_deltas++;
1715 delta_list[n++] = entry;
1718 if (nr_deltas && n > 1) {
1719 unsigned nr_done = 0;
1720 if (progress)
1721 progress_state = start_progress("Compressing objects",
1722 nr_deltas);
1723 qsort(delta_list, n, sizeof(*delta_list), type_size_sort);
1724 ll_find_deltas(delta_list, n, window+1, depth, &nr_done);
1725 if (progress)
1726 stop_progress(&progress_state);
1727 if (nr_done != nr_deltas)
1728 die("inconsistency with delta count");
1730 free(delta_list);
1733 static int git_pack_config(const char *k, const char *v)
1735 if(!strcmp(k, "pack.window")) {
1736 window = git_config_int(k, v);
1737 return 0;
1739 if (!strcmp(k, "pack.windowmemory")) {
1740 window_memory_limit = git_config_ulong(k, v);
1741 return 0;
1743 if (!strcmp(k, "pack.depth")) {
1744 depth = git_config_int(k, v);
1745 return 0;
1747 if (!strcmp(k, "pack.compression")) {
1748 int level = git_config_int(k, v);
1749 if (level == -1)
1750 level = Z_DEFAULT_COMPRESSION;
1751 else if (level < 0 || level > Z_BEST_COMPRESSION)
1752 die("bad pack compression level %d", level);
1753 pack_compression_level = level;
1754 pack_compression_seen = 1;
1755 return 0;
1757 if (!strcmp(k, "pack.deltacachesize")) {
1758 max_delta_cache_size = git_config_int(k, v);
1759 return 0;
1761 if (!strcmp(k, "pack.deltacachelimit")) {
1762 cache_max_small_delta_size = git_config_int(k, v);
1763 return 0;
1765 if (!strcmp(k, "pack.threads")) {
1766 delta_search_threads = git_config_int(k, v);
1767 if (delta_search_threads < 1)
1768 die("invalid number of threads specified (%d)",
1769 delta_search_threads);
1770 #ifndef THREADED_DELTA_SEARCH
1771 if (delta_search_threads > 1)
1772 warning("no threads support, ignoring %s", k);
1773 #endif
1774 return 0;
1776 return git_default_config(k, v);
1779 static void read_object_list_from_stdin(void)
1781 char line[40 + 1 + PATH_MAX + 2];
1782 unsigned char sha1[20];
1784 for (;;) {
1785 if (!fgets(line, sizeof(line), stdin)) {
1786 if (feof(stdin))
1787 break;
1788 if (!ferror(stdin))
1789 die("fgets returned NULL, not EOF, not error!");
1790 if (errno != EINTR)
1791 die("fgets: %s", strerror(errno));
1792 clearerr(stdin);
1793 continue;
1795 if (line[0] == '-') {
1796 if (get_sha1_hex(line+1, sha1))
1797 die("expected edge sha1, got garbage:\n %s",
1798 line);
1799 add_preferred_base(sha1);
1800 continue;
1802 if (get_sha1_hex(line, sha1))
1803 die("expected sha1, got garbage:\n %s", line);
1805 add_preferred_base_object(line+41);
1806 add_object_entry(sha1, 0, line+41, 0);
1810 #define OBJECT_ADDED (1u<<20)
1812 static void show_commit(struct commit *commit)
1814 add_object_entry(commit->object.sha1, OBJ_COMMIT, NULL, 0);
1815 commit->object.flags |= OBJECT_ADDED;
1818 static void show_object(struct object_array_entry *p)
1820 add_preferred_base_object(p->name);
1821 add_object_entry(p->item->sha1, p->item->type, p->name, 0);
1822 p->item->flags |= OBJECT_ADDED;
1825 static void show_edge(struct commit *commit)
1827 add_preferred_base(commit->object.sha1);
1830 struct in_pack_object {
1831 off_t offset;
1832 struct object *object;
1835 struct in_pack {
1836 int alloc;
1837 int nr;
1838 struct in_pack_object *array;
1841 static void mark_in_pack_object(struct object *object, struct packed_git *p, struct in_pack *in_pack)
1843 in_pack->array[in_pack->nr].offset = find_pack_entry_one(object->sha1, p);
1844 in_pack->array[in_pack->nr].object = object;
1845 in_pack->nr++;
1849 * Compare the objects in the offset order, in order to emulate the
1850 * "git-rev-list --objects" output that produced the pack originally.
1852 static int ofscmp(const void *a_, const void *b_)
1854 struct in_pack_object *a = (struct in_pack_object *)a_;
1855 struct in_pack_object *b = (struct in_pack_object *)b_;
1857 if (a->offset < b->offset)
1858 return -1;
1859 else if (a->offset > b->offset)
1860 return 1;
1861 else
1862 return hashcmp(a->object->sha1, b->object->sha1);
1865 static void add_objects_in_unpacked_packs(struct rev_info *revs)
1867 struct packed_git *p;
1868 struct in_pack in_pack;
1869 uint32_t i;
1871 memset(&in_pack, 0, sizeof(in_pack));
1873 for (p = packed_git; p; p = p->next) {
1874 const unsigned char *sha1;
1875 struct object *o;
1877 for (i = 0; i < revs->num_ignore_packed; i++) {
1878 if (matches_pack_name(p, revs->ignore_packed[i]))
1879 break;
1881 if (revs->num_ignore_packed <= i)
1882 continue;
1883 if (open_pack_index(p))
1884 die("cannot open pack index");
1886 ALLOC_GROW(in_pack.array,
1887 in_pack.nr + p->num_objects,
1888 in_pack.alloc);
1890 for (i = 0; i < p->num_objects; i++) {
1891 sha1 = nth_packed_object_sha1(p, i);
1892 o = lookup_unknown_object(sha1);
1893 if (!(o->flags & OBJECT_ADDED))
1894 mark_in_pack_object(o, p, &in_pack);
1895 o->flags |= OBJECT_ADDED;
1899 if (in_pack.nr) {
1900 qsort(in_pack.array, in_pack.nr, sizeof(in_pack.array[0]),
1901 ofscmp);
1902 for (i = 0; i < in_pack.nr; i++) {
1903 struct object *o = in_pack.array[i].object;
1904 add_object_entry(o->sha1, o->type, "", 0);
1907 free(in_pack.array);
1910 static void get_object_list(int ac, const char **av)
1912 struct rev_info revs;
1913 char line[1000];
1914 int flags = 0;
1916 init_revisions(&revs, NULL);
1917 save_commit_buffer = 0;
1918 track_object_refs = 0;
1919 setup_revisions(ac, av, &revs, NULL);
1921 while (fgets(line, sizeof(line), stdin) != NULL) {
1922 int len = strlen(line);
1923 if (line[len - 1] == '\n')
1924 line[--len] = 0;
1925 if (!len)
1926 break;
1927 if (*line == '-') {
1928 if (!strcmp(line, "--not")) {
1929 flags ^= UNINTERESTING;
1930 continue;
1932 die("not a rev '%s'", line);
1934 if (handle_revision_arg(line, &revs, flags, 1))
1935 die("bad revision '%s'", line);
1938 prepare_revision_walk(&revs);
1939 mark_edges_uninteresting(revs.commits, &revs, show_edge);
1940 traverse_commit_list(&revs, show_commit, show_object);
1942 if (keep_unreachable)
1943 add_objects_in_unpacked_packs(&revs);
1946 static int adjust_perm(const char *path, mode_t mode)
1948 if (chmod(path, mode))
1949 return -1;
1950 return adjust_shared_perm(path);
1953 int cmd_pack_objects(int argc, const char **argv, const char *prefix)
1955 int use_internal_rev_list = 0;
1956 int thin = 0;
1957 uint32_t i;
1958 const char **rp_av;
1959 int rp_ac_alloc = 64;
1960 int rp_ac;
1962 rp_av = xcalloc(rp_ac_alloc, sizeof(*rp_av));
1964 rp_av[0] = "pack-objects";
1965 rp_av[1] = "--objects"; /* --thin will make it --objects-edge */
1966 rp_ac = 2;
1968 git_config(git_pack_config);
1969 if (!pack_compression_seen && core_compression_seen)
1970 pack_compression_level = core_compression_level;
1972 progress = isatty(2);
1973 for (i = 1; i < argc; i++) {
1974 const char *arg = argv[i];
1976 if (*arg != '-')
1977 break;
1979 if (!strcmp("--non-empty", arg)) {
1980 non_empty = 1;
1981 continue;
1983 if (!strcmp("--local", arg)) {
1984 local = 1;
1985 continue;
1987 if (!strcmp("--incremental", arg)) {
1988 incremental = 1;
1989 continue;
1991 if (!prefixcmp(arg, "--compression=")) {
1992 char *end;
1993 int level = strtoul(arg+14, &end, 0);
1994 if (!arg[14] || *end)
1995 usage(pack_usage);
1996 if (level == -1)
1997 level = Z_DEFAULT_COMPRESSION;
1998 else if (level < 0 || level > Z_BEST_COMPRESSION)
1999 die("bad pack compression level %d", level);
2000 pack_compression_level = level;
2001 continue;
2003 if (!prefixcmp(arg, "--max-pack-size=")) {
2004 char *end;
2005 pack_size_limit = strtoul(arg+16, &end, 0) * 1024 * 1024;
2006 if (!arg[16] || *end)
2007 usage(pack_usage);
2008 continue;
2010 if (!prefixcmp(arg, "--window=")) {
2011 char *end;
2012 window = strtoul(arg+9, &end, 0);
2013 if (!arg[9] || *end)
2014 usage(pack_usage);
2015 continue;
2017 if (!prefixcmp(arg, "--window-memory=")) {
2018 if (!git_parse_ulong(arg+16, &window_memory_limit))
2019 usage(pack_usage);
2020 continue;
2022 if (!prefixcmp(arg, "--threads=")) {
2023 char *end;
2024 delta_search_threads = strtoul(arg+10, &end, 0);
2025 if (!arg[10] || *end || delta_search_threads < 1)
2026 usage(pack_usage);
2027 #ifndef THREADED_DELTA_SEARCH
2028 if (delta_search_threads > 1)
2029 warning("no threads support, "
2030 "ignoring %s", arg);
2031 #endif
2032 continue;
2034 if (!prefixcmp(arg, "--depth=")) {
2035 char *end;
2036 depth = strtoul(arg+8, &end, 0);
2037 if (!arg[8] || *end)
2038 usage(pack_usage);
2039 continue;
2041 if (!strcmp("--progress", arg)) {
2042 progress = 1;
2043 continue;
2045 if (!strcmp("--all-progress", arg)) {
2046 progress = 2;
2047 continue;
2049 if (!strcmp("-q", arg)) {
2050 progress = 0;
2051 continue;
2053 if (!strcmp("--no-reuse-delta", arg)) {
2054 no_reuse_delta = 1;
2055 continue;
2057 if (!strcmp("--no-reuse-object", arg)) {
2058 no_reuse_object = no_reuse_delta = 1;
2059 continue;
2061 if (!strcmp("--delta-base-offset", arg)) {
2062 allow_ofs_delta = 1;
2063 continue;
2065 if (!strcmp("--stdout", arg)) {
2066 pack_to_stdout = 1;
2067 continue;
2069 if (!strcmp("--revs", arg)) {
2070 use_internal_rev_list = 1;
2071 continue;
2073 if (!strcmp("--keep-unreachable", arg)) {
2074 keep_unreachable = 1;
2075 continue;
2077 if (!strcmp("--unpacked", arg) ||
2078 !prefixcmp(arg, "--unpacked=") ||
2079 !strcmp("--reflog", arg) ||
2080 !strcmp("--all", arg)) {
2081 use_internal_rev_list = 1;
2082 if (rp_ac >= rp_ac_alloc - 1) {
2083 rp_ac_alloc = alloc_nr(rp_ac_alloc);
2084 rp_av = xrealloc(rp_av,
2085 rp_ac_alloc * sizeof(*rp_av));
2087 rp_av[rp_ac++] = arg;
2088 continue;
2090 if (!strcmp("--thin", arg)) {
2091 use_internal_rev_list = 1;
2092 thin = 1;
2093 rp_av[1] = "--objects-edge";
2094 continue;
2096 if (!prefixcmp(arg, "--index-version=")) {
2097 char *c;
2098 pack_idx_default_version = strtoul(arg + 16, &c, 10);
2099 if (pack_idx_default_version > 2)
2100 die("bad %s", arg);
2101 if (*c == ',')
2102 pack_idx_off32_limit = strtoul(c+1, &c, 0);
2103 if (*c || pack_idx_off32_limit & 0x80000000)
2104 die("bad %s", arg);
2105 continue;
2107 usage(pack_usage);
2110 /* Traditionally "pack-objects [options] base extra" failed;
2111 * we would however want to take refs parameter that would
2112 * have been given to upstream rev-list ourselves, which means
2113 * we somehow want to say what the base name is. So the
2114 * syntax would be:
2116 * pack-objects [options] base <refs...>
2118 * in other words, we would treat the first non-option as the
2119 * base_name and send everything else to the internal revision
2120 * walker.
2123 if (!pack_to_stdout)
2124 base_name = argv[i++];
2126 if (pack_to_stdout != !base_name)
2127 usage(pack_usage);
2129 if (pack_to_stdout && pack_size_limit)
2130 die("--max-pack-size cannot be used to build a pack for transfer.");
2132 if (!pack_to_stdout && thin)
2133 die("--thin cannot be used to build an indexable pack.");
2135 prepare_packed_git();
2137 if (progress)
2138 progress_state = start_progress("Counting objects", 0);
2139 if (!use_internal_rev_list)
2140 read_object_list_from_stdin();
2141 else {
2142 rp_av[rp_ac] = NULL;
2143 get_object_list(rp_ac, rp_av);
2145 if (progress)
2146 stop_progress(&progress_state);
2148 if (non_empty && !nr_result)
2149 return 0;
2150 if (nr_result)
2151 prepare_pack(window, depth);
2152 write_pack_file();
2153 if (progress)
2154 fprintf(stderr, "Total %u (delta %u), reused %u (delta %u)\n",
2155 written, written_delta, reused, reused_delta);
2156 return 0;