1#include"builtin.h" 2#include"cache.h" 3#include"config.h" 4#include"attr.h" 5#include"object.h" 6#include"blob.h" 7#include"commit.h" 8#include"tag.h" 9#include"tree.h" 10#include"delta.h" 11#include"pack.h" 12#include"pack-revindex.h" 13#include"csum-file.h" 14#include"tree-walk.h" 15#include"diff.h" 16#include"revision.h" 17#include"list-objects.h" 18#include"list-objects-filter.h" 19#include"list-objects-filter-options.h" 20#include"pack-objects.h" 21#include"progress.h" 22#include"refs.h" 23#include"streaming.h" 24#include"thread-utils.h" 25#include"pack-bitmap.h" 26#include"reachable.h" 27#include"sha1-array.h" 28#include"argv-array.h" 29#include"list.h" 30#include"packfile.h" 31 32static const char*pack_usage[] = { 33N_("git pack-objects --stdout [<options>...] [< <ref-list> | < <object-list>]"), 34N_("git pack-objects [<options>...] <base-name> [< <ref-list> | < <object-list>]"), 35 NULL 36}; 37 38/* 39 * Objects we are going to pack are collected in the `to_pack` structure. 40 * It contains an array (dynamically expanded) of the object data, and a map 41 * that can resolve SHA1s to their position in the array. 42 */ 43static struct packing_data to_pack; 44 45static struct pack_idx_entry **written_list; 46static uint32_t nr_result, nr_written; 47 48static int non_empty; 49static int reuse_delta =1, reuse_object =1; 50static int keep_unreachable, unpack_unreachable, include_tag; 51static timestamp_t unpack_unreachable_expiration; 52static int pack_loose_unreachable; 53static int local; 54static int have_non_local_packs; 55static int incremental; 56static int ignore_packed_keep; 57static int allow_ofs_delta; 58static struct pack_idx_option pack_idx_opts; 59static const char*base_name; 60static int progress =1; 61static int window =10; 62static unsigned long pack_size_limit; 63static int depth =50; 64static int delta_search_threads; 65static int pack_to_stdout; 66static int num_preferred_base; 67static struct progress *progress_state; 68 69static struct packed_git *reuse_packfile; 70static uint32_t reuse_packfile_objects; 71static off_t reuse_packfile_offset; 72 73static int use_bitmap_index_default =1; 74static int use_bitmap_index = -1; 75static int write_bitmap_index; 76static uint16_t write_bitmap_options; 77 78static int exclude_promisor_objects; 79 80static unsigned long delta_cache_size =0; 81static unsigned long max_delta_cache_size =256*1024*1024; 82static unsigned long cache_max_small_delta_size =1000; 83 84static unsigned long window_memory_limit =0; 85 86static struct list_objects_filter_options filter_options; 87 88enum missing_action { 89 MA_ERROR =0,/* fail if any missing objects are encountered */ 90 MA_ALLOW_ANY,/* silently allow ALL missing objects */ 91 MA_ALLOW_PROMISOR,/* silently allow all missing PROMISOR objects */ 92}; 93static enum missing_action arg_missing_action; 94static show_object_fn fn_show_object; 95 96/* 97 * stats 98 */ 99static uint32_t written, written_delta; 100static uint32_t reused, reused_delta; 101 102/* 103 * Indexed commits 104 */ 105static struct commit **indexed_commits; 106static unsigned int indexed_commits_nr; 107static unsigned int indexed_commits_alloc; 108 109static voidindex_commit_for_bitmap(struct commit *commit) 110{ 111if(indexed_commits_nr >= indexed_commits_alloc) { 112 indexed_commits_alloc = (indexed_commits_alloc +32) *2; 113REALLOC_ARRAY(indexed_commits, indexed_commits_alloc); 114} 115 116 indexed_commits[indexed_commits_nr++] = commit; 117} 118 119static void*get_delta(struct object_entry *entry) 120{ 121unsigned long size, base_size, delta_size; 122void*buf, *base_buf, *delta_buf; 123enum object_type type; 124 125 buf =read_object_file(&entry->idx.oid, &type, &size); 126if(!buf) 127die("unable to read%s",oid_to_hex(&entry->idx.oid)); 128 base_buf =read_object_file(&entry->delta->idx.oid, &type, &base_size); 129if(!base_buf) 130die("unable to read%s", 131oid_to_hex(&entry->delta->idx.oid)); 132 delta_buf =diff_delta(base_buf, base_size, 133 buf, size, &delta_size,0); 134if(!delta_buf || delta_size != entry->delta_size) 135die("delta size changed"); 136free(buf); 137free(base_buf); 138return delta_buf; 139} 140 141static unsigned longdo_compress(void**pptr,unsigned long size) 142{ 143 git_zstream stream; 144void*in, *out; 145unsigned long maxsize; 146 147git_deflate_init(&stream, pack_compression_level); 148 maxsize =git_deflate_bound(&stream, size); 149 150 in = *pptr; 151 out =xmalloc(maxsize); 152*pptr = out; 153 154 stream.next_in = in; 155 stream.avail_in = size; 156 stream.next_out = out; 157 stream.avail_out = maxsize; 158while(git_deflate(&stream, Z_FINISH) == Z_OK) 159;/* nothing */ 160git_deflate_end(&stream); 161 162free(in); 163return stream.total_out; 164} 165 166static unsigned longwrite_large_blob_data(struct git_istream *st,struct hashfile *f, 167const struct object_id *oid) 168{ 169 git_zstream stream; 170unsigned char ibuf[1024*16]; 171unsigned char obuf[1024*16]; 172unsigned long olen =0; 173 174git_deflate_init(&stream, pack_compression_level); 175 176for(;;) { 177 ssize_t readlen; 178int zret = Z_OK; 179 readlen =read_istream(st, ibuf,sizeof(ibuf)); 180if(readlen == -1) 181die(_("unable to read%s"),oid_to_hex(oid)); 182 183 stream.next_in = ibuf; 184 stream.avail_in = readlen; 185while((stream.avail_in || readlen ==0) && 186(zret == Z_OK || zret == Z_BUF_ERROR)) { 187 stream.next_out = obuf; 188 stream.avail_out =sizeof(obuf); 189 zret =git_deflate(&stream, readlen ?0: Z_FINISH); 190hashwrite(f, obuf, stream.next_out - obuf); 191 olen += stream.next_out - obuf; 192} 193if(stream.avail_in) 194die(_("deflate error (%d)"), zret); 195if(readlen ==0) { 196if(zret != Z_STREAM_END) 197die(_("deflate error (%d)"), zret); 198break; 199} 200} 201git_deflate_end(&stream); 202return olen; 203} 204 205/* 206 * we are going to reuse the existing object data as is. make 207 * sure it is not corrupt. 208 */ 209static intcheck_pack_inflate(struct packed_git *p, 210struct pack_window **w_curs, 211 off_t offset, 212 off_t len, 213unsigned long expect) 214{ 215 git_zstream stream; 216unsigned char fakebuf[4096], *in; 217int st; 218 219memset(&stream,0,sizeof(stream)); 220git_inflate_init(&stream); 221do{ 222 in =use_pack(p, w_curs, offset, &stream.avail_in); 223 stream.next_in = in; 224 stream.next_out = fakebuf; 225 stream.avail_out =sizeof(fakebuf); 226 st =git_inflate(&stream, Z_FINISH); 227 offset += stream.next_in - in; 228}while(st == Z_OK || st == Z_BUF_ERROR); 229git_inflate_end(&stream); 230return(st == Z_STREAM_END && 231 stream.total_out == expect && 232 stream.total_in == len) ?0: -1; 233} 234 235static voidcopy_pack_data(struct hashfile *f, 236struct packed_git *p, 237struct pack_window **w_curs, 238 off_t offset, 239 off_t len) 240{ 241unsigned char*in; 242unsigned long avail; 243 244while(len) { 245 in =use_pack(p, w_curs, offset, &avail); 246if(avail > len) 247 avail = (unsigned long)len; 248hashwrite(f, in, avail); 249 offset += avail; 250 len -= avail; 251} 252} 253 254/* Return 0 if we will bust the pack-size limit */ 255static unsigned longwrite_no_reuse_object(struct hashfile *f,struct object_entry *entry, 256unsigned long limit,int usable_delta) 257{ 258unsigned long size, datalen; 259unsigned char header[MAX_PACK_OBJECT_HEADER], 260 dheader[MAX_PACK_OBJECT_HEADER]; 261unsigned hdrlen; 262enum object_type type; 263void*buf; 264struct git_istream *st = NULL; 265 266if(!usable_delta) { 267if(entry->type == OBJ_BLOB && 268 entry->size > big_file_threshold && 269(st =open_istream(&entry->idx.oid, &type, &size, NULL)) != NULL) 270 buf = NULL; 271else{ 272 buf =read_object_file(&entry->idx.oid, &type, &size); 273if(!buf) 274die(_("unable to read%s"), 275oid_to_hex(&entry->idx.oid)); 276} 277/* 278 * make sure no cached delta data remains from a 279 * previous attempt before a pack split occurred. 280 */ 281FREE_AND_NULL(entry->delta_data); 282 entry->z_delta_size =0; 283}else if(entry->delta_data) { 284 size = entry->delta_size; 285 buf = entry->delta_data; 286 entry->delta_data = NULL; 287 type = (allow_ofs_delta && entry->delta->idx.offset) ? 288 OBJ_OFS_DELTA : OBJ_REF_DELTA; 289}else{ 290 buf =get_delta(entry); 291 size = entry->delta_size; 292 type = (allow_ofs_delta && entry->delta->idx.offset) ? 293 OBJ_OFS_DELTA : OBJ_REF_DELTA; 294} 295 296if(st)/* large blob case, just assume we don't compress well */ 297 datalen = size; 298else if(entry->z_delta_size) 299 datalen = entry->z_delta_size; 300else 301 datalen =do_compress(&buf, size); 302 303/* 304 * The object header is a byte of 'type' followed by zero or 305 * more bytes of length. 306 */ 307 hdrlen =encode_in_pack_object_header(header,sizeof(header), 308 type, size); 309 310if(type == OBJ_OFS_DELTA) { 311/* 312 * Deltas with relative base contain an additional 313 * encoding of the relative offset for the delta 314 * base from this object's position in the pack. 315 */ 316 off_t ofs = entry->idx.offset - entry->delta->idx.offset; 317unsigned pos =sizeof(dheader) -1; 318 dheader[pos] = ofs &127; 319while(ofs >>=7) 320 dheader[--pos] =128| (--ofs &127); 321if(limit && hdrlen +sizeof(dheader) - pos + datalen +20>= limit) { 322if(st) 323close_istream(st); 324free(buf); 325return0; 326} 327hashwrite(f, header, hdrlen); 328hashwrite(f, dheader + pos,sizeof(dheader) - pos); 329 hdrlen +=sizeof(dheader) - pos; 330}else if(type == OBJ_REF_DELTA) { 331/* 332 * Deltas with a base reference contain 333 * an additional 20 bytes for the base sha1. 334 */ 335if(limit && hdrlen +20+ datalen +20>= limit) { 336if(st) 337close_istream(st); 338free(buf); 339return0; 340} 341hashwrite(f, header, hdrlen); 342hashwrite(f, entry->delta->idx.oid.hash,20); 343 hdrlen +=20; 344}else{ 345if(limit && hdrlen + datalen +20>= limit) { 346if(st) 347close_istream(st); 348free(buf); 349return0; 350} 351hashwrite(f, header, hdrlen); 352} 353if(st) { 354 datalen =write_large_blob_data(st, f, &entry->idx.oid); 355close_istream(st); 356}else{ 357hashwrite(f, buf, datalen); 358free(buf); 359} 360 361return hdrlen + datalen; 362} 363 364/* Return 0 if we will bust the pack-size limit */ 365static off_t write_reuse_object(struct hashfile *f,struct object_entry *entry, 366unsigned long limit,int usable_delta) 367{ 368struct packed_git *p = entry->in_pack; 369struct pack_window *w_curs = NULL; 370struct revindex_entry *revidx; 371 off_t offset; 372enum object_type type = entry->type; 373 off_t datalen; 374unsigned char header[MAX_PACK_OBJECT_HEADER], 375 dheader[MAX_PACK_OBJECT_HEADER]; 376unsigned hdrlen; 377 378if(entry->delta) 379 type = (allow_ofs_delta && entry->delta->idx.offset) ? 380 OBJ_OFS_DELTA : OBJ_REF_DELTA; 381 hdrlen =encode_in_pack_object_header(header,sizeof(header), 382 type, entry->size); 383 384 offset = entry->in_pack_offset; 385 revidx =find_pack_revindex(p, offset); 386 datalen = revidx[1].offset - offset; 387if(!pack_to_stdout && p->index_version >1&& 388check_pack_crc(p, &w_curs, offset, datalen, revidx->nr)) { 389error("bad packed object CRC for%s", 390oid_to_hex(&entry->idx.oid)); 391unuse_pack(&w_curs); 392returnwrite_no_reuse_object(f, entry, limit, usable_delta); 393} 394 395 offset += entry->in_pack_header_size; 396 datalen -= entry->in_pack_header_size; 397 398if(!pack_to_stdout && p->index_version ==1&& 399check_pack_inflate(p, &w_curs, offset, datalen, entry->size)) { 400error("corrupt packed object for%s", 401oid_to_hex(&entry->idx.oid)); 402unuse_pack(&w_curs); 403returnwrite_no_reuse_object(f, entry, limit, usable_delta); 404} 405 406if(type == OBJ_OFS_DELTA) { 407 off_t ofs = entry->idx.offset - entry->delta->idx.offset; 408unsigned pos =sizeof(dheader) -1; 409 dheader[pos] = ofs &127; 410while(ofs >>=7) 411 dheader[--pos] =128| (--ofs &127); 412if(limit && hdrlen +sizeof(dheader) - pos + datalen +20>= limit) { 413unuse_pack(&w_curs); 414return0; 415} 416hashwrite(f, header, hdrlen); 417hashwrite(f, dheader + pos,sizeof(dheader) - pos); 418 hdrlen +=sizeof(dheader) - pos; 419 reused_delta++; 420}else if(type == OBJ_REF_DELTA) { 421if(limit && hdrlen +20+ datalen +20>= limit) { 422unuse_pack(&w_curs); 423return0; 424} 425hashwrite(f, header, hdrlen); 426hashwrite(f, entry->delta->idx.oid.hash,20); 427 hdrlen +=20; 428 reused_delta++; 429}else{ 430if(limit && hdrlen + datalen +20>= limit) { 431unuse_pack(&w_curs); 432return0; 433} 434hashwrite(f, header, hdrlen); 435} 436copy_pack_data(f, p, &w_curs, offset, datalen); 437unuse_pack(&w_curs); 438 reused++; 439return hdrlen + datalen; 440} 441 442/* Return 0 if we will bust the pack-size limit */ 443static off_t write_object(struct hashfile *f, 444struct object_entry *entry, 445 off_t write_offset) 446{ 447unsigned long limit; 448 off_t len; 449int usable_delta, to_reuse; 450 451if(!pack_to_stdout) 452crc32_begin(f); 453 454/* apply size limit if limited packsize and not first object */ 455if(!pack_size_limit || !nr_written) 456 limit =0; 457else if(pack_size_limit <= write_offset) 458/* 459 * the earlier object did not fit the limit; avoid 460 * mistaking this with unlimited (i.e. limit = 0). 461 */ 462 limit =1; 463else 464 limit = pack_size_limit - write_offset; 465 466if(!entry->delta) 467 usable_delta =0;/* no delta */ 468else if(!pack_size_limit) 469 usable_delta =1;/* unlimited packfile */ 470else if(entry->delta->idx.offset == (off_t)-1) 471 usable_delta =0;/* base was written to another pack */ 472else if(entry->delta->idx.offset) 473 usable_delta =1;/* base already exists in this pack */ 474else 475 usable_delta =0;/* base could end up in another pack */ 476 477if(!reuse_object) 478 to_reuse =0;/* explicit */ 479else if(!entry->in_pack) 480 to_reuse =0;/* can't reuse what we don't have */ 481else if(entry->type == OBJ_REF_DELTA || entry->type == OBJ_OFS_DELTA) 482/* check_object() decided it for us ... */ 483 to_reuse = usable_delta; 484/* ... but pack split may override that */ 485else if(entry->type != entry->in_pack_type) 486 to_reuse =0;/* pack has delta which is unusable */ 487else if(entry->delta) 488 to_reuse =0;/* we want to pack afresh */ 489else 490 to_reuse =1;/* we have it in-pack undeltified, 491 * and we do not need to deltify it. 492 */ 493 494if(!to_reuse) 495 len =write_no_reuse_object(f, entry, limit, usable_delta); 496else 497 len =write_reuse_object(f, entry, limit, usable_delta); 498if(!len) 499return0; 500 501if(usable_delta) 502 written_delta++; 503 written++; 504if(!pack_to_stdout) 505 entry->idx.crc32 =crc32_end(f); 506return len; 507} 508 509enum write_one_status { 510 WRITE_ONE_SKIP = -1,/* already written */ 511 WRITE_ONE_BREAK =0,/* writing this will bust the limit; not written */ 512 WRITE_ONE_WRITTEN =1,/* normal */ 513 WRITE_ONE_RECURSIVE =2/* already scheduled to be written */ 514}; 515 516static enum write_one_status write_one(struct hashfile *f, 517struct object_entry *e, 518 off_t *offset) 519{ 520 off_t size; 521int recursing; 522 523/* 524 * we set offset to 1 (which is an impossible value) to mark 525 * the fact that this object is involved in "write its base 526 * first before writing a deltified object" recursion. 527 */ 528 recursing = (e->idx.offset ==1); 529if(recursing) { 530warning("recursive delta detected for object%s", 531oid_to_hex(&e->idx.oid)); 532return WRITE_ONE_RECURSIVE; 533}else if(e->idx.offset || e->preferred_base) { 534/* offset is non zero if object is written already. */ 535return WRITE_ONE_SKIP; 536} 537 538/* if we are deltified, write out base object first. */ 539if(e->delta) { 540 e->idx.offset =1;/* now recurse */ 541switch(write_one(f, e->delta, offset)) { 542case WRITE_ONE_RECURSIVE: 543/* we cannot depend on this one */ 544 e->delta = NULL; 545break; 546default: 547break; 548case WRITE_ONE_BREAK: 549 e->idx.offset = recursing; 550return WRITE_ONE_BREAK; 551} 552} 553 554 e->idx.offset = *offset; 555 size =write_object(f, e, *offset); 556if(!size) { 557 e->idx.offset = recursing; 558return WRITE_ONE_BREAK; 559} 560 written_list[nr_written++] = &e->idx; 561 562/* make sure off_t is sufficiently large not to wrap */ 563if(signed_add_overflows(*offset, size)) 564die("pack too large for current definition of off_t"); 565*offset += size; 566return WRITE_ONE_WRITTEN; 567} 568 569static intmark_tagged(const char*path,const struct object_id *oid,int flag, 570void*cb_data) 571{ 572struct object_id peeled; 573struct object_entry *entry =packlist_find(&to_pack, oid->hash, NULL); 574 575if(entry) 576 entry->tagged =1; 577if(!peel_ref(path, &peeled)) { 578 entry =packlist_find(&to_pack, peeled.hash, NULL); 579if(entry) 580 entry->tagged =1; 581} 582return0; 583} 584 585staticinlinevoidadd_to_write_order(struct object_entry **wo, 586unsigned int*endp, 587struct object_entry *e) 588{ 589if(e->filled) 590return; 591 wo[(*endp)++] = e; 592 e->filled =1; 593} 594 595static voidadd_descendants_to_write_order(struct object_entry **wo, 596unsigned int*endp, 597struct object_entry *e) 598{ 599int add_to_order =1; 600while(e) { 601if(add_to_order) { 602struct object_entry *s; 603/* add this node... */ 604add_to_write_order(wo, endp, e); 605/* all its siblings... */ 606for(s = e->delta_sibling; s; s = s->delta_sibling) { 607add_to_write_order(wo, endp, s); 608} 609} 610/* drop down a level to add left subtree nodes if possible */ 611if(e->delta_child) { 612 add_to_order =1; 613 e = e->delta_child; 614}else{ 615 add_to_order =0; 616/* our sibling might have some children, it is next */ 617if(e->delta_sibling) { 618 e = e->delta_sibling; 619continue; 620} 621/* go back to our parent node */ 622 e = e->delta; 623while(e && !e->delta_sibling) { 624/* we're on the right side of a subtree, keep 625 * going up until we can go right again */ 626 e = e->delta; 627} 628if(!e) { 629/* done- we hit our original root node */ 630return; 631} 632/* pass it off to sibling at this level */ 633 e = e->delta_sibling; 634} 635}; 636} 637 638static voidadd_family_to_write_order(struct object_entry **wo, 639unsigned int*endp, 640struct object_entry *e) 641{ 642struct object_entry *root; 643 644for(root = e; root->delta; root = root->delta) 645;/* nothing */ 646add_descendants_to_write_order(wo, endp, root); 647} 648 649static struct object_entry **compute_write_order(void) 650{ 651unsigned int i, wo_end, last_untagged; 652 653struct object_entry **wo; 654struct object_entry *objects = to_pack.objects; 655 656for(i =0; i < to_pack.nr_objects; i++) { 657 objects[i].tagged =0; 658 objects[i].filled =0; 659 objects[i].delta_child = NULL; 660 objects[i].delta_sibling = NULL; 661} 662 663/* 664 * Fully connect delta_child/delta_sibling network. 665 * Make sure delta_sibling is sorted in the original 666 * recency order. 667 */ 668for(i = to_pack.nr_objects; i >0;) { 669struct object_entry *e = &objects[--i]; 670if(!e->delta) 671continue; 672/* Mark me as the first child */ 673 e->delta_sibling = e->delta->delta_child; 674 e->delta->delta_child = e; 675} 676 677/* 678 * Mark objects that are at the tip of tags. 679 */ 680for_each_tag_ref(mark_tagged, NULL); 681 682/* 683 * Give the objects in the original recency order until 684 * we see a tagged tip. 685 */ 686ALLOC_ARRAY(wo, to_pack.nr_objects); 687for(i = wo_end =0; i < to_pack.nr_objects; i++) { 688if(objects[i].tagged) 689break; 690add_to_write_order(wo, &wo_end, &objects[i]); 691} 692 last_untagged = i; 693 694/* 695 * Then fill all the tagged tips. 696 */ 697for(; i < to_pack.nr_objects; i++) { 698if(objects[i].tagged) 699add_to_write_order(wo, &wo_end, &objects[i]); 700} 701 702/* 703 * And then all remaining commits and tags. 704 */ 705for(i = last_untagged; i < to_pack.nr_objects; i++) { 706if(objects[i].type != OBJ_COMMIT && 707 objects[i].type != OBJ_TAG) 708continue; 709add_to_write_order(wo, &wo_end, &objects[i]); 710} 711 712/* 713 * And then all the trees. 714 */ 715for(i = last_untagged; i < to_pack.nr_objects; i++) { 716if(objects[i].type != OBJ_TREE) 717continue; 718add_to_write_order(wo, &wo_end, &objects[i]); 719} 720 721/* 722 * Finally all the rest in really tight order 723 */ 724for(i = last_untagged; i < to_pack.nr_objects; i++) { 725if(!objects[i].filled) 726add_family_to_write_order(wo, &wo_end, &objects[i]); 727} 728 729if(wo_end != to_pack.nr_objects) 730die("ordered%uobjects, expected %"PRIu32, wo_end, to_pack.nr_objects); 731 732return wo; 733} 734 735static off_t write_reused_pack(struct hashfile *f) 736{ 737unsigned char buffer[8192]; 738 off_t to_write, total; 739int fd; 740 741if(!is_pack_valid(reuse_packfile)) 742die("packfile is invalid:%s", reuse_packfile->pack_name); 743 744 fd =git_open(reuse_packfile->pack_name); 745if(fd <0) 746die_errno("unable to open packfile for reuse:%s", 747 reuse_packfile->pack_name); 748 749if(lseek(fd,sizeof(struct pack_header), SEEK_SET) == -1) 750die_errno("unable to seek in reused packfile"); 751 752if(reuse_packfile_offset <0) 753 reuse_packfile_offset = reuse_packfile->pack_size -20; 754 755 total = to_write = reuse_packfile_offset -sizeof(struct pack_header); 756 757while(to_write) { 758int read_pack =xread(fd, buffer,sizeof(buffer)); 759 760if(read_pack <=0) 761die_errno("unable to read from reused packfile"); 762 763if(read_pack > to_write) 764 read_pack = to_write; 765 766hashwrite(f, buffer, read_pack); 767 to_write -= read_pack; 768 769/* 770 * We don't know the actual number of objects written, 771 * only how many bytes written, how many bytes total, and 772 * how many objects total. So we can fake it by pretending all 773 * objects we are writing are the same size. This gives us a 774 * smooth progress meter, and at the end it matches the true 775 * answer. 776 */ 777 written = reuse_packfile_objects * 778(((double)(total - to_write)) / total); 779display_progress(progress_state, written); 780} 781 782close(fd); 783 written = reuse_packfile_objects; 784display_progress(progress_state, written); 785return reuse_packfile_offset -sizeof(struct pack_header); 786} 787 788static const char no_split_warning[] =N_( 789"disabling bitmap writing, packs are split due to pack.packSizeLimit" 790); 791 792static voidwrite_pack_file(void) 793{ 794uint32_t i =0, j; 795struct hashfile *f; 796 off_t offset; 797uint32_t nr_remaining = nr_result; 798time_t last_mtime =0; 799struct object_entry **write_order; 800 801if(progress > pack_to_stdout) 802 progress_state =start_progress(_("Writing objects"), nr_result); 803ALLOC_ARRAY(written_list, to_pack.nr_objects); 804 write_order =compute_write_order(); 805 806do{ 807struct object_id oid; 808char*pack_tmp_name = NULL; 809 810if(pack_to_stdout) 811 f =hashfd_throughput(1,"<stdout>", progress_state); 812else 813 f =create_tmp_packfile(&pack_tmp_name); 814 815 offset =write_pack_header(f, nr_remaining); 816 817if(reuse_packfile) { 818 off_t packfile_size; 819assert(pack_to_stdout); 820 821 packfile_size =write_reused_pack(f); 822 offset += packfile_size; 823} 824 825 nr_written =0; 826for(; i < to_pack.nr_objects; i++) { 827struct object_entry *e = write_order[i]; 828if(write_one(f, e, &offset) == WRITE_ONE_BREAK) 829break; 830display_progress(progress_state, written); 831} 832 833/* 834 * Did we write the wrong # entries in the header? 835 * If so, rewrite it like in fast-import 836 */ 837if(pack_to_stdout) { 838hashclose(f, oid.hash, CSUM_CLOSE); 839}else if(nr_written == nr_remaining) { 840hashclose(f, oid.hash, CSUM_FSYNC); 841}else{ 842int fd =hashclose(f, oid.hash,0); 843fixup_pack_header_footer(fd, oid.hash, pack_tmp_name, 844 nr_written, oid.hash, offset); 845close(fd); 846if(write_bitmap_index) { 847warning(_(no_split_warning)); 848 write_bitmap_index =0; 849} 850} 851 852if(!pack_to_stdout) { 853struct stat st; 854struct strbuf tmpname = STRBUF_INIT; 855 856/* 857 * Packs are runtime accessed in their mtime 858 * order since newer packs are more likely to contain 859 * younger objects. So if we are creating multiple 860 * packs then we should modify the mtime of later ones 861 * to preserve this property. 862 */ 863if(stat(pack_tmp_name, &st) <0) { 864warning_errno("failed to stat%s", pack_tmp_name); 865}else if(!last_mtime) { 866 last_mtime = st.st_mtime; 867}else{ 868struct utimbuf utb; 869 utb.actime = st.st_atime; 870 utb.modtime = --last_mtime; 871if(utime(pack_tmp_name, &utb) <0) 872warning_errno("failed utime() on%s", pack_tmp_name); 873} 874 875strbuf_addf(&tmpname,"%s-", base_name); 876 877if(write_bitmap_index) { 878bitmap_writer_set_checksum(oid.hash); 879bitmap_writer_build_type_index(written_list, nr_written); 880} 881 882finish_tmp_packfile(&tmpname, pack_tmp_name, 883 written_list, nr_written, 884&pack_idx_opts, oid.hash); 885 886if(write_bitmap_index) { 887strbuf_addf(&tmpname,"%s.bitmap",oid_to_hex(&oid)); 888 889stop_progress(&progress_state); 890 891bitmap_writer_show_progress(progress); 892bitmap_writer_reuse_bitmaps(&to_pack); 893bitmap_writer_select_commits(indexed_commits, indexed_commits_nr, -1); 894bitmap_writer_build(&to_pack); 895bitmap_writer_finish(written_list, nr_written, 896 tmpname.buf, write_bitmap_options); 897 write_bitmap_index =0; 898} 899 900strbuf_release(&tmpname); 901free(pack_tmp_name); 902puts(oid_to_hex(&oid)); 903} 904 905/* mark written objects as written to previous pack */ 906for(j =0; j < nr_written; j++) { 907 written_list[j]->offset = (off_t)-1; 908} 909 nr_remaining -= nr_written; 910}while(nr_remaining && i < to_pack.nr_objects); 911 912free(written_list); 913free(write_order); 914stop_progress(&progress_state); 915if(written != nr_result) 916die("wrote %"PRIu32" objects while expecting %"PRIu32, 917 written, nr_result); 918} 919 920static intno_try_delta(const char*path) 921{ 922static struct attr_check *check; 923 924if(!check) 925 check =attr_check_initl("delta", NULL); 926if(git_check_attr(path, check)) 927return0; 928if(ATTR_FALSE(check->items[0].value)) 929return1; 930return0; 931} 932 933/* 934 * When adding an object, check whether we have already added it 935 * to our packing list. If so, we can skip. However, if we are 936 * being asked to excludei t, but the previous mention was to include 937 * it, make sure to adjust its flags and tweak our numbers accordingly. 938 * 939 * As an optimization, we pass out the index position where we would have 940 * found the item, since that saves us from having to look it up again a 941 * few lines later when we want to add the new entry. 942 */ 943static inthave_duplicate_entry(const struct object_id *oid, 944int exclude, 945uint32_t*index_pos) 946{ 947struct object_entry *entry; 948 949 entry =packlist_find(&to_pack, oid->hash, index_pos); 950if(!entry) 951return0; 952 953if(exclude) { 954if(!entry->preferred_base) 955 nr_result--; 956 entry->preferred_base =1; 957} 958 959return1; 960} 961 962static intwant_found_object(int exclude,struct packed_git *p) 963{ 964if(exclude) 965return1; 966if(incremental) 967return0; 968 969/* 970 * When asked to do --local (do not include an object that appears in a 971 * pack we borrow from elsewhere) or --honor-pack-keep (do not include 972 * an object that appears in a pack marked with .keep), finding a pack 973 * that matches the criteria is sufficient for us to decide to omit it. 974 * However, even if this pack does not satisfy the criteria, we need to 975 * make sure no copy of this object appears in _any_ pack that makes us 976 * to omit the object, so we need to check all the packs. 977 * 978 * We can however first check whether these options can possible matter; 979 * if they do not matter we know we want the object in generated pack. 980 * Otherwise, we signal "-1" at the end to tell the caller that we do 981 * not know either way, and it needs to check more packs. 982 */ 983if(!ignore_packed_keep && 984(!local || !have_non_local_packs)) 985return1; 986 987if(local && !p->pack_local) 988return0; 989if(ignore_packed_keep && p->pack_local && p->pack_keep) 990return0; 991 992/* we don't know yet; keep looking for more packs */ 993return-1; 994} 995 996/* 997 * Check whether we want the object in the pack (e.g., we do not want 998 * objects found in non-local stores if the "--local" option was used). 999 *1000 * If the caller already knows an existing pack it wants to take the object1001 * from, that is passed in *found_pack and *found_offset; otherwise this1002 * function finds if there is any pack that has the object and returns the pack1003 * and its offset in these variables.1004 */1005static intwant_object_in_pack(const struct object_id *oid,1006int exclude,1007struct packed_git **found_pack,1008 off_t *found_offset)1009{1010int want;1011struct list_head *pos;10121013if(!exclude && local &&has_loose_object_nonlocal(oid->hash))1014return0;10151016/*1017 * If we already know the pack object lives in, start checks from that1018 * pack - in the usual case when neither --local was given nor .keep files1019 * are present we will determine the answer right now.1020 */1021if(*found_pack) {1022 want =want_found_object(exclude, *found_pack);1023if(want != -1)1024return want;1025}10261027list_for_each(pos, &packed_git_mru) {1028struct packed_git *p =list_entry(pos,struct packed_git, mru);1029 off_t offset;10301031if(p == *found_pack)1032 offset = *found_offset;1033else1034 offset =find_pack_entry_one(oid->hash, p);10351036if(offset) {1037if(!*found_pack) {1038if(!is_pack_valid(p))1039continue;1040*found_offset = offset;1041*found_pack = p;1042}1043 want =want_found_object(exclude, p);1044if(!exclude && want >0)1045list_move(&p->mru, &packed_git_mru);1046if(want != -1)1047return want;1048}1049}10501051return1;1052}10531054static voidcreate_object_entry(const struct object_id *oid,1055enum object_type type,1056uint32_t hash,1057int exclude,1058int no_try_delta,1059uint32_t index_pos,1060struct packed_git *found_pack,1061 off_t found_offset)1062{1063struct object_entry *entry;10641065 entry =packlist_alloc(&to_pack, oid->hash, index_pos);1066 entry->hash = hash;1067if(type)1068 entry->type = type;1069if(exclude)1070 entry->preferred_base =1;1071else1072 nr_result++;1073if(found_pack) {1074 entry->in_pack = found_pack;1075 entry->in_pack_offset = found_offset;1076}10771078 entry->no_try_delta = no_try_delta;1079}10801081static const char no_closure_warning[] =N_(1082"disabling bitmap writing, as some objects are not being packed"1083);10841085static intadd_object_entry(const struct object_id *oid,enum object_type type,1086const char*name,int exclude)1087{1088struct packed_git *found_pack = NULL;1089 off_t found_offset =0;1090uint32_t index_pos;10911092if(have_duplicate_entry(oid, exclude, &index_pos))1093return0;10941095if(!want_object_in_pack(oid, exclude, &found_pack, &found_offset)) {1096/* The pack is missing an object, so it will not have closure */1097if(write_bitmap_index) {1098warning(_(no_closure_warning));1099 write_bitmap_index =0;1100}1101return0;1102}11031104create_object_entry(oid, type,pack_name_hash(name),1105 exclude, name &&no_try_delta(name),1106 index_pos, found_pack, found_offset);11071108display_progress(progress_state, nr_result);1109return1;1110}11111112static intadd_object_entry_from_bitmap(const struct object_id *oid,1113enum object_type type,1114int flags,uint32_t name_hash,1115struct packed_git *pack, off_t offset)1116{1117uint32_t index_pos;11181119if(have_duplicate_entry(oid,0, &index_pos))1120return0;11211122if(!want_object_in_pack(oid,0, &pack, &offset))1123return0;11241125create_object_entry(oid, type, name_hash,0,0, index_pos, pack, offset);11261127display_progress(progress_state, nr_result);1128return1;1129}11301131struct pbase_tree_cache {1132struct object_id oid;1133int ref;1134int temporary;1135void*tree_data;1136unsigned long tree_size;1137};11381139static struct pbase_tree_cache *(pbase_tree_cache[256]);1140static intpbase_tree_cache_ix(const struct object_id *oid)1141{1142return oid->hash[0] %ARRAY_SIZE(pbase_tree_cache);1143}1144static intpbase_tree_cache_ix_incr(int ix)1145{1146return(ix+1) %ARRAY_SIZE(pbase_tree_cache);1147}11481149static struct pbase_tree {1150struct pbase_tree *next;1151/* This is a phony "cache" entry; we are not1152 * going to evict it or find it through _get()1153 * mechanism -- this is for the toplevel node that1154 * would almost always change with any commit.1155 */1156struct pbase_tree_cache pcache;1157} *pbase_tree;11581159static struct pbase_tree_cache *pbase_tree_get(const struct object_id *oid)1160{1161struct pbase_tree_cache *ent, *nent;1162void*data;1163unsigned long size;1164enum object_type type;1165int neigh;1166int my_ix =pbase_tree_cache_ix(oid);1167int available_ix = -1;11681169/* pbase-tree-cache acts as a limited hashtable.1170 * your object will be found at your index or within a few1171 * slots after that slot if it is cached.1172 */1173for(neigh =0; neigh <8; neigh++) {1174 ent = pbase_tree_cache[my_ix];1175if(ent && !oidcmp(&ent->oid, oid)) {1176 ent->ref++;1177return ent;1178}1179else if(((available_ix <0) && (!ent || !ent->ref)) ||1180((0<= available_ix) &&1181(!ent && pbase_tree_cache[available_ix])))1182 available_ix = my_ix;1183if(!ent)1184break;1185 my_ix =pbase_tree_cache_ix_incr(my_ix);1186}11871188/* Did not find one. Either we got a bogus request or1189 * we need to read and perhaps cache.1190 */1191 data =read_object_file(oid, &type, &size);1192if(!data)1193return NULL;1194if(type != OBJ_TREE) {1195free(data);1196return NULL;1197}11981199/* We need to either cache or return a throwaway copy */12001201if(available_ix <0)1202 ent = NULL;1203else{1204 ent = pbase_tree_cache[available_ix];1205 my_ix = available_ix;1206}12071208if(!ent) {1209 nent =xmalloc(sizeof(*nent));1210 nent->temporary = (available_ix <0);1211}1212else{1213/* evict and reuse */1214free(ent->tree_data);1215 nent = ent;1216}1217oidcpy(&nent->oid, oid);1218 nent->tree_data = data;1219 nent->tree_size = size;1220 nent->ref =1;1221if(!nent->temporary)1222 pbase_tree_cache[my_ix] = nent;1223return nent;1224}12251226static voidpbase_tree_put(struct pbase_tree_cache *cache)1227{1228if(!cache->temporary) {1229 cache->ref--;1230return;1231}1232free(cache->tree_data);1233free(cache);1234}12351236static intname_cmp_len(const char*name)1237{1238int i;1239for(i =0; name[i] && name[i] !='\n'&& name[i] !='/'; i++)1240;1241return i;1242}12431244static voidadd_pbase_object(struct tree_desc *tree,1245const char*name,1246int cmplen,1247const char*fullname)1248{1249struct name_entry entry;1250int cmp;12511252while(tree_entry(tree,&entry)) {1253if(S_ISGITLINK(entry.mode))1254continue;1255 cmp =tree_entry_len(&entry) != cmplen ?1:1256memcmp(name, entry.path, cmplen);1257if(cmp >0)1258continue;1259if(cmp <0)1260return;1261if(name[cmplen] !='/') {1262add_object_entry(entry.oid,1263object_type(entry.mode),1264 fullname,1);1265return;1266}1267if(S_ISDIR(entry.mode)) {1268struct tree_desc sub;1269struct pbase_tree_cache *tree;1270const char*down = name+cmplen+1;1271int downlen =name_cmp_len(down);12721273 tree =pbase_tree_get(entry.oid);1274if(!tree)1275return;1276init_tree_desc(&sub, tree->tree_data, tree->tree_size);12771278add_pbase_object(&sub, down, downlen, fullname);1279pbase_tree_put(tree);1280}1281}1282}12831284static unsigned*done_pbase_paths;1285static int done_pbase_paths_num;1286static int done_pbase_paths_alloc;1287static intdone_pbase_path_pos(unsigned hash)1288{1289int lo =0;1290int hi = done_pbase_paths_num;1291while(lo < hi) {1292int mi = lo + (hi - lo) /2;1293if(done_pbase_paths[mi] == hash)1294return mi;1295if(done_pbase_paths[mi] < hash)1296 hi = mi;1297else1298 lo = mi +1;1299}1300return-lo-1;1301}13021303static intcheck_pbase_path(unsigned hash)1304{1305int pos =done_pbase_path_pos(hash);1306if(0<= pos)1307return1;1308 pos = -pos -1;1309ALLOC_GROW(done_pbase_paths,1310 done_pbase_paths_num +1,1311 done_pbase_paths_alloc);1312 done_pbase_paths_num++;1313if(pos < done_pbase_paths_num)1314MOVE_ARRAY(done_pbase_paths + pos +1, done_pbase_paths + pos,1315 done_pbase_paths_num - pos -1);1316 done_pbase_paths[pos] = hash;1317return0;1318}13191320static voidadd_preferred_base_object(const char*name)1321{1322struct pbase_tree *it;1323int cmplen;1324unsigned hash =pack_name_hash(name);13251326if(!num_preferred_base ||check_pbase_path(hash))1327return;13281329 cmplen =name_cmp_len(name);1330for(it = pbase_tree; it; it = it->next) {1331if(cmplen ==0) {1332add_object_entry(&it->pcache.oid, OBJ_TREE, NULL,1);1333}1334else{1335struct tree_desc tree;1336init_tree_desc(&tree, it->pcache.tree_data, it->pcache.tree_size);1337add_pbase_object(&tree, name, cmplen, name);1338}1339}1340}13411342static voidadd_preferred_base(struct object_id *oid)1343{1344struct pbase_tree *it;1345void*data;1346unsigned long size;1347struct object_id tree_oid;13481349if(window <= num_preferred_base++)1350return;13511352 data =read_object_with_reference(oid, tree_type, &size, &tree_oid);1353if(!data)1354return;13551356for(it = pbase_tree; it; it = it->next) {1357if(!oidcmp(&it->pcache.oid, &tree_oid)) {1358free(data);1359return;1360}1361}13621363 it =xcalloc(1,sizeof(*it));1364 it->next = pbase_tree;1365 pbase_tree = it;13661367oidcpy(&it->pcache.oid, &tree_oid);1368 it->pcache.tree_data = data;1369 it->pcache.tree_size = size;1370}13711372static voidcleanup_preferred_base(void)1373{1374struct pbase_tree *it;1375unsigned i;13761377 it = pbase_tree;1378 pbase_tree = NULL;1379while(it) {1380struct pbase_tree *tmp = it;1381 it = tmp->next;1382free(tmp->pcache.tree_data);1383free(tmp);1384}13851386for(i =0; i <ARRAY_SIZE(pbase_tree_cache); i++) {1387if(!pbase_tree_cache[i])1388continue;1389free(pbase_tree_cache[i]->tree_data);1390FREE_AND_NULL(pbase_tree_cache[i]);1391}13921393FREE_AND_NULL(done_pbase_paths);1394 done_pbase_paths_num = done_pbase_paths_alloc =0;1395}13961397static voidcheck_object(struct object_entry *entry)1398{1399if(entry->in_pack) {1400struct packed_git *p = entry->in_pack;1401struct pack_window *w_curs = NULL;1402const unsigned char*base_ref = NULL;1403struct object_entry *base_entry;1404unsigned long used, used_0;1405unsigned long avail;1406 off_t ofs;1407unsigned char*buf, c;14081409 buf =use_pack(p, &w_curs, entry->in_pack_offset, &avail);14101411/*1412 * We want in_pack_type even if we do not reuse delta1413 * since non-delta representations could still be reused.1414 */1415 used =unpack_object_header_buffer(buf, avail,1416&entry->in_pack_type,1417&entry->size);1418if(used ==0)1419goto give_up;14201421/*1422 * Determine if this is a delta and if so whether we can1423 * reuse it or not. Otherwise let's find out as cheaply as1424 * possible what the actual type and size for this object is.1425 */1426switch(entry->in_pack_type) {1427default:1428/* Not a delta hence we've already got all we need. */1429 entry->type = entry->in_pack_type;1430 entry->in_pack_header_size = used;1431if(entry->type < OBJ_COMMIT || entry->type > OBJ_BLOB)1432goto give_up;1433unuse_pack(&w_curs);1434return;1435case OBJ_REF_DELTA:1436if(reuse_delta && !entry->preferred_base)1437 base_ref =use_pack(p, &w_curs,1438 entry->in_pack_offset + used, NULL);1439 entry->in_pack_header_size = used +20;1440break;1441case OBJ_OFS_DELTA:1442 buf =use_pack(p, &w_curs,1443 entry->in_pack_offset + used, NULL);1444 used_0 =0;1445 c = buf[used_0++];1446 ofs = c &127;1447while(c &128) {1448 ofs +=1;1449if(!ofs ||MSB(ofs,7)) {1450error("delta base offset overflow in pack for%s",1451oid_to_hex(&entry->idx.oid));1452goto give_up;1453}1454 c = buf[used_0++];1455 ofs = (ofs <<7) + (c &127);1456}1457 ofs = entry->in_pack_offset - ofs;1458if(ofs <=0|| ofs >= entry->in_pack_offset) {1459error("delta base offset out of bound for%s",1460oid_to_hex(&entry->idx.oid));1461goto give_up;1462}1463if(reuse_delta && !entry->preferred_base) {1464struct revindex_entry *revidx;1465 revidx =find_pack_revindex(p, ofs);1466if(!revidx)1467goto give_up;1468 base_ref =nth_packed_object_sha1(p, revidx->nr);1469}1470 entry->in_pack_header_size = used + used_0;1471break;1472}14731474if(base_ref && (base_entry =packlist_find(&to_pack, base_ref, NULL))) {1475/*1476 * If base_ref was set above that means we wish to1477 * reuse delta data, and we even found that base1478 * in the list of objects we want to pack. Goodie!1479 *1480 * Depth value does not matter - find_deltas() will1481 * never consider reused delta as the base object to1482 * deltify other objects against, in order to avoid1483 * circular deltas.1484 */1485 entry->type = entry->in_pack_type;1486 entry->delta = base_entry;1487 entry->delta_size = entry->size;1488 entry->delta_sibling = base_entry->delta_child;1489 base_entry->delta_child = entry;1490unuse_pack(&w_curs);1491return;1492}14931494if(entry->type) {1495/*1496 * This must be a delta and we already know what the1497 * final object type is. Let's extract the actual1498 * object size from the delta header.1499 */1500 entry->size =get_size_from_delta(p, &w_curs,1501 entry->in_pack_offset + entry->in_pack_header_size);1502if(entry->size ==0)1503goto give_up;1504unuse_pack(&w_curs);1505return;1506}15071508/*1509 * No choice but to fall back to the recursive delta walk1510 * with sha1_object_info() to find about the object type1511 * at this point...1512 */1513 give_up:1514unuse_pack(&w_curs);1515}15161517 entry->type =oid_object_info(&entry->idx.oid, &entry->size);1518/*1519 * The error condition is checked in prepare_pack(). This is1520 * to permit a missing preferred base object to be ignored1521 * as a preferred base. Doing so can result in a larger1522 * pack file, but the transfer will still take place.1523 */1524}15251526static intpack_offset_sort(const void*_a,const void*_b)1527{1528const struct object_entry *a = *(struct object_entry **)_a;1529const struct object_entry *b = *(struct object_entry **)_b;15301531/* avoid filesystem trashing with loose objects */1532if(!a->in_pack && !b->in_pack)1533returnoidcmp(&a->idx.oid, &b->idx.oid);15341535if(a->in_pack < b->in_pack)1536return-1;1537if(a->in_pack > b->in_pack)1538return1;1539return a->in_pack_offset < b->in_pack_offset ? -1:1540(a->in_pack_offset > b->in_pack_offset);1541}15421543/*1544 * Drop an on-disk delta we were planning to reuse. Naively, this would1545 * just involve blanking out the "delta" field, but we have to deal1546 * with some extra book-keeping:1547 *1548 * 1. Removing ourselves from the delta_sibling linked list.1549 *1550 * 2. Updating our size/type to the non-delta representation. These were1551 * either not recorded initially (size) or overwritten with the delta type1552 * (type) when check_object() decided to reuse the delta.1553 *1554 * 3. Resetting our delta depth, as we are now a base object.1555 */1556static voiddrop_reused_delta(struct object_entry *entry)1557{1558struct object_entry **p = &entry->delta->delta_child;1559struct object_info oi = OBJECT_INFO_INIT;15601561while(*p) {1562if(*p == entry)1563*p = (*p)->delta_sibling;1564else1565 p = &(*p)->delta_sibling;1566}1567 entry->delta = NULL;1568 entry->depth =0;15691570 oi.sizep = &entry->size;1571 oi.typep = &entry->type;1572if(packed_object_info(entry->in_pack, entry->in_pack_offset, &oi) <0) {1573/*1574 * We failed to get the info from this pack for some reason;1575 * fall back to sha1_object_info, which may find another copy.1576 * And if that fails, the error will be recorded in entry->type1577 * and dealt with in prepare_pack().1578 */1579 entry->type =oid_object_info(&entry->idx.oid, &entry->size);1580}1581}15821583/*1584 * Follow the chain of deltas from this entry onward, throwing away any links1585 * that cause us to hit a cycle (as determined by the DFS state flags in1586 * the entries).1587 *1588 * We also detect too-long reused chains that would violate our --depth1589 * limit.1590 */1591static voidbreak_delta_chains(struct object_entry *entry)1592{1593/*1594 * The actual depth of each object we will write is stored as an int,1595 * as it cannot exceed our int "depth" limit. But before we break1596 * changes based no that limit, we may potentially go as deep as the1597 * number of objects, which is elsewhere bounded to a uint32_t.1598 */1599uint32_t total_depth;1600struct object_entry *cur, *next;16011602for(cur = entry, total_depth =0;1603 cur;1604 cur = cur->delta, total_depth++) {1605if(cur->dfs_state == DFS_DONE) {1606/*1607 * We've already seen this object and know it isn't1608 * part of a cycle. We do need to append its depth1609 * to our count.1610 */1611 total_depth += cur->depth;1612break;1613}16141615/*1616 * We break cycles before looping, so an ACTIVE state (or any1617 * other cruft which made its way into the state variable)1618 * is a bug.1619 */1620if(cur->dfs_state != DFS_NONE)1621die("BUG: confusing delta dfs state in first pass:%d",1622 cur->dfs_state);16231624/*1625 * Now we know this is the first time we've seen the object. If1626 * it's not a delta, we're done traversing, but we'll mark it1627 * done to save time on future traversals.1628 */1629if(!cur->delta) {1630 cur->dfs_state = DFS_DONE;1631break;1632}16331634/*1635 * Mark ourselves as active and see if the next step causes1636 * us to cycle to another active object. It's important to do1637 * this _before_ we loop, because it impacts where we make the1638 * cut, and thus how our total_depth counter works.1639 * E.g., We may see a partial loop like:1640 *1641 * A -> B -> C -> D -> B1642 *1643 * Cutting B->C breaks the cycle. But now the depth of A is1644 * only 1, and our total_depth counter is at 3. The size of the1645 * error is always one less than the size of the cycle we1646 * broke. Commits C and D were "lost" from A's chain.1647 *1648 * If we instead cut D->B, then the depth of A is correct at 3.1649 * We keep all commits in the chain that we examined.1650 */1651 cur->dfs_state = DFS_ACTIVE;1652if(cur->delta->dfs_state == DFS_ACTIVE) {1653drop_reused_delta(cur);1654 cur->dfs_state = DFS_DONE;1655break;1656}1657}16581659/*1660 * And now that we've gone all the way to the bottom of the chain, we1661 * need to clear the active flags and set the depth fields as1662 * appropriate. Unlike the loop above, which can quit when it drops a1663 * delta, we need to keep going to look for more depth cuts. So we need1664 * an extra "next" pointer to keep going after we reset cur->delta.1665 */1666for(cur = entry; cur; cur = next) {1667 next = cur->delta;16681669/*1670 * We should have a chain of zero or more ACTIVE states down to1671 * a final DONE. We can quit after the DONE, because either it1672 * has no bases, or we've already handled them in a previous1673 * call.1674 */1675if(cur->dfs_state == DFS_DONE)1676break;1677else if(cur->dfs_state != DFS_ACTIVE)1678die("BUG: confusing delta dfs state in second pass:%d",1679 cur->dfs_state);16801681/*1682 * If the total_depth is more than depth, then we need to snip1683 * the chain into two or more smaller chains that don't exceed1684 * the maximum depth. Most of the resulting chains will contain1685 * (depth + 1) entries (i.e., depth deltas plus one base), and1686 * the last chain (i.e., the one containing entry) will contain1687 * whatever entries are left over, namely1688 * (total_depth % (depth + 1)) of them.1689 *1690 * Since we are iterating towards decreasing depth, we need to1691 * decrement total_depth as we go, and we need to write to the1692 * entry what its final depth will be after all of the1693 * snipping. Since we're snipping into chains of length (depth1694 * + 1) entries, the final depth of an entry will be its1695 * original depth modulo (depth + 1). Any time we encounter an1696 * entry whose final depth is supposed to be zero, we snip it1697 * from its delta base, thereby making it so.1698 */1699 cur->depth = (total_depth--) % (depth +1);1700if(!cur->depth)1701drop_reused_delta(cur);17021703 cur->dfs_state = DFS_DONE;1704}1705}17061707static voidget_object_details(void)1708{1709uint32_t i;1710struct object_entry **sorted_by_offset;17111712 sorted_by_offset =xcalloc(to_pack.nr_objects,sizeof(struct object_entry *));1713for(i =0; i < to_pack.nr_objects; i++)1714 sorted_by_offset[i] = to_pack.objects + i;1715QSORT(sorted_by_offset, to_pack.nr_objects, pack_offset_sort);17161717for(i =0; i < to_pack.nr_objects; i++) {1718struct object_entry *entry = sorted_by_offset[i];1719check_object(entry);1720if(big_file_threshold < entry->size)1721 entry->no_try_delta =1;1722}17231724/*1725 * This must happen in a second pass, since we rely on the delta1726 * information for the whole list being completed.1727 */1728for(i =0; i < to_pack.nr_objects; i++)1729break_delta_chains(&to_pack.objects[i]);17301731free(sorted_by_offset);1732}17331734/*1735 * We search for deltas in a list sorted by type, by filename hash, and then1736 * by size, so that we see progressively smaller and smaller files.1737 * That's because we prefer deltas to be from the bigger file1738 * to the smaller -- deletes are potentially cheaper, but perhaps1739 * more importantly, the bigger file is likely the more recent1740 * one. The deepest deltas are therefore the oldest objects which are1741 * less susceptible to be accessed often.1742 */1743static inttype_size_sort(const void*_a,const void*_b)1744{1745const struct object_entry *a = *(struct object_entry **)_a;1746const struct object_entry *b = *(struct object_entry **)_b;17471748if(a->type > b->type)1749return-1;1750if(a->type < b->type)1751return1;1752if(a->hash > b->hash)1753return-1;1754if(a->hash < b->hash)1755return1;1756if(a->preferred_base > b->preferred_base)1757return-1;1758if(a->preferred_base < b->preferred_base)1759return1;1760if(a->size > b->size)1761return-1;1762if(a->size < b->size)1763return1;1764return a < b ? -1: (a > b);/* newest first */1765}17661767struct unpacked {1768struct object_entry *entry;1769void*data;1770struct delta_index *index;1771unsigned depth;1772};17731774static intdelta_cacheable(unsigned long src_size,unsigned long trg_size,1775unsigned long delta_size)1776{1777if(max_delta_cache_size && delta_cache_size + delta_size > max_delta_cache_size)1778return0;17791780if(delta_size < cache_max_small_delta_size)1781return1;17821783/* cache delta, if objects are large enough compared to delta size */1784if((src_size >>20) + (trg_size >>21) > (delta_size >>10))1785return1;17861787return0;1788}17891790#ifndef NO_PTHREADS17911792static pthread_mutex_t read_mutex;1793#define read_lock() pthread_mutex_lock(&read_mutex)1794#define read_unlock() pthread_mutex_unlock(&read_mutex)17951796static pthread_mutex_t cache_mutex;1797#define cache_lock() pthread_mutex_lock(&cache_mutex)1798#define cache_unlock() pthread_mutex_unlock(&cache_mutex)17991800static pthread_mutex_t progress_mutex;1801#define progress_lock() pthread_mutex_lock(&progress_mutex)1802#define progress_unlock() pthread_mutex_unlock(&progress_mutex)18031804#else18051806#define read_lock() (void)01807#define read_unlock() (void)01808#define cache_lock() (void)01809#define cache_unlock() (void)01810#define progress_lock() (void)01811#define progress_unlock() (void)018121813#endif18141815static inttry_delta(struct unpacked *trg,struct unpacked *src,1816unsigned max_depth,unsigned long*mem_usage)1817{1818struct object_entry *trg_entry = trg->entry;1819struct object_entry *src_entry = src->entry;1820unsigned long trg_size, src_size, delta_size, sizediff, max_size, sz;1821unsigned ref_depth;1822enum object_type type;1823void*delta_buf;18241825/* Don't bother doing diffs between different types */1826if(trg_entry->type != src_entry->type)1827return-1;18281829/*1830 * We do not bother to try a delta that we discarded on an1831 * earlier try, but only when reusing delta data. Note that1832 * src_entry that is marked as the preferred_base should always1833 * be considered, as even if we produce a suboptimal delta against1834 * it, we will still save the transfer cost, as we already know1835 * the other side has it and we won't send src_entry at all.1836 */1837if(reuse_delta && trg_entry->in_pack &&1838 trg_entry->in_pack == src_entry->in_pack &&1839!src_entry->preferred_base &&1840 trg_entry->in_pack_type != OBJ_REF_DELTA &&1841 trg_entry->in_pack_type != OBJ_OFS_DELTA)1842return0;18431844/* Let's not bust the allowed depth. */1845if(src->depth >= max_depth)1846return0;18471848/* Now some size filtering heuristics. */1849 trg_size = trg_entry->size;1850if(!trg_entry->delta) {1851 max_size = trg_size/2-20;1852 ref_depth =1;1853}else{1854 max_size = trg_entry->delta_size;1855 ref_depth = trg->depth;1856}1857 max_size = (uint64_t)max_size * (max_depth - src->depth) /1858(max_depth - ref_depth +1);1859if(max_size ==0)1860return0;1861 src_size = src_entry->size;1862 sizediff = src_size < trg_size ? trg_size - src_size :0;1863if(sizediff >= max_size)1864return0;1865if(trg_size < src_size /32)1866return0;18671868/* Load data if not already done */1869if(!trg->data) {1870read_lock();1871 trg->data =read_object_file(&trg_entry->idx.oid, &type, &sz);1872read_unlock();1873if(!trg->data)1874die("object%scannot be read",1875oid_to_hex(&trg_entry->idx.oid));1876if(sz != trg_size)1877die("object%sinconsistent object length (%lu vs%lu)",1878oid_to_hex(&trg_entry->idx.oid), sz,1879 trg_size);1880*mem_usage += sz;1881}1882if(!src->data) {1883read_lock();1884 src->data =read_object_file(&src_entry->idx.oid, &type, &sz);1885read_unlock();1886if(!src->data) {1887if(src_entry->preferred_base) {1888static int warned =0;1889if(!warned++)1890warning("object%scannot be read",1891oid_to_hex(&src_entry->idx.oid));1892/*1893 * Those objects are not included in the1894 * resulting pack. Be resilient and ignore1895 * them if they can't be read, in case the1896 * pack could be created nevertheless.1897 */1898return0;1899}1900die("object%scannot be read",1901oid_to_hex(&src_entry->idx.oid));1902}1903if(sz != src_size)1904die("object%sinconsistent object length (%lu vs%lu)",1905oid_to_hex(&src_entry->idx.oid), sz,1906 src_size);1907*mem_usage += sz;1908}1909if(!src->index) {1910 src->index =create_delta_index(src->data, src_size);1911if(!src->index) {1912static int warned =0;1913if(!warned++)1914warning("suboptimal pack - out of memory");1915return0;1916}1917*mem_usage +=sizeof_delta_index(src->index);1918}19191920 delta_buf =create_delta(src->index, trg->data, trg_size, &delta_size, max_size);1921if(!delta_buf)1922return0;19231924if(trg_entry->delta) {1925/* Prefer only shallower same-sized deltas. */1926if(delta_size == trg_entry->delta_size &&1927 src->depth +1>= trg->depth) {1928free(delta_buf);1929return0;1930}1931}19321933/*1934 * Handle memory allocation outside of the cache1935 * accounting lock. Compiler will optimize the strangeness1936 * away when NO_PTHREADS is defined.1937 */1938free(trg_entry->delta_data);1939cache_lock();1940if(trg_entry->delta_data) {1941 delta_cache_size -= trg_entry->delta_size;1942 trg_entry->delta_data = NULL;1943}1944if(delta_cacheable(src_size, trg_size, delta_size)) {1945 delta_cache_size += delta_size;1946cache_unlock();1947 trg_entry->delta_data =xrealloc(delta_buf, delta_size);1948}else{1949cache_unlock();1950free(delta_buf);1951}19521953 trg_entry->delta = src_entry;1954 trg_entry->delta_size = delta_size;1955 trg->depth = src->depth +1;19561957return1;1958}19591960static unsigned intcheck_delta_limit(struct object_entry *me,unsigned int n)1961{1962struct object_entry *child = me->delta_child;1963unsigned int m = n;1964while(child) {1965unsigned int c =check_delta_limit(child, n +1);1966if(m < c)1967 m = c;1968 child = child->delta_sibling;1969}1970return m;1971}19721973static unsigned longfree_unpacked(struct unpacked *n)1974{1975unsigned long freed_mem =sizeof_delta_index(n->index);1976free_delta_index(n->index);1977 n->index = NULL;1978if(n->data) {1979 freed_mem += n->entry->size;1980FREE_AND_NULL(n->data);1981}1982 n->entry = NULL;1983 n->depth =0;1984return freed_mem;1985}19861987static voidfind_deltas(struct object_entry **list,unsigned*list_size,1988int window,int depth,unsigned*processed)1989{1990uint32_t i, idx =0, count =0;1991struct unpacked *array;1992unsigned long mem_usage =0;19931994 array =xcalloc(window,sizeof(struct unpacked));19951996for(;;) {1997struct object_entry *entry;1998struct unpacked *n = array + idx;1999int j, max_depth, best_base = -1;20002001progress_lock();2002if(!*list_size) {2003progress_unlock();2004break;2005}2006 entry = *list++;2007(*list_size)--;2008if(!entry->preferred_base) {2009(*processed)++;2010display_progress(progress_state, *processed);2011}2012progress_unlock();20132014 mem_usage -=free_unpacked(n);2015 n->entry = entry;20162017while(window_memory_limit &&2018 mem_usage > window_memory_limit &&2019 count >1) {2020uint32_t tail = (idx + window - count) % window;2021 mem_usage -=free_unpacked(array + tail);2022 count--;2023}20242025/* We do not compute delta to *create* objects we are not2026 * going to pack.2027 */2028if(entry->preferred_base)2029goto next;20302031/*2032 * If the current object is at pack edge, take the depth the2033 * objects that depend on the current object into account2034 * otherwise they would become too deep.2035 */2036 max_depth = depth;2037if(entry->delta_child) {2038 max_depth -=check_delta_limit(entry,0);2039if(max_depth <=0)2040goto next;2041}20422043 j = window;2044while(--j >0) {2045int ret;2046uint32_t other_idx = idx + j;2047struct unpacked *m;2048if(other_idx >= window)2049 other_idx -= window;2050 m = array + other_idx;2051if(!m->entry)2052break;2053 ret =try_delta(n, m, max_depth, &mem_usage);2054if(ret <0)2055break;2056else if(ret >0)2057 best_base = other_idx;2058}20592060/*2061 * If we decided to cache the delta data, then it is best2062 * to compress it right away. First because we have to do2063 * it anyway, and doing it here while we're threaded will2064 * save a lot of time in the non threaded write phase,2065 * as well as allow for caching more deltas within2066 * the same cache size limit.2067 * ...2068 * But only if not writing to stdout, since in that case2069 * the network is most likely throttling writes anyway,2070 * and therefore it is best to go to the write phase ASAP2071 * instead, as we can afford spending more time compressing2072 * between writes at that moment.2073 */2074if(entry->delta_data && !pack_to_stdout) {2075 entry->z_delta_size =do_compress(&entry->delta_data,2076 entry->delta_size);2077cache_lock();2078 delta_cache_size -= entry->delta_size;2079 delta_cache_size += entry->z_delta_size;2080cache_unlock();2081}20822083/* if we made n a delta, and if n is already at max2084 * depth, leaving it in the window is pointless. we2085 * should evict it first.2086 */2087if(entry->delta && max_depth <= n->depth)2088continue;20892090/*2091 * Move the best delta base up in the window, after the2092 * currently deltified object, to keep it longer. It will2093 * be the first base object to be attempted next.2094 */2095if(entry->delta) {2096struct unpacked swap = array[best_base];2097int dist = (window + idx - best_base) % window;2098int dst = best_base;2099while(dist--) {2100int src = (dst +1) % window;2101 array[dst] = array[src];2102 dst = src;2103}2104 array[dst] = swap;2105}21062107 next:2108 idx++;2109if(count +1< window)2110 count++;2111if(idx >= window)2112 idx =0;2113}21142115for(i =0; i < window; ++i) {2116free_delta_index(array[i].index);2117free(array[i].data);2118}2119free(array);2120}21212122#ifndef NO_PTHREADS21232124static voidtry_to_free_from_threads(size_t size)2125{2126read_lock();2127release_pack_memory(size);2128read_unlock();2129}21302131static try_to_free_t old_try_to_free_routine;21322133/*2134 * The main thread waits on the condition that (at least) one of the workers2135 * has stopped working (which is indicated in the .working member of2136 * struct thread_params).2137 * When a work thread has completed its work, it sets .working to 0 and2138 * signals the main thread and waits on the condition that .data_ready2139 * becomes 1.2140 */21412142struct thread_params {2143 pthread_t thread;2144struct object_entry **list;2145unsigned list_size;2146unsigned remaining;2147int window;2148int depth;2149int working;2150int data_ready;2151 pthread_mutex_t mutex;2152 pthread_cond_t cond;2153unsigned*processed;2154};21552156static pthread_cond_t progress_cond;21572158/*2159 * Mutex and conditional variable can't be statically-initialized on Windows.2160 */2161static voidinit_threaded_search(void)2162{2163init_recursive_mutex(&read_mutex);2164pthread_mutex_init(&cache_mutex, NULL);2165pthread_mutex_init(&progress_mutex, NULL);2166pthread_cond_init(&progress_cond, NULL);2167 old_try_to_free_routine =set_try_to_free_routine(try_to_free_from_threads);2168}21692170static voidcleanup_threaded_search(void)2171{2172set_try_to_free_routine(old_try_to_free_routine);2173pthread_cond_destroy(&progress_cond);2174pthread_mutex_destroy(&read_mutex);2175pthread_mutex_destroy(&cache_mutex);2176pthread_mutex_destroy(&progress_mutex);2177}21782179static void*threaded_find_deltas(void*arg)2180{2181struct thread_params *me = arg;21822183progress_lock();2184while(me->remaining) {2185progress_unlock();21862187find_deltas(me->list, &me->remaining,2188 me->window, me->depth, me->processed);21892190progress_lock();2191 me->working =0;2192pthread_cond_signal(&progress_cond);2193progress_unlock();21942195/*2196 * We must not set ->data_ready before we wait on the2197 * condition because the main thread may have set it to 12198 * before we get here. In order to be sure that new2199 * work is available if we see 1 in ->data_ready, it2200 * was initialized to 0 before this thread was spawned2201 * and we reset it to 0 right away.2202 */2203pthread_mutex_lock(&me->mutex);2204while(!me->data_ready)2205pthread_cond_wait(&me->cond, &me->mutex);2206 me->data_ready =0;2207pthread_mutex_unlock(&me->mutex);22082209progress_lock();2210}2211progress_unlock();2212/* leave ->working 1 so that this doesn't get more work assigned */2213return NULL;2214}22152216static voidll_find_deltas(struct object_entry **list,unsigned list_size,2217int window,int depth,unsigned*processed)2218{2219struct thread_params *p;2220int i, ret, active_threads =0;22212222init_threaded_search();22232224if(delta_search_threads <=1) {2225find_deltas(list, &list_size, window, depth, processed);2226cleanup_threaded_search();2227return;2228}2229if(progress > pack_to_stdout)2230fprintf(stderr,"Delta compression using up to%dthreads.\n",2231 delta_search_threads);2232 p =xcalloc(delta_search_threads,sizeof(*p));22332234/* Partition the work amongst work threads. */2235for(i =0; i < delta_search_threads; i++) {2236unsigned sub_size = list_size / (delta_search_threads - i);22372238/* don't use too small segments or no deltas will be found */2239if(sub_size <2*window && i+1< delta_search_threads)2240 sub_size =0;22412242 p[i].window = window;2243 p[i].depth = depth;2244 p[i].processed = processed;2245 p[i].working =1;2246 p[i].data_ready =0;22472248/* try to split chunks on "path" boundaries */2249while(sub_size && sub_size < list_size &&2250 list[sub_size]->hash &&2251 list[sub_size]->hash == list[sub_size-1]->hash)2252 sub_size++;22532254 p[i].list = list;2255 p[i].list_size = sub_size;2256 p[i].remaining = sub_size;22572258 list += sub_size;2259 list_size -= sub_size;2260}22612262/* Start work threads. */2263for(i =0; i < delta_search_threads; i++) {2264if(!p[i].list_size)2265continue;2266pthread_mutex_init(&p[i].mutex, NULL);2267pthread_cond_init(&p[i].cond, NULL);2268 ret =pthread_create(&p[i].thread, NULL,2269 threaded_find_deltas, &p[i]);2270if(ret)2271die("unable to create thread:%s",strerror(ret));2272 active_threads++;2273}22742275/*2276 * Now let's wait for work completion. Each time a thread is done2277 * with its work, we steal half of the remaining work from the2278 * thread with the largest number of unprocessed objects and give2279 * it to that newly idle thread. This ensure good load balancing2280 * until the remaining object list segments are simply too short2281 * to be worth splitting anymore.2282 */2283while(active_threads) {2284struct thread_params *target = NULL;2285struct thread_params *victim = NULL;2286unsigned sub_size =0;22872288progress_lock();2289for(;;) {2290for(i =0; !target && i < delta_search_threads; i++)2291if(!p[i].working)2292 target = &p[i];2293if(target)2294break;2295pthread_cond_wait(&progress_cond, &progress_mutex);2296}22972298for(i =0; i < delta_search_threads; i++)2299if(p[i].remaining >2*window &&2300(!victim || victim->remaining < p[i].remaining))2301 victim = &p[i];2302if(victim) {2303 sub_size = victim->remaining /2;2304 list = victim->list + victim->list_size - sub_size;2305while(sub_size && list[0]->hash &&2306 list[0]->hash == list[-1]->hash) {2307 list++;2308 sub_size--;2309}2310if(!sub_size) {2311/*2312 * It is possible for some "paths" to have2313 * so many objects that no hash boundary2314 * might be found. Let's just steal the2315 * exact half in that case.2316 */2317 sub_size = victim->remaining /2;2318 list -= sub_size;2319}2320 target->list = list;2321 victim->list_size -= sub_size;2322 victim->remaining -= sub_size;2323}2324 target->list_size = sub_size;2325 target->remaining = sub_size;2326 target->working =1;2327progress_unlock();23282329pthread_mutex_lock(&target->mutex);2330 target->data_ready =1;2331pthread_cond_signal(&target->cond);2332pthread_mutex_unlock(&target->mutex);23332334if(!sub_size) {2335pthread_join(target->thread, NULL);2336pthread_cond_destroy(&target->cond);2337pthread_mutex_destroy(&target->mutex);2338 active_threads--;2339}2340}2341cleanup_threaded_search();2342free(p);2343}23442345#else2346#define ll_find_deltas(l, s, w, d, p) find_deltas(l, &s, w, d, p)2347#endif23482349static voidadd_tag_chain(const struct object_id *oid)2350{2351struct tag *tag;23522353/*2354 * We catch duplicates already in add_object_entry(), but we'd2355 * prefer to do this extra check to avoid having to parse the2356 * tag at all if we already know that it's being packed (e.g., if2357 * it was included via bitmaps, we would not have parsed it2358 * previously).2359 */2360if(packlist_find(&to_pack, oid->hash, NULL))2361return;23622363 tag =lookup_tag(oid);2364while(1) {2365if(!tag ||parse_tag(tag) || !tag->tagged)2366die("unable to pack objects reachable from tag%s",2367oid_to_hex(oid));23682369add_object_entry(&tag->object.oid, OBJ_TAG, NULL,0);23702371if(tag->tagged->type != OBJ_TAG)2372return;23732374 tag = (struct tag *)tag->tagged;2375}2376}23772378static intadd_ref_tag(const char*path,const struct object_id *oid,int flag,void*cb_data)2379{2380struct object_id peeled;23812382if(starts_with(path,"refs/tags/") &&/* is a tag? */2383!peel_ref(path, &peeled) &&/* peelable? */2384packlist_find(&to_pack, peeled.hash, NULL))/* object packed? */2385add_tag_chain(oid);2386return0;2387}23882389static voidprepare_pack(int window,int depth)2390{2391struct object_entry **delta_list;2392uint32_t i, nr_deltas;2393unsigned n;23942395get_object_details();23962397/*2398 * If we're locally repacking then we need to be doubly careful2399 * from now on in order to make sure no stealth corruption gets2400 * propagated to the new pack. Clients receiving streamed packs2401 * should validate everything they get anyway so no need to incur2402 * the additional cost here in that case.2403 */2404if(!pack_to_stdout)2405 do_check_packed_object_crc =1;24062407if(!to_pack.nr_objects || !window || !depth)2408return;24092410ALLOC_ARRAY(delta_list, to_pack.nr_objects);2411 nr_deltas = n =0;24122413for(i =0; i < to_pack.nr_objects; i++) {2414struct object_entry *entry = to_pack.objects + i;24152416if(entry->delta)2417/* This happens if we decided to reuse existing2418 * delta from a pack. "reuse_delta &&" is implied.2419 */2420continue;24212422if(entry->size <50)2423continue;24242425if(entry->no_try_delta)2426continue;24272428if(!entry->preferred_base) {2429 nr_deltas++;2430if(entry->type <0)2431die("unable to get type of object%s",2432oid_to_hex(&entry->idx.oid));2433}else{2434if(entry->type <0) {2435/*2436 * This object is not found, but we2437 * don't have to include it anyway.2438 */2439continue;2440}2441}24422443 delta_list[n++] = entry;2444}24452446if(nr_deltas && n >1) {2447unsigned nr_done =0;2448if(progress)2449 progress_state =start_progress(_("Compressing objects"),2450 nr_deltas);2451QSORT(delta_list, n, type_size_sort);2452ll_find_deltas(delta_list, n, window+1, depth, &nr_done);2453stop_progress(&progress_state);2454if(nr_done != nr_deltas)2455die("inconsistency with delta count");2456}2457free(delta_list);2458}24592460static intgit_pack_config(const char*k,const char*v,void*cb)2461{2462if(!strcmp(k,"pack.window")) {2463 window =git_config_int(k, v);2464return0;2465}2466if(!strcmp(k,"pack.windowmemory")) {2467 window_memory_limit =git_config_ulong(k, v);2468return0;2469}2470if(!strcmp(k,"pack.depth")) {2471 depth =git_config_int(k, v);2472return0;2473}2474if(!strcmp(k,"pack.deltacachesize")) {2475 max_delta_cache_size =git_config_int(k, v);2476return0;2477}2478if(!strcmp(k,"pack.deltacachelimit")) {2479 cache_max_small_delta_size =git_config_int(k, v);2480return0;2481}2482if(!strcmp(k,"pack.writebitmaphashcache")) {2483if(git_config_bool(k, v))2484 write_bitmap_options |= BITMAP_OPT_HASH_CACHE;2485else2486 write_bitmap_options &= ~BITMAP_OPT_HASH_CACHE;2487}2488if(!strcmp(k,"pack.usebitmaps")) {2489 use_bitmap_index_default =git_config_bool(k, v);2490return0;2491}2492if(!strcmp(k,"pack.threads")) {2493 delta_search_threads =git_config_int(k, v);2494if(delta_search_threads <0)2495die("invalid number of threads specified (%d)",2496 delta_search_threads);2497#ifdef NO_PTHREADS2498if(delta_search_threads !=1) {2499warning("no threads support, ignoring%s", k);2500 delta_search_threads =0;2501}2502#endif2503return0;2504}2505if(!strcmp(k,"pack.indexversion")) {2506 pack_idx_opts.version =git_config_int(k, v);2507if(pack_idx_opts.version >2)2508die("bad pack.indexversion=%"PRIu32,2509 pack_idx_opts.version);2510return0;2511}2512returngit_default_config(k, v, cb);2513}25142515static voidread_object_list_from_stdin(void)2516{2517char line[GIT_MAX_HEXSZ +1+ PATH_MAX +2];2518struct object_id oid;2519const char*p;25202521for(;;) {2522if(!fgets(line,sizeof(line), stdin)) {2523if(feof(stdin))2524break;2525if(!ferror(stdin))2526die("fgets returned NULL, not EOF, not error!");2527if(errno != EINTR)2528die_errno("fgets");2529clearerr(stdin);2530continue;2531}2532if(line[0] =='-') {2533if(get_oid_hex(line+1, &oid))2534die("expected edge object ID, got garbage:\n%s",2535 line);2536add_preferred_base(&oid);2537continue;2538}2539if(parse_oid_hex(line, &oid, &p))2540die("expected object ID, got garbage:\n%s", line);25412542add_preferred_base_object(p +1);2543add_object_entry(&oid,0, p +1,0);2544}2545}25462547/* Remember to update object flag allocation in object.h */2548#define OBJECT_ADDED (1u<<20)25492550static voidshow_commit(struct commit *commit,void*data)2551{2552add_object_entry(&commit->object.oid, OBJ_COMMIT, NULL,0);2553 commit->object.flags |= OBJECT_ADDED;25542555if(write_bitmap_index)2556index_commit_for_bitmap(commit);2557}25582559static voidshow_object(struct object *obj,const char*name,void*data)2560{2561add_preferred_base_object(name);2562add_object_entry(&obj->oid, obj->type, name,0);2563 obj->flags |= OBJECT_ADDED;2564}25652566static voidshow_object__ma_allow_any(struct object *obj,const char*name,void*data)2567{2568assert(arg_missing_action == MA_ALLOW_ANY);25692570/*2571 * Quietly ignore ALL missing objects. This avoids problems with2572 * staging them now and getting an odd error later.2573 */2574if(!has_object_file(&obj->oid))2575return;25762577show_object(obj, name, data);2578}25792580static voidshow_object__ma_allow_promisor(struct object *obj,const char*name,void*data)2581{2582assert(arg_missing_action == MA_ALLOW_PROMISOR);25832584/*2585 * Quietly ignore EXPECTED missing objects. This avoids problems with2586 * staging them now and getting an odd error later.2587 */2588if(!has_object_file(&obj->oid) &&is_promisor_object(&obj->oid))2589return;25902591show_object(obj, name, data);2592}25932594static intoption_parse_missing_action(const struct option *opt,2595const char*arg,int unset)2596{2597assert(arg);2598assert(!unset);25992600if(!strcmp(arg,"error")) {2601 arg_missing_action = MA_ERROR;2602 fn_show_object = show_object;2603return0;2604}26052606if(!strcmp(arg,"allow-any")) {2607 arg_missing_action = MA_ALLOW_ANY;2608 fetch_if_missing =0;2609 fn_show_object = show_object__ma_allow_any;2610return0;2611}26122613if(!strcmp(arg,"allow-promisor")) {2614 arg_missing_action = MA_ALLOW_PROMISOR;2615 fetch_if_missing =0;2616 fn_show_object = show_object__ma_allow_promisor;2617return0;2618}26192620die(_("invalid value for --missing"));2621return0;2622}26232624static voidshow_edge(struct commit *commit)2625{2626add_preferred_base(&commit->object.oid);2627}26282629struct in_pack_object {2630 off_t offset;2631struct object *object;2632};26332634struct in_pack {2635unsigned int alloc;2636unsigned int nr;2637struct in_pack_object *array;2638};26392640static voidmark_in_pack_object(struct object *object,struct packed_git *p,struct in_pack *in_pack)2641{2642 in_pack->array[in_pack->nr].offset =find_pack_entry_one(object->oid.hash, p);2643 in_pack->array[in_pack->nr].object = object;2644 in_pack->nr++;2645}26462647/*2648 * Compare the objects in the offset order, in order to emulate the2649 * "git rev-list --objects" output that produced the pack originally.2650 */2651static intofscmp(const void*a_,const void*b_)2652{2653struct in_pack_object *a = (struct in_pack_object *)a_;2654struct in_pack_object *b = (struct in_pack_object *)b_;26552656if(a->offset < b->offset)2657return-1;2658else if(a->offset > b->offset)2659return1;2660else2661returnoidcmp(&a->object->oid, &b->object->oid);2662}26632664static voidadd_objects_in_unpacked_packs(struct rev_info *revs)2665{2666struct packed_git *p;2667struct in_pack in_pack;2668uint32_t i;26692670memset(&in_pack,0,sizeof(in_pack));26712672for(p = packed_git; p; p = p->next) {2673struct object_id oid;2674struct object *o;26752676if(!p->pack_local || p->pack_keep)2677continue;2678if(open_pack_index(p))2679die("cannot open pack index");26802681ALLOC_GROW(in_pack.array,2682 in_pack.nr + p->num_objects,2683 in_pack.alloc);26842685for(i =0; i < p->num_objects; i++) {2686nth_packed_object_oid(&oid, p, i);2687 o =lookup_unknown_object(oid.hash);2688if(!(o->flags & OBJECT_ADDED))2689mark_in_pack_object(o, p, &in_pack);2690 o->flags |= OBJECT_ADDED;2691}2692}26932694if(in_pack.nr) {2695QSORT(in_pack.array, in_pack.nr, ofscmp);2696for(i =0; i < in_pack.nr; i++) {2697struct object *o = in_pack.array[i].object;2698add_object_entry(&o->oid, o->type,"",0);2699}2700}2701free(in_pack.array);2702}27032704static intadd_loose_object(const struct object_id *oid,const char*path,2705void*data)2706{2707enum object_type type =oid_object_info(oid, NULL);27082709if(type <0) {2710warning("loose object at%scould not be examined", path);2711return0;2712}27132714add_object_entry(oid, type,"",0);2715return0;2716}27172718/*2719 * We actually don't even have to worry about reachability here.2720 * add_object_entry will weed out duplicates, so we just add every2721 * loose object we find.2722 */2723static voidadd_unreachable_loose_objects(void)2724{2725for_each_loose_file_in_objdir(get_object_directory(),2726 add_loose_object,2727 NULL, NULL, NULL);2728}27292730static inthas_sha1_pack_kept_or_nonlocal(const struct object_id *oid)2731{2732static struct packed_git *last_found = (void*)1;2733struct packed_git *p;27342735 p = (last_found != (void*)1) ? last_found : packed_git;27362737while(p) {2738if((!p->pack_local || p->pack_keep) &&2739find_pack_entry_one(oid->hash, p)) {2740 last_found = p;2741return1;2742}2743if(p == last_found)2744 p = packed_git;2745else2746 p = p->next;2747if(p == last_found)2748 p = p->next;2749}2750return0;2751}27522753/*2754 * Store a list of sha1s that are should not be discarded2755 * because they are either written too recently, or are2756 * reachable from another object that was.2757 *2758 * This is filled by get_object_list.2759 */2760static struct oid_array recent_objects;27612762static intloosened_object_can_be_discarded(const struct object_id *oid,2763 timestamp_t mtime)2764{2765if(!unpack_unreachable_expiration)2766return0;2767if(mtime > unpack_unreachable_expiration)2768return0;2769if(oid_array_lookup(&recent_objects, oid) >=0)2770return0;2771return1;2772}27732774static voidloosen_unused_packed_objects(struct rev_info *revs)2775{2776struct packed_git *p;2777uint32_t i;2778struct object_id oid;27792780for(p = packed_git; p; p = p->next) {2781if(!p->pack_local || p->pack_keep)2782continue;27832784if(open_pack_index(p))2785die("cannot open pack index");27862787for(i =0; i < p->num_objects; i++) {2788nth_packed_object_oid(&oid, p, i);2789if(!packlist_find(&to_pack, oid.hash, NULL) &&2790!has_sha1_pack_kept_or_nonlocal(&oid) &&2791!loosened_object_can_be_discarded(&oid, p->mtime))2792if(force_object_loose(&oid, p->mtime))2793die("unable to force loose object");2794}2795}2796}27972798/*2799 * This tracks any options which pack-reuse code expects to be on, or which a2800 * reader of the pack might not understand, and which would therefore prevent2801 * blind reuse of what we have on disk.2802 */2803static intpack_options_allow_reuse(void)2804{2805return pack_to_stdout &&2806 allow_ofs_delta &&2807!ignore_packed_keep &&2808(!local || !have_non_local_packs) &&2809!incremental;2810}28112812static intget_object_list_from_bitmap(struct rev_info *revs)2813{2814if(prepare_bitmap_walk(revs) <0)2815return-1;28162817if(pack_options_allow_reuse() &&2818!reuse_partial_packfile_from_bitmap(2819&reuse_packfile,2820&reuse_packfile_objects,2821&reuse_packfile_offset)) {2822assert(reuse_packfile_objects);2823 nr_result += reuse_packfile_objects;2824display_progress(progress_state, nr_result);2825}28262827traverse_bitmap_commit_list(&add_object_entry_from_bitmap);2828return0;2829}28302831static voidrecord_recent_object(struct object *obj,2832const char*name,2833void*data)2834{2835oid_array_append(&recent_objects, &obj->oid);2836}28372838static voidrecord_recent_commit(struct commit *commit,void*data)2839{2840oid_array_append(&recent_objects, &commit->object.oid);2841}28422843static voidget_object_list(int ac,const char**av)2844{2845struct rev_info revs;2846char line[1000];2847int flags =0;28482849init_revisions(&revs, NULL);2850 save_commit_buffer =0;2851setup_revisions(ac, av, &revs, NULL);28522853/* make sure shallows are read */2854is_repository_shallow();28552856while(fgets(line,sizeof(line), stdin) != NULL) {2857int len =strlen(line);2858if(len && line[len -1] =='\n')2859 line[--len] =0;2860if(!len)2861break;2862if(*line =='-') {2863if(!strcmp(line,"--not")) {2864 flags ^= UNINTERESTING;2865 write_bitmap_index =0;2866continue;2867}2868if(starts_with(line,"--shallow ")) {2869struct object_id oid;2870if(get_oid_hex(line +10, &oid))2871die("not an SHA-1 '%s'", line +10);2872register_shallow(&oid);2873 use_bitmap_index =0;2874continue;2875}2876die("not a rev '%s'", line);2877}2878if(handle_revision_arg(line, &revs, flags, REVARG_CANNOT_BE_FILENAME))2879die("bad revision '%s'", line);2880}28812882if(use_bitmap_index && !get_object_list_from_bitmap(&revs))2883return;28842885if(prepare_revision_walk(&revs))2886die("revision walk setup failed");2887mark_edges_uninteresting(&revs, show_edge);28882889if(!fn_show_object)2890 fn_show_object = show_object;2891traverse_commit_list_filtered(&filter_options, &revs,2892 show_commit, fn_show_object, NULL,2893 NULL);28942895if(unpack_unreachable_expiration) {2896 revs.ignore_missing_links =1;2897if(add_unseen_recent_objects_to_traversal(&revs,2898 unpack_unreachable_expiration))2899die("unable to add recent objects");2900if(prepare_revision_walk(&revs))2901die("revision walk setup failed");2902traverse_commit_list(&revs, record_recent_commit,2903 record_recent_object, NULL);2904}29052906if(keep_unreachable)2907add_objects_in_unpacked_packs(&revs);2908if(pack_loose_unreachable)2909add_unreachable_loose_objects();2910if(unpack_unreachable)2911loosen_unused_packed_objects(&revs);29122913oid_array_clear(&recent_objects);2914}29152916static intoption_parse_index_version(const struct option *opt,2917const char*arg,int unset)2918{2919char*c;2920const char*val = arg;2921 pack_idx_opts.version =strtoul(val, &c,10);2922if(pack_idx_opts.version >2)2923die(_("unsupported index version%s"), val);2924if(*c ==','&& c[1])2925 pack_idx_opts.off32_limit =strtoul(c+1, &c,0);2926if(*c || pack_idx_opts.off32_limit &0x80000000)2927die(_("bad index version '%s'"), val);2928return0;2929}29302931static intoption_parse_unpack_unreachable(const struct option *opt,2932const char*arg,int unset)2933{2934if(unset) {2935 unpack_unreachable =0;2936 unpack_unreachable_expiration =0;2937}2938else{2939 unpack_unreachable =1;2940if(arg)2941 unpack_unreachable_expiration =approxidate(arg);2942}2943return0;2944}29452946intcmd_pack_objects(int argc,const char**argv,const char*prefix)2947{2948int use_internal_rev_list =0;2949int thin =0;2950int shallow =0;2951int all_progress_implied =0;2952struct argv_array rp = ARGV_ARRAY_INIT;2953int rev_list_unpacked =0, rev_list_all =0, rev_list_reflog =0;2954int rev_list_index =0;2955struct option pack_objects_options[] = {2956OPT_SET_INT('q',"quiet", &progress,2957N_("do not show progress meter"),0),2958OPT_SET_INT(0,"progress", &progress,2959N_("show progress meter"),1),2960OPT_SET_INT(0,"all-progress", &progress,2961N_("show progress meter during object writing phase"),2),2962OPT_BOOL(0,"all-progress-implied",2963&all_progress_implied,2964N_("similar to --all-progress when progress meter is shown")),2965{ OPTION_CALLBACK,0,"index-version", NULL,N_("version[,offset]"),2966N_("write the pack index file in the specified idx format version"),29670, option_parse_index_version },2968OPT_MAGNITUDE(0,"max-pack-size", &pack_size_limit,2969N_("maximum size of each output pack file")),2970OPT_BOOL(0,"local", &local,2971N_("ignore borrowed objects from alternate object store")),2972OPT_BOOL(0,"incremental", &incremental,2973N_("ignore packed objects")),2974OPT_INTEGER(0,"window", &window,2975N_("limit pack window by objects")),2976OPT_MAGNITUDE(0,"window-memory", &window_memory_limit,2977N_("limit pack window by memory in addition to object limit")),2978OPT_INTEGER(0,"depth", &depth,2979N_("maximum length of delta chain allowed in the resulting pack")),2980OPT_BOOL(0,"reuse-delta", &reuse_delta,2981N_("reuse existing deltas")),2982OPT_BOOL(0,"reuse-object", &reuse_object,2983N_("reuse existing objects")),2984OPT_BOOL(0,"delta-base-offset", &allow_ofs_delta,2985N_("use OFS_DELTA objects")),2986OPT_INTEGER(0,"threads", &delta_search_threads,2987N_("use threads when searching for best delta matches")),2988OPT_BOOL(0,"non-empty", &non_empty,2989N_("do not create an empty pack output")),2990OPT_BOOL(0,"revs", &use_internal_rev_list,2991N_("read revision arguments from standard input")),2992{ OPTION_SET_INT,0,"unpacked", &rev_list_unpacked, NULL,2993N_("limit the objects to those that are not yet packed"),2994 PARSE_OPT_NOARG | PARSE_OPT_NONEG, NULL,1},2995{ OPTION_SET_INT,0,"all", &rev_list_all, NULL,2996N_("include objects reachable from any reference"),2997 PARSE_OPT_NOARG | PARSE_OPT_NONEG, NULL,1},2998{ OPTION_SET_INT,0,"reflog", &rev_list_reflog, NULL,2999N_("include objects referred by reflog entries"),3000 PARSE_OPT_NOARG | PARSE_OPT_NONEG, NULL,1},3001{ OPTION_SET_INT,0,"indexed-objects", &rev_list_index, NULL,3002N_("include objects referred to by the index"),3003 PARSE_OPT_NOARG | PARSE_OPT_NONEG, NULL,1},3004OPT_BOOL(0,"stdout", &pack_to_stdout,3005N_("output pack to stdout")),3006OPT_BOOL(0,"include-tag", &include_tag,3007N_("include tag objects that refer to objects to be packed")),3008OPT_BOOL(0,"keep-unreachable", &keep_unreachable,3009N_("keep unreachable objects")),3010OPT_BOOL(0,"pack-loose-unreachable", &pack_loose_unreachable,3011N_("pack loose unreachable objects")),3012{ OPTION_CALLBACK,0,"unpack-unreachable", NULL,N_("time"),3013N_("unpack unreachable objects newer than <time>"),3014 PARSE_OPT_OPTARG, option_parse_unpack_unreachable },3015OPT_BOOL(0,"thin", &thin,3016N_("create thin packs")),3017OPT_BOOL(0,"shallow", &shallow,3018N_("create packs suitable for shallow fetches")),3019OPT_BOOL(0,"honor-pack-keep", &ignore_packed_keep,3020N_("ignore packs that have companion .keep file")),3021OPT_INTEGER(0,"compression", &pack_compression_level,3022N_("pack compression level")),3023OPT_SET_INT(0,"keep-true-parents", &grafts_replace_parents,3024N_("do not hide commits by grafts"),0),3025OPT_BOOL(0,"use-bitmap-index", &use_bitmap_index,3026N_("use a bitmap index if available to speed up counting objects")),3027OPT_BOOL(0,"write-bitmap-index", &write_bitmap_index,3028N_("write a bitmap index together with the pack index")),3029OPT_PARSE_LIST_OBJECTS_FILTER(&filter_options),3030{ OPTION_CALLBACK,0,"missing", NULL,N_("action"),3031N_("handling for missing objects"), PARSE_OPT_NONEG,3032 option_parse_missing_action },3033OPT_BOOL(0,"exclude-promisor-objects", &exclude_promisor_objects,3034N_("do not pack objects in promisor packfiles")),3035OPT_END(),3036};30373038 check_replace_refs =0;30393040reset_pack_idx_option(&pack_idx_opts);3041git_config(git_pack_config, NULL);30423043 progress =isatty(2);3044 argc =parse_options(argc, argv, prefix, pack_objects_options,3045 pack_usage,0);30463047if(argc) {3048 base_name = argv[0];3049 argc--;3050}3051if(pack_to_stdout != !base_name || argc)3052usage_with_options(pack_usage, pack_objects_options);30533054argv_array_push(&rp,"pack-objects");3055if(thin) {3056 use_internal_rev_list =1;3057argv_array_push(&rp, shallow3058?"--objects-edge-aggressive"3059:"--objects-edge");3060}else3061argv_array_push(&rp,"--objects");30623063if(rev_list_all) {3064 use_internal_rev_list =1;3065argv_array_push(&rp,"--all");3066}3067if(rev_list_reflog) {3068 use_internal_rev_list =1;3069argv_array_push(&rp,"--reflog");3070}3071if(rev_list_index) {3072 use_internal_rev_list =1;3073argv_array_push(&rp,"--indexed-objects");3074}3075if(rev_list_unpacked) {3076 use_internal_rev_list =1;3077argv_array_push(&rp,"--unpacked");3078}30793080if(exclude_promisor_objects) {3081 use_internal_rev_list =1;3082 fetch_if_missing =0;3083argv_array_push(&rp,"--exclude-promisor-objects");3084}30853086if(!reuse_object)3087 reuse_delta =0;3088if(pack_compression_level == -1)3089 pack_compression_level = Z_DEFAULT_COMPRESSION;3090else if(pack_compression_level <0|| pack_compression_level > Z_BEST_COMPRESSION)3091die("bad pack compression level%d", pack_compression_level);30923093if(!delta_search_threads)/* --threads=0 means autodetect */3094 delta_search_threads =online_cpus();30953096#ifdef NO_PTHREADS3097if(delta_search_threads !=1)3098warning("no threads support, ignoring --threads");3099#endif3100if(!pack_to_stdout && !pack_size_limit)3101 pack_size_limit = pack_size_limit_cfg;3102if(pack_to_stdout && pack_size_limit)3103die("--max-pack-size cannot be used to build a pack for transfer.");3104if(pack_size_limit && pack_size_limit <1024*1024) {3105warning("minimum pack size limit is 1 MiB");3106 pack_size_limit =1024*1024;3107}31083109if(!pack_to_stdout && thin)3110die("--thin cannot be used to build an indexable pack.");31113112if(keep_unreachable && unpack_unreachable)3113die("--keep-unreachable and --unpack-unreachable are incompatible.");3114if(!rev_list_all || !rev_list_reflog || !rev_list_index)3115 unpack_unreachable_expiration =0;31163117if(filter_options.choice) {3118if(!pack_to_stdout)3119die("cannot use --filter without --stdout.");3120 use_bitmap_index =0;3121}31223123/*3124 * "soft" reasons not to use bitmaps - for on-disk repack by default we want3125 *3126 * - to produce good pack (with bitmap index not-yet-packed objects are3127 * packed in suboptimal order).3128 *3129 * - to use more robust pack-generation codepath (avoiding possible3130 * bugs in bitmap code and possible bitmap index corruption).3131 */3132if(!pack_to_stdout)3133 use_bitmap_index_default =0;31343135if(use_bitmap_index <0)3136 use_bitmap_index = use_bitmap_index_default;31373138/* "hard" reasons not to use bitmaps; these just won't work at all */3139if(!use_internal_rev_list || (!pack_to_stdout && write_bitmap_index) ||is_repository_shallow())3140 use_bitmap_index =0;31413142if(pack_to_stdout || !rev_list_all)3143 write_bitmap_index =0;31443145if(progress && all_progress_implied)3146 progress =2;31473148prepare_packed_git();3149if(ignore_packed_keep) {3150struct packed_git *p;3151for(p = packed_git; p; p = p->next)3152if(p->pack_local && p->pack_keep)3153break;3154if(!p)/* no keep-able packs found */3155 ignore_packed_keep =0;3156}3157if(local) {3158/*3159 * unlike ignore_packed_keep above, we do not want to3160 * unset "local" based on looking at packs, as it3161 * also covers non-local objects3162 */3163struct packed_git *p;3164for(p = packed_git; p; p = p->next) {3165if(!p->pack_local) {3166 have_non_local_packs =1;3167break;3168}3169}3170}31713172if(progress)3173 progress_state =start_progress(_("Counting objects"),0);3174if(!use_internal_rev_list)3175read_object_list_from_stdin();3176else{3177get_object_list(rp.argc, rp.argv);3178argv_array_clear(&rp);3179}3180cleanup_preferred_base();3181if(include_tag && nr_result)3182for_each_ref(add_ref_tag, NULL);3183stop_progress(&progress_state);31843185if(non_empty && !nr_result)3186return0;3187if(nr_result)3188prepare_pack(window, depth);3189write_pack_file();3190if(progress)3191fprintf(stderr,"Total %"PRIu32" (delta %"PRIu32"),"3192" reused %"PRIu32" (delta %"PRIu32")\n",3193 written, written_delta, reused, reused_delta);3194return0;3195}