1#include"builtin.h" 2#include"cache.h" 3#include"attr.h" 4#include"object.h" 5#include"blob.h" 6#include"commit.h" 7#include"tag.h" 8#include"tree.h" 9#include"delta.h" 10#include"pack.h" 11#include"pack-revindex.h" 12#include"csum-file.h" 13#include"tree-walk.h" 14#include"diff.h" 15#include"revision.h" 16#include"list-objects.h" 17#include"pack-objects.h" 18#include"progress.h" 19#include"refs.h" 20#include"streaming.h" 21#include"thread-utils.h" 22#include"pack-bitmap.h" 23#include"reachable.h" 24#include"sha1-array.h" 25#include"argv-array.h" 26#include"mru.h" 27 28static const char*pack_usage[] = { 29N_("git pack-objects --stdout [<options>...] [< <ref-list> | < <object-list>]"), 30N_("git pack-objects [<options>...] <base-name> [< <ref-list> | < <object-list>]"), 31 NULL 32}; 33 34/* 35 * Objects we are going to pack are collected in the `to_pack` structure. 36 * It contains an array (dynamically expanded) of the object data, and a map 37 * that can resolve SHA1s to their position in the array. 38 */ 39static struct packing_data to_pack; 40 41static struct pack_idx_entry **written_list; 42static uint32_t nr_result, nr_written; 43 44static int non_empty; 45static int reuse_delta =1, reuse_object =1; 46static int keep_unreachable, unpack_unreachable, include_tag; 47static unsigned long unpack_unreachable_expiration; 48static int pack_loose_unreachable; 49static int local; 50static int have_non_local_packs; 51static int incremental; 52static int ignore_packed_keep; 53static int allow_ofs_delta; 54static struct pack_idx_option pack_idx_opts; 55static const char*base_name; 56static int progress =1; 57static int window =10; 58static unsigned long pack_size_limit; 59static int depth =50; 60static int delta_search_threads; 61static int pack_to_stdout; 62static int num_preferred_base; 63static struct progress *progress_state; 64static int pack_compression_level = Z_DEFAULT_COMPRESSION; 65static int pack_compression_seen; 66 67static struct packed_git *reuse_packfile; 68static uint32_t reuse_packfile_objects; 69static off_t reuse_packfile_offset; 70 71static int use_bitmap_index_default =1; 72static int use_bitmap_index = -1; 73static int write_bitmap_index; 74static uint16_t write_bitmap_options; 75 76static unsigned long delta_cache_size =0; 77static unsigned long max_delta_cache_size =256*1024*1024; 78static unsigned long cache_max_small_delta_size =1000; 79 80static unsigned long window_memory_limit =0; 81 82/* 83 * stats 84 */ 85static uint32_t written, written_delta; 86static uint32_t reused, reused_delta; 87 88/* 89 * Indexed commits 90 */ 91static struct commit **indexed_commits; 92static unsigned int indexed_commits_nr; 93static unsigned int indexed_commits_alloc; 94 95static voidindex_commit_for_bitmap(struct commit *commit) 96{ 97if(indexed_commits_nr >= indexed_commits_alloc) { 98 indexed_commits_alloc = (indexed_commits_alloc +32) *2; 99REALLOC_ARRAY(indexed_commits, indexed_commits_alloc); 100} 101 102 indexed_commits[indexed_commits_nr++] = commit; 103} 104 105static void*get_delta(struct object_entry *entry) 106{ 107unsigned long size, base_size, delta_size; 108void*buf, *base_buf, *delta_buf; 109enum object_type type; 110 111 buf =read_sha1_file(entry->idx.sha1, &type, &size); 112if(!buf) 113die("unable to read%s",sha1_to_hex(entry->idx.sha1)); 114 base_buf =read_sha1_file(entry->delta->idx.sha1, &type, &base_size); 115if(!base_buf) 116die("unable to read%s",sha1_to_hex(entry->delta->idx.sha1)); 117 delta_buf =diff_delta(base_buf, base_size, 118 buf, size, &delta_size,0); 119if(!delta_buf || delta_size != entry->delta_size) 120die("delta size changed"); 121free(buf); 122free(base_buf); 123return delta_buf; 124} 125 126static unsigned longdo_compress(void**pptr,unsigned long size) 127{ 128 git_zstream stream; 129void*in, *out; 130unsigned long maxsize; 131 132git_deflate_init(&stream, pack_compression_level); 133 maxsize =git_deflate_bound(&stream, size); 134 135 in = *pptr; 136 out =xmalloc(maxsize); 137*pptr = out; 138 139 stream.next_in = in; 140 stream.avail_in = size; 141 stream.next_out = out; 142 stream.avail_out = maxsize; 143while(git_deflate(&stream, Z_FINISH) == Z_OK) 144;/* nothing */ 145git_deflate_end(&stream); 146 147free(in); 148return stream.total_out; 149} 150 151static unsigned longwrite_large_blob_data(struct git_istream *st,struct sha1file *f, 152const unsigned char*sha1) 153{ 154 git_zstream stream; 155unsigned char ibuf[1024*16]; 156unsigned char obuf[1024*16]; 157unsigned long olen =0; 158 159git_deflate_init(&stream, pack_compression_level); 160 161for(;;) { 162 ssize_t readlen; 163int zret = Z_OK; 164 readlen =read_istream(st, ibuf,sizeof(ibuf)); 165if(readlen == -1) 166die(_("unable to read%s"),sha1_to_hex(sha1)); 167 168 stream.next_in = ibuf; 169 stream.avail_in = readlen; 170while((stream.avail_in || readlen ==0) && 171(zret == Z_OK || zret == Z_BUF_ERROR)) { 172 stream.next_out = obuf; 173 stream.avail_out =sizeof(obuf); 174 zret =git_deflate(&stream, readlen ?0: Z_FINISH); 175sha1write(f, obuf, stream.next_out - obuf); 176 olen += stream.next_out - obuf; 177} 178if(stream.avail_in) 179die(_("deflate error (%d)"), zret); 180if(readlen ==0) { 181if(zret != Z_STREAM_END) 182die(_("deflate error (%d)"), zret); 183break; 184} 185} 186git_deflate_end(&stream); 187return olen; 188} 189 190/* 191 * we are going to reuse the existing object data as is. make 192 * sure it is not corrupt. 193 */ 194static intcheck_pack_inflate(struct packed_git *p, 195struct pack_window **w_curs, 196 off_t offset, 197 off_t len, 198unsigned long expect) 199{ 200 git_zstream stream; 201unsigned char fakebuf[4096], *in; 202int st; 203 204memset(&stream,0,sizeof(stream)); 205git_inflate_init(&stream); 206do{ 207 in =use_pack(p, w_curs, offset, &stream.avail_in); 208 stream.next_in = in; 209 stream.next_out = fakebuf; 210 stream.avail_out =sizeof(fakebuf); 211 st =git_inflate(&stream, Z_FINISH); 212 offset += stream.next_in - in; 213}while(st == Z_OK || st == Z_BUF_ERROR); 214git_inflate_end(&stream); 215return(st == Z_STREAM_END && 216 stream.total_out == expect && 217 stream.total_in == len) ?0: -1; 218} 219 220static voidcopy_pack_data(struct sha1file *f, 221struct packed_git *p, 222struct pack_window **w_curs, 223 off_t offset, 224 off_t len) 225{ 226unsigned char*in; 227unsigned long avail; 228 229while(len) { 230 in =use_pack(p, w_curs, offset, &avail); 231if(avail > len) 232 avail = (unsigned long)len; 233sha1write(f, in, avail); 234 offset += avail; 235 len -= avail; 236} 237} 238 239/* Return 0 if we will bust the pack-size limit */ 240static unsigned longwrite_no_reuse_object(struct sha1file *f,struct object_entry *entry, 241unsigned long limit,int usable_delta) 242{ 243unsigned long size, datalen; 244unsigned char header[10], dheader[10]; 245unsigned hdrlen; 246enum object_type type; 247void*buf; 248struct git_istream *st = NULL; 249 250if(!usable_delta) { 251if(entry->type == OBJ_BLOB && 252 entry->size > big_file_threshold && 253(st =open_istream(entry->idx.sha1, &type, &size, NULL)) != NULL) 254 buf = NULL; 255else{ 256 buf =read_sha1_file(entry->idx.sha1, &type, &size); 257if(!buf) 258die(_("unable to read%s"),sha1_to_hex(entry->idx.sha1)); 259} 260/* 261 * make sure no cached delta data remains from a 262 * previous attempt before a pack split occurred. 263 */ 264free(entry->delta_data); 265 entry->delta_data = NULL; 266 entry->z_delta_size =0; 267}else if(entry->delta_data) { 268 size = entry->delta_size; 269 buf = entry->delta_data; 270 entry->delta_data = NULL; 271 type = (allow_ofs_delta && entry->delta->idx.offset) ? 272 OBJ_OFS_DELTA : OBJ_REF_DELTA; 273}else{ 274 buf =get_delta(entry); 275 size = entry->delta_size; 276 type = (allow_ofs_delta && entry->delta->idx.offset) ? 277 OBJ_OFS_DELTA : OBJ_REF_DELTA; 278} 279 280if(st)/* large blob case, just assume we don't compress well */ 281 datalen = size; 282else if(entry->z_delta_size) 283 datalen = entry->z_delta_size; 284else 285 datalen =do_compress(&buf, size); 286 287/* 288 * The object header is a byte of 'type' followed by zero or 289 * more bytes of length. 290 */ 291 hdrlen =encode_in_pack_object_header(type, size, header); 292 293if(type == OBJ_OFS_DELTA) { 294/* 295 * Deltas with relative base contain an additional 296 * encoding of the relative offset for the delta 297 * base from this object's position in the pack. 298 */ 299 off_t ofs = entry->idx.offset - entry->delta->idx.offset; 300unsigned pos =sizeof(dheader) -1; 301 dheader[pos] = ofs &127; 302while(ofs >>=7) 303 dheader[--pos] =128| (--ofs &127); 304if(limit && hdrlen +sizeof(dheader) - pos + datalen +20>= limit) { 305if(st) 306close_istream(st); 307free(buf); 308return0; 309} 310sha1write(f, header, hdrlen); 311sha1write(f, dheader + pos,sizeof(dheader) - pos); 312 hdrlen +=sizeof(dheader) - pos; 313}else if(type == OBJ_REF_DELTA) { 314/* 315 * Deltas with a base reference contain 316 * an additional 20 bytes for the base sha1. 317 */ 318if(limit && hdrlen +20+ datalen +20>= limit) { 319if(st) 320close_istream(st); 321free(buf); 322return0; 323} 324sha1write(f, header, hdrlen); 325sha1write(f, entry->delta->idx.sha1,20); 326 hdrlen +=20; 327}else{ 328if(limit && hdrlen + datalen +20>= limit) { 329if(st) 330close_istream(st); 331free(buf); 332return0; 333} 334sha1write(f, header, hdrlen); 335} 336if(st) { 337 datalen =write_large_blob_data(st, f, entry->idx.sha1); 338close_istream(st); 339}else{ 340sha1write(f, buf, datalen); 341free(buf); 342} 343 344return hdrlen + datalen; 345} 346 347/* Return 0 if we will bust the pack-size limit */ 348static off_t write_reuse_object(struct sha1file *f,struct object_entry *entry, 349unsigned long limit,int usable_delta) 350{ 351struct packed_git *p = entry->in_pack; 352struct pack_window *w_curs = NULL; 353struct revindex_entry *revidx; 354 off_t offset; 355enum object_type type = entry->type; 356 off_t datalen; 357unsigned char header[10], dheader[10]; 358unsigned hdrlen; 359 360if(entry->delta) 361 type = (allow_ofs_delta && entry->delta->idx.offset) ? 362 OBJ_OFS_DELTA : OBJ_REF_DELTA; 363 hdrlen =encode_in_pack_object_header(type, entry->size, header); 364 365 offset = entry->in_pack_offset; 366 revidx =find_pack_revindex(p, offset); 367 datalen = revidx[1].offset - offset; 368if(!pack_to_stdout && p->index_version >1&& 369check_pack_crc(p, &w_curs, offset, datalen, revidx->nr)) { 370error("bad packed object CRC for%s",sha1_to_hex(entry->idx.sha1)); 371unuse_pack(&w_curs); 372returnwrite_no_reuse_object(f, entry, limit, usable_delta); 373} 374 375 offset += entry->in_pack_header_size; 376 datalen -= entry->in_pack_header_size; 377 378if(!pack_to_stdout && p->index_version ==1&& 379check_pack_inflate(p, &w_curs, offset, datalen, entry->size)) { 380error("corrupt packed object for%s",sha1_to_hex(entry->idx.sha1)); 381unuse_pack(&w_curs); 382returnwrite_no_reuse_object(f, entry, limit, usable_delta); 383} 384 385if(type == OBJ_OFS_DELTA) { 386 off_t ofs = entry->idx.offset - entry->delta->idx.offset; 387unsigned pos =sizeof(dheader) -1; 388 dheader[pos] = ofs &127; 389while(ofs >>=7) 390 dheader[--pos] =128| (--ofs &127); 391if(limit && hdrlen +sizeof(dheader) - pos + datalen +20>= limit) { 392unuse_pack(&w_curs); 393return0; 394} 395sha1write(f, header, hdrlen); 396sha1write(f, dheader + pos,sizeof(dheader) - pos); 397 hdrlen +=sizeof(dheader) - pos; 398 reused_delta++; 399}else if(type == OBJ_REF_DELTA) { 400if(limit && hdrlen +20+ datalen +20>= limit) { 401unuse_pack(&w_curs); 402return0; 403} 404sha1write(f, header, hdrlen); 405sha1write(f, entry->delta->idx.sha1,20); 406 hdrlen +=20; 407 reused_delta++; 408}else{ 409if(limit && hdrlen + datalen +20>= limit) { 410unuse_pack(&w_curs); 411return0; 412} 413sha1write(f, header, hdrlen); 414} 415copy_pack_data(f, p, &w_curs, offset, datalen); 416unuse_pack(&w_curs); 417 reused++; 418return hdrlen + datalen; 419} 420 421/* Return 0 if we will bust the pack-size limit */ 422static off_t write_object(struct sha1file *f, 423struct object_entry *entry, 424 off_t write_offset) 425{ 426unsigned long limit; 427 off_t len; 428int usable_delta, to_reuse; 429 430if(!pack_to_stdout) 431crc32_begin(f); 432 433/* apply size limit if limited packsize and not first object */ 434if(!pack_size_limit || !nr_written) 435 limit =0; 436else if(pack_size_limit <= write_offset) 437/* 438 * the earlier object did not fit the limit; avoid 439 * mistaking this with unlimited (i.e. limit = 0). 440 */ 441 limit =1; 442else 443 limit = pack_size_limit - write_offset; 444 445if(!entry->delta) 446 usable_delta =0;/* no delta */ 447else if(!pack_size_limit) 448 usable_delta =1;/* unlimited packfile */ 449else if(entry->delta->idx.offset == (off_t)-1) 450 usable_delta =0;/* base was written to another pack */ 451else if(entry->delta->idx.offset) 452 usable_delta =1;/* base already exists in this pack */ 453else 454 usable_delta =0;/* base could end up in another pack */ 455 456if(!reuse_object) 457 to_reuse =0;/* explicit */ 458else if(!entry->in_pack) 459 to_reuse =0;/* can't reuse what we don't have */ 460else if(entry->type == OBJ_REF_DELTA || entry->type == OBJ_OFS_DELTA) 461/* check_object() decided it for us ... */ 462 to_reuse = usable_delta; 463/* ... but pack split may override that */ 464else if(entry->type != entry->in_pack_type) 465 to_reuse =0;/* pack has delta which is unusable */ 466else if(entry->delta) 467 to_reuse =0;/* we want to pack afresh */ 468else 469 to_reuse =1;/* we have it in-pack undeltified, 470 * and we do not need to deltify it. 471 */ 472 473if(!to_reuse) 474 len =write_no_reuse_object(f, entry, limit, usable_delta); 475else 476 len =write_reuse_object(f, entry, limit, usable_delta); 477if(!len) 478return0; 479 480if(usable_delta) 481 written_delta++; 482 written++; 483if(!pack_to_stdout) 484 entry->idx.crc32 =crc32_end(f); 485return len; 486} 487 488enum write_one_status { 489 WRITE_ONE_SKIP = -1,/* already written */ 490 WRITE_ONE_BREAK =0,/* writing this will bust the limit; not written */ 491 WRITE_ONE_WRITTEN =1,/* normal */ 492 WRITE_ONE_RECURSIVE =2/* already scheduled to be written */ 493}; 494 495static enum write_one_status write_one(struct sha1file *f, 496struct object_entry *e, 497 off_t *offset) 498{ 499 off_t size; 500int recursing; 501 502/* 503 * we set offset to 1 (which is an impossible value) to mark 504 * the fact that this object is involved in "write its base 505 * first before writing a deltified object" recursion. 506 */ 507 recursing = (e->idx.offset ==1); 508if(recursing) { 509warning("recursive delta detected for object%s", 510sha1_to_hex(e->idx.sha1)); 511return WRITE_ONE_RECURSIVE; 512}else if(e->idx.offset || e->preferred_base) { 513/* offset is non zero if object is written already. */ 514return WRITE_ONE_SKIP; 515} 516 517/* if we are deltified, write out base object first. */ 518if(e->delta) { 519 e->idx.offset =1;/* now recurse */ 520switch(write_one(f, e->delta, offset)) { 521case WRITE_ONE_RECURSIVE: 522/* we cannot depend on this one */ 523 e->delta = NULL; 524break; 525default: 526break; 527case WRITE_ONE_BREAK: 528 e->idx.offset = recursing; 529return WRITE_ONE_BREAK; 530} 531} 532 533 e->idx.offset = *offset; 534 size =write_object(f, e, *offset); 535if(!size) { 536 e->idx.offset = recursing; 537return WRITE_ONE_BREAK; 538} 539 written_list[nr_written++] = &e->idx; 540 541/* make sure off_t is sufficiently large not to wrap */ 542if(signed_add_overflows(*offset, size)) 543die("pack too large for current definition of off_t"); 544*offset += size; 545return WRITE_ONE_WRITTEN; 546} 547 548static intmark_tagged(const char*path,const struct object_id *oid,int flag, 549void*cb_data) 550{ 551unsigned char peeled[20]; 552struct object_entry *entry =packlist_find(&to_pack, oid->hash, NULL); 553 554if(entry) 555 entry->tagged =1; 556if(!peel_ref(path, peeled)) { 557 entry =packlist_find(&to_pack, peeled, NULL); 558if(entry) 559 entry->tagged =1; 560} 561return0; 562} 563 564staticinlinevoidadd_to_write_order(struct object_entry **wo, 565unsigned int*endp, 566struct object_entry *e) 567{ 568if(e->filled) 569return; 570 wo[(*endp)++] = e; 571 e->filled =1; 572} 573 574static voidadd_descendants_to_write_order(struct object_entry **wo, 575unsigned int*endp, 576struct object_entry *e) 577{ 578int add_to_order =1; 579while(e) { 580if(add_to_order) { 581struct object_entry *s; 582/* add this node... */ 583add_to_write_order(wo, endp, e); 584/* all its siblings... */ 585for(s = e->delta_sibling; s; s = s->delta_sibling) { 586add_to_write_order(wo, endp, s); 587} 588} 589/* drop down a level to add left subtree nodes if possible */ 590if(e->delta_child) { 591 add_to_order =1; 592 e = e->delta_child; 593}else{ 594 add_to_order =0; 595/* our sibling might have some children, it is next */ 596if(e->delta_sibling) { 597 e = e->delta_sibling; 598continue; 599} 600/* go back to our parent node */ 601 e = e->delta; 602while(e && !e->delta_sibling) { 603/* we're on the right side of a subtree, keep 604 * going up until we can go right again */ 605 e = e->delta; 606} 607if(!e) { 608/* done- we hit our original root node */ 609return; 610} 611/* pass it off to sibling at this level */ 612 e = e->delta_sibling; 613} 614}; 615} 616 617static voidadd_family_to_write_order(struct object_entry **wo, 618unsigned int*endp, 619struct object_entry *e) 620{ 621struct object_entry *root; 622 623for(root = e; root->delta; root = root->delta) 624;/* nothing */ 625add_descendants_to_write_order(wo, endp, root); 626} 627 628static struct object_entry **compute_write_order(void) 629{ 630unsigned int i, wo_end, last_untagged; 631 632struct object_entry **wo; 633struct object_entry *objects = to_pack.objects; 634 635for(i =0; i < to_pack.nr_objects; i++) { 636 objects[i].tagged =0; 637 objects[i].filled =0; 638 objects[i].delta_child = NULL; 639 objects[i].delta_sibling = NULL; 640} 641 642/* 643 * Fully connect delta_child/delta_sibling network. 644 * Make sure delta_sibling is sorted in the original 645 * recency order. 646 */ 647for(i = to_pack.nr_objects; i >0;) { 648struct object_entry *e = &objects[--i]; 649if(!e->delta) 650continue; 651/* Mark me as the first child */ 652 e->delta_sibling = e->delta->delta_child; 653 e->delta->delta_child = e; 654} 655 656/* 657 * Mark objects that are at the tip of tags. 658 */ 659for_each_tag_ref(mark_tagged, NULL); 660 661/* 662 * Give the objects in the original recency order until 663 * we see a tagged tip. 664 */ 665ALLOC_ARRAY(wo, to_pack.nr_objects); 666for(i = wo_end =0; i < to_pack.nr_objects; i++) { 667if(objects[i].tagged) 668break; 669add_to_write_order(wo, &wo_end, &objects[i]); 670} 671 last_untagged = i; 672 673/* 674 * Then fill all the tagged tips. 675 */ 676for(; i < to_pack.nr_objects; i++) { 677if(objects[i].tagged) 678add_to_write_order(wo, &wo_end, &objects[i]); 679} 680 681/* 682 * And then all remaining commits and tags. 683 */ 684for(i = last_untagged; i < to_pack.nr_objects; i++) { 685if(objects[i].type != OBJ_COMMIT && 686 objects[i].type != OBJ_TAG) 687continue; 688add_to_write_order(wo, &wo_end, &objects[i]); 689} 690 691/* 692 * And then all the trees. 693 */ 694for(i = last_untagged; i < to_pack.nr_objects; i++) { 695if(objects[i].type != OBJ_TREE) 696continue; 697add_to_write_order(wo, &wo_end, &objects[i]); 698} 699 700/* 701 * Finally all the rest in really tight order 702 */ 703for(i = last_untagged; i < to_pack.nr_objects; i++) { 704if(!objects[i].filled) 705add_family_to_write_order(wo, &wo_end, &objects[i]); 706} 707 708if(wo_end != to_pack.nr_objects) 709die("ordered%uobjects, expected %"PRIu32, wo_end, to_pack.nr_objects); 710 711return wo; 712} 713 714static off_t write_reused_pack(struct sha1file *f) 715{ 716unsigned char buffer[8192]; 717 off_t to_write, total; 718int fd; 719 720if(!is_pack_valid(reuse_packfile)) 721die("packfile is invalid:%s", reuse_packfile->pack_name); 722 723 fd =git_open(reuse_packfile->pack_name); 724if(fd <0) 725die_errno("unable to open packfile for reuse:%s", 726 reuse_packfile->pack_name); 727 728if(lseek(fd,sizeof(struct pack_header), SEEK_SET) == -1) 729die_errno("unable to seek in reused packfile"); 730 731if(reuse_packfile_offset <0) 732 reuse_packfile_offset = reuse_packfile->pack_size -20; 733 734 total = to_write = reuse_packfile_offset -sizeof(struct pack_header); 735 736while(to_write) { 737int read_pack =xread(fd, buffer,sizeof(buffer)); 738 739if(read_pack <=0) 740die_errno("unable to read from reused packfile"); 741 742if(read_pack > to_write) 743 read_pack = to_write; 744 745sha1write(f, buffer, read_pack); 746 to_write -= read_pack; 747 748/* 749 * We don't know the actual number of objects written, 750 * only how many bytes written, how many bytes total, and 751 * how many objects total. So we can fake it by pretending all 752 * objects we are writing are the same size. This gives us a 753 * smooth progress meter, and at the end it matches the true 754 * answer. 755 */ 756 written = reuse_packfile_objects * 757(((double)(total - to_write)) / total); 758display_progress(progress_state, written); 759} 760 761close(fd); 762 written = reuse_packfile_objects; 763display_progress(progress_state, written); 764return reuse_packfile_offset -sizeof(struct pack_header); 765} 766 767static const char no_split_warning[] =N_( 768"disabling bitmap writing, packs are split due to pack.packSizeLimit" 769); 770 771static voidwrite_pack_file(void) 772{ 773uint32_t i =0, j; 774struct sha1file *f; 775 off_t offset; 776uint32_t nr_remaining = nr_result; 777time_t last_mtime =0; 778struct object_entry **write_order; 779 780if(progress > pack_to_stdout) 781 progress_state =start_progress(_("Writing objects"), nr_result); 782ALLOC_ARRAY(written_list, to_pack.nr_objects); 783 write_order =compute_write_order(); 784 785do{ 786unsigned char sha1[20]; 787char*pack_tmp_name = NULL; 788 789if(pack_to_stdout) 790 f =sha1fd_throughput(1,"<stdout>", progress_state); 791else 792 f =create_tmp_packfile(&pack_tmp_name); 793 794 offset =write_pack_header(f, nr_remaining); 795 796if(reuse_packfile) { 797 off_t packfile_size; 798assert(pack_to_stdout); 799 800 packfile_size =write_reused_pack(f); 801 offset += packfile_size; 802} 803 804 nr_written =0; 805for(; i < to_pack.nr_objects; i++) { 806struct object_entry *e = write_order[i]; 807if(write_one(f, e, &offset) == WRITE_ONE_BREAK) 808break; 809display_progress(progress_state, written); 810} 811 812/* 813 * Did we write the wrong # entries in the header? 814 * If so, rewrite it like in fast-import 815 */ 816if(pack_to_stdout) { 817sha1close(f, sha1, CSUM_CLOSE); 818}else if(nr_written == nr_remaining) { 819sha1close(f, sha1, CSUM_FSYNC); 820}else{ 821int fd =sha1close(f, sha1,0); 822fixup_pack_header_footer(fd, sha1, pack_tmp_name, 823 nr_written, sha1, offset); 824close(fd); 825if(write_bitmap_index) { 826warning(_(no_split_warning)); 827 write_bitmap_index =0; 828} 829} 830 831if(!pack_to_stdout) { 832struct stat st; 833struct strbuf tmpname = STRBUF_INIT; 834 835/* 836 * Packs are runtime accessed in their mtime 837 * order since newer packs are more likely to contain 838 * younger objects. So if we are creating multiple 839 * packs then we should modify the mtime of later ones 840 * to preserve this property. 841 */ 842if(stat(pack_tmp_name, &st) <0) { 843warning_errno("failed to stat%s", pack_tmp_name); 844}else if(!last_mtime) { 845 last_mtime = st.st_mtime; 846}else{ 847struct utimbuf utb; 848 utb.actime = st.st_atime; 849 utb.modtime = --last_mtime; 850if(utime(pack_tmp_name, &utb) <0) 851warning_errno("failed utime() on%s", pack_tmp_name); 852} 853 854strbuf_addf(&tmpname,"%s-", base_name); 855 856if(write_bitmap_index) { 857bitmap_writer_set_checksum(sha1); 858bitmap_writer_build_type_index(written_list, nr_written); 859} 860 861finish_tmp_packfile(&tmpname, pack_tmp_name, 862 written_list, nr_written, 863&pack_idx_opts, sha1); 864 865if(write_bitmap_index) { 866strbuf_addf(&tmpname,"%s.bitmap",sha1_to_hex(sha1)); 867 868stop_progress(&progress_state); 869 870bitmap_writer_show_progress(progress); 871bitmap_writer_reuse_bitmaps(&to_pack); 872bitmap_writer_select_commits(indexed_commits, indexed_commits_nr, -1); 873bitmap_writer_build(&to_pack); 874bitmap_writer_finish(written_list, nr_written, 875 tmpname.buf, write_bitmap_options); 876 write_bitmap_index =0; 877} 878 879strbuf_release(&tmpname); 880free(pack_tmp_name); 881puts(sha1_to_hex(sha1)); 882} 883 884/* mark written objects as written to previous pack */ 885for(j =0; j < nr_written; j++) { 886 written_list[j]->offset = (off_t)-1; 887} 888 nr_remaining -= nr_written; 889}while(nr_remaining && i < to_pack.nr_objects); 890 891free(written_list); 892free(write_order); 893stop_progress(&progress_state); 894if(written != nr_result) 895die("wrote %"PRIu32" objects while expecting %"PRIu32, 896 written, nr_result); 897} 898 899static voidsetup_delta_attr_check(struct git_attr_check *check) 900{ 901static struct git_attr *attr_delta; 902 903if(!attr_delta) 904 attr_delta =git_attr("delta"); 905 906 check[0].attr = attr_delta; 907} 908 909static intno_try_delta(const char*path) 910{ 911struct git_attr_check check[1]; 912 913setup_delta_attr_check(check); 914if(git_check_attr(path,ARRAY_SIZE(check), check)) 915return0; 916if(ATTR_FALSE(check->value)) 917return1; 918return0; 919} 920 921/* 922 * When adding an object, check whether we have already added it 923 * to our packing list. If so, we can skip. However, if we are 924 * being asked to excludei t, but the previous mention was to include 925 * it, make sure to adjust its flags and tweak our numbers accordingly. 926 * 927 * As an optimization, we pass out the index position where we would have 928 * found the item, since that saves us from having to look it up again a 929 * few lines later when we want to add the new entry. 930 */ 931static inthave_duplicate_entry(const unsigned char*sha1, 932int exclude, 933uint32_t*index_pos) 934{ 935struct object_entry *entry; 936 937 entry =packlist_find(&to_pack, sha1, index_pos); 938if(!entry) 939return0; 940 941if(exclude) { 942if(!entry->preferred_base) 943 nr_result--; 944 entry->preferred_base =1; 945} 946 947return1; 948} 949 950static intwant_found_object(int exclude,struct packed_git *p) 951{ 952if(exclude) 953return1; 954if(incremental) 955return0; 956 957/* 958 * When asked to do --local (do not include an object that appears in a 959 * pack we borrow from elsewhere) or --honor-pack-keep (do not include 960 * an object that appears in a pack marked with .keep), finding a pack 961 * that matches the criteria is sufficient for us to decide to omit it. 962 * However, even if this pack does not satisfy the criteria, we need to 963 * make sure no copy of this object appears in _any_ pack that makes us 964 * to omit the object, so we need to check all the packs. 965 * 966 * We can however first check whether these options can possible matter; 967 * if they do not matter we know we want the object in generated pack. 968 * Otherwise, we signal "-1" at the end to tell the caller that we do 969 * not know either way, and it needs to check more packs. 970 */ 971if(!ignore_packed_keep && 972(!local || !have_non_local_packs)) 973return1; 974 975if(local && !p->pack_local) 976return0; 977if(ignore_packed_keep && p->pack_local && p->pack_keep) 978return0; 979 980/* we don't know yet; keep looking for more packs */ 981return-1; 982} 983 984/* 985 * Check whether we want the object in the pack (e.g., we do not want 986 * objects found in non-local stores if the "--local" option was used). 987 * 988 * If the caller already knows an existing pack it wants to take the object 989 * from, that is passed in *found_pack and *found_offset; otherwise this 990 * function finds if there is any pack that has the object and returns the pack 991 * and its offset in these variables. 992 */ 993static intwant_object_in_pack(const unsigned char*sha1, 994int exclude, 995struct packed_git **found_pack, 996 off_t *found_offset) 997{ 998struct mru_entry *entry; 999int want;10001001if(!exclude && local &&has_loose_object_nonlocal(sha1))1002return0;10031004/*1005 * If we already know the pack object lives in, start checks from that1006 * pack - in the usual case when neither --local was given nor .keep files1007 * are present we will determine the answer right now.1008 */1009if(*found_pack) {1010 want =want_found_object(exclude, *found_pack);1011if(want != -1)1012return want;1013}10141015for(entry = packed_git_mru->head; entry; entry = entry->next) {1016struct packed_git *p = entry->item;1017 off_t offset;10181019if(p == *found_pack)1020 offset = *found_offset;1021else1022 offset =find_pack_entry_one(sha1, p);10231024if(offset) {1025if(!*found_pack) {1026if(!is_pack_valid(p))1027continue;1028*found_offset = offset;1029*found_pack = p;1030}1031 want =want_found_object(exclude, p);1032if(!exclude && want >0)1033mru_mark(packed_git_mru, entry);1034if(want != -1)1035return want;1036}1037}10381039return1;1040}10411042static voidcreate_object_entry(const unsigned char*sha1,1043enum object_type type,1044uint32_t hash,1045int exclude,1046int no_try_delta,1047uint32_t index_pos,1048struct packed_git *found_pack,1049 off_t found_offset)1050{1051struct object_entry *entry;10521053 entry =packlist_alloc(&to_pack, sha1, index_pos);1054 entry->hash = hash;1055if(type)1056 entry->type = type;1057if(exclude)1058 entry->preferred_base =1;1059else1060 nr_result++;1061if(found_pack) {1062 entry->in_pack = found_pack;1063 entry->in_pack_offset = found_offset;1064}10651066 entry->no_try_delta = no_try_delta;1067}10681069static const char no_closure_warning[] =N_(1070"disabling bitmap writing, as some objects are not being packed"1071);10721073static intadd_object_entry(const unsigned char*sha1,enum object_type type,1074const char*name,int exclude)1075{1076struct packed_git *found_pack = NULL;1077 off_t found_offset =0;1078uint32_t index_pos;10791080if(have_duplicate_entry(sha1, exclude, &index_pos))1081return0;10821083if(!want_object_in_pack(sha1, exclude, &found_pack, &found_offset)) {1084/* The pack is missing an object, so it will not have closure */1085if(write_bitmap_index) {1086warning(_(no_closure_warning));1087 write_bitmap_index =0;1088}1089return0;1090}10911092create_object_entry(sha1, type,pack_name_hash(name),1093 exclude, name &&no_try_delta(name),1094 index_pos, found_pack, found_offset);10951096display_progress(progress_state, nr_result);1097return1;1098}10991100static intadd_object_entry_from_bitmap(const unsigned char*sha1,1101enum object_type type,1102int flags,uint32_t name_hash,1103struct packed_git *pack, off_t offset)1104{1105uint32_t index_pos;11061107if(have_duplicate_entry(sha1,0, &index_pos))1108return0;11091110if(!want_object_in_pack(sha1,0, &pack, &offset))1111return0;11121113create_object_entry(sha1, type, name_hash,0,0, index_pos, pack, offset);11141115display_progress(progress_state, nr_result);1116return1;1117}11181119struct pbase_tree_cache {1120unsigned char sha1[20];1121int ref;1122int temporary;1123void*tree_data;1124unsigned long tree_size;1125};11261127static struct pbase_tree_cache *(pbase_tree_cache[256]);1128static intpbase_tree_cache_ix(const unsigned char*sha1)1129{1130return sha1[0] %ARRAY_SIZE(pbase_tree_cache);1131}1132static intpbase_tree_cache_ix_incr(int ix)1133{1134return(ix+1) %ARRAY_SIZE(pbase_tree_cache);1135}11361137static struct pbase_tree {1138struct pbase_tree *next;1139/* This is a phony "cache" entry; we are not1140 * going to evict it or find it through _get()1141 * mechanism -- this is for the toplevel node that1142 * would almost always change with any commit.1143 */1144struct pbase_tree_cache pcache;1145} *pbase_tree;11461147static struct pbase_tree_cache *pbase_tree_get(const unsigned char*sha1)1148{1149struct pbase_tree_cache *ent, *nent;1150void*data;1151unsigned long size;1152enum object_type type;1153int neigh;1154int my_ix =pbase_tree_cache_ix(sha1);1155int available_ix = -1;11561157/* pbase-tree-cache acts as a limited hashtable.1158 * your object will be found at your index or within a few1159 * slots after that slot if it is cached.1160 */1161for(neigh =0; neigh <8; neigh++) {1162 ent = pbase_tree_cache[my_ix];1163if(ent && !hashcmp(ent->sha1, sha1)) {1164 ent->ref++;1165return ent;1166}1167else if(((available_ix <0) && (!ent || !ent->ref)) ||1168((0<= available_ix) &&1169(!ent && pbase_tree_cache[available_ix])))1170 available_ix = my_ix;1171if(!ent)1172break;1173 my_ix =pbase_tree_cache_ix_incr(my_ix);1174}11751176/* Did not find one. Either we got a bogus request or1177 * we need to read and perhaps cache.1178 */1179 data =read_sha1_file(sha1, &type, &size);1180if(!data)1181return NULL;1182if(type != OBJ_TREE) {1183free(data);1184return NULL;1185}11861187/* We need to either cache or return a throwaway copy */11881189if(available_ix <0)1190 ent = NULL;1191else{1192 ent = pbase_tree_cache[available_ix];1193 my_ix = available_ix;1194}11951196if(!ent) {1197 nent =xmalloc(sizeof(*nent));1198 nent->temporary = (available_ix <0);1199}1200else{1201/* evict and reuse */1202free(ent->tree_data);1203 nent = ent;1204}1205hashcpy(nent->sha1, sha1);1206 nent->tree_data = data;1207 nent->tree_size = size;1208 nent->ref =1;1209if(!nent->temporary)1210 pbase_tree_cache[my_ix] = nent;1211return nent;1212}12131214static voidpbase_tree_put(struct pbase_tree_cache *cache)1215{1216if(!cache->temporary) {1217 cache->ref--;1218return;1219}1220free(cache->tree_data);1221free(cache);1222}12231224static intname_cmp_len(const char*name)1225{1226int i;1227for(i =0; name[i] && name[i] !='\n'&& name[i] !='/'; i++)1228;1229return i;1230}12311232static voidadd_pbase_object(struct tree_desc *tree,1233const char*name,1234int cmplen,1235const char*fullname)1236{1237struct name_entry entry;1238int cmp;12391240while(tree_entry(tree,&entry)) {1241if(S_ISGITLINK(entry.mode))1242continue;1243 cmp =tree_entry_len(&entry) != cmplen ?1:1244memcmp(name, entry.path, cmplen);1245if(cmp >0)1246continue;1247if(cmp <0)1248return;1249if(name[cmplen] !='/') {1250add_object_entry(entry.oid->hash,1251object_type(entry.mode),1252 fullname,1);1253return;1254}1255if(S_ISDIR(entry.mode)) {1256struct tree_desc sub;1257struct pbase_tree_cache *tree;1258const char*down = name+cmplen+1;1259int downlen =name_cmp_len(down);12601261 tree =pbase_tree_get(entry.oid->hash);1262if(!tree)1263return;1264init_tree_desc(&sub, tree->tree_data, tree->tree_size);12651266add_pbase_object(&sub, down, downlen, fullname);1267pbase_tree_put(tree);1268}1269}1270}12711272static unsigned*done_pbase_paths;1273static int done_pbase_paths_num;1274static int done_pbase_paths_alloc;1275static intdone_pbase_path_pos(unsigned hash)1276{1277int lo =0;1278int hi = done_pbase_paths_num;1279while(lo < hi) {1280int mi = (hi + lo) /2;1281if(done_pbase_paths[mi] == hash)1282return mi;1283if(done_pbase_paths[mi] < hash)1284 hi = mi;1285else1286 lo = mi +1;1287}1288return-lo-1;1289}12901291static intcheck_pbase_path(unsigned hash)1292{1293int pos = (!done_pbase_paths) ? -1:done_pbase_path_pos(hash);1294if(0<= pos)1295return1;1296 pos = -pos -1;1297ALLOC_GROW(done_pbase_paths,1298 done_pbase_paths_num +1,1299 done_pbase_paths_alloc);1300 done_pbase_paths_num++;1301if(pos < done_pbase_paths_num)1302memmove(done_pbase_paths + pos +1,1303 done_pbase_paths + pos,1304(done_pbase_paths_num - pos -1) *sizeof(unsigned));1305 done_pbase_paths[pos] = hash;1306return0;1307}13081309static voidadd_preferred_base_object(const char*name)1310{1311struct pbase_tree *it;1312int cmplen;1313unsigned hash =pack_name_hash(name);13141315if(!num_preferred_base ||check_pbase_path(hash))1316return;13171318 cmplen =name_cmp_len(name);1319for(it = pbase_tree; it; it = it->next) {1320if(cmplen ==0) {1321add_object_entry(it->pcache.sha1, OBJ_TREE, NULL,1);1322}1323else{1324struct tree_desc tree;1325init_tree_desc(&tree, it->pcache.tree_data, it->pcache.tree_size);1326add_pbase_object(&tree, name, cmplen, name);1327}1328}1329}13301331static voidadd_preferred_base(unsigned char*sha1)1332{1333struct pbase_tree *it;1334void*data;1335unsigned long size;1336unsigned char tree_sha1[20];13371338if(window <= num_preferred_base++)1339return;13401341 data =read_object_with_reference(sha1, tree_type, &size, tree_sha1);1342if(!data)1343return;13441345for(it = pbase_tree; it; it = it->next) {1346if(!hashcmp(it->pcache.sha1, tree_sha1)) {1347free(data);1348return;1349}1350}13511352 it =xcalloc(1,sizeof(*it));1353 it->next = pbase_tree;1354 pbase_tree = it;13551356hashcpy(it->pcache.sha1, tree_sha1);1357 it->pcache.tree_data = data;1358 it->pcache.tree_size = size;1359}13601361static voidcleanup_preferred_base(void)1362{1363struct pbase_tree *it;1364unsigned i;13651366 it = pbase_tree;1367 pbase_tree = NULL;1368while(it) {1369struct pbase_tree *this= it;1370 it =this->next;1371free(this->pcache.tree_data);1372free(this);1373}13741375for(i =0; i <ARRAY_SIZE(pbase_tree_cache); i++) {1376if(!pbase_tree_cache[i])1377continue;1378free(pbase_tree_cache[i]->tree_data);1379free(pbase_tree_cache[i]);1380 pbase_tree_cache[i] = NULL;1381}13821383free(done_pbase_paths);1384 done_pbase_paths = NULL;1385 done_pbase_paths_num = done_pbase_paths_alloc =0;1386}13871388static voidcheck_object(struct object_entry *entry)1389{1390if(entry->in_pack) {1391struct packed_git *p = entry->in_pack;1392struct pack_window *w_curs = NULL;1393const unsigned char*base_ref = NULL;1394struct object_entry *base_entry;1395unsigned long used, used_0;1396unsigned long avail;1397 off_t ofs;1398unsigned char*buf, c;13991400 buf =use_pack(p, &w_curs, entry->in_pack_offset, &avail);14011402/*1403 * We want in_pack_type even if we do not reuse delta1404 * since non-delta representations could still be reused.1405 */1406 used =unpack_object_header_buffer(buf, avail,1407&entry->in_pack_type,1408&entry->size);1409if(used ==0)1410goto give_up;14111412/*1413 * Determine if this is a delta and if so whether we can1414 * reuse it or not. Otherwise let's find out as cheaply as1415 * possible what the actual type and size for this object is.1416 */1417switch(entry->in_pack_type) {1418default:1419/* Not a delta hence we've already got all we need. */1420 entry->type = entry->in_pack_type;1421 entry->in_pack_header_size = used;1422if(entry->type < OBJ_COMMIT || entry->type > OBJ_BLOB)1423goto give_up;1424unuse_pack(&w_curs);1425return;1426case OBJ_REF_DELTA:1427if(reuse_delta && !entry->preferred_base)1428 base_ref =use_pack(p, &w_curs,1429 entry->in_pack_offset + used, NULL);1430 entry->in_pack_header_size = used +20;1431break;1432case OBJ_OFS_DELTA:1433 buf =use_pack(p, &w_curs,1434 entry->in_pack_offset + used, NULL);1435 used_0 =0;1436 c = buf[used_0++];1437 ofs = c &127;1438while(c &128) {1439 ofs +=1;1440if(!ofs ||MSB(ofs,7)) {1441error("delta base offset overflow in pack for%s",1442sha1_to_hex(entry->idx.sha1));1443goto give_up;1444}1445 c = buf[used_0++];1446 ofs = (ofs <<7) + (c &127);1447}1448 ofs = entry->in_pack_offset - ofs;1449if(ofs <=0|| ofs >= entry->in_pack_offset) {1450error("delta base offset out of bound for%s",1451sha1_to_hex(entry->idx.sha1));1452goto give_up;1453}1454if(reuse_delta && !entry->preferred_base) {1455struct revindex_entry *revidx;1456 revidx =find_pack_revindex(p, ofs);1457if(!revidx)1458goto give_up;1459 base_ref =nth_packed_object_sha1(p, revidx->nr);1460}1461 entry->in_pack_header_size = used + used_0;1462break;1463}14641465if(base_ref && (base_entry =packlist_find(&to_pack, base_ref, NULL))) {1466/*1467 * If base_ref was set above that means we wish to1468 * reuse delta data, and we even found that base1469 * in the list of objects we want to pack. Goodie!1470 *1471 * Depth value does not matter - find_deltas() will1472 * never consider reused delta as the base object to1473 * deltify other objects against, in order to avoid1474 * circular deltas.1475 */1476 entry->type = entry->in_pack_type;1477 entry->delta = base_entry;1478 entry->delta_size = entry->size;1479 entry->delta_sibling = base_entry->delta_child;1480 base_entry->delta_child = entry;1481unuse_pack(&w_curs);1482return;1483}14841485if(entry->type) {1486/*1487 * This must be a delta and we already know what the1488 * final object type is. Let's extract the actual1489 * object size from the delta header.1490 */1491 entry->size =get_size_from_delta(p, &w_curs,1492 entry->in_pack_offset + entry->in_pack_header_size);1493if(entry->size ==0)1494goto give_up;1495unuse_pack(&w_curs);1496return;1497}14981499/*1500 * No choice but to fall back to the recursive delta walk1501 * with sha1_object_info() to find about the object type1502 * at this point...1503 */1504 give_up:1505unuse_pack(&w_curs);1506}15071508 entry->type =sha1_object_info(entry->idx.sha1, &entry->size);1509/*1510 * The error condition is checked in prepare_pack(). This is1511 * to permit a missing preferred base object to be ignored1512 * as a preferred base. Doing so can result in a larger1513 * pack file, but the transfer will still take place.1514 */1515}15161517static intpack_offset_sort(const void*_a,const void*_b)1518{1519const struct object_entry *a = *(struct object_entry **)_a;1520const struct object_entry *b = *(struct object_entry **)_b;15211522/* avoid filesystem trashing with loose objects */1523if(!a->in_pack && !b->in_pack)1524returnhashcmp(a->idx.sha1, b->idx.sha1);15251526if(a->in_pack < b->in_pack)1527return-1;1528if(a->in_pack > b->in_pack)1529return1;1530return a->in_pack_offset < b->in_pack_offset ? -1:1531(a->in_pack_offset > b->in_pack_offset);1532}15331534/*1535 * Drop an on-disk delta we were planning to reuse. Naively, this would1536 * just involve blanking out the "delta" field, but we have to deal1537 * with some extra book-keeping:1538 *1539 * 1. Removing ourselves from the delta_sibling linked list.1540 *1541 * 2. Updating our size/type to the non-delta representation. These were1542 * either not recorded initially (size) or overwritten with the delta type1543 * (type) when check_object() decided to reuse the delta.1544 *1545 * 3. Resetting our delta depth, as we are now a base object.1546 */1547static voiddrop_reused_delta(struct object_entry *entry)1548{1549struct object_entry **p = &entry->delta->delta_child;1550struct object_info oi = OBJECT_INFO_INIT;15511552while(*p) {1553if(*p == entry)1554*p = (*p)->delta_sibling;1555else1556 p = &(*p)->delta_sibling;1557}1558 entry->delta = NULL;1559 entry->depth =0;15601561 oi.sizep = &entry->size;1562 oi.typep = &entry->type;1563if(packed_object_info(entry->in_pack, entry->in_pack_offset, &oi) <0) {1564/*1565 * We failed to get the info from this pack for some reason;1566 * fall back to sha1_object_info, which may find another copy.1567 * And if that fails, the error will be recorded in entry->type1568 * and dealt with in prepare_pack().1569 */1570 entry->type =sha1_object_info(entry->idx.sha1, &entry->size);1571}1572}15731574/*1575 * Follow the chain of deltas from this entry onward, throwing away any links1576 * that cause us to hit a cycle (as determined by the DFS state flags in1577 * the entries).1578 *1579 * We also detect too-long reused chains that would violate our --depth1580 * limit.1581 */1582static voidbreak_delta_chains(struct object_entry *entry)1583{1584/*1585 * The actual depth of each object we will write is stored as an int,1586 * as it cannot exceed our int "depth" limit. But before we break1587 * changes based no that limit, we may potentially go as deep as the1588 * number of objects, which is elsewhere bounded to a uint32_t.1589 */1590uint32_t total_depth;1591struct object_entry *cur, *next;15921593for(cur = entry, total_depth =0;1594 cur;1595 cur = cur->delta, total_depth++) {1596if(cur->dfs_state == DFS_DONE) {1597/*1598 * We've already seen this object and know it isn't1599 * part of a cycle. We do need to append its depth1600 * to our count.1601 */1602 total_depth += cur->depth;1603break;1604}16051606/*1607 * We break cycles before looping, so an ACTIVE state (or any1608 * other cruft which made its way into the state variable)1609 * is a bug.1610 */1611if(cur->dfs_state != DFS_NONE)1612die("BUG: confusing delta dfs state in first pass:%d",1613 cur->dfs_state);16141615/*1616 * Now we know this is the first time we've seen the object. If1617 * it's not a delta, we're done traversing, but we'll mark it1618 * done to save time on future traversals.1619 */1620if(!cur->delta) {1621 cur->dfs_state = DFS_DONE;1622break;1623}16241625/*1626 * Mark ourselves as active and see if the next step causes1627 * us to cycle to another active object. It's important to do1628 * this _before_ we loop, because it impacts where we make the1629 * cut, and thus how our total_depth counter works.1630 * E.g., We may see a partial loop like:1631 *1632 * A -> B -> C -> D -> B1633 *1634 * Cutting B->C breaks the cycle. But now the depth of A is1635 * only 1, and our total_depth counter is at 3. The size of the1636 * error is always one less than the size of the cycle we1637 * broke. Commits C and D were "lost" from A's chain.1638 *1639 * If we instead cut D->B, then the depth of A is correct at 3.1640 * We keep all commits in the chain that we examined.1641 */1642 cur->dfs_state = DFS_ACTIVE;1643if(cur->delta->dfs_state == DFS_ACTIVE) {1644drop_reused_delta(cur);1645 cur->dfs_state = DFS_DONE;1646break;1647}1648}16491650/*1651 * And now that we've gone all the way to the bottom of the chain, we1652 * need to clear the active flags and set the depth fields as1653 * appropriate. Unlike the loop above, which can quit when it drops a1654 * delta, we need to keep going to look for more depth cuts. So we need1655 * an extra "next" pointer to keep going after we reset cur->delta.1656 */1657for(cur = entry; cur; cur = next) {1658 next = cur->delta;16591660/*1661 * We should have a chain of zero or more ACTIVE states down to1662 * a final DONE. We can quit after the DONE, because either it1663 * has no bases, or we've already handled them in a previous1664 * call.1665 */1666if(cur->dfs_state == DFS_DONE)1667break;1668else if(cur->dfs_state != DFS_ACTIVE)1669die("BUG: confusing delta dfs state in second pass:%d",1670 cur->dfs_state);16711672/*1673 * If the total_depth is more than depth, then we need to snip1674 * the chain into two or more smaller chains that don't exceed1675 * the maximum depth. Most of the resulting chains will contain1676 * (depth + 1) entries (i.e., depth deltas plus one base), and1677 * the last chain (i.e., the one containing entry) will contain1678 * whatever entries are left over, namely1679 * (total_depth % (depth + 1)) of them.1680 *1681 * Since we are iterating towards decreasing depth, we need to1682 * decrement total_depth as we go, and we need to write to the1683 * entry what its final depth will be after all of the1684 * snipping. Since we're snipping into chains of length (depth1685 * + 1) entries, the final depth of an entry will be its1686 * original depth modulo (depth + 1). Any time we encounter an1687 * entry whose final depth is supposed to be zero, we snip it1688 * from its delta base, thereby making it so.1689 */1690 cur->depth = (total_depth--) % (depth +1);1691if(!cur->depth)1692drop_reused_delta(cur);16931694 cur->dfs_state = DFS_DONE;1695}1696}16971698static voidget_object_details(void)1699{1700uint32_t i;1701struct object_entry **sorted_by_offset;17021703 sorted_by_offset =xcalloc(to_pack.nr_objects,sizeof(struct object_entry *));1704for(i =0; i < to_pack.nr_objects; i++)1705 sorted_by_offset[i] = to_pack.objects + i;1706QSORT(sorted_by_offset, to_pack.nr_objects, pack_offset_sort);17071708for(i =0; i < to_pack.nr_objects; i++) {1709struct object_entry *entry = sorted_by_offset[i];1710check_object(entry);1711if(big_file_threshold < entry->size)1712 entry->no_try_delta =1;1713}17141715/*1716 * This must happen in a second pass, since we rely on the delta1717 * information for the whole list being completed.1718 */1719for(i =0; i < to_pack.nr_objects; i++)1720break_delta_chains(&to_pack.objects[i]);17211722free(sorted_by_offset);1723}17241725/*1726 * We search for deltas in a list sorted by type, by filename hash, and then1727 * by size, so that we see progressively smaller and smaller files.1728 * That's because we prefer deltas to be from the bigger file1729 * to the smaller -- deletes are potentially cheaper, but perhaps1730 * more importantly, the bigger file is likely the more recent1731 * one. The deepest deltas are therefore the oldest objects which are1732 * less susceptible to be accessed often.1733 */1734static inttype_size_sort(const void*_a,const void*_b)1735{1736const struct object_entry *a = *(struct object_entry **)_a;1737const struct object_entry *b = *(struct object_entry **)_b;17381739if(a->type > b->type)1740return-1;1741if(a->type < b->type)1742return1;1743if(a->hash > b->hash)1744return-1;1745if(a->hash < b->hash)1746return1;1747if(a->preferred_base > b->preferred_base)1748return-1;1749if(a->preferred_base < b->preferred_base)1750return1;1751if(a->size > b->size)1752return-1;1753if(a->size < b->size)1754return1;1755return a < b ? -1: (a > b);/* newest first */1756}17571758struct unpacked {1759struct object_entry *entry;1760void*data;1761struct delta_index *index;1762unsigned depth;1763};17641765static intdelta_cacheable(unsigned long src_size,unsigned long trg_size,1766unsigned long delta_size)1767{1768if(max_delta_cache_size && delta_cache_size + delta_size > max_delta_cache_size)1769return0;17701771if(delta_size < cache_max_small_delta_size)1772return1;17731774/* cache delta, if objects are large enough compared to delta size */1775if((src_size >>20) + (trg_size >>21) > (delta_size >>10))1776return1;17771778return0;1779}17801781#ifndef NO_PTHREADS17821783static pthread_mutex_t read_mutex;1784#define read_lock() pthread_mutex_lock(&read_mutex)1785#define read_unlock() pthread_mutex_unlock(&read_mutex)17861787static pthread_mutex_t cache_mutex;1788#define cache_lock() pthread_mutex_lock(&cache_mutex)1789#define cache_unlock() pthread_mutex_unlock(&cache_mutex)17901791static pthread_mutex_t progress_mutex;1792#define progress_lock() pthread_mutex_lock(&progress_mutex)1793#define progress_unlock() pthread_mutex_unlock(&progress_mutex)17941795#else17961797#define read_lock() (void)01798#define read_unlock() (void)01799#define cache_lock() (void)01800#define cache_unlock() (void)01801#define progress_lock() (void)01802#define progress_unlock() (void)018031804#endif18051806static inttry_delta(struct unpacked *trg,struct unpacked *src,1807unsigned max_depth,unsigned long*mem_usage)1808{1809struct object_entry *trg_entry = trg->entry;1810struct object_entry *src_entry = src->entry;1811unsigned long trg_size, src_size, delta_size, sizediff, max_size, sz;1812unsigned ref_depth;1813enum object_type type;1814void*delta_buf;18151816/* Don't bother doing diffs between different types */1817if(trg_entry->type != src_entry->type)1818return-1;18191820/*1821 * We do not bother to try a delta that we discarded on an1822 * earlier try, but only when reusing delta data. Note that1823 * src_entry that is marked as the preferred_base should always1824 * be considered, as even if we produce a suboptimal delta against1825 * it, we will still save the transfer cost, as we already know1826 * the other side has it and we won't send src_entry at all.1827 */1828if(reuse_delta && trg_entry->in_pack &&1829 trg_entry->in_pack == src_entry->in_pack &&1830!src_entry->preferred_base &&1831 trg_entry->in_pack_type != OBJ_REF_DELTA &&1832 trg_entry->in_pack_type != OBJ_OFS_DELTA)1833return0;18341835/* Let's not bust the allowed depth. */1836if(src->depth >= max_depth)1837return0;18381839/* Now some size filtering heuristics. */1840 trg_size = trg_entry->size;1841if(!trg_entry->delta) {1842 max_size = trg_size/2-20;1843 ref_depth =1;1844}else{1845 max_size = trg_entry->delta_size;1846 ref_depth = trg->depth;1847}1848 max_size = (uint64_t)max_size * (max_depth - src->depth) /1849(max_depth - ref_depth +1);1850if(max_size ==0)1851return0;1852 src_size = src_entry->size;1853 sizediff = src_size < trg_size ? trg_size - src_size :0;1854if(sizediff >= max_size)1855return0;1856if(trg_size < src_size /32)1857return0;18581859/* Load data if not already done */1860if(!trg->data) {1861read_lock();1862 trg->data =read_sha1_file(trg_entry->idx.sha1, &type, &sz);1863read_unlock();1864if(!trg->data)1865die("object%scannot be read",1866sha1_to_hex(trg_entry->idx.sha1));1867if(sz != trg_size)1868die("object%sinconsistent object length (%lu vs%lu)",1869sha1_to_hex(trg_entry->idx.sha1), sz, trg_size);1870*mem_usage += sz;1871}1872if(!src->data) {1873read_lock();1874 src->data =read_sha1_file(src_entry->idx.sha1, &type, &sz);1875read_unlock();1876if(!src->data) {1877if(src_entry->preferred_base) {1878static int warned =0;1879if(!warned++)1880warning("object%scannot be read",1881sha1_to_hex(src_entry->idx.sha1));1882/*1883 * Those objects are not included in the1884 * resulting pack. Be resilient and ignore1885 * them if they can't be read, in case the1886 * pack could be created nevertheless.1887 */1888return0;1889}1890die("object%scannot be read",1891sha1_to_hex(src_entry->idx.sha1));1892}1893if(sz != src_size)1894die("object%sinconsistent object length (%lu vs%lu)",1895sha1_to_hex(src_entry->idx.sha1), sz, src_size);1896*mem_usage += sz;1897}1898if(!src->index) {1899 src->index =create_delta_index(src->data, src_size);1900if(!src->index) {1901static int warned =0;1902if(!warned++)1903warning("suboptimal pack - out of memory");1904return0;1905}1906*mem_usage +=sizeof_delta_index(src->index);1907}19081909 delta_buf =create_delta(src->index, trg->data, trg_size, &delta_size, max_size);1910if(!delta_buf)1911return0;19121913if(trg_entry->delta) {1914/* Prefer only shallower same-sized deltas. */1915if(delta_size == trg_entry->delta_size &&1916 src->depth +1>= trg->depth) {1917free(delta_buf);1918return0;1919}1920}19211922/*1923 * Handle memory allocation outside of the cache1924 * accounting lock. Compiler will optimize the strangeness1925 * away when NO_PTHREADS is defined.1926 */1927free(trg_entry->delta_data);1928cache_lock();1929if(trg_entry->delta_data) {1930 delta_cache_size -= trg_entry->delta_size;1931 trg_entry->delta_data = NULL;1932}1933if(delta_cacheable(src_size, trg_size, delta_size)) {1934 delta_cache_size += delta_size;1935cache_unlock();1936 trg_entry->delta_data =xrealloc(delta_buf, delta_size);1937}else{1938cache_unlock();1939free(delta_buf);1940}19411942 trg_entry->delta = src_entry;1943 trg_entry->delta_size = delta_size;1944 trg->depth = src->depth +1;19451946return1;1947}19481949static unsigned intcheck_delta_limit(struct object_entry *me,unsigned int n)1950{1951struct object_entry *child = me->delta_child;1952unsigned int m = n;1953while(child) {1954unsigned int c =check_delta_limit(child, n +1);1955if(m < c)1956 m = c;1957 child = child->delta_sibling;1958}1959return m;1960}19611962static unsigned longfree_unpacked(struct unpacked *n)1963{1964unsigned long freed_mem =sizeof_delta_index(n->index);1965free_delta_index(n->index);1966 n->index = NULL;1967if(n->data) {1968 freed_mem += n->entry->size;1969free(n->data);1970 n->data = NULL;1971}1972 n->entry = NULL;1973 n->depth =0;1974return freed_mem;1975}19761977static voidfind_deltas(struct object_entry **list,unsigned*list_size,1978int window,int depth,unsigned*processed)1979{1980uint32_t i, idx =0, count =0;1981struct unpacked *array;1982unsigned long mem_usage =0;19831984 array =xcalloc(window,sizeof(struct unpacked));19851986for(;;) {1987struct object_entry *entry;1988struct unpacked *n = array + idx;1989int j, max_depth, best_base = -1;19901991progress_lock();1992if(!*list_size) {1993progress_unlock();1994break;1995}1996 entry = *list++;1997(*list_size)--;1998if(!entry->preferred_base) {1999(*processed)++;2000display_progress(progress_state, *processed);2001}2002progress_unlock();20032004 mem_usage -=free_unpacked(n);2005 n->entry = entry;20062007while(window_memory_limit &&2008 mem_usage > window_memory_limit &&2009 count >1) {2010uint32_t tail = (idx + window - count) % window;2011 mem_usage -=free_unpacked(array + tail);2012 count--;2013}20142015/* We do not compute delta to *create* objects we are not2016 * going to pack.2017 */2018if(entry->preferred_base)2019goto next;20202021/*2022 * If the current object is at pack edge, take the depth the2023 * objects that depend on the current object into account2024 * otherwise they would become too deep.2025 */2026 max_depth = depth;2027if(entry->delta_child) {2028 max_depth -=check_delta_limit(entry,0);2029if(max_depth <=0)2030goto next;2031}20322033 j = window;2034while(--j >0) {2035int ret;2036uint32_t other_idx = idx + j;2037struct unpacked *m;2038if(other_idx >= window)2039 other_idx -= window;2040 m = array + other_idx;2041if(!m->entry)2042break;2043 ret =try_delta(n, m, max_depth, &mem_usage);2044if(ret <0)2045break;2046else if(ret >0)2047 best_base = other_idx;2048}20492050/*2051 * If we decided to cache the delta data, then it is best2052 * to compress it right away. First because we have to do2053 * it anyway, and doing it here while we're threaded will2054 * save a lot of time in the non threaded write phase,2055 * as well as allow for caching more deltas within2056 * the same cache size limit.2057 * ...2058 * But only if not writing to stdout, since in that case2059 * the network is most likely throttling writes anyway,2060 * and therefore it is best to go to the write phase ASAP2061 * instead, as we can afford spending more time compressing2062 * between writes at that moment.2063 */2064if(entry->delta_data && !pack_to_stdout) {2065 entry->z_delta_size =do_compress(&entry->delta_data,2066 entry->delta_size);2067cache_lock();2068 delta_cache_size -= entry->delta_size;2069 delta_cache_size += entry->z_delta_size;2070cache_unlock();2071}20722073/* if we made n a delta, and if n is already at max2074 * depth, leaving it in the window is pointless. we2075 * should evict it first.2076 */2077if(entry->delta && max_depth <= n->depth)2078continue;20792080/*2081 * Move the best delta base up in the window, after the2082 * currently deltified object, to keep it longer. It will2083 * be the first base object to be attempted next.2084 */2085if(entry->delta) {2086struct unpacked swap = array[best_base];2087int dist = (window + idx - best_base) % window;2088int dst = best_base;2089while(dist--) {2090int src = (dst +1) % window;2091 array[dst] = array[src];2092 dst = src;2093}2094 array[dst] = swap;2095}20962097 next:2098 idx++;2099if(count +1< window)2100 count++;2101if(idx >= window)2102 idx =0;2103}21042105for(i =0; i < window; ++i) {2106free_delta_index(array[i].index);2107free(array[i].data);2108}2109free(array);2110}21112112#ifndef NO_PTHREADS21132114static voidtry_to_free_from_threads(size_t size)2115{2116read_lock();2117release_pack_memory(size);2118read_unlock();2119}21202121static try_to_free_t old_try_to_free_routine;21222123/*2124 * The main thread waits on the condition that (at least) one of the workers2125 * has stopped working (which is indicated in the .working member of2126 * struct thread_params).2127 * When a work thread has completed its work, it sets .working to 0 and2128 * signals the main thread and waits on the condition that .data_ready2129 * becomes 1.2130 */21312132struct thread_params {2133 pthread_t thread;2134struct object_entry **list;2135unsigned list_size;2136unsigned remaining;2137int window;2138int depth;2139int working;2140int data_ready;2141 pthread_mutex_t mutex;2142 pthread_cond_t cond;2143unsigned*processed;2144};21452146static pthread_cond_t progress_cond;21472148/*2149 * Mutex and conditional variable can't be statically-initialized on Windows.2150 */2151static voidinit_threaded_search(void)2152{2153init_recursive_mutex(&read_mutex);2154pthread_mutex_init(&cache_mutex, NULL);2155pthread_mutex_init(&progress_mutex, NULL);2156pthread_cond_init(&progress_cond, NULL);2157 old_try_to_free_routine =set_try_to_free_routine(try_to_free_from_threads);2158}21592160static voidcleanup_threaded_search(void)2161{2162set_try_to_free_routine(old_try_to_free_routine);2163pthread_cond_destroy(&progress_cond);2164pthread_mutex_destroy(&read_mutex);2165pthread_mutex_destroy(&cache_mutex);2166pthread_mutex_destroy(&progress_mutex);2167}21682169static void*threaded_find_deltas(void*arg)2170{2171struct thread_params *me = arg;21722173while(me->remaining) {2174find_deltas(me->list, &me->remaining,2175 me->window, me->depth, me->processed);21762177progress_lock();2178 me->working =0;2179pthread_cond_signal(&progress_cond);2180progress_unlock();21812182/*2183 * We must not set ->data_ready before we wait on the2184 * condition because the main thread may have set it to 12185 * before we get here. In order to be sure that new2186 * work is available if we see 1 in ->data_ready, it2187 * was initialized to 0 before this thread was spawned2188 * and we reset it to 0 right away.2189 */2190pthread_mutex_lock(&me->mutex);2191while(!me->data_ready)2192pthread_cond_wait(&me->cond, &me->mutex);2193 me->data_ready =0;2194pthread_mutex_unlock(&me->mutex);2195}2196/* leave ->working 1 so that this doesn't get more work assigned */2197return NULL;2198}21992200static voidll_find_deltas(struct object_entry **list,unsigned list_size,2201int window,int depth,unsigned*processed)2202{2203struct thread_params *p;2204int i, ret, active_threads =0;22052206init_threaded_search();22072208if(delta_search_threads <=1) {2209find_deltas(list, &list_size, window, depth, processed);2210cleanup_threaded_search();2211return;2212}2213if(progress > pack_to_stdout)2214fprintf(stderr,"Delta compression using up to%dthreads.\n",2215 delta_search_threads);2216 p =xcalloc(delta_search_threads,sizeof(*p));22172218/* Partition the work amongst work threads. */2219for(i =0; i < delta_search_threads; i++) {2220unsigned sub_size = list_size / (delta_search_threads - i);22212222/* don't use too small segments or no deltas will be found */2223if(sub_size <2*window && i+1< delta_search_threads)2224 sub_size =0;22252226 p[i].window = window;2227 p[i].depth = depth;2228 p[i].processed = processed;2229 p[i].working =1;2230 p[i].data_ready =0;22312232/* try to split chunks on "path" boundaries */2233while(sub_size && sub_size < list_size &&2234 list[sub_size]->hash &&2235 list[sub_size]->hash == list[sub_size-1]->hash)2236 sub_size++;22372238 p[i].list = list;2239 p[i].list_size = sub_size;2240 p[i].remaining = sub_size;22412242 list += sub_size;2243 list_size -= sub_size;2244}22452246/* Start work threads. */2247for(i =0; i < delta_search_threads; i++) {2248if(!p[i].list_size)2249continue;2250pthread_mutex_init(&p[i].mutex, NULL);2251pthread_cond_init(&p[i].cond, NULL);2252 ret =pthread_create(&p[i].thread, NULL,2253 threaded_find_deltas, &p[i]);2254if(ret)2255die("unable to create thread:%s",strerror(ret));2256 active_threads++;2257}22582259/*2260 * Now let's wait for work completion. Each time a thread is done2261 * with its work, we steal half of the remaining work from the2262 * thread with the largest number of unprocessed objects and give2263 * it to that newly idle thread. This ensure good load balancing2264 * until the remaining object list segments are simply too short2265 * to be worth splitting anymore.2266 */2267while(active_threads) {2268struct thread_params *target = NULL;2269struct thread_params *victim = NULL;2270unsigned sub_size =0;22712272progress_lock();2273for(;;) {2274for(i =0; !target && i < delta_search_threads; i++)2275if(!p[i].working)2276 target = &p[i];2277if(target)2278break;2279pthread_cond_wait(&progress_cond, &progress_mutex);2280}22812282for(i =0; i < delta_search_threads; i++)2283if(p[i].remaining >2*window &&2284(!victim || victim->remaining < p[i].remaining))2285 victim = &p[i];2286if(victim) {2287 sub_size = victim->remaining /2;2288 list = victim->list + victim->list_size - sub_size;2289while(sub_size && list[0]->hash &&2290 list[0]->hash == list[-1]->hash) {2291 list++;2292 sub_size--;2293}2294if(!sub_size) {2295/*2296 * It is possible for some "paths" to have2297 * so many objects that no hash boundary2298 * might be found. Let's just steal the2299 * exact half in that case.2300 */2301 sub_size = victim->remaining /2;2302 list -= sub_size;2303}2304 target->list = list;2305 victim->list_size -= sub_size;2306 victim->remaining -= sub_size;2307}2308 target->list_size = sub_size;2309 target->remaining = sub_size;2310 target->working =1;2311progress_unlock();23122313pthread_mutex_lock(&target->mutex);2314 target->data_ready =1;2315pthread_cond_signal(&target->cond);2316pthread_mutex_unlock(&target->mutex);23172318if(!sub_size) {2319pthread_join(target->thread, NULL);2320pthread_cond_destroy(&target->cond);2321pthread_mutex_destroy(&target->mutex);2322 active_threads--;2323}2324}2325cleanup_threaded_search();2326free(p);2327}23282329#else2330#define ll_find_deltas(l, s, w, d, p) find_deltas(l, &s, w, d, p)2331#endif23322333static voidadd_tag_chain(const struct object_id *oid)2334{2335struct tag *tag;23362337/*2338 * We catch duplicates already in add_object_entry(), but we'd2339 * prefer to do this extra check to avoid having to parse the2340 * tag at all if we already know that it's being packed (e.g., if2341 * it was included via bitmaps, we would not have parsed it2342 * previously).2343 */2344if(packlist_find(&to_pack, oid->hash, NULL))2345return;23462347 tag =lookup_tag(oid->hash);2348while(1) {2349if(!tag ||parse_tag(tag) || !tag->tagged)2350die("unable to pack objects reachable from tag%s",2351oid_to_hex(oid));23522353add_object_entry(tag->object.oid.hash, OBJ_TAG, NULL,0);23542355if(tag->tagged->type != OBJ_TAG)2356return;23572358 tag = (struct tag *)tag->tagged;2359}2360}23612362static intadd_ref_tag(const char*path,const struct object_id *oid,int flag,void*cb_data)2363{2364struct object_id peeled;23652366if(starts_with(path,"refs/tags/") &&/* is a tag? */2367!peel_ref(path, peeled.hash) &&/* peelable? */2368packlist_find(&to_pack, peeled.hash, NULL))/* object packed? */2369add_tag_chain(oid);2370return0;2371}23722373static voidprepare_pack(int window,int depth)2374{2375struct object_entry **delta_list;2376uint32_t i, nr_deltas;2377unsigned n;23782379get_object_details();23802381/*2382 * If we're locally repacking then we need to be doubly careful2383 * from now on in order to make sure no stealth corruption gets2384 * propagated to the new pack. Clients receiving streamed packs2385 * should validate everything they get anyway so no need to incur2386 * the additional cost here in that case.2387 */2388if(!pack_to_stdout)2389 do_check_packed_object_crc =1;23902391if(!to_pack.nr_objects || !window || !depth)2392return;23932394ALLOC_ARRAY(delta_list, to_pack.nr_objects);2395 nr_deltas = n =0;23962397for(i =0; i < to_pack.nr_objects; i++) {2398struct object_entry *entry = to_pack.objects + i;23992400if(entry->delta)2401/* This happens if we decided to reuse existing2402 * delta from a pack. "reuse_delta &&" is implied.2403 */2404continue;24052406if(entry->size <50)2407continue;24082409if(entry->no_try_delta)2410continue;24112412if(!entry->preferred_base) {2413 nr_deltas++;2414if(entry->type <0)2415die("unable to get type of object%s",2416sha1_to_hex(entry->idx.sha1));2417}else{2418if(entry->type <0) {2419/*2420 * This object is not found, but we2421 * don't have to include it anyway.2422 */2423continue;2424}2425}24262427 delta_list[n++] = entry;2428}24292430if(nr_deltas && n >1) {2431unsigned nr_done =0;2432if(progress)2433 progress_state =start_progress(_("Compressing objects"),2434 nr_deltas);2435QSORT(delta_list, n, type_size_sort);2436ll_find_deltas(delta_list, n, window+1, depth, &nr_done);2437stop_progress(&progress_state);2438if(nr_done != nr_deltas)2439die("inconsistency with delta count");2440}2441free(delta_list);2442}24432444static intgit_pack_config(const char*k,const char*v,void*cb)2445{2446if(!strcmp(k,"pack.window")) {2447 window =git_config_int(k, v);2448return0;2449}2450if(!strcmp(k,"pack.windowmemory")) {2451 window_memory_limit =git_config_ulong(k, v);2452return0;2453}2454if(!strcmp(k,"pack.depth")) {2455 depth =git_config_int(k, v);2456return0;2457}2458if(!strcmp(k,"pack.compression")) {2459int level =git_config_int(k, v);2460if(level == -1)2461 level = Z_DEFAULT_COMPRESSION;2462else if(level <0|| level > Z_BEST_COMPRESSION)2463die("bad pack compression level%d", level);2464 pack_compression_level = level;2465 pack_compression_seen =1;2466return0;2467}2468if(!strcmp(k,"pack.deltacachesize")) {2469 max_delta_cache_size =git_config_int(k, v);2470return0;2471}2472if(!strcmp(k,"pack.deltacachelimit")) {2473 cache_max_small_delta_size =git_config_int(k, v);2474return0;2475}2476if(!strcmp(k,"pack.writebitmaphashcache")) {2477if(git_config_bool(k, v))2478 write_bitmap_options |= BITMAP_OPT_HASH_CACHE;2479else2480 write_bitmap_options &= ~BITMAP_OPT_HASH_CACHE;2481}2482if(!strcmp(k,"pack.usebitmaps")) {2483 use_bitmap_index_default =git_config_bool(k, v);2484return0;2485}2486if(!strcmp(k,"pack.threads")) {2487 delta_search_threads =git_config_int(k, v);2488if(delta_search_threads <0)2489die("invalid number of threads specified (%d)",2490 delta_search_threads);2491#ifdef NO_PTHREADS2492if(delta_search_threads !=1)2493warning("no threads support, ignoring%s", k);2494#endif2495return0;2496}2497if(!strcmp(k,"pack.indexversion")) {2498 pack_idx_opts.version =git_config_int(k, v);2499if(pack_idx_opts.version >2)2500die("bad pack.indexversion=%"PRIu32,2501 pack_idx_opts.version);2502return0;2503}2504returngit_default_config(k, v, cb);2505}25062507static voidread_object_list_from_stdin(void)2508{2509char line[40+1+ PATH_MAX +2];2510unsigned char sha1[20];25112512for(;;) {2513if(!fgets(line,sizeof(line), stdin)) {2514if(feof(stdin))2515break;2516if(!ferror(stdin))2517die("fgets returned NULL, not EOF, not error!");2518if(errno != EINTR)2519die_errno("fgets");2520clearerr(stdin);2521continue;2522}2523if(line[0] =='-') {2524if(get_sha1_hex(line+1, sha1))2525die("expected edge sha1, got garbage:\n%s",2526 line);2527add_preferred_base(sha1);2528continue;2529}2530if(get_sha1_hex(line, sha1))2531die("expected sha1, got garbage:\n%s", line);25322533add_preferred_base_object(line+41);2534add_object_entry(sha1,0, line+41,0);2535}2536}25372538#define OBJECT_ADDED (1u<<20)25392540static voidshow_commit(struct commit *commit,void*data)2541{2542add_object_entry(commit->object.oid.hash, OBJ_COMMIT, NULL,0);2543 commit->object.flags |= OBJECT_ADDED;25442545if(write_bitmap_index)2546index_commit_for_bitmap(commit);2547}25482549static voidshow_object(struct object *obj,const char*name,void*data)2550{2551add_preferred_base_object(name);2552add_object_entry(obj->oid.hash, obj->type, name,0);2553 obj->flags |= OBJECT_ADDED;2554}25552556static voidshow_edge(struct commit *commit)2557{2558add_preferred_base(commit->object.oid.hash);2559}25602561struct in_pack_object {2562 off_t offset;2563struct object *object;2564};25652566struct in_pack {2567int alloc;2568int nr;2569struct in_pack_object *array;2570};25712572static voidmark_in_pack_object(struct object *object,struct packed_git *p,struct in_pack *in_pack)2573{2574 in_pack->array[in_pack->nr].offset =find_pack_entry_one(object->oid.hash, p);2575 in_pack->array[in_pack->nr].object = object;2576 in_pack->nr++;2577}25782579/*2580 * Compare the objects in the offset order, in order to emulate the2581 * "git rev-list --objects" output that produced the pack originally.2582 */2583static intofscmp(const void*a_,const void*b_)2584{2585struct in_pack_object *a = (struct in_pack_object *)a_;2586struct in_pack_object *b = (struct in_pack_object *)b_;25872588if(a->offset < b->offset)2589return-1;2590else if(a->offset > b->offset)2591return1;2592else2593returnoidcmp(&a->object->oid, &b->object->oid);2594}25952596static voidadd_objects_in_unpacked_packs(struct rev_info *revs)2597{2598struct packed_git *p;2599struct in_pack in_pack;2600uint32_t i;26012602memset(&in_pack,0,sizeof(in_pack));26032604for(p = packed_git; p; p = p->next) {2605const unsigned char*sha1;2606struct object *o;26072608if(!p->pack_local || p->pack_keep)2609continue;2610if(open_pack_index(p))2611die("cannot open pack index");26122613ALLOC_GROW(in_pack.array,2614 in_pack.nr + p->num_objects,2615 in_pack.alloc);26162617for(i =0; i < p->num_objects; i++) {2618 sha1 =nth_packed_object_sha1(p, i);2619 o =lookup_unknown_object(sha1);2620if(!(o->flags & OBJECT_ADDED))2621mark_in_pack_object(o, p, &in_pack);2622 o->flags |= OBJECT_ADDED;2623}2624}26252626if(in_pack.nr) {2627QSORT(in_pack.array, in_pack.nr, ofscmp);2628for(i =0; i < in_pack.nr; i++) {2629struct object *o = in_pack.array[i].object;2630add_object_entry(o->oid.hash, o->type,"",0);2631}2632}2633free(in_pack.array);2634}26352636static intadd_loose_object(const unsigned char*sha1,const char*path,2637void*data)2638{2639enum object_type type =sha1_object_info(sha1, NULL);26402641if(type <0) {2642warning("loose object at%scould not be examined", path);2643return0;2644}26452646add_object_entry(sha1, type,"",0);2647return0;2648}26492650/*2651 * We actually don't even have to worry about reachability here.2652 * add_object_entry will weed out duplicates, so we just add every2653 * loose object we find.2654 */2655static voidadd_unreachable_loose_objects(void)2656{2657for_each_loose_file_in_objdir(get_object_directory(),2658 add_loose_object,2659 NULL, NULL, NULL);2660}26612662static inthas_sha1_pack_kept_or_nonlocal(const unsigned char*sha1)2663{2664static struct packed_git *last_found = (void*)1;2665struct packed_git *p;26662667 p = (last_found != (void*)1) ? last_found : packed_git;26682669while(p) {2670if((!p->pack_local || p->pack_keep) &&2671find_pack_entry_one(sha1, p)) {2672 last_found = p;2673return1;2674}2675if(p == last_found)2676 p = packed_git;2677else2678 p = p->next;2679if(p == last_found)2680 p = p->next;2681}2682return0;2683}26842685/*2686 * Store a list of sha1s that are should not be discarded2687 * because they are either written too recently, or are2688 * reachable from another object that was.2689 *2690 * This is filled by get_object_list.2691 */2692static struct sha1_array recent_objects;26932694static intloosened_object_can_be_discarded(const unsigned char*sha1,2695unsigned long mtime)2696{2697if(!unpack_unreachable_expiration)2698return0;2699if(mtime > unpack_unreachable_expiration)2700return0;2701if(sha1_array_lookup(&recent_objects, sha1) >=0)2702return0;2703return1;2704}27052706static voidloosen_unused_packed_objects(struct rev_info *revs)2707{2708struct packed_git *p;2709uint32_t i;2710const unsigned char*sha1;27112712for(p = packed_git; p; p = p->next) {2713if(!p->pack_local || p->pack_keep)2714continue;27152716if(open_pack_index(p))2717die("cannot open pack index");27182719for(i =0; i < p->num_objects; i++) {2720 sha1 =nth_packed_object_sha1(p, i);2721if(!packlist_find(&to_pack, sha1, NULL) &&2722!has_sha1_pack_kept_or_nonlocal(sha1) &&2723!loosened_object_can_be_discarded(sha1, p->mtime))2724if(force_object_loose(sha1, p->mtime))2725die("unable to force loose object");2726}2727}2728}27292730/*2731 * This tracks any options which pack-reuse code expects to be on, or which a2732 * reader of the pack might not understand, and which would therefore prevent2733 * blind reuse of what we have on disk.2734 */2735static intpack_options_allow_reuse(void)2736{2737return pack_to_stdout && allow_ofs_delta;2738}27392740static intget_object_list_from_bitmap(struct rev_info *revs)2741{2742if(prepare_bitmap_walk(revs) <0)2743return-1;27442745if(pack_options_allow_reuse() &&2746!reuse_partial_packfile_from_bitmap(2747&reuse_packfile,2748&reuse_packfile_objects,2749&reuse_packfile_offset)) {2750assert(reuse_packfile_objects);2751 nr_result += reuse_packfile_objects;2752display_progress(progress_state, nr_result);2753}27542755traverse_bitmap_commit_list(&add_object_entry_from_bitmap);2756return0;2757}27582759static voidrecord_recent_object(struct object *obj,2760const char*name,2761void*data)2762{2763sha1_array_append(&recent_objects, obj->oid.hash);2764}27652766static voidrecord_recent_commit(struct commit *commit,void*data)2767{2768sha1_array_append(&recent_objects, commit->object.oid.hash);2769}27702771static voidget_object_list(int ac,const char**av)2772{2773struct rev_info revs;2774char line[1000];2775int flags =0;27762777init_revisions(&revs, NULL);2778 save_commit_buffer =0;2779setup_revisions(ac, av, &revs, NULL);27802781/* make sure shallows are read */2782is_repository_shallow();27832784while(fgets(line,sizeof(line), stdin) != NULL) {2785int len =strlen(line);2786if(len && line[len -1] =='\n')2787 line[--len] =0;2788if(!len)2789break;2790if(*line =='-') {2791if(!strcmp(line,"--not")) {2792 flags ^= UNINTERESTING;2793 write_bitmap_index =0;2794continue;2795}2796if(starts_with(line,"--shallow ")) {2797unsigned char sha1[20];2798if(get_sha1_hex(line +10, sha1))2799die("not an SHA-1 '%s'", line +10);2800register_shallow(sha1);2801 use_bitmap_index =0;2802continue;2803}2804die("not a rev '%s'", line);2805}2806if(handle_revision_arg(line, &revs, flags, REVARG_CANNOT_BE_FILENAME))2807die("bad revision '%s'", line);2808}28092810if(use_bitmap_index && !get_object_list_from_bitmap(&revs))2811return;28122813if(prepare_revision_walk(&revs))2814die("revision walk setup failed");2815mark_edges_uninteresting(&revs, show_edge);2816traverse_commit_list(&revs, show_commit, show_object, NULL);28172818if(unpack_unreachable_expiration) {2819 revs.ignore_missing_links =1;2820if(add_unseen_recent_objects_to_traversal(&revs,2821 unpack_unreachable_expiration))2822die("unable to add recent objects");2823if(prepare_revision_walk(&revs))2824die("revision walk setup failed");2825traverse_commit_list(&revs, record_recent_commit,2826 record_recent_object, NULL);2827}28282829if(keep_unreachable)2830add_objects_in_unpacked_packs(&revs);2831if(pack_loose_unreachable)2832add_unreachable_loose_objects();2833if(unpack_unreachable)2834loosen_unused_packed_objects(&revs);28352836sha1_array_clear(&recent_objects);2837}28382839static intoption_parse_index_version(const struct option *opt,2840const char*arg,int unset)2841{2842char*c;2843const char*val = arg;2844 pack_idx_opts.version =strtoul(val, &c,10);2845if(pack_idx_opts.version >2)2846die(_("unsupported index version%s"), val);2847if(*c ==','&& c[1])2848 pack_idx_opts.off32_limit =strtoul(c+1, &c,0);2849if(*c || pack_idx_opts.off32_limit &0x80000000)2850die(_("bad index version '%s'"), val);2851return0;2852}28532854static intoption_parse_unpack_unreachable(const struct option *opt,2855const char*arg,int unset)2856{2857if(unset) {2858 unpack_unreachable =0;2859 unpack_unreachable_expiration =0;2860}2861else{2862 unpack_unreachable =1;2863if(arg)2864 unpack_unreachable_expiration =approxidate(arg);2865}2866return0;2867}28682869intcmd_pack_objects(int argc,const char**argv,const char*prefix)2870{2871int use_internal_rev_list =0;2872int thin =0;2873int shallow =0;2874int all_progress_implied =0;2875struct argv_array rp = ARGV_ARRAY_INIT;2876int rev_list_unpacked =0, rev_list_all =0, rev_list_reflog =0;2877int rev_list_index =0;2878struct option pack_objects_options[] = {2879OPT_SET_INT('q',"quiet", &progress,2880N_("do not show progress meter"),0),2881OPT_SET_INT(0,"progress", &progress,2882N_("show progress meter"),1),2883OPT_SET_INT(0,"all-progress", &progress,2884N_("show progress meter during object writing phase"),2),2885OPT_BOOL(0,"all-progress-implied",2886&all_progress_implied,2887N_("similar to --all-progress when progress meter is shown")),2888{ OPTION_CALLBACK,0,"index-version", NULL,N_("version[,offset]"),2889N_("write the pack index file in the specified idx format version"),28900, option_parse_index_version },2891OPT_MAGNITUDE(0,"max-pack-size", &pack_size_limit,2892N_("maximum size of each output pack file")),2893OPT_BOOL(0,"local", &local,2894N_("ignore borrowed objects from alternate object store")),2895OPT_BOOL(0,"incremental", &incremental,2896N_("ignore packed objects")),2897OPT_INTEGER(0,"window", &window,2898N_("limit pack window by objects")),2899OPT_MAGNITUDE(0,"window-memory", &window_memory_limit,2900N_("limit pack window by memory in addition to object limit")),2901OPT_INTEGER(0,"depth", &depth,2902N_("maximum length of delta chain allowed in the resulting pack")),2903OPT_BOOL(0,"reuse-delta", &reuse_delta,2904N_("reuse existing deltas")),2905OPT_BOOL(0,"reuse-object", &reuse_object,2906N_("reuse existing objects")),2907OPT_BOOL(0,"delta-base-offset", &allow_ofs_delta,2908N_("use OFS_DELTA objects")),2909OPT_INTEGER(0,"threads", &delta_search_threads,2910N_("use threads when searching for best delta matches")),2911OPT_BOOL(0,"non-empty", &non_empty,2912N_("do not create an empty pack output")),2913OPT_BOOL(0,"revs", &use_internal_rev_list,2914N_("read revision arguments from standard input")),2915{ OPTION_SET_INT,0,"unpacked", &rev_list_unpacked, NULL,2916N_("limit the objects to those that are not yet packed"),2917 PARSE_OPT_NOARG | PARSE_OPT_NONEG, NULL,1},2918{ OPTION_SET_INT,0,"all", &rev_list_all, NULL,2919N_("include objects reachable from any reference"),2920 PARSE_OPT_NOARG | PARSE_OPT_NONEG, NULL,1},2921{ OPTION_SET_INT,0,"reflog", &rev_list_reflog, NULL,2922N_("include objects referred by reflog entries"),2923 PARSE_OPT_NOARG | PARSE_OPT_NONEG, NULL,1},2924{ OPTION_SET_INT,0,"indexed-objects", &rev_list_index, NULL,2925N_("include objects referred to by the index"),2926 PARSE_OPT_NOARG | PARSE_OPT_NONEG, NULL,1},2927OPT_BOOL(0,"stdout", &pack_to_stdout,2928N_("output pack to stdout")),2929OPT_BOOL(0,"include-tag", &include_tag,2930N_("include tag objects that refer to objects to be packed")),2931OPT_BOOL(0,"keep-unreachable", &keep_unreachable,2932N_("keep unreachable objects")),2933OPT_BOOL(0,"pack-loose-unreachable", &pack_loose_unreachable,2934N_("pack loose unreachable objects")),2935{ OPTION_CALLBACK,0,"unpack-unreachable", NULL,N_("time"),2936N_("unpack unreachable objects newer than <time>"),2937 PARSE_OPT_OPTARG, option_parse_unpack_unreachable },2938OPT_BOOL(0,"thin", &thin,2939N_("create thin packs")),2940OPT_BOOL(0,"shallow", &shallow,2941N_("create packs suitable for shallow fetches")),2942OPT_BOOL(0,"honor-pack-keep", &ignore_packed_keep,2943N_("ignore packs that have companion .keep file")),2944OPT_INTEGER(0,"compression", &pack_compression_level,2945N_("pack compression level")),2946OPT_SET_INT(0,"keep-true-parents", &grafts_replace_parents,2947N_("do not hide commits by grafts"),0),2948OPT_BOOL(0,"use-bitmap-index", &use_bitmap_index,2949N_("use a bitmap index if available to speed up counting objects")),2950OPT_BOOL(0,"write-bitmap-index", &write_bitmap_index,2951N_("write a bitmap index together with the pack index")),2952OPT_END(),2953};29542955 check_replace_refs =0;29562957reset_pack_idx_option(&pack_idx_opts);2958git_config(git_pack_config, NULL);2959if(!pack_compression_seen && core_compression_seen)2960 pack_compression_level = core_compression_level;29612962 progress =isatty(2);2963 argc =parse_options(argc, argv, prefix, pack_objects_options,2964 pack_usage,0);29652966if(argc) {2967 base_name = argv[0];2968 argc--;2969}2970if(pack_to_stdout != !base_name || argc)2971usage_with_options(pack_usage, pack_objects_options);29722973argv_array_push(&rp,"pack-objects");2974if(thin) {2975 use_internal_rev_list =1;2976argv_array_push(&rp, shallow2977?"--objects-edge-aggressive"2978:"--objects-edge");2979}else2980argv_array_push(&rp,"--objects");29812982if(rev_list_all) {2983 use_internal_rev_list =1;2984argv_array_push(&rp,"--all");2985}2986if(rev_list_reflog) {2987 use_internal_rev_list =1;2988argv_array_push(&rp,"--reflog");2989}2990if(rev_list_index) {2991 use_internal_rev_list =1;2992argv_array_push(&rp,"--indexed-objects");2993}2994if(rev_list_unpacked) {2995 use_internal_rev_list =1;2996argv_array_push(&rp,"--unpacked");2997}29982999if(!reuse_object)3000 reuse_delta =0;3001if(pack_compression_level == -1)3002 pack_compression_level = Z_DEFAULT_COMPRESSION;3003else if(pack_compression_level <0|| pack_compression_level > Z_BEST_COMPRESSION)3004die("bad pack compression level%d", pack_compression_level);30053006if(!delta_search_threads)/* --threads=0 means autodetect */3007 delta_search_threads =online_cpus();30083009#ifdef NO_PTHREADS3010if(delta_search_threads !=1)3011warning("no threads support, ignoring --threads");3012#endif3013if(!pack_to_stdout && !pack_size_limit)3014 pack_size_limit = pack_size_limit_cfg;3015if(pack_to_stdout && pack_size_limit)3016die("--max-pack-size cannot be used to build a pack for transfer.");3017if(pack_size_limit && pack_size_limit <1024*1024) {3018warning("minimum pack size limit is 1 MiB");3019 pack_size_limit =1024*1024;3020}30213022if(!pack_to_stdout && thin)3023die("--thin cannot be used to build an indexable pack.");30243025if(keep_unreachable && unpack_unreachable)3026die("--keep-unreachable and --unpack-unreachable are incompatible.");3027if(!rev_list_all || !rev_list_reflog || !rev_list_index)3028 unpack_unreachable_expiration =0;30293030/*3031 * "soft" reasons not to use bitmaps - for on-disk repack by default we want3032 *3033 * - to produce good pack (with bitmap index not-yet-packed objects are3034 * packed in suboptimal order).3035 *3036 * - to use more robust pack-generation codepath (avoiding possible3037 * bugs in bitmap code and possible bitmap index corruption).3038 */3039if(!pack_to_stdout)3040 use_bitmap_index_default =0;30413042if(use_bitmap_index <0)3043 use_bitmap_index = use_bitmap_index_default;30443045/* "hard" reasons not to use bitmaps; these just won't work at all */3046if(!use_internal_rev_list || (!pack_to_stdout && write_bitmap_index) ||is_repository_shallow())3047 use_bitmap_index =0;30483049if(pack_to_stdout || !rev_list_all)3050 write_bitmap_index =0;30513052if(progress && all_progress_implied)3053 progress =2;30543055prepare_packed_git();3056if(ignore_packed_keep) {3057struct packed_git *p;3058for(p = packed_git; p; p = p->next)3059if(p->pack_local && p->pack_keep)3060break;3061if(!p)/* no keep-able packs found */3062 ignore_packed_keep =0;3063}3064if(local) {3065/*3066 * unlike ignore_packed_keep above, we do not want to3067 * unset "local" based on looking at packs, as it3068 * also covers non-local objects3069 */3070struct packed_git *p;3071for(p = packed_git; p; p = p->next) {3072if(!p->pack_local) {3073 have_non_local_packs =1;3074break;3075}3076}3077}30783079if(progress)3080 progress_state =start_progress(_("Counting objects"),0);3081if(!use_internal_rev_list)3082read_object_list_from_stdin();3083else{3084get_object_list(rp.argc, rp.argv);3085argv_array_clear(&rp);3086}3087cleanup_preferred_base();3088if(include_tag && nr_result)3089for_each_ref(add_ref_tag, NULL);3090stop_progress(&progress_state);30913092if(non_empty && !nr_result)3093return0;3094if(nr_result)3095prepare_pack(window, depth);3096write_pack_file();3097if(progress)3098fprintf(stderr,"Total %"PRIu32" (delta %"PRIu32"),"3099" reused %"PRIu32" (delta %"PRIu32")\n",3100 written, written_delta, reused, reused_delta);3101return0;3102}