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 27static const char*pack_usage[] = { 28N_("git pack-objects --stdout [<options>...] [< <ref-list> | < <object-list>]"), 29N_("git pack-objects [<options>...] <base-name> [< <ref-list> | < <object-list>]"), 30 NULL 31}; 32 33/* 34 * Objects we are going to pack are collected in the `to_pack` structure. 35 * It contains an array (dynamically expanded) of the object data, and a map 36 * that can resolve SHA1s to their position in the array. 37 */ 38static struct packing_data to_pack; 39 40static struct pack_idx_entry **written_list; 41static uint32_t nr_result, nr_written; 42 43static int non_empty; 44static int reuse_delta =1, reuse_object =1; 45static int keep_unreachable, unpack_unreachable, include_tag; 46static unsigned long unpack_unreachable_expiration; 47static int pack_loose_unreachable; 48static int local; 49static int have_non_local_packs; 50static int incremental; 51static int ignore_packed_keep; 52static int allow_ofs_delta; 53static struct pack_idx_option pack_idx_opts; 54static const char*base_name; 55static int progress =1; 56static int window =10; 57static unsigned long pack_size_limit; 58static int depth =50; 59static int delta_search_threads; 60static int pack_to_stdout; 61static int num_preferred_base; 62static struct progress *progress_state; 63static int pack_compression_level = Z_DEFAULT_COMPRESSION; 64static int pack_compression_seen; 65 66static struct packed_git *reuse_packfile; 67static uint32_t reuse_packfile_objects; 68static off_t reuse_packfile_offset; 69 70static int use_bitmap_index_default =1; 71static int use_bitmap_index = -1; 72static int write_bitmap_index; 73static uint16_t write_bitmap_options; 74 75static unsigned long delta_cache_size =0; 76static unsigned long max_delta_cache_size =256*1024*1024; 77static unsigned long cache_max_small_delta_size =1000; 78 79static unsigned long window_memory_limit =0; 80 81/* 82 * stats 83 */ 84static uint32_t written, written_delta; 85static uint32_t reused, reused_delta; 86 87/* 88 * Indexed commits 89 */ 90static struct commit **indexed_commits; 91static unsigned int indexed_commits_nr; 92static unsigned int indexed_commits_alloc; 93 94static voidindex_commit_for_bitmap(struct commit *commit) 95{ 96if(indexed_commits_nr >= indexed_commits_alloc) { 97 indexed_commits_alloc = (indexed_commits_alloc +32) *2; 98REALLOC_ARRAY(indexed_commits, indexed_commits_alloc); 99} 100 101 indexed_commits[indexed_commits_nr++] = commit; 102} 103 104static void*get_delta(struct object_entry *entry) 105{ 106unsigned long size, base_size, delta_size; 107void*buf, *base_buf, *delta_buf; 108enum object_type type; 109 110 buf =read_sha1_file(entry->idx.sha1, &type, &size); 111if(!buf) 112die("unable to read%s",sha1_to_hex(entry->idx.sha1)); 113 base_buf =read_sha1_file(entry->delta->idx.sha1, &type, &base_size); 114if(!base_buf) 115die("unable to read%s",sha1_to_hex(entry->delta->idx.sha1)); 116 delta_buf =diff_delta(base_buf, base_size, 117 buf, size, &delta_size,0); 118if(!delta_buf || delta_size != entry->delta_size) 119die("delta size changed"); 120free(buf); 121free(base_buf); 122return delta_buf; 123} 124 125static unsigned longdo_compress(void**pptr,unsigned long size) 126{ 127 git_zstream stream; 128void*in, *out; 129unsigned long maxsize; 130 131git_deflate_init(&stream, pack_compression_level); 132 maxsize =git_deflate_bound(&stream, size); 133 134 in = *pptr; 135 out =xmalloc(maxsize); 136*pptr = out; 137 138 stream.next_in = in; 139 stream.avail_in = size; 140 stream.next_out = out; 141 stream.avail_out = maxsize; 142while(git_deflate(&stream, Z_FINISH) == Z_OK) 143;/* nothing */ 144git_deflate_end(&stream); 145 146free(in); 147return stream.total_out; 148} 149 150static unsigned longwrite_large_blob_data(struct git_istream *st,struct sha1file *f, 151const unsigned char*sha1) 152{ 153 git_zstream stream; 154unsigned char ibuf[1024*16]; 155unsigned char obuf[1024*16]; 156unsigned long olen =0; 157 158git_deflate_init(&stream, pack_compression_level); 159 160for(;;) { 161 ssize_t readlen; 162int zret = Z_OK; 163 readlen =read_istream(st, ibuf,sizeof(ibuf)); 164if(readlen == -1) 165die(_("unable to read%s"),sha1_to_hex(sha1)); 166 167 stream.next_in = ibuf; 168 stream.avail_in = readlen; 169while((stream.avail_in || readlen ==0) && 170(zret == Z_OK || zret == Z_BUF_ERROR)) { 171 stream.next_out = obuf; 172 stream.avail_out =sizeof(obuf); 173 zret =git_deflate(&stream, readlen ?0: Z_FINISH); 174sha1write(f, obuf, stream.next_out - obuf); 175 olen += stream.next_out - obuf; 176} 177if(stream.avail_in) 178die(_("deflate error (%d)"), zret); 179if(readlen ==0) { 180if(zret != Z_STREAM_END) 181die(_("deflate error (%d)"), zret); 182break; 183} 184} 185git_deflate_end(&stream); 186return olen; 187} 188 189/* 190 * we are going to reuse the existing object data as is. make 191 * sure it is not corrupt. 192 */ 193static intcheck_pack_inflate(struct packed_git *p, 194struct pack_window **w_curs, 195 off_t offset, 196 off_t len, 197unsigned long expect) 198{ 199 git_zstream stream; 200unsigned char fakebuf[4096], *in; 201int st; 202 203memset(&stream,0,sizeof(stream)); 204git_inflate_init(&stream); 205do{ 206 in =use_pack(p, w_curs, offset, &stream.avail_in); 207 stream.next_in = in; 208 stream.next_out = fakebuf; 209 stream.avail_out =sizeof(fakebuf); 210 st =git_inflate(&stream, Z_FINISH); 211 offset += stream.next_in - in; 212}while(st == Z_OK || st == Z_BUF_ERROR); 213git_inflate_end(&stream); 214return(st == Z_STREAM_END && 215 stream.total_out == expect && 216 stream.total_in == len) ?0: -1; 217} 218 219static voidcopy_pack_data(struct sha1file *f, 220struct packed_git *p, 221struct pack_window **w_curs, 222 off_t offset, 223 off_t len) 224{ 225unsigned char*in; 226unsigned long avail; 227 228while(len) { 229 in =use_pack(p, w_curs, offset, &avail); 230if(avail > len) 231 avail = (unsigned long)len; 232sha1write(f, in, avail); 233 offset += avail; 234 len -= avail; 235} 236} 237 238/* Return 0 if we will bust the pack-size limit */ 239static unsigned longwrite_no_reuse_object(struct sha1file *f,struct object_entry *entry, 240unsigned long limit,int usable_delta) 241{ 242unsigned long size, datalen; 243unsigned char header[10], dheader[10]; 244unsigned hdrlen; 245enum object_type type; 246void*buf; 247struct git_istream *st = NULL; 248 249if(!usable_delta) { 250if(entry->type == OBJ_BLOB && 251 entry->size > big_file_threshold && 252(st =open_istream(entry->idx.sha1, &type, &size, NULL)) != NULL) 253 buf = NULL; 254else{ 255 buf =read_sha1_file(entry->idx.sha1, &type, &size); 256if(!buf) 257die(_("unable to read%s"),sha1_to_hex(entry->idx.sha1)); 258} 259/* 260 * make sure no cached delta data remains from a 261 * previous attempt before a pack split occurred. 262 */ 263free(entry->delta_data); 264 entry->delta_data = NULL; 265 entry->z_delta_size =0; 266}else if(entry->delta_data) { 267 size = entry->delta_size; 268 buf = entry->delta_data; 269 entry->delta_data = NULL; 270 type = (allow_ofs_delta && entry->delta->idx.offset) ? 271 OBJ_OFS_DELTA : OBJ_REF_DELTA; 272}else{ 273 buf =get_delta(entry); 274 size = entry->delta_size; 275 type = (allow_ofs_delta && entry->delta->idx.offset) ? 276 OBJ_OFS_DELTA : OBJ_REF_DELTA; 277} 278 279if(st)/* large blob case, just assume we don't compress well */ 280 datalen = size; 281else if(entry->z_delta_size) 282 datalen = entry->z_delta_size; 283else 284 datalen =do_compress(&buf, size); 285 286/* 287 * The object header is a byte of 'type' followed by zero or 288 * more bytes of length. 289 */ 290 hdrlen =encode_in_pack_object_header(type, size, header); 291 292if(type == OBJ_OFS_DELTA) { 293/* 294 * Deltas with relative base contain an additional 295 * encoding of the relative offset for the delta 296 * base from this object's position in the pack. 297 */ 298 off_t ofs = entry->idx.offset - entry->delta->idx.offset; 299unsigned pos =sizeof(dheader) -1; 300 dheader[pos] = ofs &127; 301while(ofs >>=7) 302 dheader[--pos] =128| (--ofs &127); 303if(limit && hdrlen +sizeof(dheader) - pos + datalen +20>= limit) { 304if(st) 305close_istream(st); 306free(buf); 307return0; 308} 309sha1write(f, header, hdrlen); 310sha1write(f, dheader + pos,sizeof(dheader) - pos); 311 hdrlen +=sizeof(dheader) - pos; 312}else if(type == OBJ_REF_DELTA) { 313/* 314 * Deltas with a base reference contain 315 * an additional 20 bytes for the base sha1. 316 */ 317if(limit && hdrlen +20+ datalen +20>= limit) { 318if(st) 319close_istream(st); 320free(buf); 321return0; 322} 323sha1write(f, header, hdrlen); 324sha1write(f, entry->delta->idx.sha1,20); 325 hdrlen +=20; 326}else{ 327if(limit && hdrlen + datalen +20>= limit) { 328if(st) 329close_istream(st); 330free(buf); 331return0; 332} 333sha1write(f, header, hdrlen); 334} 335if(st) { 336 datalen =write_large_blob_data(st, f, entry->idx.sha1); 337close_istream(st); 338}else{ 339sha1write(f, buf, datalen); 340free(buf); 341} 342 343return hdrlen + datalen; 344} 345 346/* Return 0 if we will bust the pack-size limit */ 347static unsigned longwrite_reuse_object(struct sha1file *f,struct object_entry *entry, 348unsigned long limit,int usable_delta) 349{ 350struct packed_git *p = entry->in_pack; 351struct pack_window *w_curs = NULL; 352struct revindex_entry *revidx; 353 off_t offset; 354enum object_type type = entry->type; 355unsigned long datalen; 356unsigned char header[10], dheader[10]; 357unsigned hdrlen; 358 359if(entry->delta) 360 type = (allow_ofs_delta && entry->delta->idx.offset) ? 361 OBJ_OFS_DELTA : OBJ_REF_DELTA; 362 hdrlen =encode_in_pack_object_header(type, entry->size, header); 363 364 offset = entry->in_pack_offset; 365 revidx =find_pack_revindex(p, offset); 366 datalen = revidx[1].offset - offset; 367if(!pack_to_stdout && p->index_version >1&& 368check_pack_crc(p, &w_curs, offset, datalen, revidx->nr)) { 369error("bad packed object CRC for%s",sha1_to_hex(entry->idx.sha1)); 370unuse_pack(&w_curs); 371returnwrite_no_reuse_object(f, entry, limit, usable_delta); 372} 373 374 offset += entry->in_pack_header_size; 375 datalen -= entry->in_pack_header_size; 376 377if(!pack_to_stdout && p->index_version ==1&& 378check_pack_inflate(p, &w_curs, offset, datalen, entry->size)) { 379error("corrupt packed object for%s",sha1_to_hex(entry->idx.sha1)); 380unuse_pack(&w_curs); 381returnwrite_no_reuse_object(f, entry, limit, usable_delta); 382} 383 384if(type == OBJ_OFS_DELTA) { 385 off_t ofs = entry->idx.offset - entry->delta->idx.offset; 386unsigned pos =sizeof(dheader) -1; 387 dheader[pos] = ofs &127; 388while(ofs >>=7) 389 dheader[--pos] =128| (--ofs &127); 390if(limit && hdrlen +sizeof(dheader) - pos + datalen +20>= limit) { 391unuse_pack(&w_curs); 392return0; 393} 394sha1write(f, header, hdrlen); 395sha1write(f, dheader + pos,sizeof(dheader) - pos); 396 hdrlen +=sizeof(dheader) - pos; 397 reused_delta++; 398}else if(type == OBJ_REF_DELTA) { 399if(limit && hdrlen +20+ datalen +20>= limit) { 400unuse_pack(&w_curs); 401return0; 402} 403sha1write(f, header, hdrlen); 404sha1write(f, entry->delta->idx.sha1,20); 405 hdrlen +=20; 406 reused_delta++; 407}else{ 408if(limit && hdrlen + datalen +20>= limit) { 409unuse_pack(&w_curs); 410return0; 411} 412sha1write(f, header, hdrlen); 413} 414copy_pack_data(f, p, &w_curs, offset, datalen); 415unuse_pack(&w_curs); 416 reused++; 417return hdrlen + datalen; 418} 419 420/* Return 0 if we will bust the pack-size limit */ 421static unsigned longwrite_object(struct sha1file *f, 422struct object_entry *entry, 423 off_t write_offset) 424{ 425unsigned long limit, len; 426int usable_delta, to_reuse; 427 428if(!pack_to_stdout) 429crc32_begin(f); 430 431/* apply size limit if limited packsize and not first object */ 432if(!pack_size_limit || !nr_written) 433 limit =0; 434else if(pack_size_limit <= write_offset) 435/* 436 * the earlier object did not fit the limit; avoid 437 * mistaking this with unlimited (i.e. limit = 0). 438 */ 439 limit =1; 440else 441 limit = pack_size_limit - write_offset; 442 443if(!entry->delta) 444 usable_delta =0;/* no delta */ 445else if(!pack_size_limit) 446 usable_delta =1;/* unlimited packfile */ 447else if(entry->delta->idx.offset == (off_t)-1) 448 usable_delta =0;/* base was written to another pack */ 449else if(entry->delta->idx.offset) 450 usable_delta =1;/* base already exists in this pack */ 451else 452 usable_delta =0;/* base could end up in another pack */ 453 454if(!reuse_object) 455 to_reuse =0;/* explicit */ 456else if(!entry->in_pack) 457 to_reuse =0;/* can't reuse what we don't have */ 458else if(entry->type == OBJ_REF_DELTA || entry->type == OBJ_OFS_DELTA) 459/* check_object() decided it for us ... */ 460 to_reuse = usable_delta; 461/* ... but pack split may override that */ 462else if(entry->type != entry->in_pack_type) 463 to_reuse =0;/* pack has delta which is unusable */ 464else if(entry->delta) 465 to_reuse =0;/* we want to pack afresh */ 466else 467 to_reuse =1;/* we have it in-pack undeltified, 468 * and we do not need to deltify it. 469 */ 470 471if(!to_reuse) 472 len =write_no_reuse_object(f, entry, limit, usable_delta); 473else 474 len =write_reuse_object(f, entry, limit, usable_delta); 475if(!len) 476return0; 477 478if(usable_delta) 479 written_delta++; 480 written++; 481if(!pack_to_stdout) 482 entry->idx.crc32 =crc32_end(f); 483return len; 484} 485 486enum write_one_status { 487 WRITE_ONE_SKIP = -1,/* already written */ 488 WRITE_ONE_BREAK =0,/* writing this will bust the limit; not written */ 489 WRITE_ONE_WRITTEN =1,/* normal */ 490 WRITE_ONE_RECURSIVE =2/* already scheduled to be written */ 491}; 492 493static enum write_one_status write_one(struct sha1file *f, 494struct object_entry *e, 495 off_t *offset) 496{ 497unsigned long size; 498int recursing; 499 500/* 501 * we set offset to 1 (which is an impossible value) to mark 502 * the fact that this object is involved in "write its base 503 * first before writing a deltified object" recursion. 504 */ 505 recursing = (e->idx.offset ==1); 506if(recursing) { 507warning("recursive delta detected for object%s", 508sha1_to_hex(e->idx.sha1)); 509return WRITE_ONE_RECURSIVE; 510}else if(e->idx.offset || e->preferred_base) { 511/* offset is non zero if object is written already. */ 512return WRITE_ONE_SKIP; 513} 514 515/* if we are deltified, write out base object first. */ 516if(e->delta) { 517 e->idx.offset =1;/* now recurse */ 518switch(write_one(f, e->delta, offset)) { 519case WRITE_ONE_RECURSIVE: 520/* we cannot depend on this one */ 521 e->delta = NULL; 522break; 523default: 524break; 525case WRITE_ONE_BREAK: 526 e->idx.offset = recursing; 527return WRITE_ONE_BREAK; 528} 529} 530 531 e->idx.offset = *offset; 532 size =write_object(f, e, *offset); 533if(!size) { 534 e->idx.offset = recursing; 535return WRITE_ONE_BREAK; 536} 537 written_list[nr_written++] = &e->idx; 538 539/* make sure off_t is sufficiently large not to wrap */ 540if(signed_add_overflows(*offset, size)) 541die("pack too large for current definition of off_t"); 542*offset += size; 543return WRITE_ONE_WRITTEN; 544} 545 546static intmark_tagged(const char*path,const struct object_id *oid,int flag, 547void*cb_data) 548{ 549unsigned char peeled[20]; 550struct object_entry *entry =packlist_find(&to_pack, oid->hash, NULL); 551 552if(entry) 553 entry->tagged =1; 554if(!peel_ref(path, peeled)) { 555 entry =packlist_find(&to_pack, peeled, NULL); 556if(entry) 557 entry->tagged =1; 558} 559return0; 560} 561 562staticinlinevoidadd_to_write_order(struct object_entry **wo, 563unsigned int*endp, 564struct object_entry *e) 565{ 566if(e->filled) 567return; 568 wo[(*endp)++] = e; 569 e->filled =1; 570} 571 572static voidadd_descendants_to_write_order(struct object_entry **wo, 573unsigned int*endp, 574struct object_entry *e) 575{ 576int add_to_order =1; 577while(e) { 578if(add_to_order) { 579struct object_entry *s; 580/* add this node... */ 581add_to_write_order(wo, endp, e); 582/* all its siblings... */ 583for(s = e->delta_sibling; s; s = s->delta_sibling) { 584add_to_write_order(wo, endp, s); 585} 586} 587/* drop down a level to add left subtree nodes if possible */ 588if(e->delta_child) { 589 add_to_order =1; 590 e = e->delta_child; 591}else{ 592 add_to_order =0; 593/* our sibling might have some children, it is next */ 594if(e->delta_sibling) { 595 e = e->delta_sibling; 596continue; 597} 598/* go back to our parent node */ 599 e = e->delta; 600while(e && !e->delta_sibling) { 601/* we're on the right side of a subtree, keep 602 * going up until we can go right again */ 603 e = e->delta; 604} 605if(!e) { 606/* done- we hit our original root node */ 607return; 608} 609/* pass it off to sibling at this level */ 610 e = e->delta_sibling; 611} 612}; 613} 614 615static voidadd_family_to_write_order(struct object_entry **wo, 616unsigned int*endp, 617struct object_entry *e) 618{ 619struct object_entry *root; 620 621for(root = e; root->delta; root = root->delta) 622;/* nothing */ 623add_descendants_to_write_order(wo, endp, root); 624} 625 626static struct object_entry **compute_write_order(void) 627{ 628unsigned int i, wo_end, last_untagged; 629 630struct object_entry **wo; 631struct object_entry *objects = to_pack.objects; 632 633for(i =0; i < to_pack.nr_objects; i++) { 634 objects[i].tagged =0; 635 objects[i].filled =0; 636 objects[i].delta_child = NULL; 637 objects[i].delta_sibling = NULL; 638} 639 640/* 641 * Fully connect delta_child/delta_sibling network. 642 * Make sure delta_sibling is sorted in the original 643 * recency order. 644 */ 645for(i = to_pack.nr_objects; i >0;) { 646struct object_entry *e = &objects[--i]; 647if(!e->delta) 648continue; 649/* Mark me as the first child */ 650 e->delta_sibling = e->delta->delta_child; 651 e->delta->delta_child = e; 652} 653 654/* 655 * Mark objects that are at the tip of tags. 656 */ 657for_each_tag_ref(mark_tagged, NULL); 658 659/* 660 * Give the objects in the original recency order until 661 * we see a tagged tip. 662 */ 663ALLOC_ARRAY(wo, to_pack.nr_objects); 664for(i = wo_end =0; i < to_pack.nr_objects; i++) { 665if(objects[i].tagged) 666break; 667add_to_write_order(wo, &wo_end, &objects[i]); 668} 669 last_untagged = i; 670 671/* 672 * Then fill all the tagged tips. 673 */ 674for(; i < to_pack.nr_objects; i++) { 675if(objects[i].tagged) 676add_to_write_order(wo, &wo_end, &objects[i]); 677} 678 679/* 680 * And then all remaining commits and tags. 681 */ 682for(i = last_untagged; i < to_pack.nr_objects; i++) { 683if(objects[i].type != OBJ_COMMIT && 684 objects[i].type != OBJ_TAG) 685continue; 686add_to_write_order(wo, &wo_end, &objects[i]); 687} 688 689/* 690 * And then all the trees. 691 */ 692for(i = last_untagged; i < to_pack.nr_objects; i++) { 693if(objects[i].type != OBJ_TREE) 694continue; 695add_to_write_order(wo, &wo_end, &objects[i]); 696} 697 698/* 699 * Finally all the rest in really tight order 700 */ 701for(i = last_untagged; i < to_pack.nr_objects; i++) { 702if(!objects[i].filled) 703add_family_to_write_order(wo, &wo_end, &objects[i]); 704} 705 706if(wo_end != to_pack.nr_objects) 707die("ordered%uobjects, expected %"PRIu32, wo_end, to_pack.nr_objects); 708 709return wo; 710} 711 712static off_t write_reused_pack(struct sha1file *f) 713{ 714unsigned char buffer[8192]; 715 off_t to_write, total; 716int fd; 717 718if(!is_pack_valid(reuse_packfile)) 719die("packfile is invalid:%s", reuse_packfile->pack_name); 720 721 fd =git_open_noatime(reuse_packfile->pack_name); 722if(fd <0) 723die_errno("unable to open packfile for reuse:%s", 724 reuse_packfile->pack_name); 725 726if(lseek(fd,sizeof(struct pack_header), SEEK_SET) == -1) 727die_errno("unable to seek in reused packfile"); 728 729if(reuse_packfile_offset <0) 730 reuse_packfile_offset = reuse_packfile->pack_size -20; 731 732 total = to_write = reuse_packfile_offset -sizeof(struct pack_header); 733 734while(to_write) { 735int read_pack =xread(fd, buffer,sizeof(buffer)); 736 737if(read_pack <=0) 738die_errno("unable to read from reused packfile"); 739 740if(read_pack > to_write) 741 read_pack = to_write; 742 743sha1write(f, buffer, read_pack); 744 to_write -= read_pack; 745 746/* 747 * We don't know the actual number of objects written, 748 * only how many bytes written, how many bytes total, and 749 * how many objects total. So we can fake it by pretending all 750 * objects we are writing are the same size. This gives us a 751 * smooth progress meter, and at the end it matches the true 752 * answer. 753 */ 754 written = reuse_packfile_objects * 755(((double)(total - to_write)) / total); 756display_progress(progress_state, written); 757} 758 759close(fd); 760 written = reuse_packfile_objects; 761display_progress(progress_state, written); 762return reuse_packfile_offset -sizeof(struct pack_header); 763} 764 765static const char no_split_warning[] =N_( 766"disabling bitmap writing, packs are split due to pack.packSizeLimit" 767); 768 769static voidwrite_pack_file(void) 770{ 771uint32_t i =0, j; 772struct sha1file *f; 773 off_t offset; 774uint32_t nr_remaining = nr_result; 775time_t last_mtime =0; 776struct object_entry **write_order; 777 778if(progress > pack_to_stdout) 779 progress_state =start_progress(_("Writing objects"), nr_result); 780ALLOC_ARRAY(written_list, to_pack.nr_objects); 781 write_order =compute_write_order(); 782 783do{ 784unsigned char sha1[20]; 785char*pack_tmp_name = NULL; 786 787if(pack_to_stdout) 788 f =sha1fd_throughput(1,"<stdout>", progress_state); 789else 790 f =create_tmp_packfile(&pack_tmp_name); 791 792 offset =write_pack_header(f, nr_remaining); 793 794if(reuse_packfile) { 795 off_t packfile_size; 796assert(pack_to_stdout); 797 798 packfile_size =write_reused_pack(f); 799 offset += packfile_size; 800} 801 802 nr_written =0; 803for(; i < to_pack.nr_objects; i++) { 804struct object_entry *e = write_order[i]; 805if(write_one(f, e, &offset) == WRITE_ONE_BREAK) 806break; 807display_progress(progress_state, written); 808} 809 810/* 811 * Did we write the wrong # entries in the header? 812 * If so, rewrite it like in fast-import 813 */ 814if(pack_to_stdout) { 815sha1close(f, sha1, CSUM_CLOSE); 816}else if(nr_written == nr_remaining) { 817sha1close(f, sha1, CSUM_FSYNC); 818}else{ 819int fd =sha1close(f, sha1,0); 820fixup_pack_header_footer(fd, sha1, pack_tmp_name, 821 nr_written, sha1, offset); 822close(fd); 823if(write_bitmap_index) { 824warning(_(no_split_warning)); 825 write_bitmap_index =0; 826} 827} 828 829if(!pack_to_stdout) { 830struct stat st; 831struct strbuf tmpname = STRBUF_INIT; 832 833/* 834 * Packs are runtime accessed in their mtime 835 * order since newer packs are more likely to contain 836 * younger objects. So if we are creating multiple 837 * packs then we should modify the mtime of later ones 838 * to preserve this property. 839 */ 840if(stat(pack_tmp_name, &st) <0) { 841warning_errno("failed to stat%s", pack_tmp_name); 842}else if(!last_mtime) { 843 last_mtime = st.st_mtime; 844}else{ 845struct utimbuf utb; 846 utb.actime = st.st_atime; 847 utb.modtime = --last_mtime; 848if(utime(pack_tmp_name, &utb) <0) 849warning_errno("failed utime() on%s", pack_tmp_name); 850} 851 852strbuf_addf(&tmpname,"%s-", base_name); 853 854if(write_bitmap_index) { 855bitmap_writer_set_checksum(sha1); 856bitmap_writer_build_type_index(written_list, nr_written); 857} 858 859finish_tmp_packfile(&tmpname, pack_tmp_name, 860 written_list, nr_written, 861&pack_idx_opts, sha1); 862 863if(write_bitmap_index) { 864strbuf_addf(&tmpname,"%s.bitmap",sha1_to_hex(sha1)); 865 866stop_progress(&progress_state); 867 868bitmap_writer_show_progress(progress); 869bitmap_writer_reuse_bitmaps(&to_pack); 870bitmap_writer_select_commits(indexed_commits, indexed_commits_nr, -1); 871bitmap_writer_build(&to_pack); 872bitmap_writer_finish(written_list, nr_written, 873 tmpname.buf, write_bitmap_options); 874 write_bitmap_index =0; 875} 876 877strbuf_release(&tmpname); 878free(pack_tmp_name); 879puts(sha1_to_hex(sha1)); 880} 881 882/* mark written objects as written to previous pack */ 883for(j =0; j < nr_written; j++) { 884 written_list[j]->offset = (off_t)-1; 885} 886 nr_remaining -= nr_written; 887}while(nr_remaining && i < to_pack.nr_objects); 888 889free(written_list); 890free(write_order); 891stop_progress(&progress_state); 892if(written != nr_result) 893die("wrote %"PRIu32" objects while expecting %"PRIu32, 894 written, nr_result); 895} 896 897static voidsetup_delta_attr_check(struct git_attr_check *check) 898{ 899static struct git_attr *attr_delta; 900 901if(!attr_delta) 902 attr_delta =git_attr("delta"); 903 904 check[0].attr = attr_delta; 905} 906 907static intno_try_delta(const char*path) 908{ 909struct git_attr_check check[1]; 910 911setup_delta_attr_check(check); 912if(git_check_attr(path,ARRAY_SIZE(check), check)) 913return0; 914if(ATTR_FALSE(check->value)) 915return1; 916return0; 917} 918 919/* 920 * When adding an object, check whether we have already added it 921 * to our packing list. If so, we can skip. However, if we are 922 * being asked to excludei t, but the previous mention was to include 923 * it, make sure to adjust its flags and tweak our numbers accordingly. 924 * 925 * As an optimization, we pass out the index position where we would have 926 * found the item, since that saves us from having to look it up again a 927 * few lines later when we want to add the new entry. 928 */ 929static inthave_duplicate_entry(const unsigned char*sha1, 930int exclude, 931uint32_t*index_pos) 932{ 933struct object_entry *entry; 934 935 entry =packlist_find(&to_pack, sha1, index_pos); 936if(!entry) 937return0; 938 939if(exclude) { 940if(!entry->preferred_base) 941 nr_result--; 942 entry->preferred_base =1; 943} 944 945return1; 946} 947 948static intwant_found_object(int exclude,struct packed_git *p) 949{ 950if(exclude) 951return1; 952if(incremental) 953return0; 954 955/* 956 * When asked to do --local (do not include an object that appears in a 957 * pack we borrow from elsewhere) or --honor-pack-keep (do not include 958 * an object that appears in a pack marked with .keep), finding a pack 959 * that matches the criteria is sufficient for us to decide to omit it. 960 * However, even if this pack does not satisfy the criteria, we need to 961 * make sure no copy of this object appears in _any_ pack that makes us 962 * to omit the object, so we need to check all the packs. 963 * 964 * We can however first check whether these options can possible matter; 965 * if they do not matter we know we want the object in generated pack. 966 * Otherwise, we signal "-1" at the end to tell the caller that we do 967 * not know either way, and it needs to check more packs. 968 */ 969if(!ignore_packed_keep && 970(!local || !have_non_local_packs)) 971return1; 972 973if(local && !p->pack_local) 974return0; 975if(ignore_packed_keep && p->pack_local && p->pack_keep) 976return0; 977 978/* we don't know yet; keep looking for more packs */ 979return-1; 980} 981 982/* 983 * Check whether we want the object in the pack (e.g., we do not want 984 * objects found in non-local stores if the "--local" option was used). 985 * 986 * If the caller already knows an existing pack it wants to take the object 987 * from, that is passed in *found_pack and *found_offset; otherwise this 988 * function finds if there is any pack that has the object and returns the pack 989 * and its offset in these variables. 990 */ 991static intwant_object_in_pack(const unsigned char*sha1, 992int exclude, 993struct packed_git **found_pack, 994 off_t *found_offset) 995{ 996struct packed_git *p; 997int want; 998 999if(!exclude && local &&has_loose_object_nonlocal(sha1))1000return0;10011002/*1003 * If we already know the pack object lives in, start checks from that1004 * pack - in the usual case when neither --local was given nor .keep files1005 * are present we will determine the answer right now.1006 */1007if(*found_pack) {1008 want =want_found_object(exclude, *found_pack);1009if(want != -1)1010return want;1011}10121013for(p = packed_git; p; p = p->next) {1014 off_t offset;10151016if(p == *found_pack)1017 offset = *found_offset;1018else1019 offset =find_pack_entry_one(sha1, p);10201021if(offset) {1022if(!*found_pack) {1023if(!is_pack_valid(p))1024continue;1025*found_offset = offset;1026*found_pack = p;1027}1028 want =want_found_object(exclude, p);1029if(want != -1)1030return want;1031}1032}10331034return1;1035}10361037static voidcreate_object_entry(const unsigned char*sha1,1038enum object_type type,1039uint32_t hash,1040int exclude,1041int no_try_delta,1042uint32_t index_pos,1043struct packed_git *found_pack,1044 off_t found_offset)1045{1046struct object_entry *entry;10471048 entry =packlist_alloc(&to_pack, sha1, index_pos);1049 entry->hash = hash;1050if(type)1051 entry->type = type;1052if(exclude)1053 entry->preferred_base =1;1054else1055 nr_result++;1056if(found_pack) {1057 entry->in_pack = found_pack;1058 entry->in_pack_offset = found_offset;1059}10601061 entry->no_try_delta = no_try_delta;1062}10631064static const char no_closure_warning[] =N_(1065"disabling bitmap writing, as some objects are not being packed"1066);10671068static intadd_object_entry(const unsigned char*sha1,enum object_type type,1069const char*name,int exclude)1070{1071struct packed_git *found_pack = NULL;1072 off_t found_offset =0;1073uint32_t index_pos;10741075if(have_duplicate_entry(sha1, exclude, &index_pos))1076return0;10771078if(!want_object_in_pack(sha1, exclude, &found_pack, &found_offset)) {1079/* The pack is missing an object, so it will not have closure */1080if(write_bitmap_index) {1081warning(_(no_closure_warning));1082 write_bitmap_index =0;1083}1084return0;1085}10861087create_object_entry(sha1, type,pack_name_hash(name),1088 exclude, name &&no_try_delta(name),1089 index_pos, found_pack, found_offset);10901091display_progress(progress_state, nr_result);1092return1;1093}10941095static intadd_object_entry_from_bitmap(const unsigned char*sha1,1096enum object_type type,1097int flags,uint32_t name_hash,1098struct packed_git *pack, off_t offset)1099{1100uint32_t index_pos;11011102if(have_duplicate_entry(sha1,0, &index_pos))1103return0;11041105if(!want_object_in_pack(sha1,0, &pack, &offset))1106return0;11071108create_object_entry(sha1, type, name_hash,0,0, index_pos, pack, offset);11091110display_progress(progress_state, nr_result);1111return1;1112}11131114struct pbase_tree_cache {1115unsigned char sha1[20];1116int ref;1117int temporary;1118void*tree_data;1119unsigned long tree_size;1120};11211122static struct pbase_tree_cache *(pbase_tree_cache[256]);1123static intpbase_tree_cache_ix(const unsigned char*sha1)1124{1125return sha1[0] %ARRAY_SIZE(pbase_tree_cache);1126}1127static intpbase_tree_cache_ix_incr(int ix)1128{1129return(ix+1) %ARRAY_SIZE(pbase_tree_cache);1130}11311132static struct pbase_tree {1133struct pbase_tree *next;1134/* This is a phony "cache" entry; we are not1135 * going to evict it or find it through _get()1136 * mechanism -- this is for the toplevel node that1137 * would almost always change with any commit.1138 */1139struct pbase_tree_cache pcache;1140} *pbase_tree;11411142static struct pbase_tree_cache *pbase_tree_get(const unsigned char*sha1)1143{1144struct pbase_tree_cache *ent, *nent;1145void*data;1146unsigned long size;1147enum object_type type;1148int neigh;1149int my_ix =pbase_tree_cache_ix(sha1);1150int available_ix = -1;11511152/* pbase-tree-cache acts as a limited hashtable.1153 * your object will be found at your index or within a few1154 * slots after that slot if it is cached.1155 */1156for(neigh =0; neigh <8; neigh++) {1157 ent = pbase_tree_cache[my_ix];1158if(ent && !hashcmp(ent->sha1, sha1)) {1159 ent->ref++;1160return ent;1161}1162else if(((available_ix <0) && (!ent || !ent->ref)) ||1163((0<= available_ix) &&1164(!ent && pbase_tree_cache[available_ix])))1165 available_ix = my_ix;1166if(!ent)1167break;1168 my_ix =pbase_tree_cache_ix_incr(my_ix);1169}11701171/* Did not find one. Either we got a bogus request or1172 * we need to read and perhaps cache.1173 */1174 data =read_sha1_file(sha1, &type, &size);1175if(!data)1176return NULL;1177if(type != OBJ_TREE) {1178free(data);1179return NULL;1180}11811182/* We need to either cache or return a throwaway copy */11831184if(available_ix <0)1185 ent = NULL;1186else{1187 ent = pbase_tree_cache[available_ix];1188 my_ix = available_ix;1189}11901191if(!ent) {1192 nent =xmalloc(sizeof(*nent));1193 nent->temporary = (available_ix <0);1194}1195else{1196/* evict and reuse */1197free(ent->tree_data);1198 nent = ent;1199}1200hashcpy(nent->sha1, sha1);1201 nent->tree_data = data;1202 nent->tree_size = size;1203 nent->ref =1;1204if(!nent->temporary)1205 pbase_tree_cache[my_ix] = nent;1206return nent;1207}12081209static voidpbase_tree_put(struct pbase_tree_cache *cache)1210{1211if(!cache->temporary) {1212 cache->ref--;1213return;1214}1215free(cache->tree_data);1216free(cache);1217}12181219static intname_cmp_len(const char*name)1220{1221int i;1222for(i =0; name[i] && name[i] !='\n'&& name[i] !='/'; i++)1223;1224return i;1225}12261227static voidadd_pbase_object(struct tree_desc *tree,1228const char*name,1229int cmplen,1230const char*fullname)1231{1232struct name_entry entry;1233int cmp;12341235while(tree_entry(tree,&entry)) {1236if(S_ISGITLINK(entry.mode))1237continue;1238 cmp =tree_entry_len(&entry) != cmplen ?1:1239memcmp(name, entry.path, cmplen);1240if(cmp >0)1241continue;1242if(cmp <0)1243return;1244if(name[cmplen] !='/') {1245add_object_entry(entry.oid->hash,1246object_type(entry.mode),1247 fullname,1);1248return;1249}1250if(S_ISDIR(entry.mode)) {1251struct tree_desc sub;1252struct pbase_tree_cache *tree;1253const char*down = name+cmplen+1;1254int downlen =name_cmp_len(down);12551256 tree =pbase_tree_get(entry.oid->hash);1257if(!tree)1258return;1259init_tree_desc(&sub, tree->tree_data, tree->tree_size);12601261add_pbase_object(&sub, down, downlen, fullname);1262pbase_tree_put(tree);1263}1264}1265}12661267static unsigned*done_pbase_paths;1268static int done_pbase_paths_num;1269static int done_pbase_paths_alloc;1270static intdone_pbase_path_pos(unsigned hash)1271{1272int lo =0;1273int hi = done_pbase_paths_num;1274while(lo < hi) {1275int mi = (hi + lo) /2;1276if(done_pbase_paths[mi] == hash)1277return mi;1278if(done_pbase_paths[mi] < hash)1279 hi = mi;1280else1281 lo = mi +1;1282}1283return-lo-1;1284}12851286static intcheck_pbase_path(unsigned hash)1287{1288int pos = (!done_pbase_paths) ? -1:done_pbase_path_pos(hash);1289if(0<= pos)1290return1;1291 pos = -pos -1;1292ALLOC_GROW(done_pbase_paths,1293 done_pbase_paths_num +1,1294 done_pbase_paths_alloc);1295 done_pbase_paths_num++;1296if(pos < done_pbase_paths_num)1297memmove(done_pbase_paths + pos +1,1298 done_pbase_paths + pos,1299(done_pbase_paths_num - pos -1) *sizeof(unsigned));1300 done_pbase_paths[pos] = hash;1301return0;1302}13031304static voidadd_preferred_base_object(const char*name)1305{1306struct pbase_tree *it;1307int cmplen;1308unsigned hash =pack_name_hash(name);13091310if(!num_preferred_base ||check_pbase_path(hash))1311return;13121313 cmplen =name_cmp_len(name);1314for(it = pbase_tree; it; it = it->next) {1315if(cmplen ==0) {1316add_object_entry(it->pcache.sha1, OBJ_TREE, NULL,1);1317}1318else{1319struct tree_desc tree;1320init_tree_desc(&tree, it->pcache.tree_data, it->pcache.tree_size);1321add_pbase_object(&tree, name, cmplen, name);1322}1323}1324}13251326static voidadd_preferred_base(unsigned char*sha1)1327{1328struct pbase_tree *it;1329void*data;1330unsigned long size;1331unsigned char tree_sha1[20];13321333if(window <= num_preferred_base++)1334return;13351336 data =read_object_with_reference(sha1, tree_type, &size, tree_sha1);1337if(!data)1338return;13391340for(it = pbase_tree; it; it = it->next) {1341if(!hashcmp(it->pcache.sha1, tree_sha1)) {1342free(data);1343return;1344}1345}13461347 it =xcalloc(1,sizeof(*it));1348 it->next = pbase_tree;1349 pbase_tree = it;13501351hashcpy(it->pcache.sha1, tree_sha1);1352 it->pcache.tree_data = data;1353 it->pcache.tree_size = size;1354}13551356static voidcleanup_preferred_base(void)1357{1358struct pbase_tree *it;1359unsigned i;13601361 it = pbase_tree;1362 pbase_tree = NULL;1363while(it) {1364struct pbase_tree *this= it;1365 it =this->next;1366free(this->pcache.tree_data);1367free(this);1368}13691370for(i =0; i <ARRAY_SIZE(pbase_tree_cache); i++) {1371if(!pbase_tree_cache[i])1372continue;1373free(pbase_tree_cache[i]->tree_data);1374free(pbase_tree_cache[i]);1375 pbase_tree_cache[i] = NULL;1376}13771378free(done_pbase_paths);1379 done_pbase_paths = NULL;1380 done_pbase_paths_num = done_pbase_paths_alloc =0;1381}13821383static voidcheck_object(struct object_entry *entry)1384{1385if(entry->in_pack) {1386struct packed_git *p = entry->in_pack;1387struct pack_window *w_curs = NULL;1388const unsigned char*base_ref = NULL;1389struct object_entry *base_entry;1390unsigned long used, used_0;1391unsigned long avail;1392 off_t ofs;1393unsigned char*buf, c;13941395 buf =use_pack(p, &w_curs, entry->in_pack_offset, &avail);13961397/*1398 * We want in_pack_type even if we do not reuse delta1399 * since non-delta representations could still be reused.1400 */1401 used =unpack_object_header_buffer(buf, avail,1402&entry->in_pack_type,1403&entry->size);1404if(used ==0)1405goto give_up;14061407/*1408 * Determine if this is a delta and if so whether we can1409 * reuse it or not. Otherwise let's find out as cheaply as1410 * possible what the actual type and size for this object is.1411 */1412switch(entry->in_pack_type) {1413default:1414/* Not a delta hence we've already got all we need. */1415 entry->type = entry->in_pack_type;1416 entry->in_pack_header_size = used;1417if(entry->type < OBJ_COMMIT || entry->type > OBJ_BLOB)1418goto give_up;1419unuse_pack(&w_curs);1420return;1421case OBJ_REF_DELTA:1422if(reuse_delta && !entry->preferred_base)1423 base_ref =use_pack(p, &w_curs,1424 entry->in_pack_offset + used, NULL);1425 entry->in_pack_header_size = used +20;1426break;1427case OBJ_OFS_DELTA:1428 buf =use_pack(p, &w_curs,1429 entry->in_pack_offset + used, NULL);1430 used_0 =0;1431 c = buf[used_0++];1432 ofs = c &127;1433while(c &128) {1434 ofs +=1;1435if(!ofs ||MSB(ofs,7)) {1436error("delta base offset overflow in pack for%s",1437sha1_to_hex(entry->idx.sha1));1438goto give_up;1439}1440 c = buf[used_0++];1441 ofs = (ofs <<7) + (c &127);1442}1443 ofs = entry->in_pack_offset - ofs;1444if(ofs <=0|| ofs >= entry->in_pack_offset) {1445error("delta base offset out of bound for%s",1446sha1_to_hex(entry->idx.sha1));1447goto give_up;1448}1449if(reuse_delta && !entry->preferred_base) {1450struct revindex_entry *revidx;1451 revidx =find_pack_revindex(p, ofs);1452if(!revidx)1453goto give_up;1454 base_ref =nth_packed_object_sha1(p, revidx->nr);1455}1456 entry->in_pack_header_size = used + used_0;1457break;1458}14591460if(base_ref && (base_entry =packlist_find(&to_pack, base_ref, NULL))) {1461/*1462 * If base_ref was set above that means we wish to1463 * reuse delta data, and we even found that base1464 * in the list of objects we want to pack. Goodie!1465 *1466 * Depth value does not matter - find_deltas() will1467 * never consider reused delta as the base object to1468 * deltify other objects against, in order to avoid1469 * circular deltas.1470 */1471 entry->type = entry->in_pack_type;1472 entry->delta = base_entry;1473 entry->delta_size = entry->size;1474 entry->delta_sibling = base_entry->delta_child;1475 base_entry->delta_child = entry;1476unuse_pack(&w_curs);1477return;1478}14791480if(entry->type) {1481/*1482 * This must be a delta and we already know what the1483 * final object type is. Let's extract the actual1484 * object size from the delta header.1485 */1486 entry->size =get_size_from_delta(p, &w_curs,1487 entry->in_pack_offset + entry->in_pack_header_size);1488if(entry->size ==0)1489goto give_up;1490unuse_pack(&w_curs);1491return;1492}14931494/*1495 * No choice but to fall back to the recursive delta walk1496 * with sha1_object_info() to find about the object type1497 * at this point...1498 */1499 give_up:1500unuse_pack(&w_curs);1501}15021503 entry->type =sha1_object_info(entry->idx.sha1, &entry->size);1504/*1505 * The error condition is checked in prepare_pack(). This is1506 * to permit a missing preferred base object to be ignored1507 * as a preferred base. Doing so can result in a larger1508 * pack file, but the transfer will still take place.1509 */1510}15111512static intpack_offset_sort(const void*_a,const void*_b)1513{1514const struct object_entry *a = *(struct object_entry **)_a;1515const struct object_entry *b = *(struct object_entry **)_b;15161517/* avoid filesystem trashing with loose objects */1518if(!a->in_pack && !b->in_pack)1519returnhashcmp(a->idx.sha1, b->idx.sha1);15201521if(a->in_pack < b->in_pack)1522return-1;1523if(a->in_pack > b->in_pack)1524return1;1525return a->in_pack_offset < b->in_pack_offset ? -1:1526(a->in_pack_offset > b->in_pack_offset);1527}15281529static voidget_object_details(void)1530{1531uint32_t i;1532struct object_entry **sorted_by_offset;15331534 sorted_by_offset =xcalloc(to_pack.nr_objects,sizeof(struct object_entry *));1535for(i =0; i < to_pack.nr_objects; i++)1536 sorted_by_offset[i] = to_pack.objects + i;1537qsort(sorted_by_offset, to_pack.nr_objects,sizeof(*sorted_by_offset), pack_offset_sort);15381539for(i =0; i < to_pack.nr_objects; i++) {1540struct object_entry *entry = sorted_by_offset[i];1541check_object(entry);1542if(big_file_threshold < entry->size)1543 entry->no_try_delta =1;1544}15451546free(sorted_by_offset);1547}15481549/*1550 * We search for deltas in a list sorted by type, by filename hash, and then1551 * by size, so that we see progressively smaller and smaller files.1552 * That's because we prefer deltas to be from the bigger file1553 * to the smaller -- deletes are potentially cheaper, but perhaps1554 * more importantly, the bigger file is likely the more recent1555 * one. The deepest deltas are therefore the oldest objects which are1556 * less susceptible to be accessed often.1557 */1558static inttype_size_sort(const void*_a,const void*_b)1559{1560const struct object_entry *a = *(struct object_entry **)_a;1561const struct object_entry *b = *(struct object_entry **)_b;15621563if(a->type > b->type)1564return-1;1565if(a->type < b->type)1566return1;1567if(a->hash > b->hash)1568return-1;1569if(a->hash < b->hash)1570return1;1571if(a->preferred_base > b->preferred_base)1572return-1;1573if(a->preferred_base < b->preferred_base)1574return1;1575if(a->size > b->size)1576return-1;1577if(a->size < b->size)1578return1;1579return a < b ? -1: (a > b);/* newest first */1580}15811582struct unpacked {1583struct object_entry *entry;1584void*data;1585struct delta_index *index;1586unsigned depth;1587};15881589static intdelta_cacheable(unsigned long src_size,unsigned long trg_size,1590unsigned long delta_size)1591{1592if(max_delta_cache_size && delta_cache_size + delta_size > max_delta_cache_size)1593return0;15941595if(delta_size < cache_max_small_delta_size)1596return1;15971598/* cache delta, if objects are large enough compared to delta size */1599if((src_size >>20) + (trg_size >>21) > (delta_size >>10))1600return1;16011602return0;1603}16041605#ifndef NO_PTHREADS16061607static pthread_mutex_t read_mutex;1608#define read_lock() pthread_mutex_lock(&read_mutex)1609#define read_unlock() pthread_mutex_unlock(&read_mutex)16101611static pthread_mutex_t cache_mutex;1612#define cache_lock() pthread_mutex_lock(&cache_mutex)1613#define cache_unlock() pthread_mutex_unlock(&cache_mutex)16141615static pthread_mutex_t progress_mutex;1616#define progress_lock() pthread_mutex_lock(&progress_mutex)1617#define progress_unlock() pthread_mutex_unlock(&progress_mutex)16181619#else16201621#define read_lock() (void)01622#define read_unlock() (void)01623#define cache_lock() (void)01624#define cache_unlock() (void)01625#define progress_lock() (void)01626#define progress_unlock() (void)016271628#endif16291630static inttry_delta(struct unpacked *trg,struct unpacked *src,1631unsigned max_depth,unsigned long*mem_usage)1632{1633struct object_entry *trg_entry = trg->entry;1634struct object_entry *src_entry = src->entry;1635unsigned long trg_size, src_size, delta_size, sizediff, max_size, sz;1636unsigned ref_depth;1637enum object_type type;1638void*delta_buf;16391640/* Don't bother doing diffs between different types */1641if(trg_entry->type != src_entry->type)1642return-1;16431644/*1645 * We do not bother to try a delta that we discarded on an1646 * earlier try, but only when reusing delta data. Note that1647 * src_entry that is marked as the preferred_base should always1648 * be considered, as even if we produce a suboptimal delta against1649 * it, we will still save the transfer cost, as we already know1650 * the other side has it and we won't send src_entry at all.1651 */1652if(reuse_delta && trg_entry->in_pack &&1653 trg_entry->in_pack == src_entry->in_pack &&1654!src_entry->preferred_base &&1655 trg_entry->in_pack_type != OBJ_REF_DELTA &&1656 trg_entry->in_pack_type != OBJ_OFS_DELTA)1657return0;16581659/* Let's not bust the allowed depth. */1660if(src->depth >= max_depth)1661return0;16621663/* Now some size filtering heuristics. */1664 trg_size = trg_entry->size;1665if(!trg_entry->delta) {1666 max_size = trg_size/2-20;1667 ref_depth =1;1668}else{1669 max_size = trg_entry->delta_size;1670 ref_depth = trg->depth;1671}1672 max_size = (uint64_t)max_size * (max_depth - src->depth) /1673(max_depth - ref_depth +1);1674if(max_size ==0)1675return0;1676 src_size = src_entry->size;1677 sizediff = src_size < trg_size ? trg_size - src_size :0;1678if(sizediff >= max_size)1679return0;1680if(trg_size < src_size /32)1681return0;16821683/* Load data if not already done */1684if(!trg->data) {1685read_lock();1686 trg->data =read_sha1_file(trg_entry->idx.sha1, &type, &sz);1687read_unlock();1688if(!trg->data)1689die("object%scannot be read",1690sha1_to_hex(trg_entry->idx.sha1));1691if(sz != trg_size)1692die("object%sinconsistent object length (%lu vs%lu)",1693sha1_to_hex(trg_entry->idx.sha1), sz, trg_size);1694*mem_usage += sz;1695}1696if(!src->data) {1697read_lock();1698 src->data =read_sha1_file(src_entry->idx.sha1, &type, &sz);1699read_unlock();1700if(!src->data) {1701if(src_entry->preferred_base) {1702static int warned =0;1703if(!warned++)1704warning("object%scannot be read",1705sha1_to_hex(src_entry->idx.sha1));1706/*1707 * Those objects are not included in the1708 * resulting pack. Be resilient and ignore1709 * them if they can't be read, in case the1710 * pack could be created nevertheless.1711 */1712return0;1713}1714die("object%scannot be read",1715sha1_to_hex(src_entry->idx.sha1));1716}1717if(sz != src_size)1718die("object%sinconsistent object length (%lu vs%lu)",1719sha1_to_hex(src_entry->idx.sha1), sz, src_size);1720*mem_usage += sz;1721}1722if(!src->index) {1723 src->index =create_delta_index(src->data, src_size);1724if(!src->index) {1725static int warned =0;1726if(!warned++)1727warning("suboptimal pack - out of memory");1728return0;1729}1730*mem_usage +=sizeof_delta_index(src->index);1731}17321733 delta_buf =create_delta(src->index, trg->data, trg_size, &delta_size, max_size);1734if(!delta_buf)1735return0;17361737if(trg_entry->delta) {1738/* Prefer only shallower same-sized deltas. */1739if(delta_size == trg_entry->delta_size &&1740 src->depth +1>= trg->depth) {1741free(delta_buf);1742return0;1743}1744}17451746/*1747 * Handle memory allocation outside of the cache1748 * accounting lock. Compiler will optimize the strangeness1749 * away when NO_PTHREADS is defined.1750 */1751free(trg_entry->delta_data);1752cache_lock();1753if(trg_entry->delta_data) {1754 delta_cache_size -= trg_entry->delta_size;1755 trg_entry->delta_data = NULL;1756}1757if(delta_cacheable(src_size, trg_size, delta_size)) {1758 delta_cache_size += delta_size;1759cache_unlock();1760 trg_entry->delta_data =xrealloc(delta_buf, delta_size);1761}else{1762cache_unlock();1763free(delta_buf);1764}17651766 trg_entry->delta = src_entry;1767 trg_entry->delta_size = delta_size;1768 trg->depth = src->depth +1;17691770return1;1771}17721773static unsigned intcheck_delta_limit(struct object_entry *me,unsigned int n)1774{1775struct object_entry *child = me->delta_child;1776unsigned int m = n;1777while(child) {1778unsigned int c =check_delta_limit(child, n +1);1779if(m < c)1780 m = c;1781 child = child->delta_sibling;1782}1783return m;1784}17851786static unsigned longfree_unpacked(struct unpacked *n)1787{1788unsigned long freed_mem =sizeof_delta_index(n->index);1789free_delta_index(n->index);1790 n->index = NULL;1791if(n->data) {1792 freed_mem += n->entry->size;1793free(n->data);1794 n->data = NULL;1795}1796 n->entry = NULL;1797 n->depth =0;1798return freed_mem;1799}18001801static voidfind_deltas(struct object_entry **list,unsigned*list_size,1802int window,int depth,unsigned*processed)1803{1804uint32_t i, idx =0, count =0;1805struct unpacked *array;1806unsigned long mem_usage =0;18071808 array =xcalloc(window,sizeof(struct unpacked));18091810for(;;) {1811struct object_entry *entry;1812struct unpacked *n = array + idx;1813int j, max_depth, best_base = -1;18141815progress_lock();1816if(!*list_size) {1817progress_unlock();1818break;1819}1820 entry = *list++;1821(*list_size)--;1822if(!entry->preferred_base) {1823(*processed)++;1824display_progress(progress_state, *processed);1825}1826progress_unlock();18271828 mem_usage -=free_unpacked(n);1829 n->entry = entry;18301831while(window_memory_limit &&1832 mem_usage > window_memory_limit &&1833 count >1) {1834uint32_t tail = (idx + window - count) % window;1835 mem_usage -=free_unpacked(array + tail);1836 count--;1837}18381839/* We do not compute delta to *create* objects we are not1840 * going to pack.1841 */1842if(entry->preferred_base)1843goto next;18441845/*1846 * If the current object is at pack edge, take the depth the1847 * objects that depend on the current object into account1848 * otherwise they would become too deep.1849 */1850 max_depth = depth;1851if(entry->delta_child) {1852 max_depth -=check_delta_limit(entry,0);1853if(max_depth <=0)1854goto next;1855}18561857 j = window;1858while(--j >0) {1859int ret;1860uint32_t other_idx = idx + j;1861struct unpacked *m;1862if(other_idx >= window)1863 other_idx -= window;1864 m = array + other_idx;1865if(!m->entry)1866break;1867 ret =try_delta(n, m, max_depth, &mem_usage);1868if(ret <0)1869break;1870else if(ret >0)1871 best_base = other_idx;1872}18731874/*1875 * If we decided to cache the delta data, then it is best1876 * to compress it right away. First because we have to do1877 * it anyway, and doing it here while we're threaded will1878 * save a lot of time in the non threaded write phase,1879 * as well as allow for caching more deltas within1880 * the same cache size limit.1881 * ...1882 * But only if not writing to stdout, since in that case1883 * the network is most likely throttling writes anyway,1884 * and therefore it is best to go to the write phase ASAP1885 * instead, as we can afford spending more time compressing1886 * between writes at that moment.1887 */1888if(entry->delta_data && !pack_to_stdout) {1889 entry->z_delta_size =do_compress(&entry->delta_data,1890 entry->delta_size);1891cache_lock();1892 delta_cache_size -= entry->delta_size;1893 delta_cache_size += entry->z_delta_size;1894cache_unlock();1895}18961897/* if we made n a delta, and if n is already at max1898 * depth, leaving it in the window is pointless. we1899 * should evict it first.1900 */1901if(entry->delta && max_depth <= n->depth)1902continue;19031904/*1905 * Move the best delta base up in the window, after the1906 * currently deltified object, to keep it longer. It will1907 * be the first base object to be attempted next.1908 */1909if(entry->delta) {1910struct unpacked swap = array[best_base];1911int dist = (window + idx - best_base) % window;1912int dst = best_base;1913while(dist--) {1914int src = (dst +1) % window;1915 array[dst] = array[src];1916 dst = src;1917}1918 array[dst] = swap;1919}19201921 next:1922 idx++;1923if(count +1< window)1924 count++;1925if(idx >= window)1926 idx =0;1927}19281929for(i =0; i < window; ++i) {1930free_delta_index(array[i].index);1931free(array[i].data);1932}1933free(array);1934}19351936#ifndef NO_PTHREADS19371938static voidtry_to_free_from_threads(size_t size)1939{1940read_lock();1941release_pack_memory(size);1942read_unlock();1943}19441945static try_to_free_t old_try_to_free_routine;19461947/*1948 * The main thread waits on the condition that (at least) one of the workers1949 * has stopped working (which is indicated in the .working member of1950 * struct thread_params).1951 * When a work thread has completed its work, it sets .working to 0 and1952 * signals the main thread and waits on the condition that .data_ready1953 * becomes 1.1954 */19551956struct thread_params {1957 pthread_t thread;1958struct object_entry **list;1959unsigned list_size;1960unsigned remaining;1961int window;1962int depth;1963int working;1964int data_ready;1965 pthread_mutex_t mutex;1966 pthread_cond_t cond;1967unsigned*processed;1968};19691970static pthread_cond_t progress_cond;19711972/*1973 * Mutex and conditional variable can't be statically-initialized on Windows.1974 */1975static voidinit_threaded_search(void)1976{1977init_recursive_mutex(&read_mutex);1978pthread_mutex_init(&cache_mutex, NULL);1979pthread_mutex_init(&progress_mutex, NULL);1980pthread_cond_init(&progress_cond, NULL);1981 old_try_to_free_routine =set_try_to_free_routine(try_to_free_from_threads);1982}19831984static voidcleanup_threaded_search(void)1985{1986set_try_to_free_routine(old_try_to_free_routine);1987pthread_cond_destroy(&progress_cond);1988pthread_mutex_destroy(&read_mutex);1989pthread_mutex_destroy(&cache_mutex);1990pthread_mutex_destroy(&progress_mutex);1991}19921993static void*threaded_find_deltas(void*arg)1994{1995struct thread_params *me = arg;19961997while(me->remaining) {1998find_deltas(me->list, &me->remaining,1999 me->window, me->depth, me->processed);20002001progress_lock();2002 me->working =0;2003pthread_cond_signal(&progress_cond);2004progress_unlock();20052006/*2007 * We must not set ->data_ready before we wait on the2008 * condition because the main thread may have set it to 12009 * before we get here. In order to be sure that new2010 * work is available if we see 1 in ->data_ready, it2011 * was initialized to 0 before this thread was spawned2012 * and we reset it to 0 right away.2013 */2014pthread_mutex_lock(&me->mutex);2015while(!me->data_ready)2016pthread_cond_wait(&me->cond, &me->mutex);2017 me->data_ready =0;2018pthread_mutex_unlock(&me->mutex);2019}2020/* leave ->working 1 so that this doesn't get more work assigned */2021return NULL;2022}20232024static voidll_find_deltas(struct object_entry **list,unsigned list_size,2025int window,int depth,unsigned*processed)2026{2027struct thread_params *p;2028int i, ret, active_threads =0;20292030init_threaded_search();20312032if(delta_search_threads <=1) {2033find_deltas(list, &list_size, window, depth, processed);2034cleanup_threaded_search();2035return;2036}2037if(progress > pack_to_stdout)2038fprintf(stderr,"Delta compression using up to%dthreads.\n",2039 delta_search_threads);2040 p =xcalloc(delta_search_threads,sizeof(*p));20412042/* Partition the work amongst work threads. */2043for(i =0; i < delta_search_threads; i++) {2044unsigned sub_size = list_size / (delta_search_threads - i);20452046/* don't use too small segments or no deltas will be found */2047if(sub_size <2*window && i+1< delta_search_threads)2048 sub_size =0;20492050 p[i].window = window;2051 p[i].depth = depth;2052 p[i].processed = processed;2053 p[i].working =1;2054 p[i].data_ready =0;20552056/* try to split chunks on "path" boundaries */2057while(sub_size && sub_size < list_size &&2058 list[sub_size]->hash &&2059 list[sub_size]->hash == list[sub_size-1]->hash)2060 sub_size++;20612062 p[i].list = list;2063 p[i].list_size = sub_size;2064 p[i].remaining = sub_size;20652066 list += sub_size;2067 list_size -= sub_size;2068}20692070/* Start work threads. */2071for(i =0; i < delta_search_threads; i++) {2072if(!p[i].list_size)2073continue;2074pthread_mutex_init(&p[i].mutex, NULL);2075pthread_cond_init(&p[i].cond, NULL);2076 ret =pthread_create(&p[i].thread, NULL,2077 threaded_find_deltas, &p[i]);2078if(ret)2079die("unable to create thread:%s",strerror(ret));2080 active_threads++;2081}20822083/*2084 * Now let's wait for work completion. Each time a thread is done2085 * with its work, we steal half of the remaining work from the2086 * thread with the largest number of unprocessed objects and give2087 * it to that newly idle thread. This ensure good load balancing2088 * until the remaining object list segments are simply too short2089 * to be worth splitting anymore.2090 */2091while(active_threads) {2092struct thread_params *target = NULL;2093struct thread_params *victim = NULL;2094unsigned sub_size =0;20952096progress_lock();2097for(;;) {2098for(i =0; !target && i < delta_search_threads; i++)2099if(!p[i].working)2100 target = &p[i];2101if(target)2102break;2103pthread_cond_wait(&progress_cond, &progress_mutex);2104}21052106for(i =0; i < delta_search_threads; i++)2107if(p[i].remaining >2*window &&2108(!victim || victim->remaining < p[i].remaining))2109 victim = &p[i];2110if(victim) {2111 sub_size = victim->remaining /2;2112 list = victim->list + victim->list_size - sub_size;2113while(sub_size && list[0]->hash &&2114 list[0]->hash == list[-1]->hash) {2115 list++;2116 sub_size--;2117}2118if(!sub_size) {2119/*2120 * It is possible for some "paths" to have2121 * so many objects that no hash boundary2122 * might be found. Let's just steal the2123 * exact half in that case.2124 */2125 sub_size = victim->remaining /2;2126 list -= sub_size;2127}2128 target->list = list;2129 victim->list_size -= sub_size;2130 victim->remaining -= sub_size;2131}2132 target->list_size = sub_size;2133 target->remaining = sub_size;2134 target->working =1;2135progress_unlock();21362137pthread_mutex_lock(&target->mutex);2138 target->data_ready =1;2139pthread_cond_signal(&target->cond);2140pthread_mutex_unlock(&target->mutex);21412142if(!sub_size) {2143pthread_join(target->thread, NULL);2144pthread_cond_destroy(&target->cond);2145pthread_mutex_destroy(&target->mutex);2146 active_threads--;2147}2148}2149cleanup_threaded_search();2150free(p);2151}21522153#else2154#define ll_find_deltas(l, s, w, d, p) find_deltas(l, &s, w, d, p)2155#endif21562157static intadd_ref_tag(const char*path,const struct object_id *oid,int flag,void*cb_data)2158{2159struct object_id peeled;21602161if(starts_with(path,"refs/tags/") &&/* is a tag? */2162!peel_ref(path, peeled.hash) &&/* peelable? */2163packlist_find(&to_pack, peeled.hash, NULL))/* object packed? */2164add_object_entry(oid->hash, OBJ_TAG, NULL,0);2165return0;2166}21672168static voidprepare_pack(int window,int depth)2169{2170struct object_entry **delta_list;2171uint32_t i, nr_deltas;2172unsigned n;21732174get_object_details();21752176/*2177 * If we're locally repacking then we need to be doubly careful2178 * from now on in order to make sure no stealth corruption gets2179 * propagated to the new pack. Clients receiving streamed packs2180 * should validate everything they get anyway so no need to incur2181 * the additional cost here in that case.2182 */2183if(!pack_to_stdout)2184 do_check_packed_object_crc =1;21852186if(!to_pack.nr_objects || !window || !depth)2187return;21882189ALLOC_ARRAY(delta_list, to_pack.nr_objects);2190 nr_deltas = n =0;21912192for(i =0; i < to_pack.nr_objects; i++) {2193struct object_entry *entry = to_pack.objects + i;21942195if(entry->delta)2196/* This happens if we decided to reuse existing2197 * delta from a pack. "reuse_delta &&" is implied.2198 */2199continue;22002201if(entry->size <50)2202continue;22032204if(entry->no_try_delta)2205continue;22062207if(!entry->preferred_base) {2208 nr_deltas++;2209if(entry->type <0)2210die("unable to get type of object%s",2211sha1_to_hex(entry->idx.sha1));2212}else{2213if(entry->type <0) {2214/*2215 * This object is not found, but we2216 * don't have to include it anyway.2217 */2218continue;2219}2220}22212222 delta_list[n++] = entry;2223}22242225if(nr_deltas && n >1) {2226unsigned nr_done =0;2227if(progress)2228 progress_state =start_progress(_("Compressing objects"),2229 nr_deltas);2230qsort(delta_list, n,sizeof(*delta_list), type_size_sort);2231ll_find_deltas(delta_list, n, window+1, depth, &nr_done);2232stop_progress(&progress_state);2233if(nr_done != nr_deltas)2234die("inconsistency with delta count");2235}2236free(delta_list);2237}22382239static intgit_pack_config(const char*k,const char*v,void*cb)2240{2241if(!strcmp(k,"pack.window")) {2242 window =git_config_int(k, v);2243return0;2244}2245if(!strcmp(k,"pack.windowmemory")) {2246 window_memory_limit =git_config_ulong(k, v);2247return0;2248}2249if(!strcmp(k,"pack.depth")) {2250 depth =git_config_int(k, v);2251return0;2252}2253if(!strcmp(k,"pack.compression")) {2254int level =git_config_int(k, v);2255if(level == -1)2256 level = Z_DEFAULT_COMPRESSION;2257else if(level <0|| level > Z_BEST_COMPRESSION)2258die("bad pack compression level%d", level);2259 pack_compression_level = level;2260 pack_compression_seen =1;2261return0;2262}2263if(!strcmp(k,"pack.deltacachesize")) {2264 max_delta_cache_size =git_config_int(k, v);2265return0;2266}2267if(!strcmp(k,"pack.deltacachelimit")) {2268 cache_max_small_delta_size =git_config_int(k, v);2269return0;2270}2271if(!strcmp(k,"pack.writebitmaphashcache")) {2272if(git_config_bool(k, v))2273 write_bitmap_options |= BITMAP_OPT_HASH_CACHE;2274else2275 write_bitmap_options &= ~BITMAP_OPT_HASH_CACHE;2276}2277if(!strcmp(k,"pack.usebitmaps")) {2278 use_bitmap_index_default =git_config_bool(k, v);2279return0;2280}2281if(!strcmp(k,"pack.threads")) {2282 delta_search_threads =git_config_int(k, v);2283if(delta_search_threads <0)2284die("invalid number of threads specified (%d)",2285 delta_search_threads);2286#ifdef NO_PTHREADS2287if(delta_search_threads !=1)2288warning("no threads support, ignoring%s", k);2289#endif2290return0;2291}2292if(!strcmp(k,"pack.indexversion")) {2293 pack_idx_opts.version =git_config_int(k, v);2294if(pack_idx_opts.version >2)2295die("bad pack.indexversion=%"PRIu32,2296 pack_idx_opts.version);2297return0;2298}2299returngit_default_config(k, v, cb);2300}23012302static voidread_object_list_from_stdin(void)2303{2304char line[40+1+ PATH_MAX +2];2305unsigned char sha1[20];23062307for(;;) {2308if(!fgets(line,sizeof(line), stdin)) {2309if(feof(stdin))2310break;2311if(!ferror(stdin))2312die("fgets returned NULL, not EOF, not error!");2313if(errno != EINTR)2314die_errno("fgets");2315clearerr(stdin);2316continue;2317}2318if(line[0] =='-') {2319if(get_sha1_hex(line+1, sha1))2320die("expected edge sha1, got garbage:\n%s",2321 line);2322add_preferred_base(sha1);2323continue;2324}2325if(get_sha1_hex(line, sha1))2326die("expected sha1, got garbage:\n%s", line);23272328add_preferred_base_object(line+41);2329add_object_entry(sha1,0, line+41,0);2330}2331}23322333#define OBJECT_ADDED (1u<<20)23342335static voidshow_commit(struct commit *commit,void*data)2336{2337add_object_entry(commit->object.oid.hash, OBJ_COMMIT, NULL,0);2338 commit->object.flags |= OBJECT_ADDED;23392340if(write_bitmap_index)2341index_commit_for_bitmap(commit);2342}23432344static voidshow_object(struct object *obj,const char*name,void*data)2345{2346add_preferred_base_object(name);2347add_object_entry(obj->oid.hash, obj->type, name,0);2348 obj->flags |= OBJECT_ADDED;2349}23502351static voidshow_edge(struct commit *commit)2352{2353add_preferred_base(commit->object.oid.hash);2354}23552356struct in_pack_object {2357 off_t offset;2358struct object *object;2359};23602361struct in_pack {2362int alloc;2363int nr;2364struct in_pack_object *array;2365};23662367static voidmark_in_pack_object(struct object *object,struct packed_git *p,struct in_pack *in_pack)2368{2369 in_pack->array[in_pack->nr].offset =find_pack_entry_one(object->oid.hash, p);2370 in_pack->array[in_pack->nr].object = object;2371 in_pack->nr++;2372}23732374/*2375 * Compare the objects in the offset order, in order to emulate the2376 * "git rev-list --objects" output that produced the pack originally.2377 */2378static intofscmp(const void*a_,const void*b_)2379{2380struct in_pack_object *a = (struct in_pack_object *)a_;2381struct in_pack_object *b = (struct in_pack_object *)b_;23822383if(a->offset < b->offset)2384return-1;2385else if(a->offset > b->offset)2386return1;2387else2388returnoidcmp(&a->object->oid, &b->object->oid);2389}23902391static voidadd_objects_in_unpacked_packs(struct rev_info *revs)2392{2393struct packed_git *p;2394struct in_pack in_pack;2395uint32_t i;23962397memset(&in_pack,0,sizeof(in_pack));23982399for(p = packed_git; p; p = p->next) {2400const unsigned char*sha1;2401struct object *o;24022403if(!p->pack_local || p->pack_keep)2404continue;2405if(open_pack_index(p))2406die("cannot open pack index");24072408ALLOC_GROW(in_pack.array,2409 in_pack.nr + p->num_objects,2410 in_pack.alloc);24112412for(i =0; i < p->num_objects; i++) {2413 sha1 =nth_packed_object_sha1(p, i);2414 o =lookup_unknown_object(sha1);2415if(!(o->flags & OBJECT_ADDED))2416mark_in_pack_object(o, p, &in_pack);2417 o->flags |= OBJECT_ADDED;2418}2419}24202421if(in_pack.nr) {2422qsort(in_pack.array, in_pack.nr,sizeof(in_pack.array[0]),2423 ofscmp);2424for(i =0; i < in_pack.nr; i++) {2425struct object *o = in_pack.array[i].object;2426add_object_entry(o->oid.hash, o->type,"",0);2427}2428}2429free(in_pack.array);2430}24312432static intadd_loose_object(const unsigned char*sha1,const char*path,2433void*data)2434{2435enum object_type type =sha1_object_info(sha1, NULL);24362437if(type <0) {2438warning("loose object at%scould not be examined", path);2439return0;2440}24412442add_object_entry(sha1, type,"",0);2443return0;2444}24452446/*2447 * We actually don't even have to worry about reachability here.2448 * add_object_entry will weed out duplicates, so we just add every2449 * loose object we find.2450 */2451static voidadd_unreachable_loose_objects(void)2452{2453for_each_loose_file_in_objdir(get_object_directory(),2454 add_loose_object,2455 NULL, NULL, NULL);2456}24572458static inthas_sha1_pack_kept_or_nonlocal(const unsigned char*sha1)2459{2460static struct packed_git *last_found = (void*)1;2461struct packed_git *p;24622463 p = (last_found != (void*)1) ? last_found : packed_git;24642465while(p) {2466if((!p->pack_local || p->pack_keep) &&2467find_pack_entry_one(sha1, p)) {2468 last_found = p;2469return1;2470}2471if(p == last_found)2472 p = packed_git;2473else2474 p = p->next;2475if(p == last_found)2476 p = p->next;2477}2478return0;2479}24802481/*2482 * Store a list of sha1s that are should not be discarded2483 * because they are either written too recently, or are2484 * reachable from another object that was.2485 *2486 * This is filled by get_object_list.2487 */2488static struct sha1_array recent_objects;24892490static intloosened_object_can_be_discarded(const unsigned char*sha1,2491unsigned long mtime)2492{2493if(!unpack_unreachable_expiration)2494return0;2495if(mtime > unpack_unreachable_expiration)2496return0;2497if(sha1_array_lookup(&recent_objects, sha1) >=0)2498return0;2499return1;2500}25012502static voidloosen_unused_packed_objects(struct rev_info *revs)2503{2504struct packed_git *p;2505uint32_t i;2506const unsigned char*sha1;25072508for(p = packed_git; p; p = p->next) {2509if(!p->pack_local || p->pack_keep)2510continue;25112512if(open_pack_index(p))2513die("cannot open pack index");25142515for(i =0; i < p->num_objects; i++) {2516 sha1 =nth_packed_object_sha1(p, i);2517if(!packlist_find(&to_pack, sha1, NULL) &&2518!has_sha1_pack_kept_or_nonlocal(sha1) &&2519!loosened_object_can_be_discarded(sha1, p->mtime))2520if(force_object_loose(sha1, p->mtime))2521die("unable to force loose object");2522}2523}2524}25252526/*2527 * This tracks any options which pack-reuse code expects to be on, or which a2528 * reader of the pack might not understand, and which would therefore prevent2529 * blind reuse of what we have on disk.2530 */2531static intpack_options_allow_reuse(void)2532{2533return pack_to_stdout && allow_ofs_delta;2534}25352536static intget_object_list_from_bitmap(struct rev_info *revs)2537{2538if(prepare_bitmap_walk(revs) <0)2539return-1;25402541if(pack_options_allow_reuse() &&2542!reuse_partial_packfile_from_bitmap(2543&reuse_packfile,2544&reuse_packfile_objects,2545&reuse_packfile_offset)) {2546assert(reuse_packfile_objects);2547 nr_result += reuse_packfile_objects;2548display_progress(progress_state, nr_result);2549}25502551traverse_bitmap_commit_list(&add_object_entry_from_bitmap);2552return0;2553}25542555static voidrecord_recent_object(struct object *obj,2556const char*name,2557void*data)2558{2559sha1_array_append(&recent_objects, obj->oid.hash);2560}25612562static voidrecord_recent_commit(struct commit *commit,void*data)2563{2564sha1_array_append(&recent_objects, commit->object.oid.hash);2565}25662567static voidget_object_list(int ac,const char**av)2568{2569struct rev_info revs;2570char line[1000];2571int flags =0;25722573init_revisions(&revs, NULL);2574 save_commit_buffer =0;2575setup_revisions(ac, av, &revs, NULL);25762577/* make sure shallows are read */2578is_repository_shallow();25792580while(fgets(line,sizeof(line), stdin) != NULL) {2581int len =strlen(line);2582if(len && line[len -1] =='\n')2583 line[--len] =0;2584if(!len)2585break;2586if(*line =='-') {2587if(!strcmp(line,"--not")) {2588 flags ^= UNINTERESTING;2589 write_bitmap_index =0;2590continue;2591}2592if(starts_with(line,"--shallow ")) {2593unsigned char sha1[20];2594if(get_sha1_hex(line +10, sha1))2595die("not an SHA-1 '%s'", line +10);2596register_shallow(sha1);2597 use_bitmap_index =0;2598continue;2599}2600die("not a rev '%s'", line);2601}2602if(handle_revision_arg(line, &revs, flags, REVARG_CANNOT_BE_FILENAME))2603die("bad revision '%s'", line);2604}26052606if(use_bitmap_index && !get_object_list_from_bitmap(&revs))2607return;26082609if(prepare_revision_walk(&revs))2610die("revision walk setup failed");2611mark_edges_uninteresting(&revs, show_edge);2612traverse_commit_list(&revs, show_commit, show_object, NULL);26132614if(unpack_unreachable_expiration) {2615 revs.ignore_missing_links =1;2616if(add_unseen_recent_objects_to_traversal(&revs,2617 unpack_unreachable_expiration))2618die("unable to add recent objects");2619if(prepare_revision_walk(&revs))2620die("revision walk setup failed");2621traverse_commit_list(&revs, record_recent_commit,2622 record_recent_object, NULL);2623}26242625if(keep_unreachable)2626add_objects_in_unpacked_packs(&revs);2627if(pack_loose_unreachable)2628add_unreachable_loose_objects();2629if(unpack_unreachable)2630loosen_unused_packed_objects(&revs);26312632sha1_array_clear(&recent_objects);2633}26342635static intoption_parse_index_version(const struct option *opt,2636const char*arg,int unset)2637{2638char*c;2639const char*val = arg;2640 pack_idx_opts.version =strtoul(val, &c,10);2641if(pack_idx_opts.version >2)2642die(_("unsupported index version%s"), val);2643if(*c ==','&& c[1])2644 pack_idx_opts.off32_limit =strtoul(c+1, &c,0);2645if(*c || pack_idx_opts.off32_limit &0x80000000)2646die(_("bad index version '%s'"), val);2647return0;2648}26492650static intoption_parse_unpack_unreachable(const struct option *opt,2651const char*arg,int unset)2652{2653if(unset) {2654 unpack_unreachable =0;2655 unpack_unreachable_expiration =0;2656}2657else{2658 unpack_unreachable =1;2659if(arg)2660 unpack_unreachable_expiration =approxidate(arg);2661}2662return0;2663}26642665intcmd_pack_objects(int argc,const char**argv,const char*prefix)2666{2667int use_internal_rev_list =0;2668int thin =0;2669int shallow =0;2670int all_progress_implied =0;2671struct argv_array rp = ARGV_ARRAY_INIT;2672int rev_list_unpacked =0, rev_list_all =0, rev_list_reflog =0;2673int rev_list_index =0;2674struct option pack_objects_options[] = {2675OPT_SET_INT('q',"quiet", &progress,2676N_("do not show progress meter"),0),2677OPT_SET_INT(0,"progress", &progress,2678N_("show progress meter"),1),2679OPT_SET_INT(0,"all-progress", &progress,2680N_("show progress meter during object writing phase"),2),2681OPT_BOOL(0,"all-progress-implied",2682&all_progress_implied,2683N_("similar to --all-progress when progress meter is shown")),2684{ OPTION_CALLBACK,0,"index-version", NULL,N_("version[,offset]"),2685N_("write the pack index file in the specified idx format version"),26860, option_parse_index_version },2687OPT_MAGNITUDE(0,"max-pack-size", &pack_size_limit,2688N_("maximum size of each output pack file")),2689OPT_BOOL(0,"local", &local,2690N_("ignore borrowed objects from alternate object store")),2691OPT_BOOL(0,"incremental", &incremental,2692N_("ignore packed objects")),2693OPT_INTEGER(0,"window", &window,2694N_("limit pack window by objects")),2695OPT_MAGNITUDE(0,"window-memory", &window_memory_limit,2696N_("limit pack window by memory in addition to object limit")),2697OPT_INTEGER(0,"depth", &depth,2698N_("maximum length of delta chain allowed in the resulting pack")),2699OPT_BOOL(0,"reuse-delta", &reuse_delta,2700N_("reuse existing deltas")),2701OPT_BOOL(0,"reuse-object", &reuse_object,2702N_("reuse existing objects")),2703OPT_BOOL(0,"delta-base-offset", &allow_ofs_delta,2704N_("use OFS_DELTA objects")),2705OPT_INTEGER(0,"threads", &delta_search_threads,2706N_("use threads when searching for best delta matches")),2707OPT_BOOL(0,"non-empty", &non_empty,2708N_("do not create an empty pack output")),2709OPT_BOOL(0,"revs", &use_internal_rev_list,2710N_("read revision arguments from standard input")),2711{ OPTION_SET_INT,0,"unpacked", &rev_list_unpacked, NULL,2712N_("limit the objects to those that are not yet packed"),2713 PARSE_OPT_NOARG | PARSE_OPT_NONEG, NULL,1},2714{ OPTION_SET_INT,0,"all", &rev_list_all, NULL,2715N_("include objects reachable from any reference"),2716 PARSE_OPT_NOARG | PARSE_OPT_NONEG, NULL,1},2717{ OPTION_SET_INT,0,"reflog", &rev_list_reflog, NULL,2718N_("include objects referred by reflog entries"),2719 PARSE_OPT_NOARG | PARSE_OPT_NONEG, NULL,1},2720{ OPTION_SET_INT,0,"indexed-objects", &rev_list_index, NULL,2721N_("include objects referred to by the index"),2722 PARSE_OPT_NOARG | PARSE_OPT_NONEG, NULL,1},2723OPT_BOOL(0,"stdout", &pack_to_stdout,2724N_("output pack to stdout")),2725OPT_BOOL(0,"include-tag", &include_tag,2726N_("include tag objects that refer to objects to be packed")),2727OPT_BOOL(0,"keep-unreachable", &keep_unreachable,2728N_("keep unreachable objects")),2729OPT_BOOL(0,"pack-loose-unreachable", &pack_loose_unreachable,2730N_("pack loose unreachable objects")),2731{ OPTION_CALLBACK,0,"unpack-unreachable", NULL,N_("time"),2732N_("unpack unreachable objects newer than <time>"),2733 PARSE_OPT_OPTARG, option_parse_unpack_unreachable },2734OPT_BOOL(0,"thin", &thin,2735N_("create thin packs")),2736OPT_BOOL(0,"shallow", &shallow,2737N_("create packs suitable for shallow fetches")),2738OPT_BOOL(0,"honor-pack-keep", &ignore_packed_keep,2739N_("ignore packs that have companion .keep file")),2740OPT_INTEGER(0,"compression", &pack_compression_level,2741N_("pack compression level")),2742OPT_SET_INT(0,"keep-true-parents", &grafts_replace_parents,2743N_("do not hide commits by grafts"),0),2744OPT_BOOL(0,"use-bitmap-index", &use_bitmap_index,2745N_("use a bitmap index if available to speed up counting objects")),2746OPT_BOOL(0,"write-bitmap-index", &write_bitmap_index,2747N_("write a bitmap index together with the pack index")),2748OPT_END(),2749};27502751 check_replace_refs =0;27522753reset_pack_idx_option(&pack_idx_opts);2754git_config(git_pack_config, NULL);2755if(!pack_compression_seen && core_compression_seen)2756 pack_compression_level = core_compression_level;27572758 progress =isatty(2);2759 argc =parse_options(argc, argv, prefix, pack_objects_options,2760 pack_usage,0);27612762if(argc) {2763 base_name = argv[0];2764 argc--;2765}2766if(pack_to_stdout != !base_name || argc)2767usage_with_options(pack_usage, pack_objects_options);27682769argv_array_push(&rp,"pack-objects");2770if(thin) {2771 use_internal_rev_list =1;2772argv_array_push(&rp, shallow2773?"--objects-edge-aggressive"2774:"--objects-edge");2775}else2776argv_array_push(&rp,"--objects");27772778if(rev_list_all) {2779 use_internal_rev_list =1;2780argv_array_push(&rp,"--all");2781}2782if(rev_list_reflog) {2783 use_internal_rev_list =1;2784argv_array_push(&rp,"--reflog");2785}2786if(rev_list_index) {2787 use_internal_rev_list =1;2788argv_array_push(&rp,"--indexed-objects");2789}2790if(rev_list_unpacked) {2791 use_internal_rev_list =1;2792argv_array_push(&rp,"--unpacked");2793}27942795if(!reuse_object)2796 reuse_delta =0;2797if(pack_compression_level == -1)2798 pack_compression_level = Z_DEFAULT_COMPRESSION;2799else if(pack_compression_level <0|| pack_compression_level > Z_BEST_COMPRESSION)2800die("bad pack compression level%d", pack_compression_level);28012802if(!delta_search_threads)/* --threads=0 means autodetect */2803 delta_search_threads =online_cpus();28042805#ifdef NO_PTHREADS2806if(delta_search_threads !=1)2807warning("no threads support, ignoring --threads");2808#endif2809if(!pack_to_stdout && !pack_size_limit)2810 pack_size_limit = pack_size_limit_cfg;2811if(pack_to_stdout && pack_size_limit)2812die("--max-pack-size cannot be used to build a pack for transfer.");2813if(pack_size_limit && pack_size_limit <1024*1024) {2814warning("minimum pack size limit is 1 MiB");2815 pack_size_limit =1024*1024;2816}28172818if(!pack_to_stdout && thin)2819die("--thin cannot be used to build an indexable pack.");28202821if(keep_unreachable && unpack_unreachable)2822die("--keep-unreachable and --unpack-unreachable are incompatible.");2823if(!rev_list_all || !rev_list_reflog || !rev_list_index)2824 unpack_unreachable_expiration =0;28252826/*2827 * "soft" reasons not to use bitmaps - for on-disk repack by default we want2828 *2829 * - to produce good pack (with bitmap index not-yet-packed objects are2830 * packed in suboptimal order).2831 *2832 * - to use more robust pack-generation codepath (avoiding possible2833 * bugs in bitmap code and possible bitmap index corruption).2834 */2835if(!pack_to_stdout)2836 use_bitmap_index_default =0;28372838if(use_bitmap_index <0)2839 use_bitmap_index = use_bitmap_index_default;28402841/* "hard" reasons not to use bitmaps; these just won't work at all */2842if(!use_internal_rev_list || (!pack_to_stdout && write_bitmap_index) ||is_repository_shallow())2843 use_bitmap_index =0;28442845if(pack_to_stdout || !rev_list_all)2846 write_bitmap_index =0;28472848if(progress && all_progress_implied)2849 progress =2;28502851prepare_packed_git();2852if(ignore_packed_keep) {2853struct packed_git *p;2854for(p = packed_git; p; p = p->next)2855if(p->pack_local && p->pack_keep)2856break;2857if(!p)/* no keep-able packs found */2858 ignore_packed_keep =0;2859}2860if(local) {2861/*2862 * unlike ignore_packed_keep above, we do not want to2863 * unset "local" based on looking at packs, as it2864 * also covers non-local objects2865 */2866struct packed_git *p;2867for(p = packed_git; p; p = p->next) {2868if(!p->pack_local) {2869 have_non_local_packs =1;2870break;2871}2872}2873}28742875if(progress)2876 progress_state =start_progress(_("Counting objects"),0);2877if(!use_internal_rev_list)2878read_object_list_from_stdin();2879else{2880get_object_list(rp.argc, rp.argv);2881argv_array_clear(&rp);2882}2883cleanup_preferred_base();2884if(include_tag && nr_result)2885for_each_ref(add_ref_tag, NULL);2886stop_progress(&progress_state);28872888if(non_empty && !nr_result)2889return0;2890if(nr_result)2891prepare_pack(window, depth);2892write_pack_file();2893if(progress)2894fprintf(stderr,"Total %"PRIu32" (delta %"PRIu32"),"2895" reused %"PRIu32" (delta %"PRIu32")\n",2896 written, written_delta, reused, reused_delta);2897return0;2898}