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 =1; 71static int write_bitmap_index; 72static uint16_t write_bitmap_options; 73 74static unsigned long delta_cache_size =0; 75static unsigned long max_delta_cache_size =256*1024*1024; 76static unsigned long cache_max_small_delta_size =1000; 77 78static unsigned long window_memory_limit =0; 79 80/* 81 * stats 82 */ 83static uint32_t written, written_delta; 84static uint32_t reused, reused_delta; 85 86/* 87 * Indexed commits 88 */ 89static struct commit **indexed_commits; 90static unsigned int indexed_commits_nr; 91static unsigned int indexed_commits_alloc; 92 93static voidindex_commit_for_bitmap(struct commit *commit) 94{ 95if(indexed_commits_nr >= indexed_commits_alloc) { 96 indexed_commits_alloc = (indexed_commits_alloc +32) *2; 97REALLOC_ARRAY(indexed_commits, indexed_commits_alloc); 98} 99 100 indexed_commits[indexed_commits_nr++] = commit; 101} 102 103static void*get_delta(struct object_entry *entry) 104{ 105unsigned long size, base_size, delta_size; 106void*buf, *base_buf, *delta_buf; 107enum object_type type; 108 109 buf =read_sha1_file(entry->idx.sha1, &type, &size); 110if(!buf) 111die("unable to read%s",sha1_to_hex(entry->idx.sha1)); 112 base_buf =read_sha1_file(entry->delta->idx.sha1, &type, &base_size); 113if(!base_buf) 114die("unable to read%s",sha1_to_hex(entry->delta->idx.sha1)); 115 delta_buf =diff_delta(base_buf, base_size, 116 buf, size, &delta_size,0); 117if(!delta_buf || delta_size != entry->delta_size) 118die("delta size changed"); 119free(buf); 120free(base_buf); 121return delta_buf; 122} 123 124static unsigned longdo_compress(void**pptr,unsigned long size) 125{ 126 git_zstream stream; 127void*in, *out; 128unsigned long maxsize; 129 130git_deflate_init(&stream, pack_compression_level); 131 maxsize =git_deflate_bound(&stream, size); 132 133 in = *pptr; 134 out =xmalloc(maxsize); 135*pptr = out; 136 137 stream.next_in = in; 138 stream.avail_in = size; 139 stream.next_out = out; 140 stream.avail_out = maxsize; 141while(git_deflate(&stream, Z_FINISH) == Z_OK) 142;/* nothing */ 143git_deflate_end(&stream); 144 145free(in); 146return stream.total_out; 147} 148 149static unsigned longwrite_large_blob_data(struct git_istream *st,struct sha1file *f, 150const unsigned char*sha1) 151{ 152 git_zstream stream; 153unsigned char ibuf[1024*16]; 154unsigned char obuf[1024*16]; 155unsigned long olen =0; 156 157git_deflate_init(&stream, pack_compression_level); 158 159for(;;) { 160 ssize_t readlen; 161int zret = Z_OK; 162 readlen =read_istream(st, ibuf,sizeof(ibuf)); 163if(readlen == -1) 164die(_("unable to read%s"),sha1_to_hex(sha1)); 165 166 stream.next_in = ibuf; 167 stream.avail_in = readlen; 168while((stream.avail_in || readlen ==0) && 169(zret == Z_OK || zret == Z_BUF_ERROR)) { 170 stream.next_out = obuf; 171 stream.avail_out =sizeof(obuf); 172 zret =git_deflate(&stream, readlen ?0: Z_FINISH); 173sha1write(f, obuf, stream.next_out - obuf); 174 olen += stream.next_out - obuf; 175} 176if(stream.avail_in) 177die(_("deflate error (%d)"), zret); 178if(readlen ==0) { 179if(zret != Z_STREAM_END) 180die(_("deflate error (%d)"), zret); 181break; 182} 183} 184git_deflate_end(&stream); 185return olen; 186} 187 188/* 189 * we are going to reuse the existing object data as is. make 190 * sure it is not corrupt. 191 */ 192static intcheck_pack_inflate(struct packed_git *p, 193struct pack_window **w_curs, 194 off_t offset, 195 off_t len, 196unsigned long expect) 197{ 198 git_zstream stream; 199unsigned char fakebuf[4096], *in; 200int st; 201 202memset(&stream,0,sizeof(stream)); 203git_inflate_init(&stream); 204do{ 205 in =use_pack(p, w_curs, offset, &stream.avail_in); 206 stream.next_in = in; 207 stream.next_out = fakebuf; 208 stream.avail_out =sizeof(fakebuf); 209 st =git_inflate(&stream, Z_FINISH); 210 offset += stream.next_in - in; 211}while(st == Z_OK || st == Z_BUF_ERROR); 212git_inflate_end(&stream); 213return(st == Z_STREAM_END && 214 stream.total_out == expect && 215 stream.total_in == len) ?0: -1; 216} 217 218static voidcopy_pack_data(struct sha1file *f, 219struct packed_git *p, 220struct pack_window **w_curs, 221 off_t offset, 222 off_t len) 223{ 224unsigned char*in; 225unsigned long avail; 226 227while(len) { 228 in =use_pack(p, w_curs, offset, &avail); 229if(avail > len) 230 avail = (unsigned long)len; 231sha1write(f, in, avail); 232 offset += avail; 233 len -= avail; 234} 235} 236 237/* Return 0 if we will bust the pack-size limit */ 238static unsigned longwrite_no_reuse_object(struct sha1file *f,struct object_entry *entry, 239unsigned long limit,int usable_delta) 240{ 241unsigned long size, datalen; 242unsigned char header[10], dheader[10]; 243unsigned hdrlen; 244enum object_type type; 245void*buf; 246struct git_istream *st = NULL; 247 248if(!usable_delta) { 249if(entry->type == OBJ_BLOB && 250 entry->size > big_file_threshold && 251(st =open_istream(entry->idx.sha1, &type, &size, NULL)) != NULL) 252 buf = NULL; 253else{ 254 buf =read_sha1_file(entry->idx.sha1, &type, &size); 255if(!buf) 256die(_("unable to read%s"),sha1_to_hex(entry->idx.sha1)); 257} 258/* 259 * make sure no cached delta data remains from a 260 * previous attempt before a pack split occurred. 261 */ 262free(entry->delta_data); 263 entry->delta_data = NULL; 264 entry->z_delta_size =0; 265}else if(entry->delta_data) { 266 size = entry->delta_size; 267 buf = entry->delta_data; 268 entry->delta_data = NULL; 269 type = (allow_ofs_delta && entry->delta->idx.offset) ? 270 OBJ_OFS_DELTA : OBJ_REF_DELTA; 271}else{ 272 buf =get_delta(entry); 273 size = entry->delta_size; 274 type = (allow_ofs_delta && entry->delta->idx.offset) ? 275 OBJ_OFS_DELTA : OBJ_REF_DELTA; 276} 277 278if(st)/* large blob case, just assume we don't compress well */ 279 datalen = size; 280else if(entry->z_delta_size) 281 datalen = entry->z_delta_size; 282else 283 datalen =do_compress(&buf, size); 284 285/* 286 * The object header is a byte of 'type' followed by zero or 287 * more bytes of length. 288 */ 289 hdrlen =encode_in_pack_object_header(type, size, header); 290 291if(type == OBJ_OFS_DELTA) { 292/* 293 * Deltas with relative base contain an additional 294 * encoding of the relative offset for the delta 295 * base from this object's position in the pack. 296 */ 297 off_t ofs = entry->idx.offset - entry->delta->idx.offset; 298unsigned pos =sizeof(dheader) -1; 299 dheader[pos] = ofs &127; 300while(ofs >>=7) 301 dheader[--pos] =128| (--ofs &127); 302if(limit && hdrlen +sizeof(dheader) - pos + datalen +20>= limit) { 303if(st) 304close_istream(st); 305free(buf); 306return0; 307} 308sha1write(f, header, hdrlen); 309sha1write(f, dheader + pos,sizeof(dheader) - pos); 310 hdrlen +=sizeof(dheader) - pos; 311}else if(type == OBJ_REF_DELTA) { 312/* 313 * Deltas with a base reference contain 314 * an additional 20 bytes for the base sha1. 315 */ 316if(limit && hdrlen +20+ datalen +20>= limit) { 317if(st) 318close_istream(st); 319free(buf); 320return0; 321} 322sha1write(f, header, hdrlen); 323sha1write(f, entry->delta->idx.sha1,20); 324 hdrlen +=20; 325}else{ 326if(limit && hdrlen + datalen +20>= limit) { 327if(st) 328close_istream(st); 329free(buf); 330return0; 331} 332sha1write(f, header, hdrlen); 333} 334if(st) { 335 datalen =write_large_blob_data(st, f, entry->idx.sha1); 336close_istream(st); 337}else{ 338sha1write(f, buf, datalen); 339free(buf); 340} 341 342return hdrlen + datalen; 343} 344 345/* Return 0 if we will bust the pack-size limit */ 346static off_t write_reuse_object(struct sha1file *f,struct object_entry *entry, 347unsigned long limit,int usable_delta) 348{ 349struct packed_git *p = entry->in_pack; 350struct pack_window *w_curs = NULL; 351struct revindex_entry *revidx; 352 off_t offset; 353enum object_type type = entry->type; 354 off_t datalen; 355unsigned char header[10], dheader[10]; 356unsigned hdrlen; 357 358if(entry->delta) 359 type = (allow_ofs_delta && entry->delta->idx.offset) ? 360 OBJ_OFS_DELTA : OBJ_REF_DELTA; 361 hdrlen =encode_in_pack_object_header(type, entry->size, header); 362 363 offset = entry->in_pack_offset; 364 revidx =find_pack_revindex(p, offset); 365 datalen = revidx[1].offset - offset; 366if(!pack_to_stdout && p->index_version >1&& 367check_pack_crc(p, &w_curs, offset, datalen, revidx->nr)) { 368error("bad packed object CRC for%s",sha1_to_hex(entry->idx.sha1)); 369unuse_pack(&w_curs); 370returnwrite_no_reuse_object(f, entry, limit, usable_delta); 371} 372 373 offset += entry->in_pack_header_size; 374 datalen -= entry->in_pack_header_size; 375 376if(!pack_to_stdout && p->index_version ==1&& 377check_pack_inflate(p, &w_curs, offset, datalen, entry->size)) { 378error("corrupt packed object for%s",sha1_to_hex(entry->idx.sha1)); 379unuse_pack(&w_curs); 380returnwrite_no_reuse_object(f, entry, limit, usable_delta); 381} 382 383if(type == OBJ_OFS_DELTA) { 384 off_t ofs = entry->idx.offset - entry->delta->idx.offset; 385unsigned pos =sizeof(dheader) -1; 386 dheader[pos] = ofs &127; 387while(ofs >>=7) 388 dheader[--pos] =128| (--ofs &127); 389if(limit && hdrlen +sizeof(dheader) - pos + datalen +20>= limit) { 390unuse_pack(&w_curs); 391return0; 392} 393sha1write(f, header, hdrlen); 394sha1write(f, dheader + pos,sizeof(dheader) - pos); 395 hdrlen +=sizeof(dheader) - pos; 396 reused_delta++; 397}else if(type == OBJ_REF_DELTA) { 398if(limit && hdrlen +20+ datalen +20>= limit) { 399unuse_pack(&w_curs); 400return0; 401} 402sha1write(f, header, hdrlen); 403sha1write(f, entry->delta->idx.sha1,20); 404 hdrlen +=20; 405 reused_delta++; 406}else{ 407if(limit && hdrlen + datalen +20>= limit) { 408unuse_pack(&w_curs); 409return0; 410} 411sha1write(f, header, hdrlen); 412} 413copy_pack_data(f, p, &w_curs, offset, datalen); 414unuse_pack(&w_curs); 415 reused++; 416return hdrlen + datalen; 417} 418 419/* Return 0 if we will bust the pack-size limit */ 420static off_t write_object(struct sha1file *f, 421struct object_entry *entry, 422 off_t write_offset) 423{ 424unsigned long limit; 425 off_t 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{ 497 off_t 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 948/* 949 * Check whether we want the object in the pack (e.g., we do not want 950 * objects found in non-local stores if the "--local" option was used). 951 * 952 * As a side effect of this check, we will find the packed version of this 953 * object, if any. We therefore pass out the pack information to avoid having 954 * to look it up again later. 955 */ 956static intwant_object_in_pack(const unsigned char*sha1, 957int exclude, 958struct packed_git **found_pack, 959 off_t *found_offset) 960{ 961struct packed_git *p; 962 963if(!exclude && local &&has_loose_object_nonlocal(sha1)) 964return0; 965 966*found_pack = NULL; 967*found_offset =0; 968 969for(p = packed_git; p; p = p->next) { 970 off_t offset =find_pack_entry_one(sha1, p); 971if(offset) { 972if(!*found_pack) { 973if(!is_pack_valid(p)) 974continue; 975*found_offset = offset; 976*found_pack = p; 977} 978if(exclude) 979return1; 980if(incremental) 981return0; 982 983/* 984 * When asked to do --local (do not include an 985 * object that appears in a pack we borrow 986 * from elsewhere) or --honor-pack-keep (do not 987 * include an object that appears in a pack marked 988 * with .keep), we need to make sure no copy of this 989 * object come from in _any_ pack that causes us to 990 * omit it, and need to complete this loop. When 991 * neither option is in effect, we know the object 992 * we just found is going to be packed, so break 993 * out of the loop to return 1 now. 994 */ 995if(!ignore_packed_keep && 996(!local || !have_non_local_packs)) 997break; 998 999if(local && !p->pack_local)1000return0;1001if(ignore_packed_keep && p->pack_local && p->pack_keep)1002return0;1003}1004}10051006return1;1007}10081009static voidcreate_object_entry(const unsigned char*sha1,1010enum object_type type,1011uint32_t hash,1012int exclude,1013int no_try_delta,1014uint32_t index_pos,1015struct packed_git *found_pack,1016 off_t found_offset)1017{1018struct object_entry *entry;10191020 entry =packlist_alloc(&to_pack, sha1, index_pos);1021 entry->hash = hash;1022if(type)1023 entry->type = type;1024if(exclude)1025 entry->preferred_base =1;1026else1027 nr_result++;1028if(found_pack) {1029 entry->in_pack = found_pack;1030 entry->in_pack_offset = found_offset;1031}10321033 entry->no_try_delta = no_try_delta;1034}10351036static const char no_closure_warning[] =N_(1037"disabling bitmap writing, as some objects are not being packed"1038);10391040static intadd_object_entry(const unsigned char*sha1,enum object_type type,1041const char*name,int exclude)1042{1043struct packed_git *found_pack;1044 off_t found_offset;1045uint32_t index_pos;10461047if(have_duplicate_entry(sha1, exclude, &index_pos))1048return0;10491050if(!want_object_in_pack(sha1, exclude, &found_pack, &found_offset)) {1051/* The pack is missing an object, so it will not have closure */1052if(write_bitmap_index) {1053warning(_(no_closure_warning));1054 write_bitmap_index =0;1055}1056return0;1057}10581059create_object_entry(sha1, type,pack_name_hash(name),1060 exclude, name &&no_try_delta(name),1061 index_pos, found_pack, found_offset);10621063display_progress(progress_state, nr_result);1064return1;1065}10661067static intadd_object_entry_from_bitmap(const unsigned char*sha1,1068enum object_type type,1069int flags,uint32_t name_hash,1070struct packed_git *pack, off_t offset)1071{1072uint32_t index_pos;10731074if(have_duplicate_entry(sha1,0, &index_pos))1075return0;10761077create_object_entry(sha1, type, name_hash,0,0, index_pos, pack, offset);10781079display_progress(progress_state, nr_result);1080return1;1081}10821083struct pbase_tree_cache {1084unsigned char sha1[20];1085int ref;1086int temporary;1087void*tree_data;1088unsigned long tree_size;1089};10901091static struct pbase_tree_cache *(pbase_tree_cache[256]);1092static intpbase_tree_cache_ix(const unsigned char*sha1)1093{1094return sha1[0] %ARRAY_SIZE(pbase_tree_cache);1095}1096static intpbase_tree_cache_ix_incr(int ix)1097{1098return(ix+1) %ARRAY_SIZE(pbase_tree_cache);1099}11001101static struct pbase_tree {1102struct pbase_tree *next;1103/* This is a phony "cache" entry; we are not1104 * going to evict it or find it through _get()1105 * mechanism -- this is for the toplevel node that1106 * would almost always change with any commit.1107 */1108struct pbase_tree_cache pcache;1109} *pbase_tree;11101111static struct pbase_tree_cache *pbase_tree_get(const unsigned char*sha1)1112{1113struct pbase_tree_cache *ent, *nent;1114void*data;1115unsigned long size;1116enum object_type type;1117int neigh;1118int my_ix =pbase_tree_cache_ix(sha1);1119int available_ix = -1;11201121/* pbase-tree-cache acts as a limited hashtable.1122 * your object will be found at your index or within a few1123 * slots after that slot if it is cached.1124 */1125for(neigh =0; neigh <8; neigh++) {1126 ent = pbase_tree_cache[my_ix];1127if(ent && !hashcmp(ent->sha1, sha1)) {1128 ent->ref++;1129return ent;1130}1131else if(((available_ix <0) && (!ent || !ent->ref)) ||1132((0<= available_ix) &&1133(!ent && pbase_tree_cache[available_ix])))1134 available_ix = my_ix;1135if(!ent)1136break;1137 my_ix =pbase_tree_cache_ix_incr(my_ix);1138}11391140/* Did not find one. Either we got a bogus request or1141 * we need to read and perhaps cache.1142 */1143 data =read_sha1_file(sha1, &type, &size);1144if(!data)1145return NULL;1146if(type != OBJ_TREE) {1147free(data);1148return NULL;1149}11501151/* We need to either cache or return a throwaway copy */11521153if(available_ix <0)1154 ent = NULL;1155else{1156 ent = pbase_tree_cache[available_ix];1157 my_ix = available_ix;1158}11591160if(!ent) {1161 nent =xmalloc(sizeof(*nent));1162 nent->temporary = (available_ix <0);1163}1164else{1165/* evict and reuse */1166free(ent->tree_data);1167 nent = ent;1168}1169hashcpy(nent->sha1, sha1);1170 nent->tree_data = data;1171 nent->tree_size = size;1172 nent->ref =1;1173if(!nent->temporary)1174 pbase_tree_cache[my_ix] = nent;1175return nent;1176}11771178static voidpbase_tree_put(struct pbase_tree_cache *cache)1179{1180if(!cache->temporary) {1181 cache->ref--;1182return;1183}1184free(cache->tree_data);1185free(cache);1186}11871188static intname_cmp_len(const char*name)1189{1190int i;1191for(i =0; name[i] && name[i] !='\n'&& name[i] !='/'; i++)1192;1193return i;1194}11951196static voidadd_pbase_object(struct tree_desc *tree,1197const char*name,1198int cmplen,1199const char*fullname)1200{1201struct name_entry entry;1202int cmp;12031204while(tree_entry(tree,&entry)) {1205if(S_ISGITLINK(entry.mode))1206continue;1207 cmp =tree_entry_len(&entry) != cmplen ?1:1208memcmp(name, entry.path, cmplen);1209if(cmp >0)1210continue;1211if(cmp <0)1212return;1213if(name[cmplen] !='/') {1214add_object_entry(entry.oid->hash,1215object_type(entry.mode),1216 fullname,1);1217return;1218}1219if(S_ISDIR(entry.mode)) {1220struct tree_desc sub;1221struct pbase_tree_cache *tree;1222const char*down = name+cmplen+1;1223int downlen =name_cmp_len(down);12241225 tree =pbase_tree_get(entry.oid->hash);1226if(!tree)1227return;1228init_tree_desc(&sub, tree->tree_data, tree->tree_size);12291230add_pbase_object(&sub, down, downlen, fullname);1231pbase_tree_put(tree);1232}1233}1234}12351236static unsigned*done_pbase_paths;1237static int done_pbase_paths_num;1238static int done_pbase_paths_alloc;1239static intdone_pbase_path_pos(unsigned hash)1240{1241int lo =0;1242int hi = done_pbase_paths_num;1243while(lo < hi) {1244int mi = (hi + lo) /2;1245if(done_pbase_paths[mi] == hash)1246return mi;1247if(done_pbase_paths[mi] < hash)1248 hi = mi;1249else1250 lo = mi +1;1251}1252return-lo-1;1253}12541255static intcheck_pbase_path(unsigned hash)1256{1257int pos = (!done_pbase_paths) ? -1:done_pbase_path_pos(hash);1258if(0<= pos)1259return1;1260 pos = -pos -1;1261ALLOC_GROW(done_pbase_paths,1262 done_pbase_paths_num +1,1263 done_pbase_paths_alloc);1264 done_pbase_paths_num++;1265if(pos < done_pbase_paths_num)1266memmove(done_pbase_paths + pos +1,1267 done_pbase_paths + pos,1268(done_pbase_paths_num - pos -1) *sizeof(unsigned));1269 done_pbase_paths[pos] = hash;1270return0;1271}12721273static voidadd_preferred_base_object(const char*name)1274{1275struct pbase_tree *it;1276int cmplen;1277unsigned hash =pack_name_hash(name);12781279if(!num_preferred_base ||check_pbase_path(hash))1280return;12811282 cmplen =name_cmp_len(name);1283for(it = pbase_tree; it; it = it->next) {1284if(cmplen ==0) {1285add_object_entry(it->pcache.sha1, OBJ_TREE, NULL,1);1286}1287else{1288struct tree_desc tree;1289init_tree_desc(&tree, it->pcache.tree_data, it->pcache.tree_size);1290add_pbase_object(&tree, name, cmplen, name);1291}1292}1293}12941295static voidadd_preferred_base(unsigned char*sha1)1296{1297struct pbase_tree *it;1298void*data;1299unsigned long size;1300unsigned char tree_sha1[20];13011302if(window <= num_preferred_base++)1303return;13041305 data =read_object_with_reference(sha1, tree_type, &size, tree_sha1);1306if(!data)1307return;13081309for(it = pbase_tree; it; it = it->next) {1310if(!hashcmp(it->pcache.sha1, tree_sha1)) {1311free(data);1312return;1313}1314}13151316 it =xcalloc(1,sizeof(*it));1317 it->next = pbase_tree;1318 pbase_tree = it;13191320hashcpy(it->pcache.sha1, tree_sha1);1321 it->pcache.tree_data = data;1322 it->pcache.tree_size = size;1323}13241325static voidcleanup_preferred_base(void)1326{1327struct pbase_tree *it;1328unsigned i;13291330 it = pbase_tree;1331 pbase_tree = NULL;1332while(it) {1333struct pbase_tree *this= it;1334 it =this->next;1335free(this->pcache.tree_data);1336free(this);1337}13381339for(i =0; i <ARRAY_SIZE(pbase_tree_cache); i++) {1340if(!pbase_tree_cache[i])1341continue;1342free(pbase_tree_cache[i]->tree_data);1343free(pbase_tree_cache[i]);1344 pbase_tree_cache[i] = NULL;1345}13461347free(done_pbase_paths);1348 done_pbase_paths = NULL;1349 done_pbase_paths_num = done_pbase_paths_alloc =0;1350}13511352static voidcheck_object(struct object_entry *entry)1353{1354if(entry->in_pack) {1355struct packed_git *p = entry->in_pack;1356struct pack_window *w_curs = NULL;1357const unsigned char*base_ref = NULL;1358struct object_entry *base_entry;1359unsigned long used, used_0;1360unsigned long avail;1361 off_t ofs;1362unsigned char*buf, c;13631364 buf =use_pack(p, &w_curs, entry->in_pack_offset, &avail);13651366/*1367 * We want in_pack_type even if we do not reuse delta1368 * since non-delta representations could still be reused.1369 */1370 used =unpack_object_header_buffer(buf, avail,1371&entry->in_pack_type,1372&entry->size);1373if(used ==0)1374goto give_up;13751376/*1377 * Determine if this is a delta and if so whether we can1378 * reuse it or not. Otherwise let's find out as cheaply as1379 * possible what the actual type and size for this object is.1380 */1381switch(entry->in_pack_type) {1382default:1383/* Not a delta hence we've already got all we need. */1384 entry->type = entry->in_pack_type;1385 entry->in_pack_header_size = used;1386if(entry->type < OBJ_COMMIT || entry->type > OBJ_BLOB)1387goto give_up;1388unuse_pack(&w_curs);1389return;1390case OBJ_REF_DELTA:1391if(reuse_delta && !entry->preferred_base)1392 base_ref =use_pack(p, &w_curs,1393 entry->in_pack_offset + used, NULL);1394 entry->in_pack_header_size = used +20;1395break;1396case OBJ_OFS_DELTA:1397 buf =use_pack(p, &w_curs,1398 entry->in_pack_offset + used, NULL);1399 used_0 =0;1400 c = buf[used_0++];1401 ofs = c &127;1402while(c &128) {1403 ofs +=1;1404if(!ofs ||MSB(ofs,7)) {1405error("delta base offset overflow in pack for%s",1406sha1_to_hex(entry->idx.sha1));1407goto give_up;1408}1409 c = buf[used_0++];1410 ofs = (ofs <<7) + (c &127);1411}1412 ofs = entry->in_pack_offset - ofs;1413if(ofs <=0|| ofs >= entry->in_pack_offset) {1414error("delta base offset out of bound for%s",1415sha1_to_hex(entry->idx.sha1));1416goto give_up;1417}1418if(reuse_delta && !entry->preferred_base) {1419struct revindex_entry *revidx;1420 revidx =find_pack_revindex(p, ofs);1421if(!revidx)1422goto give_up;1423 base_ref =nth_packed_object_sha1(p, revidx->nr);1424}1425 entry->in_pack_header_size = used + used_0;1426break;1427}14281429if(base_ref && (base_entry =packlist_find(&to_pack, base_ref, NULL))) {1430/*1431 * If base_ref was set above that means we wish to1432 * reuse delta data, and we even found that base1433 * in the list of objects we want to pack. Goodie!1434 *1435 * Depth value does not matter - find_deltas() will1436 * never consider reused delta as the base object to1437 * deltify other objects against, in order to avoid1438 * circular deltas.1439 */1440 entry->type = entry->in_pack_type;1441 entry->delta = base_entry;1442 entry->delta_size = entry->size;1443 entry->delta_sibling = base_entry->delta_child;1444 base_entry->delta_child = entry;1445unuse_pack(&w_curs);1446return;1447}14481449if(entry->type) {1450/*1451 * This must be a delta and we already know what the1452 * final object type is. Let's extract the actual1453 * object size from the delta header.1454 */1455 entry->size =get_size_from_delta(p, &w_curs,1456 entry->in_pack_offset + entry->in_pack_header_size);1457if(entry->size ==0)1458goto give_up;1459unuse_pack(&w_curs);1460return;1461}14621463/*1464 * No choice but to fall back to the recursive delta walk1465 * with sha1_object_info() to find about the object type1466 * at this point...1467 */1468 give_up:1469unuse_pack(&w_curs);1470}14711472 entry->type =sha1_object_info(entry->idx.sha1, &entry->size);1473/*1474 * The error condition is checked in prepare_pack(). This is1475 * to permit a missing preferred base object to be ignored1476 * as a preferred base. Doing so can result in a larger1477 * pack file, but the transfer will still take place.1478 */1479}14801481static intpack_offset_sort(const void*_a,const void*_b)1482{1483const struct object_entry *a = *(struct object_entry **)_a;1484const struct object_entry *b = *(struct object_entry **)_b;14851486/* avoid filesystem trashing with loose objects */1487if(!a->in_pack && !b->in_pack)1488returnhashcmp(a->idx.sha1, b->idx.sha1);14891490if(a->in_pack < b->in_pack)1491return-1;1492if(a->in_pack > b->in_pack)1493return1;1494return a->in_pack_offset < b->in_pack_offset ? -1:1495(a->in_pack_offset > b->in_pack_offset);1496}14971498static voidget_object_details(void)1499{1500uint32_t i;1501struct object_entry **sorted_by_offset;15021503 sorted_by_offset =xcalloc(to_pack.nr_objects,sizeof(struct object_entry *));1504for(i =0; i < to_pack.nr_objects; i++)1505 sorted_by_offset[i] = to_pack.objects + i;1506qsort(sorted_by_offset, to_pack.nr_objects,sizeof(*sorted_by_offset), pack_offset_sort);15071508for(i =0; i < to_pack.nr_objects; i++) {1509struct object_entry *entry = sorted_by_offset[i];1510check_object(entry);1511if(big_file_threshold < entry->size)1512 entry->no_try_delta =1;1513}15141515free(sorted_by_offset);1516}15171518/*1519 * We search for deltas in a list sorted by type, by filename hash, and then1520 * by size, so that we see progressively smaller and smaller files.1521 * That's because we prefer deltas to be from the bigger file1522 * to the smaller -- deletes are potentially cheaper, but perhaps1523 * more importantly, the bigger file is likely the more recent1524 * one. The deepest deltas are therefore the oldest objects which are1525 * less susceptible to be accessed often.1526 */1527static inttype_size_sort(const void*_a,const void*_b)1528{1529const struct object_entry *a = *(struct object_entry **)_a;1530const struct object_entry *b = *(struct object_entry **)_b;15311532if(a->type > b->type)1533return-1;1534if(a->type < b->type)1535return1;1536if(a->hash > b->hash)1537return-1;1538if(a->hash < b->hash)1539return1;1540if(a->preferred_base > b->preferred_base)1541return-1;1542if(a->preferred_base < b->preferred_base)1543return1;1544if(a->size > b->size)1545return-1;1546if(a->size < b->size)1547return1;1548return a < b ? -1: (a > b);/* newest first */1549}15501551struct unpacked {1552struct object_entry *entry;1553void*data;1554struct delta_index *index;1555unsigned depth;1556};15571558static intdelta_cacheable(unsigned long src_size,unsigned long trg_size,1559unsigned long delta_size)1560{1561if(max_delta_cache_size && delta_cache_size + delta_size > max_delta_cache_size)1562return0;15631564if(delta_size < cache_max_small_delta_size)1565return1;15661567/* cache delta, if objects are large enough compared to delta size */1568if((src_size >>20) + (trg_size >>21) > (delta_size >>10))1569return1;15701571return0;1572}15731574#ifndef NO_PTHREADS15751576static pthread_mutex_t read_mutex;1577#define read_lock() pthread_mutex_lock(&read_mutex)1578#define read_unlock() pthread_mutex_unlock(&read_mutex)15791580static pthread_mutex_t cache_mutex;1581#define cache_lock() pthread_mutex_lock(&cache_mutex)1582#define cache_unlock() pthread_mutex_unlock(&cache_mutex)15831584static pthread_mutex_t progress_mutex;1585#define progress_lock() pthread_mutex_lock(&progress_mutex)1586#define progress_unlock() pthread_mutex_unlock(&progress_mutex)15871588#else15891590#define read_lock() (void)01591#define read_unlock() (void)01592#define cache_lock() (void)01593#define cache_unlock() (void)01594#define progress_lock() (void)01595#define progress_unlock() (void)015961597#endif15981599static inttry_delta(struct unpacked *trg,struct unpacked *src,1600unsigned max_depth,unsigned long*mem_usage)1601{1602struct object_entry *trg_entry = trg->entry;1603struct object_entry *src_entry = src->entry;1604unsigned long trg_size, src_size, delta_size, sizediff, max_size, sz;1605unsigned ref_depth;1606enum object_type type;1607void*delta_buf;16081609/* Don't bother doing diffs between different types */1610if(trg_entry->type != src_entry->type)1611return-1;16121613/*1614 * We do not bother to try a delta that we discarded on an1615 * earlier try, but only when reusing delta data. Note that1616 * src_entry that is marked as the preferred_base should always1617 * be considered, as even if we produce a suboptimal delta against1618 * it, we will still save the transfer cost, as we already know1619 * the other side has it and we won't send src_entry at all.1620 */1621if(reuse_delta && trg_entry->in_pack &&1622 trg_entry->in_pack == src_entry->in_pack &&1623!src_entry->preferred_base &&1624 trg_entry->in_pack_type != OBJ_REF_DELTA &&1625 trg_entry->in_pack_type != OBJ_OFS_DELTA)1626return0;16271628/* Let's not bust the allowed depth. */1629if(src->depth >= max_depth)1630return0;16311632/* Now some size filtering heuristics. */1633 trg_size = trg_entry->size;1634if(!trg_entry->delta) {1635 max_size = trg_size/2-20;1636 ref_depth =1;1637}else{1638 max_size = trg_entry->delta_size;1639 ref_depth = trg->depth;1640}1641 max_size = (uint64_t)max_size * (max_depth - src->depth) /1642(max_depth - ref_depth +1);1643if(max_size ==0)1644return0;1645 src_size = src_entry->size;1646 sizediff = src_size < trg_size ? trg_size - src_size :0;1647if(sizediff >= max_size)1648return0;1649if(trg_size < src_size /32)1650return0;16511652/* Load data if not already done */1653if(!trg->data) {1654read_lock();1655 trg->data =read_sha1_file(trg_entry->idx.sha1, &type, &sz);1656read_unlock();1657if(!trg->data)1658die("object%scannot be read",1659sha1_to_hex(trg_entry->idx.sha1));1660if(sz != trg_size)1661die("object%sinconsistent object length (%lu vs%lu)",1662sha1_to_hex(trg_entry->idx.sha1), sz, trg_size);1663*mem_usage += sz;1664}1665if(!src->data) {1666read_lock();1667 src->data =read_sha1_file(src_entry->idx.sha1, &type, &sz);1668read_unlock();1669if(!src->data) {1670if(src_entry->preferred_base) {1671static int warned =0;1672if(!warned++)1673warning("object%scannot be read",1674sha1_to_hex(src_entry->idx.sha1));1675/*1676 * Those objects are not included in the1677 * resulting pack. Be resilient and ignore1678 * them if they can't be read, in case the1679 * pack could be created nevertheless.1680 */1681return0;1682}1683die("object%scannot be read",1684sha1_to_hex(src_entry->idx.sha1));1685}1686if(sz != src_size)1687die("object%sinconsistent object length (%lu vs%lu)",1688sha1_to_hex(src_entry->idx.sha1), sz, src_size);1689*mem_usage += sz;1690}1691if(!src->index) {1692 src->index =create_delta_index(src->data, src_size);1693if(!src->index) {1694static int warned =0;1695if(!warned++)1696warning("suboptimal pack - out of memory");1697return0;1698}1699*mem_usage +=sizeof_delta_index(src->index);1700}17011702 delta_buf =create_delta(src->index, trg->data, trg_size, &delta_size, max_size);1703if(!delta_buf)1704return0;17051706if(trg_entry->delta) {1707/* Prefer only shallower same-sized deltas. */1708if(delta_size == trg_entry->delta_size &&1709 src->depth +1>= trg->depth) {1710free(delta_buf);1711return0;1712}1713}17141715/*1716 * Handle memory allocation outside of the cache1717 * accounting lock. Compiler will optimize the strangeness1718 * away when NO_PTHREADS is defined.1719 */1720free(trg_entry->delta_data);1721cache_lock();1722if(trg_entry->delta_data) {1723 delta_cache_size -= trg_entry->delta_size;1724 trg_entry->delta_data = NULL;1725}1726if(delta_cacheable(src_size, trg_size, delta_size)) {1727 delta_cache_size += delta_size;1728cache_unlock();1729 trg_entry->delta_data =xrealloc(delta_buf, delta_size);1730}else{1731cache_unlock();1732free(delta_buf);1733}17341735 trg_entry->delta = src_entry;1736 trg_entry->delta_size = delta_size;1737 trg->depth = src->depth +1;17381739return1;1740}17411742static unsigned intcheck_delta_limit(struct object_entry *me,unsigned int n)1743{1744struct object_entry *child = me->delta_child;1745unsigned int m = n;1746while(child) {1747unsigned int c =check_delta_limit(child, n +1);1748if(m < c)1749 m = c;1750 child = child->delta_sibling;1751}1752return m;1753}17541755static unsigned longfree_unpacked(struct unpacked *n)1756{1757unsigned long freed_mem =sizeof_delta_index(n->index);1758free_delta_index(n->index);1759 n->index = NULL;1760if(n->data) {1761 freed_mem += n->entry->size;1762free(n->data);1763 n->data = NULL;1764}1765 n->entry = NULL;1766 n->depth =0;1767return freed_mem;1768}17691770static voidfind_deltas(struct object_entry **list,unsigned*list_size,1771int window,int depth,unsigned*processed)1772{1773uint32_t i, idx =0, count =0;1774struct unpacked *array;1775unsigned long mem_usage =0;17761777 array =xcalloc(window,sizeof(struct unpacked));17781779for(;;) {1780struct object_entry *entry;1781struct unpacked *n = array + idx;1782int j, max_depth, best_base = -1;17831784progress_lock();1785if(!*list_size) {1786progress_unlock();1787break;1788}1789 entry = *list++;1790(*list_size)--;1791if(!entry->preferred_base) {1792(*processed)++;1793display_progress(progress_state, *processed);1794}1795progress_unlock();17961797 mem_usage -=free_unpacked(n);1798 n->entry = entry;17991800while(window_memory_limit &&1801 mem_usage > window_memory_limit &&1802 count >1) {1803uint32_t tail = (idx + window - count) % window;1804 mem_usage -=free_unpacked(array + tail);1805 count--;1806}18071808/* We do not compute delta to *create* objects we are not1809 * going to pack.1810 */1811if(entry->preferred_base)1812goto next;18131814/*1815 * If the current object is at pack edge, take the depth the1816 * objects that depend on the current object into account1817 * otherwise they would become too deep.1818 */1819 max_depth = depth;1820if(entry->delta_child) {1821 max_depth -=check_delta_limit(entry,0);1822if(max_depth <=0)1823goto next;1824}18251826 j = window;1827while(--j >0) {1828int ret;1829uint32_t other_idx = idx + j;1830struct unpacked *m;1831if(other_idx >= window)1832 other_idx -= window;1833 m = array + other_idx;1834if(!m->entry)1835break;1836 ret =try_delta(n, m, max_depth, &mem_usage);1837if(ret <0)1838break;1839else if(ret >0)1840 best_base = other_idx;1841}18421843/*1844 * If we decided to cache the delta data, then it is best1845 * to compress it right away. First because we have to do1846 * it anyway, and doing it here while we're threaded will1847 * save a lot of time in the non threaded write phase,1848 * as well as allow for caching more deltas within1849 * the same cache size limit.1850 * ...1851 * But only if not writing to stdout, since in that case1852 * the network is most likely throttling writes anyway,1853 * and therefore it is best to go to the write phase ASAP1854 * instead, as we can afford spending more time compressing1855 * between writes at that moment.1856 */1857if(entry->delta_data && !pack_to_stdout) {1858 entry->z_delta_size =do_compress(&entry->delta_data,1859 entry->delta_size);1860cache_lock();1861 delta_cache_size -= entry->delta_size;1862 delta_cache_size += entry->z_delta_size;1863cache_unlock();1864}18651866/* if we made n a delta, and if n is already at max1867 * depth, leaving it in the window is pointless. we1868 * should evict it first.1869 */1870if(entry->delta && max_depth <= n->depth)1871continue;18721873/*1874 * Move the best delta base up in the window, after the1875 * currently deltified object, to keep it longer. It will1876 * be the first base object to be attempted next.1877 */1878if(entry->delta) {1879struct unpacked swap = array[best_base];1880int dist = (window + idx - best_base) % window;1881int dst = best_base;1882while(dist--) {1883int src = (dst +1) % window;1884 array[dst] = array[src];1885 dst = src;1886}1887 array[dst] = swap;1888}18891890 next:1891 idx++;1892if(count +1< window)1893 count++;1894if(idx >= window)1895 idx =0;1896}18971898for(i =0; i < window; ++i) {1899free_delta_index(array[i].index);1900free(array[i].data);1901}1902free(array);1903}19041905#ifndef NO_PTHREADS19061907static voidtry_to_free_from_threads(size_t size)1908{1909read_lock();1910release_pack_memory(size);1911read_unlock();1912}19131914static try_to_free_t old_try_to_free_routine;19151916/*1917 * The main thread waits on the condition that (at least) one of the workers1918 * has stopped working (which is indicated in the .working member of1919 * struct thread_params).1920 * When a work thread has completed its work, it sets .working to 0 and1921 * signals the main thread and waits on the condition that .data_ready1922 * becomes 1.1923 */19241925struct thread_params {1926 pthread_t thread;1927struct object_entry **list;1928unsigned list_size;1929unsigned remaining;1930int window;1931int depth;1932int working;1933int data_ready;1934 pthread_mutex_t mutex;1935 pthread_cond_t cond;1936unsigned*processed;1937};19381939static pthread_cond_t progress_cond;19401941/*1942 * Mutex and conditional variable can't be statically-initialized on Windows.1943 */1944static voidinit_threaded_search(void)1945{1946init_recursive_mutex(&read_mutex);1947pthread_mutex_init(&cache_mutex, NULL);1948pthread_mutex_init(&progress_mutex, NULL);1949pthread_cond_init(&progress_cond, NULL);1950 old_try_to_free_routine =set_try_to_free_routine(try_to_free_from_threads);1951}19521953static voidcleanup_threaded_search(void)1954{1955set_try_to_free_routine(old_try_to_free_routine);1956pthread_cond_destroy(&progress_cond);1957pthread_mutex_destroy(&read_mutex);1958pthread_mutex_destroy(&cache_mutex);1959pthread_mutex_destroy(&progress_mutex);1960}19611962static void*threaded_find_deltas(void*arg)1963{1964struct thread_params *me = arg;19651966while(me->remaining) {1967find_deltas(me->list, &me->remaining,1968 me->window, me->depth, me->processed);19691970progress_lock();1971 me->working =0;1972pthread_cond_signal(&progress_cond);1973progress_unlock();19741975/*1976 * We must not set ->data_ready before we wait on the1977 * condition because the main thread may have set it to 11978 * before we get here. In order to be sure that new1979 * work is available if we see 1 in ->data_ready, it1980 * was initialized to 0 before this thread was spawned1981 * and we reset it to 0 right away.1982 */1983pthread_mutex_lock(&me->mutex);1984while(!me->data_ready)1985pthread_cond_wait(&me->cond, &me->mutex);1986 me->data_ready =0;1987pthread_mutex_unlock(&me->mutex);1988}1989/* leave ->working 1 so that this doesn't get more work assigned */1990return NULL;1991}19921993static voidll_find_deltas(struct object_entry **list,unsigned list_size,1994int window,int depth,unsigned*processed)1995{1996struct thread_params *p;1997int i, ret, active_threads =0;19981999init_threaded_search();20002001if(delta_search_threads <=1) {2002find_deltas(list, &list_size, window, depth, processed);2003cleanup_threaded_search();2004return;2005}2006if(progress > pack_to_stdout)2007fprintf(stderr,"Delta compression using up to%dthreads.\n",2008 delta_search_threads);2009 p =xcalloc(delta_search_threads,sizeof(*p));20102011/* Partition the work amongst work threads. */2012for(i =0; i < delta_search_threads; i++) {2013unsigned sub_size = list_size / (delta_search_threads - i);20142015/* don't use too small segments or no deltas will be found */2016if(sub_size <2*window && i+1< delta_search_threads)2017 sub_size =0;20182019 p[i].window = window;2020 p[i].depth = depth;2021 p[i].processed = processed;2022 p[i].working =1;2023 p[i].data_ready =0;20242025/* try to split chunks on "path" boundaries */2026while(sub_size && sub_size < list_size &&2027 list[sub_size]->hash &&2028 list[sub_size]->hash == list[sub_size-1]->hash)2029 sub_size++;20302031 p[i].list = list;2032 p[i].list_size = sub_size;2033 p[i].remaining = sub_size;20342035 list += sub_size;2036 list_size -= sub_size;2037}20382039/* Start work threads. */2040for(i =0; i < delta_search_threads; i++) {2041if(!p[i].list_size)2042continue;2043pthread_mutex_init(&p[i].mutex, NULL);2044pthread_cond_init(&p[i].cond, NULL);2045 ret =pthread_create(&p[i].thread, NULL,2046 threaded_find_deltas, &p[i]);2047if(ret)2048die("unable to create thread:%s",strerror(ret));2049 active_threads++;2050}20512052/*2053 * Now let's wait for work completion. Each time a thread is done2054 * with its work, we steal half of the remaining work from the2055 * thread with the largest number of unprocessed objects and give2056 * it to that newly idle thread. This ensure good load balancing2057 * until the remaining object list segments are simply too short2058 * to be worth splitting anymore.2059 */2060while(active_threads) {2061struct thread_params *target = NULL;2062struct thread_params *victim = NULL;2063unsigned sub_size =0;20642065progress_lock();2066for(;;) {2067for(i =0; !target && i < delta_search_threads; i++)2068if(!p[i].working)2069 target = &p[i];2070if(target)2071break;2072pthread_cond_wait(&progress_cond, &progress_mutex);2073}20742075for(i =0; i < delta_search_threads; i++)2076if(p[i].remaining >2*window &&2077(!victim || victim->remaining < p[i].remaining))2078 victim = &p[i];2079if(victim) {2080 sub_size = victim->remaining /2;2081 list = victim->list + victim->list_size - sub_size;2082while(sub_size && list[0]->hash &&2083 list[0]->hash == list[-1]->hash) {2084 list++;2085 sub_size--;2086}2087if(!sub_size) {2088/*2089 * It is possible for some "paths" to have2090 * so many objects that no hash boundary2091 * might be found. Let's just steal the2092 * exact half in that case.2093 */2094 sub_size = victim->remaining /2;2095 list -= sub_size;2096}2097 target->list = list;2098 victim->list_size -= sub_size;2099 victim->remaining -= sub_size;2100}2101 target->list_size = sub_size;2102 target->remaining = sub_size;2103 target->working =1;2104progress_unlock();21052106pthread_mutex_lock(&target->mutex);2107 target->data_ready =1;2108pthread_cond_signal(&target->cond);2109pthread_mutex_unlock(&target->mutex);21102111if(!sub_size) {2112pthread_join(target->thread, NULL);2113pthread_cond_destroy(&target->cond);2114pthread_mutex_destroy(&target->mutex);2115 active_threads--;2116}2117}2118cleanup_threaded_search();2119free(p);2120}21212122#else2123#define ll_find_deltas(l, s, w, d, p) find_deltas(l, &s, w, d, p)2124#endif21252126static voidadd_tag_chain(const struct object_id *oid)2127{2128struct tag *tag;21292130/*2131 * We catch duplicates already in add_object_entry(), but we'd2132 * prefer to do this extra check to avoid having to parse the2133 * tag at all if we already know that it's being packed (e.g., if2134 * it was included via bitmaps, we would not have parsed it2135 * previously).2136 */2137if(packlist_find(&to_pack, oid->hash, NULL))2138return;21392140 tag =lookup_tag(oid->hash);2141while(1) {2142if(!tag ||parse_tag(tag) || !tag->tagged)2143die("unable to pack objects reachable from tag%s",2144oid_to_hex(oid));21452146add_object_entry(tag->object.oid.hash, OBJ_TAG, NULL,0);21472148if(tag->tagged->type != OBJ_TAG)2149return;21502151 tag = (struct tag *)tag->tagged;2152}2153}21542155static intadd_ref_tag(const char*path,const struct object_id *oid,int flag,void*cb_data)2156{2157struct object_id peeled;21582159if(starts_with(path,"refs/tags/") &&/* is a tag? */2160!peel_ref(path, peeled.hash) &&/* peelable? */2161packlist_find(&to_pack, peeled.hash, NULL))/* object packed? */2162add_tag_chain(oid);2163return0;2164}21652166static voidprepare_pack(int window,int depth)2167{2168struct object_entry **delta_list;2169uint32_t i, nr_deltas;2170unsigned n;21712172get_object_details();21732174/*2175 * If we're locally repacking then we need to be doubly careful2176 * from now on in order to make sure no stealth corruption gets2177 * propagated to the new pack. Clients receiving streamed packs2178 * should validate everything they get anyway so no need to incur2179 * the additional cost here in that case.2180 */2181if(!pack_to_stdout)2182 do_check_packed_object_crc =1;21832184if(!to_pack.nr_objects || !window || !depth)2185return;21862187ALLOC_ARRAY(delta_list, to_pack.nr_objects);2188 nr_deltas = n =0;21892190for(i =0; i < to_pack.nr_objects; i++) {2191struct object_entry *entry = to_pack.objects + i;21922193if(entry->delta)2194/* This happens if we decided to reuse existing2195 * delta from a pack. "reuse_delta &&" is implied.2196 */2197continue;21982199if(entry->size <50)2200continue;22012202if(entry->no_try_delta)2203continue;22042205if(!entry->preferred_base) {2206 nr_deltas++;2207if(entry->type <0)2208die("unable to get type of object%s",2209sha1_to_hex(entry->idx.sha1));2210}else{2211if(entry->type <0) {2212/*2213 * This object is not found, but we2214 * don't have to include it anyway.2215 */2216continue;2217}2218}22192220 delta_list[n++] = entry;2221}22222223if(nr_deltas && n >1) {2224unsigned nr_done =0;2225if(progress)2226 progress_state =start_progress(_("Compressing objects"),2227 nr_deltas);2228qsort(delta_list, n,sizeof(*delta_list), type_size_sort);2229ll_find_deltas(delta_list, n, window+1, depth, &nr_done);2230stop_progress(&progress_state);2231if(nr_done != nr_deltas)2232die("inconsistency with delta count");2233}2234free(delta_list);2235}22362237static intgit_pack_config(const char*k,const char*v,void*cb)2238{2239if(!strcmp(k,"pack.window")) {2240 window =git_config_int(k, v);2241return0;2242}2243if(!strcmp(k,"pack.windowmemory")) {2244 window_memory_limit =git_config_ulong(k, v);2245return0;2246}2247if(!strcmp(k,"pack.depth")) {2248 depth =git_config_int(k, v);2249return0;2250}2251if(!strcmp(k,"pack.compression")) {2252int level =git_config_int(k, v);2253if(level == -1)2254 level = Z_DEFAULT_COMPRESSION;2255else if(level <0|| level > Z_BEST_COMPRESSION)2256die("bad pack compression level%d", level);2257 pack_compression_level = level;2258 pack_compression_seen =1;2259return0;2260}2261if(!strcmp(k,"pack.deltacachesize")) {2262 max_delta_cache_size =git_config_int(k, v);2263return0;2264}2265if(!strcmp(k,"pack.deltacachelimit")) {2266 cache_max_small_delta_size =git_config_int(k, v);2267return0;2268}2269if(!strcmp(k,"pack.writebitmaphashcache")) {2270if(git_config_bool(k, v))2271 write_bitmap_options |= BITMAP_OPT_HASH_CACHE;2272else2273 write_bitmap_options &= ~BITMAP_OPT_HASH_CACHE;2274}2275if(!strcmp(k,"pack.usebitmaps")) {2276 use_bitmap_index =git_config_bool(k, v);2277return0;2278}2279if(!strcmp(k,"pack.threads")) {2280 delta_search_threads =git_config_int(k, v);2281if(delta_search_threads <0)2282die("invalid number of threads specified (%d)",2283 delta_search_threads);2284#ifdef NO_PTHREADS2285if(delta_search_threads !=1)2286warning("no threads support, ignoring%s", k);2287#endif2288return0;2289}2290if(!strcmp(k,"pack.indexversion")) {2291 pack_idx_opts.version =git_config_int(k, v);2292if(pack_idx_opts.version >2)2293die("bad pack.indexversion=%"PRIu32,2294 pack_idx_opts.version);2295return0;2296}2297returngit_default_config(k, v, cb);2298}22992300static voidread_object_list_from_stdin(void)2301{2302char line[40+1+ PATH_MAX +2];2303unsigned char sha1[20];23042305for(;;) {2306if(!fgets(line,sizeof(line), stdin)) {2307if(feof(stdin))2308break;2309if(!ferror(stdin))2310die("fgets returned NULL, not EOF, not error!");2311if(errno != EINTR)2312die_errno("fgets");2313clearerr(stdin);2314continue;2315}2316if(line[0] =='-') {2317if(get_sha1_hex(line+1, sha1))2318die("expected edge sha1, got garbage:\n%s",2319 line);2320add_preferred_base(sha1);2321continue;2322}2323if(get_sha1_hex(line, sha1))2324die("expected sha1, got garbage:\n%s", line);23252326add_preferred_base_object(line+41);2327add_object_entry(sha1,0, line+41,0);2328}2329}23302331#define OBJECT_ADDED (1u<<20)23322333static voidshow_commit(struct commit *commit,void*data)2334{2335add_object_entry(commit->object.oid.hash, OBJ_COMMIT, NULL,0);2336 commit->object.flags |= OBJECT_ADDED;23372338if(write_bitmap_index)2339index_commit_for_bitmap(commit);2340}23412342static voidshow_object(struct object *obj,const char*name,void*data)2343{2344add_preferred_base_object(name);2345add_object_entry(obj->oid.hash, obj->type, name,0);2346 obj->flags |= OBJECT_ADDED;2347}23482349static voidshow_edge(struct commit *commit)2350{2351add_preferred_base(commit->object.oid.hash);2352}23532354struct in_pack_object {2355 off_t offset;2356struct object *object;2357};23582359struct in_pack {2360int alloc;2361int nr;2362struct in_pack_object *array;2363};23642365static voidmark_in_pack_object(struct object *object,struct packed_git *p,struct in_pack *in_pack)2366{2367 in_pack->array[in_pack->nr].offset =find_pack_entry_one(object->oid.hash, p);2368 in_pack->array[in_pack->nr].object = object;2369 in_pack->nr++;2370}23712372/*2373 * Compare the objects in the offset order, in order to emulate the2374 * "git rev-list --objects" output that produced the pack originally.2375 */2376static intofscmp(const void*a_,const void*b_)2377{2378struct in_pack_object *a = (struct in_pack_object *)a_;2379struct in_pack_object *b = (struct in_pack_object *)b_;23802381if(a->offset < b->offset)2382return-1;2383else if(a->offset > b->offset)2384return1;2385else2386returnoidcmp(&a->object->oid, &b->object->oid);2387}23882389static voidadd_objects_in_unpacked_packs(struct rev_info *revs)2390{2391struct packed_git *p;2392struct in_pack in_pack;2393uint32_t i;23942395memset(&in_pack,0,sizeof(in_pack));23962397for(p = packed_git; p; p = p->next) {2398const unsigned char*sha1;2399struct object *o;24002401if(!p->pack_local || p->pack_keep)2402continue;2403if(open_pack_index(p))2404die("cannot open pack index");24052406ALLOC_GROW(in_pack.array,2407 in_pack.nr + p->num_objects,2408 in_pack.alloc);24092410for(i =0; i < p->num_objects; i++) {2411 sha1 =nth_packed_object_sha1(p, i);2412 o =lookup_unknown_object(sha1);2413if(!(o->flags & OBJECT_ADDED))2414mark_in_pack_object(o, p, &in_pack);2415 o->flags |= OBJECT_ADDED;2416}2417}24182419if(in_pack.nr) {2420qsort(in_pack.array, in_pack.nr,sizeof(in_pack.array[0]),2421 ofscmp);2422for(i =0; i < in_pack.nr; i++) {2423struct object *o = in_pack.array[i].object;2424add_object_entry(o->oid.hash, o->type,"",0);2425}2426}2427free(in_pack.array);2428}24292430static intadd_loose_object(const unsigned char*sha1,const char*path,2431void*data)2432{2433enum object_type type =sha1_object_info(sha1, NULL);24342435if(type <0) {2436warning("loose object at%scould not be examined", path);2437return0;2438}24392440add_object_entry(sha1, type,"",0);2441return0;2442}24432444/*2445 * We actually don't even have to worry about reachability here.2446 * add_object_entry will weed out duplicates, so we just add every2447 * loose object we find.2448 */2449static voidadd_unreachable_loose_objects(void)2450{2451for_each_loose_file_in_objdir(get_object_directory(),2452 add_loose_object,2453 NULL, NULL, NULL);2454}24552456static inthas_sha1_pack_kept_or_nonlocal(const unsigned char*sha1)2457{2458static struct packed_git *last_found = (void*)1;2459struct packed_git *p;24602461 p = (last_found != (void*)1) ? last_found : packed_git;24622463while(p) {2464if((!p->pack_local || p->pack_keep) &&2465find_pack_entry_one(sha1, p)) {2466 last_found = p;2467return1;2468}2469if(p == last_found)2470 p = packed_git;2471else2472 p = p->next;2473if(p == last_found)2474 p = p->next;2475}2476return0;2477}24782479/*2480 * Store a list of sha1s that are should not be discarded2481 * because they are either written too recently, or are2482 * reachable from another object that was.2483 *2484 * This is filled by get_object_list.2485 */2486static struct sha1_array recent_objects;24872488static intloosened_object_can_be_discarded(const unsigned char*sha1,2489unsigned long mtime)2490{2491if(!unpack_unreachable_expiration)2492return0;2493if(mtime > unpack_unreachable_expiration)2494return0;2495if(sha1_array_lookup(&recent_objects, sha1) >=0)2496return0;2497return1;2498}24992500static voidloosen_unused_packed_objects(struct rev_info *revs)2501{2502struct packed_git *p;2503uint32_t i;2504const unsigned char*sha1;25052506for(p = packed_git; p; p = p->next) {2507if(!p->pack_local || p->pack_keep)2508continue;25092510if(open_pack_index(p))2511die("cannot open pack index");25122513for(i =0; i < p->num_objects; i++) {2514 sha1 =nth_packed_object_sha1(p, i);2515if(!packlist_find(&to_pack, sha1, NULL) &&2516!has_sha1_pack_kept_or_nonlocal(sha1) &&2517!loosened_object_can_be_discarded(sha1, p->mtime))2518if(force_object_loose(sha1, p->mtime))2519die("unable to force loose object");2520}2521}2522}25232524/*2525 * This tracks any options which a reader of the pack might2526 * not understand, and which would therefore prevent blind reuse2527 * of what we have on disk.2528 */2529static intpack_options_allow_reuse(void)2530{2531return allow_ofs_delta;2532}25332534static intget_object_list_from_bitmap(struct rev_info *revs)2535{2536if(prepare_bitmap_walk(revs) <0)2537return-1;25382539if(pack_options_allow_reuse() &&2540!reuse_partial_packfile_from_bitmap(2541&reuse_packfile,2542&reuse_packfile_objects,2543&reuse_packfile_offset)) {2544assert(reuse_packfile_objects);2545 nr_result += reuse_packfile_objects;2546display_progress(progress_state, nr_result);2547}25482549traverse_bitmap_commit_list(&add_object_entry_from_bitmap);2550return0;2551}25522553static voidrecord_recent_object(struct object *obj,2554const char*name,2555void*data)2556{2557sha1_array_append(&recent_objects, obj->oid.hash);2558}25592560static voidrecord_recent_commit(struct commit *commit,void*data)2561{2562sha1_array_append(&recent_objects, commit->object.oid.hash);2563}25642565static voidget_object_list(int ac,const char**av)2566{2567struct rev_info revs;2568char line[1000];2569int flags =0;25702571init_revisions(&revs, NULL);2572 save_commit_buffer =0;2573setup_revisions(ac, av, &revs, NULL);25742575/* make sure shallows are read */2576is_repository_shallow();25772578while(fgets(line,sizeof(line), stdin) != NULL) {2579int len =strlen(line);2580if(len && line[len -1] =='\n')2581 line[--len] =0;2582if(!len)2583break;2584if(*line =='-') {2585if(!strcmp(line,"--not")) {2586 flags ^= UNINTERESTING;2587 write_bitmap_index =0;2588continue;2589}2590if(starts_with(line,"--shallow ")) {2591unsigned char sha1[20];2592if(get_sha1_hex(line +10, sha1))2593die("not an SHA-1 '%s'", line +10);2594register_shallow(sha1);2595 use_bitmap_index =0;2596continue;2597}2598die("not a rev '%s'", line);2599}2600if(handle_revision_arg(line, &revs, flags, REVARG_CANNOT_BE_FILENAME))2601die("bad revision '%s'", line);2602}26032604if(use_bitmap_index && !get_object_list_from_bitmap(&revs))2605return;26062607if(prepare_revision_walk(&revs))2608die("revision walk setup failed");2609mark_edges_uninteresting(&revs, show_edge);2610traverse_commit_list(&revs, show_commit, show_object, NULL);26112612if(unpack_unreachable_expiration) {2613 revs.ignore_missing_links =1;2614if(add_unseen_recent_objects_to_traversal(&revs,2615 unpack_unreachable_expiration))2616die("unable to add recent objects");2617if(prepare_revision_walk(&revs))2618die("revision walk setup failed");2619traverse_commit_list(&revs, record_recent_commit,2620 record_recent_object, NULL);2621}26222623if(keep_unreachable)2624add_objects_in_unpacked_packs(&revs);2625if(pack_loose_unreachable)2626add_unreachable_loose_objects();2627if(unpack_unreachable)2628loosen_unused_packed_objects(&revs);26292630sha1_array_clear(&recent_objects);2631}26322633static intoption_parse_index_version(const struct option *opt,2634const char*arg,int unset)2635{2636char*c;2637const char*val = arg;2638 pack_idx_opts.version =strtoul(val, &c,10);2639if(pack_idx_opts.version >2)2640die(_("unsupported index version%s"), val);2641if(*c ==','&& c[1])2642 pack_idx_opts.off32_limit =strtoul(c+1, &c,0);2643if(*c || pack_idx_opts.off32_limit &0x80000000)2644die(_("bad index version '%s'"), val);2645return0;2646}26472648static intoption_parse_unpack_unreachable(const struct option *opt,2649const char*arg,int unset)2650{2651if(unset) {2652 unpack_unreachable =0;2653 unpack_unreachable_expiration =0;2654}2655else{2656 unpack_unreachable =1;2657if(arg)2658 unpack_unreachable_expiration =approxidate(arg);2659}2660return0;2661}26622663intcmd_pack_objects(int argc,const char**argv,const char*prefix)2664{2665int use_internal_rev_list =0;2666int thin =0;2667int shallow =0;2668int all_progress_implied =0;2669struct argv_array rp = ARGV_ARRAY_INIT;2670int rev_list_unpacked =0, rev_list_all =0, rev_list_reflog =0;2671int rev_list_index =0;2672struct option pack_objects_options[] = {2673OPT_SET_INT('q',"quiet", &progress,2674N_("do not show progress meter"),0),2675OPT_SET_INT(0,"progress", &progress,2676N_("show progress meter"),1),2677OPT_SET_INT(0,"all-progress", &progress,2678N_("show progress meter during object writing phase"),2),2679OPT_BOOL(0,"all-progress-implied",2680&all_progress_implied,2681N_("similar to --all-progress when progress meter is shown")),2682{ OPTION_CALLBACK,0,"index-version", NULL,N_("version[,offset]"),2683N_("write the pack index file in the specified idx format version"),26840, option_parse_index_version },2685OPT_MAGNITUDE(0,"max-pack-size", &pack_size_limit,2686N_("maximum size of each output pack file")),2687OPT_BOOL(0,"local", &local,2688N_("ignore borrowed objects from alternate object store")),2689OPT_BOOL(0,"incremental", &incremental,2690N_("ignore packed objects")),2691OPT_INTEGER(0,"window", &window,2692N_("limit pack window by objects")),2693OPT_MAGNITUDE(0,"window-memory", &window_memory_limit,2694N_("limit pack window by memory in addition to object limit")),2695OPT_INTEGER(0,"depth", &depth,2696N_("maximum length of delta chain allowed in the resulting pack")),2697OPT_BOOL(0,"reuse-delta", &reuse_delta,2698N_("reuse existing deltas")),2699OPT_BOOL(0,"reuse-object", &reuse_object,2700N_("reuse existing objects")),2701OPT_BOOL(0,"delta-base-offset", &allow_ofs_delta,2702N_("use OFS_DELTA objects")),2703OPT_INTEGER(0,"threads", &delta_search_threads,2704N_("use threads when searching for best delta matches")),2705OPT_BOOL(0,"non-empty", &non_empty,2706N_("do not create an empty pack output")),2707OPT_BOOL(0,"revs", &use_internal_rev_list,2708N_("read revision arguments from standard input")),2709{ OPTION_SET_INT,0,"unpacked", &rev_list_unpacked, NULL,2710N_("limit the objects to those that are not yet packed"),2711 PARSE_OPT_NOARG | PARSE_OPT_NONEG, NULL,1},2712{ OPTION_SET_INT,0,"all", &rev_list_all, NULL,2713N_("include objects reachable from any reference"),2714 PARSE_OPT_NOARG | PARSE_OPT_NONEG, NULL,1},2715{ OPTION_SET_INT,0,"reflog", &rev_list_reflog, NULL,2716N_("include objects referred by reflog entries"),2717 PARSE_OPT_NOARG | PARSE_OPT_NONEG, NULL,1},2718{ OPTION_SET_INT,0,"indexed-objects", &rev_list_index, NULL,2719N_("include objects referred to by the index"),2720 PARSE_OPT_NOARG | PARSE_OPT_NONEG, NULL,1},2721OPT_BOOL(0,"stdout", &pack_to_stdout,2722N_("output pack to stdout")),2723OPT_BOOL(0,"include-tag", &include_tag,2724N_("include tag objects that refer to objects to be packed")),2725OPT_BOOL(0,"keep-unreachable", &keep_unreachable,2726N_("keep unreachable objects")),2727OPT_BOOL(0,"pack-loose-unreachable", &pack_loose_unreachable,2728N_("pack loose unreachable objects")),2729{ OPTION_CALLBACK,0,"unpack-unreachable", NULL,N_("time"),2730N_("unpack unreachable objects newer than <time>"),2731 PARSE_OPT_OPTARG, option_parse_unpack_unreachable },2732OPT_BOOL(0,"thin", &thin,2733N_("create thin packs")),2734OPT_BOOL(0,"shallow", &shallow,2735N_("create packs suitable for shallow fetches")),2736OPT_BOOL(0,"honor-pack-keep", &ignore_packed_keep,2737N_("ignore packs that have companion .keep file")),2738OPT_INTEGER(0,"compression", &pack_compression_level,2739N_("pack compression level")),2740OPT_SET_INT(0,"keep-true-parents", &grafts_replace_parents,2741N_("do not hide commits by grafts"),0),2742OPT_BOOL(0,"use-bitmap-index", &use_bitmap_index,2743N_("use a bitmap index if available to speed up counting objects")),2744OPT_BOOL(0,"write-bitmap-index", &write_bitmap_index,2745N_("write a bitmap index together with the pack index")),2746OPT_END(),2747};27482749 check_replace_refs =0;27502751reset_pack_idx_option(&pack_idx_opts);2752git_config(git_pack_config, NULL);2753if(!pack_compression_seen && core_compression_seen)2754 pack_compression_level = core_compression_level;27552756 progress =isatty(2);2757 argc =parse_options(argc, argv, prefix, pack_objects_options,2758 pack_usage,0);27592760if(argc) {2761 base_name = argv[0];2762 argc--;2763}2764if(pack_to_stdout != !base_name || argc)2765usage_with_options(pack_usage, pack_objects_options);27662767argv_array_push(&rp,"pack-objects");2768if(thin) {2769 use_internal_rev_list =1;2770argv_array_push(&rp, shallow2771?"--objects-edge-aggressive"2772:"--objects-edge");2773}else2774argv_array_push(&rp,"--objects");27752776if(rev_list_all) {2777 use_internal_rev_list =1;2778argv_array_push(&rp,"--all");2779}2780if(rev_list_reflog) {2781 use_internal_rev_list =1;2782argv_array_push(&rp,"--reflog");2783}2784if(rev_list_index) {2785 use_internal_rev_list =1;2786argv_array_push(&rp,"--indexed-objects");2787}2788if(rev_list_unpacked) {2789 use_internal_rev_list =1;2790argv_array_push(&rp,"--unpacked");2791}27922793if(!reuse_object)2794 reuse_delta =0;2795if(pack_compression_level == -1)2796 pack_compression_level = Z_DEFAULT_COMPRESSION;2797else if(pack_compression_level <0|| pack_compression_level > Z_BEST_COMPRESSION)2798die("bad pack compression level%d", pack_compression_level);27992800if(!delta_search_threads)/* --threads=0 means autodetect */2801 delta_search_threads =online_cpus();28022803#ifdef NO_PTHREADS2804if(delta_search_threads !=1)2805warning("no threads support, ignoring --threads");2806#endif2807if(!pack_to_stdout && !pack_size_limit)2808 pack_size_limit = pack_size_limit_cfg;2809if(pack_to_stdout && pack_size_limit)2810die("--max-pack-size cannot be used to build a pack for transfer.");2811if(pack_size_limit && pack_size_limit <1024*1024) {2812warning("minimum pack size limit is 1 MiB");2813 pack_size_limit =1024*1024;2814}28152816if(!pack_to_stdout && thin)2817die("--thin cannot be used to build an indexable pack.");28182819if(keep_unreachable && unpack_unreachable)2820die("--keep-unreachable and --unpack-unreachable are incompatible.");2821if(!rev_list_all || !rev_list_reflog || !rev_list_index)2822 unpack_unreachable_expiration =0;28232824if(!use_internal_rev_list || !pack_to_stdout ||is_repository_shallow())2825 use_bitmap_index =0;28262827if(pack_to_stdout || !rev_list_all)2828 write_bitmap_index =0;28292830if(progress && all_progress_implied)2831 progress =2;28322833prepare_packed_git();2834if(ignore_packed_keep) {2835struct packed_git *p;2836for(p = packed_git; p; p = p->next)2837if(p->pack_local && p->pack_keep)2838break;2839if(!p)/* no keep-able packs found */2840 ignore_packed_keep =0;2841}2842if(local) {2843/*2844 * unlike ignore_packed_keep above, we do not want to2845 * unset "local" based on looking at packs, as it2846 * also covers non-local objects2847 */2848struct packed_git *p;2849for(p = packed_git; p; p = p->next) {2850if(!p->pack_local) {2851 have_non_local_packs =1;2852break;2853}2854}2855}28562857if(progress)2858 progress_state =start_progress(_("Counting objects"),0);2859if(!use_internal_rev_list)2860read_object_list_from_stdin();2861else{2862get_object_list(rp.argc, rp.argv);2863argv_array_clear(&rp);2864}2865cleanup_preferred_base();2866if(include_tag && nr_result)2867for_each_ref(add_ref_tag, NULL);2868stop_progress(&progress_state);28692870if(non_empty && !nr_result)2871return0;2872if(nr_result)2873prepare_pack(window, depth);2874write_pack_file();2875if(progress)2876fprintf(stderr,"Total %"PRIu32" (delta %"PRIu32"),"2877" reused %"PRIu32" (delta %"PRIu32")\n",2878 written, written_delta, reused, reused_delta);2879return0;2880}