1#include"builtin.h" 2#include"cache.h" 3#include"config.h" 4#include"attr.h" 5#include"object.h" 6#include"blob.h" 7#include"commit.h" 8#include"tag.h" 9#include"tree.h" 10#include"delta.h" 11#include"pack.h" 12#include"pack-revindex.h" 13#include"csum-file.h" 14#include"tree-walk.h" 15#include"diff.h" 16#include"revision.h" 17#include"list-objects.h" 18#include"list-objects-filter.h" 19#include"list-objects-filter-options.h" 20#include"pack-objects.h" 21#include"progress.h" 22#include"refs.h" 23#include"streaming.h" 24#include"thread-utils.h" 25#include"pack-bitmap.h" 26#include"reachable.h" 27#include"sha1-array.h" 28#include"argv-array.h" 29#include"mru.h" 30#include"packfile.h" 31 32static const char*pack_usage[] = { 33N_("git pack-objects --stdout [<options>...] [< <ref-list> | < <object-list>]"), 34N_("git pack-objects [<options>...] <base-name> [< <ref-list> | < <object-list>]"), 35 NULL 36}; 37 38/* 39 * Objects we are going to pack are collected in the `to_pack` structure. 40 * It contains an array (dynamically expanded) of the object data, and a map 41 * that can resolve SHA1s to their position in the array. 42 */ 43static struct packing_data to_pack; 44 45static struct pack_idx_entry **written_list; 46static uint32_t nr_result, nr_written; 47 48static int non_empty; 49static int reuse_delta =1, reuse_object =1; 50static int keep_unreachable, unpack_unreachable, include_tag; 51static timestamp_t unpack_unreachable_expiration; 52static int pack_loose_unreachable; 53static int local; 54static int have_non_local_packs; 55static int incremental; 56static int ignore_packed_keep; 57static int allow_ofs_delta; 58static struct pack_idx_option pack_idx_opts; 59static const char*base_name; 60static int progress =1; 61static int window =10; 62static unsigned long pack_size_limit; 63static int depth =50; 64static int delta_search_threads; 65static int pack_to_stdout; 66static int num_preferred_base; 67static struct progress *progress_state; 68 69static struct packed_git *reuse_packfile; 70static uint32_t reuse_packfile_objects; 71static off_t reuse_packfile_offset; 72 73static int use_bitmap_index_default =1; 74static int use_bitmap_index = -1; 75static int write_bitmap_index; 76static uint16_t write_bitmap_options; 77 78static unsigned long delta_cache_size =0; 79static unsigned long max_delta_cache_size =256*1024*1024; 80static unsigned long cache_max_small_delta_size =1000; 81 82static unsigned long window_memory_limit =0; 83 84static struct list_objects_filter_options filter_options; 85 86enum missing_action { 87 MA_ERROR =0,/* fail if any missing objects are encountered */ 88 MA_ALLOW_ANY,/* silently allow ALL missing objects */ 89}; 90static enum missing_action arg_missing_action; 91static show_object_fn fn_show_object; 92 93/* 94 * stats 95 */ 96static uint32_t written, written_delta; 97static uint32_t reused, reused_delta; 98 99/* 100 * Indexed commits 101 */ 102static struct commit **indexed_commits; 103static unsigned int indexed_commits_nr; 104static unsigned int indexed_commits_alloc; 105 106static voidindex_commit_for_bitmap(struct commit *commit) 107{ 108if(indexed_commits_nr >= indexed_commits_alloc) { 109 indexed_commits_alloc = (indexed_commits_alloc +32) *2; 110REALLOC_ARRAY(indexed_commits, indexed_commits_alloc); 111} 112 113 indexed_commits[indexed_commits_nr++] = commit; 114} 115 116static void*get_delta(struct object_entry *entry) 117{ 118unsigned long size, base_size, delta_size; 119void*buf, *base_buf, *delta_buf; 120enum object_type type; 121 122 buf =read_sha1_file(entry->idx.oid.hash, &type, &size); 123if(!buf) 124die("unable to read%s",oid_to_hex(&entry->idx.oid)); 125 base_buf =read_sha1_file(entry->delta->idx.oid.hash, &type, 126&base_size); 127if(!base_buf) 128die("unable to read%s", 129oid_to_hex(&entry->delta->idx.oid)); 130 delta_buf =diff_delta(base_buf, base_size, 131 buf, size, &delta_size,0); 132if(!delta_buf || delta_size != entry->delta_size) 133die("delta size changed"); 134free(buf); 135free(base_buf); 136return delta_buf; 137} 138 139static unsigned longdo_compress(void**pptr,unsigned long size) 140{ 141 git_zstream stream; 142void*in, *out; 143unsigned long maxsize; 144 145git_deflate_init(&stream, pack_compression_level); 146 maxsize =git_deflate_bound(&stream, size); 147 148 in = *pptr; 149 out =xmalloc(maxsize); 150*pptr = out; 151 152 stream.next_in = in; 153 stream.avail_in = size; 154 stream.next_out = out; 155 stream.avail_out = maxsize; 156while(git_deflate(&stream, Z_FINISH) == Z_OK) 157;/* nothing */ 158git_deflate_end(&stream); 159 160free(in); 161return stream.total_out; 162} 163 164static unsigned longwrite_large_blob_data(struct git_istream *st,struct sha1file *f, 165const struct object_id *oid) 166{ 167 git_zstream stream; 168unsigned char ibuf[1024*16]; 169unsigned char obuf[1024*16]; 170unsigned long olen =0; 171 172git_deflate_init(&stream, pack_compression_level); 173 174for(;;) { 175 ssize_t readlen; 176int zret = Z_OK; 177 readlen =read_istream(st, ibuf,sizeof(ibuf)); 178if(readlen == -1) 179die(_("unable to read%s"),oid_to_hex(oid)); 180 181 stream.next_in = ibuf; 182 stream.avail_in = readlen; 183while((stream.avail_in || readlen ==0) && 184(zret == Z_OK || zret == Z_BUF_ERROR)) { 185 stream.next_out = obuf; 186 stream.avail_out =sizeof(obuf); 187 zret =git_deflate(&stream, readlen ?0: Z_FINISH); 188sha1write(f, obuf, stream.next_out - obuf); 189 olen += stream.next_out - obuf; 190} 191if(stream.avail_in) 192die(_("deflate error (%d)"), zret); 193if(readlen ==0) { 194if(zret != Z_STREAM_END) 195die(_("deflate error (%d)"), zret); 196break; 197} 198} 199git_deflate_end(&stream); 200return olen; 201} 202 203/* 204 * we are going to reuse the existing object data as is. make 205 * sure it is not corrupt. 206 */ 207static intcheck_pack_inflate(struct packed_git *p, 208struct pack_window **w_curs, 209 off_t offset, 210 off_t len, 211unsigned long expect) 212{ 213 git_zstream stream; 214unsigned char fakebuf[4096], *in; 215int st; 216 217memset(&stream,0,sizeof(stream)); 218git_inflate_init(&stream); 219do{ 220 in =use_pack(p, w_curs, offset, &stream.avail_in); 221 stream.next_in = in; 222 stream.next_out = fakebuf; 223 stream.avail_out =sizeof(fakebuf); 224 st =git_inflate(&stream, Z_FINISH); 225 offset += stream.next_in - in; 226}while(st == Z_OK || st == Z_BUF_ERROR); 227git_inflate_end(&stream); 228return(st == Z_STREAM_END && 229 stream.total_out == expect && 230 stream.total_in == len) ?0: -1; 231} 232 233static voidcopy_pack_data(struct sha1file *f, 234struct packed_git *p, 235struct pack_window **w_curs, 236 off_t offset, 237 off_t len) 238{ 239unsigned char*in; 240unsigned long avail; 241 242while(len) { 243 in =use_pack(p, w_curs, offset, &avail); 244if(avail > len) 245 avail = (unsigned long)len; 246sha1write(f, in, avail); 247 offset += avail; 248 len -= avail; 249} 250} 251 252/* Return 0 if we will bust the pack-size limit */ 253static unsigned longwrite_no_reuse_object(struct sha1file *f,struct object_entry *entry, 254unsigned long limit,int usable_delta) 255{ 256unsigned long size, datalen; 257unsigned char header[MAX_PACK_OBJECT_HEADER], 258 dheader[MAX_PACK_OBJECT_HEADER]; 259unsigned hdrlen; 260enum object_type type; 261void*buf; 262struct git_istream *st = NULL; 263 264if(!usable_delta) { 265if(entry->type == OBJ_BLOB && 266 entry->size > big_file_threshold && 267(st =open_istream(entry->idx.oid.hash, &type, &size, NULL)) != NULL) 268 buf = NULL; 269else{ 270 buf =read_sha1_file(entry->idx.oid.hash, &type, 271&size); 272if(!buf) 273die(_("unable to read%s"), 274oid_to_hex(&entry->idx.oid)); 275} 276/* 277 * make sure no cached delta data remains from a 278 * previous attempt before a pack split occurred. 279 */ 280FREE_AND_NULL(entry->delta_data); 281 entry->z_delta_size =0; 282}else if(entry->delta_data) { 283 size = entry->delta_size; 284 buf = entry->delta_data; 285 entry->delta_data = NULL; 286 type = (allow_ofs_delta && entry->delta->idx.offset) ? 287 OBJ_OFS_DELTA : OBJ_REF_DELTA; 288}else{ 289 buf =get_delta(entry); 290 size = entry->delta_size; 291 type = (allow_ofs_delta && entry->delta->idx.offset) ? 292 OBJ_OFS_DELTA : OBJ_REF_DELTA; 293} 294 295if(st)/* large blob case, just assume we don't compress well */ 296 datalen = size; 297else if(entry->z_delta_size) 298 datalen = entry->z_delta_size; 299else 300 datalen =do_compress(&buf, size); 301 302/* 303 * The object header is a byte of 'type' followed by zero or 304 * more bytes of length. 305 */ 306 hdrlen =encode_in_pack_object_header(header,sizeof(header), 307 type, size); 308 309if(type == OBJ_OFS_DELTA) { 310/* 311 * Deltas with relative base contain an additional 312 * encoding of the relative offset for the delta 313 * base from this object's position in the pack. 314 */ 315 off_t ofs = entry->idx.offset - entry->delta->idx.offset; 316unsigned pos =sizeof(dheader) -1; 317 dheader[pos] = ofs &127; 318while(ofs >>=7) 319 dheader[--pos] =128| (--ofs &127); 320if(limit && hdrlen +sizeof(dheader) - pos + datalen +20>= limit) { 321if(st) 322close_istream(st); 323free(buf); 324return0; 325} 326sha1write(f, header, hdrlen); 327sha1write(f, dheader + pos,sizeof(dheader) - pos); 328 hdrlen +=sizeof(dheader) - pos; 329}else if(type == OBJ_REF_DELTA) { 330/* 331 * Deltas with a base reference contain 332 * an additional 20 bytes for the base sha1. 333 */ 334if(limit && hdrlen +20+ datalen +20>= limit) { 335if(st) 336close_istream(st); 337free(buf); 338return0; 339} 340sha1write(f, header, hdrlen); 341sha1write(f, entry->delta->idx.oid.hash,20); 342 hdrlen +=20; 343}else{ 344if(limit && hdrlen + datalen +20>= limit) { 345if(st) 346close_istream(st); 347free(buf); 348return0; 349} 350sha1write(f, header, hdrlen); 351} 352if(st) { 353 datalen =write_large_blob_data(st, f, &entry->idx.oid); 354close_istream(st); 355}else{ 356sha1write(f, buf, datalen); 357free(buf); 358} 359 360return hdrlen + datalen; 361} 362 363/* Return 0 if we will bust the pack-size limit */ 364static off_t write_reuse_object(struct sha1file *f,struct object_entry *entry, 365unsigned long limit,int usable_delta) 366{ 367struct packed_git *p = entry->in_pack; 368struct pack_window *w_curs = NULL; 369struct revindex_entry *revidx; 370 off_t offset; 371enum object_type type = entry->type; 372 off_t datalen; 373unsigned char header[MAX_PACK_OBJECT_HEADER], 374 dheader[MAX_PACK_OBJECT_HEADER]; 375unsigned hdrlen; 376 377if(entry->delta) 378 type = (allow_ofs_delta && entry->delta->idx.offset) ? 379 OBJ_OFS_DELTA : OBJ_REF_DELTA; 380 hdrlen =encode_in_pack_object_header(header,sizeof(header), 381 type, entry->size); 382 383 offset = entry->in_pack_offset; 384 revidx =find_pack_revindex(p, offset); 385 datalen = revidx[1].offset - offset; 386if(!pack_to_stdout && p->index_version >1&& 387check_pack_crc(p, &w_curs, offset, datalen, revidx->nr)) { 388error("bad packed object CRC for%s", 389oid_to_hex(&entry->idx.oid)); 390unuse_pack(&w_curs); 391returnwrite_no_reuse_object(f, entry, limit, usable_delta); 392} 393 394 offset += entry->in_pack_header_size; 395 datalen -= entry->in_pack_header_size; 396 397if(!pack_to_stdout && p->index_version ==1&& 398check_pack_inflate(p, &w_curs, offset, datalen, entry->size)) { 399error("corrupt packed object for%s", 400oid_to_hex(&entry->idx.oid)); 401unuse_pack(&w_curs); 402returnwrite_no_reuse_object(f, entry, limit, usable_delta); 403} 404 405if(type == OBJ_OFS_DELTA) { 406 off_t ofs = entry->idx.offset - entry->delta->idx.offset; 407unsigned pos =sizeof(dheader) -1; 408 dheader[pos] = ofs &127; 409while(ofs >>=7) 410 dheader[--pos] =128| (--ofs &127); 411if(limit && hdrlen +sizeof(dheader) - pos + datalen +20>= limit) { 412unuse_pack(&w_curs); 413return0; 414} 415sha1write(f, header, hdrlen); 416sha1write(f, dheader + pos,sizeof(dheader) - pos); 417 hdrlen +=sizeof(dheader) - pos; 418 reused_delta++; 419}else if(type == OBJ_REF_DELTA) { 420if(limit && hdrlen +20+ datalen +20>= limit) { 421unuse_pack(&w_curs); 422return0; 423} 424sha1write(f, header, hdrlen); 425sha1write(f, entry->delta->idx.oid.hash,20); 426 hdrlen +=20; 427 reused_delta++; 428}else{ 429if(limit && hdrlen + datalen +20>= limit) { 430unuse_pack(&w_curs); 431return0; 432} 433sha1write(f, header, hdrlen); 434} 435copy_pack_data(f, p, &w_curs, offset, datalen); 436unuse_pack(&w_curs); 437 reused++; 438return hdrlen + datalen; 439} 440 441/* Return 0 if we will bust the pack-size limit */ 442static off_t write_object(struct sha1file *f, 443struct object_entry *entry, 444 off_t write_offset) 445{ 446unsigned long limit; 447 off_t len; 448int usable_delta, to_reuse; 449 450if(!pack_to_stdout) 451crc32_begin(f); 452 453/* apply size limit if limited packsize and not first object */ 454if(!pack_size_limit || !nr_written) 455 limit =0; 456else if(pack_size_limit <= write_offset) 457/* 458 * the earlier object did not fit the limit; avoid 459 * mistaking this with unlimited (i.e. limit = 0). 460 */ 461 limit =1; 462else 463 limit = pack_size_limit - write_offset; 464 465if(!entry->delta) 466 usable_delta =0;/* no delta */ 467else if(!pack_size_limit) 468 usable_delta =1;/* unlimited packfile */ 469else if(entry->delta->idx.offset == (off_t)-1) 470 usable_delta =0;/* base was written to another pack */ 471else if(entry->delta->idx.offset) 472 usable_delta =1;/* base already exists in this pack */ 473else 474 usable_delta =0;/* base could end up in another pack */ 475 476if(!reuse_object) 477 to_reuse =0;/* explicit */ 478else if(!entry->in_pack) 479 to_reuse =0;/* can't reuse what we don't have */ 480else if(entry->type == OBJ_REF_DELTA || entry->type == OBJ_OFS_DELTA) 481/* check_object() decided it for us ... */ 482 to_reuse = usable_delta; 483/* ... but pack split may override that */ 484else if(entry->type != entry->in_pack_type) 485 to_reuse =0;/* pack has delta which is unusable */ 486else if(entry->delta) 487 to_reuse =0;/* we want to pack afresh */ 488else 489 to_reuse =1;/* we have it in-pack undeltified, 490 * and we do not need to deltify it. 491 */ 492 493if(!to_reuse) 494 len =write_no_reuse_object(f, entry, limit, usable_delta); 495else 496 len =write_reuse_object(f, entry, limit, usable_delta); 497if(!len) 498return0; 499 500if(usable_delta) 501 written_delta++; 502 written++; 503if(!pack_to_stdout) 504 entry->idx.crc32 =crc32_end(f); 505return len; 506} 507 508enum write_one_status { 509 WRITE_ONE_SKIP = -1,/* already written */ 510 WRITE_ONE_BREAK =0,/* writing this will bust the limit; not written */ 511 WRITE_ONE_WRITTEN =1,/* normal */ 512 WRITE_ONE_RECURSIVE =2/* already scheduled to be written */ 513}; 514 515static enum write_one_status write_one(struct sha1file *f, 516struct object_entry *e, 517 off_t *offset) 518{ 519 off_t size; 520int recursing; 521 522/* 523 * we set offset to 1 (which is an impossible value) to mark 524 * the fact that this object is involved in "write its base 525 * first before writing a deltified object" recursion. 526 */ 527 recursing = (e->idx.offset ==1); 528if(recursing) { 529warning("recursive delta detected for object%s", 530oid_to_hex(&e->idx.oid)); 531return WRITE_ONE_RECURSIVE; 532}else if(e->idx.offset || e->preferred_base) { 533/* offset is non zero if object is written already. */ 534return WRITE_ONE_SKIP; 535} 536 537/* if we are deltified, write out base object first. */ 538if(e->delta) { 539 e->idx.offset =1;/* now recurse */ 540switch(write_one(f, e->delta, offset)) { 541case WRITE_ONE_RECURSIVE: 542/* we cannot depend on this one */ 543 e->delta = NULL; 544break; 545default: 546break; 547case WRITE_ONE_BREAK: 548 e->idx.offset = recursing; 549return WRITE_ONE_BREAK; 550} 551} 552 553 e->idx.offset = *offset; 554 size =write_object(f, e, *offset); 555if(!size) { 556 e->idx.offset = recursing; 557return WRITE_ONE_BREAK; 558} 559 written_list[nr_written++] = &e->idx; 560 561/* make sure off_t is sufficiently large not to wrap */ 562if(signed_add_overflows(*offset, size)) 563die("pack too large for current definition of off_t"); 564*offset += size; 565return WRITE_ONE_WRITTEN; 566} 567 568static intmark_tagged(const char*path,const struct object_id *oid,int flag, 569void*cb_data) 570{ 571struct object_id peeled; 572struct object_entry *entry =packlist_find(&to_pack, oid->hash, NULL); 573 574if(entry) 575 entry->tagged =1; 576if(!peel_ref(path, &peeled)) { 577 entry =packlist_find(&to_pack, peeled.hash, NULL); 578if(entry) 579 entry->tagged =1; 580} 581return0; 582} 583 584staticinlinevoidadd_to_write_order(struct object_entry **wo, 585unsigned int*endp, 586struct object_entry *e) 587{ 588if(e->filled) 589return; 590 wo[(*endp)++] = e; 591 e->filled =1; 592} 593 594static voidadd_descendants_to_write_order(struct object_entry **wo, 595unsigned int*endp, 596struct object_entry *e) 597{ 598int add_to_order =1; 599while(e) { 600if(add_to_order) { 601struct object_entry *s; 602/* add this node... */ 603add_to_write_order(wo, endp, e); 604/* all its siblings... */ 605for(s = e->delta_sibling; s; s = s->delta_sibling) { 606add_to_write_order(wo, endp, s); 607} 608} 609/* drop down a level to add left subtree nodes if possible */ 610if(e->delta_child) { 611 add_to_order =1; 612 e = e->delta_child; 613}else{ 614 add_to_order =0; 615/* our sibling might have some children, it is next */ 616if(e->delta_sibling) { 617 e = e->delta_sibling; 618continue; 619} 620/* go back to our parent node */ 621 e = e->delta; 622while(e && !e->delta_sibling) { 623/* we're on the right side of a subtree, keep 624 * going up until we can go right again */ 625 e = e->delta; 626} 627if(!e) { 628/* done- we hit our original root node */ 629return; 630} 631/* pass it off to sibling at this level */ 632 e = e->delta_sibling; 633} 634}; 635} 636 637static voidadd_family_to_write_order(struct object_entry **wo, 638unsigned int*endp, 639struct object_entry *e) 640{ 641struct object_entry *root; 642 643for(root = e; root->delta; root = root->delta) 644;/* nothing */ 645add_descendants_to_write_order(wo, endp, root); 646} 647 648static struct object_entry **compute_write_order(void) 649{ 650unsigned int i, wo_end, last_untagged; 651 652struct object_entry **wo; 653struct object_entry *objects = to_pack.objects; 654 655for(i =0; i < to_pack.nr_objects; i++) { 656 objects[i].tagged =0; 657 objects[i].filled =0; 658 objects[i].delta_child = NULL; 659 objects[i].delta_sibling = NULL; 660} 661 662/* 663 * Fully connect delta_child/delta_sibling network. 664 * Make sure delta_sibling is sorted in the original 665 * recency order. 666 */ 667for(i = to_pack.nr_objects; i >0;) { 668struct object_entry *e = &objects[--i]; 669if(!e->delta) 670continue; 671/* Mark me as the first child */ 672 e->delta_sibling = e->delta->delta_child; 673 e->delta->delta_child = e; 674} 675 676/* 677 * Mark objects that are at the tip of tags. 678 */ 679for_each_tag_ref(mark_tagged, NULL); 680 681/* 682 * Give the objects in the original recency order until 683 * we see a tagged tip. 684 */ 685ALLOC_ARRAY(wo, to_pack.nr_objects); 686for(i = wo_end =0; i < to_pack.nr_objects; i++) { 687if(objects[i].tagged) 688break; 689add_to_write_order(wo, &wo_end, &objects[i]); 690} 691 last_untagged = i; 692 693/* 694 * Then fill all the tagged tips. 695 */ 696for(; i < to_pack.nr_objects; i++) { 697if(objects[i].tagged) 698add_to_write_order(wo, &wo_end, &objects[i]); 699} 700 701/* 702 * And then all remaining commits and tags. 703 */ 704for(i = last_untagged; i < to_pack.nr_objects; i++) { 705if(objects[i].type != OBJ_COMMIT && 706 objects[i].type != OBJ_TAG) 707continue; 708add_to_write_order(wo, &wo_end, &objects[i]); 709} 710 711/* 712 * And then all the trees. 713 */ 714for(i = last_untagged; i < to_pack.nr_objects; i++) { 715if(objects[i].type != OBJ_TREE) 716continue; 717add_to_write_order(wo, &wo_end, &objects[i]); 718} 719 720/* 721 * Finally all the rest in really tight order 722 */ 723for(i = last_untagged; i < to_pack.nr_objects; i++) { 724if(!objects[i].filled) 725add_family_to_write_order(wo, &wo_end, &objects[i]); 726} 727 728if(wo_end != to_pack.nr_objects) 729die("ordered%uobjects, expected %"PRIu32, wo_end, to_pack.nr_objects); 730 731return wo; 732} 733 734static off_t write_reused_pack(struct sha1file *f) 735{ 736unsigned char buffer[8192]; 737 off_t to_write, total; 738int fd; 739 740if(!is_pack_valid(reuse_packfile)) 741die("packfile is invalid:%s", reuse_packfile->pack_name); 742 743 fd =git_open(reuse_packfile->pack_name); 744if(fd <0) 745die_errno("unable to open packfile for reuse:%s", 746 reuse_packfile->pack_name); 747 748if(lseek(fd,sizeof(struct pack_header), SEEK_SET) == -1) 749die_errno("unable to seek in reused packfile"); 750 751if(reuse_packfile_offset <0) 752 reuse_packfile_offset = reuse_packfile->pack_size -20; 753 754 total = to_write = reuse_packfile_offset -sizeof(struct pack_header); 755 756while(to_write) { 757int read_pack =xread(fd, buffer,sizeof(buffer)); 758 759if(read_pack <=0) 760die_errno("unable to read from reused packfile"); 761 762if(read_pack > to_write) 763 read_pack = to_write; 764 765sha1write(f, buffer, read_pack); 766 to_write -= read_pack; 767 768/* 769 * We don't know the actual number of objects written, 770 * only how many bytes written, how many bytes total, and 771 * how many objects total. So we can fake it by pretending all 772 * objects we are writing are the same size. This gives us a 773 * smooth progress meter, and at the end it matches the true 774 * answer. 775 */ 776 written = reuse_packfile_objects * 777(((double)(total - to_write)) / total); 778display_progress(progress_state, written); 779} 780 781close(fd); 782 written = reuse_packfile_objects; 783display_progress(progress_state, written); 784return reuse_packfile_offset -sizeof(struct pack_header); 785} 786 787static const char no_split_warning[] =N_( 788"disabling bitmap writing, packs are split due to pack.packSizeLimit" 789); 790 791static voidwrite_pack_file(void) 792{ 793uint32_t i =0, j; 794struct sha1file *f; 795 off_t offset; 796uint32_t nr_remaining = nr_result; 797time_t last_mtime =0; 798struct object_entry **write_order; 799 800if(progress > pack_to_stdout) 801 progress_state =start_progress(_("Writing objects"), nr_result); 802ALLOC_ARRAY(written_list, to_pack.nr_objects); 803 write_order =compute_write_order(); 804 805do{ 806struct object_id oid; 807char*pack_tmp_name = NULL; 808 809if(pack_to_stdout) 810 f =sha1fd_throughput(1,"<stdout>", progress_state); 811else 812 f =create_tmp_packfile(&pack_tmp_name); 813 814 offset =write_pack_header(f, nr_remaining); 815 816if(reuse_packfile) { 817 off_t packfile_size; 818assert(pack_to_stdout); 819 820 packfile_size =write_reused_pack(f); 821 offset += packfile_size; 822} 823 824 nr_written =0; 825for(; i < to_pack.nr_objects; i++) { 826struct object_entry *e = write_order[i]; 827if(write_one(f, e, &offset) == WRITE_ONE_BREAK) 828break; 829display_progress(progress_state, written); 830} 831 832/* 833 * Did we write the wrong # entries in the header? 834 * If so, rewrite it like in fast-import 835 */ 836if(pack_to_stdout) { 837sha1close(f, oid.hash, CSUM_CLOSE); 838}else if(nr_written == nr_remaining) { 839sha1close(f, oid.hash, CSUM_FSYNC); 840}else{ 841int fd =sha1close(f, oid.hash,0); 842fixup_pack_header_footer(fd, oid.hash, pack_tmp_name, 843 nr_written, oid.hash, offset); 844close(fd); 845if(write_bitmap_index) { 846warning(_(no_split_warning)); 847 write_bitmap_index =0; 848} 849} 850 851if(!pack_to_stdout) { 852struct stat st; 853struct strbuf tmpname = STRBUF_INIT; 854 855/* 856 * Packs are runtime accessed in their mtime 857 * order since newer packs are more likely to contain 858 * younger objects. So if we are creating multiple 859 * packs then we should modify the mtime of later ones 860 * to preserve this property. 861 */ 862if(stat(pack_tmp_name, &st) <0) { 863warning_errno("failed to stat%s", pack_tmp_name); 864}else if(!last_mtime) { 865 last_mtime = st.st_mtime; 866}else{ 867struct utimbuf utb; 868 utb.actime = st.st_atime; 869 utb.modtime = --last_mtime; 870if(utime(pack_tmp_name, &utb) <0) 871warning_errno("failed utime() on%s", pack_tmp_name); 872} 873 874strbuf_addf(&tmpname,"%s-", base_name); 875 876if(write_bitmap_index) { 877bitmap_writer_set_checksum(oid.hash); 878bitmap_writer_build_type_index(written_list, nr_written); 879} 880 881finish_tmp_packfile(&tmpname, pack_tmp_name, 882 written_list, nr_written, 883&pack_idx_opts, oid.hash); 884 885if(write_bitmap_index) { 886strbuf_addf(&tmpname,"%s.bitmap",oid_to_hex(&oid)); 887 888stop_progress(&progress_state); 889 890bitmap_writer_show_progress(progress); 891bitmap_writer_reuse_bitmaps(&to_pack); 892bitmap_writer_select_commits(indexed_commits, indexed_commits_nr, -1); 893bitmap_writer_build(&to_pack); 894bitmap_writer_finish(written_list, nr_written, 895 tmpname.buf, write_bitmap_options); 896 write_bitmap_index =0; 897} 898 899strbuf_release(&tmpname); 900free(pack_tmp_name); 901puts(oid_to_hex(&oid)); 902} 903 904/* mark written objects as written to previous pack */ 905for(j =0; j < nr_written; j++) { 906 written_list[j]->offset = (off_t)-1; 907} 908 nr_remaining -= nr_written; 909}while(nr_remaining && i < to_pack.nr_objects); 910 911free(written_list); 912free(write_order); 913stop_progress(&progress_state); 914if(written != nr_result) 915die("wrote %"PRIu32" objects while expecting %"PRIu32, 916 written, nr_result); 917} 918 919static intno_try_delta(const char*path) 920{ 921static struct attr_check *check; 922 923if(!check) 924 check =attr_check_initl("delta", NULL); 925if(git_check_attr(path, check)) 926return0; 927if(ATTR_FALSE(check->items[0].value)) 928return1; 929return0; 930} 931 932/* 933 * When adding an object, check whether we have already added it 934 * to our packing list. If so, we can skip. However, if we are 935 * being asked to excludei t, but the previous mention was to include 936 * it, make sure to adjust its flags and tweak our numbers accordingly. 937 * 938 * As an optimization, we pass out the index position where we would have 939 * found the item, since that saves us from having to look it up again a 940 * few lines later when we want to add the new entry. 941 */ 942static inthave_duplicate_entry(const struct object_id *oid, 943int exclude, 944uint32_t*index_pos) 945{ 946struct object_entry *entry; 947 948 entry =packlist_find(&to_pack, oid->hash, index_pos); 949if(!entry) 950return0; 951 952if(exclude) { 953if(!entry->preferred_base) 954 nr_result--; 955 entry->preferred_base =1; 956} 957 958return1; 959} 960 961static intwant_found_object(int exclude,struct packed_git *p) 962{ 963if(exclude) 964return1; 965if(incremental) 966return0; 967 968/* 969 * When asked to do --local (do not include an object that appears in a 970 * pack we borrow from elsewhere) or --honor-pack-keep (do not include 971 * an object that appears in a pack marked with .keep), finding a pack 972 * that matches the criteria is sufficient for us to decide to omit it. 973 * However, even if this pack does not satisfy the criteria, we need to 974 * make sure no copy of this object appears in _any_ pack that makes us 975 * to omit the object, so we need to check all the packs. 976 * 977 * We can however first check whether these options can possible matter; 978 * if they do not matter we know we want the object in generated pack. 979 * Otherwise, we signal "-1" at the end to tell the caller that we do 980 * not know either way, and it needs to check more packs. 981 */ 982if(!ignore_packed_keep && 983(!local || !have_non_local_packs)) 984return1; 985 986if(local && !p->pack_local) 987return0; 988if(ignore_packed_keep && p->pack_local && p->pack_keep) 989return0; 990 991/* we don't know yet; keep looking for more packs */ 992return-1; 993} 994 995/* 996 * Check whether we want the object in the pack (e.g., we do not want 997 * objects found in non-local stores if the "--local" option was used). 998 * 999 * If the caller already knows an existing pack it wants to take the object1000 * from, that is passed in *found_pack and *found_offset; otherwise this1001 * function finds if there is any pack that has the object and returns the pack1002 * and its offset in these variables.1003 */1004static intwant_object_in_pack(const struct object_id *oid,1005int exclude,1006struct packed_git **found_pack,1007 off_t *found_offset)1008{1009struct mru_entry *entry;1010int want;10111012if(!exclude && local &&has_loose_object_nonlocal(oid->hash))1013return0;10141015/*1016 * If we already know the pack object lives in, start checks from that1017 * pack - in the usual case when neither --local was given nor .keep files1018 * are present we will determine the answer right now.1019 */1020if(*found_pack) {1021 want =want_found_object(exclude, *found_pack);1022if(want != -1)1023return want;1024}10251026for(entry = packed_git_mru.head; entry; entry = entry->next) {1027struct packed_git *p = entry->item;1028 off_t offset;10291030if(p == *found_pack)1031 offset = *found_offset;1032else1033 offset =find_pack_entry_one(oid->hash, p);10341035if(offset) {1036if(!*found_pack) {1037if(!is_pack_valid(p))1038continue;1039*found_offset = offset;1040*found_pack = p;1041}1042 want =want_found_object(exclude, p);1043if(!exclude && want >0)1044mru_mark(&packed_git_mru, entry);1045if(want != -1)1046return want;1047}1048}10491050return1;1051}10521053static voidcreate_object_entry(const struct object_id *oid,1054enum object_type type,1055uint32_t hash,1056int exclude,1057int no_try_delta,1058uint32_t index_pos,1059struct packed_git *found_pack,1060 off_t found_offset)1061{1062struct object_entry *entry;10631064 entry =packlist_alloc(&to_pack, oid->hash, index_pos);1065 entry->hash = hash;1066if(type)1067 entry->type = type;1068if(exclude)1069 entry->preferred_base =1;1070else1071 nr_result++;1072if(found_pack) {1073 entry->in_pack = found_pack;1074 entry->in_pack_offset = found_offset;1075}10761077 entry->no_try_delta = no_try_delta;1078}10791080static const char no_closure_warning[] =N_(1081"disabling bitmap writing, as some objects are not being packed"1082);10831084static intadd_object_entry(const struct object_id *oid,enum object_type type,1085const char*name,int exclude)1086{1087struct packed_git *found_pack = NULL;1088 off_t found_offset =0;1089uint32_t index_pos;10901091if(have_duplicate_entry(oid, exclude, &index_pos))1092return0;10931094if(!want_object_in_pack(oid, exclude, &found_pack, &found_offset)) {1095/* The pack is missing an object, so it will not have closure */1096if(write_bitmap_index) {1097warning(_(no_closure_warning));1098 write_bitmap_index =0;1099}1100return0;1101}11021103create_object_entry(oid, type,pack_name_hash(name),1104 exclude, name &&no_try_delta(name),1105 index_pos, found_pack, found_offset);11061107display_progress(progress_state, nr_result);1108return1;1109}11101111static intadd_object_entry_from_bitmap(const struct object_id *oid,1112enum object_type type,1113int flags,uint32_t name_hash,1114struct packed_git *pack, off_t offset)1115{1116uint32_t index_pos;11171118if(have_duplicate_entry(oid,0, &index_pos))1119return0;11201121if(!want_object_in_pack(oid,0, &pack, &offset))1122return0;11231124create_object_entry(oid, type, name_hash,0,0, index_pos, pack, offset);11251126display_progress(progress_state, nr_result);1127return1;1128}11291130struct pbase_tree_cache {1131struct object_id oid;1132int ref;1133int temporary;1134void*tree_data;1135unsigned long tree_size;1136};11371138static struct pbase_tree_cache *(pbase_tree_cache[256]);1139static intpbase_tree_cache_ix(const struct object_id *oid)1140{1141return oid->hash[0] %ARRAY_SIZE(pbase_tree_cache);1142}1143static intpbase_tree_cache_ix_incr(int ix)1144{1145return(ix+1) %ARRAY_SIZE(pbase_tree_cache);1146}11471148static struct pbase_tree {1149struct pbase_tree *next;1150/* This is a phony "cache" entry; we are not1151 * going to evict it or find it through _get()1152 * mechanism -- this is for the toplevel node that1153 * would almost always change with any commit.1154 */1155struct pbase_tree_cache pcache;1156} *pbase_tree;11571158static struct pbase_tree_cache *pbase_tree_get(const struct object_id *oid)1159{1160struct pbase_tree_cache *ent, *nent;1161void*data;1162unsigned long size;1163enum object_type type;1164int neigh;1165int my_ix =pbase_tree_cache_ix(oid);1166int available_ix = -1;11671168/* pbase-tree-cache acts as a limited hashtable.1169 * your object will be found at your index or within a few1170 * slots after that slot if it is cached.1171 */1172for(neigh =0; neigh <8; neigh++) {1173 ent = pbase_tree_cache[my_ix];1174if(ent && !oidcmp(&ent->oid, oid)) {1175 ent->ref++;1176return ent;1177}1178else if(((available_ix <0) && (!ent || !ent->ref)) ||1179((0<= available_ix) &&1180(!ent && pbase_tree_cache[available_ix])))1181 available_ix = my_ix;1182if(!ent)1183break;1184 my_ix =pbase_tree_cache_ix_incr(my_ix);1185}11861187/* Did not find one. Either we got a bogus request or1188 * we need to read and perhaps cache.1189 */1190 data =read_sha1_file(oid->hash, &type, &size);1191if(!data)1192return NULL;1193if(type != OBJ_TREE) {1194free(data);1195return NULL;1196}11971198/* We need to either cache or return a throwaway copy */11991200if(available_ix <0)1201 ent = NULL;1202else{1203 ent = pbase_tree_cache[available_ix];1204 my_ix = available_ix;1205}12061207if(!ent) {1208 nent =xmalloc(sizeof(*nent));1209 nent->temporary = (available_ix <0);1210}1211else{1212/* evict and reuse */1213free(ent->tree_data);1214 nent = ent;1215}1216oidcpy(&nent->oid, oid);1217 nent->tree_data = data;1218 nent->tree_size = size;1219 nent->ref =1;1220if(!nent->temporary)1221 pbase_tree_cache[my_ix] = nent;1222return nent;1223}12241225static voidpbase_tree_put(struct pbase_tree_cache *cache)1226{1227if(!cache->temporary) {1228 cache->ref--;1229return;1230}1231free(cache->tree_data);1232free(cache);1233}12341235static intname_cmp_len(const char*name)1236{1237int i;1238for(i =0; name[i] && name[i] !='\n'&& name[i] !='/'; i++)1239;1240return i;1241}12421243static voidadd_pbase_object(struct tree_desc *tree,1244const char*name,1245int cmplen,1246const char*fullname)1247{1248struct name_entry entry;1249int cmp;12501251while(tree_entry(tree,&entry)) {1252if(S_ISGITLINK(entry.mode))1253continue;1254 cmp =tree_entry_len(&entry) != cmplen ?1:1255memcmp(name, entry.path, cmplen);1256if(cmp >0)1257continue;1258if(cmp <0)1259return;1260if(name[cmplen] !='/') {1261add_object_entry(entry.oid,1262object_type(entry.mode),1263 fullname,1);1264return;1265}1266if(S_ISDIR(entry.mode)) {1267struct tree_desc sub;1268struct pbase_tree_cache *tree;1269const char*down = name+cmplen+1;1270int downlen =name_cmp_len(down);12711272 tree =pbase_tree_get(entry.oid);1273if(!tree)1274return;1275init_tree_desc(&sub, tree->tree_data, tree->tree_size);12761277add_pbase_object(&sub, down, downlen, fullname);1278pbase_tree_put(tree);1279}1280}1281}12821283static unsigned*done_pbase_paths;1284static int done_pbase_paths_num;1285static int done_pbase_paths_alloc;1286static intdone_pbase_path_pos(unsigned hash)1287{1288int lo =0;1289int hi = done_pbase_paths_num;1290while(lo < hi) {1291int mi = lo + (hi - lo) /2;1292if(done_pbase_paths[mi] == hash)1293return mi;1294if(done_pbase_paths[mi] < hash)1295 hi = mi;1296else1297 lo = mi +1;1298}1299return-lo-1;1300}13011302static intcheck_pbase_path(unsigned hash)1303{1304int pos =done_pbase_path_pos(hash);1305if(0<= pos)1306return1;1307 pos = -pos -1;1308ALLOC_GROW(done_pbase_paths,1309 done_pbase_paths_num +1,1310 done_pbase_paths_alloc);1311 done_pbase_paths_num++;1312if(pos < done_pbase_paths_num)1313MOVE_ARRAY(done_pbase_paths + pos +1, done_pbase_paths + pos,1314 done_pbase_paths_num - pos -1);1315 done_pbase_paths[pos] = hash;1316return0;1317}13181319static voidadd_preferred_base_object(const char*name)1320{1321struct pbase_tree *it;1322int cmplen;1323unsigned hash =pack_name_hash(name);13241325if(!num_preferred_base ||check_pbase_path(hash))1326return;13271328 cmplen =name_cmp_len(name);1329for(it = pbase_tree; it; it = it->next) {1330if(cmplen ==0) {1331add_object_entry(&it->pcache.oid, OBJ_TREE, NULL,1);1332}1333else{1334struct tree_desc tree;1335init_tree_desc(&tree, it->pcache.tree_data, it->pcache.tree_size);1336add_pbase_object(&tree, name, cmplen, name);1337}1338}1339}13401341static voidadd_preferred_base(struct object_id *oid)1342{1343struct pbase_tree *it;1344void*data;1345unsigned long size;1346struct object_id tree_oid;13471348if(window <= num_preferred_base++)1349return;13501351 data =read_object_with_reference(oid->hash, tree_type, &size, tree_oid.hash);1352if(!data)1353return;13541355for(it = pbase_tree; it; it = it->next) {1356if(!oidcmp(&it->pcache.oid, &tree_oid)) {1357free(data);1358return;1359}1360}13611362 it =xcalloc(1,sizeof(*it));1363 it->next = pbase_tree;1364 pbase_tree = it;13651366oidcpy(&it->pcache.oid, &tree_oid);1367 it->pcache.tree_data = data;1368 it->pcache.tree_size = size;1369}13701371static voidcleanup_preferred_base(void)1372{1373struct pbase_tree *it;1374unsigned i;13751376 it = pbase_tree;1377 pbase_tree = NULL;1378while(it) {1379struct pbase_tree *this= it;1380 it =this->next;1381free(this->pcache.tree_data);1382free(this);1383}13841385for(i =0; i <ARRAY_SIZE(pbase_tree_cache); i++) {1386if(!pbase_tree_cache[i])1387continue;1388free(pbase_tree_cache[i]->tree_data);1389FREE_AND_NULL(pbase_tree_cache[i]);1390}13911392FREE_AND_NULL(done_pbase_paths);1393 done_pbase_paths_num = done_pbase_paths_alloc =0;1394}13951396static voidcheck_object(struct object_entry *entry)1397{1398if(entry->in_pack) {1399struct packed_git *p = entry->in_pack;1400struct pack_window *w_curs = NULL;1401const unsigned char*base_ref = NULL;1402struct object_entry *base_entry;1403unsigned long used, used_0;1404unsigned long avail;1405 off_t ofs;1406unsigned char*buf, c;14071408 buf =use_pack(p, &w_curs, entry->in_pack_offset, &avail);14091410/*1411 * We want in_pack_type even if we do not reuse delta1412 * since non-delta representations could still be reused.1413 */1414 used =unpack_object_header_buffer(buf, avail,1415&entry->in_pack_type,1416&entry->size);1417if(used ==0)1418goto give_up;14191420/*1421 * Determine if this is a delta and if so whether we can1422 * reuse it or not. Otherwise let's find out as cheaply as1423 * possible what the actual type and size for this object is.1424 */1425switch(entry->in_pack_type) {1426default:1427/* Not a delta hence we've already got all we need. */1428 entry->type = entry->in_pack_type;1429 entry->in_pack_header_size = used;1430if(entry->type < OBJ_COMMIT || entry->type > OBJ_BLOB)1431goto give_up;1432unuse_pack(&w_curs);1433return;1434case OBJ_REF_DELTA:1435if(reuse_delta && !entry->preferred_base)1436 base_ref =use_pack(p, &w_curs,1437 entry->in_pack_offset + used, NULL);1438 entry->in_pack_header_size = used +20;1439break;1440case OBJ_OFS_DELTA:1441 buf =use_pack(p, &w_curs,1442 entry->in_pack_offset + used, NULL);1443 used_0 =0;1444 c = buf[used_0++];1445 ofs = c &127;1446while(c &128) {1447 ofs +=1;1448if(!ofs ||MSB(ofs,7)) {1449error("delta base offset overflow in pack for%s",1450oid_to_hex(&entry->idx.oid));1451goto give_up;1452}1453 c = buf[used_0++];1454 ofs = (ofs <<7) + (c &127);1455}1456 ofs = entry->in_pack_offset - ofs;1457if(ofs <=0|| ofs >= entry->in_pack_offset) {1458error("delta base offset out of bound for%s",1459oid_to_hex(&entry->idx.oid));1460goto give_up;1461}1462if(reuse_delta && !entry->preferred_base) {1463struct revindex_entry *revidx;1464 revidx =find_pack_revindex(p, ofs);1465if(!revidx)1466goto give_up;1467 base_ref =nth_packed_object_sha1(p, revidx->nr);1468}1469 entry->in_pack_header_size = used + used_0;1470break;1471}14721473if(base_ref && (base_entry =packlist_find(&to_pack, base_ref, NULL))) {1474/*1475 * If base_ref was set above that means we wish to1476 * reuse delta data, and we even found that base1477 * in the list of objects we want to pack. Goodie!1478 *1479 * Depth value does not matter - find_deltas() will1480 * never consider reused delta as the base object to1481 * deltify other objects against, in order to avoid1482 * circular deltas.1483 */1484 entry->type = entry->in_pack_type;1485 entry->delta = base_entry;1486 entry->delta_size = entry->size;1487 entry->delta_sibling = base_entry->delta_child;1488 base_entry->delta_child = entry;1489unuse_pack(&w_curs);1490return;1491}14921493if(entry->type) {1494/*1495 * This must be a delta and we already know what the1496 * final object type is. Let's extract the actual1497 * object size from the delta header.1498 */1499 entry->size =get_size_from_delta(p, &w_curs,1500 entry->in_pack_offset + entry->in_pack_header_size);1501if(entry->size ==0)1502goto give_up;1503unuse_pack(&w_curs);1504return;1505}15061507/*1508 * No choice but to fall back to the recursive delta walk1509 * with sha1_object_info() to find about the object type1510 * at this point...1511 */1512 give_up:1513unuse_pack(&w_curs);1514}15151516 entry->type =sha1_object_info(entry->idx.oid.hash, &entry->size);1517/*1518 * The error condition is checked in prepare_pack(). This is1519 * to permit a missing preferred base object to be ignored1520 * as a preferred base. Doing so can result in a larger1521 * pack file, but the transfer will still take place.1522 */1523}15241525static intpack_offset_sort(const void*_a,const void*_b)1526{1527const struct object_entry *a = *(struct object_entry **)_a;1528const struct object_entry *b = *(struct object_entry **)_b;15291530/* avoid filesystem trashing with loose objects */1531if(!a->in_pack && !b->in_pack)1532returnoidcmp(&a->idx.oid, &b->idx.oid);15331534if(a->in_pack < b->in_pack)1535return-1;1536if(a->in_pack > b->in_pack)1537return1;1538return a->in_pack_offset < b->in_pack_offset ? -1:1539(a->in_pack_offset > b->in_pack_offset);1540}15411542/*1543 * Drop an on-disk delta we were planning to reuse. Naively, this would1544 * just involve blanking out the "delta" field, but we have to deal1545 * with some extra book-keeping:1546 *1547 * 1. Removing ourselves from the delta_sibling linked list.1548 *1549 * 2. Updating our size/type to the non-delta representation. These were1550 * either not recorded initially (size) or overwritten with the delta type1551 * (type) when check_object() decided to reuse the delta.1552 *1553 * 3. Resetting our delta depth, as we are now a base object.1554 */1555static voiddrop_reused_delta(struct object_entry *entry)1556{1557struct object_entry **p = &entry->delta->delta_child;1558struct object_info oi = OBJECT_INFO_INIT;15591560while(*p) {1561if(*p == entry)1562*p = (*p)->delta_sibling;1563else1564 p = &(*p)->delta_sibling;1565}1566 entry->delta = NULL;1567 entry->depth =0;15681569 oi.sizep = &entry->size;1570 oi.typep = &entry->type;1571if(packed_object_info(entry->in_pack, entry->in_pack_offset, &oi) <0) {1572/*1573 * We failed to get the info from this pack for some reason;1574 * fall back to sha1_object_info, which may find another copy.1575 * And if that fails, the error will be recorded in entry->type1576 * and dealt with in prepare_pack().1577 */1578 entry->type =sha1_object_info(entry->idx.oid.hash,1579&entry->size);1580}1581}15821583/*1584 * Follow the chain of deltas from this entry onward, throwing away any links1585 * that cause us to hit a cycle (as determined by the DFS state flags in1586 * the entries).1587 *1588 * We also detect too-long reused chains that would violate our --depth1589 * limit.1590 */1591static voidbreak_delta_chains(struct object_entry *entry)1592{1593/*1594 * The actual depth of each object we will write is stored as an int,1595 * as it cannot exceed our int "depth" limit. But before we break1596 * changes based no that limit, we may potentially go as deep as the1597 * number of objects, which is elsewhere bounded to a uint32_t.1598 */1599uint32_t total_depth;1600struct object_entry *cur, *next;16011602for(cur = entry, total_depth =0;1603 cur;1604 cur = cur->delta, total_depth++) {1605if(cur->dfs_state == DFS_DONE) {1606/*1607 * We've already seen this object and know it isn't1608 * part of a cycle. We do need to append its depth1609 * to our count.1610 */1611 total_depth += cur->depth;1612break;1613}16141615/*1616 * We break cycles before looping, so an ACTIVE state (or any1617 * other cruft which made its way into the state variable)1618 * is a bug.1619 */1620if(cur->dfs_state != DFS_NONE)1621die("BUG: confusing delta dfs state in first pass:%d",1622 cur->dfs_state);16231624/*1625 * Now we know this is the first time we've seen the object. If1626 * it's not a delta, we're done traversing, but we'll mark it1627 * done to save time on future traversals.1628 */1629if(!cur->delta) {1630 cur->dfs_state = DFS_DONE;1631break;1632}16331634/*1635 * Mark ourselves as active and see if the next step causes1636 * us to cycle to another active object. It's important to do1637 * this _before_ we loop, because it impacts where we make the1638 * cut, and thus how our total_depth counter works.1639 * E.g., We may see a partial loop like:1640 *1641 * A -> B -> C -> D -> B1642 *1643 * Cutting B->C breaks the cycle. But now the depth of A is1644 * only 1, and our total_depth counter is at 3. The size of the1645 * error is always one less than the size of the cycle we1646 * broke. Commits C and D were "lost" from A's chain.1647 *1648 * If we instead cut D->B, then the depth of A is correct at 3.1649 * We keep all commits in the chain that we examined.1650 */1651 cur->dfs_state = DFS_ACTIVE;1652if(cur->delta->dfs_state == DFS_ACTIVE) {1653drop_reused_delta(cur);1654 cur->dfs_state = DFS_DONE;1655break;1656}1657}16581659/*1660 * And now that we've gone all the way to the bottom of the chain, we1661 * need to clear the active flags and set the depth fields as1662 * appropriate. Unlike the loop above, which can quit when it drops a1663 * delta, we need to keep going to look for more depth cuts. So we need1664 * an extra "next" pointer to keep going after we reset cur->delta.1665 */1666for(cur = entry; cur; cur = next) {1667 next = cur->delta;16681669/*1670 * We should have a chain of zero or more ACTIVE states down to1671 * a final DONE. We can quit after the DONE, because either it1672 * has no bases, or we've already handled them in a previous1673 * call.1674 */1675if(cur->dfs_state == DFS_DONE)1676break;1677else if(cur->dfs_state != DFS_ACTIVE)1678die("BUG: confusing delta dfs state in second pass:%d",1679 cur->dfs_state);16801681/*1682 * If the total_depth is more than depth, then we need to snip1683 * the chain into two or more smaller chains that don't exceed1684 * the maximum depth. Most of the resulting chains will contain1685 * (depth + 1) entries (i.e., depth deltas plus one base), and1686 * the last chain (i.e., the one containing entry) will contain1687 * whatever entries are left over, namely1688 * (total_depth % (depth + 1)) of them.1689 *1690 * Since we are iterating towards decreasing depth, we need to1691 * decrement total_depth as we go, and we need to write to the1692 * entry what its final depth will be after all of the1693 * snipping. Since we're snipping into chains of length (depth1694 * + 1) entries, the final depth of an entry will be its1695 * original depth modulo (depth + 1). Any time we encounter an1696 * entry whose final depth is supposed to be zero, we snip it1697 * from its delta base, thereby making it so.1698 */1699 cur->depth = (total_depth--) % (depth +1);1700if(!cur->depth)1701drop_reused_delta(cur);17021703 cur->dfs_state = DFS_DONE;1704}1705}17061707static voidget_object_details(void)1708{1709uint32_t i;1710struct object_entry **sorted_by_offset;17111712 sorted_by_offset =xcalloc(to_pack.nr_objects,sizeof(struct object_entry *));1713for(i =0; i < to_pack.nr_objects; i++)1714 sorted_by_offset[i] = to_pack.objects + i;1715QSORT(sorted_by_offset, to_pack.nr_objects, pack_offset_sort);17161717for(i =0; i < to_pack.nr_objects; i++) {1718struct object_entry *entry = sorted_by_offset[i];1719check_object(entry);1720if(big_file_threshold < entry->size)1721 entry->no_try_delta =1;1722}17231724/*1725 * This must happen in a second pass, since we rely on the delta1726 * information for the whole list being completed.1727 */1728for(i =0; i < to_pack.nr_objects; i++)1729break_delta_chains(&to_pack.objects[i]);17301731free(sorted_by_offset);1732}17331734/*1735 * We search for deltas in a list sorted by type, by filename hash, and then1736 * by size, so that we see progressively smaller and smaller files.1737 * That's because we prefer deltas to be from the bigger file1738 * to the smaller -- deletes are potentially cheaper, but perhaps1739 * more importantly, the bigger file is likely the more recent1740 * one. The deepest deltas are therefore the oldest objects which are1741 * less susceptible to be accessed often.1742 */1743static inttype_size_sort(const void*_a,const void*_b)1744{1745const struct object_entry *a = *(struct object_entry **)_a;1746const struct object_entry *b = *(struct object_entry **)_b;17471748if(a->type > b->type)1749return-1;1750if(a->type < b->type)1751return1;1752if(a->hash > b->hash)1753return-1;1754if(a->hash < b->hash)1755return1;1756if(a->preferred_base > b->preferred_base)1757return-1;1758if(a->preferred_base < b->preferred_base)1759return1;1760if(a->size > b->size)1761return-1;1762if(a->size < b->size)1763return1;1764return a < b ? -1: (a > b);/* newest first */1765}17661767struct unpacked {1768struct object_entry *entry;1769void*data;1770struct delta_index *index;1771unsigned depth;1772};17731774static intdelta_cacheable(unsigned long src_size,unsigned long trg_size,1775unsigned long delta_size)1776{1777if(max_delta_cache_size && delta_cache_size + delta_size > max_delta_cache_size)1778return0;17791780if(delta_size < cache_max_small_delta_size)1781return1;17821783/* cache delta, if objects are large enough compared to delta size */1784if((src_size >>20) + (trg_size >>21) > (delta_size >>10))1785return1;17861787return0;1788}17891790#ifndef NO_PTHREADS17911792static pthread_mutex_t read_mutex;1793#define read_lock() pthread_mutex_lock(&read_mutex)1794#define read_unlock() pthread_mutex_unlock(&read_mutex)17951796static pthread_mutex_t cache_mutex;1797#define cache_lock() pthread_mutex_lock(&cache_mutex)1798#define cache_unlock() pthread_mutex_unlock(&cache_mutex)17991800static pthread_mutex_t progress_mutex;1801#define progress_lock() pthread_mutex_lock(&progress_mutex)1802#define progress_unlock() pthread_mutex_unlock(&progress_mutex)18031804#else18051806#define read_lock() (void)01807#define read_unlock() (void)01808#define cache_lock() (void)01809#define cache_unlock() (void)01810#define progress_lock() (void)01811#define progress_unlock() (void)018121813#endif18141815static inttry_delta(struct unpacked *trg,struct unpacked *src,1816unsigned max_depth,unsigned long*mem_usage)1817{1818struct object_entry *trg_entry = trg->entry;1819struct object_entry *src_entry = src->entry;1820unsigned long trg_size, src_size, delta_size, sizediff, max_size, sz;1821unsigned ref_depth;1822enum object_type type;1823void*delta_buf;18241825/* Don't bother doing diffs between different types */1826if(trg_entry->type != src_entry->type)1827return-1;18281829/*1830 * We do not bother to try a delta that we discarded on an1831 * earlier try, but only when reusing delta data. Note that1832 * src_entry that is marked as the preferred_base should always1833 * be considered, as even if we produce a suboptimal delta against1834 * it, we will still save the transfer cost, as we already know1835 * the other side has it and we won't send src_entry at all.1836 */1837if(reuse_delta && trg_entry->in_pack &&1838 trg_entry->in_pack == src_entry->in_pack &&1839!src_entry->preferred_base &&1840 trg_entry->in_pack_type != OBJ_REF_DELTA &&1841 trg_entry->in_pack_type != OBJ_OFS_DELTA)1842return0;18431844/* Let's not bust the allowed depth. */1845if(src->depth >= max_depth)1846return0;18471848/* Now some size filtering heuristics. */1849 trg_size = trg_entry->size;1850if(!trg_entry->delta) {1851 max_size = trg_size/2-20;1852 ref_depth =1;1853}else{1854 max_size = trg_entry->delta_size;1855 ref_depth = trg->depth;1856}1857 max_size = (uint64_t)max_size * (max_depth - src->depth) /1858(max_depth - ref_depth +1);1859if(max_size ==0)1860return0;1861 src_size = src_entry->size;1862 sizediff = src_size < trg_size ? trg_size - src_size :0;1863if(sizediff >= max_size)1864return0;1865if(trg_size < src_size /32)1866return0;18671868/* Load data if not already done */1869if(!trg->data) {1870read_lock();1871 trg->data =read_sha1_file(trg_entry->idx.oid.hash, &type,1872&sz);1873read_unlock();1874if(!trg->data)1875die("object%scannot be read",1876oid_to_hex(&trg_entry->idx.oid));1877if(sz != trg_size)1878die("object%sinconsistent object length (%lu vs%lu)",1879oid_to_hex(&trg_entry->idx.oid), sz,1880 trg_size);1881*mem_usage += sz;1882}1883if(!src->data) {1884read_lock();1885 src->data =read_sha1_file(src_entry->idx.oid.hash, &type,1886&sz);1887read_unlock();1888if(!src->data) {1889if(src_entry->preferred_base) {1890static int warned =0;1891if(!warned++)1892warning("object%scannot be read",1893oid_to_hex(&src_entry->idx.oid));1894/*1895 * Those objects are not included in the1896 * resulting pack. Be resilient and ignore1897 * them if they can't be read, in case the1898 * pack could be created nevertheless.1899 */1900return0;1901}1902die("object%scannot be read",1903oid_to_hex(&src_entry->idx.oid));1904}1905if(sz != src_size)1906die("object%sinconsistent object length (%lu vs%lu)",1907oid_to_hex(&src_entry->idx.oid), sz,1908 src_size);1909*mem_usage += sz;1910}1911if(!src->index) {1912 src->index =create_delta_index(src->data, src_size);1913if(!src->index) {1914static int warned =0;1915if(!warned++)1916warning("suboptimal pack - out of memory");1917return0;1918}1919*mem_usage +=sizeof_delta_index(src->index);1920}19211922 delta_buf =create_delta(src->index, trg->data, trg_size, &delta_size, max_size);1923if(!delta_buf)1924return0;19251926if(trg_entry->delta) {1927/* Prefer only shallower same-sized deltas. */1928if(delta_size == trg_entry->delta_size &&1929 src->depth +1>= trg->depth) {1930free(delta_buf);1931return0;1932}1933}19341935/*1936 * Handle memory allocation outside of the cache1937 * accounting lock. Compiler will optimize the strangeness1938 * away when NO_PTHREADS is defined.1939 */1940free(trg_entry->delta_data);1941cache_lock();1942if(trg_entry->delta_data) {1943 delta_cache_size -= trg_entry->delta_size;1944 trg_entry->delta_data = NULL;1945}1946if(delta_cacheable(src_size, trg_size, delta_size)) {1947 delta_cache_size += delta_size;1948cache_unlock();1949 trg_entry->delta_data =xrealloc(delta_buf, delta_size);1950}else{1951cache_unlock();1952free(delta_buf);1953}19541955 trg_entry->delta = src_entry;1956 trg_entry->delta_size = delta_size;1957 trg->depth = src->depth +1;19581959return1;1960}19611962static unsigned intcheck_delta_limit(struct object_entry *me,unsigned int n)1963{1964struct object_entry *child = me->delta_child;1965unsigned int m = n;1966while(child) {1967unsigned int c =check_delta_limit(child, n +1);1968if(m < c)1969 m = c;1970 child = child->delta_sibling;1971}1972return m;1973}19741975static unsigned longfree_unpacked(struct unpacked *n)1976{1977unsigned long freed_mem =sizeof_delta_index(n->index);1978free_delta_index(n->index);1979 n->index = NULL;1980if(n->data) {1981 freed_mem += n->entry->size;1982FREE_AND_NULL(n->data);1983}1984 n->entry = NULL;1985 n->depth =0;1986return freed_mem;1987}19881989static voidfind_deltas(struct object_entry **list,unsigned*list_size,1990int window,int depth,unsigned*processed)1991{1992uint32_t i, idx =0, count =0;1993struct unpacked *array;1994unsigned long mem_usage =0;19951996 array =xcalloc(window,sizeof(struct unpacked));19971998for(;;) {1999struct object_entry *entry;2000struct unpacked *n = array + idx;2001int j, max_depth, best_base = -1;20022003progress_lock();2004if(!*list_size) {2005progress_unlock();2006break;2007}2008 entry = *list++;2009(*list_size)--;2010if(!entry->preferred_base) {2011(*processed)++;2012display_progress(progress_state, *processed);2013}2014progress_unlock();20152016 mem_usage -=free_unpacked(n);2017 n->entry = entry;20182019while(window_memory_limit &&2020 mem_usage > window_memory_limit &&2021 count >1) {2022uint32_t tail = (idx + window - count) % window;2023 mem_usage -=free_unpacked(array + tail);2024 count--;2025}20262027/* We do not compute delta to *create* objects we are not2028 * going to pack.2029 */2030if(entry->preferred_base)2031goto next;20322033/*2034 * If the current object is at pack edge, take the depth the2035 * objects that depend on the current object into account2036 * otherwise they would become too deep.2037 */2038 max_depth = depth;2039if(entry->delta_child) {2040 max_depth -=check_delta_limit(entry,0);2041if(max_depth <=0)2042goto next;2043}20442045 j = window;2046while(--j >0) {2047int ret;2048uint32_t other_idx = idx + j;2049struct unpacked *m;2050if(other_idx >= window)2051 other_idx -= window;2052 m = array + other_idx;2053if(!m->entry)2054break;2055 ret =try_delta(n, m, max_depth, &mem_usage);2056if(ret <0)2057break;2058else if(ret >0)2059 best_base = other_idx;2060}20612062/*2063 * If we decided to cache the delta data, then it is best2064 * to compress it right away. First because we have to do2065 * it anyway, and doing it here while we're threaded will2066 * save a lot of time in the non threaded write phase,2067 * as well as allow for caching more deltas within2068 * the same cache size limit.2069 * ...2070 * But only if not writing to stdout, since in that case2071 * the network is most likely throttling writes anyway,2072 * and therefore it is best to go to the write phase ASAP2073 * instead, as we can afford spending more time compressing2074 * between writes at that moment.2075 */2076if(entry->delta_data && !pack_to_stdout) {2077 entry->z_delta_size =do_compress(&entry->delta_data,2078 entry->delta_size);2079cache_lock();2080 delta_cache_size -= entry->delta_size;2081 delta_cache_size += entry->z_delta_size;2082cache_unlock();2083}20842085/* if we made n a delta, and if n is already at max2086 * depth, leaving it in the window is pointless. we2087 * should evict it first.2088 */2089if(entry->delta && max_depth <= n->depth)2090continue;20912092/*2093 * Move the best delta base up in the window, after the2094 * currently deltified object, to keep it longer. It will2095 * be the first base object to be attempted next.2096 */2097if(entry->delta) {2098struct unpacked swap = array[best_base];2099int dist = (window + idx - best_base) % window;2100int dst = best_base;2101while(dist--) {2102int src = (dst +1) % window;2103 array[dst] = array[src];2104 dst = src;2105}2106 array[dst] = swap;2107}21082109 next:2110 idx++;2111if(count +1< window)2112 count++;2113if(idx >= window)2114 idx =0;2115}21162117for(i =0; i < window; ++i) {2118free_delta_index(array[i].index);2119free(array[i].data);2120}2121free(array);2122}21232124#ifndef NO_PTHREADS21252126static voidtry_to_free_from_threads(size_t size)2127{2128read_lock();2129release_pack_memory(size);2130read_unlock();2131}21322133static try_to_free_t old_try_to_free_routine;21342135/*2136 * The main thread waits on the condition that (at least) one of the workers2137 * has stopped working (which is indicated in the .working member of2138 * struct thread_params).2139 * When a work thread has completed its work, it sets .working to 0 and2140 * signals the main thread and waits on the condition that .data_ready2141 * becomes 1.2142 */21432144struct thread_params {2145 pthread_t thread;2146struct object_entry **list;2147unsigned list_size;2148unsigned remaining;2149int window;2150int depth;2151int working;2152int data_ready;2153 pthread_mutex_t mutex;2154 pthread_cond_t cond;2155unsigned*processed;2156};21572158static pthread_cond_t progress_cond;21592160/*2161 * Mutex and conditional variable can't be statically-initialized on Windows.2162 */2163static voidinit_threaded_search(void)2164{2165init_recursive_mutex(&read_mutex);2166pthread_mutex_init(&cache_mutex, NULL);2167pthread_mutex_init(&progress_mutex, NULL);2168pthread_cond_init(&progress_cond, NULL);2169 old_try_to_free_routine =set_try_to_free_routine(try_to_free_from_threads);2170}21712172static voidcleanup_threaded_search(void)2173{2174set_try_to_free_routine(old_try_to_free_routine);2175pthread_cond_destroy(&progress_cond);2176pthread_mutex_destroy(&read_mutex);2177pthread_mutex_destroy(&cache_mutex);2178pthread_mutex_destroy(&progress_mutex);2179}21802181static void*threaded_find_deltas(void*arg)2182{2183struct thread_params *me = arg;21842185progress_lock();2186while(me->remaining) {2187progress_unlock();21882189find_deltas(me->list, &me->remaining,2190 me->window, me->depth, me->processed);21912192progress_lock();2193 me->working =0;2194pthread_cond_signal(&progress_cond);2195progress_unlock();21962197/*2198 * We must not set ->data_ready before we wait on the2199 * condition because the main thread may have set it to 12200 * before we get here. In order to be sure that new2201 * work is available if we see 1 in ->data_ready, it2202 * was initialized to 0 before this thread was spawned2203 * and we reset it to 0 right away.2204 */2205pthread_mutex_lock(&me->mutex);2206while(!me->data_ready)2207pthread_cond_wait(&me->cond, &me->mutex);2208 me->data_ready =0;2209pthread_mutex_unlock(&me->mutex);22102211progress_lock();2212}2213progress_unlock();2214/* leave ->working 1 so that this doesn't get more work assigned */2215return NULL;2216}22172218static voidll_find_deltas(struct object_entry **list,unsigned list_size,2219int window,int depth,unsigned*processed)2220{2221struct thread_params *p;2222int i, ret, active_threads =0;22232224init_threaded_search();22252226if(delta_search_threads <=1) {2227find_deltas(list, &list_size, window, depth, processed);2228cleanup_threaded_search();2229return;2230}2231if(progress > pack_to_stdout)2232fprintf(stderr,"Delta compression using up to%dthreads.\n",2233 delta_search_threads);2234 p =xcalloc(delta_search_threads,sizeof(*p));22352236/* Partition the work amongst work threads. */2237for(i =0; i < delta_search_threads; i++) {2238unsigned sub_size = list_size / (delta_search_threads - i);22392240/* don't use too small segments or no deltas will be found */2241if(sub_size <2*window && i+1< delta_search_threads)2242 sub_size =0;22432244 p[i].window = window;2245 p[i].depth = depth;2246 p[i].processed = processed;2247 p[i].working =1;2248 p[i].data_ready =0;22492250/* try to split chunks on "path" boundaries */2251while(sub_size && sub_size < list_size &&2252 list[sub_size]->hash &&2253 list[sub_size]->hash == list[sub_size-1]->hash)2254 sub_size++;22552256 p[i].list = list;2257 p[i].list_size = sub_size;2258 p[i].remaining = sub_size;22592260 list += sub_size;2261 list_size -= sub_size;2262}22632264/* Start work threads. */2265for(i =0; i < delta_search_threads; i++) {2266if(!p[i].list_size)2267continue;2268pthread_mutex_init(&p[i].mutex, NULL);2269pthread_cond_init(&p[i].cond, NULL);2270 ret =pthread_create(&p[i].thread, NULL,2271 threaded_find_deltas, &p[i]);2272if(ret)2273die("unable to create thread:%s",strerror(ret));2274 active_threads++;2275}22762277/*2278 * Now let's wait for work completion. Each time a thread is done2279 * with its work, we steal half of the remaining work from the2280 * thread with the largest number of unprocessed objects and give2281 * it to that newly idle thread. This ensure good load balancing2282 * until the remaining object list segments are simply too short2283 * to be worth splitting anymore.2284 */2285while(active_threads) {2286struct thread_params *target = NULL;2287struct thread_params *victim = NULL;2288unsigned sub_size =0;22892290progress_lock();2291for(;;) {2292for(i =0; !target && i < delta_search_threads; i++)2293if(!p[i].working)2294 target = &p[i];2295if(target)2296break;2297pthread_cond_wait(&progress_cond, &progress_mutex);2298}22992300for(i =0; i < delta_search_threads; i++)2301if(p[i].remaining >2*window &&2302(!victim || victim->remaining < p[i].remaining))2303 victim = &p[i];2304if(victim) {2305 sub_size = victim->remaining /2;2306 list = victim->list + victim->list_size - sub_size;2307while(sub_size && list[0]->hash &&2308 list[0]->hash == list[-1]->hash) {2309 list++;2310 sub_size--;2311}2312if(!sub_size) {2313/*2314 * It is possible for some "paths" to have2315 * so many objects that no hash boundary2316 * might be found. Let's just steal the2317 * exact half in that case.2318 */2319 sub_size = victim->remaining /2;2320 list -= sub_size;2321}2322 target->list = list;2323 victim->list_size -= sub_size;2324 victim->remaining -= sub_size;2325}2326 target->list_size = sub_size;2327 target->remaining = sub_size;2328 target->working =1;2329progress_unlock();23302331pthread_mutex_lock(&target->mutex);2332 target->data_ready =1;2333pthread_cond_signal(&target->cond);2334pthread_mutex_unlock(&target->mutex);23352336if(!sub_size) {2337pthread_join(target->thread, NULL);2338pthread_cond_destroy(&target->cond);2339pthread_mutex_destroy(&target->mutex);2340 active_threads--;2341}2342}2343cleanup_threaded_search();2344free(p);2345}23462347#else2348#define ll_find_deltas(l, s, w, d, p) find_deltas(l, &s, w, d, p)2349#endif23502351static voidadd_tag_chain(const struct object_id *oid)2352{2353struct tag *tag;23542355/*2356 * We catch duplicates already in add_object_entry(), but we'd2357 * prefer to do this extra check to avoid having to parse the2358 * tag at all if we already know that it's being packed (e.g., if2359 * it was included via bitmaps, we would not have parsed it2360 * previously).2361 */2362if(packlist_find(&to_pack, oid->hash, NULL))2363return;23642365 tag =lookup_tag(oid);2366while(1) {2367if(!tag ||parse_tag(tag) || !tag->tagged)2368die("unable to pack objects reachable from tag%s",2369oid_to_hex(oid));23702371add_object_entry(&tag->object.oid, OBJ_TAG, NULL,0);23722373if(tag->tagged->type != OBJ_TAG)2374return;23752376 tag = (struct tag *)tag->tagged;2377}2378}23792380static intadd_ref_tag(const char*path,const struct object_id *oid,int flag,void*cb_data)2381{2382struct object_id peeled;23832384if(starts_with(path,"refs/tags/") &&/* is a tag? */2385!peel_ref(path, &peeled) &&/* peelable? */2386packlist_find(&to_pack, peeled.hash, NULL))/* object packed? */2387add_tag_chain(oid);2388return0;2389}23902391static voidprepare_pack(int window,int depth)2392{2393struct object_entry **delta_list;2394uint32_t i, nr_deltas;2395unsigned n;23962397get_object_details();23982399/*2400 * If we're locally repacking then we need to be doubly careful2401 * from now on in order to make sure no stealth corruption gets2402 * propagated to the new pack. Clients receiving streamed packs2403 * should validate everything they get anyway so no need to incur2404 * the additional cost here in that case.2405 */2406if(!pack_to_stdout)2407 do_check_packed_object_crc =1;24082409if(!to_pack.nr_objects || !window || !depth)2410return;24112412ALLOC_ARRAY(delta_list, to_pack.nr_objects);2413 nr_deltas = n =0;24142415for(i =0; i < to_pack.nr_objects; i++) {2416struct object_entry *entry = to_pack.objects + i;24172418if(entry->delta)2419/* This happens if we decided to reuse existing2420 * delta from a pack. "reuse_delta &&" is implied.2421 */2422continue;24232424if(entry->size <50)2425continue;24262427if(entry->no_try_delta)2428continue;24292430if(!entry->preferred_base) {2431 nr_deltas++;2432if(entry->type <0)2433die("unable to get type of object%s",2434oid_to_hex(&entry->idx.oid));2435}else{2436if(entry->type <0) {2437/*2438 * This object is not found, but we2439 * don't have to include it anyway.2440 */2441continue;2442}2443}24442445 delta_list[n++] = entry;2446}24472448if(nr_deltas && n >1) {2449unsigned nr_done =0;2450if(progress)2451 progress_state =start_progress(_("Compressing objects"),2452 nr_deltas);2453QSORT(delta_list, n, type_size_sort);2454ll_find_deltas(delta_list, n, window+1, depth, &nr_done);2455stop_progress(&progress_state);2456if(nr_done != nr_deltas)2457die("inconsistency with delta count");2458}2459free(delta_list);2460}24612462static intgit_pack_config(const char*k,const char*v,void*cb)2463{2464if(!strcmp(k,"pack.window")) {2465 window =git_config_int(k, v);2466return0;2467}2468if(!strcmp(k,"pack.windowmemory")) {2469 window_memory_limit =git_config_ulong(k, v);2470return0;2471}2472if(!strcmp(k,"pack.depth")) {2473 depth =git_config_int(k, v);2474return0;2475}2476if(!strcmp(k,"pack.deltacachesize")) {2477 max_delta_cache_size =git_config_int(k, v);2478return0;2479}2480if(!strcmp(k,"pack.deltacachelimit")) {2481 cache_max_small_delta_size =git_config_int(k, v);2482return0;2483}2484if(!strcmp(k,"pack.writebitmaphashcache")) {2485if(git_config_bool(k, v))2486 write_bitmap_options |= BITMAP_OPT_HASH_CACHE;2487else2488 write_bitmap_options &= ~BITMAP_OPT_HASH_CACHE;2489}2490if(!strcmp(k,"pack.usebitmaps")) {2491 use_bitmap_index_default =git_config_bool(k, v);2492return0;2493}2494if(!strcmp(k,"pack.threads")) {2495 delta_search_threads =git_config_int(k, v);2496if(delta_search_threads <0)2497die("invalid number of threads specified (%d)",2498 delta_search_threads);2499#ifdef NO_PTHREADS2500if(delta_search_threads !=1) {2501warning("no threads support, ignoring%s", k);2502 delta_search_threads =0;2503}2504#endif2505return0;2506}2507if(!strcmp(k,"pack.indexversion")) {2508 pack_idx_opts.version =git_config_int(k, v);2509if(pack_idx_opts.version >2)2510die("bad pack.indexversion=%"PRIu32,2511 pack_idx_opts.version);2512return0;2513}2514returngit_default_config(k, v, cb);2515}25162517static voidread_object_list_from_stdin(void)2518{2519char line[GIT_MAX_HEXSZ +1+ PATH_MAX +2];2520struct object_id oid;2521const char*p;25222523for(;;) {2524if(!fgets(line,sizeof(line), stdin)) {2525if(feof(stdin))2526break;2527if(!ferror(stdin))2528die("fgets returned NULL, not EOF, not error!");2529if(errno != EINTR)2530die_errno("fgets");2531clearerr(stdin);2532continue;2533}2534if(line[0] =='-') {2535if(get_oid_hex(line+1, &oid))2536die("expected edge object ID, got garbage:\n%s",2537 line);2538add_preferred_base(&oid);2539continue;2540}2541if(parse_oid_hex(line, &oid, &p))2542die("expected object ID, got garbage:\n%s", line);25432544add_preferred_base_object(p +1);2545add_object_entry(&oid,0, p +1,0);2546}2547}25482549#define OBJECT_ADDED (1u<<20)25502551static voidshow_commit(struct commit *commit,void*data)2552{2553add_object_entry(&commit->object.oid, OBJ_COMMIT, NULL,0);2554 commit->object.flags |= OBJECT_ADDED;25552556if(write_bitmap_index)2557index_commit_for_bitmap(commit);2558}25592560static voidshow_object(struct object *obj,const char*name,void*data)2561{2562add_preferred_base_object(name);2563add_object_entry(&obj->oid, obj->type, name,0);2564 obj->flags |= OBJECT_ADDED;2565}25662567static voidshow_object__ma_allow_any(struct object *obj,const char*name,void*data)2568{2569assert(arg_missing_action == MA_ALLOW_ANY);25702571/*2572 * Quietly ignore ALL missing objects. This avoids problems with2573 * staging them now and getting an odd error later.2574 */2575if(!has_object_file(&obj->oid))2576return;25772578show_object(obj, name, data);2579}25802581static intoption_parse_missing_action(const struct option *opt,2582const char*arg,int unset)2583{2584assert(arg);2585assert(!unset);25862587if(!strcmp(arg,"error")) {2588 arg_missing_action = MA_ERROR;2589 fn_show_object = show_object;2590return0;2591}25922593if(!strcmp(arg,"allow-any")) {2594 arg_missing_action = MA_ALLOW_ANY;2595 fn_show_object = show_object__ma_allow_any;2596return0;2597}25982599die(_("invalid value for --missing"));2600return0;2601}26022603static voidshow_edge(struct commit *commit)2604{2605add_preferred_base(&commit->object.oid);2606}26072608struct in_pack_object {2609 off_t offset;2610struct object *object;2611};26122613struct in_pack {2614unsigned int alloc;2615unsigned int nr;2616struct in_pack_object *array;2617};26182619static voidmark_in_pack_object(struct object *object,struct packed_git *p,struct in_pack *in_pack)2620{2621 in_pack->array[in_pack->nr].offset =find_pack_entry_one(object->oid.hash, p);2622 in_pack->array[in_pack->nr].object = object;2623 in_pack->nr++;2624}26252626/*2627 * Compare the objects in the offset order, in order to emulate the2628 * "git rev-list --objects" output that produced the pack originally.2629 */2630static intofscmp(const void*a_,const void*b_)2631{2632struct in_pack_object *a = (struct in_pack_object *)a_;2633struct in_pack_object *b = (struct in_pack_object *)b_;26342635if(a->offset < b->offset)2636return-1;2637else if(a->offset > b->offset)2638return1;2639else2640returnoidcmp(&a->object->oid, &b->object->oid);2641}26422643static voidadd_objects_in_unpacked_packs(struct rev_info *revs)2644{2645struct packed_git *p;2646struct in_pack in_pack;2647uint32_t i;26482649memset(&in_pack,0,sizeof(in_pack));26502651for(p = packed_git; p; p = p->next) {2652struct object_id oid;2653struct object *o;26542655if(!p->pack_local || p->pack_keep)2656continue;2657if(open_pack_index(p))2658die("cannot open pack index");26592660ALLOC_GROW(in_pack.array,2661 in_pack.nr + p->num_objects,2662 in_pack.alloc);26632664for(i =0; i < p->num_objects; i++) {2665nth_packed_object_oid(&oid, p, i);2666 o =lookup_unknown_object(oid.hash);2667if(!(o->flags & OBJECT_ADDED))2668mark_in_pack_object(o, p, &in_pack);2669 o->flags |= OBJECT_ADDED;2670}2671}26722673if(in_pack.nr) {2674QSORT(in_pack.array, in_pack.nr, ofscmp);2675for(i =0; i < in_pack.nr; i++) {2676struct object *o = in_pack.array[i].object;2677add_object_entry(&o->oid, o->type,"",0);2678}2679}2680free(in_pack.array);2681}26822683static intadd_loose_object(const struct object_id *oid,const char*path,2684void*data)2685{2686enum object_type type =sha1_object_info(oid->hash, NULL);26872688if(type <0) {2689warning("loose object at%scould not be examined", path);2690return0;2691}26922693add_object_entry(oid, type,"",0);2694return0;2695}26962697/*2698 * We actually don't even have to worry about reachability here.2699 * add_object_entry will weed out duplicates, so we just add every2700 * loose object we find.2701 */2702static voidadd_unreachable_loose_objects(void)2703{2704for_each_loose_file_in_objdir(get_object_directory(),2705 add_loose_object,2706 NULL, NULL, NULL);2707}27082709static inthas_sha1_pack_kept_or_nonlocal(const struct object_id *oid)2710{2711static struct packed_git *last_found = (void*)1;2712struct packed_git *p;27132714 p = (last_found != (void*)1) ? last_found : packed_git;27152716while(p) {2717if((!p->pack_local || p->pack_keep) &&2718find_pack_entry_one(oid->hash, p)) {2719 last_found = p;2720return1;2721}2722if(p == last_found)2723 p = packed_git;2724else2725 p = p->next;2726if(p == last_found)2727 p = p->next;2728}2729return0;2730}27312732/*2733 * Store a list of sha1s that are should not be discarded2734 * because they are either written too recently, or are2735 * reachable from another object that was.2736 *2737 * This is filled by get_object_list.2738 */2739static struct oid_array recent_objects;27402741static intloosened_object_can_be_discarded(const struct object_id *oid,2742 timestamp_t mtime)2743{2744if(!unpack_unreachable_expiration)2745return0;2746if(mtime > unpack_unreachable_expiration)2747return0;2748if(oid_array_lookup(&recent_objects, oid) >=0)2749return0;2750return1;2751}27522753static voidloosen_unused_packed_objects(struct rev_info *revs)2754{2755struct packed_git *p;2756uint32_t i;2757struct object_id oid;27582759for(p = packed_git; p; p = p->next) {2760if(!p->pack_local || p->pack_keep)2761continue;27622763if(open_pack_index(p))2764die("cannot open pack index");27652766for(i =0; i < p->num_objects; i++) {2767nth_packed_object_oid(&oid, p, i);2768if(!packlist_find(&to_pack, oid.hash, NULL) &&2769!has_sha1_pack_kept_or_nonlocal(&oid) &&2770!loosened_object_can_be_discarded(&oid, p->mtime))2771if(force_object_loose(oid.hash, p->mtime))2772die("unable to force loose object");2773}2774}2775}27762777/*2778 * This tracks any options which pack-reuse code expects to be on, or which a2779 * reader of the pack might not understand, and which would therefore prevent2780 * blind reuse of what we have on disk.2781 */2782static intpack_options_allow_reuse(void)2783{2784return pack_to_stdout &&2785 allow_ofs_delta &&2786!ignore_packed_keep &&2787(!local || !have_non_local_packs) &&2788!incremental;2789}27902791static intget_object_list_from_bitmap(struct rev_info *revs)2792{2793if(prepare_bitmap_walk(revs) <0)2794return-1;27952796if(pack_options_allow_reuse() &&2797!reuse_partial_packfile_from_bitmap(2798&reuse_packfile,2799&reuse_packfile_objects,2800&reuse_packfile_offset)) {2801assert(reuse_packfile_objects);2802 nr_result += reuse_packfile_objects;2803display_progress(progress_state, nr_result);2804}28052806traverse_bitmap_commit_list(&add_object_entry_from_bitmap);2807return0;2808}28092810static voidrecord_recent_object(struct object *obj,2811const char*name,2812void*data)2813{2814oid_array_append(&recent_objects, &obj->oid);2815}28162817static voidrecord_recent_commit(struct commit *commit,void*data)2818{2819oid_array_append(&recent_objects, &commit->object.oid);2820}28212822static voidget_object_list(int ac,const char**av)2823{2824struct rev_info revs;2825char line[1000];2826int flags =0;28272828init_revisions(&revs, NULL);2829 save_commit_buffer =0;2830setup_revisions(ac, av, &revs, NULL);28312832/* make sure shallows are read */2833is_repository_shallow();28342835while(fgets(line,sizeof(line), stdin) != NULL) {2836int len =strlen(line);2837if(len && line[len -1] =='\n')2838 line[--len] =0;2839if(!len)2840break;2841if(*line =='-') {2842if(!strcmp(line,"--not")) {2843 flags ^= UNINTERESTING;2844 write_bitmap_index =0;2845continue;2846}2847if(starts_with(line,"--shallow ")) {2848struct object_id oid;2849if(get_oid_hex(line +10, &oid))2850die("not an SHA-1 '%s'", line +10);2851register_shallow(&oid);2852 use_bitmap_index =0;2853continue;2854}2855die("not a rev '%s'", line);2856}2857if(handle_revision_arg(line, &revs, flags, REVARG_CANNOT_BE_FILENAME))2858die("bad revision '%s'", line);2859}28602861if(use_bitmap_index && !get_object_list_from_bitmap(&revs))2862return;28632864if(prepare_revision_walk(&revs))2865die("revision walk setup failed");2866mark_edges_uninteresting(&revs, show_edge);28672868if(!fn_show_object)2869 fn_show_object = show_object;2870traverse_commit_list_filtered(&filter_options, &revs,2871 show_commit, fn_show_object, NULL,2872 NULL);28732874if(unpack_unreachable_expiration) {2875 revs.ignore_missing_links =1;2876if(add_unseen_recent_objects_to_traversal(&revs,2877 unpack_unreachable_expiration))2878die("unable to add recent objects");2879if(prepare_revision_walk(&revs))2880die("revision walk setup failed");2881traverse_commit_list(&revs, record_recent_commit,2882 record_recent_object, NULL);2883}28842885if(keep_unreachable)2886add_objects_in_unpacked_packs(&revs);2887if(pack_loose_unreachable)2888add_unreachable_loose_objects();2889if(unpack_unreachable)2890loosen_unused_packed_objects(&revs);28912892oid_array_clear(&recent_objects);2893}28942895static intoption_parse_index_version(const struct option *opt,2896const char*arg,int unset)2897{2898char*c;2899const char*val = arg;2900 pack_idx_opts.version =strtoul(val, &c,10);2901if(pack_idx_opts.version >2)2902die(_("unsupported index version%s"), val);2903if(*c ==','&& c[1])2904 pack_idx_opts.off32_limit =strtoul(c+1, &c,0);2905if(*c || pack_idx_opts.off32_limit &0x80000000)2906die(_("bad index version '%s'"), val);2907return0;2908}29092910static intoption_parse_unpack_unreachable(const struct option *opt,2911const char*arg,int unset)2912{2913if(unset) {2914 unpack_unreachable =0;2915 unpack_unreachable_expiration =0;2916}2917else{2918 unpack_unreachable =1;2919if(arg)2920 unpack_unreachable_expiration =approxidate(arg);2921}2922return0;2923}29242925intcmd_pack_objects(int argc,const char**argv,const char*prefix)2926{2927int use_internal_rev_list =0;2928int thin =0;2929int shallow =0;2930int all_progress_implied =0;2931struct argv_array rp = ARGV_ARRAY_INIT;2932int rev_list_unpacked =0, rev_list_all =0, rev_list_reflog =0;2933int rev_list_index =0;2934struct option pack_objects_options[] = {2935OPT_SET_INT('q',"quiet", &progress,2936N_("do not show progress meter"),0),2937OPT_SET_INT(0,"progress", &progress,2938N_("show progress meter"),1),2939OPT_SET_INT(0,"all-progress", &progress,2940N_("show progress meter during object writing phase"),2),2941OPT_BOOL(0,"all-progress-implied",2942&all_progress_implied,2943N_("similar to --all-progress when progress meter is shown")),2944{ OPTION_CALLBACK,0,"index-version", NULL,N_("version[,offset]"),2945N_("write the pack index file in the specified idx format version"),29460, option_parse_index_version },2947OPT_MAGNITUDE(0,"max-pack-size", &pack_size_limit,2948N_("maximum size of each output pack file")),2949OPT_BOOL(0,"local", &local,2950N_("ignore borrowed objects from alternate object store")),2951OPT_BOOL(0,"incremental", &incremental,2952N_("ignore packed objects")),2953OPT_INTEGER(0,"window", &window,2954N_("limit pack window by objects")),2955OPT_MAGNITUDE(0,"window-memory", &window_memory_limit,2956N_("limit pack window by memory in addition to object limit")),2957OPT_INTEGER(0,"depth", &depth,2958N_("maximum length of delta chain allowed in the resulting pack")),2959OPT_BOOL(0,"reuse-delta", &reuse_delta,2960N_("reuse existing deltas")),2961OPT_BOOL(0,"reuse-object", &reuse_object,2962N_("reuse existing objects")),2963OPT_BOOL(0,"delta-base-offset", &allow_ofs_delta,2964N_("use OFS_DELTA objects")),2965OPT_INTEGER(0,"threads", &delta_search_threads,2966N_("use threads when searching for best delta matches")),2967OPT_BOOL(0,"non-empty", &non_empty,2968N_("do not create an empty pack output")),2969OPT_BOOL(0,"revs", &use_internal_rev_list,2970N_("read revision arguments from standard input")),2971{ OPTION_SET_INT,0,"unpacked", &rev_list_unpacked, NULL,2972N_("limit the objects to those that are not yet packed"),2973 PARSE_OPT_NOARG | PARSE_OPT_NONEG, NULL,1},2974{ OPTION_SET_INT,0,"all", &rev_list_all, NULL,2975N_("include objects reachable from any reference"),2976 PARSE_OPT_NOARG | PARSE_OPT_NONEG, NULL,1},2977{ OPTION_SET_INT,0,"reflog", &rev_list_reflog, NULL,2978N_("include objects referred by reflog entries"),2979 PARSE_OPT_NOARG | PARSE_OPT_NONEG, NULL,1},2980{ OPTION_SET_INT,0,"indexed-objects", &rev_list_index, NULL,2981N_("include objects referred to by the index"),2982 PARSE_OPT_NOARG | PARSE_OPT_NONEG, NULL,1},2983OPT_BOOL(0,"stdout", &pack_to_stdout,2984N_("output pack to stdout")),2985OPT_BOOL(0,"include-tag", &include_tag,2986N_("include tag objects that refer to objects to be packed")),2987OPT_BOOL(0,"keep-unreachable", &keep_unreachable,2988N_("keep unreachable objects")),2989OPT_BOOL(0,"pack-loose-unreachable", &pack_loose_unreachable,2990N_("pack loose unreachable objects")),2991{ OPTION_CALLBACK,0,"unpack-unreachable", NULL,N_("time"),2992N_("unpack unreachable objects newer than <time>"),2993 PARSE_OPT_OPTARG, option_parse_unpack_unreachable },2994OPT_BOOL(0,"thin", &thin,2995N_("create thin packs")),2996OPT_BOOL(0,"shallow", &shallow,2997N_("create packs suitable for shallow fetches")),2998OPT_BOOL(0,"honor-pack-keep", &ignore_packed_keep,2999N_("ignore packs that have companion .keep file")),3000OPT_INTEGER(0,"compression", &pack_compression_level,3001N_("pack compression level")),3002OPT_SET_INT(0,"keep-true-parents", &grafts_replace_parents,3003N_("do not hide commits by grafts"),0),3004OPT_BOOL(0,"use-bitmap-index", &use_bitmap_index,3005N_("use a bitmap index if available to speed up counting objects")),3006OPT_BOOL(0,"write-bitmap-index", &write_bitmap_index,3007N_("write a bitmap index together with the pack index")),3008OPT_PARSE_LIST_OBJECTS_FILTER(&filter_options),3009{ OPTION_CALLBACK,0,"missing", NULL,N_("action"),3010N_("handling for missing objects"), PARSE_OPT_NONEG,3011 option_parse_missing_action },3012OPT_END(),3013};30143015 check_replace_refs =0;30163017reset_pack_idx_option(&pack_idx_opts);3018git_config(git_pack_config, NULL);30193020 progress =isatty(2);3021 argc =parse_options(argc, argv, prefix, pack_objects_options,3022 pack_usage,0);30233024if(argc) {3025 base_name = argv[0];3026 argc--;3027}3028if(pack_to_stdout != !base_name || argc)3029usage_with_options(pack_usage, pack_objects_options);30303031argv_array_push(&rp,"pack-objects");3032if(thin) {3033 use_internal_rev_list =1;3034argv_array_push(&rp, shallow3035?"--objects-edge-aggressive"3036:"--objects-edge");3037}else3038argv_array_push(&rp,"--objects");30393040if(rev_list_all) {3041 use_internal_rev_list =1;3042argv_array_push(&rp,"--all");3043}3044if(rev_list_reflog) {3045 use_internal_rev_list =1;3046argv_array_push(&rp,"--reflog");3047}3048if(rev_list_index) {3049 use_internal_rev_list =1;3050argv_array_push(&rp,"--indexed-objects");3051}3052if(rev_list_unpacked) {3053 use_internal_rev_list =1;3054argv_array_push(&rp,"--unpacked");3055}30563057if(!reuse_object)3058 reuse_delta =0;3059if(pack_compression_level == -1)3060 pack_compression_level = Z_DEFAULT_COMPRESSION;3061else if(pack_compression_level <0|| pack_compression_level > Z_BEST_COMPRESSION)3062die("bad pack compression level%d", pack_compression_level);30633064if(!delta_search_threads)/* --threads=0 means autodetect */3065 delta_search_threads =online_cpus();30663067#ifdef NO_PTHREADS3068if(delta_search_threads !=1)3069warning("no threads support, ignoring --threads");3070#endif3071if(!pack_to_stdout && !pack_size_limit)3072 pack_size_limit = pack_size_limit_cfg;3073if(pack_to_stdout && pack_size_limit)3074die("--max-pack-size cannot be used to build a pack for transfer.");3075if(pack_size_limit && pack_size_limit <1024*1024) {3076warning("minimum pack size limit is 1 MiB");3077 pack_size_limit =1024*1024;3078}30793080if(!pack_to_stdout && thin)3081die("--thin cannot be used to build an indexable pack.");30823083if(keep_unreachable && unpack_unreachable)3084die("--keep-unreachable and --unpack-unreachable are incompatible.");3085if(!rev_list_all || !rev_list_reflog || !rev_list_index)3086 unpack_unreachable_expiration =0;30873088if(filter_options.choice) {3089if(!pack_to_stdout)3090die("cannot use --filter without --stdout.");3091 use_bitmap_index =0;3092}30933094/*3095 * "soft" reasons not to use bitmaps - for on-disk repack by default we want3096 *3097 * - to produce good pack (with bitmap index not-yet-packed objects are3098 * packed in suboptimal order).3099 *3100 * - to use more robust pack-generation codepath (avoiding possible3101 * bugs in bitmap code and possible bitmap index corruption).3102 */3103if(!pack_to_stdout)3104 use_bitmap_index_default =0;31053106if(use_bitmap_index <0)3107 use_bitmap_index = use_bitmap_index_default;31083109/* "hard" reasons not to use bitmaps; these just won't work at all */3110if(!use_internal_rev_list || (!pack_to_stdout && write_bitmap_index) ||is_repository_shallow())3111 use_bitmap_index =0;31123113if(pack_to_stdout || !rev_list_all)3114 write_bitmap_index =0;31153116if(progress && all_progress_implied)3117 progress =2;31183119prepare_packed_git();3120if(ignore_packed_keep) {3121struct packed_git *p;3122for(p = packed_git; p; p = p->next)3123if(p->pack_local && p->pack_keep)3124break;3125if(!p)/* no keep-able packs found */3126 ignore_packed_keep =0;3127}3128if(local) {3129/*3130 * unlike ignore_packed_keep above, we do not want to3131 * unset "local" based on looking at packs, as it3132 * also covers non-local objects3133 */3134struct packed_git *p;3135for(p = packed_git; p; p = p->next) {3136if(!p->pack_local) {3137 have_non_local_packs =1;3138break;3139}3140}3141}31423143if(progress)3144 progress_state =start_progress(_("Counting objects"),0);3145if(!use_internal_rev_list)3146read_object_list_from_stdin();3147else{3148get_object_list(rp.argc, rp.argv);3149argv_array_clear(&rp);3150}3151cleanup_preferred_base();3152if(include_tag && nr_result)3153for_each_ref(add_ref_tag, NULL);3154stop_progress(&progress_state);31553156if(non_empty && !nr_result)3157return0;3158if(nr_result)3159prepare_pack(window, depth);3160write_pack_file();3161if(progress)3162fprintf(stderr,"Total %"PRIu32" (delta %"PRIu32"),"3163" reused %"PRIu32" (delta %"PRIu32")\n",3164 written, written_delta, reused, reused_delta);3165return0;3166}