1#include"builtin.h" 2#include"cache.h" 3#include"attr.h" 4#include"object.h" 5#include"blob.h" 6#include"commit.h" 7#include"tag.h" 8#include"tree.h" 9#include"delta.h" 10#include"pack.h" 11#include"pack-revindex.h" 12#include"csum-file.h" 13#include"tree-walk.h" 14#include"diff.h" 15#include"revision.h" 16#include"list-objects.h" 17#include"pack-objects.h" 18#include"progress.h" 19#include"refs.h" 20#include"streaming.h" 21#include"thread-utils.h" 22#include"pack-bitmap.h" 23#include"reachable.h" 24#include"sha1-array.h" 25#include"argv-array.h" 26#include"mru.h" 27 28static const char*pack_usage[] = { 29N_("git pack-objects --stdout [<options>...] [< <ref-list> | < <object-list>]"), 30N_("git pack-objects [<options>...] <base-name> [< <ref-list> | < <object-list>]"), 31 NULL 32}; 33 34/* 35 * Objects we are going to pack are collected in the `to_pack` structure. 36 * It contains an array (dynamically expanded) of the object data, and a map 37 * that can resolve SHA1s to their position in the array. 38 */ 39static struct packing_data to_pack; 40 41static struct pack_idx_entry **written_list; 42static uint32_t nr_result, nr_written; 43 44static int non_empty; 45static int reuse_delta =1, reuse_object =1; 46static int keep_unreachable, unpack_unreachable, include_tag; 47static timestamp_t unpack_unreachable_expiration; 48static int pack_loose_unreachable; 49static int local; 50static int have_non_local_packs; 51static int incremental; 52static int ignore_packed_keep; 53static int allow_ofs_delta; 54static struct pack_idx_option pack_idx_opts; 55static const char*base_name; 56static int progress =1; 57static int window =10; 58static unsigned long pack_size_limit; 59static int depth =50; 60static int delta_search_threads; 61static int pack_to_stdout; 62static int num_preferred_base; 63static struct progress *progress_state; 64 65static struct packed_git *reuse_packfile; 66static uint32_t reuse_packfile_objects; 67static off_t reuse_packfile_offset; 68 69static int use_bitmap_index_default =1; 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.oid.hash, &type, &size); 110if(!buf) 111die("unable to read%s",oid_to_hex(&entry->idx.oid)); 112 base_buf =read_sha1_file(entry->delta->idx.oid.hash, &type, 113&base_size); 114if(!base_buf) 115die("unable to read%s", 116oid_to_hex(&entry->delta->idx.oid)); 117 delta_buf =diff_delta(base_buf, base_size, 118 buf, size, &delta_size,0); 119if(!delta_buf || delta_size != entry->delta_size) 120die("delta size changed"); 121free(buf); 122free(base_buf); 123return delta_buf; 124} 125 126static unsigned longdo_compress(void**pptr,unsigned long size) 127{ 128 git_zstream stream; 129void*in, *out; 130unsigned long maxsize; 131 132git_deflate_init(&stream, pack_compression_level); 133 maxsize =git_deflate_bound(&stream, size); 134 135 in = *pptr; 136 out =xmalloc(maxsize); 137*pptr = out; 138 139 stream.next_in = in; 140 stream.avail_in = size; 141 stream.next_out = out; 142 stream.avail_out = maxsize; 143while(git_deflate(&stream, Z_FINISH) == Z_OK) 144;/* nothing */ 145git_deflate_end(&stream); 146 147free(in); 148return stream.total_out; 149} 150 151static unsigned longwrite_large_blob_data(struct git_istream *st,struct sha1file *f, 152const unsigned char*sha1) 153{ 154 git_zstream stream; 155unsigned char ibuf[1024*16]; 156unsigned char obuf[1024*16]; 157unsigned long olen =0; 158 159git_deflate_init(&stream, pack_compression_level); 160 161for(;;) { 162 ssize_t readlen; 163int zret = Z_OK; 164 readlen =read_istream(st, ibuf,sizeof(ibuf)); 165if(readlen == -1) 166die(_("unable to read%s"),sha1_to_hex(sha1)); 167 168 stream.next_in = ibuf; 169 stream.avail_in = readlen; 170while((stream.avail_in || readlen ==0) && 171(zret == Z_OK || zret == Z_BUF_ERROR)) { 172 stream.next_out = obuf; 173 stream.avail_out =sizeof(obuf); 174 zret =git_deflate(&stream, readlen ?0: Z_FINISH); 175sha1write(f, obuf, stream.next_out - obuf); 176 olen += stream.next_out - obuf; 177} 178if(stream.avail_in) 179die(_("deflate error (%d)"), zret); 180if(readlen ==0) { 181if(zret != Z_STREAM_END) 182die(_("deflate error (%d)"), zret); 183break; 184} 185} 186git_deflate_end(&stream); 187return olen; 188} 189 190/* 191 * we are going to reuse the existing object data as is. make 192 * sure it is not corrupt. 193 */ 194static intcheck_pack_inflate(struct packed_git *p, 195struct pack_window **w_curs, 196 off_t offset, 197 off_t len, 198unsigned long expect) 199{ 200 git_zstream stream; 201unsigned char fakebuf[4096], *in; 202int st; 203 204memset(&stream,0,sizeof(stream)); 205git_inflate_init(&stream); 206do{ 207 in =use_pack(p, w_curs, offset, &stream.avail_in); 208 stream.next_in = in; 209 stream.next_out = fakebuf; 210 stream.avail_out =sizeof(fakebuf); 211 st =git_inflate(&stream, Z_FINISH); 212 offset += stream.next_in - in; 213}while(st == Z_OK || st == Z_BUF_ERROR); 214git_inflate_end(&stream); 215return(st == Z_STREAM_END && 216 stream.total_out == expect && 217 stream.total_in == len) ?0: -1; 218} 219 220static voidcopy_pack_data(struct sha1file *f, 221struct packed_git *p, 222struct pack_window **w_curs, 223 off_t offset, 224 off_t len) 225{ 226unsigned char*in; 227unsigned long avail; 228 229while(len) { 230 in =use_pack(p, w_curs, offset, &avail); 231if(avail > len) 232 avail = (unsigned long)len; 233sha1write(f, in, avail); 234 offset += avail; 235 len -= avail; 236} 237} 238 239/* Return 0 if we will bust the pack-size limit */ 240static unsigned longwrite_no_reuse_object(struct sha1file *f,struct object_entry *entry, 241unsigned long limit,int usable_delta) 242{ 243unsigned long size, datalen; 244unsigned char header[MAX_PACK_OBJECT_HEADER], 245 dheader[MAX_PACK_OBJECT_HEADER]; 246unsigned hdrlen; 247enum object_type type; 248void*buf; 249struct git_istream *st = NULL; 250 251if(!usable_delta) { 252if(entry->type == OBJ_BLOB && 253 entry->size > big_file_threshold && 254(st =open_istream(entry->idx.oid.hash, &type, &size, NULL)) != NULL) 255 buf = NULL; 256else{ 257 buf =read_sha1_file(entry->idx.oid.hash, &type, 258&size); 259if(!buf) 260die(_("unable to read%s"), 261oid_to_hex(&entry->idx.oid)); 262} 263/* 264 * make sure no cached delta data remains from a 265 * previous attempt before a pack split occurred. 266 */ 267free(entry->delta_data); 268 entry->delta_data = NULL; 269 entry->z_delta_size =0; 270}else if(entry->delta_data) { 271 size = entry->delta_size; 272 buf = entry->delta_data; 273 entry->delta_data = NULL; 274 type = (allow_ofs_delta && entry->delta->idx.offset) ? 275 OBJ_OFS_DELTA : OBJ_REF_DELTA; 276}else{ 277 buf =get_delta(entry); 278 size = entry->delta_size; 279 type = (allow_ofs_delta && entry->delta->idx.offset) ? 280 OBJ_OFS_DELTA : OBJ_REF_DELTA; 281} 282 283if(st)/* large blob case, just assume we don't compress well */ 284 datalen = size; 285else if(entry->z_delta_size) 286 datalen = entry->z_delta_size; 287else 288 datalen =do_compress(&buf, size); 289 290/* 291 * The object header is a byte of 'type' followed by zero or 292 * more bytes of length. 293 */ 294 hdrlen =encode_in_pack_object_header(header,sizeof(header), 295 type, size); 296 297if(type == OBJ_OFS_DELTA) { 298/* 299 * Deltas with relative base contain an additional 300 * encoding of the relative offset for the delta 301 * base from this object's position in the pack. 302 */ 303 off_t ofs = entry->idx.offset - entry->delta->idx.offset; 304unsigned pos =sizeof(dheader) -1; 305 dheader[pos] = ofs &127; 306while(ofs >>=7) 307 dheader[--pos] =128| (--ofs &127); 308if(limit && hdrlen +sizeof(dheader) - pos + datalen +20>= limit) { 309if(st) 310close_istream(st); 311free(buf); 312return0; 313} 314sha1write(f, header, hdrlen); 315sha1write(f, dheader + pos,sizeof(dheader) - pos); 316 hdrlen +=sizeof(dheader) - pos; 317}else if(type == OBJ_REF_DELTA) { 318/* 319 * Deltas with a base reference contain 320 * an additional 20 bytes for the base sha1. 321 */ 322if(limit && hdrlen +20+ datalen +20>= limit) { 323if(st) 324close_istream(st); 325free(buf); 326return0; 327} 328sha1write(f, header, hdrlen); 329sha1write(f, entry->delta->idx.oid.hash,20); 330 hdrlen +=20; 331}else{ 332if(limit && hdrlen + datalen +20>= limit) { 333if(st) 334close_istream(st); 335free(buf); 336return0; 337} 338sha1write(f, header, hdrlen); 339} 340if(st) { 341 datalen =write_large_blob_data(st, f, entry->idx.oid.hash); 342close_istream(st); 343}else{ 344sha1write(f, buf, datalen); 345free(buf); 346} 347 348return hdrlen + datalen; 349} 350 351/* Return 0 if we will bust the pack-size limit */ 352static off_t write_reuse_object(struct sha1file *f,struct object_entry *entry, 353unsigned long limit,int usable_delta) 354{ 355struct packed_git *p = entry->in_pack; 356struct pack_window *w_curs = NULL; 357struct revindex_entry *revidx; 358 off_t offset; 359enum object_type type = entry->type; 360 off_t datalen; 361unsigned char header[MAX_PACK_OBJECT_HEADER], 362 dheader[MAX_PACK_OBJECT_HEADER]; 363unsigned hdrlen; 364 365if(entry->delta) 366 type = (allow_ofs_delta && entry->delta->idx.offset) ? 367 OBJ_OFS_DELTA : OBJ_REF_DELTA; 368 hdrlen =encode_in_pack_object_header(header,sizeof(header), 369 type, entry->size); 370 371 offset = entry->in_pack_offset; 372 revidx =find_pack_revindex(p, offset); 373 datalen = revidx[1].offset - offset; 374if(!pack_to_stdout && p->index_version >1&& 375check_pack_crc(p, &w_curs, offset, datalen, revidx->nr)) { 376error("bad packed object CRC for%s", 377oid_to_hex(&entry->idx.oid)); 378unuse_pack(&w_curs); 379returnwrite_no_reuse_object(f, entry, limit, usable_delta); 380} 381 382 offset += entry->in_pack_header_size; 383 datalen -= entry->in_pack_header_size; 384 385if(!pack_to_stdout && p->index_version ==1&& 386check_pack_inflate(p, &w_curs, offset, datalen, entry->size)) { 387error("corrupt packed object for%s", 388oid_to_hex(&entry->idx.oid)); 389unuse_pack(&w_curs); 390returnwrite_no_reuse_object(f, entry, limit, usable_delta); 391} 392 393if(type == OBJ_OFS_DELTA) { 394 off_t ofs = entry->idx.offset - entry->delta->idx.offset; 395unsigned pos =sizeof(dheader) -1; 396 dheader[pos] = ofs &127; 397while(ofs >>=7) 398 dheader[--pos] =128| (--ofs &127); 399if(limit && hdrlen +sizeof(dheader) - pos + datalen +20>= limit) { 400unuse_pack(&w_curs); 401return0; 402} 403sha1write(f, header, hdrlen); 404sha1write(f, dheader + pos,sizeof(dheader) - pos); 405 hdrlen +=sizeof(dheader) - pos; 406 reused_delta++; 407}else if(type == OBJ_REF_DELTA) { 408if(limit && hdrlen +20+ datalen +20>= limit) { 409unuse_pack(&w_curs); 410return0; 411} 412sha1write(f, header, hdrlen); 413sha1write(f, entry->delta->idx.oid.hash,20); 414 hdrlen +=20; 415 reused_delta++; 416}else{ 417if(limit && hdrlen + datalen +20>= limit) { 418unuse_pack(&w_curs); 419return0; 420} 421sha1write(f, header, hdrlen); 422} 423copy_pack_data(f, p, &w_curs, offset, datalen); 424unuse_pack(&w_curs); 425 reused++; 426return hdrlen + datalen; 427} 428 429/* Return 0 if we will bust the pack-size limit */ 430static off_t write_object(struct sha1file *f, 431struct object_entry *entry, 432 off_t write_offset) 433{ 434unsigned long limit; 435 off_t len; 436int usable_delta, to_reuse; 437 438if(!pack_to_stdout) 439crc32_begin(f); 440 441/* apply size limit if limited packsize and not first object */ 442if(!pack_size_limit || !nr_written) 443 limit =0; 444else if(pack_size_limit <= write_offset) 445/* 446 * the earlier object did not fit the limit; avoid 447 * mistaking this with unlimited (i.e. limit = 0). 448 */ 449 limit =1; 450else 451 limit = pack_size_limit - write_offset; 452 453if(!entry->delta) 454 usable_delta =0;/* no delta */ 455else if(!pack_size_limit) 456 usable_delta =1;/* unlimited packfile */ 457else if(entry->delta->idx.offset == (off_t)-1) 458 usable_delta =0;/* base was written to another pack */ 459else if(entry->delta->idx.offset) 460 usable_delta =1;/* base already exists in this pack */ 461else 462 usable_delta =0;/* base could end up in another pack */ 463 464if(!reuse_object) 465 to_reuse =0;/* explicit */ 466else if(!entry->in_pack) 467 to_reuse =0;/* can't reuse what we don't have */ 468else if(entry->type == OBJ_REF_DELTA || entry->type == OBJ_OFS_DELTA) 469/* check_object() decided it for us ... */ 470 to_reuse = usable_delta; 471/* ... but pack split may override that */ 472else if(entry->type != entry->in_pack_type) 473 to_reuse =0;/* pack has delta which is unusable */ 474else if(entry->delta) 475 to_reuse =0;/* we want to pack afresh */ 476else 477 to_reuse =1;/* we have it in-pack undeltified, 478 * and we do not need to deltify it. 479 */ 480 481if(!to_reuse) 482 len =write_no_reuse_object(f, entry, limit, usable_delta); 483else 484 len =write_reuse_object(f, entry, limit, usable_delta); 485if(!len) 486return0; 487 488if(usable_delta) 489 written_delta++; 490 written++; 491if(!pack_to_stdout) 492 entry->idx.crc32 =crc32_end(f); 493return len; 494} 495 496enum write_one_status { 497 WRITE_ONE_SKIP = -1,/* already written */ 498 WRITE_ONE_BREAK =0,/* writing this will bust the limit; not written */ 499 WRITE_ONE_WRITTEN =1,/* normal */ 500 WRITE_ONE_RECURSIVE =2/* already scheduled to be written */ 501}; 502 503static enum write_one_status write_one(struct sha1file *f, 504struct object_entry *e, 505 off_t *offset) 506{ 507 off_t size; 508int recursing; 509 510/* 511 * we set offset to 1 (which is an impossible value) to mark 512 * the fact that this object is involved in "write its base 513 * first before writing a deltified object" recursion. 514 */ 515 recursing = (e->idx.offset ==1); 516if(recursing) { 517warning("recursive delta detected for object%s", 518oid_to_hex(&e->idx.oid)); 519return WRITE_ONE_RECURSIVE; 520}else if(e->idx.offset || e->preferred_base) { 521/* offset is non zero if object is written already. */ 522return WRITE_ONE_SKIP; 523} 524 525/* if we are deltified, write out base object first. */ 526if(e->delta) { 527 e->idx.offset =1;/* now recurse */ 528switch(write_one(f, e->delta, offset)) { 529case WRITE_ONE_RECURSIVE: 530/* we cannot depend on this one */ 531 e->delta = NULL; 532break; 533default: 534break; 535case WRITE_ONE_BREAK: 536 e->idx.offset = recursing; 537return WRITE_ONE_BREAK; 538} 539} 540 541 e->idx.offset = *offset; 542 size =write_object(f, e, *offset); 543if(!size) { 544 e->idx.offset = recursing; 545return WRITE_ONE_BREAK; 546} 547 written_list[nr_written++] = &e->idx; 548 549/* make sure off_t is sufficiently large not to wrap */ 550if(signed_add_overflows(*offset, size)) 551die("pack too large for current definition of off_t"); 552*offset += size; 553return WRITE_ONE_WRITTEN; 554} 555 556static intmark_tagged(const char*path,const struct object_id *oid,int flag, 557void*cb_data) 558{ 559unsigned char peeled[20]; 560struct object_entry *entry =packlist_find(&to_pack, oid->hash, NULL); 561 562if(entry) 563 entry->tagged =1; 564if(!peel_ref(path, peeled)) { 565 entry =packlist_find(&to_pack, peeled, NULL); 566if(entry) 567 entry->tagged =1; 568} 569return0; 570} 571 572staticinlinevoidadd_to_write_order(struct object_entry **wo, 573unsigned int*endp, 574struct object_entry *e) 575{ 576if(e->filled) 577return; 578 wo[(*endp)++] = e; 579 e->filled =1; 580} 581 582static voidadd_descendants_to_write_order(struct object_entry **wo, 583unsigned int*endp, 584struct object_entry *e) 585{ 586int add_to_order =1; 587while(e) { 588if(add_to_order) { 589struct object_entry *s; 590/* add this node... */ 591add_to_write_order(wo, endp, e); 592/* all its siblings... */ 593for(s = e->delta_sibling; s; s = s->delta_sibling) { 594add_to_write_order(wo, endp, s); 595} 596} 597/* drop down a level to add left subtree nodes if possible */ 598if(e->delta_child) { 599 add_to_order =1; 600 e = e->delta_child; 601}else{ 602 add_to_order =0; 603/* our sibling might have some children, it is next */ 604if(e->delta_sibling) { 605 e = e->delta_sibling; 606continue; 607} 608/* go back to our parent node */ 609 e = e->delta; 610while(e && !e->delta_sibling) { 611/* we're on the right side of a subtree, keep 612 * going up until we can go right again */ 613 e = e->delta; 614} 615if(!e) { 616/* done- we hit our original root node */ 617return; 618} 619/* pass it off to sibling at this level */ 620 e = e->delta_sibling; 621} 622}; 623} 624 625static voidadd_family_to_write_order(struct object_entry **wo, 626unsigned int*endp, 627struct object_entry *e) 628{ 629struct object_entry *root; 630 631for(root = e; root->delta; root = root->delta) 632;/* nothing */ 633add_descendants_to_write_order(wo, endp, root); 634} 635 636static struct object_entry **compute_write_order(void) 637{ 638unsigned int i, wo_end, last_untagged; 639 640struct object_entry **wo; 641struct object_entry *objects = to_pack.objects; 642 643for(i =0; i < to_pack.nr_objects; i++) { 644 objects[i].tagged =0; 645 objects[i].filled =0; 646 objects[i].delta_child = NULL; 647 objects[i].delta_sibling = NULL; 648} 649 650/* 651 * Fully connect delta_child/delta_sibling network. 652 * Make sure delta_sibling is sorted in the original 653 * recency order. 654 */ 655for(i = to_pack.nr_objects; i >0;) { 656struct object_entry *e = &objects[--i]; 657if(!e->delta) 658continue; 659/* Mark me as the first child */ 660 e->delta_sibling = e->delta->delta_child; 661 e->delta->delta_child = e; 662} 663 664/* 665 * Mark objects that are at the tip of tags. 666 */ 667for_each_tag_ref(mark_tagged, NULL); 668 669/* 670 * Give the objects in the original recency order until 671 * we see a tagged tip. 672 */ 673ALLOC_ARRAY(wo, to_pack.nr_objects); 674for(i = wo_end =0; i < to_pack.nr_objects; i++) { 675if(objects[i].tagged) 676break; 677add_to_write_order(wo, &wo_end, &objects[i]); 678} 679 last_untagged = i; 680 681/* 682 * Then fill all the tagged tips. 683 */ 684for(; i < to_pack.nr_objects; i++) { 685if(objects[i].tagged) 686add_to_write_order(wo, &wo_end, &objects[i]); 687} 688 689/* 690 * And then all remaining commits and tags. 691 */ 692for(i = last_untagged; i < to_pack.nr_objects; i++) { 693if(objects[i].type != OBJ_COMMIT && 694 objects[i].type != OBJ_TAG) 695continue; 696add_to_write_order(wo, &wo_end, &objects[i]); 697} 698 699/* 700 * And then all the trees. 701 */ 702for(i = last_untagged; i < to_pack.nr_objects; i++) { 703if(objects[i].type != OBJ_TREE) 704continue; 705add_to_write_order(wo, &wo_end, &objects[i]); 706} 707 708/* 709 * Finally all the rest in really tight order 710 */ 711for(i = last_untagged; i < to_pack.nr_objects; i++) { 712if(!objects[i].filled) 713add_family_to_write_order(wo, &wo_end, &objects[i]); 714} 715 716if(wo_end != to_pack.nr_objects) 717die("ordered%uobjects, expected %"PRIu32, wo_end, to_pack.nr_objects); 718 719return wo; 720} 721 722static off_t write_reused_pack(struct sha1file *f) 723{ 724unsigned char buffer[8192]; 725 off_t to_write, total; 726int fd; 727 728if(!is_pack_valid(reuse_packfile)) 729die("packfile is invalid:%s", reuse_packfile->pack_name); 730 731 fd =git_open(reuse_packfile->pack_name); 732if(fd <0) 733die_errno("unable to open packfile for reuse:%s", 734 reuse_packfile->pack_name); 735 736if(lseek(fd,sizeof(struct pack_header), SEEK_SET) == -1) 737die_errno("unable to seek in reused packfile"); 738 739if(reuse_packfile_offset <0) 740 reuse_packfile_offset = reuse_packfile->pack_size -20; 741 742 total = to_write = reuse_packfile_offset -sizeof(struct pack_header); 743 744while(to_write) { 745int read_pack =xread(fd, buffer,sizeof(buffer)); 746 747if(read_pack <=0) 748die_errno("unable to read from reused packfile"); 749 750if(read_pack > to_write) 751 read_pack = to_write; 752 753sha1write(f, buffer, read_pack); 754 to_write -= read_pack; 755 756/* 757 * We don't know the actual number of objects written, 758 * only how many bytes written, how many bytes total, and 759 * how many objects total. So we can fake it by pretending all 760 * objects we are writing are the same size. This gives us a 761 * smooth progress meter, and at the end it matches the true 762 * answer. 763 */ 764 written = reuse_packfile_objects * 765(((double)(total - to_write)) / total); 766display_progress(progress_state, written); 767} 768 769close(fd); 770 written = reuse_packfile_objects; 771display_progress(progress_state, written); 772return reuse_packfile_offset -sizeof(struct pack_header); 773} 774 775static const char no_split_warning[] =N_( 776"disabling bitmap writing, packs are split due to pack.packSizeLimit" 777); 778 779static voidwrite_pack_file(void) 780{ 781uint32_t i =0, j; 782struct sha1file *f; 783 off_t offset; 784uint32_t nr_remaining = nr_result; 785time_t last_mtime =0; 786struct object_entry **write_order; 787 788if(progress > pack_to_stdout) 789 progress_state =start_progress(_("Writing objects"), nr_result); 790ALLOC_ARRAY(written_list, to_pack.nr_objects); 791 write_order =compute_write_order(); 792 793do{ 794unsigned char sha1[20]; 795char*pack_tmp_name = NULL; 796 797if(pack_to_stdout) 798 f =sha1fd_throughput(1,"<stdout>", progress_state); 799else 800 f =create_tmp_packfile(&pack_tmp_name); 801 802 offset =write_pack_header(f, nr_remaining); 803 804if(reuse_packfile) { 805 off_t packfile_size; 806assert(pack_to_stdout); 807 808 packfile_size =write_reused_pack(f); 809 offset += packfile_size; 810} 811 812 nr_written =0; 813for(; i < to_pack.nr_objects; i++) { 814struct object_entry *e = write_order[i]; 815if(write_one(f, e, &offset) == WRITE_ONE_BREAK) 816break; 817display_progress(progress_state, written); 818} 819 820/* 821 * Did we write the wrong # entries in the header? 822 * If so, rewrite it like in fast-import 823 */ 824if(pack_to_stdout) { 825sha1close(f, sha1, CSUM_CLOSE); 826}else if(nr_written == nr_remaining) { 827sha1close(f, sha1, CSUM_FSYNC); 828}else{ 829int fd =sha1close(f, sha1,0); 830fixup_pack_header_footer(fd, sha1, pack_tmp_name, 831 nr_written, sha1, offset); 832close(fd); 833if(write_bitmap_index) { 834warning(_(no_split_warning)); 835 write_bitmap_index =0; 836} 837} 838 839if(!pack_to_stdout) { 840struct stat st; 841struct strbuf tmpname = STRBUF_INIT; 842 843/* 844 * Packs are runtime accessed in their mtime 845 * order since newer packs are more likely to contain 846 * younger objects. So if we are creating multiple 847 * packs then we should modify the mtime of later ones 848 * to preserve this property. 849 */ 850if(stat(pack_tmp_name, &st) <0) { 851warning_errno("failed to stat%s", pack_tmp_name); 852}else if(!last_mtime) { 853 last_mtime = st.st_mtime; 854}else{ 855struct utimbuf utb; 856 utb.actime = st.st_atime; 857 utb.modtime = --last_mtime; 858if(utime(pack_tmp_name, &utb) <0) 859warning_errno("failed utime() on%s", pack_tmp_name); 860} 861 862strbuf_addf(&tmpname,"%s-", base_name); 863 864if(write_bitmap_index) { 865bitmap_writer_set_checksum(sha1); 866bitmap_writer_build_type_index(written_list, nr_written); 867} 868 869finish_tmp_packfile(&tmpname, pack_tmp_name, 870 written_list, nr_written, 871&pack_idx_opts, sha1); 872 873if(write_bitmap_index) { 874strbuf_addf(&tmpname,"%s.bitmap",sha1_to_hex(sha1)); 875 876stop_progress(&progress_state); 877 878bitmap_writer_show_progress(progress); 879bitmap_writer_reuse_bitmaps(&to_pack); 880bitmap_writer_select_commits(indexed_commits, indexed_commits_nr, -1); 881bitmap_writer_build(&to_pack); 882bitmap_writer_finish(written_list, nr_written, 883 tmpname.buf, write_bitmap_options); 884 write_bitmap_index =0; 885} 886 887strbuf_release(&tmpname); 888free(pack_tmp_name); 889puts(sha1_to_hex(sha1)); 890} 891 892/* mark written objects as written to previous pack */ 893for(j =0; j < nr_written; j++) { 894 written_list[j]->offset = (off_t)-1; 895} 896 nr_remaining -= nr_written; 897}while(nr_remaining && i < to_pack.nr_objects); 898 899free(written_list); 900free(write_order); 901stop_progress(&progress_state); 902if(written != nr_result) 903die("wrote %"PRIu32" objects while expecting %"PRIu32, 904 written, nr_result); 905} 906 907static intno_try_delta(const char*path) 908{ 909static struct attr_check *check; 910 911if(!check) 912 check =attr_check_initl("delta", NULL); 913if(git_check_attr(path, check)) 914return0; 915if(ATTR_FALSE(check->items[0].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 mru_entry *entry; 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(entry = packed_git_mru->head; entry; entry = entry->next) {1015struct packed_git *p = entry->item;1016 off_t offset;10171018if(p == *found_pack)1019 offset = *found_offset;1020else1021 offset =find_pack_entry_one(sha1, p);10221023if(offset) {1024if(!*found_pack) {1025if(!is_pack_valid(p))1026continue;1027*found_offset = offset;1028*found_pack = p;1029}1030 want =want_found_object(exclude, p);1031if(!exclude && want >0)1032mru_mark(packed_git_mru, entry);1033if(want != -1)1034return want;1035}1036}10371038return1;1039}10401041static voidcreate_object_entry(const unsigned char*sha1,1042enum object_type type,1043uint32_t hash,1044int exclude,1045int no_try_delta,1046uint32_t index_pos,1047struct packed_git *found_pack,1048 off_t found_offset)1049{1050struct object_entry *entry;10511052 entry =packlist_alloc(&to_pack, sha1, index_pos);1053 entry->hash = hash;1054if(type)1055 entry->type = type;1056if(exclude)1057 entry->preferred_base =1;1058else1059 nr_result++;1060if(found_pack) {1061 entry->in_pack = found_pack;1062 entry->in_pack_offset = found_offset;1063}10641065 entry->no_try_delta = no_try_delta;1066}10671068static const char no_closure_warning[] =N_(1069"disabling bitmap writing, as some objects are not being packed"1070);10711072static intadd_object_entry(const unsigned char*sha1,enum object_type type,1073const char*name,int exclude)1074{1075struct packed_git *found_pack = NULL;1076 off_t found_offset =0;1077uint32_t index_pos;10781079if(have_duplicate_entry(sha1, exclude, &index_pos))1080return0;10811082if(!want_object_in_pack(sha1, exclude, &found_pack, &found_offset)) {1083/* The pack is missing an object, so it will not have closure */1084if(write_bitmap_index) {1085warning(_(no_closure_warning));1086 write_bitmap_index =0;1087}1088return0;1089}10901091create_object_entry(sha1, type,pack_name_hash(name),1092 exclude, name &&no_try_delta(name),1093 index_pos, found_pack, found_offset);10941095display_progress(progress_state, nr_result);1096return1;1097}10981099static intadd_object_entry_from_bitmap(const unsigned char*sha1,1100enum object_type type,1101int flags,uint32_t name_hash,1102struct packed_git *pack, off_t offset)1103{1104uint32_t index_pos;11051106if(have_duplicate_entry(sha1,0, &index_pos))1107return0;11081109if(!want_object_in_pack(sha1,0, &pack, &offset))1110return0;11111112create_object_entry(sha1, type, name_hash,0,0, index_pos, pack, offset);11131114display_progress(progress_state, nr_result);1115return1;1116}11171118struct pbase_tree_cache {1119unsigned char sha1[20];1120int ref;1121int temporary;1122void*tree_data;1123unsigned long tree_size;1124};11251126static struct pbase_tree_cache *(pbase_tree_cache[256]);1127static intpbase_tree_cache_ix(const unsigned char*sha1)1128{1129return sha1[0] %ARRAY_SIZE(pbase_tree_cache);1130}1131static intpbase_tree_cache_ix_incr(int ix)1132{1133return(ix+1) %ARRAY_SIZE(pbase_tree_cache);1134}11351136static struct pbase_tree {1137struct pbase_tree *next;1138/* This is a phony "cache" entry; we are not1139 * going to evict it or find it through _get()1140 * mechanism -- this is for the toplevel node that1141 * would almost always change with any commit.1142 */1143struct pbase_tree_cache pcache;1144} *pbase_tree;11451146static struct pbase_tree_cache *pbase_tree_get(const unsigned char*sha1)1147{1148struct pbase_tree_cache *ent, *nent;1149void*data;1150unsigned long size;1151enum object_type type;1152int neigh;1153int my_ix =pbase_tree_cache_ix(sha1);1154int available_ix = -1;11551156/* pbase-tree-cache acts as a limited hashtable.1157 * your object will be found at your index or within a few1158 * slots after that slot if it is cached.1159 */1160for(neigh =0; neigh <8; neigh++) {1161 ent = pbase_tree_cache[my_ix];1162if(ent && !hashcmp(ent->sha1, sha1)) {1163 ent->ref++;1164return ent;1165}1166else if(((available_ix <0) && (!ent || !ent->ref)) ||1167((0<= available_ix) &&1168(!ent && pbase_tree_cache[available_ix])))1169 available_ix = my_ix;1170if(!ent)1171break;1172 my_ix =pbase_tree_cache_ix_incr(my_ix);1173}11741175/* Did not find one. Either we got a bogus request or1176 * we need to read and perhaps cache.1177 */1178 data =read_sha1_file(sha1, &type, &size);1179if(!data)1180return NULL;1181if(type != OBJ_TREE) {1182free(data);1183return NULL;1184}11851186/* We need to either cache or return a throwaway copy */11871188if(available_ix <0)1189 ent = NULL;1190else{1191 ent = pbase_tree_cache[available_ix];1192 my_ix = available_ix;1193}11941195if(!ent) {1196 nent =xmalloc(sizeof(*nent));1197 nent->temporary = (available_ix <0);1198}1199else{1200/* evict and reuse */1201free(ent->tree_data);1202 nent = ent;1203}1204hashcpy(nent->sha1, sha1);1205 nent->tree_data = data;1206 nent->tree_size = size;1207 nent->ref =1;1208if(!nent->temporary)1209 pbase_tree_cache[my_ix] = nent;1210return nent;1211}12121213static voidpbase_tree_put(struct pbase_tree_cache *cache)1214{1215if(!cache->temporary) {1216 cache->ref--;1217return;1218}1219free(cache->tree_data);1220free(cache);1221}12221223static intname_cmp_len(const char*name)1224{1225int i;1226for(i =0; name[i] && name[i] !='\n'&& name[i] !='/'; i++)1227;1228return i;1229}12301231static voidadd_pbase_object(struct tree_desc *tree,1232const char*name,1233int cmplen,1234const char*fullname)1235{1236struct name_entry entry;1237int cmp;12381239while(tree_entry(tree,&entry)) {1240if(S_ISGITLINK(entry.mode))1241continue;1242 cmp =tree_entry_len(&entry) != cmplen ?1:1243memcmp(name, entry.path, cmplen);1244if(cmp >0)1245continue;1246if(cmp <0)1247return;1248if(name[cmplen] !='/') {1249add_object_entry(entry.oid->hash,1250object_type(entry.mode),1251 fullname,1);1252return;1253}1254if(S_ISDIR(entry.mode)) {1255struct tree_desc sub;1256struct pbase_tree_cache *tree;1257const char*down = name+cmplen+1;1258int downlen =name_cmp_len(down);12591260 tree =pbase_tree_get(entry.oid->hash);1261if(!tree)1262return;1263init_tree_desc(&sub, tree->tree_data, tree->tree_size);12641265add_pbase_object(&sub, down, downlen, fullname);1266pbase_tree_put(tree);1267}1268}1269}12701271static unsigned*done_pbase_paths;1272static int done_pbase_paths_num;1273static int done_pbase_paths_alloc;1274static intdone_pbase_path_pos(unsigned hash)1275{1276int lo =0;1277int hi = done_pbase_paths_num;1278while(lo < hi) {1279int mi = (hi + lo) /2;1280if(done_pbase_paths[mi] == hash)1281return mi;1282if(done_pbase_paths[mi] < hash)1283 hi = mi;1284else1285 lo = mi +1;1286}1287return-lo-1;1288}12891290static intcheck_pbase_path(unsigned hash)1291{1292int pos = (!done_pbase_paths) ? -1:done_pbase_path_pos(hash);1293if(0<= pos)1294return1;1295 pos = -pos -1;1296ALLOC_GROW(done_pbase_paths,1297 done_pbase_paths_num +1,1298 done_pbase_paths_alloc);1299 done_pbase_paths_num++;1300if(pos < done_pbase_paths_num)1301memmove(done_pbase_paths + pos +1,1302 done_pbase_paths + pos,1303(done_pbase_paths_num - pos -1) *sizeof(unsigned));1304 done_pbase_paths[pos] = hash;1305return0;1306}13071308static voidadd_preferred_base_object(const char*name)1309{1310struct pbase_tree *it;1311int cmplen;1312unsigned hash =pack_name_hash(name);13131314if(!num_preferred_base ||check_pbase_path(hash))1315return;13161317 cmplen =name_cmp_len(name);1318for(it = pbase_tree; it; it = it->next) {1319if(cmplen ==0) {1320add_object_entry(it->pcache.sha1, OBJ_TREE, NULL,1);1321}1322else{1323struct tree_desc tree;1324init_tree_desc(&tree, it->pcache.tree_data, it->pcache.tree_size);1325add_pbase_object(&tree, name, cmplen, name);1326}1327}1328}13291330static voidadd_preferred_base(unsigned char*sha1)1331{1332struct pbase_tree *it;1333void*data;1334unsigned long size;1335unsigned char tree_sha1[20];13361337if(window <= num_preferred_base++)1338return;13391340 data =read_object_with_reference(sha1, tree_type, &size, tree_sha1);1341if(!data)1342return;13431344for(it = pbase_tree; it; it = it->next) {1345if(!hashcmp(it->pcache.sha1, tree_sha1)) {1346free(data);1347return;1348}1349}13501351 it =xcalloc(1,sizeof(*it));1352 it->next = pbase_tree;1353 pbase_tree = it;13541355hashcpy(it->pcache.sha1, tree_sha1);1356 it->pcache.tree_data = data;1357 it->pcache.tree_size = size;1358}13591360static voidcleanup_preferred_base(void)1361{1362struct pbase_tree *it;1363unsigned i;13641365 it = pbase_tree;1366 pbase_tree = NULL;1367while(it) {1368struct pbase_tree *this= it;1369 it =this->next;1370free(this->pcache.tree_data);1371free(this);1372}13731374for(i =0; i <ARRAY_SIZE(pbase_tree_cache); i++) {1375if(!pbase_tree_cache[i])1376continue;1377free(pbase_tree_cache[i]->tree_data);1378free(pbase_tree_cache[i]);1379 pbase_tree_cache[i] = NULL;1380}13811382free(done_pbase_paths);1383 done_pbase_paths = NULL;1384 done_pbase_paths_num = done_pbase_paths_alloc =0;1385}13861387static voidcheck_object(struct object_entry *entry)1388{1389if(entry->in_pack) {1390struct packed_git *p = entry->in_pack;1391struct pack_window *w_curs = NULL;1392const unsigned char*base_ref = NULL;1393struct object_entry *base_entry;1394unsigned long used, used_0;1395unsigned long avail;1396 off_t ofs;1397unsigned char*buf, c;13981399 buf =use_pack(p, &w_curs, entry->in_pack_offset, &avail);14001401/*1402 * We want in_pack_type even if we do not reuse delta1403 * since non-delta representations could still be reused.1404 */1405 used =unpack_object_header_buffer(buf, avail,1406&entry->in_pack_type,1407&entry->size);1408if(used ==0)1409goto give_up;14101411/*1412 * Determine if this is a delta and if so whether we can1413 * reuse it or not. Otherwise let's find out as cheaply as1414 * possible what the actual type and size for this object is.1415 */1416switch(entry->in_pack_type) {1417default:1418/* Not a delta hence we've already got all we need. */1419 entry->type = entry->in_pack_type;1420 entry->in_pack_header_size = used;1421if(entry->type < OBJ_COMMIT || entry->type > OBJ_BLOB)1422goto give_up;1423unuse_pack(&w_curs);1424return;1425case OBJ_REF_DELTA:1426if(reuse_delta && !entry->preferred_base)1427 base_ref =use_pack(p, &w_curs,1428 entry->in_pack_offset + used, NULL);1429 entry->in_pack_header_size = used +20;1430break;1431case OBJ_OFS_DELTA:1432 buf =use_pack(p, &w_curs,1433 entry->in_pack_offset + used, NULL);1434 used_0 =0;1435 c = buf[used_0++];1436 ofs = c &127;1437while(c &128) {1438 ofs +=1;1439if(!ofs ||MSB(ofs,7)) {1440error("delta base offset overflow in pack for%s",1441oid_to_hex(&entry->idx.oid));1442goto give_up;1443}1444 c = buf[used_0++];1445 ofs = (ofs <<7) + (c &127);1446}1447 ofs = entry->in_pack_offset - ofs;1448if(ofs <=0|| ofs >= entry->in_pack_offset) {1449error("delta base offset out of bound for%s",1450oid_to_hex(&entry->idx.oid));1451goto give_up;1452}1453if(reuse_delta && !entry->preferred_base) {1454struct revindex_entry *revidx;1455 revidx =find_pack_revindex(p, ofs);1456if(!revidx)1457goto give_up;1458 base_ref =nth_packed_object_sha1(p, revidx->nr);1459}1460 entry->in_pack_header_size = used + used_0;1461break;1462}14631464if(base_ref && (base_entry =packlist_find(&to_pack, base_ref, NULL))) {1465/*1466 * If base_ref was set above that means we wish to1467 * reuse delta data, and we even found that base1468 * in the list of objects we want to pack. Goodie!1469 *1470 * Depth value does not matter - find_deltas() will1471 * never consider reused delta as the base object to1472 * deltify other objects against, in order to avoid1473 * circular deltas.1474 */1475 entry->type = entry->in_pack_type;1476 entry->delta = base_entry;1477 entry->delta_size = entry->size;1478 entry->delta_sibling = base_entry->delta_child;1479 base_entry->delta_child = entry;1480unuse_pack(&w_curs);1481return;1482}14831484if(entry->type) {1485/*1486 * This must be a delta and we already know what the1487 * final object type is. Let's extract the actual1488 * object size from the delta header.1489 */1490 entry->size =get_size_from_delta(p, &w_curs,1491 entry->in_pack_offset + entry->in_pack_header_size);1492if(entry->size ==0)1493goto give_up;1494unuse_pack(&w_curs);1495return;1496}14971498/*1499 * No choice but to fall back to the recursive delta walk1500 * with sha1_object_info() to find about the object type1501 * at this point...1502 */1503 give_up:1504unuse_pack(&w_curs);1505}15061507 entry->type =sha1_object_info(entry->idx.oid.hash, &entry->size);1508/*1509 * The error condition is checked in prepare_pack(). This is1510 * to permit a missing preferred base object to be ignored1511 * as a preferred base. Doing so can result in a larger1512 * pack file, but the transfer will still take place.1513 */1514}15151516static intpack_offset_sort(const void*_a,const void*_b)1517{1518const struct object_entry *a = *(struct object_entry **)_a;1519const struct object_entry *b = *(struct object_entry **)_b;15201521/* avoid filesystem trashing with loose objects */1522if(!a->in_pack && !b->in_pack)1523returnoidcmp(&a->idx.oid, &b->idx.oid);15241525if(a->in_pack < b->in_pack)1526return-1;1527if(a->in_pack > b->in_pack)1528return1;1529return a->in_pack_offset < b->in_pack_offset ? -1:1530(a->in_pack_offset > b->in_pack_offset);1531}15321533/*1534 * Drop an on-disk delta we were planning to reuse. Naively, this would1535 * just involve blanking out the "delta" field, but we have to deal1536 * with some extra book-keeping:1537 *1538 * 1. Removing ourselves from the delta_sibling linked list.1539 *1540 * 2. Updating our size/type to the non-delta representation. These were1541 * either not recorded initially (size) or overwritten with the delta type1542 * (type) when check_object() decided to reuse the delta.1543 *1544 * 3. Resetting our delta depth, as we are now a base object.1545 */1546static voiddrop_reused_delta(struct object_entry *entry)1547{1548struct object_entry **p = &entry->delta->delta_child;1549struct object_info oi = OBJECT_INFO_INIT;15501551while(*p) {1552if(*p == entry)1553*p = (*p)->delta_sibling;1554else1555 p = &(*p)->delta_sibling;1556}1557 entry->delta = NULL;1558 entry->depth =0;15591560 oi.sizep = &entry->size;1561 oi.typep = &entry->type;1562if(packed_object_info(entry->in_pack, entry->in_pack_offset, &oi) <0) {1563/*1564 * We failed to get the info from this pack for some reason;1565 * fall back to sha1_object_info, which may find another copy.1566 * And if that fails, the error will be recorded in entry->type1567 * and dealt with in prepare_pack().1568 */1569 entry->type =sha1_object_info(entry->idx.oid.hash,1570&entry->size);1571}1572}15731574/*1575 * Follow the chain of deltas from this entry onward, throwing away any links1576 * that cause us to hit a cycle (as determined by the DFS state flags in1577 * the entries).1578 *1579 * We also detect too-long reused chains that would violate our --depth1580 * limit.1581 */1582static voidbreak_delta_chains(struct object_entry *entry)1583{1584/*1585 * The actual depth of each object we will write is stored as an int,1586 * as it cannot exceed our int "depth" limit. But before we break1587 * changes based no that limit, we may potentially go as deep as the1588 * number of objects, which is elsewhere bounded to a uint32_t.1589 */1590uint32_t total_depth;1591struct object_entry *cur, *next;15921593for(cur = entry, total_depth =0;1594 cur;1595 cur = cur->delta, total_depth++) {1596if(cur->dfs_state == DFS_DONE) {1597/*1598 * We've already seen this object and know it isn't1599 * part of a cycle. We do need to append its depth1600 * to our count.1601 */1602 total_depth += cur->depth;1603break;1604}16051606/*1607 * We break cycles before looping, so an ACTIVE state (or any1608 * other cruft which made its way into the state variable)1609 * is a bug.1610 */1611if(cur->dfs_state != DFS_NONE)1612die("BUG: confusing delta dfs state in first pass:%d",1613 cur->dfs_state);16141615/*1616 * Now we know this is the first time we've seen the object. If1617 * it's not a delta, we're done traversing, but we'll mark it1618 * done to save time on future traversals.1619 */1620if(!cur->delta) {1621 cur->dfs_state = DFS_DONE;1622break;1623}16241625/*1626 * Mark ourselves as active and see if the next step causes1627 * us to cycle to another active object. It's important to do1628 * this _before_ we loop, because it impacts where we make the1629 * cut, and thus how our total_depth counter works.1630 * E.g., We may see a partial loop like:1631 *1632 * A -> B -> C -> D -> B1633 *1634 * Cutting B->C breaks the cycle. But now the depth of A is1635 * only 1, and our total_depth counter is at 3. The size of the1636 * error is always one less than the size of the cycle we1637 * broke. Commits C and D were "lost" from A's chain.1638 *1639 * If we instead cut D->B, then the depth of A is correct at 3.1640 * We keep all commits in the chain that we examined.1641 */1642 cur->dfs_state = DFS_ACTIVE;1643if(cur->delta->dfs_state == DFS_ACTIVE) {1644drop_reused_delta(cur);1645 cur->dfs_state = DFS_DONE;1646break;1647}1648}16491650/*1651 * And now that we've gone all the way to the bottom of the chain, we1652 * need to clear the active flags and set the depth fields as1653 * appropriate. Unlike the loop above, which can quit when it drops a1654 * delta, we need to keep going to look for more depth cuts. So we need1655 * an extra "next" pointer to keep going after we reset cur->delta.1656 */1657for(cur = entry; cur; cur = next) {1658 next = cur->delta;16591660/*1661 * We should have a chain of zero or more ACTIVE states down to1662 * a final DONE. We can quit after the DONE, because either it1663 * has no bases, or we've already handled them in a previous1664 * call.1665 */1666if(cur->dfs_state == DFS_DONE)1667break;1668else if(cur->dfs_state != DFS_ACTIVE)1669die("BUG: confusing delta dfs state in second pass:%d",1670 cur->dfs_state);16711672/*1673 * If the total_depth is more than depth, then we need to snip1674 * the chain into two or more smaller chains that don't exceed1675 * the maximum depth. Most of the resulting chains will contain1676 * (depth + 1) entries (i.e., depth deltas plus one base), and1677 * the last chain (i.e., the one containing entry) will contain1678 * whatever entries are left over, namely1679 * (total_depth % (depth + 1)) of them.1680 *1681 * Since we are iterating towards decreasing depth, we need to1682 * decrement total_depth as we go, and we need to write to the1683 * entry what its final depth will be after all of the1684 * snipping. Since we're snipping into chains of length (depth1685 * + 1) entries, the final depth of an entry will be its1686 * original depth modulo (depth + 1). Any time we encounter an1687 * entry whose final depth is supposed to be zero, we snip it1688 * from its delta base, thereby making it so.1689 */1690 cur->depth = (total_depth--) % (depth +1);1691if(!cur->depth)1692drop_reused_delta(cur);16931694 cur->dfs_state = DFS_DONE;1695}1696}16971698static voidget_object_details(void)1699{1700uint32_t i;1701struct object_entry **sorted_by_offset;17021703 sorted_by_offset =xcalloc(to_pack.nr_objects,sizeof(struct object_entry *));1704for(i =0; i < to_pack.nr_objects; i++)1705 sorted_by_offset[i] = to_pack.objects + i;1706QSORT(sorted_by_offset, to_pack.nr_objects, pack_offset_sort);17071708for(i =0; i < to_pack.nr_objects; i++) {1709struct object_entry *entry = sorted_by_offset[i];1710check_object(entry);1711if(big_file_threshold < entry->size)1712 entry->no_try_delta =1;1713}17141715/*1716 * This must happen in a second pass, since we rely on the delta1717 * information for the whole list being completed.1718 */1719for(i =0; i < to_pack.nr_objects; i++)1720break_delta_chains(&to_pack.objects[i]);17211722free(sorted_by_offset);1723}17241725/*1726 * We search for deltas in a list sorted by type, by filename hash, and then1727 * by size, so that we see progressively smaller and smaller files.1728 * That's because we prefer deltas to be from the bigger file1729 * to the smaller -- deletes are potentially cheaper, but perhaps1730 * more importantly, the bigger file is likely the more recent1731 * one. The deepest deltas are therefore the oldest objects which are1732 * less susceptible to be accessed often.1733 */1734static inttype_size_sort(const void*_a,const void*_b)1735{1736const struct object_entry *a = *(struct object_entry **)_a;1737const struct object_entry *b = *(struct object_entry **)_b;17381739if(a->type > b->type)1740return-1;1741if(a->type < b->type)1742return1;1743if(a->hash > b->hash)1744return-1;1745if(a->hash < b->hash)1746return1;1747if(a->preferred_base > b->preferred_base)1748return-1;1749if(a->preferred_base < b->preferred_base)1750return1;1751if(a->size > b->size)1752return-1;1753if(a->size < b->size)1754return1;1755return a < b ? -1: (a > b);/* newest first */1756}17571758struct unpacked {1759struct object_entry *entry;1760void*data;1761struct delta_index *index;1762unsigned depth;1763};17641765static intdelta_cacheable(unsigned long src_size,unsigned long trg_size,1766unsigned long delta_size)1767{1768if(max_delta_cache_size && delta_cache_size + delta_size > max_delta_cache_size)1769return0;17701771if(delta_size < cache_max_small_delta_size)1772return1;17731774/* cache delta, if objects are large enough compared to delta size */1775if((src_size >>20) + (trg_size >>21) > (delta_size >>10))1776return1;17771778return0;1779}17801781#ifndef NO_PTHREADS17821783static pthread_mutex_t read_mutex;1784#define read_lock() pthread_mutex_lock(&read_mutex)1785#define read_unlock() pthread_mutex_unlock(&read_mutex)17861787static pthread_mutex_t cache_mutex;1788#define cache_lock() pthread_mutex_lock(&cache_mutex)1789#define cache_unlock() pthread_mutex_unlock(&cache_mutex)17901791static pthread_mutex_t progress_mutex;1792#define progress_lock() pthread_mutex_lock(&progress_mutex)1793#define progress_unlock() pthread_mutex_unlock(&progress_mutex)17941795#else17961797#define read_lock() (void)01798#define read_unlock() (void)01799#define cache_lock() (void)01800#define cache_unlock() (void)01801#define progress_lock() (void)01802#define progress_unlock() (void)018031804#endif18051806static inttry_delta(struct unpacked *trg,struct unpacked *src,1807unsigned max_depth,unsigned long*mem_usage)1808{1809struct object_entry *trg_entry = trg->entry;1810struct object_entry *src_entry = src->entry;1811unsigned long trg_size, src_size, delta_size, sizediff, max_size, sz;1812unsigned ref_depth;1813enum object_type type;1814void*delta_buf;18151816/* Don't bother doing diffs between different types */1817if(trg_entry->type != src_entry->type)1818return-1;18191820/*1821 * We do not bother to try a delta that we discarded on an1822 * earlier try, but only when reusing delta data. Note that1823 * src_entry that is marked as the preferred_base should always1824 * be considered, as even if we produce a suboptimal delta against1825 * it, we will still save the transfer cost, as we already know1826 * the other side has it and we won't send src_entry at all.1827 */1828if(reuse_delta && trg_entry->in_pack &&1829 trg_entry->in_pack == src_entry->in_pack &&1830!src_entry->preferred_base &&1831 trg_entry->in_pack_type != OBJ_REF_DELTA &&1832 trg_entry->in_pack_type != OBJ_OFS_DELTA)1833return0;18341835/* Let's not bust the allowed depth. */1836if(src->depth >= max_depth)1837return0;18381839/* Now some size filtering heuristics. */1840 trg_size = trg_entry->size;1841if(!trg_entry->delta) {1842 max_size = trg_size/2-20;1843 ref_depth =1;1844}else{1845 max_size = trg_entry->delta_size;1846 ref_depth = trg->depth;1847}1848 max_size = (uint64_t)max_size * (max_depth - src->depth) /1849(max_depth - ref_depth +1);1850if(max_size ==0)1851return0;1852 src_size = src_entry->size;1853 sizediff = src_size < trg_size ? trg_size - src_size :0;1854if(sizediff >= max_size)1855return0;1856if(trg_size < src_size /32)1857return0;18581859/* Load data if not already done */1860if(!trg->data) {1861read_lock();1862 trg->data =read_sha1_file(trg_entry->idx.oid.hash, &type,1863&sz);1864read_unlock();1865if(!trg->data)1866die("object%scannot be read",1867oid_to_hex(&trg_entry->idx.oid));1868if(sz != trg_size)1869die("object%sinconsistent object length (%lu vs%lu)",1870oid_to_hex(&trg_entry->idx.oid), sz,1871 trg_size);1872*mem_usage += sz;1873}1874if(!src->data) {1875read_lock();1876 src->data =read_sha1_file(src_entry->idx.oid.hash, &type,1877&sz);1878read_unlock();1879if(!src->data) {1880if(src_entry->preferred_base) {1881static int warned =0;1882if(!warned++)1883warning("object%scannot be read",1884oid_to_hex(&src_entry->idx.oid));1885/*1886 * Those objects are not included in the1887 * resulting pack. Be resilient and ignore1888 * them if they can't be read, in case the1889 * pack could be created nevertheless.1890 */1891return0;1892}1893die("object%scannot be read",1894oid_to_hex(&src_entry->idx.oid));1895}1896if(sz != src_size)1897die("object%sinconsistent object length (%lu vs%lu)",1898oid_to_hex(&src_entry->idx.oid), sz,1899 src_size);1900*mem_usage += sz;1901}1902if(!src->index) {1903 src->index =create_delta_index(src->data, src_size);1904if(!src->index) {1905static int warned =0;1906if(!warned++)1907warning("suboptimal pack - out of memory");1908return0;1909}1910*mem_usage +=sizeof_delta_index(src->index);1911}19121913 delta_buf =create_delta(src->index, trg->data, trg_size, &delta_size, max_size);1914if(!delta_buf)1915return0;19161917if(trg_entry->delta) {1918/* Prefer only shallower same-sized deltas. */1919if(delta_size == trg_entry->delta_size &&1920 src->depth +1>= trg->depth) {1921free(delta_buf);1922return0;1923}1924}19251926/*1927 * Handle memory allocation outside of the cache1928 * accounting lock. Compiler will optimize the strangeness1929 * away when NO_PTHREADS is defined.1930 */1931free(trg_entry->delta_data);1932cache_lock();1933if(trg_entry->delta_data) {1934 delta_cache_size -= trg_entry->delta_size;1935 trg_entry->delta_data = NULL;1936}1937if(delta_cacheable(src_size, trg_size, delta_size)) {1938 delta_cache_size += delta_size;1939cache_unlock();1940 trg_entry->delta_data =xrealloc(delta_buf, delta_size);1941}else{1942cache_unlock();1943free(delta_buf);1944}19451946 trg_entry->delta = src_entry;1947 trg_entry->delta_size = delta_size;1948 trg->depth = src->depth +1;19491950return1;1951}19521953static unsigned intcheck_delta_limit(struct object_entry *me,unsigned int n)1954{1955struct object_entry *child = me->delta_child;1956unsigned int m = n;1957while(child) {1958unsigned int c =check_delta_limit(child, n +1);1959if(m < c)1960 m = c;1961 child = child->delta_sibling;1962}1963return m;1964}19651966static unsigned longfree_unpacked(struct unpacked *n)1967{1968unsigned long freed_mem =sizeof_delta_index(n->index);1969free_delta_index(n->index);1970 n->index = NULL;1971if(n->data) {1972 freed_mem += n->entry->size;1973free(n->data);1974 n->data = NULL;1975}1976 n->entry = NULL;1977 n->depth =0;1978return freed_mem;1979}19801981static voidfind_deltas(struct object_entry **list,unsigned*list_size,1982int window,int depth,unsigned*processed)1983{1984uint32_t i, idx =0, count =0;1985struct unpacked *array;1986unsigned long mem_usage =0;19871988 array =xcalloc(window,sizeof(struct unpacked));19891990for(;;) {1991struct object_entry *entry;1992struct unpacked *n = array + idx;1993int j, max_depth, best_base = -1;19941995progress_lock();1996if(!*list_size) {1997progress_unlock();1998break;1999}2000 entry = *list++;2001(*list_size)--;2002if(!entry->preferred_base) {2003(*processed)++;2004display_progress(progress_state, *processed);2005}2006progress_unlock();20072008 mem_usage -=free_unpacked(n);2009 n->entry = entry;20102011while(window_memory_limit &&2012 mem_usage > window_memory_limit &&2013 count >1) {2014uint32_t tail = (idx + window - count) % window;2015 mem_usage -=free_unpacked(array + tail);2016 count--;2017}20182019/* We do not compute delta to *create* objects we are not2020 * going to pack.2021 */2022if(entry->preferred_base)2023goto next;20242025/*2026 * If the current object is at pack edge, take the depth the2027 * objects that depend on the current object into account2028 * otherwise they would become too deep.2029 */2030 max_depth = depth;2031if(entry->delta_child) {2032 max_depth -=check_delta_limit(entry,0);2033if(max_depth <=0)2034goto next;2035}20362037 j = window;2038while(--j >0) {2039int ret;2040uint32_t other_idx = idx + j;2041struct unpacked *m;2042if(other_idx >= window)2043 other_idx -= window;2044 m = array + other_idx;2045if(!m->entry)2046break;2047 ret =try_delta(n, m, max_depth, &mem_usage);2048if(ret <0)2049break;2050else if(ret >0)2051 best_base = other_idx;2052}20532054/*2055 * If we decided to cache the delta data, then it is best2056 * to compress it right away. First because we have to do2057 * it anyway, and doing it here while we're threaded will2058 * save a lot of time in the non threaded write phase,2059 * as well as allow for caching more deltas within2060 * the same cache size limit.2061 * ...2062 * But only if not writing to stdout, since in that case2063 * the network is most likely throttling writes anyway,2064 * and therefore it is best to go to the write phase ASAP2065 * instead, as we can afford spending more time compressing2066 * between writes at that moment.2067 */2068if(entry->delta_data && !pack_to_stdout) {2069 entry->z_delta_size =do_compress(&entry->delta_data,2070 entry->delta_size);2071cache_lock();2072 delta_cache_size -= entry->delta_size;2073 delta_cache_size += entry->z_delta_size;2074cache_unlock();2075}20762077/* if we made n a delta, and if n is already at max2078 * depth, leaving it in the window is pointless. we2079 * should evict it first.2080 */2081if(entry->delta && max_depth <= n->depth)2082continue;20832084/*2085 * Move the best delta base up in the window, after the2086 * currently deltified object, to keep it longer. It will2087 * be the first base object to be attempted next.2088 */2089if(entry->delta) {2090struct unpacked swap = array[best_base];2091int dist = (window + idx - best_base) % window;2092int dst = best_base;2093while(dist--) {2094int src = (dst +1) % window;2095 array[dst] = array[src];2096 dst = src;2097}2098 array[dst] = swap;2099}21002101 next:2102 idx++;2103if(count +1< window)2104 count++;2105if(idx >= window)2106 idx =0;2107}21082109for(i =0; i < window; ++i) {2110free_delta_index(array[i].index);2111free(array[i].data);2112}2113free(array);2114}21152116#ifndef NO_PTHREADS21172118static voidtry_to_free_from_threads(size_t size)2119{2120read_lock();2121release_pack_memory(size);2122read_unlock();2123}21242125static try_to_free_t old_try_to_free_routine;21262127/*2128 * The main thread waits on the condition that (at least) one of the workers2129 * has stopped working (which is indicated in the .working member of2130 * struct thread_params).2131 * When a work thread has completed its work, it sets .working to 0 and2132 * signals the main thread and waits on the condition that .data_ready2133 * becomes 1.2134 */21352136struct thread_params {2137 pthread_t thread;2138struct object_entry **list;2139unsigned list_size;2140unsigned remaining;2141int window;2142int depth;2143int working;2144int data_ready;2145 pthread_mutex_t mutex;2146 pthread_cond_t cond;2147unsigned*processed;2148};21492150static pthread_cond_t progress_cond;21512152/*2153 * Mutex and conditional variable can't be statically-initialized on Windows.2154 */2155static voidinit_threaded_search(void)2156{2157init_recursive_mutex(&read_mutex);2158pthread_mutex_init(&cache_mutex, NULL);2159pthread_mutex_init(&progress_mutex, NULL);2160pthread_cond_init(&progress_cond, NULL);2161 old_try_to_free_routine =set_try_to_free_routine(try_to_free_from_threads);2162}21632164static voidcleanup_threaded_search(void)2165{2166set_try_to_free_routine(old_try_to_free_routine);2167pthread_cond_destroy(&progress_cond);2168pthread_mutex_destroy(&read_mutex);2169pthread_mutex_destroy(&cache_mutex);2170pthread_mutex_destroy(&progress_mutex);2171}21722173static void*threaded_find_deltas(void*arg)2174{2175struct thread_params *me = arg;21762177while(me->remaining) {2178find_deltas(me->list, &me->remaining,2179 me->window, me->depth, me->processed);21802181progress_lock();2182 me->working =0;2183pthread_cond_signal(&progress_cond);2184progress_unlock();21852186/*2187 * We must not set ->data_ready before we wait on the2188 * condition because the main thread may have set it to 12189 * before we get here. In order to be sure that new2190 * work is available if we see 1 in ->data_ready, it2191 * was initialized to 0 before this thread was spawned2192 * and we reset it to 0 right away.2193 */2194pthread_mutex_lock(&me->mutex);2195while(!me->data_ready)2196pthread_cond_wait(&me->cond, &me->mutex);2197 me->data_ready =0;2198pthread_mutex_unlock(&me->mutex);2199}2200/* leave ->working 1 so that this doesn't get more work assigned */2201return NULL;2202}22032204static voidll_find_deltas(struct object_entry **list,unsigned list_size,2205int window,int depth,unsigned*processed)2206{2207struct thread_params *p;2208int i, ret, active_threads =0;22092210init_threaded_search();22112212if(delta_search_threads <=1) {2213find_deltas(list, &list_size, window, depth, processed);2214cleanup_threaded_search();2215return;2216}2217if(progress > pack_to_stdout)2218fprintf(stderr,"Delta compression using up to%dthreads.\n",2219 delta_search_threads);2220 p =xcalloc(delta_search_threads,sizeof(*p));22212222/* Partition the work amongst work threads. */2223for(i =0; i < delta_search_threads; i++) {2224unsigned sub_size = list_size / (delta_search_threads - i);22252226/* don't use too small segments or no deltas will be found */2227if(sub_size <2*window && i+1< delta_search_threads)2228 sub_size =0;22292230 p[i].window = window;2231 p[i].depth = depth;2232 p[i].processed = processed;2233 p[i].working =1;2234 p[i].data_ready =0;22352236/* try to split chunks on "path" boundaries */2237while(sub_size && sub_size < list_size &&2238 list[sub_size]->hash &&2239 list[sub_size]->hash == list[sub_size-1]->hash)2240 sub_size++;22412242 p[i].list = list;2243 p[i].list_size = sub_size;2244 p[i].remaining = sub_size;22452246 list += sub_size;2247 list_size -= sub_size;2248}22492250/* Start work threads. */2251for(i =0; i < delta_search_threads; i++) {2252if(!p[i].list_size)2253continue;2254pthread_mutex_init(&p[i].mutex, NULL);2255pthread_cond_init(&p[i].cond, NULL);2256 ret =pthread_create(&p[i].thread, NULL,2257 threaded_find_deltas, &p[i]);2258if(ret)2259die("unable to create thread:%s",strerror(ret));2260 active_threads++;2261}22622263/*2264 * Now let's wait for work completion. Each time a thread is done2265 * with its work, we steal half of the remaining work from the2266 * thread with the largest number of unprocessed objects and give2267 * it to that newly idle thread. This ensure good load balancing2268 * until the remaining object list segments are simply too short2269 * to be worth splitting anymore.2270 */2271while(active_threads) {2272struct thread_params *target = NULL;2273struct thread_params *victim = NULL;2274unsigned sub_size =0;22752276progress_lock();2277for(;;) {2278for(i =0; !target && i < delta_search_threads; i++)2279if(!p[i].working)2280 target = &p[i];2281if(target)2282break;2283pthread_cond_wait(&progress_cond, &progress_mutex);2284}22852286for(i =0; i < delta_search_threads; i++)2287if(p[i].remaining >2*window &&2288(!victim || victim->remaining < p[i].remaining))2289 victim = &p[i];2290if(victim) {2291 sub_size = victim->remaining /2;2292 list = victim->list + victim->list_size - sub_size;2293while(sub_size && list[0]->hash &&2294 list[0]->hash == list[-1]->hash) {2295 list++;2296 sub_size--;2297}2298if(!sub_size) {2299/*2300 * It is possible for some "paths" to have2301 * so many objects that no hash boundary2302 * might be found. Let's just steal the2303 * exact half in that case.2304 */2305 sub_size = victim->remaining /2;2306 list -= sub_size;2307}2308 target->list = list;2309 victim->list_size -= sub_size;2310 victim->remaining -= sub_size;2311}2312 target->list_size = sub_size;2313 target->remaining = sub_size;2314 target->working =1;2315progress_unlock();23162317pthread_mutex_lock(&target->mutex);2318 target->data_ready =1;2319pthread_cond_signal(&target->cond);2320pthread_mutex_unlock(&target->mutex);23212322if(!sub_size) {2323pthread_join(target->thread, NULL);2324pthread_cond_destroy(&target->cond);2325pthread_mutex_destroy(&target->mutex);2326 active_threads--;2327}2328}2329cleanup_threaded_search();2330free(p);2331}23322333#else2334#define ll_find_deltas(l, s, w, d, p) find_deltas(l, &s, w, d, p)2335#endif23362337static voidadd_tag_chain(const struct object_id *oid)2338{2339struct tag *tag;23402341/*2342 * We catch duplicates already in add_object_entry(), but we'd2343 * prefer to do this extra check to avoid having to parse the2344 * tag at all if we already know that it's being packed (e.g., if2345 * it was included via bitmaps, we would not have parsed it2346 * previously).2347 */2348if(packlist_find(&to_pack, oid->hash, NULL))2349return;23502351 tag =lookup_tag(oid);2352while(1) {2353if(!tag ||parse_tag(tag) || !tag->tagged)2354die("unable to pack objects reachable from tag%s",2355oid_to_hex(oid));23562357add_object_entry(tag->object.oid.hash, OBJ_TAG, NULL,0);23582359if(tag->tagged->type != OBJ_TAG)2360return;23612362 tag = (struct tag *)tag->tagged;2363}2364}23652366static intadd_ref_tag(const char*path,const struct object_id *oid,int flag,void*cb_data)2367{2368struct object_id peeled;23692370if(starts_with(path,"refs/tags/") &&/* is a tag? */2371!peel_ref(path, peeled.hash) &&/* peelable? */2372packlist_find(&to_pack, peeled.hash, NULL))/* object packed? */2373add_tag_chain(oid);2374return0;2375}23762377static voidprepare_pack(int window,int depth)2378{2379struct object_entry **delta_list;2380uint32_t i, nr_deltas;2381unsigned n;23822383get_object_details();23842385/*2386 * If we're locally repacking then we need to be doubly careful2387 * from now on in order to make sure no stealth corruption gets2388 * propagated to the new pack. Clients receiving streamed packs2389 * should validate everything they get anyway so no need to incur2390 * the additional cost here in that case.2391 */2392if(!pack_to_stdout)2393 do_check_packed_object_crc =1;23942395if(!to_pack.nr_objects || !window || !depth)2396return;23972398ALLOC_ARRAY(delta_list, to_pack.nr_objects);2399 nr_deltas = n =0;24002401for(i =0; i < to_pack.nr_objects; i++) {2402struct object_entry *entry = to_pack.objects + i;24032404if(entry->delta)2405/* This happens if we decided to reuse existing2406 * delta from a pack. "reuse_delta &&" is implied.2407 */2408continue;24092410if(entry->size <50)2411continue;24122413if(entry->no_try_delta)2414continue;24152416if(!entry->preferred_base) {2417 nr_deltas++;2418if(entry->type <0)2419die("unable to get type of object%s",2420oid_to_hex(&entry->idx.oid));2421}else{2422if(entry->type <0) {2423/*2424 * This object is not found, but we2425 * don't have to include it anyway.2426 */2427continue;2428}2429}24302431 delta_list[n++] = entry;2432}24332434if(nr_deltas && n >1) {2435unsigned nr_done =0;2436if(progress)2437 progress_state =start_progress(_("Compressing objects"),2438 nr_deltas);2439QSORT(delta_list, n, type_size_sort);2440ll_find_deltas(delta_list, n, window+1, depth, &nr_done);2441stop_progress(&progress_state);2442if(nr_done != nr_deltas)2443die("inconsistency with delta count");2444}2445free(delta_list);2446}24472448static intgit_pack_config(const char*k,const char*v,void*cb)2449{2450if(!strcmp(k,"pack.window")) {2451 window =git_config_int(k, v);2452return0;2453}2454if(!strcmp(k,"pack.windowmemory")) {2455 window_memory_limit =git_config_ulong(k, v);2456return0;2457}2458if(!strcmp(k,"pack.depth")) {2459 depth =git_config_int(k, v);2460return0;2461}2462if(!strcmp(k,"pack.deltacachesize")) {2463 max_delta_cache_size =git_config_int(k, v);2464return0;2465}2466if(!strcmp(k,"pack.deltacachelimit")) {2467 cache_max_small_delta_size =git_config_int(k, v);2468return0;2469}2470if(!strcmp(k,"pack.writebitmaphashcache")) {2471if(git_config_bool(k, v))2472 write_bitmap_options |= BITMAP_OPT_HASH_CACHE;2473else2474 write_bitmap_options &= ~BITMAP_OPT_HASH_CACHE;2475}2476if(!strcmp(k,"pack.usebitmaps")) {2477 use_bitmap_index_default =git_config_bool(k, v);2478return0;2479}2480if(!strcmp(k,"pack.threads")) {2481 delta_search_threads =git_config_int(k, v);2482if(delta_search_threads <0)2483die("invalid number of threads specified (%d)",2484 delta_search_threads);2485#ifdef NO_PTHREADS2486if(delta_search_threads !=1) {2487warning("no threads support, ignoring%s", k);2488 delta_search_threads =0;2489}2490#endif2491return0;2492}2493if(!strcmp(k,"pack.indexversion")) {2494 pack_idx_opts.version =git_config_int(k, v);2495if(pack_idx_opts.version >2)2496die("bad pack.indexversion=%"PRIu32,2497 pack_idx_opts.version);2498return0;2499}2500returngit_default_config(k, v, cb);2501}25022503static voidread_object_list_from_stdin(void)2504{2505char line[40+1+ PATH_MAX +2];2506unsigned char sha1[20];25072508for(;;) {2509if(!fgets(line,sizeof(line), stdin)) {2510if(feof(stdin))2511break;2512if(!ferror(stdin))2513die("fgets returned NULL, not EOF, not error!");2514if(errno != EINTR)2515die_errno("fgets");2516clearerr(stdin);2517continue;2518}2519if(line[0] =='-') {2520if(get_sha1_hex(line+1, sha1))2521die("expected edge sha1, got garbage:\n%s",2522 line);2523add_preferred_base(sha1);2524continue;2525}2526if(get_sha1_hex(line, sha1))2527die("expected sha1, got garbage:\n%s", line);25282529add_preferred_base_object(line+41);2530add_object_entry(sha1,0, line+41,0);2531}2532}25332534#define OBJECT_ADDED (1u<<20)25352536static voidshow_commit(struct commit *commit,void*data)2537{2538add_object_entry(commit->object.oid.hash, OBJ_COMMIT, NULL,0);2539 commit->object.flags |= OBJECT_ADDED;25402541if(write_bitmap_index)2542index_commit_for_bitmap(commit);2543}25442545static voidshow_object(struct object *obj,const char*name,void*data)2546{2547add_preferred_base_object(name);2548add_object_entry(obj->oid.hash, obj->type, name,0);2549 obj->flags |= OBJECT_ADDED;2550}25512552static voidshow_edge(struct commit *commit)2553{2554add_preferred_base(commit->object.oid.hash);2555}25562557struct in_pack_object {2558 off_t offset;2559struct object *object;2560};25612562struct in_pack {2563int alloc;2564int nr;2565struct in_pack_object *array;2566};25672568static voidmark_in_pack_object(struct object *object,struct packed_git *p,struct in_pack *in_pack)2569{2570 in_pack->array[in_pack->nr].offset =find_pack_entry_one(object->oid.hash, p);2571 in_pack->array[in_pack->nr].object = object;2572 in_pack->nr++;2573}25742575/*2576 * Compare the objects in the offset order, in order to emulate the2577 * "git rev-list --objects" output that produced the pack originally.2578 */2579static intofscmp(const void*a_,const void*b_)2580{2581struct in_pack_object *a = (struct in_pack_object *)a_;2582struct in_pack_object *b = (struct in_pack_object *)b_;25832584if(a->offset < b->offset)2585return-1;2586else if(a->offset > b->offset)2587return1;2588else2589returnoidcmp(&a->object->oid, &b->object->oid);2590}25912592static voidadd_objects_in_unpacked_packs(struct rev_info *revs)2593{2594struct packed_git *p;2595struct in_pack in_pack;2596uint32_t i;25972598memset(&in_pack,0,sizeof(in_pack));25992600for(p = packed_git; p; p = p->next) {2601const unsigned char*sha1;2602struct object *o;26032604if(!p->pack_local || p->pack_keep)2605continue;2606if(open_pack_index(p))2607die("cannot open pack index");26082609ALLOC_GROW(in_pack.array,2610 in_pack.nr + p->num_objects,2611 in_pack.alloc);26122613for(i =0; i < p->num_objects; i++) {2614 sha1 =nth_packed_object_sha1(p, i);2615 o =lookup_unknown_object(sha1);2616if(!(o->flags & OBJECT_ADDED))2617mark_in_pack_object(o, p, &in_pack);2618 o->flags |= OBJECT_ADDED;2619}2620}26212622if(in_pack.nr) {2623QSORT(in_pack.array, in_pack.nr, ofscmp);2624for(i =0; i < in_pack.nr; i++) {2625struct object *o = in_pack.array[i].object;2626add_object_entry(o->oid.hash, o->type,"",0);2627}2628}2629free(in_pack.array);2630}26312632static intadd_loose_object(const struct object_id *oid,const char*path,2633void*data)2634{2635enum object_type type =sha1_object_info(oid->hash, NULL);26362637if(type <0) {2638warning("loose object at%scould not be examined", path);2639return0;2640}26412642add_object_entry(oid->hash, type,"",0);2643return0;2644}26452646/*2647 * We actually don't even have to worry about reachability here.2648 * add_object_entry will weed out duplicates, so we just add every2649 * loose object we find.2650 */2651static voidadd_unreachable_loose_objects(void)2652{2653for_each_loose_file_in_objdir(get_object_directory(),2654 add_loose_object,2655 NULL, NULL, NULL);2656}26572658static inthas_sha1_pack_kept_or_nonlocal(const unsigned char*sha1)2659{2660static struct packed_git *last_found = (void*)1;2661struct packed_git *p;26622663 p = (last_found != (void*)1) ? last_found : packed_git;26642665while(p) {2666if((!p->pack_local || p->pack_keep) &&2667find_pack_entry_one(sha1, p)) {2668 last_found = p;2669return1;2670}2671if(p == last_found)2672 p = packed_git;2673else2674 p = p->next;2675if(p == last_found)2676 p = p->next;2677}2678return0;2679}26802681/*2682 * Store a list of sha1s that are should not be discarded2683 * because they are either written too recently, or are2684 * reachable from another object that was.2685 *2686 * This is filled by get_object_list.2687 */2688static struct oid_array recent_objects;26892690static intloosened_object_can_be_discarded(const struct object_id *oid,2691 timestamp_t mtime)2692{2693if(!unpack_unreachable_expiration)2694return0;2695if(mtime > unpack_unreachable_expiration)2696return0;2697if(oid_array_lookup(&recent_objects, oid) >=0)2698return0;2699return1;2700}27012702static voidloosen_unused_packed_objects(struct rev_info *revs)2703{2704struct packed_git *p;2705uint32_t i;2706struct object_id oid;27072708for(p = packed_git; p; p = p->next) {2709if(!p->pack_local || p->pack_keep)2710continue;27112712if(open_pack_index(p))2713die("cannot open pack index");27142715for(i =0; i < p->num_objects; i++) {2716nth_packed_object_oid(&oid, p, i);2717if(!packlist_find(&to_pack, oid.hash, NULL) &&2718!has_sha1_pack_kept_or_nonlocal(oid.hash) &&2719!loosened_object_can_be_discarded(&oid, p->mtime))2720if(force_object_loose(oid.hash, p->mtime))2721die("unable to force loose object");2722}2723}2724}27252726/*2727 * This tracks any options which pack-reuse code expects to be on, or which a2728 * reader of the pack might not understand, and which would therefore prevent2729 * blind reuse of what we have on disk.2730 */2731static intpack_options_allow_reuse(void)2732{2733return pack_to_stdout &&2734 allow_ofs_delta &&2735!ignore_packed_keep &&2736(!local || !have_non_local_packs) &&2737!incremental;2738}27392740static intget_object_list_from_bitmap(struct rev_info *revs)2741{2742if(prepare_bitmap_walk(revs) <0)2743return-1;27442745if(pack_options_allow_reuse() &&2746!reuse_partial_packfile_from_bitmap(2747&reuse_packfile,2748&reuse_packfile_objects,2749&reuse_packfile_offset)) {2750assert(reuse_packfile_objects);2751 nr_result += reuse_packfile_objects;2752display_progress(progress_state, nr_result);2753}27542755traverse_bitmap_commit_list(&add_object_entry_from_bitmap);2756return0;2757}27582759static voidrecord_recent_object(struct object *obj,2760const char*name,2761void*data)2762{2763oid_array_append(&recent_objects, &obj->oid);2764}27652766static voidrecord_recent_commit(struct commit *commit,void*data)2767{2768oid_array_append(&recent_objects, &commit->object.oid);2769}27702771static voidget_object_list(int ac,const char**av)2772{2773struct rev_info revs;2774char line[1000];2775int flags =0;27762777init_revisions(&revs, NULL);2778 save_commit_buffer =0;2779setup_revisions(ac, av, &revs, NULL);27802781/* make sure shallows are read */2782is_repository_shallow();27832784while(fgets(line,sizeof(line), stdin) != NULL) {2785int len =strlen(line);2786if(len && line[len -1] =='\n')2787 line[--len] =0;2788if(!len)2789break;2790if(*line =='-') {2791if(!strcmp(line,"--not")) {2792 flags ^= UNINTERESTING;2793 write_bitmap_index =0;2794continue;2795}2796if(starts_with(line,"--shallow ")) {2797struct object_id oid;2798if(get_oid_hex(line +10, &oid))2799die("not an SHA-1 '%s'", line +10);2800register_shallow(&oid);2801 use_bitmap_index =0;2802continue;2803}2804die("not a rev '%s'", line);2805}2806if(handle_revision_arg(line, &revs, flags, REVARG_CANNOT_BE_FILENAME))2807die("bad revision '%s'", line);2808}28092810if(use_bitmap_index && !get_object_list_from_bitmap(&revs))2811return;28122813if(prepare_revision_walk(&revs))2814die("revision walk setup failed");2815mark_edges_uninteresting(&revs, show_edge);2816traverse_commit_list(&revs, show_commit, show_object, NULL);28172818if(unpack_unreachable_expiration) {2819 revs.ignore_missing_links =1;2820if(add_unseen_recent_objects_to_traversal(&revs,2821 unpack_unreachable_expiration))2822die("unable to add recent objects");2823if(prepare_revision_walk(&revs))2824die("revision walk setup failed");2825traverse_commit_list(&revs, record_recent_commit,2826 record_recent_object, NULL);2827}28282829if(keep_unreachable)2830add_objects_in_unpacked_packs(&revs);2831if(pack_loose_unreachable)2832add_unreachable_loose_objects();2833if(unpack_unreachable)2834loosen_unused_packed_objects(&revs);28352836oid_array_clear(&recent_objects);2837}28382839static intoption_parse_index_version(const struct option *opt,2840const char*arg,int unset)2841{2842char*c;2843const char*val = arg;2844 pack_idx_opts.version =strtoul(val, &c,10);2845if(pack_idx_opts.version >2)2846die(_("unsupported index version%s"), val);2847if(*c ==','&& c[1])2848 pack_idx_opts.off32_limit =strtoul(c+1, &c,0);2849if(*c || pack_idx_opts.off32_limit &0x80000000)2850die(_("bad index version '%s'"), val);2851return0;2852}28532854static intoption_parse_unpack_unreachable(const struct option *opt,2855const char*arg,int unset)2856{2857if(unset) {2858 unpack_unreachable =0;2859 unpack_unreachable_expiration =0;2860}2861else{2862 unpack_unreachable =1;2863if(arg)2864 unpack_unreachable_expiration =approxidate(arg);2865}2866return0;2867}28682869intcmd_pack_objects(int argc,const char**argv,const char*prefix)2870{2871int use_internal_rev_list =0;2872int thin =0;2873int shallow =0;2874int all_progress_implied =0;2875struct argv_array rp = ARGV_ARRAY_INIT;2876int rev_list_unpacked =0, rev_list_all =0, rev_list_reflog =0;2877int rev_list_index =0;2878struct option pack_objects_options[] = {2879OPT_SET_INT('q',"quiet", &progress,2880N_("do not show progress meter"),0),2881OPT_SET_INT(0,"progress", &progress,2882N_("show progress meter"),1),2883OPT_SET_INT(0,"all-progress", &progress,2884N_("show progress meter during object writing phase"),2),2885OPT_BOOL(0,"all-progress-implied",2886&all_progress_implied,2887N_("similar to --all-progress when progress meter is shown")),2888{ OPTION_CALLBACK,0,"index-version", NULL,N_("version[,offset]"),2889N_("write the pack index file in the specified idx format version"),28900, option_parse_index_version },2891OPT_MAGNITUDE(0,"max-pack-size", &pack_size_limit,2892N_("maximum size of each output pack file")),2893OPT_BOOL(0,"local", &local,2894N_("ignore borrowed objects from alternate object store")),2895OPT_BOOL(0,"incremental", &incremental,2896N_("ignore packed objects")),2897OPT_INTEGER(0,"window", &window,2898N_("limit pack window by objects")),2899OPT_MAGNITUDE(0,"window-memory", &window_memory_limit,2900N_("limit pack window by memory in addition to object limit")),2901OPT_INTEGER(0,"depth", &depth,2902N_("maximum length of delta chain allowed in the resulting pack")),2903OPT_BOOL(0,"reuse-delta", &reuse_delta,2904N_("reuse existing deltas")),2905OPT_BOOL(0,"reuse-object", &reuse_object,2906N_("reuse existing objects")),2907OPT_BOOL(0,"delta-base-offset", &allow_ofs_delta,2908N_("use OFS_DELTA objects")),2909OPT_INTEGER(0,"threads", &delta_search_threads,2910N_("use threads when searching for best delta matches")),2911OPT_BOOL(0,"non-empty", &non_empty,2912N_("do not create an empty pack output")),2913OPT_BOOL(0,"revs", &use_internal_rev_list,2914N_("read revision arguments from standard input")),2915{ OPTION_SET_INT,0,"unpacked", &rev_list_unpacked, NULL,2916N_("limit the objects to those that are not yet packed"),2917 PARSE_OPT_NOARG | PARSE_OPT_NONEG, NULL,1},2918{ OPTION_SET_INT,0,"all", &rev_list_all, NULL,2919N_("include objects reachable from any reference"),2920 PARSE_OPT_NOARG | PARSE_OPT_NONEG, NULL,1},2921{ OPTION_SET_INT,0,"reflog", &rev_list_reflog, NULL,2922N_("include objects referred by reflog entries"),2923 PARSE_OPT_NOARG | PARSE_OPT_NONEG, NULL,1},2924{ OPTION_SET_INT,0,"indexed-objects", &rev_list_index, NULL,2925N_("include objects referred to by the index"),2926 PARSE_OPT_NOARG | PARSE_OPT_NONEG, NULL,1},2927OPT_BOOL(0,"stdout", &pack_to_stdout,2928N_("output pack to stdout")),2929OPT_BOOL(0,"include-tag", &include_tag,2930N_("include tag objects that refer to objects to be packed")),2931OPT_BOOL(0,"keep-unreachable", &keep_unreachable,2932N_("keep unreachable objects")),2933OPT_BOOL(0,"pack-loose-unreachable", &pack_loose_unreachable,2934N_("pack loose unreachable objects")),2935{ OPTION_CALLBACK,0,"unpack-unreachable", NULL,N_("time"),2936N_("unpack unreachable objects newer than <time>"),2937 PARSE_OPT_OPTARG, option_parse_unpack_unreachable },2938OPT_BOOL(0,"thin", &thin,2939N_("create thin packs")),2940OPT_BOOL(0,"shallow", &shallow,2941N_("create packs suitable for shallow fetches")),2942OPT_BOOL(0,"honor-pack-keep", &ignore_packed_keep,2943N_("ignore packs that have companion .keep file")),2944OPT_INTEGER(0,"compression", &pack_compression_level,2945N_("pack compression level")),2946OPT_SET_INT(0,"keep-true-parents", &grafts_replace_parents,2947N_("do not hide commits by grafts"),0),2948OPT_BOOL(0,"use-bitmap-index", &use_bitmap_index,2949N_("use a bitmap index if available to speed up counting objects")),2950OPT_BOOL(0,"write-bitmap-index", &write_bitmap_index,2951N_("write a bitmap index together with the pack index")),2952OPT_END(),2953};29542955 check_replace_refs =0;29562957reset_pack_idx_option(&pack_idx_opts);2958git_config(git_pack_config, NULL);29592960 progress =isatty(2);2961 argc =parse_options(argc, argv, prefix, pack_objects_options,2962 pack_usage,0);29632964if(argc) {2965 base_name = argv[0];2966 argc--;2967}2968if(pack_to_stdout != !base_name || argc)2969usage_with_options(pack_usage, pack_objects_options);29702971argv_array_push(&rp,"pack-objects");2972if(thin) {2973 use_internal_rev_list =1;2974argv_array_push(&rp, shallow2975?"--objects-edge-aggressive"2976:"--objects-edge");2977}else2978argv_array_push(&rp,"--objects");29792980if(rev_list_all) {2981 use_internal_rev_list =1;2982argv_array_push(&rp,"--all");2983}2984if(rev_list_reflog) {2985 use_internal_rev_list =1;2986argv_array_push(&rp,"--reflog");2987}2988if(rev_list_index) {2989 use_internal_rev_list =1;2990argv_array_push(&rp,"--indexed-objects");2991}2992if(rev_list_unpacked) {2993 use_internal_rev_list =1;2994argv_array_push(&rp,"--unpacked");2995}29962997if(!reuse_object)2998 reuse_delta =0;2999if(pack_compression_level == -1)3000 pack_compression_level = Z_DEFAULT_COMPRESSION;3001else if(pack_compression_level <0|| pack_compression_level > Z_BEST_COMPRESSION)3002die("bad pack compression level%d", pack_compression_level);30033004if(!delta_search_threads)/* --threads=0 means autodetect */3005 delta_search_threads =online_cpus();30063007#ifdef NO_PTHREADS3008if(delta_search_threads !=1)3009warning("no threads support, ignoring --threads");3010#endif3011if(!pack_to_stdout && !pack_size_limit)3012 pack_size_limit = pack_size_limit_cfg;3013if(pack_to_stdout && pack_size_limit)3014die("--max-pack-size cannot be used to build a pack for transfer.");3015if(pack_size_limit && pack_size_limit <1024*1024) {3016warning("minimum pack size limit is 1 MiB");3017 pack_size_limit =1024*1024;3018}30193020if(!pack_to_stdout && thin)3021die("--thin cannot be used to build an indexable pack.");30223023if(keep_unreachable && unpack_unreachable)3024die("--keep-unreachable and --unpack-unreachable are incompatible.");3025if(!rev_list_all || !rev_list_reflog || !rev_list_index)3026 unpack_unreachable_expiration =0;30273028/*3029 * "soft" reasons not to use bitmaps - for on-disk repack by default we want3030 *3031 * - to produce good pack (with bitmap index not-yet-packed objects are3032 * packed in suboptimal order).3033 *3034 * - to use more robust pack-generation codepath (avoiding possible3035 * bugs in bitmap code and possible bitmap index corruption).3036 */3037if(!pack_to_stdout)3038 use_bitmap_index_default =0;30393040if(use_bitmap_index <0)3041 use_bitmap_index = use_bitmap_index_default;30423043/* "hard" reasons not to use bitmaps; these just won't work at all */3044if(!use_internal_rev_list || (!pack_to_stdout && write_bitmap_index) ||is_repository_shallow())3045 use_bitmap_index =0;30463047if(pack_to_stdout || !rev_list_all)3048 write_bitmap_index =0;30493050if(progress && all_progress_implied)3051 progress =2;30523053prepare_packed_git();3054if(ignore_packed_keep) {3055struct packed_git *p;3056for(p = packed_git; p; p = p->next)3057if(p->pack_local && p->pack_keep)3058break;3059if(!p)/* no keep-able packs found */3060 ignore_packed_keep =0;3061}3062if(local) {3063/*3064 * unlike ignore_packed_keep above, we do not want to3065 * unset "local" based on looking at packs, as it3066 * also covers non-local objects3067 */3068struct packed_git *p;3069for(p = packed_git; p; p = p->next) {3070if(!p->pack_local) {3071 have_non_local_packs =1;3072break;3073}3074}3075}30763077if(progress)3078 progress_state =start_progress(_("Counting objects"),0);3079if(!use_internal_rev_list)3080read_object_list_from_stdin();3081else{3082get_object_list(rp.argc, rp.argv);3083argv_array_clear(&rp);3084}3085cleanup_preferred_base();3086if(include_tag && nr_result)3087for_each_ref(add_ref_tag, NULL);3088stop_progress(&progress_state);30893090if(non_empty && !nr_result)3091return0;3092if(nr_result)3093prepare_pack(window, depth);3094write_pack_file();3095if(progress)3096fprintf(stderr,"Total %"PRIu32" (delta %"PRIu32"),"3097" reused %"PRIu32" (delta %"PRIu32")\n",3098 written, written_delta, reused, reused_delta);3099return0;3100}