1#include"builtin.h" 2#include"cache.h" 3#include"attr.h" 4#include"object.h" 5#include"blob.h" 6#include"commit.h" 7#include"tag.h" 8#include"tree.h" 9#include"delta.h" 10#include"pack.h" 11#include"pack-revindex.h" 12#include"csum-file.h" 13#include"tree-walk.h" 14#include"diff.h" 15#include"revision.h" 16#include"list-objects.h" 17#include"pack-objects.h" 18#include"progress.h" 19#include"refs.h" 20#include"streaming.h" 21#include"thread-utils.h" 22#include"pack-bitmap.h" 23#include"reachable.h" 24#include"sha1-array.h" 25#include"argv-array.h" 26 27static const char*pack_usage[] = { 28N_("git pack-objects --stdout [<options>...] [< <ref-list> | < <object-list>]"), 29N_("git pack-objects [<options>...] <base-name> [< <ref-list> | < <object-list>]"), 30 NULL 31}; 32 33/* 34 * Objects we are going to pack are collected in the `to_pack` structure. 35 * It contains an array (dynamically expanded) of the object data, and a map 36 * that can resolve SHA1s to their position in the array. 37 */ 38static struct packing_data to_pack; 39 40static struct pack_idx_entry **written_list; 41static uint32_t nr_result, nr_written; 42 43static int non_empty; 44static int reuse_delta =1, reuse_object =1; 45static int keep_unreachable, unpack_unreachable, include_tag; 46static unsigned long unpack_unreachable_expiration; 47static int pack_loose_unreachable; 48static int local; 49static int have_non_local_packs; 50static int incremental; 51static int ignore_packed_keep; 52static int allow_ofs_delta; 53static struct pack_idx_option pack_idx_opts; 54static const char*base_name; 55static int progress =1; 56static int window =10; 57static unsigned long pack_size_limit; 58static int depth =50; 59static int delta_search_threads; 60static int pack_to_stdout; 61static int num_preferred_base; 62static struct progress *progress_state; 63static int pack_compression_level = Z_DEFAULT_COMPRESSION; 64static int pack_compression_seen; 65 66static struct packed_git *reuse_packfile; 67static uint32_t reuse_packfile_objects; 68static off_t reuse_packfile_offset; 69 70static int use_bitmap_index_default =1; 71static int use_bitmap_index = -1; 72static int write_bitmap_index; 73static uint16_t write_bitmap_options; 74 75static unsigned long delta_cache_size =0; 76static unsigned long max_delta_cache_size =256*1024*1024; 77static unsigned long cache_max_small_delta_size =1000; 78 79static unsigned long window_memory_limit =0; 80 81/* 82 * stats 83 */ 84static uint32_t written, written_delta; 85static uint32_t reused, reused_delta; 86 87/* 88 * Indexed commits 89 */ 90static struct commit **indexed_commits; 91static unsigned int indexed_commits_nr; 92static unsigned int indexed_commits_alloc; 93 94static voidindex_commit_for_bitmap(struct commit *commit) 95{ 96if(indexed_commits_nr >= indexed_commits_alloc) { 97 indexed_commits_alloc = (indexed_commits_alloc +32) *2; 98REALLOC_ARRAY(indexed_commits, indexed_commits_alloc); 99} 100 101 indexed_commits[indexed_commits_nr++] = commit; 102} 103 104static void*get_delta(struct object_entry *entry) 105{ 106unsigned long size, base_size, delta_size; 107void*buf, *base_buf, *delta_buf; 108enum object_type type; 109 110 buf =read_sha1_file(entry->idx.sha1, &type, &size); 111if(!buf) 112die("unable to read%s",sha1_to_hex(entry->idx.sha1)); 113 base_buf =read_sha1_file(entry->delta->idx.sha1, &type, &base_size); 114if(!base_buf) 115die("unable to read%s",sha1_to_hex(entry->delta->idx.sha1)); 116 delta_buf =diff_delta(base_buf, base_size, 117 buf, size, &delta_size,0); 118if(!delta_buf || delta_size != entry->delta_size) 119die("delta size changed"); 120free(buf); 121free(base_buf); 122return delta_buf; 123} 124 125static unsigned longdo_compress(void**pptr,unsigned long size) 126{ 127 git_zstream stream; 128void*in, *out; 129unsigned long maxsize; 130 131git_deflate_init(&stream, pack_compression_level); 132 maxsize =git_deflate_bound(&stream, size); 133 134 in = *pptr; 135 out =xmalloc(maxsize); 136*pptr = out; 137 138 stream.next_in = in; 139 stream.avail_in = size; 140 stream.next_out = out; 141 stream.avail_out = maxsize; 142while(git_deflate(&stream, Z_FINISH) == Z_OK) 143;/* nothing */ 144git_deflate_end(&stream); 145 146free(in); 147return stream.total_out; 148} 149 150static unsigned longwrite_large_blob_data(struct git_istream *st,struct sha1file *f, 151const unsigned char*sha1) 152{ 153 git_zstream stream; 154unsigned char ibuf[1024*16]; 155unsigned char obuf[1024*16]; 156unsigned long olen =0; 157 158git_deflate_init(&stream, pack_compression_level); 159 160for(;;) { 161 ssize_t readlen; 162int zret = Z_OK; 163 readlen =read_istream(st, ibuf,sizeof(ibuf)); 164if(readlen == -1) 165die(_("unable to read%s"),sha1_to_hex(sha1)); 166 167 stream.next_in = ibuf; 168 stream.avail_in = readlen; 169while((stream.avail_in || readlen ==0) && 170(zret == Z_OK || zret == Z_BUF_ERROR)) { 171 stream.next_out = obuf; 172 stream.avail_out =sizeof(obuf); 173 zret =git_deflate(&stream, readlen ?0: Z_FINISH); 174sha1write(f, obuf, stream.next_out - obuf); 175 olen += stream.next_out - obuf; 176} 177if(stream.avail_in) 178die(_("deflate error (%d)"), zret); 179if(readlen ==0) { 180if(zret != Z_STREAM_END) 181die(_("deflate error (%d)"), zret); 182break; 183} 184} 185git_deflate_end(&stream); 186return olen; 187} 188 189/* 190 * we are going to reuse the existing object data as is. make 191 * sure it is not corrupt. 192 */ 193static intcheck_pack_inflate(struct packed_git *p, 194struct pack_window **w_curs, 195 off_t offset, 196 off_t len, 197unsigned long expect) 198{ 199 git_zstream stream; 200unsigned char fakebuf[4096], *in; 201int st; 202 203memset(&stream,0,sizeof(stream)); 204git_inflate_init(&stream); 205do{ 206 in =use_pack(p, w_curs, offset, &stream.avail_in); 207 stream.next_in = in; 208 stream.next_out = fakebuf; 209 stream.avail_out =sizeof(fakebuf); 210 st =git_inflate(&stream, Z_FINISH); 211 offset += stream.next_in - in; 212}while(st == Z_OK || st == Z_BUF_ERROR); 213git_inflate_end(&stream); 214return(st == Z_STREAM_END && 215 stream.total_out == expect && 216 stream.total_in == len) ?0: -1; 217} 218 219static voidcopy_pack_data(struct sha1file *f, 220struct packed_git *p, 221struct pack_window **w_curs, 222 off_t offset, 223 off_t len) 224{ 225unsigned char*in; 226unsigned long avail; 227 228while(len) { 229 in =use_pack(p, w_curs, offset, &avail); 230if(avail > len) 231 avail = (unsigned long)len; 232sha1write(f, in, avail); 233 offset += avail; 234 len -= avail; 235} 236} 237 238/* Return 0 if we will bust the pack-size limit */ 239static unsigned longwrite_no_reuse_object(struct sha1file *f,struct object_entry *entry, 240unsigned long limit,int usable_delta) 241{ 242unsigned long size, datalen; 243unsigned char header[10], dheader[10]; 244unsigned hdrlen; 245enum object_type type; 246void*buf; 247struct git_istream *st = NULL; 248 249if(!usable_delta) { 250if(entry->type == OBJ_BLOB && 251 entry->size > big_file_threshold && 252(st =open_istream(entry->idx.sha1, &type, &size, NULL)) != NULL) 253 buf = NULL; 254else{ 255 buf =read_sha1_file(entry->idx.sha1, &type, &size); 256if(!buf) 257die(_("unable to read%s"),sha1_to_hex(entry->idx.sha1)); 258} 259/* 260 * make sure no cached delta data remains from a 261 * previous attempt before a pack split occurred. 262 */ 263free(entry->delta_data); 264 entry->delta_data = NULL; 265 entry->z_delta_size =0; 266}else if(entry->delta_data) { 267 size = entry->delta_size; 268 buf = entry->delta_data; 269 entry->delta_data = NULL; 270 type = (allow_ofs_delta && entry->delta->idx.offset) ? 271 OBJ_OFS_DELTA : OBJ_REF_DELTA; 272}else{ 273 buf =get_delta(entry); 274 size = entry->delta_size; 275 type = (allow_ofs_delta && entry->delta->idx.offset) ? 276 OBJ_OFS_DELTA : OBJ_REF_DELTA; 277} 278 279if(st)/* large blob case, just assume we don't compress well */ 280 datalen = size; 281else if(entry->z_delta_size) 282 datalen = entry->z_delta_size; 283else 284 datalen =do_compress(&buf, size); 285 286/* 287 * The object header is a byte of 'type' followed by zero or 288 * more bytes of length. 289 */ 290 hdrlen =encode_in_pack_object_header(type, size, header); 291 292if(type == OBJ_OFS_DELTA) { 293/* 294 * Deltas with relative base contain an additional 295 * encoding of the relative offset for the delta 296 * base from this object's position in the pack. 297 */ 298 off_t ofs = entry->idx.offset - entry->delta->idx.offset; 299unsigned pos =sizeof(dheader) -1; 300 dheader[pos] = ofs &127; 301while(ofs >>=7) 302 dheader[--pos] =128| (--ofs &127); 303if(limit && hdrlen +sizeof(dheader) - pos + datalen +20>= limit) { 304if(st) 305close_istream(st); 306free(buf); 307return0; 308} 309sha1write(f, header, hdrlen); 310sha1write(f, dheader + pos,sizeof(dheader) - pos); 311 hdrlen +=sizeof(dheader) - pos; 312}else if(type == OBJ_REF_DELTA) { 313/* 314 * Deltas with a base reference contain 315 * an additional 20 bytes for the base sha1. 316 */ 317if(limit && hdrlen +20+ datalen +20>= limit) { 318if(st) 319close_istream(st); 320free(buf); 321return0; 322} 323sha1write(f, header, hdrlen); 324sha1write(f, entry->delta->idx.sha1,20); 325 hdrlen +=20; 326}else{ 327if(limit && hdrlen + datalen +20>= limit) { 328if(st) 329close_istream(st); 330free(buf); 331return0; 332} 333sha1write(f, header, hdrlen); 334} 335if(st) { 336 datalen =write_large_blob_data(st, f, entry->idx.sha1); 337close_istream(st); 338}else{ 339sha1write(f, buf, datalen); 340free(buf); 341} 342 343return hdrlen + datalen; 344} 345 346/* Return 0 if we will bust the pack-size limit */ 347static off_t write_reuse_object(struct sha1file *f,struct object_entry *entry, 348unsigned long limit,int usable_delta) 349{ 350struct packed_git *p = entry->in_pack; 351struct pack_window *w_curs = NULL; 352struct revindex_entry *revidx; 353 off_t offset; 354enum object_type type = entry->type; 355 off_t datalen; 356unsigned char header[10], dheader[10]; 357unsigned hdrlen; 358 359if(entry->delta) 360 type = (allow_ofs_delta && entry->delta->idx.offset) ? 361 OBJ_OFS_DELTA : OBJ_REF_DELTA; 362 hdrlen =encode_in_pack_object_header(type, entry->size, header); 363 364 offset = entry->in_pack_offset; 365 revidx =find_pack_revindex(p, offset); 366 datalen = revidx[1].offset - offset; 367if(!pack_to_stdout && p->index_version >1&& 368check_pack_crc(p, &w_curs, offset, datalen, revidx->nr)) { 369error("bad packed object CRC for%s",sha1_to_hex(entry->idx.sha1)); 370unuse_pack(&w_curs); 371returnwrite_no_reuse_object(f, entry, limit, usable_delta); 372} 373 374 offset += entry->in_pack_header_size; 375 datalen -= entry->in_pack_header_size; 376 377if(!pack_to_stdout && p->index_version ==1&& 378check_pack_inflate(p, &w_curs, offset, datalen, entry->size)) { 379error("corrupt packed object for%s",sha1_to_hex(entry->idx.sha1)); 380unuse_pack(&w_curs); 381returnwrite_no_reuse_object(f, entry, limit, usable_delta); 382} 383 384if(type == OBJ_OFS_DELTA) { 385 off_t ofs = entry->idx.offset - entry->delta->idx.offset; 386unsigned pos =sizeof(dheader) -1; 387 dheader[pos] = ofs &127; 388while(ofs >>=7) 389 dheader[--pos] =128| (--ofs &127); 390if(limit && hdrlen +sizeof(dheader) - pos + datalen +20>= limit) { 391unuse_pack(&w_curs); 392return0; 393} 394sha1write(f, header, hdrlen); 395sha1write(f, dheader + pos,sizeof(dheader) - pos); 396 hdrlen +=sizeof(dheader) - pos; 397 reused_delta++; 398}else if(type == OBJ_REF_DELTA) { 399if(limit && hdrlen +20+ datalen +20>= limit) { 400unuse_pack(&w_curs); 401return0; 402} 403sha1write(f, header, hdrlen); 404sha1write(f, entry->delta->idx.sha1,20); 405 hdrlen +=20; 406 reused_delta++; 407}else{ 408if(limit && hdrlen + datalen +20>= limit) { 409unuse_pack(&w_curs); 410return0; 411} 412sha1write(f, header, hdrlen); 413} 414copy_pack_data(f, p, &w_curs, offset, datalen); 415unuse_pack(&w_curs); 416 reused++; 417return hdrlen + datalen; 418} 419 420/* Return 0 if we will bust the pack-size limit */ 421static off_t write_object(struct sha1file *f, 422struct object_entry *entry, 423 off_t write_offset) 424{ 425unsigned long limit; 426 off_t len; 427int usable_delta, to_reuse; 428 429if(!pack_to_stdout) 430crc32_begin(f); 431 432/* apply size limit if limited packsize and not first object */ 433if(!pack_size_limit || !nr_written) 434 limit =0; 435else if(pack_size_limit <= write_offset) 436/* 437 * the earlier object did not fit the limit; avoid 438 * mistaking this with unlimited (i.e. limit = 0). 439 */ 440 limit =1; 441else 442 limit = pack_size_limit - write_offset; 443 444if(!entry->delta) 445 usable_delta =0;/* no delta */ 446else if(!pack_size_limit) 447 usable_delta =1;/* unlimited packfile */ 448else if(entry->delta->idx.offset == (off_t)-1) 449 usable_delta =0;/* base was written to another pack */ 450else if(entry->delta->idx.offset) 451 usable_delta =1;/* base already exists in this pack */ 452else 453 usable_delta =0;/* base could end up in another pack */ 454 455if(!reuse_object) 456 to_reuse =0;/* explicit */ 457else if(!entry->in_pack) 458 to_reuse =0;/* can't reuse what we don't have */ 459else if(entry->type == OBJ_REF_DELTA || entry->type == OBJ_OFS_DELTA) 460/* check_object() decided it for us ... */ 461 to_reuse = usable_delta; 462/* ... but pack split may override that */ 463else if(entry->type != entry->in_pack_type) 464 to_reuse =0;/* pack has delta which is unusable */ 465else if(entry->delta) 466 to_reuse =0;/* we want to pack afresh */ 467else 468 to_reuse =1;/* we have it in-pack undeltified, 469 * and we do not need to deltify it. 470 */ 471 472if(!to_reuse) 473 len =write_no_reuse_object(f, entry, limit, usable_delta); 474else 475 len =write_reuse_object(f, entry, limit, usable_delta); 476if(!len) 477return0; 478 479if(usable_delta) 480 written_delta++; 481 written++; 482if(!pack_to_stdout) 483 entry->idx.crc32 =crc32_end(f); 484return len; 485} 486 487enum write_one_status { 488 WRITE_ONE_SKIP = -1,/* already written */ 489 WRITE_ONE_BREAK =0,/* writing this will bust the limit; not written */ 490 WRITE_ONE_WRITTEN =1,/* normal */ 491 WRITE_ONE_RECURSIVE =2/* already scheduled to be written */ 492}; 493 494static enum write_one_status write_one(struct sha1file *f, 495struct object_entry *e, 496 off_t *offset) 497{ 498 off_t size; 499int recursing; 500 501/* 502 * we set offset to 1 (which is an impossible value) to mark 503 * the fact that this object is involved in "write its base 504 * first before writing a deltified object" recursion. 505 */ 506 recursing = (e->idx.offset ==1); 507if(recursing) { 508warning("recursive delta detected for object%s", 509sha1_to_hex(e->idx.sha1)); 510return WRITE_ONE_RECURSIVE; 511}else if(e->idx.offset || e->preferred_base) { 512/* offset is non zero if object is written already. */ 513return WRITE_ONE_SKIP; 514} 515 516/* if we are deltified, write out base object first. */ 517if(e->delta) { 518 e->idx.offset =1;/* now recurse */ 519switch(write_one(f, e->delta, offset)) { 520case WRITE_ONE_RECURSIVE: 521/* we cannot depend on this one */ 522 e->delta = NULL; 523break; 524default: 525break; 526case WRITE_ONE_BREAK: 527 e->idx.offset = recursing; 528return WRITE_ONE_BREAK; 529} 530} 531 532 e->idx.offset = *offset; 533 size =write_object(f, e, *offset); 534if(!size) { 535 e->idx.offset = recursing; 536return WRITE_ONE_BREAK; 537} 538 written_list[nr_written++] = &e->idx; 539 540/* make sure off_t is sufficiently large not to wrap */ 541if(signed_add_overflows(*offset, size)) 542die("pack too large for current definition of off_t"); 543*offset += size; 544return WRITE_ONE_WRITTEN; 545} 546 547static intmark_tagged(const char*path,const struct object_id *oid,int flag, 548void*cb_data) 549{ 550unsigned char peeled[20]; 551struct object_entry *entry =packlist_find(&to_pack, oid->hash, NULL); 552 553if(entry) 554 entry->tagged =1; 555if(!peel_ref(path, peeled)) { 556 entry =packlist_find(&to_pack, peeled, NULL); 557if(entry) 558 entry->tagged =1; 559} 560return0; 561} 562 563staticinlinevoidadd_to_write_order(struct object_entry **wo, 564unsigned int*endp, 565struct object_entry *e) 566{ 567if(e->filled) 568return; 569 wo[(*endp)++] = e; 570 e->filled =1; 571} 572 573static voidadd_descendants_to_write_order(struct object_entry **wo, 574unsigned int*endp, 575struct object_entry *e) 576{ 577int add_to_order =1; 578while(e) { 579if(add_to_order) { 580struct object_entry *s; 581/* add this node... */ 582add_to_write_order(wo, endp, e); 583/* all its siblings... */ 584for(s = e->delta_sibling; s; s = s->delta_sibling) { 585add_to_write_order(wo, endp, s); 586} 587} 588/* drop down a level to add left subtree nodes if possible */ 589if(e->delta_child) { 590 add_to_order =1; 591 e = e->delta_child; 592}else{ 593 add_to_order =0; 594/* our sibling might have some children, it is next */ 595if(e->delta_sibling) { 596 e = e->delta_sibling; 597continue; 598} 599/* go back to our parent node */ 600 e = e->delta; 601while(e && !e->delta_sibling) { 602/* we're on the right side of a subtree, keep 603 * going up until we can go right again */ 604 e = e->delta; 605} 606if(!e) { 607/* done- we hit our original root node */ 608return; 609} 610/* pass it off to sibling at this level */ 611 e = e->delta_sibling; 612} 613}; 614} 615 616static voidadd_family_to_write_order(struct object_entry **wo, 617unsigned int*endp, 618struct object_entry *e) 619{ 620struct object_entry *root; 621 622for(root = e; root->delta; root = root->delta) 623;/* nothing */ 624add_descendants_to_write_order(wo, endp, root); 625} 626 627static struct object_entry **compute_write_order(void) 628{ 629unsigned int i, wo_end, last_untagged; 630 631struct object_entry **wo; 632struct object_entry *objects = to_pack.objects; 633 634for(i =0; i < to_pack.nr_objects; i++) { 635 objects[i].tagged =0; 636 objects[i].filled =0; 637 objects[i].delta_child = NULL; 638 objects[i].delta_sibling = NULL; 639} 640 641/* 642 * Fully connect delta_child/delta_sibling network. 643 * Make sure delta_sibling is sorted in the original 644 * recency order. 645 */ 646for(i = to_pack.nr_objects; i >0;) { 647struct object_entry *e = &objects[--i]; 648if(!e->delta) 649continue; 650/* Mark me as the first child */ 651 e->delta_sibling = e->delta->delta_child; 652 e->delta->delta_child = e; 653} 654 655/* 656 * Mark objects that are at the tip of tags. 657 */ 658for_each_tag_ref(mark_tagged, NULL); 659 660/* 661 * Give the objects in the original recency order until 662 * we see a tagged tip. 663 */ 664ALLOC_ARRAY(wo, to_pack.nr_objects); 665for(i = wo_end =0; i < to_pack.nr_objects; i++) { 666if(objects[i].tagged) 667break; 668add_to_write_order(wo, &wo_end, &objects[i]); 669} 670 last_untagged = i; 671 672/* 673 * Then fill all the tagged tips. 674 */ 675for(; i < to_pack.nr_objects; i++) { 676if(objects[i].tagged) 677add_to_write_order(wo, &wo_end, &objects[i]); 678} 679 680/* 681 * And then all remaining commits and tags. 682 */ 683for(i = last_untagged; i < to_pack.nr_objects; i++) { 684if(objects[i].type != OBJ_COMMIT && 685 objects[i].type != OBJ_TAG) 686continue; 687add_to_write_order(wo, &wo_end, &objects[i]); 688} 689 690/* 691 * And then all the trees. 692 */ 693for(i = last_untagged; i < to_pack.nr_objects; i++) { 694if(objects[i].type != OBJ_TREE) 695continue; 696add_to_write_order(wo, &wo_end, &objects[i]); 697} 698 699/* 700 * Finally all the rest in really tight order 701 */ 702for(i = last_untagged; i < to_pack.nr_objects; i++) { 703if(!objects[i].filled) 704add_family_to_write_order(wo, &wo_end, &objects[i]); 705} 706 707if(wo_end != to_pack.nr_objects) 708die("ordered%uobjects, expected %"PRIu32, wo_end, to_pack.nr_objects); 709 710return wo; 711} 712 713static off_t write_reused_pack(struct sha1file *f) 714{ 715unsigned char buffer[8192]; 716 off_t to_write, total; 717int fd; 718 719if(!is_pack_valid(reuse_packfile)) 720die("packfile is invalid:%s", reuse_packfile->pack_name); 721 722 fd =git_open_noatime(reuse_packfile->pack_name); 723if(fd <0) 724die_errno("unable to open packfile for reuse:%s", 725 reuse_packfile->pack_name); 726 727if(lseek(fd,sizeof(struct pack_header), SEEK_SET) == -1) 728die_errno("unable to seek in reused packfile"); 729 730if(reuse_packfile_offset <0) 731 reuse_packfile_offset = reuse_packfile->pack_size -20; 732 733 total = to_write = reuse_packfile_offset -sizeof(struct pack_header); 734 735while(to_write) { 736int read_pack =xread(fd, buffer,sizeof(buffer)); 737 738if(read_pack <=0) 739die_errno("unable to read from reused packfile"); 740 741if(read_pack > to_write) 742 read_pack = to_write; 743 744sha1write(f, buffer, read_pack); 745 to_write -= read_pack; 746 747/* 748 * We don't know the actual number of objects written, 749 * only how many bytes written, how many bytes total, and 750 * how many objects total. So we can fake it by pretending all 751 * objects we are writing are the same size. This gives us a 752 * smooth progress meter, and at the end it matches the true 753 * answer. 754 */ 755 written = reuse_packfile_objects * 756(((double)(total - to_write)) / total); 757display_progress(progress_state, written); 758} 759 760close(fd); 761 written = reuse_packfile_objects; 762display_progress(progress_state, written); 763return reuse_packfile_offset -sizeof(struct pack_header); 764} 765 766static const char no_split_warning[] =N_( 767"disabling bitmap writing, packs are split due to pack.packSizeLimit" 768); 769 770static voidwrite_pack_file(void) 771{ 772uint32_t i =0, j; 773struct sha1file *f; 774 off_t offset; 775uint32_t nr_remaining = nr_result; 776time_t last_mtime =0; 777struct object_entry **write_order; 778 779if(progress > pack_to_stdout) 780 progress_state =start_progress(_("Writing objects"), nr_result); 781ALLOC_ARRAY(written_list, to_pack.nr_objects); 782 write_order =compute_write_order(); 783 784do{ 785unsigned char sha1[20]; 786char*pack_tmp_name = NULL; 787 788if(pack_to_stdout) 789 f =sha1fd_throughput(1,"<stdout>", progress_state); 790else 791 f =create_tmp_packfile(&pack_tmp_name); 792 793 offset =write_pack_header(f, nr_remaining); 794 795if(reuse_packfile) { 796 off_t packfile_size; 797assert(pack_to_stdout); 798 799 packfile_size =write_reused_pack(f); 800 offset += packfile_size; 801} 802 803 nr_written =0; 804for(; i < to_pack.nr_objects; i++) { 805struct object_entry *e = write_order[i]; 806if(write_one(f, e, &offset) == WRITE_ONE_BREAK) 807break; 808display_progress(progress_state, written); 809} 810 811/* 812 * Did we write the wrong # entries in the header? 813 * If so, rewrite it like in fast-import 814 */ 815if(pack_to_stdout) { 816sha1close(f, sha1, CSUM_CLOSE); 817}else if(nr_written == nr_remaining) { 818sha1close(f, sha1, CSUM_FSYNC); 819}else{ 820int fd =sha1close(f, sha1,0); 821fixup_pack_header_footer(fd, sha1, pack_tmp_name, 822 nr_written, sha1, offset); 823close(fd); 824if(write_bitmap_index) { 825warning(_(no_split_warning)); 826 write_bitmap_index =0; 827} 828} 829 830if(!pack_to_stdout) { 831struct stat st; 832struct strbuf tmpname = STRBUF_INIT; 833 834/* 835 * Packs are runtime accessed in their mtime 836 * order since newer packs are more likely to contain 837 * younger objects. So if we are creating multiple 838 * packs then we should modify the mtime of later ones 839 * to preserve this property. 840 */ 841if(stat(pack_tmp_name, &st) <0) { 842warning_errno("failed to stat%s", pack_tmp_name); 843}else if(!last_mtime) { 844 last_mtime = st.st_mtime; 845}else{ 846struct utimbuf utb; 847 utb.actime = st.st_atime; 848 utb.modtime = --last_mtime; 849if(utime(pack_tmp_name, &utb) <0) 850warning_errno("failed utime() on%s", pack_tmp_name); 851} 852 853strbuf_addf(&tmpname,"%s-", base_name); 854 855if(write_bitmap_index) { 856bitmap_writer_set_checksum(sha1); 857bitmap_writer_build_type_index(written_list, nr_written); 858} 859 860finish_tmp_packfile(&tmpname, pack_tmp_name, 861 written_list, nr_written, 862&pack_idx_opts, sha1); 863 864if(write_bitmap_index) { 865strbuf_addf(&tmpname,"%s.bitmap",sha1_to_hex(sha1)); 866 867stop_progress(&progress_state); 868 869bitmap_writer_show_progress(progress); 870bitmap_writer_reuse_bitmaps(&to_pack); 871bitmap_writer_select_commits(indexed_commits, indexed_commits_nr, -1); 872bitmap_writer_build(&to_pack); 873bitmap_writer_finish(written_list, nr_written, 874 tmpname.buf, write_bitmap_options); 875 write_bitmap_index =0; 876} 877 878strbuf_release(&tmpname); 879free(pack_tmp_name); 880puts(sha1_to_hex(sha1)); 881} 882 883/* mark written objects as written to previous pack */ 884for(j =0; j < nr_written; j++) { 885 written_list[j]->offset = (off_t)-1; 886} 887 nr_remaining -= nr_written; 888}while(nr_remaining && i < to_pack.nr_objects); 889 890free(written_list); 891free(write_order); 892stop_progress(&progress_state); 893if(written != nr_result) 894die("wrote %"PRIu32" objects while expecting %"PRIu32, 895 written, nr_result); 896} 897 898static voidsetup_delta_attr_check(struct git_attr_check *check) 899{ 900static struct git_attr *attr_delta; 901 902if(!attr_delta) 903 attr_delta =git_attr("delta"); 904 905 check[0].attr = attr_delta; 906} 907 908static intno_try_delta(const char*path) 909{ 910struct git_attr_check check[1]; 911 912setup_delta_attr_check(check); 913if(git_check_attr(path,ARRAY_SIZE(check), check)) 914return0; 915if(ATTR_FALSE(check->value)) 916return1; 917return0; 918} 919 920/* 921 * When adding an object, check whether we have already added it 922 * to our packing list. If so, we can skip. However, if we are 923 * being asked to excludei t, but the previous mention was to include 924 * it, make sure to adjust its flags and tweak our numbers accordingly. 925 * 926 * As an optimization, we pass out the index position where we would have 927 * found the item, since that saves us from having to look it up again a 928 * few lines later when we want to add the new entry. 929 */ 930static inthave_duplicate_entry(const unsigned char*sha1, 931int exclude, 932uint32_t*index_pos) 933{ 934struct object_entry *entry; 935 936 entry =packlist_find(&to_pack, sha1, index_pos); 937if(!entry) 938return0; 939 940if(exclude) { 941if(!entry->preferred_base) 942 nr_result--; 943 entry->preferred_base =1; 944} 945 946return1; 947} 948 949static intwant_found_object(int exclude,struct packed_git *p) 950{ 951if(exclude) 952return1; 953if(incremental) 954return0; 955 956/* 957 * When asked to do --local (do not include an object that appears in a 958 * pack we borrow from elsewhere) or --honor-pack-keep (do not include 959 * an object that appears in a pack marked with .keep), finding a pack 960 * that matches the criteria is sufficient for us to decide to omit it. 961 * However, even if this pack does not satisfy the criteria, we need to 962 * make sure no copy of this object appears in _any_ pack that makes us 963 * to omit the object, so we need to check all the packs. 964 * 965 * We can however first check whether these options can possible matter; 966 * if they do not matter we know we want the object in generated pack. 967 * Otherwise, we signal "-1" at the end to tell the caller that we do 968 * not know either way, and it needs to check more packs. 969 */ 970if(!ignore_packed_keep && 971(!local || !have_non_local_packs)) 972return1; 973 974if(local && !p->pack_local) 975return0; 976if(ignore_packed_keep && p->pack_local && p->pack_keep) 977return0; 978 979/* we don't know yet; keep looking for more packs */ 980return-1; 981} 982 983/* 984 * Check whether we want the object in the pack (e.g., we do not want 985 * objects found in non-local stores if the "--local" option was used). 986 * 987 * If the caller already knows an existing pack it wants to take the object 988 * from, that is passed in *found_pack and *found_offset; otherwise this 989 * function finds if there is any pack that has the object and returns the pack 990 * and its offset in these variables. 991 */ 992static intwant_object_in_pack(const unsigned char*sha1, 993int exclude, 994struct packed_git **found_pack, 995 off_t *found_offset) 996{ 997struct packed_git *p; 998int want; 9991000if(!exclude && local &&has_loose_object_nonlocal(sha1))1001return0;10021003/*1004 * If we already know the pack object lives in, start checks from that1005 * pack - in the usual case when neither --local was given nor .keep files1006 * are present we will determine the answer right now.1007 */1008if(*found_pack) {1009 want =want_found_object(exclude, *found_pack);1010if(want != -1)1011return want;1012}10131014for(p = packed_git; p; p = p->next) {1015 off_t offset;10161017if(p == *found_pack)1018 offset = *found_offset;1019else1020 offset =find_pack_entry_one(sha1, p);10211022if(offset) {1023if(!*found_pack) {1024if(!is_pack_valid(p))1025continue;1026*found_offset = offset;1027*found_pack = p;1028}1029 want =want_found_object(exclude, p);1030if(want != -1)1031return want;1032}1033}10341035return1;1036}10371038static voidcreate_object_entry(const unsigned char*sha1,1039enum object_type type,1040uint32_t hash,1041int exclude,1042int no_try_delta,1043uint32_t index_pos,1044struct packed_git *found_pack,1045 off_t found_offset)1046{1047struct object_entry *entry;10481049 entry =packlist_alloc(&to_pack, sha1, index_pos);1050 entry->hash = hash;1051if(type)1052 entry->type = type;1053if(exclude)1054 entry->preferred_base =1;1055else1056 nr_result++;1057if(found_pack) {1058 entry->in_pack = found_pack;1059 entry->in_pack_offset = found_offset;1060}10611062 entry->no_try_delta = no_try_delta;1063}10641065static const char no_closure_warning[] =N_(1066"disabling bitmap writing, as some objects are not being packed"1067);10681069static intadd_object_entry(const unsigned char*sha1,enum object_type type,1070const char*name,int exclude)1071{1072struct packed_git *found_pack = NULL;1073 off_t found_offset =0;1074uint32_t index_pos;10751076if(have_duplicate_entry(sha1, exclude, &index_pos))1077return0;10781079if(!want_object_in_pack(sha1, exclude, &found_pack, &found_offset)) {1080/* The pack is missing an object, so it will not have closure */1081if(write_bitmap_index) {1082warning(_(no_closure_warning));1083 write_bitmap_index =0;1084}1085return0;1086}10871088create_object_entry(sha1, type,pack_name_hash(name),1089 exclude, name &&no_try_delta(name),1090 index_pos, found_pack, found_offset);10911092display_progress(progress_state, nr_result);1093return1;1094}10951096static intadd_object_entry_from_bitmap(const unsigned char*sha1,1097enum object_type type,1098int flags,uint32_t name_hash,1099struct packed_git *pack, off_t offset)1100{1101uint32_t index_pos;11021103if(have_duplicate_entry(sha1,0, &index_pos))1104return0;11051106if(!want_object_in_pack(sha1,0, &pack, &offset))1107return0;11081109create_object_entry(sha1, type, name_hash,0,0, index_pos, pack, offset);11101111display_progress(progress_state, nr_result);1112return1;1113}11141115struct pbase_tree_cache {1116unsigned char sha1[20];1117int ref;1118int temporary;1119void*tree_data;1120unsigned long tree_size;1121};11221123static struct pbase_tree_cache *(pbase_tree_cache[256]);1124static intpbase_tree_cache_ix(const unsigned char*sha1)1125{1126return sha1[0] %ARRAY_SIZE(pbase_tree_cache);1127}1128static intpbase_tree_cache_ix_incr(int ix)1129{1130return(ix+1) %ARRAY_SIZE(pbase_tree_cache);1131}11321133static struct pbase_tree {1134struct pbase_tree *next;1135/* This is a phony "cache" entry; we are not1136 * going to evict it or find it through _get()1137 * mechanism -- this is for the toplevel node that1138 * would almost always change with any commit.1139 */1140struct pbase_tree_cache pcache;1141} *pbase_tree;11421143static struct pbase_tree_cache *pbase_tree_get(const unsigned char*sha1)1144{1145struct pbase_tree_cache *ent, *nent;1146void*data;1147unsigned long size;1148enum object_type type;1149int neigh;1150int my_ix =pbase_tree_cache_ix(sha1);1151int available_ix = -1;11521153/* pbase-tree-cache acts as a limited hashtable.1154 * your object will be found at your index or within a few1155 * slots after that slot if it is cached.1156 */1157for(neigh =0; neigh <8; neigh++) {1158 ent = pbase_tree_cache[my_ix];1159if(ent && !hashcmp(ent->sha1, sha1)) {1160 ent->ref++;1161return ent;1162}1163else if(((available_ix <0) && (!ent || !ent->ref)) ||1164((0<= available_ix) &&1165(!ent && pbase_tree_cache[available_ix])))1166 available_ix = my_ix;1167if(!ent)1168break;1169 my_ix =pbase_tree_cache_ix_incr(my_ix);1170}11711172/* Did not find one. Either we got a bogus request or1173 * we need to read and perhaps cache.1174 */1175 data =read_sha1_file(sha1, &type, &size);1176if(!data)1177return NULL;1178if(type != OBJ_TREE) {1179free(data);1180return NULL;1181}11821183/* We need to either cache or return a throwaway copy */11841185if(available_ix <0)1186 ent = NULL;1187else{1188 ent = pbase_tree_cache[available_ix];1189 my_ix = available_ix;1190}11911192if(!ent) {1193 nent =xmalloc(sizeof(*nent));1194 nent->temporary = (available_ix <0);1195}1196else{1197/* evict and reuse */1198free(ent->tree_data);1199 nent = ent;1200}1201hashcpy(nent->sha1, sha1);1202 nent->tree_data = data;1203 nent->tree_size = size;1204 nent->ref =1;1205if(!nent->temporary)1206 pbase_tree_cache[my_ix] = nent;1207return nent;1208}12091210static voidpbase_tree_put(struct pbase_tree_cache *cache)1211{1212if(!cache->temporary) {1213 cache->ref--;1214return;1215}1216free(cache->tree_data);1217free(cache);1218}12191220static intname_cmp_len(const char*name)1221{1222int i;1223for(i =0; name[i] && name[i] !='\n'&& name[i] !='/'; i++)1224;1225return i;1226}12271228static voidadd_pbase_object(struct tree_desc *tree,1229const char*name,1230int cmplen,1231const char*fullname)1232{1233struct name_entry entry;1234int cmp;12351236while(tree_entry(tree,&entry)) {1237if(S_ISGITLINK(entry.mode))1238continue;1239 cmp =tree_entry_len(&entry) != cmplen ?1:1240memcmp(name, entry.path, cmplen);1241if(cmp >0)1242continue;1243if(cmp <0)1244return;1245if(name[cmplen] !='/') {1246add_object_entry(entry.oid->hash,1247object_type(entry.mode),1248 fullname,1);1249return;1250}1251if(S_ISDIR(entry.mode)) {1252struct tree_desc sub;1253struct pbase_tree_cache *tree;1254const char*down = name+cmplen+1;1255int downlen =name_cmp_len(down);12561257 tree =pbase_tree_get(entry.oid->hash);1258if(!tree)1259return;1260init_tree_desc(&sub, tree->tree_data, tree->tree_size);12611262add_pbase_object(&sub, down, downlen, fullname);1263pbase_tree_put(tree);1264}1265}1266}12671268static unsigned*done_pbase_paths;1269static int done_pbase_paths_num;1270static int done_pbase_paths_alloc;1271static intdone_pbase_path_pos(unsigned hash)1272{1273int lo =0;1274int hi = done_pbase_paths_num;1275while(lo < hi) {1276int mi = (hi + lo) /2;1277if(done_pbase_paths[mi] == hash)1278return mi;1279if(done_pbase_paths[mi] < hash)1280 hi = mi;1281else1282 lo = mi +1;1283}1284return-lo-1;1285}12861287static intcheck_pbase_path(unsigned hash)1288{1289int pos = (!done_pbase_paths) ? -1:done_pbase_path_pos(hash);1290if(0<= pos)1291return1;1292 pos = -pos -1;1293ALLOC_GROW(done_pbase_paths,1294 done_pbase_paths_num +1,1295 done_pbase_paths_alloc);1296 done_pbase_paths_num++;1297if(pos < done_pbase_paths_num)1298memmove(done_pbase_paths + pos +1,1299 done_pbase_paths + pos,1300(done_pbase_paths_num - pos -1) *sizeof(unsigned));1301 done_pbase_paths[pos] = hash;1302return0;1303}13041305static voidadd_preferred_base_object(const char*name)1306{1307struct pbase_tree *it;1308int cmplen;1309unsigned hash =pack_name_hash(name);13101311if(!num_preferred_base ||check_pbase_path(hash))1312return;13131314 cmplen =name_cmp_len(name);1315for(it = pbase_tree; it; it = it->next) {1316if(cmplen ==0) {1317add_object_entry(it->pcache.sha1, OBJ_TREE, NULL,1);1318}1319else{1320struct tree_desc tree;1321init_tree_desc(&tree, it->pcache.tree_data, it->pcache.tree_size);1322add_pbase_object(&tree, name, cmplen, name);1323}1324}1325}13261327static voidadd_preferred_base(unsigned char*sha1)1328{1329struct pbase_tree *it;1330void*data;1331unsigned long size;1332unsigned char tree_sha1[20];13331334if(window <= num_preferred_base++)1335return;13361337 data =read_object_with_reference(sha1, tree_type, &size, tree_sha1);1338if(!data)1339return;13401341for(it = pbase_tree; it; it = it->next) {1342if(!hashcmp(it->pcache.sha1, tree_sha1)) {1343free(data);1344return;1345}1346}13471348 it =xcalloc(1,sizeof(*it));1349 it->next = pbase_tree;1350 pbase_tree = it;13511352hashcpy(it->pcache.sha1, tree_sha1);1353 it->pcache.tree_data = data;1354 it->pcache.tree_size = size;1355}13561357static voidcleanup_preferred_base(void)1358{1359struct pbase_tree *it;1360unsigned i;13611362 it = pbase_tree;1363 pbase_tree = NULL;1364while(it) {1365struct pbase_tree *this= it;1366 it =this->next;1367free(this->pcache.tree_data);1368free(this);1369}13701371for(i =0; i <ARRAY_SIZE(pbase_tree_cache); i++) {1372if(!pbase_tree_cache[i])1373continue;1374free(pbase_tree_cache[i]->tree_data);1375free(pbase_tree_cache[i]);1376 pbase_tree_cache[i] = NULL;1377}13781379free(done_pbase_paths);1380 done_pbase_paths = NULL;1381 done_pbase_paths_num = done_pbase_paths_alloc =0;1382}13831384static voidcheck_object(struct object_entry *entry)1385{1386if(entry->in_pack) {1387struct packed_git *p = entry->in_pack;1388struct pack_window *w_curs = NULL;1389const unsigned char*base_ref = NULL;1390struct object_entry *base_entry;1391unsigned long used, used_0;1392unsigned long avail;1393 off_t ofs;1394unsigned char*buf, c;13951396 buf =use_pack(p, &w_curs, entry->in_pack_offset, &avail);13971398/*1399 * We want in_pack_type even if we do not reuse delta1400 * since non-delta representations could still be reused.1401 */1402 used =unpack_object_header_buffer(buf, avail,1403&entry->in_pack_type,1404&entry->size);1405if(used ==0)1406goto give_up;14071408/*1409 * Determine if this is a delta and if so whether we can1410 * reuse it or not. Otherwise let's find out as cheaply as1411 * possible what the actual type and size for this object is.1412 */1413switch(entry->in_pack_type) {1414default:1415/* Not a delta hence we've already got all we need. */1416 entry->type = entry->in_pack_type;1417 entry->in_pack_header_size = used;1418if(entry->type < OBJ_COMMIT || entry->type > OBJ_BLOB)1419goto give_up;1420unuse_pack(&w_curs);1421return;1422case OBJ_REF_DELTA:1423if(reuse_delta && !entry->preferred_base)1424 base_ref =use_pack(p, &w_curs,1425 entry->in_pack_offset + used, NULL);1426 entry->in_pack_header_size = used +20;1427break;1428case OBJ_OFS_DELTA:1429 buf =use_pack(p, &w_curs,1430 entry->in_pack_offset + used, NULL);1431 used_0 =0;1432 c = buf[used_0++];1433 ofs = c &127;1434while(c &128) {1435 ofs +=1;1436if(!ofs ||MSB(ofs,7)) {1437error("delta base offset overflow in pack for%s",1438sha1_to_hex(entry->idx.sha1));1439goto give_up;1440}1441 c = buf[used_0++];1442 ofs = (ofs <<7) + (c &127);1443}1444 ofs = entry->in_pack_offset - ofs;1445if(ofs <=0|| ofs >= entry->in_pack_offset) {1446error("delta base offset out of bound for%s",1447sha1_to_hex(entry->idx.sha1));1448goto give_up;1449}1450if(reuse_delta && !entry->preferred_base) {1451struct revindex_entry *revidx;1452 revidx =find_pack_revindex(p, ofs);1453if(!revidx)1454goto give_up;1455 base_ref =nth_packed_object_sha1(p, revidx->nr);1456}1457 entry->in_pack_header_size = used + used_0;1458break;1459}14601461if(base_ref && (base_entry =packlist_find(&to_pack, base_ref, NULL))) {1462/*1463 * If base_ref was set above that means we wish to1464 * reuse delta data, and we even found that base1465 * in the list of objects we want to pack. Goodie!1466 *1467 * Depth value does not matter - find_deltas() will1468 * never consider reused delta as the base object to1469 * deltify other objects against, in order to avoid1470 * circular deltas.1471 */1472 entry->type = entry->in_pack_type;1473 entry->delta = base_entry;1474 entry->delta_size = entry->size;1475 entry->delta_sibling = base_entry->delta_child;1476 base_entry->delta_child = entry;1477unuse_pack(&w_curs);1478return;1479}14801481if(entry->type) {1482/*1483 * This must be a delta and we already know what the1484 * final object type is. Let's extract the actual1485 * object size from the delta header.1486 */1487 entry->size =get_size_from_delta(p, &w_curs,1488 entry->in_pack_offset + entry->in_pack_header_size);1489if(entry->size ==0)1490goto give_up;1491unuse_pack(&w_curs);1492return;1493}14941495/*1496 * No choice but to fall back to the recursive delta walk1497 * with sha1_object_info() to find about the object type1498 * at this point...1499 */1500 give_up:1501unuse_pack(&w_curs);1502}15031504 entry->type =sha1_object_info(entry->idx.sha1, &entry->size);1505/*1506 * The error condition is checked in prepare_pack(). This is1507 * to permit a missing preferred base object to be ignored1508 * as a preferred base. Doing so can result in a larger1509 * pack file, but the transfer will still take place.1510 */1511}15121513static intpack_offset_sort(const void*_a,const void*_b)1514{1515const struct object_entry *a = *(struct object_entry **)_a;1516const struct object_entry *b = *(struct object_entry **)_b;15171518/* avoid filesystem trashing with loose objects */1519if(!a->in_pack && !b->in_pack)1520returnhashcmp(a->idx.sha1, b->idx.sha1);15211522if(a->in_pack < b->in_pack)1523return-1;1524if(a->in_pack > b->in_pack)1525return1;1526return a->in_pack_offset < b->in_pack_offset ? -1:1527(a->in_pack_offset > b->in_pack_offset);1528}15291530static voidget_object_details(void)1531{1532uint32_t i;1533struct object_entry **sorted_by_offset;15341535 sorted_by_offset =xcalloc(to_pack.nr_objects,sizeof(struct object_entry *));1536for(i =0; i < to_pack.nr_objects; i++)1537 sorted_by_offset[i] = to_pack.objects + i;1538QSORT(sorted_by_offset, to_pack.nr_objects, pack_offset_sort);15391540for(i =0; i < to_pack.nr_objects; i++) {1541struct object_entry *entry = sorted_by_offset[i];1542check_object(entry);1543if(big_file_threshold < entry->size)1544 entry->no_try_delta =1;1545}15461547free(sorted_by_offset);1548}15491550/*1551 * We search for deltas in a list sorted by type, by filename hash, and then1552 * by size, so that we see progressively smaller and smaller files.1553 * That's because we prefer deltas to be from the bigger file1554 * to the smaller -- deletes are potentially cheaper, but perhaps1555 * more importantly, the bigger file is likely the more recent1556 * one. The deepest deltas are therefore the oldest objects which are1557 * less susceptible to be accessed often.1558 */1559static inttype_size_sort(const void*_a,const void*_b)1560{1561const struct object_entry *a = *(struct object_entry **)_a;1562const struct object_entry *b = *(struct object_entry **)_b;15631564if(a->type > b->type)1565return-1;1566if(a->type < b->type)1567return1;1568if(a->hash > b->hash)1569return-1;1570if(a->hash < b->hash)1571return1;1572if(a->preferred_base > b->preferred_base)1573return-1;1574if(a->preferred_base < b->preferred_base)1575return1;1576if(a->size > b->size)1577return-1;1578if(a->size < b->size)1579return1;1580return a < b ? -1: (a > b);/* newest first */1581}15821583struct unpacked {1584struct object_entry *entry;1585void*data;1586struct delta_index *index;1587unsigned depth;1588};15891590static intdelta_cacheable(unsigned long src_size,unsigned long trg_size,1591unsigned long delta_size)1592{1593if(max_delta_cache_size && delta_cache_size + delta_size > max_delta_cache_size)1594return0;15951596if(delta_size < cache_max_small_delta_size)1597return1;15981599/* cache delta, if objects are large enough compared to delta size */1600if((src_size >>20) + (trg_size >>21) > (delta_size >>10))1601return1;16021603return0;1604}16051606#ifndef NO_PTHREADS16071608static pthread_mutex_t read_mutex;1609#define read_lock() pthread_mutex_lock(&read_mutex)1610#define read_unlock() pthread_mutex_unlock(&read_mutex)16111612static pthread_mutex_t cache_mutex;1613#define cache_lock() pthread_mutex_lock(&cache_mutex)1614#define cache_unlock() pthread_mutex_unlock(&cache_mutex)16151616static pthread_mutex_t progress_mutex;1617#define progress_lock() pthread_mutex_lock(&progress_mutex)1618#define progress_unlock() pthread_mutex_unlock(&progress_mutex)16191620#else16211622#define read_lock() (void)01623#define read_unlock() (void)01624#define cache_lock() (void)01625#define cache_unlock() (void)01626#define progress_lock() (void)01627#define progress_unlock() (void)016281629#endif16301631static inttry_delta(struct unpacked *trg,struct unpacked *src,1632unsigned max_depth,unsigned long*mem_usage)1633{1634struct object_entry *trg_entry = trg->entry;1635struct object_entry *src_entry = src->entry;1636unsigned long trg_size, src_size, delta_size, sizediff, max_size, sz;1637unsigned ref_depth;1638enum object_type type;1639void*delta_buf;16401641/* Don't bother doing diffs between different types */1642if(trg_entry->type != src_entry->type)1643return-1;16441645/*1646 * We do not bother to try a delta that we discarded on an1647 * earlier try, but only when reusing delta data. Note that1648 * src_entry that is marked as the preferred_base should always1649 * be considered, as even if we produce a suboptimal delta against1650 * it, we will still save the transfer cost, as we already know1651 * the other side has it and we won't send src_entry at all.1652 */1653if(reuse_delta && trg_entry->in_pack &&1654 trg_entry->in_pack == src_entry->in_pack &&1655!src_entry->preferred_base &&1656 trg_entry->in_pack_type != OBJ_REF_DELTA &&1657 trg_entry->in_pack_type != OBJ_OFS_DELTA)1658return0;16591660/* Let's not bust the allowed depth. */1661if(src->depth >= max_depth)1662return0;16631664/* Now some size filtering heuristics. */1665 trg_size = trg_entry->size;1666if(!trg_entry->delta) {1667 max_size = trg_size/2-20;1668 ref_depth =1;1669}else{1670 max_size = trg_entry->delta_size;1671 ref_depth = trg->depth;1672}1673 max_size = (uint64_t)max_size * (max_depth - src->depth) /1674(max_depth - ref_depth +1);1675if(max_size ==0)1676return0;1677 src_size = src_entry->size;1678 sizediff = src_size < trg_size ? trg_size - src_size :0;1679if(sizediff >= max_size)1680return0;1681if(trg_size < src_size /32)1682return0;16831684/* Load data if not already done */1685if(!trg->data) {1686read_lock();1687 trg->data =read_sha1_file(trg_entry->idx.sha1, &type, &sz);1688read_unlock();1689if(!trg->data)1690die("object%scannot be read",1691sha1_to_hex(trg_entry->idx.sha1));1692if(sz != trg_size)1693die("object%sinconsistent object length (%lu vs%lu)",1694sha1_to_hex(trg_entry->idx.sha1), sz, trg_size);1695*mem_usage += sz;1696}1697if(!src->data) {1698read_lock();1699 src->data =read_sha1_file(src_entry->idx.sha1, &type, &sz);1700read_unlock();1701if(!src->data) {1702if(src_entry->preferred_base) {1703static int warned =0;1704if(!warned++)1705warning("object%scannot be read",1706sha1_to_hex(src_entry->idx.sha1));1707/*1708 * Those objects are not included in the1709 * resulting pack. Be resilient and ignore1710 * them if they can't be read, in case the1711 * pack could be created nevertheless.1712 */1713return0;1714}1715die("object%scannot be read",1716sha1_to_hex(src_entry->idx.sha1));1717}1718if(sz != src_size)1719die("object%sinconsistent object length (%lu vs%lu)",1720sha1_to_hex(src_entry->idx.sha1), sz, src_size);1721*mem_usage += sz;1722}1723if(!src->index) {1724 src->index =create_delta_index(src->data, src_size);1725if(!src->index) {1726static int warned =0;1727if(!warned++)1728warning("suboptimal pack - out of memory");1729return0;1730}1731*mem_usage +=sizeof_delta_index(src->index);1732}17331734 delta_buf =create_delta(src->index, trg->data, trg_size, &delta_size, max_size);1735if(!delta_buf)1736return0;17371738if(trg_entry->delta) {1739/* Prefer only shallower same-sized deltas. */1740if(delta_size == trg_entry->delta_size &&1741 src->depth +1>= trg->depth) {1742free(delta_buf);1743return0;1744}1745}17461747/*1748 * Handle memory allocation outside of the cache1749 * accounting lock. Compiler will optimize the strangeness1750 * away when NO_PTHREADS is defined.1751 */1752free(trg_entry->delta_data);1753cache_lock();1754if(trg_entry->delta_data) {1755 delta_cache_size -= trg_entry->delta_size;1756 trg_entry->delta_data = NULL;1757}1758if(delta_cacheable(src_size, trg_size, delta_size)) {1759 delta_cache_size += delta_size;1760cache_unlock();1761 trg_entry->delta_data =xrealloc(delta_buf, delta_size);1762}else{1763cache_unlock();1764free(delta_buf);1765}17661767 trg_entry->delta = src_entry;1768 trg_entry->delta_size = delta_size;1769 trg->depth = src->depth +1;17701771return1;1772}17731774static unsigned intcheck_delta_limit(struct object_entry *me,unsigned int n)1775{1776struct object_entry *child = me->delta_child;1777unsigned int m = n;1778while(child) {1779unsigned int c =check_delta_limit(child, n +1);1780if(m < c)1781 m = c;1782 child = child->delta_sibling;1783}1784return m;1785}17861787static unsigned longfree_unpacked(struct unpacked *n)1788{1789unsigned long freed_mem =sizeof_delta_index(n->index);1790free_delta_index(n->index);1791 n->index = NULL;1792if(n->data) {1793 freed_mem += n->entry->size;1794free(n->data);1795 n->data = NULL;1796}1797 n->entry = NULL;1798 n->depth =0;1799return freed_mem;1800}18011802static voidfind_deltas(struct object_entry **list,unsigned*list_size,1803int window,int depth,unsigned*processed)1804{1805uint32_t i, idx =0, count =0;1806struct unpacked *array;1807unsigned long mem_usage =0;18081809 array =xcalloc(window,sizeof(struct unpacked));18101811for(;;) {1812struct object_entry *entry;1813struct unpacked *n = array + idx;1814int j, max_depth, best_base = -1;18151816progress_lock();1817if(!*list_size) {1818progress_unlock();1819break;1820}1821 entry = *list++;1822(*list_size)--;1823if(!entry->preferred_base) {1824(*processed)++;1825display_progress(progress_state, *processed);1826}1827progress_unlock();18281829 mem_usage -=free_unpacked(n);1830 n->entry = entry;18311832while(window_memory_limit &&1833 mem_usage > window_memory_limit &&1834 count >1) {1835uint32_t tail = (idx + window - count) % window;1836 mem_usage -=free_unpacked(array + tail);1837 count--;1838}18391840/* We do not compute delta to *create* objects we are not1841 * going to pack.1842 */1843if(entry->preferred_base)1844goto next;18451846/*1847 * If the current object is at pack edge, take the depth the1848 * objects that depend on the current object into account1849 * otherwise they would become too deep.1850 */1851 max_depth = depth;1852if(entry->delta_child) {1853 max_depth -=check_delta_limit(entry,0);1854if(max_depth <=0)1855goto next;1856}18571858 j = window;1859while(--j >0) {1860int ret;1861uint32_t other_idx = idx + j;1862struct unpacked *m;1863if(other_idx >= window)1864 other_idx -= window;1865 m = array + other_idx;1866if(!m->entry)1867break;1868 ret =try_delta(n, m, max_depth, &mem_usage);1869if(ret <0)1870break;1871else if(ret >0)1872 best_base = other_idx;1873}18741875/*1876 * If we decided to cache the delta data, then it is best1877 * to compress it right away. First because we have to do1878 * it anyway, and doing it here while we're threaded will1879 * save a lot of time in the non threaded write phase,1880 * as well as allow for caching more deltas within1881 * the same cache size limit.1882 * ...1883 * But only if not writing to stdout, since in that case1884 * the network is most likely throttling writes anyway,1885 * and therefore it is best to go to the write phase ASAP1886 * instead, as we can afford spending more time compressing1887 * between writes at that moment.1888 */1889if(entry->delta_data && !pack_to_stdout) {1890 entry->z_delta_size =do_compress(&entry->delta_data,1891 entry->delta_size);1892cache_lock();1893 delta_cache_size -= entry->delta_size;1894 delta_cache_size += entry->z_delta_size;1895cache_unlock();1896}18971898/* if we made n a delta, and if n is already at max1899 * depth, leaving it in the window is pointless. we1900 * should evict it first.1901 */1902if(entry->delta && max_depth <= n->depth)1903continue;19041905/*1906 * Move the best delta base up in the window, after the1907 * currently deltified object, to keep it longer. It will1908 * be the first base object to be attempted next.1909 */1910if(entry->delta) {1911struct unpacked swap = array[best_base];1912int dist = (window + idx - best_base) % window;1913int dst = best_base;1914while(dist--) {1915int src = (dst +1) % window;1916 array[dst] = array[src];1917 dst = src;1918}1919 array[dst] = swap;1920}19211922 next:1923 idx++;1924if(count +1< window)1925 count++;1926if(idx >= window)1927 idx =0;1928}19291930for(i =0; i < window; ++i) {1931free_delta_index(array[i].index);1932free(array[i].data);1933}1934free(array);1935}19361937#ifndef NO_PTHREADS19381939static voidtry_to_free_from_threads(size_t size)1940{1941read_lock();1942release_pack_memory(size);1943read_unlock();1944}19451946static try_to_free_t old_try_to_free_routine;19471948/*1949 * The main thread waits on the condition that (at least) one of the workers1950 * has stopped working (which is indicated in the .working member of1951 * struct thread_params).1952 * When a work thread has completed its work, it sets .working to 0 and1953 * signals the main thread and waits on the condition that .data_ready1954 * becomes 1.1955 */19561957struct thread_params {1958 pthread_t thread;1959struct object_entry **list;1960unsigned list_size;1961unsigned remaining;1962int window;1963int depth;1964int working;1965int data_ready;1966 pthread_mutex_t mutex;1967 pthread_cond_t cond;1968unsigned*processed;1969};19701971static pthread_cond_t progress_cond;19721973/*1974 * Mutex and conditional variable can't be statically-initialized on Windows.1975 */1976static voidinit_threaded_search(void)1977{1978init_recursive_mutex(&read_mutex);1979pthread_mutex_init(&cache_mutex, NULL);1980pthread_mutex_init(&progress_mutex, NULL);1981pthread_cond_init(&progress_cond, NULL);1982 old_try_to_free_routine =set_try_to_free_routine(try_to_free_from_threads);1983}19841985static voidcleanup_threaded_search(void)1986{1987set_try_to_free_routine(old_try_to_free_routine);1988pthread_cond_destroy(&progress_cond);1989pthread_mutex_destroy(&read_mutex);1990pthread_mutex_destroy(&cache_mutex);1991pthread_mutex_destroy(&progress_mutex);1992}19931994static void*threaded_find_deltas(void*arg)1995{1996struct thread_params *me = arg;19971998while(me->remaining) {1999find_deltas(me->list, &me->remaining,2000 me->window, me->depth, me->processed);20012002progress_lock();2003 me->working =0;2004pthread_cond_signal(&progress_cond);2005progress_unlock();20062007/*2008 * We must not set ->data_ready before we wait on the2009 * condition because the main thread may have set it to 12010 * before we get here. In order to be sure that new2011 * work is available if we see 1 in ->data_ready, it2012 * was initialized to 0 before this thread was spawned2013 * and we reset it to 0 right away.2014 */2015pthread_mutex_lock(&me->mutex);2016while(!me->data_ready)2017pthread_cond_wait(&me->cond, &me->mutex);2018 me->data_ready =0;2019pthread_mutex_unlock(&me->mutex);2020}2021/* leave ->working 1 so that this doesn't get more work assigned */2022return NULL;2023}20242025static voidll_find_deltas(struct object_entry **list,unsigned list_size,2026int window,int depth,unsigned*processed)2027{2028struct thread_params *p;2029int i, ret, active_threads =0;20302031init_threaded_search();20322033if(delta_search_threads <=1) {2034find_deltas(list, &list_size, window, depth, processed);2035cleanup_threaded_search();2036return;2037}2038if(progress > pack_to_stdout)2039fprintf(stderr,"Delta compression using up to%dthreads.\n",2040 delta_search_threads);2041 p =xcalloc(delta_search_threads,sizeof(*p));20422043/* Partition the work amongst work threads. */2044for(i =0; i < delta_search_threads; i++) {2045unsigned sub_size = list_size / (delta_search_threads - i);20462047/* don't use too small segments or no deltas will be found */2048if(sub_size <2*window && i+1< delta_search_threads)2049 sub_size =0;20502051 p[i].window = window;2052 p[i].depth = depth;2053 p[i].processed = processed;2054 p[i].working =1;2055 p[i].data_ready =0;20562057/* try to split chunks on "path" boundaries */2058while(sub_size && sub_size < list_size &&2059 list[sub_size]->hash &&2060 list[sub_size]->hash == list[sub_size-1]->hash)2061 sub_size++;20622063 p[i].list = list;2064 p[i].list_size = sub_size;2065 p[i].remaining = sub_size;20662067 list += sub_size;2068 list_size -= sub_size;2069}20702071/* Start work threads. */2072for(i =0; i < delta_search_threads; i++) {2073if(!p[i].list_size)2074continue;2075pthread_mutex_init(&p[i].mutex, NULL);2076pthread_cond_init(&p[i].cond, NULL);2077 ret =pthread_create(&p[i].thread, NULL,2078 threaded_find_deltas, &p[i]);2079if(ret)2080die("unable to create thread:%s",strerror(ret));2081 active_threads++;2082}20832084/*2085 * Now let's wait for work completion. Each time a thread is done2086 * with its work, we steal half of the remaining work from the2087 * thread with the largest number of unprocessed objects and give2088 * it to that newly idle thread. This ensure good load balancing2089 * until the remaining object list segments are simply too short2090 * to be worth splitting anymore.2091 */2092while(active_threads) {2093struct thread_params *target = NULL;2094struct thread_params *victim = NULL;2095unsigned sub_size =0;20962097progress_lock();2098for(;;) {2099for(i =0; !target && i < delta_search_threads; i++)2100if(!p[i].working)2101 target = &p[i];2102if(target)2103break;2104pthread_cond_wait(&progress_cond, &progress_mutex);2105}21062107for(i =0; i < delta_search_threads; i++)2108if(p[i].remaining >2*window &&2109(!victim || victim->remaining < p[i].remaining))2110 victim = &p[i];2111if(victim) {2112 sub_size = victim->remaining /2;2113 list = victim->list + victim->list_size - sub_size;2114while(sub_size && list[0]->hash &&2115 list[0]->hash == list[-1]->hash) {2116 list++;2117 sub_size--;2118}2119if(!sub_size) {2120/*2121 * It is possible for some "paths" to have2122 * so many objects that no hash boundary2123 * might be found. Let's just steal the2124 * exact half in that case.2125 */2126 sub_size = victim->remaining /2;2127 list -= sub_size;2128}2129 target->list = list;2130 victim->list_size -= sub_size;2131 victim->remaining -= sub_size;2132}2133 target->list_size = sub_size;2134 target->remaining = sub_size;2135 target->working =1;2136progress_unlock();21372138pthread_mutex_lock(&target->mutex);2139 target->data_ready =1;2140pthread_cond_signal(&target->cond);2141pthread_mutex_unlock(&target->mutex);21422143if(!sub_size) {2144pthread_join(target->thread, NULL);2145pthread_cond_destroy(&target->cond);2146pthread_mutex_destroy(&target->mutex);2147 active_threads--;2148}2149}2150cleanup_threaded_search();2151free(p);2152}21532154#else2155#define ll_find_deltas(l, s, w, d, p) find_deltas(l, &s, w, d, p)2156#endif21572158static voidadd_tag_chain(const struct object_id *oid)2159{2160struct tag *tag;21612162/*2163 * We catch duplicates already in add_object_entry(), but we'd2164 * prefer to do this extra check to avoid having to parse the2165 * tag at all if we already know that it's being packed (e.g., if2166 * it was included via bitmaps, we would not have parsed it2167 * previously).2168 */2169if(packlist_find(&to_pack, oid->hash, NULL))2170return;21712172 tag =lookup_tag(oid->hash);2173while(1) {2174if(!tag ||parse_tag(tag) || !tag->tagged)2175die("unable to pack objects reachable from tag%s",2176oid_to_hex(oid));21772178add_object_entry(tag->object.oid.hash, OBJ_TAG, NULL,0);21792180if(tag->tagged->type != OBJ_TAG)2181return;21822183 tag = (struct tag *)tag->tagged;2184}2185}21862187static intadd_ref_tag(const char*path,const struct object_id *oid,int flag,void*cb_data)2188{2189struct object_id peeled;21902191if(starts_with(path,"refs/tags/") &&/* is a tag? */2192!peel_ref(path, peeled.hash) &&/* peelable? */2193packlist_find(&to_pack, peeled.hash, NULL))/* object packed? */2194add_tag_chain(oid);2195return0;2196}21972198static voidprepare_pack(int window,int depth)2199{2200struct object_entry **delta_list;2201uint32_t i, nr_deltas;2202unsigned n;22032204get_object_details();22052206/*2207 * If we're locally repacking then we need to be doubly careful2208 * from now on in order to make sure no stealth corruption gets2209 * propagated to the new pack. Clients receiving streamed packs2210 * should validate everything they get anyway so no need to incur2211 * the additional cost here in that case.2212 */2213if(!pack_to_stdout)2214 do_check_packed_object_crc =1;22152216if(!to_pack.nr_objects || !window || !depth)2217return;22182219ALLOC_ARRAY(delta_list, to_pack.nr_objects);2220 nr_deltas = n =0;22212222for(i =0; i < to_pack.nr_objects; i++) {2223struct object_entry *entry = to_pack.objects + i;22242225if(entry->delta)2226/* This happens if we decided to reuse existing2227 * delta from a pack. "reuse_delta &&" is implied.2228 */2229continue;22302231if(entry->size <50)2232continue;22332234if(entry->no_try_delta)2235continue;22362237if(!entry->preferred_base) {2238 nr_deltas++;2239if(entry->type <0)2240die("unable to get type of object%s",2241sha1_to_hex(entry->idx.sha1));2242}else{2243if(entry->type <0) {2244/*2245 * This object is not found, but we2246 * don't have to include it anyway.2247 */2248continue;2249}2250}22512252 delta_list[n++] = entry;2253}22542255if(nr_deltas && n >1) {2256unsigned nr_done =0;2257if(progress)2258 progress_state =start_progress(_("Compressing objects"),2259 nr_deltas);2260QSORT(delta_list, n, type_size_sort);2261ll_find_deltas(delta_list, n, window+1, depth, &nr_done);2262stop_progress(&progress_state);2263if(nr_done != nr_deltas)2264die("inconsistency with delta count");2265}2266free(delta_list);2267}22682269static intgit_pack_config(const char*k,const char*v,void*cb)2270{2271if(!strcmp(k,"pack.window")) {2272 window =git_config_int(k, v);2273return0;2274}2275if(!strcmp(k,"pack.windowmemory")) {2276 window_memory_limit =git_config_ulong(k, v);2277return0;2278}2279if(!strcmp(k,"pack.depth")) {2280 depth =git_config_int(k, v);2281return0;2282}2283if(!strcmp(k,"pack.compression")) {2284int level =git_config_int(k, v);2285if(level == -1)2286 level = Z_DEFAULT_COMPRESSION;2287else if(level <0|| level > Z_BEST_COMPRESSION)2288die("bad pack compression level%d", level);2289 pack_compression_level = level;2290 pack_compression_seen =1;2291return0;2292}2293if(!strcmp(k,"pack.deltacachesize")) {2294 max_delta_cache_size =git_config_int(k, v);2295return0;2296}2297if(!strcmp(k,"pack.deltacachelimit")) {2298 cache_max_small_delta_size =git_config_int(k, v);2299return0;2300}2301if(!strcmp(k,"pack.writebitmaphashcache")) {2302if(git_config_bool(k, v))2303 write_bitmap_options |= BITMAP_OPT_HASH_CACHE;2304else2305 write_bitmap_options &= ~BITMAP_OPT_HASH_CACHE;2306}2307if(!strcmp(k,"pack.usebitmaps")) {2308 use_bitmap_index_default =git_config_bool(k, v);2309return0;2310}2311if(!strcmp(k,"pack.threads")) {2312 delta_search_threads =git_config_int(k, v);2313if(delta_search_threads <0)2314die("invalid number of threads specified (%d)",2315 delta_search_threads);2316#ifdef NO_PTHREADS2317if(delta_search_threads !=1)2318warning("no threads support, ignoring%s", k);2319#endif2320return0;2321}2322if(!strcmp(k,"pack.indexversion")) {2323 pack_idx_opts.version =git_config_int(k, v);2324if(pack_idx_opts.version >2)2325die("bad pack.indexversion=%"PRIu32,2326 pack_idx_opts.version);2327return0;2328}2329returngit_default_config(k, v, cb);2330}23312332static voidread_object_list_from_stdin(void)2333{2334char line[40+1+ PATH_MAX +2];2335unsigned char sha1[20];23362337for(;;) {2338if(!fgets(line,sizeof(line), stdin)) {2339if(feof(stdin))2340break;2341if(!ferror(stdin))2342die("fgets returned NULL, not EOF, not error!");2343if(errno != EINTR)2344die_errno("fgets");2345clearerr(stdin);2346continue;2347}2348if(line[0] =='-') {2349if(get_sha1_hex(line+1, sha1))2350die("expected edge sha1, got garbage:\n%s",2351 line);2352add_preferred_base(sha1);2353continue;2354}2355if(get_sha1_hex(line, sha1))2356die("expected sha1, got garbage:\n%s", line);23572358add_preferred_base_object(line+41);2359add_object_entry(sha1,0, line+41,0);2360}2361}23622363#define OBJECT_ADDED (1u<<20)23642365static voidshow_commit(struct commit *commit,void*data)2366{2367add_object_entry(commit->object.oid.hash, OBJ_COMMIT, NULL,0);2368 commit->object.flags |= OBJECT_ADDED;23692370if(write_bitmap_index)2371index_commit_for_bitmap(commit);2372}23732374static voidshow_object(struct object *obj,const char*name,void*data)2375{2376add_preferred_base_object(name);2377add_object_entry(obj->oid.hash, obj->type, name,0);2378 obj->flags |= OBJECT_ADDED;2379}23802381static voidshow_edge(struct commit *commit)2382{2383add_preferred_base(commit->object.oid.hash);2384}23852386struct in_pack_object {2387 off_t offset;2388struct object *object;2389};23902391struct in_pack {2392int alloc;2393int nr;2394struct in_pack_object *array;2395};23962397static voidmark_in_pack_object(struct object *object,struct packed_git *p,struct in_pack *in_pack)2398{2399 in_pack->array[in_pack->nr].offset =find_pack_entry_one(object->oid.hash, p);2400 in_pack->array[in_pack->nr].object = object;2401 in_pack->nr++;2402}24032404/*2405 * Compare the objects in the offset order, in order to emulate the2406 * "git rev-list --objects" output that produced the pack originally.2407 */2408static intofscmp(const void*a_,const void*b_)2409{2410struct in_pack_object *a = (struct in_pack_object *)a_;2411struct in_pack_object *b = (struct in_pack_object *)b_;24122413if(a->offset < b->offset)2414return-1;2415else if(a->offset > b->offset)2416return1;2417else2418returnoidcmp(&a->object->oid, &b->object->oid);2419}24202421static voidadd_objects_in_unpacked_packs(struct rev_info *revs)2422{2423struct packed_git *p;2424struct in_pack in_pack;2425uint32_t i;24262427memset(&in_pack,0,sizeof(in_pack));24282429for(p = packed_git; p; p = p->next) {2430const unsigned char*sha1;2431struct object *o;24322433if(!p->pack_local || p->pack_keep)2434continue;2435if(open_pack_index(p))2436die("cannot open pack index");24372438ALLOC_GROW(in_pack.array,2439 in_pack.nr + p->num_objects,2440 in_pack.alloc);24412442for(i =0; i < p->num_objects; i++) {2443 sha1 =nth_packed_object_sha1(p, i);2444 o =lookup_unknown_object(sha1);2445if(!(o->flags & OBJECT_ADDED))2446mark_in_pack_object(o, p, &in_pack);2447 o->flags |= OBJECT_ADDED;2448}2449}24502451if(in_pack.nr) {2452QSORT(in_pack.array, in_pack.nr, ofscmp);2453for(i =0; i < in_pack.nr; i++) {2454struct object *o = in_pack.array[i].object;2455add_object_entry(o->oid.hash, o->type,"",0);2456}2457}2458free(in_pack.array);2459}24602461static intadd_loose_object(const unsigned char*sha1,const char*path,2462void*data)2463{2464enum object_type type =sha1_object_info(sha1, NULL);24652466if(type <0) {2467warning("loose object at%scould not be examined", path);2468return0;2469}24702471add_object_entry(sha1, type,"",0);2472return0;2473}24742475/*2476 * We actually don't even have to worry about reachability here.2477 * add_object_entry will weed out duplicates, so we just add every2478 * loose object we find.2479 */2480static voidadd_unreachable_loose_objects(void)2481{2482for_each_loose_file_in_objdir(get_object_directory(),2483 add_loose_object,2484 NULL, NULL, NULL);2485}24862487static inthas_sha1_pack_kept_or_nonlocal(const unsigned char*sha1)2488{2489static struct packed_git *last_found = (void*)1;2490struct packed_git *p;24912492 p = (last_found != (void*)1) ? last_found : packed_git;24932494while(p) {2495if((!p->pack_local || p->pack_keep) &&2496find_pack_entry_one(sha1, p)) {2497 last_found = p;2498return1;2499}2500if(p == last_found)2501 p = packed_git;2502else2503 p = p->next;2504if(p == last_found)2505 p = p->next;2506}2507return0;2508}25092510/*2511 * Store a list of sha1s that are should not be discarded2512 * because they are either written too recently, or are2513 * reachable from another object that was.2514 *2515 * This is filled by get_object_list.2516 */2517static struct sha1_array recent_objects;25182519static intloosened_object_can_be_discarded(const unsigned char*sha1,2520unsigned long mtime)2521{2522if(!unpack_unreachable_expiration)2523return0;2524if(mtime > unpack_unreachable_expiration)2525return0;2526if(sha1_array_lookup(&recent_objects, sha1) >=0)2527return0;2528return1;2529}25302531static voidloosen_unused_packed_objects(struct rev_info *revs)2532{2533struct packed_git *p;2534uint32_t i;2535const unsigned char*sha1;25362537for(p = packed_git; p; p = p->next) {2538if(!p->pack_local || p->pack_keep)2539continue;25402541if(open_pack_index(p))2542die("cannot open pack index");25432544for(i =0; i < p->num_objects; i++) {2545 sha1 =nth_packed_object_sha1(p, i);2546if(!packlist_find(&to_pack, sha1, NULL) &&2547!has_sha1_pack_kept_or_nonlocal(sha1) &&2548!loosened_object_can_be_discarded(sha1, p->mtime))2549if(force_object_loose(sha1, p->mtime))2550die("unable to force loose object");2551}2552}2553}25542555/*2556 * This tracks any options which pack-reuse code expects to be on, or which a2557 * reader of the pack might not understand, and which would therefore prevent2558 * blind reuse of what we have on disk.2559 */2560static intpack_options_allow_reuse(void)2561{2562return pack_to_stdout && allow_ofs_delta;2563}25642565static intget_object_list_from_bitmap(struct rev_info *revs)2566{2567if(prepare_bitmap_walk(revs) <0)2568return-1;25692570if(pack_options_allow_reuse() &&2571!reuse_partial_packfile_from_bitmap(2572&reuse_packfile,2573&reuse_packfile_objects,2574&reuse_packfile_offset)) {2575assert(reuse_packfile_objects);2576 nr_result += reuse_packfile_objects;2577display_progress(progress_state, nr_result);2578}25792580traverse_bitmap_commit_list(&add_object_entry_from_bitmap);2581return0;2582}25832584static voidrecord_recent_object(struct object *obj,2585const char*name,2586void*data)2587{2588sha1_array_append(&recent_objects, obj->oid.hash);2589}25902591static voidrecord_recent_commit(struct commit *commit,void*data)2592{2593sha1_array_append(&recent_objects, commit->object.oid.hash);2594}25952596static voidget_object_list(int ac,const char**av)2597{2598struct rev_info revs;2599char line[1000];2600int flags =0;26012602init_revisions(&revs, NULL);2603 save_commit_buffer =0;2604setup_revisions(ac, av, &revs, NULL);26052606/* make sure shallows are read */2607is_repository_shallow();26082609while(fgets(line,sizeof(line), stdin) != NULL) {2610int len =strlen(line);2611if(len && line[len -1] =='\n')2612 line[--len] =0;2613if(!len)2614break;2615if(*line =='-') {2616if(!strcmp(line,"--not")) {2617 flags ^= UNINTERESTING;2618 write_bitmap_index =0;2619continue;2620}2621if(starts_with(line,"--shallow ")) {2622unsigned char sha1[20];2623if(get_sha1_hex(line +10, sha1))2624die("not an SHA-1 '%s'", line +10);2625register_shallow(sha1);2626 use_bitmap_index =0;2627continue;2628}2629die("not a rev '%s'", line);2630}2631if(handle_revision_arg(line, &revs, flags, REVARG_CANNOT_BE_FILENAME))2632die("bad revision '%s'", line);2633}26342635if(use_bitmap_index && !get_object_list_from_bitmap(&revs))2636return;26372638if(prepare_revision_walk(&revs))2639die("revision walk setup failed");2640mark_edges_uninteresting(&revs, show_edge);2641traverse_commit_list(&revs, show_commit, show_object, NULL);26422643if(unpack_unreachable_expiration) {2644 revs.ignore_missing_links =1;2645if(add_unseen_recent_objects_to_traversal(&revs,2646 unpack_unreachable_expiration))2647die("unable to add recent objects");2648if(prepare_revision_walk(&revs))2649die("revision walk setup failed");2650traverse_commit_list(&revs, record_recent_commit,2651 record_recent_object, NULL);2652}26532654if(keep_unreachable)2655add_objects_in_unpacked_packs(&revs);2656if(pack_loose_unreachable)2657add_unreachable_loose_objects();2658if(unpack_unreachable)2659loosen_unused_packed_objects(&revs);26602661sha1_array_clear(&recent_objects);2662}26632664static intoption_parse_index_version(const struct option *opt,2665const char*arg,int unset)2666{2667char*c;2668const char*val = arg;2669 pack_idx_opts.version =strtoul(val, &c,10);2670if(pack_idx_opts.version >2)2671die(_("unsupported index version%s"), val);2672if(*c ==','&& c[1])2673 pack_idx_opts.off32_limit =strtoul(c+1, &c,0);2674if(*c || pack_idx_opts.off32_limit &0x80000000)2675die(_("bad index version '%s'"), val);2676return0;2677}26782679static intoption_parse_unpack_unreachable(const struct option *opt,2680const char*arg,int unset)2681{2682if(unset) {2683 unpack_unreachable =0;2684 unpack_unreachable_expiration =0;2685}2686else{2687 unpack_unreachable =1;2688if(arg)2689 unpack_unreachable_expiration =approxidate(arg);2690}2691return0;2692}26932694intcmd_pack_objects(int argc,const char**argv,const char*prefix)2695{2696int use_internal_rev_list =0;2697int thin =0;2698int shallow =0;2699int all_progress_implied =0;2700struct argv_array rp = ARGV_ARRAY_INIT;2701int rev_list_unpacked =0, rev_list_all =0, rev_list_reflog =0;2702int rev_list_index =0;2703struct option pack_objects_options[] = {2704OPT_SET_INT('q',"quiet", &progress,2705N_("do not show progress meter"),0),2706OPT_SET_INT(0,"progress", &progress,2707N_("show progress meter"),1),2708OPT_SET_INT(0,"all-progress", &progress,2709N_("show progress meter during object writing phase"),2),2710OPT_BOOL(0,"all-progress-implied",2711&all_progress_implied,2712N_("similar to --all-progress when progress meter is shown")),2713{ OPTION_CALLBACK,0,"index-version", NULL,N_("version[,offset]"),2714N_("write the pack index file in the specified idx format version"),27150, option_parse_index_version },2716OPT_MAGNITUDE(0,"max-pack-size", &pack_size_limit,2717N_("maximum size of each output pack file")),2718OPT_BOOL(0,"local", &local,2719N_("ignore borrowed objects from alternate object store")),2720OPT_BOOL(0,"incremental", &incremental,2721N_("ignore packed objects")),2722OPT_INTEGER(0,"window", &window,2723N_("limit pack window by objects")),2724OPT_MAGNITUDE(0,"window-memory", &window_memory_limit,2725N_("limit pack window by memory in addition to object limit")),2726OPT_INTEGER(0,"depth", &depth,2727N_("maximum length of delta chain allowed in the resulting pack")),2728OPT_BOOL(0,"reuse-delta", &reuse_delta,2729N_("reuse existing deltas")),2730OPT_BOOL(0,"reuse-object", &reuse_object,2731N_("reuse existing objects")),2732OPT_BOOL(0,"delta-base-offset", &allow_ofs_delta,2733N_("use OFS_DELTA objects")),2734OPT_INTEGER(0,"threads", &delta_search_threads,2735N_("use threads when searching for best delta matches")),2736OPT_BOOL(0,"non-empty", &non_empty,2737N_("do not create an empty pack output")),2738OPT_BOOL(0,"revs", &use_internal_rev_list,2739N_("read revision arguments from standard input")),2740{ OPTION_SET_INT,0,"unpacked", &rev_list_unpacked, NULL,2741N_("limit the objects to those that are not yet packed"),2742 PARSE_OPT_NOARG | PARSE_OPT_NONEG, NULL,1},2743{ OPTION_SET_INT,0,"all", &rev_list_all, NULL,2744N_("include objects reachable from any reference"),2745 PARSE_OPT_NOARG | PARSE_OPT_NONEG, NULL,1},2746{ OPTION_SET_INT,0,"reflog", &rev_list_reflog, NULL,2747N_("include objects referred by reflog entries"),2748 PARSE_OPT_NOARG | PARSE_OPT_NONEG, NULL,1},2749{ OPTION_SET_INT,0,"indexed-objects", &rev_list_index, NULL,2750N_("include objects referred to by the index"),2751 PARSE_OPT_NOARG | PARSE_OPT_NONEG, NULL,1},2752OPT_BOOL(0,"stdout", &pack_to_stdout,2753N_("output pack to stdout")),2754OPT_BOOL(0,"include-tag", &include_tag,2755N_("include tag objects that refer to objects to be packed")),2756OPT_BOOL(0,"keep-unreachable", &keep_unreachable,2757N_("keep unreachable objects")),2758OPT_BOOL(0,"pack-loose-unreachable", &pack_loose_unreachable,2759N_("pack loose unreachable objects")),2760{ OPTION_CALLBACK,0,"unpack-unreachable", NULL,N_("time"),2761N_("unpack unreachable objects newer than <time>"),2762 PARSE_OPT_OPTARG, option_parse_unpack_unreachable },2763OPT_BOOL(0,"thin", &thin,2764N_("create thin packs")),2765OPT_BOOL(0,"shallow", &shallow,2766N_("create packs suitable for shallow fetches")),2767OPT_BOOL(0,"honor-pack-keep", &ignore_packed_keep,2768N_("ignore packs that have companion .keep file")),2769OPT_INTEGER(0,"compression", &pack_compression_level,2770N_("pack compression level")),2771OPT_SET_INT(0,"keep-true-parents", &grafts_replace_parents,2772N_("do not hide commits by grafts"),0),2773OPT_BOOL(0,"use-bitmap-index", &use_bitmap_index,2774N_("use a bitmap index if available to speed up counting objects")),2775OPT_BOOL(0,"write-bitmap-index", &write_bitmap_index,2776N_("write a bitmap index together with the pack index")),2777OPT_END(),2778};27792780 check_replace_refs =0;27812782reset_pack_idx_option(&pack_idx_opts);2783git_config(git_pack_config, NULL);2784if(!pack_compression_seen && core_compression_seen)2785 pack_compression_level = core_compression_level;27862787 progress =isatty(2);2788 argc =parse_options(argc, argv, prefix, pack_objects_options,2789 pack_usage,0);27902791if(argc) {2792 base_name = argv[0];2793 argc--;2794}2795if(pack_to_stdout != !base_name || argc)2796usage_with_options(pack_usage, pack_objects_options);27972798argv_array_push(&rp,"pack-objects");2799if(thin) {2800 use_internal_rev_list =1;2801argv_array_push(&rp, shallow2802?"--objects-edge-aggressive"2803:"--objects-edge");2804}else2805argv_array_push(&rp,"--objects");28062807if(rev_list_all) {2808 use_internal_rev_list =1;2809argv_array_push(&rp,"--all");2810}2811if(rev_list_reflog) {2812 use_internal_rev_list =1;2813argv_array_push(&rp,"--reflog");2814}2815if(rev_list_index) {2816 use_internal_rev_list =1;2817argv_array_push(&rp,"--indexed-objects");2818}2819if(rev_list_unpacked) {2820 use_internal_rev_list =1;2821argv_array_push(&rp,"--unpacked");2822}28232824if(!reuse_object)2825 reuse_delta =0;2826if(pack_compression_level == -1)2827 pack_compression_level = Z_DEFAULT_COMPRESSION;2828else if(pack_compression_level <0|| pack_compression_level > Z_BEST_COMPRESSION)2829die("bad pack compression level%d", pack_compression_level);28302831if(!delta_search_threads)/* --threads=0 means autodetect */2832 delta_search_threads =online_cpus();28332834#ifdef NO_PTHREADS2835if(delta_search_threads !=1)2836warning("no threads support, ignoring --threads");2837#endif2838if(!pack_to_stdout && !pack_size_limit)2839 pack_size_limit = pack_size_limit_cfg;2840if(pack_to_stdout && pack_size_limit)2841die("--max-pack-size cannot be used to build a pack for transfer.");2842if(pack_size_limit && pack_size_limit <1024*1024) {2843warning("minimum pack size limit is 1 MiB");2844 pack_size_limit =1024*1024;2845}28462847if(!pack_to_stdout && thin)2848die("--thin cannot be used to build an indexable pack.");28492850if(keep_unreachable && unpack_unreachable)2851die("--keep-unreachable and --unpack-unreachable are incompatible.");2852if(!rev_list_all || !rev_list_reflog || !rev_list_index)2853 unpack_unreachable_expiration =0;28542855/*2856 * "soft" reasons not to use bitmaps - for on-disk repack by default we want2857 *2858 * - to produce good pack (with bitmap index not-yet-packed objects are2859 * packed in suboptimal order).2860 *2861 * - to use more robust pack-generation codepath (avoiding possible2862 * bugs in bitmap code and possible bitmap index corruption).2863 */2864if(!pack_to_stdout)2865 use_bitmap_index_default =0;28662867if(use_bitmap_index <0)2868 use_bitmap_index = use_bitmap_index_default;28692870/* "hard" reasons not to use bitmaps; these just won't work at all */2871if(!use_internal_rev_list || (!pack_to_stdout && write_bitmap_index) ||is_repository_shallow())2872 use_bitmap_index =0;28732874if(pack_to_stdout || !rev_list_all)2875 write_bitmap_index =0;28762877if(progress && all_progress_implied)2878 progress =2;28792880prepare_packed_git();2881if(ignore_packed_keep) {2882struct packed_git *p;2883for(p = packed_git; p; p = p->next)2884if(p->pack_local && p->pack_keep)2885break;2886if(!p)/* no keep-able packs found */2887 ignore_packed_keep =0;2888}2889if(local) {2890/*2891 * unlike ignore_packed_keep above, we do not want to2892 * unset "local" based on looking at packs, as it2893 * also covers non-local objects2894 */2895struct packed_git *p;2896for(p = packed_git; p; p = p->next) {2897if(!p->pack_local) {2898 have_non_local_packs =1;2899break;2900}2901}2902}29032904if(progress)2905 progress_state =start_progress(_("Counting objects"),0);2906if(!use_internal_rev_list)2907read_object_list_from_stdin();2908else{2909get_object_list(rp.argc, rp.argv);2910argv_array_clear(&rp);2911}2912cleanup_preferred_base();2913if(include_tag && nr_result)2914for_each_ref(add_ref_tag, NULL);2915stop_progress(&progress_state);29162917if(non_empty && !nr_result)2918return0;2919if(nr_result)2920prepare_pack(window, depth);2921write_pack_file();2922if(progress)2923fprintf(stderr,"Total %"PRIu32" (delta %"PRIu32"),"2924" reused %"PRIu32" (delta %"PRIu32")\n",2925 written, written_delta, reused, reused_delta);2926return0;2927}