Make builtin-update-ref.c use parse_options
[git/gitweb-caching.git] / builtin-pack-objects.c
blob0be539ed7fd9bf95bb40515b560c7615ed318f37
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 *pack_tmp_name, *idx_tmp_name;
69 static char tmpname[PATH_MAX];
70 static const char *base_name;
71 static int progress = 1;
72 static int window = 10;
73 static uint32_t pack_size_limit;
74 static int depth = 50;
75 static int delta_search_threads = 1;
76 static int pack_to_stdout;
77 static int num_preferred_base;
78 static struct progress progress_state;
79 static int pack_compression_level = Z_DEFAULT_COMPRESSION;
80 static int pack_compression_seen;
82 static unsigned long delta_cache_size = 0;
83 static unsigned long max_delta_cache_size = 0;
84 static unsigned long cache_max_small_delta_size = 1000;
86 static unsigned long window_memory_limit = 0;
89 * The object names in objects array are hashed with this hashtable,
90 * to help looking up the entry by object name.
91 * This hashtable is built after all the objects are seen.
93 static int *object_ix;
94 static int object_ix_hashsz;
97 * Pack index for existing packs give us easy access to the offsets into
98 * corresponding pack file where each object's data starts, but the entries
99 * do not store the size of the compressed representation (uncompressed
100 * size is easily available by examining the pack entry header). It is
101 * also rather expensive to find the sha1 for an object given its offset.
103 * We build a hashtable of existing packs (pack_revindex), and keep reverse
104 * index here -- pack index file is sorted by object name mapping to offset;
105 * this pack_revindex[].revindex array is a list of offset/index_nr pairs
106 * ordered by offset, so if you know the offset of an object, next offset
107 * is where its packed representation ends and the index_nr can be used to
108 * get the object sha1 from the main index.
110 struct revindex_entry {
111 off_t offset;
112 unsigned int nr;
114 struct pack_revindex {
115 struct packed_git *p;
116 struct revindex_entry *revindex;
118 static struct pack_revindex *pack_revindex;
119 static int pack_revindex_hashsz;
122 * stats
124 static uint32_t written, written_delta;
125 static uint32_t reused, reused_delta;
127 static int pack_revindex_ix(struct packed_git *p)
129 unsigned long ui = (unsigned long)p;
130 int i;
132 ui = ui ^ (ui >> 16); /* defeat structure alignment */
133 i = (int)(ui % pack_revindex_hashsz);
134 while (pack_revindex[i].p) {
135 if (pack_revindex[i].p == p)
136 return i;
137 if (++i == pack_revindex_hashsz)
138 i = 0;
140 return -1 - i;
143 static void prepare_pack_ix(void)
145 int num;
146 struct packed_git *p;
147 for (num = 0, p = packed_git; p; p = p->next)
148 num++;
149 if (!num)
150 return;
151 pack_revindex_hashsz = num * 11;
152 pack_revindex = xcalloc(sizeof(*pack_revindex), pack_revindex_hashsz);
153 for (p = packed_git; p; p = p->next) {
154 num = pack_revindex_ix(p);
155 num = - 1 - num;
156 pack_revindex[num].p = p;
158 /* revindex elements are lazily initialized */
161 static int cmp_offset(const void *a_, const void *b_)
163 const struct revindex_entry *a = a_;
164 const struct revindex_entry *b = b_;
165 return (a->offset < b->offset) ? -1 : (a->offset > b->offset) ? 1 : 0;
169 * Ordered list of offsets of objects in the pack.
171 static void prepare_pack_revindex(struct pack_revindex *rix)
173 struct packed_git *p = rix->p;
174 int num_ent = p->num_objects;
175 int i;
176 const char *index = p->index_data;
178 rix->revindex = xmalloc(sizeof(*rix->revindex) * (num_ent + 1));
179 index += 4 * 256;
181 if (p->index_version > 1) {
182 const uint32_t *off_32 =
183 (uint32_t *)(index + 8 + p->num_objects * (20 + 4));
184 const uint32_t *off_64 = off_32 + p->num_objects;
185 for (i = 0; i < num_ent; i++) {
186 uint32_t off = ntohl(*off_32++);
187 if (!(off & 0x80000000)) {
188 rix->revindex[i].offset = off;
189 } else {
190 rix->revindex[i].offset =
191 ((uint64_t)ntohl(*off_64++)) << 32;
192 rix->revindex[i].offset |=
193 ntohl(*off_64++);
195 rix->revindex[i].nr = i;
197 } else {
198 for (i = 0; i < num_ent; i++) {
199 uint32_t hl = *((uint32_t *)(index + 24 * i));
200 rix->revindex[i].offset = ntohl(hl);
201 rix->revindex[i].nr = i;
205 /* This knows the pack format -- the 20-byte trailer
206 * follows immediately after the last object data.
208 rix->revindex[num_ent].offset = p->pack_size - 20;
209 rix->revindex[num_ent].nr = -1;
210 qsort(rix->revindex, num_ent, sizeof(*rix->revindex), cmp_offset);
213 static struct revindex_entry * find_packed_object(struct packed_git *p,
214 off_t ofs)
216 int num;
217 int lo, hi;
218 struct pack_revindex *rix;
219 struct revindex_entry *revindex;
220 num = pack_revindex_ix(p);
221 if (num < 0)
222 die("internal error: pack revindex uninitialized");
223 rix = &pack_revindex[num];
224 if (!rix->revindex)
225 prepare_pack_revindex(rix);
226 revindex = rix->revindex;
227 lo = 0;
228 hi = p->num_objects + 1;
229 do {
230 int mi = (lo + hi) / 2;
231 if (revindex[mi].offset == ofs) {
232 return revindex + mi;
234 else if (ofs < revindex[mi].offset)
235 hi = mi;
236 else
237 lo = mi + 1;
238 } while (lo < hi);
239 die("internal error: pack revindex corrupt");
242 static const unsigned char *find_packed_object_name(struct packed_git *p,
243 off_t ofs)
245 struct revindex_entry *entry = find_packed_object(p, ofs);
246 return nth_packed_object_sha1(p, entry->nr);
249 static void *delta_against(void *buf, unsigned long size, struct object_entry *entry)
251 unsigned long othersize, delta_size;
252 enum object_type type;
253 void *otherbuf = read_sha1_file(entry->delta->idx.sha1, &type, &othersize);
254 void *delta_buf;
256 if (!otherbuf)
257 die("unable to read %s", sha1_to_hex(entry->delta->idx.sha1));
258 delta_buf = diff_delta(otherbuf, othersize,
259 buf, size, &delta_size, 0);
260 if (!delta_buf || delta_size != entry->delta_size)
261 die("delta size changed");
262 free(buf);
263 free(otherbuf);
264 return delta_buf;
268 * The per-object header is a pretty dense thing, which is
269 * - first byte: low four bits are "size", then three bits of "type",
270 * and the high bit is "size continues".
271 * - each byte afterwards: low seven bits are size continuation,
272 * with the high bit being "size continues"
274 static int encode_header(enum object_type type, unsigned long size, unsigned char *hdr)
276 int n = 1;
277 unsigned char c;
279 if (type < OBJ_COMMIT || type > OBJ_REF_DELTA)
280 die("bad type %d", type);
282 c = (type << 4) | (size & 15);
283 size >>= 4;
284 while (size) {
285 *hdr++ = c | 0x80;
286 c = size & 0x7f;
287 size >>= 7;
288 n++;
290 *hdr = c;
291 return n;
295 * we are going to reuse the existing object data as is. make
296 * sure it is not corrupt.
298 static int check_pack_inflate(struct packed_git *p,
299 struct pack_window **w_curs,
300 off_t offset,
301 off_t len,
302 unsigned long expect)
304 z_stream stream;
305 unsigned char fakebuf[4096], *in;
306 int st;
308 memset(&stream, 0, sizeof(stream));
309 inflateInit(&stream);
310 do {
311 in = use_pack(p, w_curs, offset, &stream.avail_in);
312 stream.next_in = in;
313 stream.next_out = fakebuf;
314 stream.avail_out = sizeof(fakebuf);
315 st = inflate(&stream, Z_FINISH);
316 offset += stream.next_in - in;
317 } while (st == Z_OK || st == Z_BUF_ERROR);
318 inflateEnd(&stream);
319 return (st == Z_STREAM_END &&
320 stream.total_out == expect &&
321 stream.total_in == len) ? 0 : -1;
324 static int check_pack_crc(struct packed_git *p, struct pack_window **w_curs,
325 off_t offset, off_t len, unsigned int nr)
327 const uint32_t *index_crc;
328 uint32_t data_crc = crc32(0, Z_NULL, 0);
330 do {
331 unsigned int avail;
332 void *data = use_pack(p, w_curs, offset, &avail);
333 if (avail > len)
334 avail = len;
335 data_crc = crc32(data_crc, data, avail);
336 offset += avail;
337 len -= avail;
338 } while (len);
340 index_crc = p->index_data;
341 index_crc += 2 + 256 + p->num_objects * (20/4) + nr;
343 return data_crc != ntohl(*index_crc);
346 static void copy_pack_data(struct sha1file *f,
347 struct packed_git *p,
348 struct pack_window **w_curs,
349 off_t offset,
350 off_t len)
352 unsigned char *in;
353 unsigned int avail;
355 while (len) {
356 in = use_pack(p, w_curs, offset, &avail);
357 if (avail > len)
358 avail = (unsigned int)len;
359 sha1write(f, in, avail);
360 offset += avail;
361 len -= avail;
365 static unsigned long write_object(struct sha1file *f,
366 struct object_entry *entry,
367 off_t write_offset)
369 unsigned long size;
370 enum object_type type;
371 void *buf;
372 unsigned char header[10];
373 unsigned char dheader[10];
374 unsigned hdrlen;
375 off_t datalen;
376 enum object_type obj_type;
377 int to_reuse = 0;
378 /* write limit if limited packsize and not first object */
379 unsigned long limit = pack_size_limit && nr_written ?
380 pack_size_limit - write_offset : 0;
381 /* no if no delta */
382 int usable_delta = !entry->delta ? 0 :
383 /* yes if unlimited packfile */
384 !pack_size_limit ? 1 :
385 /* no if base written to previous pack */
386 entry->delta->idx.offset == (off_t)-1 ? 0 :
387 /* otherwise double-check written to this
388 * pack, like we do below
390 entry->delta->idx.offset ? 1 : 0;
392 if (!pack_to_stdout)
393 crc32_begin(f);
395 obj_type = entry->type;
396 if (no_reuse_object)
397 to_reuse = 0; /* explicit */
398 else if (!entry->in_pack)
399 to_reuse = 0; /* can't reuse what we don't have */
400 else if (obj_type == OBJ_REF_DELTA || obj_type == OBJ_OFS_DELTA)
401 /* check_object() decided it for us ... */
402 to_reuse = usable_delta;
403 /* ... but pack split may override that */
404 else if (obj_type != entry->in_pack_type)
405 to_reuse = 0; /* pack has delta which is unusable */
406 else if (entry->delta)
407 to_reuse = 0; /* we want to pack afresh */
408 else
409 to_reuse = 1; /* we have it in-pack undeltified,
410 * and we do not need to deltify it.
413 if (!to_reuse) {
414 z_stream stream;
415 unsigned long maxsize;
416 void *out;
417 if (!usable_delta) {
418 buf = read_sha1_file(entry->idx.sha1, &obj_type, &size);
419 if (!buf)
420 die("unable to read %s", sha1_to_hex(entry->idx.sha1));
421 } else if (entry->delta_data) {
422 size = entry->delta_size;
423 buf = entry->delta_data;
424 entry->delta_data = NULL;
425 obj_type = (allow_ofs_delta && entry->delta->idx.offset) ?
426 OBJ_OFS_DELTA : OBJ_REF_DELTA;
427 } else {
428 buf = read_sha1_file(entry->idx.sha1, &type, &size);
429 if (!buf)
430 die("unable to read %s", sha1_to_hex(entry->idx.sha1));
431 buf = delta_against(buf, size, entry);
432 size = entry->delta_size;
433 obj_type = (allow_ofs_delta && entry->delta->idx.offset) ?
434 OBJ_OFS_DELTA : OBJ_REF_DELTA;
436 /* compress the data to store and put compressed length in datalen */
437 memset(&stream, 0, sizeof(stream));
438 deflateInit(&stream, pack_compression_level);
439 maxsize = deflateBound(&stream, size);
440 out = xmalloc(maxsize);
441 /* Compress it */
442 stream.next_in = buf;
443 stream.avail_in = size;
444 stream.next_out = out;
445 stream.avail_out = maxsize;
446 while (deflate(&stream, Z_FINISH) == Z_OK)
447 /* nothing */;
448 deflateEnd(&stream);
449 datalen = stream.total_out;
450 deflateEnd(&stream);
452 * The object header is a byte of 'type' followed by zero or
453 * more bytes of length.
455 hdrlen = encode_header(obj_type, size, header);
457 if (obj_type == OBJ_OFS_DELTA) {
459 * Deltas with relative base contain an additional
460 * encoding of the relative offset for the delta
461 * base from this object's position in the pack.
463 off_t ofs = entry->idx.offset - entry->delta->idx.offset;
464 unsigned pos = sizeof(dheader) - 1;
465 dheader[pos] = ofs & 127;
466 while (ofs >>= 7)
467 dheader[--pos] = 128 | (--ofs & 127);
468 if (limit && hdrlen + sizeof(dheader) - pos + datalen + 20 >= limit) {
469 free(out);
470 free(buf);
471 return 0;
473 sha1write(f, header, hdrlen);
474 sha1write(f, dheader + pos, sizeof(dheader) - pos);
475 hdrlen += sizeof(dheader) - pos;
476 } else if (obj_type == OBJ_REF_DELTA) {
478 * Deltas with a base reference contain
479 * an additional 20 bytes for the base sha1.
481 if (limit && hdrlen + 20 + datalen + 20 >= limit) {
482 free(out);
483 free(buf);
484 return 0;
486 sha1write(f, header, hdrlen);
487 sha1write(f, entry->delta->idx.sha1, 20);
488 hdrlen += 20;
489 } else {
490 if (limit && hdrlen + datalen + 20 >= limit) {
491 free(out);
492 free(buf);
493 return 0;
495 sha1write(f, header, hdrlen);
497 sha1write(f, out, datalen);
498 free(out);
499 free(buf);
501 else {
502 struct packed_git *p = entry->in_pack;
503 struct pack_window *w_curs = NULL;
504 struct revindex_entry *revidx;
505 off_t offset;
507 if (entry->delta) {
508 obj_type = (allow_ofs_delta && entry->delta->idx.offset) ?
509 OBJ_OFS_DELTA : OBJ_REF_DELTA;
510 reused_delta++;
512 hdrlen = encode_header(obj_type, entry->size, header);
513 offset = entry->in_pack_offset;
514 revidx = find_packed_object(p, offset);
515 datalen = revidx[1].offset - offset;
516 if (!pack_to_stdout && p->index_version > 1 &&
517 check_pack_crc(p, &w_curs, offset, datalen, revidx->nr))
518 die("bad packed object CRC for %s", sha1_to_hex(entry->idx.sha1));
519 offset += entry->in_pack_header_size;
520 datalen -= entry->in_pack_header_size;
521 if (obj_type == OBJ_OFS_DELTA) {
522 off_t ofs = entry->idx.offset - entry->delta->idx.offset;
523 unsigned pos = sizeof(dheader) - 1;
524 dheader[pos] = ofs & 127;
525 while (ofs >>= 7)
526 dheader[--pos] = 128 | (--ofs & 127);
527 if (limit && hdrlen + sizeof(dheader) - pos + datalen + 20 >= limit)
528 return 0;
529 sha1write(f, header, hdrlen);
530 sha1write(f, dheader + pos, sizeof(dheader) - pos);
531 hdrlen += sizeof(dheader) - pos;
532 } else if (obj_type == OBJ_REF_DELTA) {
533 if (limit && hdrlen + 20 + datalen + 20 >= limit)
534 return 0;
535 sha1write(f, header, hdrlen);
536 sha1write(f, entry->delta->idx.sha1, 20);
537 hdrlen += 20;
538 } else {
539 if (limit && hdrlen + datalen + 20 >= limit)
540 return 0;
541 sha1write(f, header, hdrlen);
544 if (!pack_to_stdout && p->index_version == 1 &&
545 check_pack_inflate(p, &w_curs, offset, datalen, entry->size))
546 die("corrupt packed object for %s", sha1_to_hex(entry->idx.sha1));
547 copy_pack_data(f, p, &w_curs, offset, datalen);
548 unuse_pack(&w_curs);
549 reused++;
551 if (usable_delta)
552 written_delta++;
553 written++;
554 if (!pack_to_stdout)
555 entry->idx.crc32 = crc32_end(f);
556 return hdrlen + datalen;
559 static off_t write_one(struct sha1file *f,
560 struct object_entry *e,
561 off_t offset)
563 unsigned long size;
565 /* offset is non zero if object is written already. */
566 if (e->idx.offset || e->preferred_base)
567 return offset;
569 /* if we are deltified, write out base object first. */
570 if (e->delta) {
571 offset = write_one(f, e->delta, offset);
572 if (!offset)
573 return 0;
576 e->idx.offset = offset;
577 size = write_object(f, e, offset);
578 if (!size) {
579 e->idx.offset = 0;
580 return 0;
582 written_list[nr_written++] = e;
584 /* make sure off_t is sufficiently large not to wrap */
585 if (offset > offset + size)
586 die("pack too large for current definition of off_t");
587 return offset + size;
590 static int open_object_dir_tmp(const char *path)
592 snprintf(tmpname, sizeof(tmpname), "%s/%s", get_object_directory(), path);
593 return xmkstemp(tmpname);
596 /* forward declaration for write_pack_file */
597 static int adjust_perm(const char *path, mode_t mode);
599 static void write_pack_file(void)
601 uint32_t i = 0, j;
602 struct sha1file *f;
603 off_t offset, offset_one, last_obj_offset = 0;
604 struct pack_header hdr;
605 int do_progress = progress >> pack_to_stdout;
606 uint32_t nr_remaining = nr_result;
608 if (do_progress)
609 start_progress(&progress_state, "Writing %u objects...", "", nr_result);
610 written_list = xmalloc(nr_objects * sizeof(struct object_entry *));
612 do {
613 unsigned char sha1[20];
615 if (pack_to_stdout) {
616 f = sha1fd(1, "<stdout>");
617 } else {
618 int fd = open_object_dir_tmp("tmp_pack_XXXXXX");
619 pack_tmp_name = xstrdup(tmpname);
620 f = sha1fd(fd, pack_tmp_name);
623 hdr.hdr_signature = htonl(PACK_SIGNATURE);
624 hdr.hdr_version = htonl(PACK_VERSION);
625 hdr.hdr_entries = htonl(nr_remaining);
626 sha1write(f, &hdr, sizeof(hdr));
627 offset = sizeof(hdr);
628 nr_written = 0;
629 for (; i < nr_objects; i++) {
630 last_obj_offset = offset;
631 offset_one = write_one(f, objects + i, offset);
632 if (!offset_one)
633 break;
634 offset = offset_one;
635 if (do_progress)
636 display_progress(&progress_state, written);
640 * Did we write the wrong # entries in the header?
641 * If so, rewrite it like in fast-import
643 if (pack_to_stdout || nr_written == nr_remaining) {
644 sha1close(f, sha1, 1);
645 } else {
646 sha1close(f, sha1, 0);
647 fixup_pack_header_footer(f->fd, sha1, pack_tmp_name, nr_written);
648 close(f->fd);
651 if (!pack_to_stdout) {
652 mode_t mode = umask(0);
654 umask(mode);
655 mode = 0444 & ~mode;
657 idx_tmp_name = write_idx_file(NULL,
658 (struct pack_idx_entry **) written_list, nr_written, sha1);
659 snprintf(tmpname, sizeof(tmpname), "%s-%s.pack",
660 base_name, sha1_to_hex(sha1));
661 if (adjust_perm(pack_tmp_name, mode))
662 die("unable to make temporary pack file readable: %s",
663 strerror(errno));
664 if (rename(pack_tmp_name, tmpname))
665 die("unable to rename temporary pack file: %s",
666 strerror(errno));
667 snprintf(tmpname, sizeof(tmpname), "%s-%s.idx",
668 base_name, sha1_to_hex(sha1));
669 if (adjust_perm(idx_tmp_name, mode))
670 die("unable to make temporary index file readable: %s",
671 strerror(errno));
672 if (rename(idx_tmp_name, tmpname))
673 die("unable to rename temporary index file: %s",
674 strerror(errno));
675 puts(sha1_to_hex(sha1));
678 /* mark written objects as written to previous pack */
679 for (j = 0; j < nr_written; j++) {
680 written_list[j]->idx.offset = (off_t)-1;
682 nr_remaining -= nr_written;
683 } while (nr_remaining && i < nr_objects);
685 free(written_list);
686 if (do_progress)
687 stop_progress(&progress_state);
688 if (written != nr_result)
689 die("wrote %u objects while expecting %u", written, nr_result);
691 * We have scanned through [0 ... i). Since we have written
692 * the correct number of objects, the remaining [i ... nr_objects)
693 * items must be either already written (due to out-of-order delta base)
694 * or a preferred base. Count those which are neither and complain if any.
696 for (j = 0; i < nr_objects; i++) {
697 struct object_entry *e = objects + i;
698 j += !e->idx.offset && !e->preferred_base;
700 if (j)
701 die("wrote %u objects as expected but %u unwritten", written, j);
704 static int locate_object_entry_hash(const unsigned char *sha1)
706 int i;
707 unsigned int ui;
708 memcpy(&ui, sha1, sizeof(unsigned int));
709 i = ui % object_ix_hashsz;
710 while (0 < object_ix[i]) {
711 if (!hashcmp(sha1, objects[object_ix[i] - 1].idx.sha1))
712 return i;
713 if (++i == object_ix_hashsz)
714 i = 0;
716 return -1 - i;
719 static struct object_entry *locate_object_entry(const unsigned char *sha1)
721 int i;
723 if (!object_ix_hashsz)
724 return NULL;
726 i = locate_object_entry_hash(sha1);
727 if (0 <= i)
728 return &objects[object_ix[i]-1];
729 return NULL;
732 static void rehash_objects(void)
734 uint32_t i;
735 struct object_entry *oe;
737 object_ix_hashsz = nr_objects * 3;
738 if (object_ix_hashsz < 1024)
739 object_ix_hashsz = 1024;
740 object_ix = xrealloc(object_ix, sizeof(int) * object_ix_hashsz);
741 memset(object_ix, 0, sizeof(int) * object_ix_hashsz);
742 for (i = 0, oe = objects; i < nr_objects; i++, oe++) {
743 int ix = locate_object_entry_hash(oe->idx.sha1);
744 if (0 <= ix)
745 continue;
746 ix = -1 - ix;
747 object_ix[ix] = i + 1;
751 static unsigned name_hash(const char *name)
753 unsigned char c;
754 unsigned hash = 0;
756 if (!name)
757 return 0;
760 * This effectively just creates a sortable number from the
761 * last sixteen non-whitespace characters. Last characters
762 * count "most", so things that end in ".c" sort together.
764 while ((c = *name++) != 0) {
765 if (isspace(c))
766 continue;
767 hash = (hash >> 2) + (c << 24);
769 return hash;
772 static void setup_delta_attr_check(struct git_attr_check *check)
774 static struct git_attr *attr_delta;
776 if (!attr_delta)
777 attr_delta = git_attr("delta", 5);
779 check[0].attr = attr_delta;
782 static int no_try_delta(const char *path)
784 struct git_attr_check check[1];
786 setup_delta_attr_check(check);
787 if (git_checkattr(path, ARRAY_SIZE(check), check))
788 return 0;
789 if (ATTR_FALSE(check->value))
790 return 1;
791 return 0;
794 static int add_object_entry(const unsigned char *sha1, enum object_type type,
795 const char *name, int exclude)
797 struct object_entry *entry;
798 struct packed_git *p, *found_pack = NULL;
799 off_t found_offset = 0;
800 int ix;
801 unsigned hash = name_hash(name);
803 ix = nr_objects ? locate_object_entry_hash(sha1) : -1;
804 if (ix >= 0) {
805 if (exclude) {
806 entry = objects + object_ix[ix] - 1;
807 if (!entry->preferred_base)
808 nr_result--;
809 entry->preferred_base = 1;
811 return 0;
814 for (p = packed_git; p; p = p->next) {
815 off_t offset = find_pack_entry_one(sha1, p);
816 if (offset) {
817 if (!found_pack) {
818 found_offset = offset;
819 found_pack = p;
821 if (exclude)
822 break;
823 if (incremental)
824 return 0;
825 if (local && !p->pack_local)
826 return 0;
830 if (nr_objects >= nr_alloc) {
831 nr_alloc = (nr_alloc + 1024) * 3 / 2;
832 objects = xrealloc(objects, nr_alloc * sizeof(*entry));
835 entry = objects + nr_objects++;
836 memset(entry, 0, sizeof(*entry));
837 hashcpy(entry->idx.sha1, sha1);
838 entry->hash = hash;
839 if (type)
840 entry->type = type;
841 if (exclude)
842 entry->preferred_base = 1;
843 else
844 nr_result++;
845 if (found_pack) {
846 entry->in_pack = found_pack;
847 entry->in_pack_offset = found_offset;
850 if (object_ix_hashsz * 3 <= nr_objects * 4)
851 rehash_objects();
852 else
853 object_ix[-1 - ix] = nr_objects;
855 if (progress)
856 display_progress(&progress_state, nr_objects);
858 if (name && no_try_delta(name))
859 entry->no_try_delta = 1;
861 return 1;
864 struct pbase_tree_cache {
865 unsigned char sha1[20];
866 int ref;
867 int temporary;
868 void *tree_data;
869 unsigned long tree_size;
872 static struct pbase_tree_cache *(pbase_tree_cache[256]);
873 static int pbase_tree_cache_ix(const unsigned char *sha1)
875 return sha1[0] % ARRAY_SIZE(pbase_tree_cache);
877 static int pbase_tree_cache_ix_incr(int ix)
879 return (ix+1) % ARRAY_SIZE(pbase_tree_cache);
882 static struct pbase_tree {
883 struct pbase_tree *next;
884 /* This is a phony "cache" entry; we are not
885 * going to evict it nor find it through _get()
886 * mechanism -- this is for the toplevel node that
887 * would almost always change with any commit.
889 struct pbase_tree_cache pcache;
890 } *pbase_tree;
892 static struct pbase_tree_cache *pbase_tree_get(const unsigned char *sha1)
894 struct pbase_tree_cache *ent, *nent;
895 void *data;
896 unsigned long size;
897 enum object_type type;
898 int neigh;
899 int my_ix = pbase_tree_cache_ix(sha1);
900 int available_ix = -1;
902 /* pbase-tree-cache acts as a limited hashtable.
903 * your object will be found at your index or within a few
904 * slots after that slot if it is cached.
906 for (neigh = 0; neigh < 8; neigh++) {
907 ent = pbase_tree_cache[my_ix];
908 if (ent && !hashcmp(ent->sha1, sha1)) {
909 ent->ref++;
910 return ent;
912 else if (((available_ix < 0) && (!ent || !ent->ref)) ||
913 ((0 <= available_ix) &&
914 (!ent && pbase_tree_cache[available_ix])))
915 available_ix = my_ix;
916 if (!ent)
917 break;
918 my_ix = pbase_tree_cache_ix_incr(my_ix);
921 /* Did not find one. Either we got a bogus request or
922 * we need to read and perhaps cache.
924 data = read_sha1_file(sha1, &type, &size);
925 if (!data)
926 return NULL;
927 if (type != OBJ_TREE) {
928 free(data);
929 return NULL;
932 /* We need to either cache or return a throwaway copy */
934 if (available_ix < 0)
935 ent = NULL;
936 else {
937 ent = pbase_tree_cache[available_ix];
938 my_ix = available_ix;
941 if (!ent) {
942 nent = xmalloc(sizeof(*nent));
943 nent->temporary = (available_ix < 0);
945 else {
946 /* evict and reuse */
947 free(ent->tree_data);
948 nent = ent;
950 hashcpy(nent->sha1, sha1);
951 nent->tree_data = data;
952 nent->tree_size = size;
953 nent->ref = 1;
954 if (!nent->temporary)
955 pbase_tree_cache[my_ix] = nent;
956 return nent;
959 static void pbase_tree_put(struct pbase_tree_cache *cache)
961 if (!cache->temporary) {
962 cache->ref--;
963 return;
965 free(cache->tree_data);
966 free(cache);
969 static int name_cmp_len(const char *name)
971 int i;
972 for (i = 0; name[i] && name[i] != '\n' && name[i] != '/'; i++)
974 return i;
977 static void add_pbase_object(struct tree_desc *tree,
978 const char *name,
979 int cmplen,
980 const char *fullname)
982 struct name_entry entry;
983 int cmp;
985 while (tree_entry(tree,&entry)) {
986 if (S_ISGITLINK(entry.mode))
987 continue;
988 cmp = tree_entry_len(entry.path, entry.sha1) != cmplen ? 1 :
989 memcmp(name, entry.path, cmplen);
990 if (cmp > 0)
991 continue;
992 if (cmp < 0)
993 return;
994 if (name[cmplen] != '/') {
995 add_object_entry(entry.sha1,
996 S_ISDIR(entry.mode) ? OBJ_TREE : OBJ_BLOB,
997 fullname, 1);
998 return;
1000 if (S_ISDIR(entry.mode)) {
1001 struct tree_desc sub;
1002 struct pbase_tree_cache *tree;
1003 const char *down = name+cmplen+1;
1004 int downlen = name_cmp_len(down);
1006 tree = pbase_tree_get(entry.sha1);
1007 if (!tree)
1008 return;
1009 init_tree_desc(&sub, tree->tree_data, tree->tree_size);
1011 add_pbase_object(&sub, down, downlen, fullname);
1012 pbase_tree_put(tree);
1017 static unsigned *done_pbase_paths;
1018 static int done_pbase_paths_num;
1019 static int done_pbase_paths_alloc;
1020 static int done_pbase_path_pos(unsigned hash)
1022 int lo = 0;
1023 int hi = done_pbase_paths_num;
1024 while (lo < hi) {
1025 int mi = (hi + lo) / 2;
1026 if (done_pbase_paths[mi] == hash)
1027 return mi;
1028 if (done_pbase_paths[mi] < hash)
1029 hi = mi;
1030 else
1031 lo = mi + 1;
1033 return -lo-1;
1036 static int check_pbase_path(unsigned hash)
1038 int pos = (!done_pbase_paths) ? -1 : done_pbase_path_pos(hash);
1039 if (0 <= pos)
1040 return 1;
1041 pos = -pos - 1;
1042 if (done_pbase_paths_alloc <= done_pbase_paths_num) {
1043 done_pbase_paths_alloc = alloc_nr(done_pbase_paths_alloc);
1044 done_pbase_paths = xrealloc(done_pbase_paths,
1045 done_pbase_paths_alloc *
1046 sizeof(unsigned));
1048 done_pbase_paths_num++;
1049 if (pos < done_pbase_paths_num)
1050 memmove(done_pbase_paths + pos + 1,
1051 done_pbase_paths + pos,
1052 (done_pbase_paths_num - pos - 1) * sizeof(unsigned));
1053 done_pbase_paths[pos] = hash;
1054 return 0;
1057 static void add_preferred_base_object(const char *name)
1059 struct pbase_tree *it;
1060 int cmplen;
1061 unsigned hash = name_hash(name);
1063 if (!num_preferred_base || check_pbase_path(hash))
1064 return;
1066 cmplen = name_cmp_len(name);
1067 for (it = pbase_tree; it; it = it->next) {
1068 if (cmplen == 0) {
1069 add_object_entry(it->pcache.sha1, OBJ_TREE, NULL, 1);
1071 else {
1072 struct tree_desc tree;
1073 init_tree_desc(&tree, it->pcache.tree_data, it->pcache.tree_size);
1074 add_pbase_object(&tree, name, cmplen, name);
1079 static void add_preferred_base(unsigned char *sha1)
1081 struct pbase_tree *it;
1082 void *data;
1083 unsigned long size;
1084 unsigned char tree_sha1[20];
1086 if (window <= num_preferred_base++)
1087 return;
1089 data = read_object_with_reference(sha1, tree_type, &size, tree_sha1);
1090 if (!data)
1091 return;
1093 for (it = pbase_tree; it; it = it->next) {
1094 if (!hashcmp(it->pcache.sha1, tree_sha1)) {
1095 free(data);
1096 return;
1100 it = xcalloc(1, sizeof(*it));
1101 it->next = pbase_tree;
1102 pbase_tree = it;
1104 hashcpy(it->pcache.sha1, tree_sha1);
1105 it->pcache.tree_data = data;
1106 it->pcache.tree_size = size;
1109 static void check_object(struct object_entry *entry)
1111 if (entry->in_pack) {
1112 struct packed_git *p = entry->in_pack;
1113 struct pack_window *w_curs = NULL;
1114 const unsigned char *base_ref = NULL;
1115 struct object_entry *base_entry;
1116 unsigned long used, used_0;
1117 unsigned int avail;
1118 off_t ofs;
1119 unsigned char *buf, c;
1121 buf = use_pack(p, &w_curs, entry->in_pack_offset, &avail);
1124 * We want in_pack_type even if we do not reuse delta
1125 * since non-delta representations could still be reused.
1127 used = unpack_object_header_gently(buf, avail,
1128 &entry->in_pack_type,
1129 &entry->size);
1132 * Determine if this is a delta and if so whether we can
1133 * reuse it or not. Otherwise let's find out as cheaply as
1134 * possible what the actual type and size for this object is.
1136 switch (entry->in_pack_type) {
1137 default:
1138 /* Not a delta hence we've already got all we need. */
1139 entry->type = entry->in_pack_type;
1140 entry->in_pack_header_size = used;
1141 unuse_pack(&w_curs);
1142 return;
1143 case OBJ_REF_DELTA:
1144 if (!no_reuse_delta && !entry->preferred_base)
1145 base_ref = use_pack(p, &w_curs,
1146 entry->in_pack_offset + used, NULL);
1147 entry->in_pack_header_size = used + 20;
1148 break;
1149 case OBJ_OFS_DELTA:
1150 buf = use_pack(p, &w_curs,
1151 entry->in_pack_offset + used, NULL);
1152 used_0 = 0;
1153 c = buf[used_0++];
1154 ofs = c & 127;
1155 while (c & 128) {
1156 ofs += 1;
1157 if (!ofs || MSB(ofs, 7))
1158 die("delta base offset overflow in pack for %s",
1159 sha1_to_hex(entry->idx.sha1));
1160 c = buf[used_0++];
1161 ofs = (ofs << 7) + (c & 127);
1163 if (ofs >= entry->in_pack_offset)
1164 die("delta base offset out of bound for %s",
1165 sha1_to_hex(entry->idx.sha1));
1166 ofs = entry->in_pack_offset - ofs;
1167 if (!no_reuse_delta && !entry->preferred_base)
1168 base_ref = find_packed_object_name(p, ofs);
1169 entry->in_pack_header_size = used + used_0;
1170 break;
1173 if (base_ref && (base_entry = locate_object_entry(base_ref))) {
1175 * If base_ref was set above that means we wish to
1176 * reuse delta data, and we even found that base
1177 * in the list of objects we want to pack. Goodie!
1179 * Depth value does not matter - find_deltas() will
1180 * never consider reused delta as the base object to
1181 * deltify other objects against, in order to avoid
1182 * circular deltas.
1184 entry->type = entry->in_pack_type;
1185 entry->delta = base_entry;
1186 entry->delta_sibling = base_entry->delta_child;
1187 base_entry->delta_child = entry;
1188 unuse_pack(&w_curs);
1189 return;
1192 if (entry->type) {
1194 * This must be a delta and we already know what the
1195 * final object type is. Let's extract the actual
1196 * object size from the delta header.
1198 entry->size = get_size_from_delta(p, &w_curs,
1199 entry->in_pack_offset + entry->in_pack_header_size);
1200 unuse_pack(&w_curs);
1201 return;
1205 * No choice but to fall back to the recursive delta walk
1206 * with sha1_object_info() to find about the object type
1207 * at this point...
1209 unuse_pack(&w_curs);
1212 entry->type = sha1_object_info(entry->idx.sha1, &entry->size);
1213 if (entry->type < 0)
1214 die("unable to get type of object %s",
1215 sha1_to_hex(entry->idx.sha1));
1218 static int pack_offset_sort(const void *_a, const void *_b)
1220 const struct object_entry *a = *(struct object_entry **)_a;
1221 const struct object_entry *b = *(struct object_entry **)_b;
1223 /* avoid filesystem trashing with loose objects */
1224 if (!a->in_pack && !b->in_pack)
1225 return hashcmp(a->idx.sha1, b->idx.sha1);
1227 if (a->in_pack < b->in_pack)
1228 return -1;
1229 if (a->in_pack > b->in_pack)
1230 return 1;
1231 return a->in_pack_offset < b->in_pack_offset ? -1 :
1232 (a->in_pack_offset > b->in_pack_offset);
1235 static void get_object_details(void)
1237 uint32_t i;
1238 struct object_entry **sorted_by_offset;
1240 sorted_by_offset = xcalloc(nr_objects, sizeof(struct object_entry *));
1241 for (i = 0; i < nr_objects; i++)
1242 sorted_by_offset[i] = objects + i;
1243 qsort(sorted_by_offset, nr_objects, sizeof(*sorted_by_offset), pack_offset_sort);
1245 prepare_pack_ix();
1246 for (i = 0; i < nr_objects; i++)
1247 check_object(sorted_by_offset[i]);
1248 free(sorted_by_offset);
1251 static int type_size_sort(const void *_a, const void *_b)
1253 const struct object_entry *a = *(struct object_entry **)_a;
1254 const struct object_entry *b = *(struct object_entry **)_b;
1256 if (a->type < b->type)
1257 return -1;
1258 if (a->type > b->type)
1259 return 1;
1260 if (a->hash < b->hash)
1261 return -1;
1262 if (a->hash > b->hash)
1263 return 1;
1264 if (a->preferred_base < b->preferred_base)
1265 return -1;
1266 if (a->preferred_base > b->preferred_base)
1267 return 1;
1268 if (a->size < b->size)
1269 return -1;
1270 if (a->size > b->size)
1271 return 1;
1272 return a > b ? -1 : (a < b); /* newest last */
1275 struct unpacked {
1276 struct object_entry *entry;
1277 void *data;
1278 struct delta_index *index;
1279 unsigned depth;
1282 static int delta_cacheable(unsigned long src_size, unsigned long trg_size,
1283 unsigned long delta_size)
1285 if (max_delta_cache_size && delta_cache_size + delta_size > max_delta_cache_size)
1286 return 0;
1288 if (delta_size < cache_max_small_delta_size)
1289 return 1;
1291 /* cache delta, if objects are large enough compared to delta size */
1292 if ((src_size >> 20) + (trg_size >> 21) > (delta_size >> 10))
1293 return 1;
1295 return 0;
1298 #ifdef THREADED_DELTA_SEARCH
1300 static pthread_mutex_t read_mutex = PTHREAD_MUTEX_INITIALIZER;
1301 #define read_lock() pthread_mutex_lock(&read_mutex)
1302 #define read_unlock() pthread_mutex_unlock(&read_mutex)
1304 static pthread_mutex_t cache_mutex = PTHREAD_MUTEX_INITIALIZER;
1305 #define cache_lock() pthread_mutex_lock(&cache_mutex)
1306 #define cache_unlock() pthread_mutex_unlock(&cache_mutex)
1308 static pthread_mutex_t progress_mutex = PTHREAD_MUTEX_INITIALIZER;
1309 #define progress_lock() pthread_mutex_lock(&progress_mutex)
1310 #define progress_unlock() pthread_mutex_unlock(&progress_mutex)
1312 #else
1314 #define read_lock() (void)0
1315 #define read_unlock() (void)0
1316 #define cache_lock() (void)0
1317 #define cache_unlock() (void)0
1318 #define progress_lock() (void)0
1319 #define progress_unlock() (void)0
1321 #endif
1324 * We search for deltas _backwards_ in a list sorted by type and
1325 * by size, so that we see progressively smaller and smaller files.
1326 * That's because we prefer deltas to be from the bigger file
1327 * to the smaller - deletes are potentially cheaper, but perhaps
1328 * more importantly, the bigger file is likely the more recent
1329 * one.
1331 static int try_delta(struct unpacked *trg, struct unpacked *src,
1332 unsigned max_depth, unsigned long *mem_usage)
1334 struct object_entry *trg_entry = trg->entry;
1335 struct object_entry *src_entry = src->entry;
1336 unsigned long trg_size, src_size, delta_size, sizediff, max_size, sz;
1337 unsigned ref_depth;
1338 enum object_type type;
1339 void *delta_buf;
1341 /* Don't bother doing diffs between different types */
1342 if (trg_entry->type != src_entry->type)
1343 return -1;
1346 * We do not bother to try a delta that we discarded
1347 * on an earlier try, but only when reusing delta data.
1349 if (!no_reuse_delta && trg_entry->in_pack &&
1350 trg_entry->in_pack == src_entry->in_pack &&
1351 trg_entry->in_pack_type != OBJ_REF_DELTA &&
1352 trg_entry->in_pack_type != OBJ_OFS_DELTA)
1353 return 0;
1355 /* Let's not bust the allowed depth. */
1356 if (src->depth >= max_depth)
1357 return 0;
1359 /* Now some size filtering heuristics. */
1360 trg_size = trg_entry->size;
1361 if (!trg_entry->delta) {
1362 max_size = trg_size/2 - 20;
1363 ref_depth = 1;
1364 } else {
1365 max_size = trg_entry->delta_size;
1366 ref_depth = trg->depth;
1368 max_size = max_size * (max_depth - src->depth) /
1369 (max_depth - ref_depth + 1);
1370 if (max_size == 0)
1371 return 0;
1372 src_size = src_entry->size;
1373 sizediff = src_size < trg_size ? trg_size - src_size : 0;
1374 if (sizediff >= max_size)
1375 return 0;
1376 if (trg_size < src_size / 32)
1377 return 0;
1379 /* Load data if not already done */
1380 if (!trg->data) {
1381 read_lock();
1382 trg->data = read_sha1_file(trg_entry->idx.sha1, &type, &sz);
1383 read_unlock();
1384 if (!trg->data)
1385 die("object %s cannot be read",
1386 sha1_to_hex(trg_entry->idx.sha1));
1387 if (sz != trg_size)
1388 die("object %s inconsistent object length (%lu vs %lu)",
1389 sha1_to_hex(trg_entry->idx.sha1), sz, trg_size);
1390 *mem_usage += sz;
1392 if (!src->data) {
1393 read_lock();
1394 src->data = read_sha1_file(src_entry->idx.sha1, &type, &sz);
1395 read_unlock();
1396 if (!src->data)
1397 die("object %s cannot be read",
1398 sha1_to_hex(src_entry->idx.sha1));
1399 if (sz != src_size)
1400 die("object %s inconsistent object length (%lu vs %lu)",
1401 sha1_to_hex(src_entry->idx.sha1), sz, src_size);
1402 *mem_usage += sz;
1404 if (!src->index) {
1405 src->index = create_delta_index(src->data, src_size);
1406 if (!src->index) {
1407 static int warned = 0;
1408 if (!warned++)
1409 warning("suboptimal pack - out of memory");
1410 return 0;
1412 *mem_usage += sizeof_delta_index(src->index);
1415 delta_buf = create_delta(src->index, trg->data, trg_size, &delta_size, max_size);
1416 if (!delta_buf)
1417 return 0;
1419 if (trg_entry->delta) {
1420 /* Prefer only shallower same-sized deltas. */
1421 if (delta_size == trg_entry->delta_size &&
1422 src->depth + 1 >= trg->depth) {
1423 free(delta_buf);
1424 return 0;
1428 trg_entry->delta = src_entry;
1429 trg_entry->delta_size = delta_size;
1430 trg->depth = src->depth + 1;
1433 * Handle memory allocation outside of the cache
1434 * accounting lock. Compiler will optimize the strangeness
1435 * away when THREADED_DELTA_SEARCH is not defined.
1437 if (trg_entry->delta_data)
1438 free(trg_entry->delta_data);
1439 cache_lock();
1440 if (trg_entry->delta_data) {
1441 delta_cache_size -= trg_entry->delta_size;
1442 trg_entry->delta_data = NULL;
1444 if (delta_cacheable(src_size, trg_size, delta_size)) {
1445 delta_cache_size += trg_entry->delta_size;
1446 cache_unlock();
1447 trg_entry->delta_data = xrealloc(delta_buf, delta_size);
1448 } else {
1449 cache_unlock();
1450 free(delta_buf);
1453 return 1;
1456 static unsigned int check_delta_limit(struct object_entry *me, unsigned int n)
1458 struct object_entry *child = me->delta_child;
1459 unsigned int m = n;
1460 while (child) {
1461 unsigned int c = check_delta_limit(child, n + 1);
1462 if (m < c)
1463 m = c;
1464 child = child->delta_sibling;
1466 return m;
1469 static unsigned long free_unpacked(struct unpacked *n)
1471 unsigned long freed_mem = sizeof_delta_index(n->index);
1472 free_delta_index(n->index);
1473 n->index = NULL;
1474 if (n->data) {
1475 freed_mem += n->entry->size;
1476 free(n->data);
1477 n->data = NULL;
1479 n->entry = NULL;
1480 n->depth = 0;
1481 return freed_mem;
1484 static void find_deltas(struct object_entry **list, unsigned list_size,
1485 int window, int depth, unsigned *processed)
1487 uint32_t i = list_size, idx = 0, count = 0;
1488 unsigned int array_size = window * sizeof(struct unpacked);
1489 struct unpacked *array;
1490 unsigned long mem_usage = 0;
1492 array = xmalloc(array_size);
1493 memset(array, 0, array_size);
1495 do {
1496 struct object_entry *entry = list[--i];
1497 struct unpacked *n = array + idx;
1498 int j, max_depth, best_base = -1;
1500 mem_usage -= free_unpacked(n);
1501 n->entry = entry;
1503 while (window_memory_limit &&
1504 mem_usage > window_memory_limit &&
1505 count > 1) {
1506 uint32_t tail = (idx + window - count) % window;
1507 mem_usage -= free_unpacked(array + tail);
1508 count--;
1511 /* We do not compute delta to *create* objects we are not
1512 * going to pack.
1514 if (entry->preferred_base)
1515 goto next;
1517 progress_lock();
1518 (*processed)++;
1519 if (progress)
1520 display_progress(&progress_state, *processed);
1521 progress_unlock();
1524 * If the current object is at pack edge, take the depth the
1525 * objects that depend on the current object into account
1526 * otherwise they would become too deep.
1528 max_depth = depth;
1529 if (entry->delta_child) {
1530 max_depth -= check_delta_limit(entry, 0);
1531 if (max_depth <= 0)
1532 goto next;
1535 j = window;
1536 while (--j > 0) {
1537 int ret;
1538 uint32_t other_idx = idx + j;
1539 struct unpacked *m;
1540 if (other_idx >= window)
1541 other_idx -= window;
1542 m = array + other_idx;
1543 if (!m->entry)
1544 break;
1545 ret = try_delta(n, m, max_depth, &mem_usage);
1546 if (ret < 0)
1547 break;
1548 else if (ret > 0)
1549 best_base = other_idx;
1552 /* if we made n a delta, and if n is already at max
1553 * depth, leaving it in the window is pointless. we
1554 * should evict it first.
1556 if (entry->delta && depth <= n->depth)
1557 continue;
1560 * Move the best delta base up in the window, after the
1561 * currently deltified object, to keep it longer. It will
1562 * be the first base object to be attempted next.
1564 if (entry->delta) {
1565 struct unpacked swap = array[best_base];
1566 int dist = (window + idx - best_base) % window;
1567 int dst = best_base;
1568 while (dist--) {
1569 int src = (dst + 1) % window;
1570 array[dst] = array[src];
1571 dst = src;
1573 array[dst] = swap;
1576 next:
1577 idx++;
1578 if (count + 1 < window)
1579 count++;
1580 if (idx >= window)
1581 idx = 0;
1582 } while (i > 0);
1584 for (i = 0; i < window; ++i) {
1585 free_delta_index(array[i].index);
1586 free(array[i].data);
1588 free(array);
1591 #ifdef THREADED_DELTA_SEARCH
1593 struct thread_params {
1594 pthread_t thread;
1595 struct object_entry **list;
1596 unsigned list_size;
1597 int window;
1598 int depth;
1599 unsigned *processed;
1602 static pthread_mutex_t data_request = PTHREAD_MUTEX_INITIALIZER;
1603 static pthread_mutex_t data_ready = PTHREAD_MUTEX_INITIALIZER;
1604 static pthread_mutex_t data_provider = PTHREAD_MUTEX_INITIALIZER;
1605 static struct thread_params *data_requester;
1607 static void *threaded_find_deltas(void *arg)
1609 struct thread_params *me = arg;
1611 for (;;) {
1612 pthread_mutex_lock(&data_request);
1613 data_requester = me;
1614 pthread_mutex_unlock(&data_provider);
1615 pthread_mutex_lock(&data_ready);
1616 pthread_mutex_unlock(&data_request);
1618 if (!me->list_size)
1619 return NULL;
1621 find_deltas(me->list, me->list_size,
1622 me->window, me->depth, me->processed);
1626 static void ll_find_deltas(struct object_entry **list, unsigned list_size,
1627 int window, int depth, unsigned *processed)
1629 struct thread_params *target, p[delta_search_threads];
1630 int i, ret;
1631 unsigned chunk_size;
1633 if (delta_search_threads <= 1) {
1634 find_deltas(list, list_size, window, depth, processed);
1635 return;
1638 pthread_mutex_lock(&data_provider);
1639 pthread_mutex_lock(&data_ready);
1641 for (i = 0; i < delta_search_threads; i++) {
1642 p[i].window = window;
1643 p[i].depth = depth;
1644 p[i].processed = processed;
1645 ret = pthread_create(&p[i].thread, NULL,
1646 threaded_find_deltas, &p[i]);
1647 if (ret)
1648 die("unable to create thread: %s", strerror(ret));
1651 /* this should be auto-tuned somehow */
1652 chunk_size = window * 1000;
1654 do {
1655 unsigned sublist_size = chunk_size;
1656 if (sublist_size > list_size)
1657 sublist_size = list_size;
1659 /* try to split chunks on "path" boundaries */
1660 while (sublist_size < list_size && list[sublist_size]->hash &&
1661 list[sublist_size]->hash == list[sublist_size-1]->hash)
1662 sublist_size++;
1664 pthread_mutex_lock(&data_provider);
1665 target = data_requester;
1666 target->list = list;
1667 target->list_size = sublist_size;
1668 pthread_mutex_unlock(&data_ready);
1670 list += sublist_size;
1671 list_size -= sublist_size;
1672 if (!sublist_size) {
1673 pthread_join(target->thread, NULL);
1674 i--;
1676 } while (i);
1679 #else
1680 #define ll_find_deltas find_deltas
1681 #endif
1683 static void prepare_pack(int window, int depth)
1685 struct object_entry **delta_list;
1686 uint32_t i, n, nr_deltas;
1688 get_object_details();
1690 if (!nr_objects || !window || !depth)
1691 return;
1693 delta_list = xmalloc(nr_objects * sizeof(*delta_list));
1694 nr_deltas = n = 0;
1696 for (i = 0; i < nr_objects; i++) {
1697 struct object_entry *entry = objects + i;
1699 if (entry->delta)
1700 /* This happens if we decided to reuse existing
1701 * delta from a pack. "!no_reuse_delta &&" is implied.
1703 continue;
1705 if (entry->size < 50)
1706 continue;
1708 if (entry->no_try_delta)
1709 continue;
1711 if (!entry->preferred_base)
1712 nr_deltas++;
1714 delta_list[n++] = entry;
1717 if (nr_deltas) {
1718 unsigned nr_done = 0;
1719 if (progress)
1720 start_progress(&progress_state,
1721 "Deltifying %u objects...", "",
1722 nr_deltas);
1723 qsort(delta_list, n, sizeof(*delta_list), type_size_sort);
1724 ll_find_deltas(delta_list, n, window+1, depth, &nr_done);
1725 if (progress)
1726 stop_progress(&progress_state);
1727 if (nr_done != nr_deltas)
1728 die("inconsistency with delta count");
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 start_progress(&progress_state, "Generating pack...",
2139 "Counting objects: ", 0);
2140 if (!use_internal_rev_list)
2141 read_object_list_from_stdin();
2142 else {
2143 rp_av[rp_ac] = NULL;
2144 get_object_list(rp_ac, rp_av);
2146 if (progress) {
2147 stop_progress(&progress_state);
2148 fprintf(stderr, "Done counting %u objects.\n", nr_objects);
2151 if (non_empty && !nr_result)
2152 return 0;
2153 if (progress && (nr_objects != nr_result))
2154 fprintf(stderr, "Result has %u objects.\n", nr_result);
2155 if (nr_result)
2156 prepare_pack(window, depth);
2157 write_pack_file();
2158 if (progress)
2159 fprintf(stderr, "Total %u (delta %u), reused %u (delta %u)\n",
2160 written, written_delta, reused, reused_delta);
2161 return 0;