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 unsigned longwrite_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; 354unsigned long 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 unsigned longwrite_object(struct sha1file *f, 421struct object_entry *entry, 422 off_t write_offset) 423{ 424unsigned long limit, len; 425int usable_delta, to_reuse; 426 427if(!pack_to_stdout) 428crc32_begin(f); 429 430/* apply size limit if limited packsize and not first object */ 431if(!pack_size_limit || !nr_written) 432 limit =0; 433else if(pack_size_limit <= write_offset) 434/* 435 * the earlier object did not fit the limit; avoid 436 * mistaking this with unlimited (i.e. limit = 0). 437 */ 438 limit =1; 439else 440 limit = pack_size_limit - write_offset; 441 442if(!entry->delta) 443 usable_delta =0;/* no delta */ 444else if(!pack_size_limit) 445 usable_delta =1;/* unlimited packfile */ 446else if(entry->delta->idx.offset == (off_t)-1) 447 usable_delta =0;/* base was written to another pack */ 448else if(entry->delta->idx.offset) 449 usable_delta =1;/* base already exists in this pack */ 450else 451 usable_delta =0;/* base could end up in another pack */ 452 453if(!reuse_object) 454 to_reuse =0;/* explicit */ 455else if(!entry->in_pack) 456 to_reuse =0;/* can't reuse what we don't have */ 457else if(entry->type == OBJ_REF_DELTA || entry->type == OBJ_OFS_DELTA) 458/* check_object() decided it for us ... */ 459 to_reuse = usable_delta; 460/* ... but pack split may override that */ 461else if(entry->type != entry->in_pack_type) 462 to_reuse =0;/* pack has delta which is unusable */ 463else if(entry->delta) 464 to_reuse =0;/* we want to pack afresh */ 465else 466 to_reuse =1;/* we have it in-pack undeltified, 467 * and we do not need to deltify it. 468 */ 469 470if(!to_reuse) 471 len =write_no_reuse_object(f, entry, limit, usable_delta); 472else 473 len =write_reuse_object(f, entry, limit, usable_delta); 474if(!len) 475return0; 476 477if(usable_delta) 478 written_delta++; 479 written++; 480if(!pack_to_stdout) 481 entry->idx.crc32 =crc32_end(f); 482return len; 483} 484 485enum write_one_status { 486 WRITE_ONE_SKIP = -1,/* already written */ 487 WRITE_ONE_BREAK =0,/* writing this will bust the limit; not written */ 488 WRITE_ONE_WRITTEN =1,/* normal */ 489 WRITE_ONE_RECURSIVE =2/* already scheduled to be written */ 490}; 491 492static enum write_one_status write_one(struct sha1file *f, 493struct object_entry *e, 494 off_t *offset) 495{ 496unsigned long size; 497int recursing; 498 499/* 500 * we set offset to 1 (which is an impossible value) to mark 501 * the fact that this object is involved in "write its base 502 * first before writing a deltified object" recursion. 503 */ 504 recursing = (e->idx.offset ==1); 505if(recursing) { 506warning("recursive delta detected for object%s", 507sha1_to_hex(e->idx.sha1)); 508return WRITE_ONE_RECURSIVE; 509}else if(e->idx.offset || e->preferred_base) { 510/* offset is non zero if object is written already. */ 511return WRITE_ONE_SKIP; 512} 513 514/* if we are deltified, write out base object first. */ 515if(e->delta) { 516 e->idx.offset =1;/* now recurse */ 517switch(write_one(f, e->delta, offset)) { 518case WRITE_ONE_RECURSIVE: 519/* we cannot depend on this one */ 520 e->delta = NULL; 521break; 522default: 523break; 524case WRITE_ONE_BREAK: 525 e->idx.offset = recursing; 526return WRITE_ONE_BREAK; 527} 528} 529 530 e->idx.offset = *offset; 531 size =write_object(f, e, *offset); 532if(!size) { 533 e->idx.offset = recursing; 534return WRITE_ONE_BREAK; 535} 536 written_list[nr_written++] = &e->idx; 537 538/* make sure off_t is sufficiently large not to wrap */ 539if(signed_add_overflows(*offset, size)) 540die("pack too large for current definition of off_t"); 541*offset += size; 542return WRITE_ONE_WRITTEN; 543} 544 545static intmark_tagged(const char*path,const struct object_id *oid,int flag, 546void*cb_data) 547{ 548unsigned char peeled[20]; 549struct object_entry *entry =packlist_find(&to_pack, oid->hash, NULL); 550 551if(entry) 552 entry->tagged =1; 553if(!peel_ref(path, peeled)) { 554 entry =packlist_find(&to_pack, peeled, NULL); 555if(entry) 556 entry->tagged =1; 557} 558return0; 559} 560 561staticinlinevoidadd_to_write_order(struct object_entry **wo, 562unsigned int*endp, 563struct object_entry *e) 564{ 565if(e->filled) 566return; 567 wo[(*endp)++] = e; 568 e->filled =1; 569} 570 571static voidadd_descendants_to_write_order(struct object_entry **wo, 572unsigned int*endp, 573struct object_entry *e) 574{ 575int add_to_order =1; 576while(e) { 577if(add_to_order) { 578struct object_entry *s; 579/* add this node... */ 580add_to_write_order(wo, endp, e); 581/* all its siblings... */ 582for(s = e->delta_sibling; s; s = s->delta_sibling) { 583add_to_write_order(wo, endp, s); 584} 585} 586/* drop down a level to add left subtree nodes if possible */ 587if(e->delta_child) { 588 add_to_order =1; 589 e = e->delta_child; 590}else{ 591 add_to_order =0; 592/* our sibling might have some children, it is next */ 593if(e->delta_sibling) { 594 e = e->delta_sibling; 595continue; 596} 597/* go back to our parent node */ 598 e = e->delta; 599while(e && !e->delta_sibling) { 600/* we're on the right side of a subtree, keep 601 * going up until we can go right again */ 602 e = e->delta; 603} 604if(!e) { 605/* done- we hit our original root node */ 606return; 607} 608/* pass it off to sibling at this level */ 609 e = e->delta_sibling; 610} 611}; 612} 613 614static voidadd_family_to_write_order(struct object_entry **wo, 615unsigned int*endp, 616struct object_entry *e) 617{ 618struct object_entry *root; 619 620for(root = e; root->delta; root = root->delta) 621;/* nothing */ 622add_descendants_to_write_order(wo, endp, root); 623} 624 625static struct object_entry **compute_write_order(void) 626{ 627unsigned int i, wo_end, last_untagged; 628 629struct object_entry **wo; 630struct object_entry *objects = to_pack.objects; 631 632for(i =0; i < to_pack.nr_objects; i++) { 633 objects[i].tagged =0; 634 objects[i].filled =0; 635 objects[i].delta_child = NULL; 636 objects[i].delta_sibling = NULL; 637} 638 639/* 640 * Fully connect delta_child/delta_sibling network. 641 * Make sure delta_sibling is sorted in the original 642 * recency order. 643 */ 644for(i = to_pack.nr_objects; i >0;) { 645struct object_entry *e = &objects[--i]; 646if(!e->delta) 647continue; 648/* Mark me as the first child */ 649 e->delta_sibling = e->delta->delta_child; 650 e->delta->delta_child = e; 651} 652 653/* 654 * Mark objects that are at the tip of tags. 655 */ 656for_each_tag_ref(mark_tagged, NULL); 657 658/* 659 * Give the objects in the original recency order until 660 * we see a tagged tip. 661 */ 662ALLOC_ARRAY(wo, to_pack.nr_objects); 663for(i = wo_end =0; i < to_pack.nr_objects; i++) { 664if(objects[i].tagged) 665break; 666add_to_write_order(wo, &wo_end, &objects[i]); 667} 668 last_untagged = i; 669 670/* 671 * Then fill all the tagged tips. 672 */ 673for(; i < to_pack.nr_objects; i++) { 674if(objects[i].tagged) 675add_to_write_order(wo, &wo_end, &objects[i]); 676} 677 678/* 679 * And then all remaining commits and tags. 680 */ 681for(i = last_untagged; i < to_pack.nr_objects; i++) { 682if(objects[i].type != OBJ_COMMIT && 683 objects[i].type != OBJ_TAG) 684continue; 685add_to_write_order(wo, &wo_end, &objects[i]); 686} 687 688/* 689 * And then all the trees. 690 */ 691for(i = last_untagged; i < to_pack.nr_objects; i++) { 692if(objects[i].type != OBJ_TREE) 693continue; 694add_to_write_order(wo, &wo_end, &objects[i]); 695} 696 697/* 698 * Finally all the rest in really tight order 699 */ 700for(i = last_untagged; i < to_pack.nr_objects; i++) { 701if(!objects[i].filled) 702add_family_to_write_order(wo, &wo_end, &objects[i]); 703} 704 705if(wo_end != to_pack.nr_objects) 706die("ordered%uobjects, expected %"PRIu32, wo_end, to_pack.nr_objects); 707 708return wo; 709} 710 711static off_t write_reused_pack(struct sha1file *f) 712{ 713unsigned char buffer[8192]; 714 off_t to_write, total; 715int fd; 716 717if(!is_pack_valid(reuse_packfile)) 718die("packfile is invalid:%s", reuse_packfile->pack_name); 719 720 fd =git_open_noatime(reuse_packfile->pack_name); 721if(fd <0) 722die_errno("unable to open packfile for reuse:%s", 723 reuse_packfile->pack_name); 724 725if(lseek(fd,sizeof(struct pack_header), SEEK_SET) == -1) 726die_errno("unable to seek in reused packfile"); 727 728if(reuse_packfile_offset <0) 729 reuse_packfile_offset = reuse_packfile->pack_size -20; 730 731 total = to_write = reuse_packfile_offset -sizeof(struct pack_header); 732 733while(to_write) { 734int read_pack =xread(fd, buffer,sizeof(buffer)); 735 736if(read_pack <=0) 737die_errno("unable to read from reused packfile"); 738 739if(read_pack > to_write) 740 read_pack = to_write; 741 742sha1write(f, buffer, read_pack); 743 to_write -= read_pack; 744 745/* 746 * We don't know the actual number of objects written, 747 * only how many bytes written, how many bytes total, and 748 * how many objects total. So we can fake it by pretending all 749 * objects we are writing are the same size. This gives us a 750 * smooth progress meter, and at the end it matches the true 751 * answer. 752 */ 753 written = reuse_packfile_objects * 754(((double)(total - to_write)) / total); 755display_progress(progress_state, written); 756} 757 758close(fd); 759 written = reuse_packfile_objects; 760display_progress(progress_state, written); 761return reuse_packfile_offset -sizeof(struct pack_header); 762} 763 764static const char no_split_warning[] =N_( 765"disabling bitmap writing, packs are split due to pack.packSizeLimit" 766); 767 768static voidwrite_pack_file(void) 769{ 770uint32_t i =0, j; 771struct sha1file *f; 772 off_t offset; 773uint32_t nr_remaining = nr_result; 774time_t last_mtime =0; 775struct object_entry **write_order; 776 777if(progress > pack_to_stdout) 778 progress_state =start_progress(_("Writing objects"), nr_result); 779ALLOC_ARRAY(written_list, to_pack.nr_objects); 780 write_order =compute_write_order(); 781 782do{ 783unsigned char sha1[20]; 784char*pack_tmp_name = NULL; 785 786if(pack_to_stdout) 787 f =sha1fd_throughput(1,"<stdout>", progress_state); 788else 789 f =create_tmp_packfile(&pack_tmp_name); 790 791 offset =write_pack_header(f, nr_remaining); 792 793if(reuse_packfile) { 794 off_t packfile_size; 795assert(pack_to_stdout); 796 797 packfile_size =write_reused_pack(f); 798 offset += packfile_size; 799} 800 801 nr_written =0; 802for(; i < to_pack.nr_objects; i++) { 803struct object_entry *e = write_order[i]; 804if(write_one(f, e, &offset) == WRITE_ONE_BREAK) 805break; 806display_progress(progress_state, written); 807} 808 809/* 810 * Did we write the wrong # entries in the header? 811 * If so, rewrite it like in fast-import 812 */ 813if(pack_to_stdout) { 814sha1close(f, sha1, CSUM_CLOSE); 815}else if(nr_written == nr_remaining) { 816sha1close(f, sha1, CSUM_FSYNC); 817}else{ 818int fd =sha1close(f, sha1,0); 819fixup_pack_header_footer(fd, sha1, pack_tmp_name, 820 nr_written, sha1, offset); 821close(fd); 822if(write_bitmap_index) { 823warning(_(no_split_warning)); 824 write_bitmap_index =0; 825} 826} 827 828if(!pack_to_stdout) { 829struct stat st; 830struct strbuf tmpname = STRBUF_INIT; 831 832/* 833 * Packs are runtime accessed in their mtime 834 * order since newer packs are more likely to contain 835 * younger objects. So if we are creating multiple 836 * packs then we should modify the mtime of later ones 837 * to preserve this property. 838 */ 839if(stat(pack_tmp_name, &st) <0) { 840warning_errno("failed to stat%s", pack_tmp_name); 841}else if(!last_mtime) { 842 last_mtime = st.st_mtime; 843}else{ 844struct utimbuf utb; 845 utb.actime = st.st_atime; 846 utb.modtime = --last_mtime; 847if(utime(pack_tmp_name, &utb) <0) 848warning_errno("failed utime() on%s", pack_tmp_name); 849} 850 851strbuf_addf(&tmpname,"%s-", base_name); 852 853if(write_bitmap_index) { 854bitmap_writer_set_checksum(sha1); 855bitmap_writer_build_type_index(written_list, nr_written); 856} 857 858finish_tmp_packfile(&tmpname, pack_tmp_name, 859 written_list, nr_written, 860&pack_idx_opts, sha1); 861 862if(write_bitmap_index) { 863strbuf_addf(&tmpname,"%s.bitmap",sha1_to_hex(sha1)); 864 865stop_progress(&progress_state); 866 867bitmap_writer_show_progress(progress); 868bitmap_writer_reuse_bitmaps(&to_pack); 869bitmap_writer_select_commits(indexed_commits, indexed_commits_nr, -1); 870bitmap_writer_build(&to_pack); 871bitmap_writer_finish(written_list, nr_written, 872 tmpname.buf, write_bitmap_options); 873 write_bitmap_index =0; 874} 875 876strbuf_release(&tmpname); 877free(pack_tmp_name); 878puts(sha1_to_hex(sha1)); 879} 880 881/* mark written objects as written to previous pack */ 882for(j =0; j < nr_written; j++) { 883 written_list[j]->offset = (off_t)-1; 884} 885 nr_remaining -= nr_written; 886}while(nr_remaining && i < to_pack.nr_objects); 887 888free(written_list); 889free(write_order); 890stop_progress(&progress_state); 891if(written != nr_result) 892die("wrote %"PRIu32" objects while expecting %"PRIu32, 893 written, nr_result); 894} 895 896static voidsetup_delta_attr_check(struct git_attr_check *check) 897{ 898static struct git_attr *attr_delta; 899 900if(!attr_delta) 901 attr_delta =git_attr("delta"); 902 903 check[0].attr = attr_delta; 904} 905 906static intno_try_delta(const char*path) 907{ 908struct git_attr_check check[1]; 909 910setup_delta_attr_check(check); 911if(git_check_attr(path,ARRAY_SIZE(check), check)) 912return0; 913if(ATTR_FALSE(check->value)) 914return1; 915return0; 916} 917 918/* 919 * When adding an object, check whether we have already added it 920 * to our packing list. If so, we can skip. However, if we are 921 * being asked to excludei t, but the previous mention was to include 922 * it, make sure to adjust its flags and tweak our numbers accordingly. 923 * 924 * As an optimization, we pass out the index position where we would have 925 * found the item, since that saves us from having to look it up again a 926 * few lines later when we want to add the new entry. 927 */ 928static inthave_duplicate_entry(const unsigned char*sha1, 929int exclude, 930uint32_t*index_pos) 931{ 932struct object_entry *entry; 933 934 entry =packlist_find(&to_pack, sha1, index_pos); 935if(!entry) 936return0; 937 938if(exclude) { 939if(!entry->preferred_base) 940 nr_result--; 941 entry->preferred_base =1; 942} 943 944return1; 945} 946 947static intwant_found_object(int exclude,struct packed_git *p) 948{ 949if(exclude) 950return1; 951if(incremental) 952return0; 953 954/* 955 * When asked to do --local (do not include an object that appears in a 956 * pack we borrow from elsewhere) or --honor-pack-keep (do not include 957 * an object that appears in a pack marked with .keep), finding a pack 958 * that matches the criteria is sufficient for us to decide to omit it. 959 * However, even if this pack does not satisfy the criteria, we need to 960 * make sure no copy of this object appears in _any_ pack that makes us 961 * to omit the object, so we need to check all the packs. 962 * 963 * We can however first check whether these options can possible matter; 964 * if they do not matter we know we want the object in generated pack. 965 * Otherwise, we signal "-1" at the end to tell the caller that we do 966 * not know either way, and it needs to check more packs. 967 */ 968if(!ignore_packed_keep && 969(!local || !have_non_local_packs)) 970return1; 971 972if(local && !p->pack_local) 973return0; 974if(ignore_packed_keep && p->pack_local && p->pack_keep) 975return0; 976 977/* we don't know yet; keep looking for more packs */ 978return-1; 979} 980 981/* 982 * Check whether we want the object in the pack (e.g., we do not want 983 * objects found in non-local stores if the "--local" option was used). 984 * 985 * If the caller already knows an existing pack it wants to take the object 986 * from, that is passed in *found_pack and *found_offset; otherwise this 987 * function finds if there is any pack that has the object and returns the pack 988 * and its offset in these variables. 989 */ 990static intwant_object_in_pack(const unsigned char*sha1, 991int exclude, 992struct packed_git **found_pack, 993 off_t *found_offset) 994{ 995struct packed_git *p; 996int want; 997 998if(!exclude && local &&has_loose_object_nonlocal(sha1)) 999return0;10001001/*1002 * If we already know the pack object lives in, start checks from that1003 * pack - in the usual case when neither --local was given nor .keep files1004 * are present we will determine the answer right now.1005 */1006if(*found_pack) {1007 want =want_found_object(exclude, *found_pack);1008if(want != -1)1009return want;1010}10111012for(p = packed_git; p; p = p->next) {1013 off_t offset;10141015if(p == *found_pack)1016 offset = *found_offset;1017else1018 offset =find_pack_entry_one(sha1, p);10191020if(offset) {1021if(!*found_pack) {1022if(!is_pack_valid(p))1023continue;1024*found_offset = offset;1025*found_pack = p;1026}1027 want =want_found_object(exclude, p);1028if(want != -1)1029return want;1030}1031}10321033return1;1034}10351036static voidcreate_object_entry(const unsigned char*sha1,1037enum object_type type,1038uint32_t hash,1039int exclude,1040int no_try_delta,1041uint32_t index_pos,1042struct packed_git *found_pack,1043 off_t found_offset)1044{1045struct object_entry *entry;10461047 entry =packlist_alloc(&to_pack, sha1, index_pos);1048 entry->hash = hash;1049if(type)1050 entry->type = type;1051if(exclude)1052 entry->preferred_base =1;1053else1054 nr_result++;1055if(found_pack) {1056 entry->in_pack = found_pack;1057 entry->in_pack_offset = found_offset;1058}10591060 entry->no_try_delta = no_try_delta;1061}10621063static const char no_closure_warning[] =N_(1064"disabling bitmap writing, as some objects are not being packed"1065);10661067static intadd_object_entry(const unsigned char*sha1,enum object_type type,1068const char*name,int exclude)1069{1070struct packed_git *found_pack = NULL;1071 off_t found_offset =0;1072uint32_t index_pos;10731074if(have_duplicate_entry(sha1, exclude, &index_pos))1075return0;10761077if(!want_object_in_pack(sha1, exclude, &found_pack, &found_offset)) {1078/* The pack is missing an object, so it will not have closure */1079if(write_bitmap_index) {1080warning(_(no_closure_warning));1081 write_bitmap_index =0;1082}1083return0;1084}10851086create_object_entry(sha1, type,pack_name_hash(name),1087 exclude, name &&no_try_delta(name),1088 index_pos, found_pack, found_offset);10891090display_progress(progress_state, nr_result);1091return1;1092}10931094static intadd_object_entry_from_bitmap(const unsigned char*sha1,1095enum object_type type,1096int flags,uint32_t name_hash,1097struct packed_git *pack, off_t offset)1098{1099uint32_t index_pos;11001101if(have_duplicate_entry(sha1,0, &index_pos))1102return0;11031104if(!want_object_in_pack(sha1,0, &pack, &offset))1105return0;11061107create_object_entry(sha1, type, name_hash,0,0, index_pos, pack, offset);11081109display_progress(progress_state, nr_result);1110return1;1111}11121113struct pbase_tree_cache {1114unsigned char sha1[20];1115int ref;1116int temporary;1117void*tree_data;1118unsigned long tree_size;1119};11201121static struct pbase_tree_cache *(pbase_tree_cache[256]);1122static intpbase_tree_cache_ix(const unsigned char*sha1)1123{1124return sha1[0] %ARRAY_SIZE(pbase_tree_cache);1125}1126static intpbase_tree_cache_ix_incr(int ix)1127{1128return(ix+1) %ARRAY_SIZE(pbase_tree_cache);1129}11301131static struct pbase_tree {1132struct pbase_tree *next;1133/* This is a phony "cache" entry; we are not1134 * going to evict it or find it through _get()1135 * mechanism -- this is for the toplevel node that1136 * would almost always change with any commit.1137 */1138struct pbase_tree_cache pcache;1139} *pbase_tree;11401141static struct pbase_tree_cache *pbase_tree_get(const unsigned char*sha1)1142{1143struct pbase_tree_cache *ent, *nent;1144void*data;1145unsigned long size;1146enum object_type type;1147int neigh;1148int my_ix =pbase_tree_cache_ix(sha1);1149int available_ix = -1;11501151/* pbase-tree-cache acts as a limited hashtable.1152 * your object will be found at your index or within a few1153 * slots after that slot if it is cached.1154 */1155for(neigh =0; neigh <8; neigh++) {1156 ent = pbase_tree_cache[my_ix];1157if(ent && !hashcmp(ent->sha1, sha1)) {1158 ent->ref++;1159return ent;1160}1161else if(((available_ix <0) && (!ent || !ent->ref)) ||1162((0<= available_ix) &&1163(!ent && pbase_tree_cache[available_ix])))1164 available_ix = my_ix;1165if(!ent)1166break;1167 my_ix =pbase_tree_cache_ix_incr(my_ix);1168}11691170/* Did not find one. Either we got a bogus request or1171 * we need to read and perhaps cache.1172 */1173 data =read_sha1_file(sha1, &type, &size);1174if(!data)1175return NULL;1176if(type != OBJ_TREE) {1177free(data);1178return NULL;1179}11801181/* We need to either cache or return a throwaway copy */11821183if(available_ix <0)1184 ent = NULL;1185else{1186 ent = pbase_tree_cache[available_ix];1187 my_ix = available_ix;1188}11891190if(!ent) {1191 nent =xmalloc(sizeof(*nent));1192 nent->temporary = (available_ix <0);1193}1194else{1195/* evict and reuse */1196free(ent->tree_data);1197 nent = ent;1198}1199hashcpy(nent->sha1, sha1);1200 nent->tree_data = data;1201 nent->tree_size = size;1202 nent->ref =1;1203if(!nent->temporary)1204 pbase_tree_cache[my_ix] = nent;1205return nent;1206}12071208static voidpbase_tree_put(struct pbase_tree_cache *cache)1209{1210if(!cache->temporary) {1211 cache->ref--;1212return;1213}1214free(cache->tree_data);1215free(cache);1216}12171218static intname_cmp_len(const char*name)1219{1220int i;1221for(i =0; name[i] && name[i] !='\n'&& name[i] !='/'; i++)1222;1223return i;1224}12251226static voidadd_pbase_object(struct tree_desc *tree,1227const char*name,1228int cmplen,1229const char*fullname)1230{1231struct name_entry entry;1232int cmp;12331234while(tree_entry(tree,&entry)) {1235if(S_ISGITLINK(entry.mode))1236continue;1237 cmp =tree_entry_len(&entry) != cmplen ?1:1238memcmp(name, entry.path, cmplen);1239if(cmp >0)1240continue;1241if(cmp <0)1242return;1243if(name[cmplen] !='/') {1244add_object_entry(entry.oid->hash,1245object_type(entry.mode),1246 fullname,1);1247return;1248}1249if(S_ISDIR(entry.mode)) {1250struct tree_desc sub;1251struct pbase_tree_cache *tree;1252const char*down = name+cmplen+1;1253int downlen =name_cmp_len(down);12541255 tree =pbase_tree_get(entry.oid->hash);1256if(!tree)1257return;1258init_tree_desc(&sub, tree->tree_data, tree->tree_size);12591260add_pbase_object(&sub, down, downlen, fullname);1261pbase_tree_put(tree);1262}1263}1264}12651266static unsigned*done_pbase_paths;1267static int done_pbase_paths_num;1268static int done_pbase_paths_alloc;1269static intdone_pbase_path_pos(unsigned hash)1270{1271int lo =0;1272int hi = done_pbase_paths_num;1273while(lo < hi) {1274int mi = (hi + lo) /2;1275if(done_pbase_paths[mi] == hash)1276return mi;1277if(done_pbase_paths[mi] < hash)1278 hi = mi;1279else1280 lo = mi +1;1281}1282return-lo-1;1283}12841285static intcheck_pbase_path(unsigned hash)1286{1287int pos = (!done_pbase_paths) ? -1:done_pbase_path_pos(hash);1288if(0<= pos)1289return1;1290 pos = -pos -1;1291ALLOC_GROW(done_pbase_paths,1292 done_pbase_paths_num +1,1293 done_pbase_paths_alloc);1294 done_pbase_paths_num++;1295if(pos < done_pbase_paths_num)1296memmove(done_pbase_paths + pos +1,1297 done_pbase_paths + pos,1298(done_pbase_paths_num - pos -1) *sizeof(unsigned));1299 done_pbase_paths[pos] = hash;1300return0;1301}13021303static voidadd_preferred_base_object(const char*name)1304{1305struct pbase_tree *it;1306int cmplen;1307unsigned hash =pack_name_hash(name);13081309if(!num_preferred_base ||check_pbase_path(hash))1310return;13111312 cmplen =name_cmp_len(name);1313for(it = pbase_tree; it; it = it->next) {1314if(cmplen ==0) {1315add_object_entry(it->pcache.sha1, OBJ_TREE, NULL,1);1316}1317else{1318struct tree_desc tree;1319init_tree_desc(&tree, it->pcache.tree_data, it->pcache.tree_size);1320add_pbase_object(&tree, name, cmplen, name);1321}1322}1323}13241325static voidadd_preferred_base(unsigned char*sha1)1326{1327struct pbase_tree *it;1328void*data;1329unsigned long size;1330unsigned char tree_sha1[20];13311332if(window <= num_preferred_base++)1333return;13341335 data =read_object_with_reference(sha1, tree_type, &size, tree_sha1);1336if(!data)1337return;13381339for(it = pbase_tree; it; it = it->next) {1340if(!hashcmp(it->pcache.sha1, tree_sha1)) {1341free(data);1342return;1343}1344}13451346 it =xcalloc(1,sizeof(*it));1347 it->next = pbase_tree;1348 pbase_tree = it;13491350hashcpy(it->pcache.sha1, tree_sha1);1351 it->pcache.tree_data = data;1352 it->pcache.tree_size = size;1353}13541355static voidcleanup_preferred_base(void)1356{1357struct pbase_tree *it;1358unsigned i;13591360 it = pbase_tree;1361 pbase_tree = NULL;1362while(it) {1363struct pbase_tree *this= it;1364 it =this->next;1365free(this->pcache.tree_data);1366free(this);1367}13681369for(i =0; i <ARRAY_SIZE(pbase_tree_cache); i++) {1370if(!pbase_tree_cache[i])1371continue;1372free(pbase_tree_cache[i]->tree_data);1373free(pbase_tree_cache[i]);1374 pbase_tree_cache[i] = NULL;1375}13761377free(done_pbase_paths);1378 done_pbase_paths = NULL;1379 done_pbase_paths_num = done_pbase_paths_alloc =0;1380}13811382static voidcheck_object(struct object_entry *entry)1383{1384if(entry->in_pack) {1385struct packed_git *p = entry->in_pack;1386struct pack_window *w_curs = NULL;1387const unsigned char*base_ref = NULL;1388struct object_entry *base_entry;1389unsigned long used, used_0;1390unsigned long avail;1391 off_t ofs;1392unsigned char*buf, c;13931394 buf =use_pack(p, &w_curs, entry->in_pack_offset, &avail);13951396/*1397 * We want in_pack_type even if we do not reuse delta1398 * since non-delta representations could still be reused.1399 */1400 used =unpack_object_header_buffer(buf, avail,1401&entry->in_pack_type,1402&entry->size);1403if(used ==0)1404goto give_up;14051406/*1407 * Determine if this is a delta and if so whether we can1408 * reuse it or not. Otherwise let's find out as cheaply as1409 * possible what the actual type and size for this object is.1410 */1411switch(entry->in_pack_type) {1412default:1413/* Not a delta hence we've already got all we need. */1414 entry->type = entry->in_pack_type;1415 entry->in_pack_header_size = used;1416if(entry->type < OBJ_COMMIT || entry->type > OBJ_BLOB)1417goto give_up;1418unuse_pack(&w_curs);1419return;1420case OBJ_REF_DELTA:1421if(reuse_delta && !entry->preferred_base)1422 base_ref =use_pack(p, &w_curs,1423 entry->in_pack_offset + used, NULL);1424 entry->in_pack_header_size = used +20;1425break;1426case OBJ_OFS_DELTA:1427 buf =use_pack(p, &w_curs,1428 entry->in_pack_offset + used, NULL);1429 used_0 =0;1430 c = buf[used_0++];1431 ofs = c &127;1432while(c &128) {1433 ofs +=1;1434if(!ofs ||MSB(ofs,7)) {1435error("delta base offset overflow in pack for%s",1436sha1_to_hex(entry->idx.sha1));1437goto give_up;1438}1439 c = buf[used_0++];1440 ofs = (ofs <<7) + (c &127);1441}1442 ofs = entry->in_pack_offset - ofs;1443if(ofs <=0|| ofs >= entry->in_pack_offset) {1444error("delta base offset out of bound for%s",1445sha1_to_hex(entry->idx.sha1));1446goto give_up;1447}1448if(reuse_delta && !entry->preferred_base) {1449struct revindex_entry *revidx;1450 revidx =find_pack_revindex(p, ofs);1451if(!revidx)1452goto give_up;1453 base_ref =nth_packed_object_sha1(p, revidx->nr);1454}1455 entry->in_pack_header_size = used + used_0;1456break;1457}14581459if(base_ref && (base_entry =packlist_find(&to_pack, base_ref, NULL))) {1460/*1461 * If base_ref was set above that means we wish to1462 * reuse delta data, and we even found that base1463 * in the list of objects we want to pack. Goodie!1464 *1465 * Depth value does not matter - find_deltas() will1466 * never consider reused delta as the base object to1467 * deltify other objects against, in order to avoid1468 * circular deltas.1469 */1470 entry->type = entry->in_pack_type;1471 entry->delta = base_entry;1472 entry->delta_size = entry->size;1473 entry->delta_sibling = base_entry->delta_child;1474 base_entry->delta_child = entry;1475unuse_pack(&w_curs);1476return;1477}14781479if(entry->type) {1480/*1481 * This must be a delta and we already know what the1482 * final object type is. Let's extract the actual1483 * object size from the delta header.1484 */1485 entry->size =get_size_from_delta(p, &w_curs,1486 entry->in_pack_offset + entry->in_pack_header_size);1487if(entry->size ==0)1488goto give_up;1489unuse_pack(&w_curs);1490return;1491}14921493/*1494 * No choice but to fall back to the recursive delta walk1495 * with sha1_object_info() to find about the object type1496 * at this point...1497 */1498 give_up:1499unuse_pack(&w_curs);1500}15011502 entry->type =sha1_object_info(entry->idx.sha1, &entry->size);1503/*1504 * The error condition is checked in prepare_pack(). This is1505 * to permit a missing preferred base object to be ignored1506 * as a preferred base. Doing so can result in a larger1507 * pack file, but the transfer will still take place.1508 */1509}15101511static intpack_offset_sort(const void*_a,const void*_b)1512{1513const struct object_entry *a = *(struct object_entry **)_a;1514const struct object_entry *b = *(struct object_entry **)_b;15151516/* avoid filesystem trashing with loose objects */1517if(!a->in_pack && !b->in_pack)1518returnhashcmp(a->idx.sha1, b->idx.sha1);15191520if(a->in_pack < b->in_pack)1521return-1;1522if(a->in_pack > b->in_pack)1523return1;1524return a->in_pack_offset < b->in_pack_offset ? -1:1525(a->in_pack_offset > b->in_pack_offset);1526}15271528static voidget_object_details(void)1529{1530uint32_t i;1531struct object_entry **sorted_by_offset;15321533 sorted_by_offset =xcalloc(to_pack.nr_objects,sizeof(struct object_entry *));1534for(i =0; i < to_pack.nr_objects; i++)1535 sorted_by_offset[i] = to_pack.objects + i;1536qsort(sorted_by_offset, to_pack.nr_objects,sizeof(*sorted_by_offset), pack_offset_sort);15371538for(i =0; i < to_pack.nr_objects; i++) {1539struct object_entry *entry = sorted_by_offset[i];1540check_object(entry);1541if(big_file_threshold < entry->size)1542 entry->no_try_delta =1;1543}15441545free(sorted_by_offset);1546}15471548/*1549 * We search for deltas in a list sorted by type, by filename hash, and then1550 * by size, so that we see progressively smaller and smaller files.1551 * That's because we prefer deltas to be from the bigger file1552 * to the smaller -- deletes are potentially cheaper, but perhaps1553 * more importantly, the bigger file is likely the more recent1554 * one. The deepest deltas are therefore the oldest objects which are1555 * less susceptible to be accessed often.1556 */1557static inttype_size_sort(const void*_a,const void*_b)1558{1559const struct object_entry *a = *(struct object_entry **)_a;1560const struct object_entry *b = *(struct object_entry **)_b;15611562if(a->type > b->type)1563return-1;1564if(a->type < b->type)1565return1;1566if(a->hash > b->hash)1567return-1;1568if(a->hash < b->hash)1569return1;1570if(a->preferred_base > b->preferred_base)1571return-1;1572if(a->preferred_base < b->preferred_base)1573return1;1574if(a->size > b->size)1575return-1;1576if(a->size < b->size)1577return1;1578return a < b ? -1: (a > b);/* newest first */1579}15801581struct unpacked {1582struct object_entry *entry;1583void*data;1584struct delta_index *index;1585unsigned depth;1586};15871588static intdelta_cacheable(unsigned long src_size,unsigned long trg_size,1589unsigned long delta_size)1590{1591if(max_delta_cache_size && delta_cache_size + delta_size > max_delta_cache_size)1592return0;15931594if(delta_size < cache_max_small_delta_size)1595return1;15961597/* cache delta, if objects are large enough compared to delta size */1598if((src_size >>20) + (trg_size >>21) > (delta_size >>10))1599return1;16001601return0;1602}16031604#ifndef NO_PTHREADS16051606static pthread_mutex_t read_mutex;1607#define read_lock() pthread_mutex_lock(&read_mutex)1608#define read_unlock() pthread_mutex_unlock(&read_mutex)16091610static pthread_mutex_t cache_mutex;1611#define cache_lock() pthread_mutex_lock(&cache_mutex)1612#define cache_unlock() pthread_mutex_unlock(&cache_mutex)16131614static pthread_mutex_t progress_mutex;1615#define progress_lock() pthread_mutex_lock(&progress_mutex)1616#define progress_unlock() pthread_mutex_unlock(&progress_mutex)16171618#else16191620#define read_lock() (void)01621#define read_unlock() (void)01622#define cache_lock() (void)01623#define cache_unlock() (void)01624#define progress_lock() (void)01625#define progress_unlock() (void)016261627#endif16281629static inttry_delta(struct unpacked *trg,struct unpacked *src,1630unsigned max_depth,unsigned long*mem_usage)1631{1632struct object_entry *trg_entry = trg->entry;1633struct object_entry *src_entry = src->entry;1634unsigned long trg_size, src_size, delta_size, sizediff, max_size, sz;1635unsigned ref_depth;1636enum object_type type;1637void*delta_buf;16381639/* Don't bother doing diffs between different types */1640if(trg_entry->type != src_entry->type)1641return-1;16421643/*1644 * We do not bother to try a delta that we discarded on an1645 * earlier try, but only when reusing delta data. Note that1646 * src_entry that is marked as the preferred_base should always1647 * be considered, as even if we produce a suboptimal delta against1648 * it, we will still save the transfer cost, as we already know1649 * the other side has it and we won't send src_entry at all.1650 */1651if(reuse_delta && trg_entry->in_pack &&1652 trg_entry->in_pack == src_entry->in_pack &&1653!src_entry->preferred_base &&1654 trg_entry->in_pack_type != OBJ_REF_DELTA &&1655 trg_entry->in_pack_type != OBJ_OFS_DELTA)1656return0;16571658/* Let's not bust the allowed depth. */1659if(src->depth >= max_depth)1660return0;16611662/* Now some size filtering heuristics. */1663 trg_size = trg_entry->size;1664if(!trg_entry->delta) {1665 max_size = trg_size/2-20;1666 ref_depth =1;1667}else{1668 max_size = trg_entry->delta_size;1669 ref_depth = trg->depth;1670}1671 max_size = (uint64_t)max_size * (max_depth - src->depth) /1672(max_depth - ref_depth +1);1673if(max_size ==0)1674return0;1675 src_size = src_entry->size;1676 sizediff = src_size < trg_size ? trg_size - src_size :0;1677if(sizediff >= max_size)1678return0;1679if(trg_size < src_size /32)1680return0;16811682/* Load data if not already done */1683if(!trg->data) {1684read_lock();1685 trg->data =read_sha1_file(trg_entry->idx.sha1, &type, &sz);1686read_unlock();1687if(!trg->data)1688die("object%scannot be read",1689sha1_to_hex(trg_entry->idx.sha1));1690if(sz != trg_size)1691die("object%sinconsistent object length (%lu vs%lu)",1692sha1_to_hex(trg_entry->idx.sha1), sz, trg_size);1693*mem_usage += sz;1694}1695if(!src->data) {1696read_lock();1697 src->data =read_sha1_file(src_entry->idx.sha1, &type, &sz);1698read_unlock();1699if(!src->data) {1700if(src_entry->preferred_base) {1701static int warned =0;1702if(!warned++)1703warning("object%scannot be read",1704sha1_to_hex(src_entry->idx.sha1));1705/*1706 * Those objects are not included in the1707 * resulting pack. Be resilient and ignore1708 * them if they can't be read, in case the1709 * pack could be created nevertheless.1710 */1711return0;1712}1713die("object%scannot be read",1714sha1_to_hex(src_entry->idx.sha1));1715}1716if(sz != src_size)1717die("object%sinconsistent object length (%lu vs%lu)",1718sha1_to_hex(src_entry->idx.sha1), sz, src_size);1719*mem_usage += sz;1720}1721if(!src->index) {1722 src->index =create_delta_index(src->data, src_size);1723if(!src->index) {1724static int warned =0;1725if(!warned++)1726warning("suboptimal pack - out of memory");1727return0;1728}1729*mem_usage +=sizeof_delta_index(src->index);1730}17311732 delta_buf =create_delta(src->index, trg->data, trg_size, &delta_size, max_size);1733if(!delta_buf)1734return0;17351736if(trg_entry->delta) {1737/* Prefer only shallower same-sized deltas. */1738if(delta_size == trg_entry->delta_size &&1739 src->depth +1>= trg->depth) {1740free(delta_buf);1741return0;1742}1743}17441745/*1746 * Handle memory allocation outside of the cache1747 * accounting lock. Compiler will optimize the strangeness1748 * away when NO_PTHREADS is defined.1749 */1750free(trg_entry->delta_data);1751cache_lock();1752if(trg_entry->delta_data) {1753 delta_cache_size -= trg_entry->delta_size;1754 trg_entry->delta_data = NULL;1755}1756if(delta_cacheable(src_size, trg_size, delta_size)) {1757 delta_cache_size += delta_size;1758cache_unlock();1759 trg_entry->delta_data =xrealloc(delta_buf, delta_size);1760}else{1761cache_unlock();1762free(delta_buf);1763}17641765 trg_entry->delta = src_entry;1766 trg_entry->delta_size = delta_size;1767 trg->depth = src->depth +1;17681769return1;1770}17711772static unsigned intcheck_delta_limit(struct object_entry *me,unsigned int n)1773{1774struct object_entry *child = me->delta_child;1775unsigned int m = n;1776while(child) {1777unsigned int c =check_delta_limit(child, n +1);1778if(m < c)1779 m = c;1780 child = child->delta_sibling;1781}1782return m;1783}17841785static unsigned longfree_unpacked(struct unpacked *n)1786{1787unsigned long freed_mem =sizeof_delta_index(n->index);1788free_delta_index(n->index);1789 n->index = NULL;1790if(n->data) {1791 freed_mem += n->entry->size;1792free(n->data);1793 n->data = NULL;1794}1795 n->entry = NULL;1796 n->depth =0;1797return freed_mem;1798}17991800static voidfind_deltas(struct object_entry **list,unsigned*list_size,1801int window,int depth,unsigned*processed)1802{1803uint32_t i, idx =0, count =0;1804struct unpacked *array;1805unsigned long mem_usage =0;18061807 array =xcalloc(window,sizeof(struct unpacked));18081809for(;;) {1810struct object_entry *entry;1811struct unpacked *n = array + idx;1812int j, max_depth, best_base = -1;18131814progress_lock();1815if(!*list_size) {1816progress_unlock();1817break;1818}1819 entry = *list++;1820(*list_size)--;1821if(!entry->preferred_base) {1822(*processed)++;1823display_progress(progress_state, *processed);1824}1825progress_unlock();18261827 mem_usage -=free_unpacked(n);1828 n->entry = entry;18291830while(window_memory_limit &&1831 mem_usage > window_memory_limit &&1832 count >1) {1833uint32_t tail = (idx + window - count) % window;1834 mem_usage -=free_unpacked(array + tail);1835 count--;1836}18371838/* We do not compute delta to *create* objects we are not1839 * going to pack.1840 */1841if(entry->preferred_base)1842goto next;18431844/*1845 * If the current object is at pack edge, take the depth the1846 * objects that depend on the current object into account1847 * otherwise they would become too deep.1848 */1849 max_depth = depth;1850if(entry->delta_child) {1851 max_depth -=check_delta_limit(entry,0);1852if(max_depth <=0)1853goto next;1854}18551856 j = window;1857while(--j >0) {1858int ret;1859uint32_t other_idx = idx + j;1860struct unpacked *m;1861if(other_idx >= window)1862 other_idx -= window;1863 m = array + other_idx;1864if(!m->entry)1865break;1866 ret =try_delta(n, m, max_depth, &mem_usage);1867if(ret <0)1868break;1869else if(ret >0)1870 best_base = other_idx;1871}18721873/*1874 * If we decided to cache the delta data, then it is best1875 * to compress it right away. First because we have to do1876 * it anyway, and doing it here while we're threaded will1877 * save a lot of time in the non threaded write phase,1878 * as well as allow for caching more deltas within1879 * the same cache size limit.1880 * ...1881 * But only if not writing to stdout, since in that case1882 * the network is most likely throttling writes anyway,1883 * and therefore it is best to go to the write phase ASAP1884 * instead, as we can afford spending more time compressing1885 * between writes at that moment.1886 */1887if(entry->delta_data && !pack_to_stdout) {1888 entry->z_delta_size =do_compress(&entry->delta_data,1889 entry->delta_size);1890cache_lock();1891 delta_cache_size -= entry->delta_size;1892 delta_cache_size += entry->z_delta_size;1893cache_unlock();1894}18951896/* if we made n a delta, and if n is already at max1897 * depth, leaving it in the window is pointless. we1898 * should evict it first.1899 */1900if(entry->delta && max_depth <= n->depth)1901continue;19021903/*1904 * Move the best delta base up in the window, after the1905 * currently deltified object, to keep it longer. It will1906 * be the first base object to be attempted next.1907 */1908if(entry->delta) {1909struct unpacked swap = array[best_base];1910int dist = (window + idx - best_base) % window;1911int dst = best_base;1912while(dist--) {1913int src = (dst +1) % window;1914 array[dst] = array[src];1915 dst = src;1916}1917 array[dst] = swap;1918}19191920 next:1921 idx++;1922if(count +1< window)1923 count++;1924if(idx >= window)1925 idx =0;1926}19271928for(i =0; i < window; ++i) {1929free_delta_index(array[i].index);1930free(array[i].data);1931}1932free(array);1933}19341935#ifndef NO_PTHREADS19361937static voidtry_to_free_from_threads(size_t size)1938{1939read_lock();1940release_pack_memory(size);1941read_unlock();1942}19431944static try_to_free_t old_try_to_free_routine;19451946/*1947 * The main thread waits on the condition that (at least) one of the workers1948 * has stopped working (which is indicated in the .working member of1949 * struct thread_params).1950 * When a work thread has completed its work, it sets .working to 0 and1951 * signals the main thread and waits on the condition that .data_ready1952 * becomes 1.1953 */19541955struct thread_params {1956 pthread_t thread;1957struct object_entry **list;1958unsigned list_size;1959unsigned remaining;1960int window;1961int depth;1962int working;1963int data_ready;1964 pthread_mutex_t mutex;1965 pthread_cond_t cond;1966unsigned*processed;1967};19681969static pthread_cond_t progress_cond;19701971/*1972 * Mutex and conditional variable can't be statically-initialized on Windows.1973 */1974static voidinit_threaded_search(void)1975{1976init_recursive_mutex(&read_mutex);1977pthread_mutex_init(&cache_mutex, NULL);1978pthread_mutex_init(&progress_mutex, NULL);1979pthread_cond_init(&progress_cond, NULL);1980 old_try_to_free_routine =set_try_to_free_routine(try_to_free_from_threads);1981}19821983static voidcleanup_threaded_search(void)1984{1985set_try_to_free_routine(old_try_to_free_routine);1986pthread_cond_destroy(&progress_cond);1987pthread_mutex_destroy(&read_mutex);1988pthread_mutex_destroy(&cache_mutex);1989pthread_mutex_destroy(&progress_mutex);1990}19911992static void*threaded_find_deltas(void*arg)1993{1994struct thread_params *me = arg;19951996while(me->remaining) {1997find_deltas(me->list, &me->remaining,1998 me->window, me->depth, me->processed);19992000progress_lock();2001 me->working =0;2002pthread_cond_signal(&progress_cond);2003progress_unlock();20042005/*2006 * We must not set ->data_ready before we wait on the2007 * condition because the main thread may have set it to 12008 * before we get here. In order to be sure that new2009 * work is available if we see 1 in ->data_ready, it2010 * was initialized to 0 before this thread was spawned2011 * and we reset it to 0 right away.2012 */2013pthread_mutex_lock(&me->mutex);2014while(!me->data_ready)2015pthread_cond_wait(&me->cond, &me->mutex);2016 me->data_ready =0;2017pthread_mutex_unlock(&me->mutex);2018}2019/* leave ->working 1 so that this doesn't get more work assigned */2020return NULL;2021}20222023static voidll_find_deltas(struct object_entry **list,unsigned list_size,2024int window,int depth,unsigned*processed)2025{2026struct thread_params *p;2027int i, ret, active_threads =0;20282029init_threaded_search();20302031if(delta_search_threads <=1) {2032find_deltas(list, &list_size, window, depth, processed);2033cleanup_threaded_search();2034return;2035}2036if(progress > pack_to_stdout)2037fprintf(stderr,"Delta compression using up to%dthreads.\n",2038 delta_search_threads);2039 p =xcalloc(delta_search_threads,sizeof(*p));20402041/* Partition the work amongst work threads. */2042for(i =0; i < delta_search_threads; i++) {2043unsigned sub_size = list_size / (delta_search_threads - i);20442045/* don't use too small segments or no deltas will be found */2046if(sub_size <2*window && i+1< delta_search_threads)2047 sub_size =0;20482049 p[i].window = window;2050 p[i].depth = depth;2051 p[i].processed = processed;2052 p[i].working =1;2053 p[i].data_ready =0;20542055/* try to split chunks on "path" boundaries */2056while(sub_size && sub_size < list_size &&2057 list[sub_size]->hash &&2058 list[sub_size]->hash == list[sub_size-1]->hash)2059 sub_size++;20602061 p[i].list = list;2062 p[i].list_size = sub_size;2063 p[i].remaining = sub_size;20642065 list += sub_size;2066 list_size -= sub_size;2067}20682069/* Start work threads. */2070for(i =0; i < delta_search_threads; i++) {2071if(!p[i].list_size)2072continue;2073pthread_mutex_init(&p[i].mutex, NULL);2074pthread_cond_init(&p[i].cond, NULL);2075 ret =pthread_create(&p[i].thread, NULL,2076 threaded_find_deltas, &p[i]);2077if(ret)2078die("unable to create thread:%s",strerror(ret));2079 active_threads++;2080}20812082/*2083 * Now let's wait for work completion. Each time a thread is done2084 * with its work, we steal half of the remaining work from the2085 * thread with the largest number of unprocessed objects and give2086 * it to that newly idle thread. This ensure good load balancing2087 * until the remaining object list segments are simply too short2088 * to be worth splitting anymore.2089 */2090while(active_threads) {2091struct thread_params *target = NULL;2092struct thread_params *victim = NULL;2093unsigned sub_size =0;20942095progress_lock();2096for(;;) {2097for(i =0; !target && i < delta_search_threads; i++)2098if(!p[i].working)2099 target = &p[i];2100if(target)2101break;2102pthread_cond_wait(&progress_cond, &progress_mutex);2103}21042105for(i =0; i < delta_search_threads; i++)2106if(p[i].remaining >2*window &&2107(!victim || victim->remaining < p[i].remaining))2108 victim = &p[i];2109if(victim) {2110 sub_size = victim->remaining /2;2111 list = victim->list + victim->list_size - sub_size;2112while(sub_size && list[0]->hash &&2113 list[0]->hash == list[-1]->hash) {2114 list++;2115 sub_size--;2116}2117if(!sub_size) {2118/*2119 * It is possible for some "paths" to have2120 * so many objects that no hash boundary2121 * might be found. Let's just steal the2122 * exact half in that case.2123 */2124 sub_size = victim->remaining /2;2125 list -= sub_size;2126}2127 target->list = list;2128 victim->list_size -= sub_size;2129 victim->remaining -= sub_size;2130}2131 target->list_size = sub_size;2132 target->remaining = sub_size;2133 target->working =1;2134progress_unlock();21352136pthread_mutex_lock(&target->mutex);2137 target->data_ready =1;2138pthread_cond_signal(&target->cond);2139pthread_mutex_unlock(&target->mutex);21402141if(!sub_size) {2142pthread_join(target->thread, NULL);2143pthread_cond_destroy(&target->cond);2144pthread_mutex_destroy(&target->mutex);2145 active_threads--;2146}2147}2148cleanup_threaded_search();2149free(p);2150}21512152#else2153#define ll_find_deltas(l, s, w, d, p) find_deltas(l, &s, w, d, p)2154#endif21552156static intadd_ref_tag(const char*path,const struct object_id *oid,int flag,void*cb_data)2157{2158struct object_id peeled;21592160if(starts_with(path,"refs/tags/") &&/* is a tag? */2161!peel_ref(path, peeled.hash) &&/* peelable? */2162packlist_find(&to_pack, peeled.hash, NULL))/* object packed? */2163add_object_entry(oid->hash, OBJ_TAG, NULL,0);2164return0;2165}21662167static voidprepare_pack(int window,int depth)2168{2169struct object_entry **delta_list;2170uint32_t i, nr_deltas;2171unsigned n;21722173get_object_details();21742175/*2176 * If we're locally repacking then we need to be doubly careful2177 * from now on in order to make sure no stealth corruption gets2178 * propagated to the new pack. Clients receiving streamed packs2179 * should validate everything they get anyway so no need to incur2180 * the additional cost here in that case.2181 */2182if(!pack_to_stdout)2183 do_check_packed_object_crc =1;21842185if(!to_pack.nr_objects || !window || !depth)2186return;21872188ALLOC_ARRAY(delta_list, to_pack.nr_objects);2189 nr_deltas = n =0;21902191for(i =0; i < to_pack.nr_objects; i++) {2192struct object_entry *entry = to_pack.objects + i;21932194if(entry->delta)2195/* This happens if we decided to reuse existing2196 * delta from a pack. "reuse_delta &&" is implied.2197 */2198continue;21992200if(entry->size <50)2201continue;22022203if(entry->no_try_delta)2204continue;22052206if(!entry->preferred_base) {2207 nr_deltas++;2208if(entry->type <0)2209die("unable to get type of object%s",2210sha1_to_hex(entry->idx.sha1));2211}else{2212if(entry->type <0) {2213/*2214 * This object is not found, but we2215 * don't have to include it anyway.2216 */2217continue;2218}2219}22202221 delta_list[n++] = entry;2222}22232224if(nr_deltas && n >1) {2225unsigned nr_done =0;2226if(progress)2227 progress_state =start_progress(_("Compressing objects"),2228 nr_deltas);2229qsort(delta_list, n,sizeof(*delta_list), type_size_sort);2230ll_find_deltas(delta_list, n, window+1, depth, &nr_done);2231stop_progress(&progress_state);2232if(nr_done != nr_deltas)2233die("inconsistency with delta count");2234}2235free(delta_list);2236}22372238static intgit_pack_config(const char*k,const char*v,void*cb)2239{2240if(!strcmp(k,"pack.window")) {2241 window =git_config_int(k, v);2242return0;2243}2244if(!strcmp(k,"pack.windowmemory")) {2245 window_memory_limit =git_config_ulong(k, v);2246return0;2247}2248if(!strcmp(k,"pack.depth")) {2249 depth =git_config_int(k, v);2250return0;2251}2252if(!strcmp(k,"pack.compression")) {2253int level =git_config_int(k, v);2254if(level == -1)2255 level = Z_DEFAULT_COMPRESSION;2256else if(level <0|| level > Z_BEST_COMPRESSION)2257die("bad pack compression level%d", level);2258 pack_compression_level = level;2259 pack_compression_seen =1;2260return0;2261}2262if(!strcmp(k,"pack.deltacachesize")) {2263 max_delta_cache_size =git_config_int(k, v);2264return0;2265}2266if(!strcmp(k,"pack.deltacachelimit")) {2267 cache_max_small_delta_size =git_config_int(k, v);2268return0;2269}2270if(!strcmp(k,"pack.writebitmaphashcache")) {2271if(git_config_bool(k, v))2272 write_bitmap_options |= BITMAP_OPT_HASH_CACHE;2273else2274 write_bitmap_options &= ~BITMAP_OPT_HASH_CACHE;2275}2276if(!strcmp(k,"pack.usebitmaps")) {2277 use_bitmap_index =git_config_bool(k, v);2278return0;2279}2280if(!strcmp(k,"pack.threads")) {2281 delta_search_threads =git_config_int(k, v);2282if(delta_search_threads <0)2283die("invalid number of threads specified (%d)",2284 delta_search_threads);2285#ifdef NO_PTHREADS2286if(delta_search_threads !=1)2287warning("no threads support, ignoring%s", k);2288#endif2289return0;2290}2291if(!strcmp(k,"pack.indexversion")) {2292 pack_idx_opts.version =git_config_int(k, v);2293if(pack_idx_opts.version >2)2294die("bad pack.indexversion=%"PRIu32,2295 pack_idx_opts.version);2296return0;2297}2298returngit_default_config(k, v, cb);2299}23002301static voidread_object_list_from_stdin(void)2302{2303char line[40+1+ PATH_MAX +2];2304unsigned char sha1[20];23052306for(;;) {2307if(!fgets(line,sizeof(line), stdin)) {2308if(feof(stdin))2309break;2310if(!ferror(stdin))2311die("fgets returned NULL, not EOF, not error!");2312if(errno != EINTR)2313die_errno("fgets");2314clearerr(stdin);2315continue;2316}2317if(line[0] =='-') {2318if(get_sha1_hex(line+1, sha1))2319die("expected edge sha1, got garbage:\n%s",2320 line);2321add_preferred_base(sha1);2322continue;2323}2324if(get_sha1_hex(line, sha1))2325die("expected sha1, got garbage:\n%s", line);23262327add_preferred_base_object(line+41);2328add_object_entry(sha1,0, line+41,0);2329}2330}23312332#define OBJECT_ADDED (1u<<20)23332334static voidshow_commit(struct commit *commit,void*data)2335{2336add_object_entry(commit->object.oid.hash, OBJ_COMMIT, NULL,0);2337 commit->object.flags |= OBJECT_ADDED;23382339if(write_bitmap_index)2340index_commit_for_bitmap(commit);2341}23422343static voidshow_object(struct object *obj,const char*name,void*data)2344{2345add_preferred_base_object(name);2346add_object_entry(obj->oid.hash, obj->type, name,0);2347 obj->flags |= OBJECT_ADDED;2348}23492350static voidshow_edge(struct commit *commit)2351{2352add_preferred_base(commit->object.oid.hash);2353}23542355struct in_pack_object {2356 off_t offset;2357struct object *object;2358};23592360struct in_pack {2361int alloc;2362int nr;2363struct in_pack_object *array;2364};23652366static voidmark_in_pack_object(struct object *object,struct packed_git *p,struct in_pack *in_pack)2367{2368 in_pack->array[in_pack->nr].offset =find_pack_entry_one(object->oid.hash, p);2369 in_pack->array[in_pack->nr].object = object;2370 in_pack->nr++;2371}23722373/*2374 * Compare the objects in the offset order, in order to emulate the2375 * "git rev-list --objects" output that produced the pack originally.2376 */2377static intofscmp(const void*a_,const void*b_)2378{2379struct in_pack_object *a = (struct in_pack_object *)a_;2380struct in_pack_object *b = (struct in_pack_object *)b_;23812382if(a->offset < b->offset)2383return-1;2384else if(a->offset > b->offset)2385return1;2386else2387returnoidcmp(&a->object->oid, &b->object->oid);2388}23892390static voidadd_objects_in_unpacked_packs(struct rev_info *revs)2391{2392struct packed_git *p;2393struct in_pack in_pack;2394uint32_t i;23952396memset(&in_pack,0,sizeof(in_pack));23972398for(p = packed_git; p; p = p->next) {2399const unsigned char*sha1;2400struct object *o;24012402if(!p->pack_local || p->pack_keep)2403continue;2404if(open_pack_index(p))2405die("cannot open pack index");24062407ALLOC_GROW(in_pack.array,2408 in_pack.nr + p->num_objects,2409 in_pack.alloc);24102411for(i =0; i < p->num_objects; i++) {2412 sha1 =nth_packed_object_sha1(p, i);2413 o =lookup_unknown_object(sha1);2414if(!(o->flags & OBJECT_ADDED))2415mark_in_pack_object(o, p, &in_pack);2416 o->flags |= OBJECT_ADDED;2417}2418}24192420if(in_pack.nr) {2421qsort(in_pack.array, in_pack.nr,sizeof(in_pack.array[0]),2422 ofscmp);2423for(i =0; i < in_pack.nr; i++) {2424struct object *o = in_pack.array[i].object;2425add_object_entry(o->oid.hash, o->type,"",0);2426}2427}2428free(in_pack.array);2429}24302431static intadd_loose_object(const unsigned char*sha1,const char*path,2432void*data)2433{2434enum object_type type =sha1_object_info(sha1, NULL);24352436if(type <0) {2437warning("loose object at%scould not be examined", path);2438return0;2439}24402441add_object_entry(sha1, type,"",0);2442return0;2443}24442445/*2446 * We actually don't even have to worry about reachability here.2447 * add_object_entry will weed out duplicates, so we just add every2448 * loose object we find.2449 */2450static voidadd_unreachable_loose_objects(void)2451{2452for_each_loose_file_in_objdir(get_object_directory(),2453 add_loose_object,2454 NULL, NULL, NULL);2455}24562457static inthas_sha1_pack_kept_or_nonlocal(const unsigned char*sha1)2458{2459static struct packed_git *last_found = (void*)1;2460struct packed_git *p;24612462 p = (last_found != (void*)1) ? last_found : packed_git;24632464while(p) {2465if((!p->pack_local || p->pack_keep) &&2466find_pack_entry_one(sha1, p)) {2467 last_found = p;2468return1;2469}2470if(p == last_found)2471 p = packed_git;2472else2473 p = p->next;2474if(p == last_found)2475 p = p->next;2476}2477return0;2478}24792480/*2481 * Store a list of sha1s that are should not be discarded2482 * because they are either written too recently, or are2483 * reachable from another object that was.2484 *2485 * This is filled by get_object_list.2486 */2487static struct sha1_array recent_objects;24882489static intloosened_object_can_be_discarded(const unsigned char*sha1,2490unsigned long mtime)2491{2492if(!unpack_unreachable_expiration)2493return0;2494if(mtime > unpack_unreachable_expiration)2495return0;2496if(sha1_array_lookup(&recent_objects, sha1) >=0)2497return0;2498return1;2499}25002501static voidloosen_unused_packed_objects(struct rev_info *revs)2502{2503struct packed_git *p;2504uint32_t i;2505const unsigned char*sha1;25062507for(p = packed_git; p; p = p->next) {2508if(!p->pack_local || p->pack_keep)2509continue;25102511if(open_pack_index(p))2512die("cannot open pack index");25132514for(i =0; i < p->num_objects; i++) {2515 sha1 =nth_packed_object_sha1(p, i);2516if(!packlist_find(&to_pack, sha1, NULL) &&2517!has_sha1_pack_kept_or_nonlocal(sha1) &&2518!loosened_object_can_be_discarded(sha1, p->mtime))2519if(force_object_loose(sha1, p->mtime))2520die("unable to force loose object");2521}2522}2523}25242525/*2526 * This tracks any options which a reader of the pack might2527 * not understand, and which would therefore prevent blind reuse2528 * of what we have on disk.2529 */2530static intpack_options_allow_reuse(void)2531{2532return allow_ofs_delta;2533}25342535static intget_object_list_from_bitmap(struct rev_info *revs)2536{2537if(prepare_bitmap_walk(revs) <0)2538return-1;25392540if(pack_options_allow_reuse() &&2541!reuse_partial_packfile_from_bitmap(2542&reuse_packfile,2543&reuse_packfile_objects,2544&reuse_packfile_offset)) {2545assert(reuse_packfile_objects);2546 nr_result += reuse_packfile_objects;2547display_progress(progress_state, nr_result);2548}25492550traverse_bitmap_commit_list(&add_object_entry_from_bitmap);2551return0;2552}25532554static voidrecord_recent_object(struct object *obj,2555const char*name,2556void*data)2557{2558sha1_array_append(&recent_objects, obj->oid.hash);2559}25602561static voidrecord_recent_commit(struct commit *commit,void*data)2562{2563sha1_array_append(&recent_objects, commit->object.oid.hash);2564}25652566static voidget_object_list(int ac,const char**av)2567{2568struct rev_info revs;2569char line[1000];2570int flags =0;25712572init_revisions(&revs, NULL);2573 save_commit_buffer =0;2574setup_revisions(ac, av, &revs, NULL);25752576/* make sure shallows are read */2577is_repository_shallow();25782579while(fgets(line,sizeof(line), stdin) != NULL) {2580int len =strlen(line);2581if(len && line[len -1] =='\n')2582 line[--len] =0;2583if(!len)2584break;2585if(*line =='-') {2586if(!strcmp(line,"--not")) {2587 flags ^= UNINTERESTING;2588 write_bitmap_index =0;2589continue;2590}2591if(starts_with(line,"--shallow ")) {2592unsigned char sha1[20];2593if(get_sha1_hex(line +10, sha1))2594die("not an SHA-1 '%s'", line +10);2595register_shallow(sha1);2596 use_bitmap_index =0;2597continue;2598}2599die("not a rev '%s'", line);2600}2601if(handle_revision_arg(line, &revs, flags, REVARG_CANNOT_BE_FILENAME))2602die("bad revision '%s'", line);2603}26042605if(use_bitmap_index && !get_object_list_from_bitmap(&revs))2606return;26072608if(prepare_revision_walk(&revs))2609die("revision walk setup failed");2610mark_edges_uninteresting(&revs, show_edge);2611traverse_commit_list(&revs, show_commit, show_object, NULL);26122613if(unpack_unreachable_expiration) {2614 revs.ignore_missing_links =1;2615if(add_unseen_recent_objects_to_traversal(&revs,2616 unpack_unreachable_expiration))2617die("unable to add recent objects");2618if(prepare_revision_walk(&revs))2619die("revision walk setup failed");2620traverse_commit_list(&revs, record_recent_commit,2621 record_recent_object, NULL);2622}26232624if(keep_unreachable)2625add_objects_in_unpacked_packs(&revs);2626if(pack_loose_unreachable)2627add_unreachable_loose_objects();2628if(unpack_unreachable)2629loosen_unused_packed_objects(&revs);26302631sha1_array_clear(&recent_objects);2632}26332634static intoption_parse_index_version(const struct option *opt,2635const char*arg,int unset)2636{2637char*c;2638const char*val = arg;2639 pack_idx_opts.version =strtoul(val, &c,10);2640if(pack_idx_opts.version >2)2641die(_("unsupported index version%s"), val);2642if(*c ==','&& c[1])2643 pack_idx_opts.off32_limit =strtoul(c+1, &c,0);2644if(*c || pack_idx_opts.off32_limit &0x80000000)2645die(_("bad index version '%s'"), val);2646return0;2647}26482649static intoption_parse_unpack_unreachable(const struct option *opt,2650const char*arg,int unset)2651{2652if(unset) {2653 unpack_unreachable =0;2654 unpack_unreachable_expiration =0;2655}2656else{2657 unpack_unreachable =1;2658if(arg)2659 unpack_unreachable_expiration =approxidate(arg);2660}2661return0;2662}26632664intcmd_pack_objects(int argc,const char**argv,const char*prefix)2665{2666int use_internal_rev_list =0;2667int thin =0;2668int shallow =0;2669int all_progress_implied =0;2670struct argv_array rp = ARGV_ARRAY_INIT;2671int rev_list_unpacked =0, rev_list_all =0, rev_list_reflog =0;2672int rev_list_index =0;2673struct option pack_objects_options[] = {2674OPT_SET_INT('q',"quiet", &progress,2675N_("do not show progress meter"),0),2676OPT_SET_INT(0,"progress", &progress,2677N_("show progress meter"),1),2678OPT_SET_INT(0,"all-progress", &progress,2679N_("show progress meter during object writing phase"),2),2680OPT_BOOL(0,"all-progress-implied",2681&all_progress_implied,2682N_("similar to --all-progress when progress meter is shown")),2683{ OPTION_CALLBACK,0,"index-version", NULL,N_("version[,offset]"),2684N_("write the pack index file in the specified idx format version"),26850, option_parse_index_version },2686OPT_MAGNITUDE(0,"max-pack-size", &pack_size_limit,2687N_("maximum size of each output pack file")),2688OPT_BOOL(0,"local", &local,2689N_("ignore borrowed objects from alternate object store")),2690OPT_BOOL(0,"incremental", &incremental,2691N_("ignore packed objects")),2692OPT_INTEGER(0,"window", &window,2693N_("limit pack window by objects")),2694OPT_MAGNITUDE(0,"window-memory", &window_memory_limit,2695N_("limit pack window by memory in addition to object limit")),2696OPT_INTEGER(0,"depth", &depth,2697N_("maximum length of delta chain allowed in the resulting pack")),2698OPT_BOOL(0,"reuse-delta", &reuse_delta,2699N_("reuse existing deltas")),2700OPT_BOOL(0,"reuse-object", &reuse_object,2701N_("reuse existing objects")),2702OPT_BOOL(0,"delta-base-offset", &allow_ofs_delta,2703N_("use OFS_DELTA objects")),2704OPT_INTEGER(0,"threads", &delta_search_threads,2705N_("use threads when searching for best delta matches")),2706OPT_BOOL(0,"non-empty", &non_empty,2707N_("do not create an empty pack output")),2708OPT_BOOL(0,"revs", &use_internal_rev_list,2709N_("read revision arguments from standard input")),2710{ OPTION_SET_INT,0,"unpacked", &rev_list_unpacked, NULL,2711N_("limit the objects to those that are not yet packed"),2712 PARSE_OPT_NOARG | PARSE_OPT_NONEG, NULL,1},2713{ OPTION_SET_INT,0,"all", &rev_list_all, NULL,2714N_("include objects reachable from any reference"),2715 PARSE_OPT_NOARG | PARSE_OPT_NONEG, NULL,1},2716{ OPTION_SET_INT,0,"reflog", &rev_list_reflog, NULL,2717N_("include objects referred by reflog entries"),2718 PARSE_OPT_NOARG | PARSE_OPT_NONEG, NULL,1},2719{ OPTION_SET_INT,0,"indexed-objects", &rev_list_index, NULL,2720N_("include objects referred to by the index"),2721 PARSE_OPT_NOARG | PARSE_OPT_NONEG, NULL,1},2722OPT_BOOL(0,"stdout", &pack_to_stdout,2723N_("output pack to stdout")),2724OPT_BOOL(0,"include-tag", &include_tag,2725N_("include tag objects that refer to objects to be packed")),2726OPT_BOOL(0,"keep-unreachable", &keep_unreachable,2727N_("keep unreachable objects")),2728OPT_BOOL(0,"pack-loose-unreachable", &pack_loose_unreachable,2729N_("pack loose unreachable objects")),2730{ OPTION_CALLBACK,0,"unpack-unreachable", NULL,N_("time"),2731N_("unpack unreachable objects newer than <time>"),2732 PARSE_OPT_OPTARG, option_parse_unpack_unreachable },2733OPT_BOOL(0,"thin", &thin,2734N_("create thin packs")),2735OPT_BOOL(0,"shallow", &shallow,2736N_("create packs suitable for shallow fetches")),2737OPT_BOOL(0,"honor-pack-keep", &ignore_packed_keep,2738N_("ignore packs that have companion .keep file")),2739OPT_INTEGER(0,"compression", &pack_compression_level,2740N_("pack compression level")),2741OPT_SET_INT(0,"keep-true-parents", &grafts_replace_parents,2742N_("do not hide commits by grafts"),0),2743OPT_BOOL(0,"use-bitmap-index", &use_bitmap_index,2744N_("use a bitmap index if available to speed up counting objects")),2745OPT_BOOL(0,"write-bitmap-index", &write_bitmap_index,2746N_("write a bitmap index together with the pack index")),2747OPT_END(),2748};27492750 check_replace_refs =0;27512752reset_pack_idx_option(&pack_idx_opts);2753git_config(git_pack_config, NULL);2754if(!pack_compression_seen && core_compression_seen)2755 pack_compression_level = core_compression_level;27562757 progress =isatty(2);2758 argc =parse_options(argc, argv, prefix, pack_objects_options,2759 pack_usage,0);27602761if(argc) {2762 base_name = argv[0];2763 argc--;2764}2765if(pack_to_stdout != !base_name || argc)2766usage_with_options(pack_usage, pack_objects_options);27672768argv_array_push(&rp,"pack-objects");2769if(thin) {2770 use_internal_rev_list =1;2771argv_array_push(&rp, shallow2772?"--objects-edge-aggressive"2773:"--objects-edge");2774}else2775argv_array_push(&rp,"--objects");27762777if(rev_list_all) {2778 use_internal_rev_list =1;2779argv_array_push(&rp,"--all");2780}2781if(rev_list_reflog) {2782 use_internal_rev_list =1;2783argv_array_push(&rp,"--reflog");2784}2785if(rev_list_index) {2786 use_internal_rev_list =1;2787argv_array_push(&rp,"--indexed-objects");2788}2789if(rev_list_unpacked) {2790 use_internal_rev_list =1;2791argv_array_push(&rp,"--unpacked");2792}27932794if(!reuse_object)2795 reuse_delta =0;2796if(pack_compression_level == -1)2797 pack_compression_level = Z_DEFAULT_COMPRESSION;2798else if(pack_compression_level <0|| pack_compression_level > Z_BEST_COMPRESSION)2799die("bad pack compression level%d", pack_compression_level);28002801if(!delta_search_threads)/* --threads=0 means autodetect */2802 delta_search_threads =online_cpus();28032804#ifdef NO_PTHREADS2805if(delta_search_threads !=1)2806warning("no threads support, ignoring --threads");2807#endif2808if(!pack_to_stdout && !pack_size_limit)2809 pack_size_limit = pack_size_limit_cfg;2810if(pack_to_stdout && pack_size_limit)2811die("--max-pack-size cannot be used to build a pack for transfer.");2812if(pack_size_limit && pack_size_limit <1024*1024) {2813warning("minimum pack size limit is 1 MiB");2814 pack_size_limit =1024*1024;2815}28162817if(!pack_to_stdout && thin)2818die("--thin cannot be used to build an indexable pack.");28192820if(keep_unreachable && unpack_unreachable)2821die("--keep-unreachable and --unpack-unreachable are incompatible.");2822if(!rev_list_all || !rev_list_reflog || !rev_list_index)2823 unpack_unreachable_expiration =0;28242825if(!use_internal_rev_list || !pack_to_stdout ||is_repository_shallow())2826 use_bitmap_index =0;28272828if(pack_to_stdout || !rev_list_all)2829 write_bitmap_index =0;28302831if(progress && all_progress_implied)2832 progress =2;28332834prepare_packed_git();2835if(ignore_packed_keep) {2836struct packed_git *p;2837for(p = packed_git; p; p = p->next)2838if(p->pack_local && p->pack_keep)2839break;2840if(!p)/* no keep-able packs found */2841 ignore_packed_keep =0;2842}2843if(local) {2844/*2845 * unlike ignore_packed_keep above, we do not want to2846 * unset "local" based on looking at packs, as it2847 * also covers non-local objects2848 */2849struct packed_git *p;2850for(p = packed_git; p; p = p->next) {2851if(!p->pack_local) {2852 have_non_local_packs =1;2853break;2854}2855}2856}28572858if(progress)2859 progress_state =start_progress(_("Counting objects"),0);2860if(!use_internal_rev_list)2861read_object_list_from_stdin();2862else{2863get_object_list(rp.argc, rp.argv);2864argv_array_clear(&rp);2865}2866cleanup_preferred_base();2867if(include_tag && nr_result)2868for_each_ref(add_ref_tag, NULL);2869stop_progress(&progress_state);28702871if(non_empty && !nr_result)2872return0;2873if(nr_result)2874prepare_pack(window, depth);2875write_pack_file();2876if(progress)2877fprintf(stderr,"Total %"PRIu32" (delta %"PRIu32"),"2878" reused %"PRIu32" (delta %"PRIu32")\n",2879 written, written_delta, reused, reused_delta);2880return0;2881}