1#include"builtin.h" 2#include"cache.h" 3#include"repository.h" 4#include"config.h" 5#include"attr.h" 6#include"object.h" 7#include"blob.h" 8#include"commit.h" 9#include"tag.h" 10#include"tree.h" 11#include"delta.h" 12#include"pack.h" 13#include"pack-revindex.h" 14#include"csum-file.h" 15#include"tree-walk.h" 16#include"diff.h" 17#include"revision.h" 18#include"list-objects.h" 19#include"list-objects-filter.h" 20#include"list-objects-filter-options.h" 21#include"pack-objects.h" 22#include"progress.h" 23#include"refs.h" 24#include"streaming.h" 25#include"thread-utils.h" 26#include"pack-bitmap.h" 27#include"delta-islands.h" 28#include"reachable.h" 29#include"sha1-array.h" 30#include"argv-array.h" 31#include"list.h" 32#include"packfile.h" 33#include"object-store.h" 34#include"dir.h" 35#include"midx.h" 36#include"trace2.h" 37 38#define IN_PACK(obj) oe_in_pack(&to_pack, obj) 39#define SIZE(obj) oe_size(&to_pack, obj) 40#define SET_SIZE(obj,size) oe_set_size(&to_pack, obj, size) 41#define DELTA_SIZE(obj) oe_delta_size(&to_pack, obj) 42#define DELTA(obj) oe_delta(&to_pack, obj) 43#define DELTA_CHILD(obj) oe_delta_child(&to_pack, obj) 44#define DELTA_SIBLING(obj) oe_delta_sibling(&to_pack, obj) 45#define SET_DELTA(obj, val) oe_set_delta(&to_pack, obj, val) 46#define SET_DELTA_EXT(obj, oid) oe_set_delta_ext(&to_pack, obj, oid) 47#define SET_DELTA_SIZE(obj, val) oe_set_delta_size(&to_pack, obj, val) 48#define SET_DELTA_CHILD(obj, val) oe_set_delta_child(&to_pack, obj, val) 49#define SET_DELTA_SIBLING(obj, val) oe_set_delta_sibling(&to_pack, obj, val) 50 51static const char*pack_usage[] = { 52N_("git pack-objects --stdout [<options>...] [< <ref-list> | < <object-list>]"), 53N_("git pack-objects [<options>...] <base-name> [< <ref-list> | < <object-list>]"), 54 NULL 55}; 56 57/* 58 * Objects we are going to pack are collected in the `to_pack` structure. 59 * It contains an array (dynamically expanded) of the object data, and a map 60 * that can resolve SHA1s to their position in the array. 61 */ 62static struct packing_data to_pack; 63 64static struct pack_idx_entry **written_list; 65static uint32_t nr_result, nr_written, nr_seen; 66static struct bitmap_index *bitmap_git; 67static uint32_t write_layer; 68 69static int non_empty; 70static int reuse_delta =1, reuse_object =1; 71static int keep_unreachable, unpack_unreachable, include_tag; 72static timestamp_t unpack_unreachable_expiration; 73static int pack_loose_unreachable; 74static int local; 75static int have_non_local_packs; 76static int incremental; 77static int ignore_packed_keep_on_disk; 78static int ignore_packed_keep_in_core; 79static int allow_ofs_delta; 80static struct pack_idx_option pack_idx_opts; 81static const char*base_name; 82static int progress =1; 83static int window =10; 84static unsigned long pack_size_limit; 85static int depth =50; 86static int delta_search_threads; 87static int pack_to_stdout; 88static int sparse; 89static int thin; 90static int num_preferred_base; 91static struct progress *progress_state; 92 93static struct packed_git *reuse_packfile; 94static uint32_t reuse_packfile_objects; 95static off_t reuse_packfile_offset; 96 97static int use_bitmap_index_default =1; 98static int use_bitmap_index = -1; 99static int write_bitmap_index; 100static uint16_t write_bitmap_options = BITMAP_OPT_HASH_CACHE; 101 102static int exclude_promisor_objects; 103 104static int use_delta_islands; 105 106static unsigned long delta_cache_size =0; 107static unsigned long max_delta_cache_size = DEFAULT_DELTA_CACHE_SIZE; 108static unsigned long cache_max_small_delta_size =1000; 109 110static unsigned long window_memory_limit =0; 111 112static struct list_objects_filter_options filter_options; 113 114enum missing_action { 115 MA_ERROR =0,/* fail if any missing objects are encountered */ 116 MA_ALLOW_ANY,/* silently allow ALL missing objects */ 117 MA_ALLOW_PROMISOR,/* silently allow all missing PROMISOR objects */ 118}; 119static enum missing_action arg_missing_action; 120static show_object_fn fn_show_object; 121 122/* 123 * stats 124 */ 125static uint32_t written, written_delta; 126static uint32_t reused, reused_delta; 127 128/* 129 * Indexed commits 130 */ 131static struct commit **indexed_commits; 132static unsigned int indexed_commits_nr; 133static unsigned int indexed_commits_alloc; 134 135static voidindex_commit_for_bitmap(struct commit *commit) 136{ 137if(indexed_commits_nr >= indexed_commits_alloc) { 138 indexed_commits_alloc = (indexed_commits_alloc +32) *2; 139REALLOC_ARRAY(indexed_commits, indexed_commits_alloc); 140} 141 142 indexed_commits[indexed_commits_nr++] = commit; 143} 144 145static void*get_delta(struct object_entry *entry) 146{ 147unsigned long size, base_size, delta_size; 148void*buf, *base_buf, *delta_buf; 149enum object_type type; 150 151 buf =read_object_file(&entry->idx.oid, &type, &size); 152if(!buf) 153die(_("unable to read%s"),oid_to_hex(&entry->idx.oid)); 154 base_buf =read_object_file(&DELTA(entry)->idx.oid, &type, 155&base_size); 156if(!base_buf) 157die("unable to read%s", 158oid_to_hex(&DELTA(entry)->idx.oid)); 159 delta_buf =diff_delta(base_buf, base_size, 160 buf, size, &delta_size,0); 161/* 162 * We succesfully computed this delta once but dropped it for 163 * memory reasons. Something is very wrong if this time we 164 * recompute and create a different delta. 165 */ 166if(!delta_buf || delta_size !=DELTA_SIZE(entry)) 167BUG("delta size changed"); 168free(buf); 169free(base_buf); 170return delta_buf; 171} 172 173static unsigned longdo_compress(void**pptr,unsigned long size) 174{ 175 git_zstream stream; 176void*in, *out; 177unsigned long maxsize; 178 179git_deflate_init(&stream, pack_compression_level); 180 maxsize =git_deflate_bound(&stream, size); 181 182 in = *pptr; 183 out =xmalloc(maxsize); 184*pptr = out; 185 186 stream.next_in = in; 187 stream.avail_in = size; 188 stream.next_out = out; 189 stream.avail_out = maxsize; 190while(git_deflate(&stream, Z_FINISH) == Z_OK) 191;/* nothing */ 192git_deflate_end(&stream); 193 194free(in); 195return stream.total_out; 196} 197 198static unsigned longwrite_large_blob_data(struct git_istream *st,struct hashfile *f, 199const struct object_id *oid) 200{ 201 git_zstream stream; 202unsigned char ibuf[1024*16]; 203unsigned char obuf[1024*16]; 204unsigned long olen =0; 205 206git_deflate_init(&stream, pack_compression_level); 207 208for(;;) { 209 ssize_t readlen; 210int zret = Z_OK; 211 readlen =read_istream(st, ibuf,sizeof(ibuf)); 212if(readlen == -1) 213die(_("unable to read%s"),oid_to_hex(oid)); 214 215 stream.next_in = ibuf; 216 stream.avail_in = readlen; 217while((stream.avail_in || readlen ==0) && 218(zret == Z_OK || zret == Z_BUF_ERROR)) { 219 stream.next_out = obuf; 220 stream.avail_out =sizeof(obuf); 221 zret =git_deflate(&stream, readlen ?0: Z_FINISH); 222hashwrite(f, obuf, stream.next_out - obuf); 223 olen += stream.next_out - obuf; 224} 225if(stream.avail_in) 226die(_("deflate error (%d)"), zret); 227if(readlen ==0) { 228if(zret != Z_STREAM_END) 229die(_("deflate error (%d)"), zret); 230break; 231} 232} 233git_deflate_end(&stream); 234return olen; 235} 236 237/* 238 * we are going to reuse the existing object data as is. make 239 * sure it is not corrupt. 240 */ 241static intcheck_pack_inflate(struct packed_git *p, 242struct pack_window **w_curs, 243 off_t offset, 244 off_t len, 245unsigned long expect) 246{ 247 git_zstream stream; 248unsigned char fakebuf[4096], *in; 249int st; 250 251memset(&stream,0,sizeof(stream)); 252git_inflate_init(&stream); 253do{ 254 in =use_pack(p, w_curs, offset, &stream.avail_in); 255 stream.next_in = in; 256 stream.next_out = fakebuf; 257 stream.avail_out =sizeof(fakebuf); 258 st =git_inflate(&stream, Z_FINISH); 259 offset += stream.next_in - in; 260}while(st == Z_OK || st == Z_BUF_ERROR); 261git_inflate_end(&stream); 262return(st == Z_STREAM_END && 263 stream.total_out == expect && 264 stream.total_in == len) ?0: -1; 265} 266 267static voidcopy_pack_data(struct hashfile *f, 268struct packed_git *p, 269struct pack_window **w_curs, 270 off_t offset, 271 off_t len) 272{ 273unsigned char*in; 274unsigned long avail; 275 276while(len) { 277 in =use_pack(p, w_curs, offset, &avail); 278if(avail > len) 279 avail = (unsigned long)len; 280hashwrite(f, in, avail); 281 offset += avail; 282 len -= avail; 283} 284} 285 286/* Return 0 if we will bust the pack-size limit */ 287static unsigned longwrite_no_reuse_object(struct hashfile *f,struct object_entry *entry, 288unsigned long limit,int usable_delta) 289{ 290unsigned long size, datalen; 291unsigned char header[MAX_PACK_OBJECT_HEADER], 292 dheader[MAX_PACK_OBJECT_HEADER]; 293unsigned hdrlen; 294enum object_type type; 295void*buf; 296struct git_istream *st = NULL; 297const unsigned hashsz = the_hash_algo->rawsz; 298 299if(!usable_delta) { 300if(oe_type(entry) == OBJ_BLOB && 301oe_size_greater_than(&to_pack, entry, big_file_threshold) && 302(st =open_istream(&entry->idx.oid, &type, &size, NULL)) != NULL) 303 buf = NULL; 304else{ 305 buf =read_object_file(&entry->idx.oid, &type, &size); 306if(!buf) 307die(_("unable to read%s"), 308oid_to_hex(&entry->idx.oid)); 309} 310/* 311 * make sure no cached delta data remains from a 312 * previous attempt before a pack split occurred. 313 */ 314FREE_AND_NULL(entry->delta_data); 315 entry->z_delta_size =0; 316}else if(entry->delta_data) { 317 size =DELTA_SIZE(entry); 318 buf = entry->delta_data; 319 entry->delta_data = NULL; 320 type = (allow_ofs_delta &&DELTA(entry)->idx.offset) ? 321 OBJ_OFS_DELTA : OBJ_REF_DELTA; 322}else{ 323 buf =get_delta(entry); 324 size =DELTA_SIZE(entry); 325 type = (allow_ofs_delta &&DELTA(entry)->idx.offset) ? 326 OBJ_OFS_DELTA : OBJ_REF_DELTA; 327} 328 329if(st)/* large blob case, just assume we don't compress well */ 330 datalen = size; 331else if(entry->z_delta_size) 332 datalen = entry->z_delta_size; 333else 334 datalen =do_compress(&buf, size); 335 336/* 337 * The object header is a byte of 'type' followed by zero or 338 * more bytes of length. 339 */ 340 hdrlen =encode_in_pack_object_header(header,sizeof(header), 341 type, size); 342 343if(type == OBJ_OFS_DELTA) { 344/* 345 * Deltas with relative base contain an additional 346 * encoding of the relative offset for the delta 347 * base from this object's position in the pack. 348 */ 349 off_t ofs = entry->idx.offset -DELTA(entry)->idx.offset; 350unsigned pos =sizeof(dheader) -1; 351 dheader[pos] = ofs &127; 352while(ofs >>=7) 353 dheader[--pos] =128| (--ofs &127); 354if(limit && hdrlen +sizeof(dheader) - pos + datalen + hashsz >= limit) { 355if(st) 356close_istream(st); 357free(buf); 358return0; 359} 360hashwrite(f, header, hdrlen); 361hashwrite(f, dheader + pos,sizeof(dheader) - pos); 362 hdrlen +=sizeof(dheader) - pos; 363}else if(type == OBJ_REF_DELTA) { 364/* 365 * Deltas with a base reference contain 366 * additional bytes for the base object ID. 367 */ 368if(limit && hdrlen + hashsz + datalen + hashsz >= limit) { 369if(st) 370close_istream(st); 371free(buf); 372return0; 373} 374hashwrite(f, header, hdrlen); 375hashwrite(f,DELTA(entry)->idx.oid.hash, hashsz); 376 hdrlen += hashsz; 377}else{ 378if(limit && hdrlen + datalen + hashsz >= limit) { 379if(st) 380close_istream(st); 381free(buf); 382return0; 383} 384hashwrite(f, header, hdrlen); 385} 386if(st) { 387 datalen =write_large_blob_data(st, f, &entry->idx.oid); 388close_istream(st); 389}else{ 390hashwrite(f, buf, datalen); 391free(buf); 392} 393 394return hdrlen + datalen; 395} 396 397/* Return 0 if we will bust the pack-size limit */ 398static off_t write_reuse_object(struct hashfile *f,struct object_entry *entry, 399unsigned long limit,int usable_delta) 400{ 401struct packed_git *p =IN_PACK(entry); 402struct pack_window *w_curs = NULL; 403struct revindex_entry *revidx; 404 off_t offset; 405enum object_type type =oe_type(entry); 406 off_t datalen; 407unsigned char header[MAX_PACK_OBJECT_HEADER], 408 dheader[MAX_PACK_OBJECT_HEADER]; 409unsigned hdrlen; 410const unsigned hashsz = the_hash_algo->rawsz; 411unsigned long entry_size =SIZE(entry); 412 413if(DELTA(entry)) 414 type = (allow_ofs_delta &&DELTA(entry)->idx.offset) ? 415 OBJ_OFS_DELTA : OBJ_REF_DELTA; 416 hdrlen =encode_in_pack_object_header(header,sizeof(header), 417 type, entry_size); 418 419 offset = entry->in_pack_offset; 420 revidx =find_pack_revindex(p, offset); 421 datalen = revidx[1].offset - offset; 422if(!pack_to_stdout && p->index_version >1&& 423check_pack_crc(p, &w_curs, offset, datalen, revidx->nr)) { 424error(_("bad packed object CRC for%s"), 425oid_to_hex(&entry->idx.oid)); 426unuse_pack(&w_curs); 427returnwrite_no_reuse_object(f, entry, limit, usable_delta); 428} 429 430 offset += entry->in_pack_header_size; 431 datalen -= entry->in_pack_header_size; 432 433if(!pack_to_stdout && p->index_version ==1&& 434check_pack_inflate(p, &w_curs, offset, datalen, entry_size)) { 435error(_("corrupt packed object for%s"), 436oid_to_hex(&entry->idx.oid)); 437unuse_pack(&w_curs); 438returnwrite_no_reuse_object(f, entry, limit, usable_delta); 439} 440 441if(type == OBJ_OFS_DELTA) { 442 off_t ofs = entry->idx.offset -DELTA(entry)->idx.offset; 443unsigned pos =sizeof(dheader) -1; 444 dheader[pos] = ofs &127; 445while(ofs >>=7) 446 dheader[--pos] =128| (--ofs &127); 447if(limit && hdrlen +sizeof(dheader) - pos + datalen + hashsz >= limit) { 448unuse_pack(&w_curs); 449return0; 450} 451hashwrite(f, header, hdrlen); 452hashwrite(f, dheader + pos,sizeof(dheader) - pos); 453 hdrlen +=sizeof(dheader) - pos; 454 reused_delta++; 455}else if(type == OBJ_REF_DELTA) { 456if(limit && hdrlen + hashsz + datalen + hashsz >= limit) { 457unuse_pack(&w_curs); 458return0; 459} 460hashwrite(f, header, hdrlen); 461hashwrite(f,DELTA(entry)->idx.oid.hash, hashsz); 462 hdrlen += hashsz; 463 reused_delta++; 464}else{ 465if(limit && hdrlen + datalen + hashsz >= limit) { 466unuse_pack(&w_curs); 467return0; 468} 469hashwrite(f, header, hdrlen); 470} 471copy_pack_data(f, p, &w_curs, offset, datalen); 472unuse_pack(&w_curs); 473 reused++; 474return hdrlen + datalen; 475} 476 477/* Return 0 if we will bust the pack-size limit */ 478static off_t write_object(struct hashfile *f, 479struct object_entry *entry, 480 off_t write_offset) 481{ 482unsigned long limit; 483 off_t len; 484int usable_delta, to_reuse; 485 486if(!pack_to_stdout) 487crc32_begin(f); 488 489/* apply size limit if limited packsize and not first object */ 490if(!pack_size_limit || !nr_written) 491 limit =0; 492else if(pack_size_limit <= write_offset) 493/* 494 * the earlier object did not fit the limit; avoid 495 * mistaking this with unlimited (i.e. limit = 0). 496 */ 497 limit =1; 498else 499 limit = pack_size_limit - write_offset; 500 501if(!DELTA(entry)) 502 usable_delta =0;/* no delta */ 503else if(!pack_size_limit) 504 usable_delta =1;/* unlimited packfile */ 505else if(DELTA(entry)->idx.offset == (off_t)-1) 506 usable_delta =0;/* base was written to another pack */ 507else if(DELTA(entry)->idx.offset) 508 usable_delta =1;/* base already exists in this pack */ 509else 510 usable_delta =0;/* base could end up in another pack */ 511 512if(!reuse_object) 513 to_reuse =0;/* explicit */ 514else if(!IN_PACK(entry)) 515 to_reuse =0;/* can't reuse what we don't have */ 516else if(oe_type(entry) == OBJ_REF_DELTA || 517oe_type(entry) == OBJ_OFS_DELTA) 518/* check_object() decided it for us ... */ 519 to_reuse = usable_delta; 520/* ... but pack split may override that */ 521else if(oe_type(entry) != entry->in_pack_type) 522 to_reuse =0;/* pack has delta which is unusable */ 523else if(DELTA(entry)) 524 to_reuse =0;/* we want to pack afresh */ 525else 526 to_reuse =1;/* we have it in-pack undeltified, 527 * and we do not need to deltify it. 528 */ 529 530if(!to_reuse) 531 len =write_no_reuse_object(f, entry, limit, usable_delta); 532else 533 len =write_reuse_object(f, entry, limit, usable_delta); 534if(!len) 535return0; 536 537if(usable_delta) 538 written_delta++; 539 written++; 540if(!pack_to_stdout) 541 entry->idx.crc32 =crc32_end(f); 542return len; 543} 544 545enum write_one_status { 546 WRITE_ONE_SKIP = -1,/* already written */ 547 WRITE_ONE_BREAK =0,/* writing this will bust the limit; not written */ 548 WRITE_ONE_WRITTEN =1,/* normal */ 549 WRITE_ONE_RECURSIVE =2/* already scheduled to be written */ 550}; 551 552static enum write_one_status write_one(struct hashfile *f, 553struct object_entry *e, 554 off_t *offset) 555{ 556 off_t size; 557int recursing; 558 559/* 560 * we set offset to 1 (which is an impossible value) to mark 561 * the fact that this object is involved in "write its base 562 * first before writing a deltified object" recursion. 563 */ 564 recursing = (e->idx.offset ==1); 565if(recursing) { 566warning(_("recursive delta detected for object%s"), 567oid_to_hex(&e->idx.oid)); 568return WRITE_ONE_RECURSIVE; 569}else if(e->idx.offset || e->preferred_base) { 570/* offset is non zero if object is written already. */ 571return WRITE_ONE_SKIP; 572} 573 574/* if we are deltified, write out base object first. */ 575if(DELTA(e)) { 576 e->idx.offset =1;/* now recurse */ 577switch(write_one(f,DELTA(e), offset)) { 578case WRITE_ONE_RECURSIVE: 579/* we cannot depend on this one */ 580SET_DELTA(e, NULL); 581break; 582default: 583break; 584case WRITE_ONE_BREAK: 585 e->idx.offset = recursing; 586return WRITE_ONE_BREAK; 587} 588} 589 590 e->idx.offset = *offset; 591 size =write_object(f, e, *offset); 592if(!size) { 593 e->idx.offset = recursing; 594return WRITE_ONE_BREAK; 595} 596 written_list[nr_written++] = &e->idx; 597 598/* make sure off_t is sufficiently large not to wrap */ 599if(signed_add_overflows(*offset, size)) 600die(_("pack too large for current definition of off_t")); 601*offset += size; 602return WRITE_ONE_WRITTEN; 603} 604 605static intmark_tagged(const char*path,const struct object_id *oid,int flag, 606void*cb_data) 607{ 608struct object_id peeled; 609struct object_entry *entry =packlist_find(&to_pack, oid->hash, NULL); 610 611if(entry) 612 entry->tagged =1; 613if(!peel_ref(path, &peeled)) { 614 entry =packlist_find(&to_pack, peeled.hash, NULL); 615if(entry) 616 entry->tagged =1; 617} 618return0; 619} 620 621staticinlinevoidadd_to_write_order(struct object_entry **wo, 622unsigned int*endp, 623struct object_entry *e) 624{ 625if(e->filled ||oe_layer(&to_pack, e) != write_layer) 626return; 627 wo[(*endp)++] = e; 628 e->filled =1; 629} 630 631static voidadd_descendants_to_write_order(struct object_entry **wo, 632unsigned int*endp, 633struct object_entry *e) 634{ 635int add_to_order =1; 636while(e) { 637if(add_to_order) { 638struct object_entry *s; 639/* add this node... */ 640add_to_write_order(wo, endp, e); 641/* all its siblings... */ 642for(s =DELTA_SIBLING(e); s; s =DELTA_SIBLING(s)) { 643add_to_write_order(wo, endp, s); 644} 645} 646/* drop down a level to add left subtree nodes if possible */ 647if(DELTA_CHILD(e)) { 648 add_to_order =1; 649 e =DELTA_CHILD(e); 650}else{ 651 add_to_order =0; 652/* our sibling might have some children, it is next */ 653if(DELTA_SIBLING(e)) { 654 e =DELTA_SIBLING(e); 655continue; 656} 657/* go back to our parent node */ 658 e =DELTA(e); 659while(e && !DELTA_SIBLING(e)) { 660/* we're on the right side of a subtree, keep 661 * going up until we can go right again */ 662 e =DELTA(e); 663} 664if(!e) { 665/* done- we hit our original root node */ 666return; 667} 668/* pass it off to sibling at this level */ 669 e =DELTA_SIBLING(e); 670} 671}; 672} 673 674static voidadd_family_to_write_order(struct object_entry **wo, 675unsigned int*endp, 676struct object_entry *e) 677{ 678struct object_entry *root; 679 680for(root = e;DELTA(root); root =DELTA(root)) 681;/* nothing */ 682add_descendants_to_write_order(wo, endp, root); 683} 684 685static voidcompute_layer_order(struct object_entry **wo,unsigned int*wo_end) 686{ 687unsigned int i, last_untagged; 688struct object_entry *objects = to_pack.objects; 689 690for(i =0; i < to_pack.nr_objects; i++) { 691if(objects[i].tagged) 692break; 693add_to_write_order(wo, wo_end, &objects[i]); 694} 695 last_untagged = i; 696 697/* 698 * Then fill all the tagged tips. 699 */ 700for(; i < to_pack.nr_objects; i++) { 701if(objects[i].tagged) 702add_to_write_order(wo, wo_end, &objects[i]); 703} 704 705/* 706 * And then all remaining commits and tags. 707 */ 708for(i = last_untagged; i < to_pack.nr_objects; i++) { 709if(oe_type(&objects[i]) != OBJ_COMMIT && 710oe_type(&objects[i]) != OBJ_TAG) 711continue; 712add_to_write_order(wo, wo_end, &objects[i]); 713} 714 715/* 716 * And then all the trees. 717 */ 718for(i = last_untagged; i < to_pack.nr_objects; i++) { 719if(oe_type(&objects[i]) != OBJ_TREE) 720continue; 721add_to_write_order(wo, wo_end, &objects[i]); 722} 723 724/* 725 * Finally all the rest in really tight order 726 */ 727for(i = last_untagged; i < to_pack.nr_objects; i++) { 728if(!objects[i].filled &&oe_layer(&to_pack, &objects[i]) == write_layer) 729add_family_to_write_order(wo, wo_end, &objects[i]); 730} 731} 732 733static struct object_entry **compute_write_order(void) 734{ 735uint32_t max_layers =1; 736unsigned int i, wo_end; 737 738struct object_entry **wo; 739struct object_entry *objects = to_pack.objects; 740 741for(i =0; i < to_pack.nr_objects; i++) { 742 objects[i].tagged =0; 743 objects[i].filled =0; 744SET_DELTA_CHILD(&objects[i], NULL); 745SET_DELTA_SIBLING(&objects[i], NULL); 746} 747 748/* 749 * Fully connect delta_child/delta_sibling network. 750 * Make sure delta_sibling is sorted in the original 751 * recency order. 752 */ 753for(i = to_pack.nr_objects; i >0;) { 754struct object_entry *e = &objects[--i]; 755if(!DELTA(e)) 756continue; 757/* Mark me as the first child */ 758 e->delta_sibling_idx =DELTA(e)->delta_child_idx; 759SET_DELTA_CHILD(DELTA(e), e); 760} 761 762/* 763 * Mark objects that are at the tip of tags. 764 */ 765for_each_tag_ref(mark_tagged, NULL); 766 767if(use_delta_islands) 768 max_layers =compute_pack_layers(&to_pack); 769 770ALLOC_ARRAY(wo, to_pack.nr_objects); 771 wo_end =0; 772 773for(; write_layer < max_layers; ++write_layer) 774compute_layer_order(wo, &wo_end); 775 776if(wo_end != to_pack.nr_objects) 777die(_("ordered%uobjects, expected %"PRIu32), 778 wo_end, to_pack.nr_objects); 779 780return wo; 781} 782 783static off_t write_reused_pack(struct hashfile *f) 784{ 785unsigned char buffer[8192]; 786 off_t to_write, total; 787int fd; 788 789if(!is_pack_valid(reuse_packfile)) 790die(_("packfile is invalid:%s"), reuse_packfile->pack_name); 791 792 fd =git_open(reuse_packfile->pack_name); 793if(fd <0) 794die_errno(_("unable to open packfile for reuse:%s"), 795 reuse_packfile->pack_name); 796 797if(lseek(fd,sizeof(struct pack_header), SEEK_SET) == -1) 798die_errno(_("unable to seek in reused packfile")); 799 800if(reuse_packfile_offset <0) 801 reuse_packfile_offset = reuse_packfile->pack_size - the_hash_algo->rawsz; 802 803 total = to_write = reuse_packfile_offset -sizeof(struct pack_header); 804 805while(to_write) { 806int read_pack =xread(fd, buffer,sizeof(buffer)); 807 808if(read_pack <=0) 809die_errno(_("unable to read from reused packfile")); 810 811if(read_pack > to_write) 812 read_pack = to_write; 813 814hashwrite(f, buffer, read_pack); 815 to_write -= read_pack; 816 817/* 818 * We don't know the actual number of objects written, 819 * only how many bytes written, how many bytes total, and 820 * how many objects total. So we can fake it by pretending all 821 * objects we are writing are the same size. This gives us a 822 * smooth progress meter, and at the end it matches the true 823 * answer. 824 */ 825 written = reuse_packfile_objects * 826(((double)(total - to_write)) / total); 827display_progress(progress_state, written); 828} 829 830close(fd); 831 written = reuse_packfile_objects; 832display_progress(progress_state, written); 833return reuse_packfile_offset -sizeof(struct pack_header); 834} 835 836static const char no_split_warning[] =N_( 837"disabling bitmap writing, packs are split due to pack.packSizeLimit" 838); 839 840static voidwrite_pack_file(void) 841{ 842uint32_t i =0, j; 843struct hashfile *f; 844 off_t offset; 845uint32_t nr_remaining = nr_result; 846time_t last_mtime =0; 847struct object_entry **write_order; 848 849if(progress > pack_to_stdout) 850 progress_state =start_progress(_("Writing objects"), nr_result); 851ALLOC_ARRAY(written_list, to_pack.nr_objects); 852 write_order =compute_write_order(); 853 854do{ 855struct object_id oid; 856char*pack_tmp_name = NULL; 857 858if(pack_to_stdout) 859 f =hashfd_throughput(1,"<stdout>", progress_state); 860else 861 f =create_tmp_packfile(&pack_tmp_name); 862 863 offset =write_pack_header(f, nr_remaining); 864 865if(reuse_packfile) { 866 off_t packfile_size; 867assert(pack_to_stdout); 868 869 packfile_size =write_reused_pack(f); 870 offset += packfile_size; 871} 872 873 nr_written =0; 874for(; i < to_pack.nr_objects; i++) { 875struct object_entry *e = write_order[i]; 876if(write_one(f, e, &offset) == WRITE_ONE_BREAK) 877break; 878display_progress(progress_state, written); 879} 880 881/* 882 * Did we write the wrong # entries in the header? 883 * If so, rewrite it like in fast-import 884 */ 885if(pack_to_stdout) { 886finalize_hashfile(f, oid.hash, CSUM_HASH_IN_STREAM | CSUM_CLOSE); 887}else if(nr_written == nr_remaining) { 888finalize_hashfile(f, oid.hash, CSUM_HASH_IN_STREAM | CSUM_FSYNC | CSUM_CLOSE); 889}else{ 890int fd =finalize_hashfile(f, oid.hash,0); 891fixup_pack_header_footer(fd, oid.hash, pack_tmp_name, 892 nr_written, oid.hash, offset); 893close(fd); 894if(write_bitmap_index) { 895warning(_(no_split_warning)); 896 write_bitmap_index =0; 897} 898} 899 900if(!pack_to_stdout) { 901struct stat st; 902struct strbuf tmpname = STRBUF_INIT; 903 904/* 905 * Packs are runtime accessed in their mtime 906 * order since newer packs are more likely to contain 907 * younger objects. So if we are creating multiple 908 * packs then we should modify the mtime of later ones 909 * to preserve this property. 910 */ 911if(stat(pack_tmp_name, &st) <0) { 912warning_errno(_("failed to stat%s"), pack_tmp_name); 913}else if(!last_mtime) { 914 last_mtime = st.st_mtime; 915}else{ 916struct utimbuf utb; 917 utb.actime = st.st_atime; 918 utb.modtime = --last_mtime; 919if(utime(pack_tmp_name, &utb) <0) 920warning_errno(_("failed utime() on%s"), pack_tmp_name); 921} 922 923strbuf_addf(&tmpname,"%s-", base_name); 924 925if(write_bitmap_index) { 926bitmap_writer_set_checksum(oid.hash); 927bitmap_writer_build_type_index( 928&to_pack, written_list, nr_written); 929} 930 931finish_tmp_packfile(&tmpname, pack_tmp_name, 932 written_list, nr_written, 933&pack_idx_opts, oid.hash); 934 935if(write_bitmap_index) { 936strbuf_addf(&tmpname,"%s.bitmap",oid_to_hex(&oid)); 937 938stop_progress(&progress_state); 939 940bitmap_writer_show_progress(progress); 941bitmap_writer_reuse_bitmaps(&to_pack); 942bitmap_writer_select_commits(indexed_commits, indexed_commits_nr, -1); 943bitmap_writer_build(&to_pack); 944bitmap_writer_finish(written_list, nr_written, 945 tmpname.buf, write_bitmap_options); 946 write_bitmap_index =0; 947} 948 949strbuf_release(&tmpname); 950free(pack_tmp_name); 951puts(oid_to_hex(&oid)); 952} 953 954/* mark written objects as written to previous pack */ 955for(j =0; j < nr_written; j++) { 956 written_list[j]->offset = (off_t)-1; 957} 958 nr_remaining -= nr_written; 959}while(nr_remaining && i < to_pack.nr_objects); 960 961free(written_list); 962free(write_order); 963stop_progress(&progress_state); 964if(written != nr_result) 965die(_("wrote %"PRIu32" objects while expecting %"PRIu32), 966 written, nr_result); 967trace2_data_intmax("pack-objects", the_repository, 968"write_pack_file/wrote", nr_result); 969} 970 971static intno_try_delta(const char*path) 972{ 973static struct attr_check *check; 974 975if(!check) 976 check =attr_check_initl("delta", NULL); 977git_check_attr(the_repository->index, path, check); 978if(ATTR_FALSE(check->items[0].value)) 979return1; 980return0; 981} 982 983/* 984 * When adding an object, check whether we have already added it 985 * to our packing list. If so, we can skip. However, if we are 986 * being asked to excludei t, but the previous mention was to include 987 * it, make sure to adjust its flags and tweak our numbers accordingly. 988 * 989 * As an optimization, we pass out the index position where we would have 990 * found the item, since that saves us from having to look it up again a 991 * few lines later when we want to add the new entry. 992 */ 993static inthave_duplicate_entry(const struct object_id *oid, 994int exclude, 995uint32_t*index_pos) 996{ 997struct object_entry *entry; 998 999 entry =packlist_find(&to_pack, oid->hash, index_pos);1000if(!entry)1001return0;10021003if(exclude) {1004if(!entry->preferred_base)1005 nr_result--;1006 entry->preferred_base =1;1007}10081009return1;1010}10111012static intwant_found_object(int exclude,struct packed_git *p)1013{1014if(exclude)1015return1;1016if(incremental)1017return0;10181019/*1020 * When asked to do --local (do not include an object that appears in a1021 * pack we borrow from elsewhere) or --honor-pack-keep (do not include1022 * an object that appears in a pack marked with .keep), finding a pack1023 * that matches the criteria is sufficient for us to decide to omit it.1024 * However, even if this pack does not satisfy the criteria, we need to1025 * make sure no copy of this object appears in _any_ pack that makes us1026 * to omit the object, so we need to check all the packs.1027 *1028 * We can however first check whether these options can possible matter;1029 * if they do not matter we know we want the object in generated pack.1030 * Otherwise, we signal "-1" at the end to tell the caller that we do1031 * not know either way, and it needs to check more packs.1032 */1033if(!ignore_packed_keep_on_disk &&1034!ignore_packed_keep_in_core &&1035(!local || !have_non_local_packs))1036return1;10371038if(local && !p->pack_local)1039return0;1040if(p->pack_local &&1041((ignore_packed_keep_on_disk && p->pack_keep) ||1042(ignore_packed_keep_in_core && p->pack_keep_in_core)))1043return0;10441045/* we don't know yet; keep looking for more packs */1046return-1;1047}10481049/*1050 * Check whether we want the object in the pack (e.g., we do not want1051 * objects found in non-local stores if the "--local" option was used).1052 *1053 * If the caller already knows an existing pack it wants to take the object1054 * from, that is passed in *found_pack and *found_offset; otherwise this1055 * function finds if there is any pack that has the object and returns the pack1056 * and its offset in these variables.1057 */1058static intwant_object_in_pack(const struct object_id *oid,1059int exclude,1060struct packed_git **found_pack,1061 off_t *found_offset)1062{1063int want;1064struct list_head *pos;1065struct multi_pack_index *m;10661067if(!exclude && local &&has_loose_object_nonlocal(oid))1068return0;10691070/*1071 * If we already know the pack object lives in, start checks from that1072 * pack - in the usual case when neither --local was given nor .keep files1073 * are present we will determine the answer right now.1074 */1075if(*found_pack) {1076 want =want_found_object(exclude, *found_pack);1077if(want != -1)1078return want;1079}10801081for(m =get_multi_pack_index(the_repository); m; m = m->next) {1082struct pack_entry e;1083if(fill_midx_entry(the_repository, oid, &e, m)) {1084struct packed_git *p = e.p;1085 off_t offset;10861087if(p == *found_pack)1088 offset = *found_offset;1089else1090 offset =find_pack_entry_one(oid->hash, p);10911092if(offset) {1093if(!*found_pack) {1094if(!is_pack_valid(p))1095continue;1096*found_offset = offset;1097*found_pack = p;1098}1099 want =want_found_object(exclude, p);1100if(want != -1)1101return want;1102}1103}1104}11051106list_for_each(pos,get_packed_git_mru(the_repository)) {1107struct packed_git *p =list_entry(pos,struct packed_git, mru);1108 off_t offset;11091110if(p == *found_pack)1111 offset = *found_offset;1112else1113 offset =find_pack_entry_one(oid->hash, p);11141115if(offset) {1116if(!*found_pack) {1117if(!is_pack_valid(p))1118continue;1119*found_offset = offset;1120*found_pack = p;1121}1122 want =want_found_object(exclude, p);1123if(!exclude && want >0)1124list_move(&p->mru,1125get_packed_git_mru(the_repository));1126if(want != -1)1127return want;1128}1129}11301131return1;1132}11331134static voidcreate_object_entry(const struct object_id *oid,1135enum object_type type,1136uint32_t hash,1137int exclude,1138int no_try_delta,1139uint32_t index_pos,1140struct packed_git *found_pack,1141 off_t found_offset)1142{1143struct object_entry *entry;11441145 entry =packlist_alloc(&to_pack, oid->hash, index_pos);1146 entry->hash = hash;1147oe_set_type(entry, type);1148if(exclude)1149 entry->preferred_base =1;1150else1151 nr_result++;1152if(found_pack) {1153oe_set_in_pack(&to_pack, entry, found_pack);1154 entry->in_pack_offset = found_offset;1155}11561157 entry->no_try_delta = no_try_delta;1158}11591160static const char no_closure_warning[] =N_(1161"disabling bitmap writing, as some objects are not being packed"1162);11631164static intadd_object_entry(const struct object_id *oid,enum object_type type,1165const char*name,int exclude)1166{1167struct packed_git *found_pack = NULL;1168 off_t found_offset =0;1169uint32_t index_pos;11701171display_progress(progress_state, ++nr_seen);11721173if(have_duplicate_entry(oid, exclude, &index_pos))1174return0;11751176if(!want_object_in_pack(oid, exclude, &found_pack, &found_offset)) {1177/* The pack is missing an object, so it will not have closure */1178if(write_bitmap_index) {1179warning(_(no_closure_warning));1180 write_bitmap_index =0;1181}1182return0;1183}11841185create_object_entry(oid, type,pack_name_hash(name),1186 exclude, name &&no_try_delta(name),1187 index_pos, found_pack, found_offset);1188return1;1189}11901191static intadd_object_entry_from_bitmap(const struct object_id *oid,1192enum object_type type,1193int flags,uint32_t name_hash,1194struct packed_git *pack, off_t offset)1195{1196uint32_t index_pos;11971198display_progress(progress_state, ++nr_seen);11991200if(have_duplicate_entry(oid,0, &index_pos))1201return0;12021203if(!want_object_in_pack(oid,0, &pack, &offset))1204return0;12051206create_object_entry(oid, type, name_hash,0,0, index_pos, pack, offset);1207return1;1208}12091210struct pbase_tree_cache {1211struct object_id oid;1212int ref;1213int temporary;1214void*tree_data;1215unsigned long tree_size;1216};12171218static struct pbase_tree_cache *(pbase_tree_cache[256]);1219static intpbase_tree_cache_ix(const struct object_id *oid)1220{1221return oid->hash[0] %ARRAY_SIZE(pbase_tree_cache);1222}1223static intpbase_tree_cache_ix_incr(int ix)1224{1225return(ix+1) %ARRAY_SIZE(pbase_tree_cache);1226}12271228static struct pbase_tree {1229struct pbase_tree *next;1230/* This is a phony "cache" entry; we are not1231 * going to evict it or find it through _get()1232 * mechanism -- this is for the toplevel node that1233 * would almost always change with any commit.1234 */1235struct pbase_tree_cache pcache;1236} *pbase_tree;12371238static struct pbase_tree_cache *pbase_tree_get(const struct object_id *oid)1239{1240struct pbase_tree_cache *ent, *nent;1241void*data;1242unsigned long size;1243enum object_type type;1244int neigh;1245int my_ix =pbase_tree_cache_ix(oid);1246int available_ix = -1;12471248/* pbase-tree-cache acts as a limited hashtable.1249 * your object will be found at your index or within a few1250 * slots after that slot if it is cached.1251 */1252for(neigh =0; neigh <8; neigh++) {1253 ent = pbase_tree_cache[my_ix];1254if(ent &&oideq(&ent->oid, oid)) {1255 ent->ref++;1256return ent;1257}1258else if(((available_ix <0) && (!ent || !ent->ref)) ||1259((0<= available_ix) &&1260(!ent && pbase_tree_cache[available_ix])))1261 available_ix = my_ix;1262if(!ent)1263break;1264 my_ix =pbase_tree_cache_ix_incr(my_ix);1265}12661267/* Did not find one. Either we got a bogus request or1268 * we need to read and perhaps cache.1269 */1270 data =read_object_file(oid, &type, &size);1271if(!data)1272return NULL;1273if(type != OBJ_TREE) {1274free(data);1275return NULL;1276}12771278/* We need to either cache or return a throwaway copy */12791280if(available_ix <0)1281 ent = NULL;1282else{1283 ent = pbase_tree_cache[available_ix];1284 my_ix = available_ix;1285}12861287if(!ent) {1288 nent =xmalloc(sizeof(*nent));1289 nent->temporary = (available_ix <0);1290}1291else{1292/* evict and reuse */1293free(ent->tree_data);1294 nent = ent;1295}1296oidcpy(&nent->oid, oid);1297 nent->tree_data = data;1298 nent->tree_size = size;1299 nent->ref =1;1300if(!nent->temporary)1301 pbase_tree_cache[my_ix] = nent;1302return nent;1303}13041305static voidpbase_tree_put(struct pbase_tree_cache *cache)1306{1307if(!cache->temporary) {1308 cache->ref--;1309return;1310}1311free(cache->tree_data);1312free(cache);1313}13141315static intname_cmp_len(const char*name)1316{1317int i;1318for(i =0; name[i] && name[i] !='\n'&& name[i] !='/'; i++)1319;1320return i;1321}13221323static voidadd_pbase_object(struct tree_desc *tree,1324const char*name,1325int cmplen,1326const char*fullname)1327{1328struct name_entry entry;1329int cmp;13301331while(tree_entry(tree,&entry)) {1332if(S_ISGITLINK(entry.mode))1333continue;1334 cmp =tree_entry_len(&entry) != cmplen ?1:1335memcmp(name, entry.path, cmplen);1336if(cmp >0)1337continue;1338if(cmp <0)1339return;1340if(name[cmplen] !='/') {1341add_object_entry(&entry.oid,1342object_type(entry.mode),1343 fullname,1);1344return;1345}1346if(S_ISDIR(entry.mode)) {1347struct tree_desc sub;1348struct pbase_tree_cache *tree;1349const char*down = name+cmplen+1;1350int downlen =name_cmp_len(down);13511352 tree =pbase_tree_get(&entry.oid);1353if(!tree)1354return;1355init_tree_desc(&sub, tree->tree_data, tree->tree_size);13561357add_pbase_object(&sub, down, downlen, fullname);1358pbase_tree_put(tree);1359}1360}1361}13621363static unsigned*done_pbase_paths;1364static int done_pbase_paths_num;1365static int done_pbase_paths_alloc;1366static intdone_pbase_path_pos(unsigned hash)1367{1368int lo =0;1369int hi = done_pbase_paths_num;1370while(lo < hi) {1371int mi = lo + (hi - lo) /2;1372if(done_pbase_paths[mi] == hash)1373return mi;1374if(done_pbase_paths[mi] < hash)1375 hi = mi;1376else1377 lo = mi +1;1378}1379return-lo-1;1380}13811382static intcheck_pbase_path(unsigned hash)1383{1384int pos =done_pbase_path_pos(hash);1385if(0<= pos)1386return1;1387 pos = -pos -1;1388ALLOC_GROW(done_pbase_paths,1389 done_pbase_paths_num +1,1390 done_pbase_paths_alloc);1391 done_pbase_paths_num++;1392if(pos < done_pbase_paths_num)1393MOVE_ARRAY(done_pbase_paths + pos +1, done_pbase_paths + pos,1394 done_pbase_paths_num - pos -1);1395 done_pbase_paths[pos] = hash;1396return0;1397}13981399static voidadd_preferred_base_object(const char*name)1400{1401struct pbase_tree *it;1402int cmplen;1403unsigned hash =pack_name_hash(name);14041405if(!num_preferred_base ||check_pbase_path(hash))1406return;14071408 cmplen =name_cmp_len(name);1409for(it = pbase_tree; it; it = it->next) {1410if(cmplen ==0) {1411add_object_entry(&it->pcache.oid, OBJ_TREE, NULL,1);1412}1413else{1414struct tree_desc tree;1415init_tree_desc(&tree, it->pcache.tree_data, it->pcache.tree_size);1416add_pbase_object(&tree, name, cmplen, name);1417}1418}1419}14201421static voidadd_preferred_base(struct object_id *oid)1422{1423struct pbase_tree *it;1424void*data;1425unsigned long size;1426struct object_id tree_oid;14271428if(window <= num_preferred_base++)1429return;14301431 data =read_object_with_reference(oid, tree_type, &size, &tree_oid);1432if(!data)1433return;14341435for(it = pbase_tree; it; it = it->next) {1436if(oideq(&it->pcache.oid, &tree_oid)) {1437free(data);1438return;1439}1440}14411442 it =xcalloc(1,sizeof(*it));1443 it->next = pbase_tree;1444 pbase_tree = it;14451446oidcpy(&it->pcache.oid, &tree_oid);1447 it->pcache.tree_data = data;1448 it->pcache.tree_size = size;1449}14501451static voidcleanup_preferred_base(void)1452{1453struct pbase_tree *it;1454unsigned i;14551456 it = pbase_tree;1457 pbase_tree = NULL;1458while(it) {1459struct pbase_tree *tmp = it;1460 it = tmp->next;1461free(tmp->pcache.tree_data);1462free(tmp);1463}14641465for(i =0; i <ARRAY_SIZE(pbase_tree_cache); i++) {1466if(!pbase_tree_cache[i])1467continue;1468free(pbase_tree_cache[i]->tree_data);1469FREE_AND_NULL(pbase_tree_cache[i]);1470}14711472FREE_AND_NULL(done_pbase_paths);1473 done_pbase_paths_num = done_pbase_paths_alloc =0;1474}14751476/*1477 * Return 1 iff the object specified by "delta" can be sent1478 * literally as a delta against the base in "base_sha1". If1479 * so, then *base_out will point to the entry in our packing1480 * list, or NULL if we must use the external-base list.1481 *1482 * Depth value does not matter - find_deltas() will1483 * never consider reused delta as the base object to1484 * deltify other objects against, in order to avoid1485 * circular deltas.1486 */1487static intcan_reuse_delta(const unsigned char*base_sha1,1488struct object_entry *delta,1489struct object_entry **base_out)1490{1491struct object_entry *base;1492struct object_id base_oid;14931494if(!base_sha1)1495return0;14961497/*1498 * First see if we're already sending the base (or it's explicitly in1499 * our "excluded" list).1500 */1501 base =packlist_find(&to_pack, base_sha1, NULL);1502if(base) {1503if(!in_same_island(&delta->idx.oid, &base->idx.oid))1504return0;1505*base_out = base;1506return1;1507}15081509/*1510 * Otherwise, reachability bitmaps may tell us if the receiver has it,1511 * even if it was buried too deep in history to make it into the1512 * packing list.1513 */1514oidread(&base_oid, base_sha1);1515if(thin &&bitmap_has_oid_in_uninteresting(bitmap_git, &base_oid)) {1516if(use_delta_islands) {1517if(!in_same_island(&delta->idx.oid, &base_oid))1518return0;1519}1520*base_out = NULL;1521return1;1522}15231524return0;1525}15261527static voidcheck_object(struct object_entry *entry)1528{1529unsigned long canonical_size;15301531if(IN_PACK(entry)) {1532struct packed_git *p =IN_PACK(entry);1533struct pack_window *w_curs = NULL;1534const unsigned char*base_ref = NULL;1535struct object_entry *base_entry;1536unsigned long used, used_0;1537unsigned long avail;1538 off_t ofs;1539unsigned char*buf, c;1540enum object_type type;1541unsigned long in_pack_size;15421543 buf =use_pack(p, &w_curs, entry->in_pack_offset, &avail);15441545/*1546 * We want in_pack_type even if we do not reuse delta1547 * since non-delta representations could still be reused.1548 */1549 used =unpack_object_header_buffer(buf, avail,1550&type,1551&in_pack_size);1552if(used ==0)1553goto give_up;15541555if(type <0)1556BUG("invalid type%d", type);1557 entry->in_pack_type = type;15581559/*1560 * Determine if this is a delta and if so whether we can1561 * reuse it or not. Otherwise let's find out as cheaply as1562 * possible what the actual type and size for this object is.1563 */1564switch(entry->in_pack_type) {1565default:1566/* Not a delta hence we've already got all we need. */1567oe_set_type(entry, entry->in_pack_type);1568SET_SIZE(entry, in_pack_size);1569 entry->in_pack_header_size = used;1570if(oe_type(entry) < OBJ_COMMIT ||oe_type(entry) > OBJ_BLOB)1571goto give_up;1572unuse_pack(&w_curs);1573return;1574case OBJ_REF_DELTA:1575if(reuse_delta && !entry->preferred_base)1576 base_ref =use_pack(p, &w_curs,1577 entry->in_pack_offset + used, NULL);1578 entry->in_pack_header_size = used + the_hash_algo->rawsz;1579break;1580case OBJ_OFS_DELTA:1581 buf =use_pack(p, &w_curs,1582 entry->in_pack_offset + used, NULL);1583 used_0 =0;1584 c = buf[used_0++];1585 ofs = c &127;1586while(c &128) {1587 ofs +=1;1588if(!ofs ||MSB(ofs,7)) {1589error(_("delta base offset overflow in pack for%s"),1590oid_to_hex(&entry->idx.oid));1591goto give_up;1592}1593 c = buf[used_0++];1594 ofs = (ofs <<7) + (c &127);1595}1596 ofs = entry->in_pack_offset - ofs;1597if(ofs <=0|| ofs >= entry->in_pack_offset) {1598error(_("delta base offset out of bound for%s"),1599oid_to_hex(&entry->idx.oid));1600goto give_up;1601}1602if(reuse_delta && !entry->preferred_base) {1603struct revindex_entry *revidx;1604 revidx =find_pack_revindex(p, ofs);1605if(!revidx)1606goto give_up;1607 base_ref =nth_packed_object_sha1(p, revidx->nr);1608}1609 entry->in_pack_header_size = used + used_0;1610break;1611}16121613if(can_reuse_delta(base_ref, entry, &base_entry)) {1614oe_set_type(entry, entry->in_pack_type);1615SET_SIZE(entry, in_pack_size);/* delta size */1616SET_DELTA_SIZE(entry, in_pack_size);16171618if(base_entry) {1619SET_DELTA(entry, base_entry);1620 entry->delta_sibling_idx = base_entry->delta_child_idx;1621SET_DELTA_CHILD(base_entry, entry);1622}else{1623SET_DELTA_EXT(entry, base_ref);1624}16251626unuse_pack(&w_curs);1627return;1628}16291630if(oe_type(entry)) {1631 off_t delta_pos;16321633/*1634 * This must be a delta and we already know what the1635 * final object type is. Let's extract the actual1636 * object size from the delta header.1637 */1638 delta_pos = entry->in_pack_offset + entry->in_pack_header_size;1639 canonical_size =get_size_from_delta(p, &w_curs, delta_pos);1640if(canonical_size ==0)1641goto give_up;1642SET_SIZE(entry, canonical_size);1643unuse_pack(&w_curs);1644return;1645}16461647/*1648 * No choice but to fall back to the recursive delta walk1649 * with oid_object_info() to find about the object type1650 * at this point...1651 */1652 give_up:1653unuse_pack(&w_curs);1654}16551656oe_set_type(entry,1657oid_object_info(the_repository, &entry->idx.oid, &canonical_size));1658if(entry->type_valid) {1659SET_SIZE(entry, canonical_size);1660}else{1661/*1662 * Bad object type is checked in prepare_pack(). This is1663 * to permit a missing preferred base object to be ignored1664 * as a preferred base. Doing so can result in a larger1665 * pack file, but the transfer will still take place.1666 */1667}1668}16691670static intpack_offset_sort(const void*_a,const void*_b)1671{1672const struct object_entry *a = *(struct object_entry **)_a;1673const struct object_entry *b = *(struct object_entry **)_b;1674const struct packed_git *a_in_pack =IN_PACK(a);1675const struct packed_git *b_in_pack =IN_PACK(b);16761677/* avoid filesystem trashing with loose objects */1678if(!a_in_pack && !b_in_pack)1679returnoidcmp(&a->idx.oid, &b->idx.oid);16801681if(a_in_pack < b_in_pack)1682return-1;1683if(a_in_pack > b_in_pack)1684return1;1685return a->in_pack_offset < b->in_pack_offset ? -1:1686(a->in_pack_offset > b->in_pack_offset);1687}16881689/*1690 * Drop an on-disk delta we were planning to reuse. Naively, this would1691 * just involve blanking out the "delta" field, but we have to deal1692 * with some extra book-keeping:1693 *1694 * 1. Removing ourselves from the delta_sibling linked list.1695 *1696 * 2. Updating our size/type to the non-delta representation. These were1697 * either not recorded initially (size) or overwritten with the delta type1698 * (type) when check_object() decided to reuse the delta.1699 *1700 * 3. Resetting our delta depth, as we are now a base object.1701 */1702static voiddrop_reused_delta(struct object_entry *entry)1703{1704unsigned*idx = &to_pack.objects[entry->delta_idx -1].delta_child_idx;1705struct object_info oi = OBJECT_INFO_INIT;1706enum object_type type;1707unsigned long size;17081709while(*idx) {1710struct object_entry *oe = &to_pack.objects[*idx -1];17111712if(oe == entry)1713*idx = oe->delta_sibling_idx;1714else1715 idx = &oe->delta_sibling_idx;1716}1717SET_DELTA(entry, NULL);1718 entry->depth =0;17191720 oi.sizep = &size;1721 oi.typep = &type;1722if(packed_object_info(the_repository,IN_PACK(entry), entry->in_pack_offset, &oi) <0) {1723/*1724 * We failed to get the info from this pack for some reason;1725 * fall back to oid_object_info, which may find another copy.1726 * And if that fails, the error will be recorded in oe_type(entry)1727 * and dealt with in prepare_pack().1728 */1729oe_set_type(entry,1730oid_object_info(the_repository, &entry->idx.oid, &size));1731}else{1732oe_set_type(entry, type);1733}1734SET_SIZE(entry, size);1735}17361737/*1738 * Follow the chain of deltas from this entry onward, throwing away any links1739 * that cause us to hit a cycle (as determined by the DFS state flags in1740 * the entries).1741 *1742 * We also detect too-long reused chains that would violate our --depth1743 * limit.1744 */1745static voidbreak_delta_chains(struct object_entry *entry)1746{1747/*1748 * The actual depth of each object we will write is stored as an int,1749 * as it cannot exceed our int "depth" limit. But before we break1750 * changes based no that limit, we may potentially go as deep as the1751 * number of objects, which is elsewhere bounded to a uint32_t.1752 */1753uint32_t total_depth;1754struct object_entry *cur, *next;17551756for(cur = entry, total_depth =0;1757 cur;1758 cur =DELTA(cur), total_depth++) {1759if(cur->dfs_state == DFS_DONE) {1760/*1761 * We've already seen this object and know it isn't1762 * part of a cycle. We do need to append its depth1763 * to our count.1764 */1765 total_depth += cur->depth;1766break;1767}17681769/*1770 * We break cycles before looping, so an ACTIVE state (or any1771 * other cruft which made its way into the state variable)1772 * is a bug.1773 */1774if(cur->dfs_state != DFS_NONE)1775BUG("confusing delta dfs state in first pass:%d",1776 cur->dfs_state);17771778/*1779 * Now we know this is the first time we've seen the object. If1780 * it's not a delta, we're done traversing, but we'll mark it1781 * done to save time on future traversals.1782 */1783if(!DELTA(cur)) {1784 cur->dfs_state = DFS_DONE;1785break;1786}17871788/*1789 * Mark ourselves as active and see if the next step causes1790 * us to cycle to another active object. It's important to do1791 * this _before_ we loop, because it impacts where we make the1792 * cut, and thus how our total_depth counter works.1793 * E.g., We may see a partial loop like:1794 *1795 * A -> B -> C -> D -> B1796 *1797 * Cutting B->C breaks the cycle. But now the depth of A is1798 * only 1, and our total_depth counter is at 3. The size of the1799 * error is always one less than the size of the cycle we1800 * broke. Commits C and D were "lost" from A's chain.1801 *1802 * If we instead cut D->B, then the depth of A is correct at 3.1803 * We keep all commits in the chain that we examined.1804 */1805 cur->dfs_state = DFS_ACTIVE;1806if(DELTA(cur)->dfs_state == DFS_ACTIVE) {1807drop_reused_delta(cur);1808 cur->dfs_state = DFS_DONE;1809break;1810}1811}18121813/*1814 * And now that we've gone all the way to the bottom of the chain, we1815 * need to clear the active flags and set the depth fields as1816 * appropriate. Unlike the loop above, which can quit when it drops a1817 * delta, we need to keep going to look for more depth cuts. So we need1818 * an extra "next" pointer to keep going after we reset cur->delta.1819 */1820for(cur = entry; cur; cur = next) {1821 next =DELTA(cur);18221823/*1824 * We should have a chain of zero or more ACTIVE states down to1825 * a final DONE. We can quit after the DONE, because either it1826 * has no bases, or we've already handled them in a previous1827 * call.1828 */1829if(cur->dfs_state == DFS_DONE)1830break;1831else if(cur->dfs_state != DFS_ACTIVE)1832BUG("confusing delta dfs state in second pass:%d",1833 cur->dfs_state);18341835/*1836 * If the total_depth is more than depth, then we need to snip1837 * the chain into two or more smaller chains that don't exceed1838 * the maximum depth. Most of the resulting chains will contain1839 * (depth + 1) entries (i.e., depth deltas plus one base), and1840 * the last chain (i.e., the one containing entry) will contain1841 * whatever entries are left over, namely1842 * (total_depth % (depth + 1)) of them.1843 *1844 * Since we are iterating towards decreasing depth, we need to1845 * decrement total_depth as we go, and we need to write to the1846 * entry what its final depth will be after all of the1847 * snipping. Since we're snipping into chains of length (depth1848 * + 1) entries, the final depth of an entry will be its1849 * original depth modulo (depth + 1). Any time we encounter an1850 * entry whose final depth is supposed to be zero, we snip it1851 * from its delta base, thereby making it so.1852 */1853 cur->depth = (total_depth--) % (depth +1);1854if(!cur->depth)1855drop_reused_delta(cur);18561857 cur->dfs_state = DFS_DONE;1858}1859}18601861static voidget_object_details(void)1862{1863uint32_t i;1864struct object_entry **sorted_by_offset;18651866if(progress)1867 progress_state =start_progress(_("Counting objects"),1868 to_pack.nr_objects);18691870 sorted_by_offset =xcalloc(to_pack.nr_objects,sizeof(struct object_entry *));1871for(i =0; i < to_pack.nr_objects; i++)1872 sorted_by_offset[i] = to_pack.objects + i;1873QSORT(sorted_by_offset, to_pack.nr_objects, pack_offset_sort);18741875for(i =0; i < to_pack.nr_objects; i++) {1876struct object_entry *entry = sorted_by_offset[i];1877check_object(entry);1878if(entry->type_valid &&1879oe_size_greater_than(&to_pack, entry, big_file_threshold))1880 entry->no_try_delta =1;1881display_progress(progress_state, i +1);1882}1883stop_progress(&progress_state);18841885/*1886 * This must happen in a second pass, since we rely on the delta1887 * information for the whole list being completed.1888 */1889for(i =0; i < to_pack.nr_objects; i++)1890break_delta_chains(&to_pack.objects[i]);18911892free(sorted_by_offset);1893}18941895/*1896 * We search for deltas in a list sorted by type, by filename hash, and then1897 * by size, so that we see progressively smaller and smaller files.1898 * That's because we prefer deltas to be from the bigger file1899 * to the smaller -- deletes are potentially cheaper, but perhaps1900 * more importantly, the bigger file is likely the more recent1901 * one. The deepest deltas are therefore the oldest objects which are1902 * less susceptible to be accessed often.1903 */1904static inttype_size_sort(const void*_a,const void*_b)1905{1906const struct object_entry *a = *(struct object_entry **)_a;1907const struct object_entry *b = *(struct object_entry **)_b;1908const enum object_type a_type =oe_type(a);1909const enum object_type b_type =oe_type(b);1910const unsigned long a_size =SIZE(a);1911const unsigned long b_size =SIZE(b);19121913if(a_type > b_type)1914return-1;1915if(a_type < b_type)1916return1;1917if(a->hash > b->hash)1918return-1;1919if(a->hash < b->hash)1920return1;1921if(a->preferred_base > b->preferred_base)1922return-1;1923if(a->preferred_base < b->preferred_base)1924return1;1925if(use_delta_islands) {1926const int island_cmp =island_delta_cmp(&a->idx.oid, &b->idx.oid);1927if(island_cmp)1928return island_cmp;1929}1930if(a_size > b_size)1931return-1;1932if(a_size < b_size)1933return1;1934return a < b ? -1: (a > b);/* newest first */1935}19361937struct unpacked {1938struct object_entry *entry;1939void*data;1940struct delta_index *index;1941unsigned depth;1942};19431944static intdelta_cacheable(unsigned long src_size,unsigned long trg_size,1945unsigned long delta_size)1946{1947if(max_delta_cache_size && delta_cache_size + delta_size > max_delta_cache_size)1948return0;19491950if(delta_size < cache_max_small_delta_size)1951return1;19521953/* cache delta, if objects are large enough compared to delta size */1954if((src_size >>20) + (trg_size >>21) > (delta_size >>10))1955return1;19561957return0;1958}19591960/* Protect delta_cache_size */1961static pthread_mutex_t cache_mutex;1962#define cache_lock() pthread_mutex_lock(&cache_mutex)1963#define cache_unlock() pthread_mutex_unlock(&cache_mutex)19641965/*1966 * Protect object list partitioning (e.g. struct thread_param) and1967 * progress_state1968 */1969static pthread_mutex_t progress_mutex;1970#define progress_lock() pthread_mutex_lock(&progress_mutex)1971#define progress_unlock() pthread_mutex_unlock(&progress_mutex)19721973/*1974 * Access to struct object_entry is unprotected since each thread owns1975 * a portion of the main object list. Just don't access object entries1976 * ahead in the list because they can be stolen and would need1977 * progress_mutex for protection.1978 */19791980/*1981 * Return the size of the object without doing any delta1982 * reconstruction (so non-deltas are true object sizes, but deltas1983 * return the size of the delta data).1984 */1985unsigned longoe_get_size_slow(struct packing_data *pack,1986const struct object_entry *e)1987{1988struct packed_git *p;1989struct pack_window *w_curs;1990unsigned char*buf;1991enum object_type type;1992unsigned long used, avail, size;19931994if(e->type_ != OBJ_OFS_DELTA && e->type_ != OBJ_REF_DELTA) {1995packing_data_lock(&to_pack);1996if(oid_object_info(the_repository, &e->idx.oid, &size) <0)1997die(_("unable to get size of%s"),1998oid_to_hex(&e->idx.oid));1999packing_data_unlock(&to_pack);2000return size;2001}20022003 p =oe_in_pack(pack, e);2004if(!p)2005BUG("when e->type is a delta, it must belong to a pack");20062007packing_data_lock(&to_pack);2008 w_curs = NULL;2009 buf =use_pack(p, &w_curs, e->in_pack_offset, &avail);2010 used =unpack_object_header_buffer(buf, avail, &type, &size);2011if(used ==0)2012die(_("unable to parse object header of%s"),2013oid_to_hex(&e->idx.oid));20142015unuse_pack(&w_curs);2016packing_data_unlock(&to_pack);2017return size;2018}20192020static inttry_delta(struct unpacked *trg,struct unpacked *src,2021unsigned max_depth,unsigned long*mem_usage)2022{2023struct object_entry *trg_entry = trg->entry;2024struct object_entry *src_entry = src->entry;2025unsigned long trg_size, src_size, delta_size, sizediff, max_size, sz;2026unsigned ref_depth;2027enum object_type type;2028void*delta_buf;20292030/* Don't bother doing diffs between different types */2031if(oe_type(trg_entry) !=oe_type(src_entry))2032return-1;20332034/*2035 * We do not bother to try a delta that we discarded on an2036 * earlier try, but only when reusing delta data. Note that2037 * src_entry that is marked as the preferred_base should always2038 * be considered, as even if we produce a suboptimal delta against2039 * it, we will still save the transfer cost, as we already know2040 * the other side has it and we won't send src_entry at all.2041 */2042if(reuse_delta &&IN_PACK(trg_entry) &&2043IN_PACK(trg_entry) ==IN_PACK(src_entry) &&2044!src_entry->preferred_base &&2045 trg_entry->in_pack_type != OBJ_REF_DELTA &&2046 trg_entry->in_pack_type != OBJ_OFS_DELTA)2047return0;20482049/* Let's not bust the allowed depth. */2050if(src->depth >= max_depth)2051return0;20522053/* Now some size filtering heuristics. */2054 trg_size =SIZE(trg_entry);2055if(!DELTA(trg_entry)) {2056 max_size = trg_size/2- the_hash_algo->rawsz;2057 ref_depth =1;2058}else{2059 max_size =DELTA_SIZE(trg_entry);2060 ref_depth = trg->depth;2061}2062 max_size = (uint64_t)max_size * (max_depth - src->depth) /2063(max_depth - ref_depth +1);2064if(max_size ==0)2065return0;2066 src_size =SIZE(src_entry);2067 sizediff = src_size < trg_size ? trg_size - src_size :0;2068if(sizediff >= max_size)2069return0;2070if(trg_size < src_size /32)2071return0;20722073if(!in_same_island(&trg->entry->idx.oid, &src->entry->idx.oid))2074return0;20752076/* Load data if not already done */2077if(!trg->data) {2078packing_data_lock(&to_pack);2079 trg->data =read_object_file(&trg_entry->idx.oid, &type, &sz);2080packing_data_unlock(&to_pack);2081if(!trg->data)2082die(_("object%scannot be read"),2083oid_to_hex(&trg_entry->idx.oid));2084if(sz != trg_size)2085die(_("object%sinconsistent object length (%"PRIuMAX" vs %"PRIuMAX")"),2086oid_to_hex(&trg_entry->idx.oid), (uintmax_t)sz,2087(uintmax_t)trg_size);2088*mem_usage += sz;2089}2090if(!src->data) {2091packing_data_lock(&to_pack);2092 src->data =read_object_file(&src_entry->idx.oid, &type, &sz);2093packing_data_unlock(&to_pack);2094if(!src->data) {2095if(src_entry->preferred_base) {2096static int warned =0;2097if(!warned++)2098warning(_("object%scannot be read"),2099oid_to_hex(&src_entry->idx.oid));2100/*2101 * Those objects are not included in the2102 * resulting pack. Be resilient and ignore2103 * them if they can't be read, in case the2104 * pack could be created nevertheless.2105 */2106return0;2107}2108die(_("object%scannot be read"),2109oid_to_hex(&src_entry->idx.oid));2110}2111if(sz != src_size)2112die(_("object%sinconsistent object length (%"PRIuMAX" vs %"PRIuMAX")"),2113oid_to_hex(&src_entry->idx.oid), (uintmax_t)sz,2114(uintmax_t)src_size);2115*mem_usage += sz;2116}2117if(!src->index) {2118 src->index =create_delta_index(src->data, src_size);2119if(!src->index) {2120static int warned =0;2121if(!warned++)2122warning(_("suboptimal pack - out of memory"));2123return0;2124}2125*mem_usage +=sizeof_delta_index(src->index);2126}21272128 delta_buf =create_delta(src->index, trg->data, trg_size, &delta_size, max_size);2129if(!delta_buf)2130return0;21312132if(DELTA(trg_entry)) {2133/* Prefer only shallower same-sized deltas. */2134if(delta_size ==DELTA_SIZE(trg_entry) &&2135 src->depth +1>= trg->depth) {2136free(delta_buf);2137return0;2138}2139}21402141/*2142 * Handle memory allocation outside of the cache2143 * accounting lock. Compiler will optimize the strangeness2144 * away when NO_PTHREADS is defined.2145 */2146free(trg_entry->delta_data);2147cache_lock();2148if(trg_entry->delta_data) {2149 delta_cache_size -=DELTA_SIZE(trg_entry);2150 trg_entry->delta_data = NULL;2151}2152if(delta_cacheable(src_size, trg_size, delta_size)) {2153 delta_cache_size += delta_size;2154cache_unlock();2155 trg_entry->delta_data =xrealloc(delta_buf, delta_size);2156}else{2157cache_unlock();2158free(delta_buf);2159}21602161SET_DELTA(trg_entry, src_entry);2162SET_DELTA_SIZE(trg_entry, delta_size);2163 trg->depth = src->depth +1;21642165return1;2166}21672168static unsigned intcheck_delta_limit(struct object_entry *me,unsigned int n)2169{2170struct object_entry *child =DELTA_CHILD(me);2171unsigned int m = n;2172while(child) {2173const unsigned int c =check_delta_limit(child, n +1);2174if(m < c)2175 m = c;2176 child =DELTA_SIBLING(child);2177}2178return m;2179}21802181static unsigned longfree_unpacked(struct unpacked *n)2182{2183unsigned long freed_mem =sizeof_delta_index(n->index);2184free_delta_index(n->index);2185 n->index = NULL;2186if(n->data) {2187 freed_mem +=SIZE(n->entry);2188FREE_AND_NULL(n->data);2189}2190 n->entry = NULL;2191 n->depth =0;2192return freed_mem;2193}21942195static voidfind_deltas(struct object_entry **list,unsigned*list_size,2196int window,int depth,unsigned*processed)2197{2198uint32_t i, idx =0, count =0;2199struct unpacked *array;2200unsigned long mem_usage =0;22012202 array =xcalloc(window,sizeof(struct unpacked));22032204for(;;) {2205struct object_entry *entry;2206struct unpacked *n = array + idx;2207int j, max_depth, best_base = -1;22082209progress_lock();2210if(!*list_size) {2211progress_unlock();2212break;2213}2214 entry = *list++;2215(*list_size)--;2216if(!entry->preferred_base) {2217(*processed)++;2218display_progress(progress_state, *processed);2219}2220progress_unlock();22212222 mem_usage -=free_unpacked(n);2223 n->entry = entry;22242225while(window_memory_limit &&2226 mem_usage > window_memory_limit &&2227 count >1) {2228const uint32_t tail = (idx + window - count) % window;2229 mem_usage -=free_unpacked(array + tail);2230 count--;2231}22322233/* We do not compute delta to *create* objects we are not2234 * going to pack.2235 */2236if(entry->preferred_base)2237goto next;22382239/*2240 * If the current object is at pack edge, take the depth the2241 * objects that depend on the current object into account2242 * otherwise they would become too deep.2243 */2244 max_depth = depth;2245if(DELTA_CHILD(entry)) {2246 max_depth -=check_delta_limit(entry,0);2247if(max_depth <=0)2248goto next;2249}22502251 j = window;2252while(--j >0) {2253int ret;2254uint32_t other_idx = idx + j;2255struct unpacked *m;2256if(other_idx >= window)2257 other_idx -= window;2258 m = array + other_idx;2259if(!m->entry)2260break;2261 ret =try_delta(n, m, max_depth, &mem_usage);2262if(ret <0)2263break;2264else if(ret >0)2265 best_base = other_idx;2266}22672268/*2269 * If we decided to cache the delta data, then it is best2270 * to compress it right away. First because we have to do2271 * it anyway, and doing it here while we're threaded will2272 * save a lot of time in the non threaded write phase,2273 * as well as allow for caching more deltas within2274 * the same cache size limit.2275 * ...2276 * But only if not writing to stdout, since in that case2277 * the network is most likely throttling writes anyway,2278 * and therefore it is best to go to the write phase ASAP2279 * instead, as we can afford spending more time compressing2280 * between writes at that moment.2281 */2282if(entry->delta_data && !pack_to_stdout) {2283unsigned long size;22842285 size =do_compress(&entry->delta_data,DELTA_SIZE(entry));2286if(size < (1U<< OE_Z_DELTA_BITS)) {2287 entry->z_delta_size = size;2288cache_lock();2289 delta_cache_size -=DELTA_SIZE(entry);2290 delta_cache_size += entry->z_delta_size;2291cache_unlock();2292}else{2293FREE_AND_NULL(entry->delta_data);2294 entry->z_delta_size =0;2295}2296}22972298/* if we made n a delta, and if n is already at max2299 * depth, leaving it in the window is pointless. we2300 * should evict it first.2301 */2302if(DELTA(entry) && max_depth <= n->depth)2303continue;23042305/*2306 * Move the best delta base up in the window, after the2307 * currently deltified object, to keep it longer. It will2308 * be the first base object to be attempted next.2309 */2310if(DELTA(entry)) {2311struct unpacked swap = array[best_base];2312int dist = (window + idx - best_base) % window;2313int dst = best_base;2314while(dist--) {2315int src = (dst +1) % window;2316 array[dst] = array[src];2317 dst = src;2318}2319 array[dst] = swap;2320}23212322 next:2323 idx++;2324if(count +1< window)2325 count++;2326if(idx >= window)2327 idx =0;2328}23292330for(i =0; i < window; ++i) {2331free_delta_index(array[i].index);2332free(array[i].data);2333}2334free(array);2335}23362337static voidtry_to_free_from_threads(size_t size)2338{2339packing_data_lock(&to_pack);2340release_pack_memory(size);2341packing_data_unlock(&to_pack);2342}23432344static try_to_free_t old_try_to_free_routine;23452346/*2347 * The main object list is split into smaller lists, each is handed to2348 * one worker.2349 *2350 * The main thread waits on the condition that (at least) one of the workers2351 * has stopped working (which is indicated in the .working member of2352 * struct thread_params).2353 *2354 * When a work thread has completed its work, it sets .working to 0 and2355 * signals the main thread and waits on the condition that .data_ready2356 * becomes 1.2357 *2358 * The main thread steals half of the work from the worker that has2359 * most work left to hand it to the idle worker.2360 */23612362struct thread_params {2363 pthread_t thread;2364struct object_entry **list;2365unsigned list_size;2366unsigned remaining;2367int window;2368int depth;2369int working;2370int data_ready;2371 pthread_mutex_t mutex;2372 pthread_cond_t cond;2373unsigned*processed;2374};23752376static pthread_cond_t progress_cond;23772378/*2379 * Mutex and conditional variable can't be statically-initialized on Windows.2380 */2381static voidinit_threaded_search(void)2382{2383pthread_mutex_init(&cache_mutex, NULL);2384pthread_mutex_init(&progress_mutex, NULL);2385pthread_cond_init(&progress_cond, NULL);2386 old_try_to_free_routine =set_try_to_free_routine(try_to_free_from_threads);2387}23882389static voidcleanup_threaded_search(void)2390{2391set_try_to_free_routine(old_try_to_free_routine);2392pthread_cond_destroy(&progress_cond);2393pthread_mutex_destroy(&cache_mutex);2394pthread_mutex_destroy(&progress_mutex);2395}23962397static void*threaded_find_deltas(void*arg)2398{2399struct thread_params *me = arg;24002401progress_lock();2402while(me->remaining) {2403progress_unlock();24042405find_deltas(me->list, &me->remaining,2406 me->window, me->depth, me->processed);24072408progress_lock();2409 me->working =0;2410pthread_cond_signal(&progress_cond);2411progress_unlock();24122413/*2414 * We must not set ->data_ready before we wait on the2415 * condition because the main thread may have set it to 12416 * before we get here. In order to be sure that new2417 * work is available if we see 1 in ->data_ready, it2418 * was initialized to 0 before this thread was spawned2419 * and we reset it to 0 right away.2420 */2421pthread_mutex_lock(&me->mutex);2422while(!me->data_ready)2423pthread_cond_wait(&me->cond, &me->mutex);2424 me->data_ready =0;2425pthread_mutex_unlock(&me->mutex);24262427progress_lock();2428}2429progress_unlock();2430/* leave ->working 1 so that this doesn't get more work assigned */2431return NULL;2432}24332434static voidll_find_deltas(struct object_entry **list,unsigned list_size,2435int window,int depth,unsigned*processed)2436{2437struct thread_params *p;2438int i, ret, active_threads =0;24392440init_threaded_search();24412442if(delta_search_threads <=1) {2443find_deltas(list, &list_size, window, depth, processed);2444cleanup_threaded_search();2445return;2446}2447if(progress > pack_to_stdout)2448fprintf_ln(stderr,_("Delta compression using up to%dthreads"),2449 delta_search_threads);2450 p =xcalloc(delta_search_threads,sizeof(*p));24512452/* Partition the work amongst work threads. */2453for(i =0; i < delta_search_threads; i++) {2454unsigned sub_size = list_size / (delta_search_threads - i);24552456/* don't use too small segments or no deltas will be found */2457if(sub_size <2*window && i+1< delta_search_threads)2458 sub_size =0;24592460 p[i].window = window;2461 p[i].depth = depth;2462 p[i].processed = processed;2463 p[i].working =1;2464 p[i].data_ready =0;24652466/* try to split chunks on "path" boundaries */2467while(sub_size && sub_size < list_size &&2468 list[sub_size]->hash &&2469 list[sub_size]->hash == list[sub_size-1]->hash)2470 sub_size++;24712472 p[i].list = list;2473 p[i].list_size = sub_size;2474 p[i].remaining = sub_size;24752476 list += sub_size;2477 list_size -= sub_size;2478}24792480/* Start work threads. */2481for(i =0; i < delta_search_threads; i++) {2482if(!p[i].list_size)2483continue;2484pthread_mutex_init(&p[i].mutex, NULL);2485pthread_cond_init(&p[i].cond, NULL);2486 ret =pthread_create(&p[i].thread, NULL,2487 threaded_find_deltas, &p[i]);2488if(ret)2489die(_("unable to create thread:%s"),strerror(ret));2490 active_threads++;2491}24922493/*2494 * Now let's wait for work completion. Each time a thread is done2495 * with its work, we steal half of the remaining work from the2496 * thread with the largest number of unprocessed objects and give2497 * it to that newly idle thread. This ensure good load balancing2498 * until the remaining object list segments are simply too short2499 * to be worth splitting anymore.2500 */2501while(active_threads) {2502struct thread_params *target = NULL;2503struct thread_params *victim = NULL;2504unsigned sub_size =0;25052506progress_lock();2507for(;;) {2508for(i =0; !target && i < delta_search_threads; i++)2509if(!p[i].working)2510 target = &p[i];2511if(target)2512break;2513pthread_cond_wait(&progress_cond, &progress_mutex);2514}25152516for(i =0; i < delta_search_threads; i++)2517if(p[i].remaining >2*window &&2518(!victim || victim->remaining < p[i].remaining))2519 victim = &p[i];2520if(victim) {2521 sub_size = victim->remaining /2;2522 list = victim->list + victim->list_size - sub_size;2523while(sub_size && list[0]->hash &&2524 list[0]->hash == list[-1]->hash) {2525 list++;2526 sub_size--;2527}2528if(!sub_size) {2529/*2530 * It is possible for some "paths" to have2531 * so many objects that no hash boundary2532 * might be found. Let's just steal the2533 * exact half in that case.2534 */2535 sub_size = victim->remaining /2;2536 list -= sub_size;2537}2538 target->list = list;2539 victim->list_size -= sub_size;2540 victim->remaining -= sub_size;2541}2542 target->list_size = sub_size;2543 target->remaining = sub_size;2544 target->working =1;2545progress_unlock();25462547pthread_mutex_lock(&target->mutex);2548 target->data_ready =1;2549pthread_cond_signal(&target->cond);2550pthread_mutex_unlock(&target->mutex);25512552if(!sub_size) {2553pthread_join(target->thread, NULL);2554pthread_cond_destroy(&target->cond);2555pthread_mutex_destroy(&target->mutex);2556 active_threads--;2557}2558}2559cleanup_threaded_search();2560free(p);2561}25622563static voidadd_tag_chain(const struct object_id *oid)2564{2565struct tag *tag;25662567/*2568 * We catch duplicates already in add_object_entry(), but we'd2569 * prefer to do this extra check to avoid having to parse the2570 * tag at all if we already know that it's being packed (e.g., if2571 * it was included via bitmaps, we would not have parsed it2572 * previously).2573 */2574if(packlist_find(&to_pack, oid->hash, NULL))2575return;25762577 tag =lookup_tag(the_repository, oid);2578while(1) {2579if(!tag ||parse_tag(tag) || !tag->tagged)2580die(_("unable to pack objects reachable from tag%s"),2581oid_to_hex(oid));25822583add_object_entry(&tag->object.oid, OBJ_TAG, NULL,0);25842585if(tag->tagged->type != OBJ_TAG)2586return;25872588 tag = (struct tag *)tag->tagged;2589}2590}25912592static intadd_ref_tag(const char*path,const struct object_id *oid,int flag,void*cb_data)2593{2594struct object_id peeled;25952596if(starts_with(path,"refs/tags/") &&/* is a tag? */2597!peel_ref(path, &peeled) &&/* peelable? */2598packlist_find(&to_pack, peeled.hash, NULL))/* object packed? */2599add_tag_chain(oid);2600return0;2601}26022603static voidprepare_pack(int window,int depth)2604{2605struct object_entry **delta_list;2606uint32_t i, nr_deltas;2607unsigned n;26082609if(use_delta_islands)2610resolve_tree_islands(the_repository, progress, &to_pack);26112612get_object_details();26132614/*2615 * If we're locally repacking then we need to be doubly careful2616 * from now on in order to make sure no stealth corruption gets2617 * propagated to the new pack. Clients receiving streamed packs2618 * should validate everything they get anyway so no need to incur2619 * the additional cost here in that case.2620 */2621if(!pack_to_stdout)2622 do_check_packed_object_crc =1;26232624if(!to_pack.nr_objects || !window || !depth)2625return;26262627ALLOC_ARRAY(delta_list, to_pack.nr_objects);2628 nr_deltas = n =0;26292630for(i =0; i < to_pack.nr_objects; i++) {2631struct object_entry *entry = to_pack.objects + i;26322633if(DELTA(entry))2634/* This happens if we decided to reuse existing2635 * delta from a pack. "reuse_delta &&" is implied.2636 */2637continue;26382639if(!entry->type_valid ||2640oe_size_less_than(&to_pack, entry,50))2641continue;26422643if(entry->no_try_delta)2644continue;26452646if(!entry->preferred_base) {2647 nr_deltas++;2648if(oe_type(entry) <0)2649die(_("unable to get type of object%s"),2650oid_to_hex(&entry->idx.oid));2651}else{2652if(oe_type(entry) <0) {2653/*2654 * This object is not found, but we2655 * don't have to include it anyway.2656 */2657continue;2658}2659}26602661 delta_list[n++] = entry;2662}26632664if(nr_deltas && n >1) {2665unsigned nr_done =0;2666if(progress)2667 progress_state =start_progress(_("Compressing objects"),2668 nr_deltas);2669QSORT(delta_list, n, type_size_sort);2670ll_find_deltas(delta_list, n, window+1, depth, &nr_done);2671stop_progress(&progress_state);2672if(nr_done != nr_deltas)2673die(_("inconsistency with delta count"));2674}2675free(delta_list);2676}26772678static intgit_pack_config(const char*k,const char*v,void*cb)2679{2680if(!strcmp(k,"pack.window")) {2681 window =git_config_int(k, v);2682return0;2683}2684if(!strcmp(k,"pack.windowmemory")) {2685 window_memory_limit =git_config_ulong(k, v);2686return0;2687}2688if(!strcmp(k,"pack.depth")) {2689 depth =git_config_int(k, v);2690return0;2691}2692if(!strcmp(k,"pack.deltacachesize")) {2693 max_delta_cache_size =git_config_int(k, v);2694return0;2695}2696if(!strcmp(k,"pack.deltacachelimit")) {2697 cache_max_small_delta_size =git_config_int(k, v);2698return0;2699}2700if(!strcmp(k,"pack.writebitmaphashcache")) {2701if(git_config_bool(k, v))2702 write_bitmap_options |= BITMAP_OPT_HASH_CACHE;2703else2704 write_bitmap_options &= ~BITMAP_OPT_HASH_CACHE;2705}2706if(!strcmp(k,"pack.usebitmaps")) {2707 use_bitmap_index_default =git_config_bool(k, v);2708return0;2709}2710if(!strcmp(k,"pack.usesparse")) {2711 sparse =git_config_bool(k, v);2712return0;2713}2714if(!strcmp(k,"pack.threads")) {2715 delta_search_threads =git_config_int(k, v);2716if(delta_search_threads <0)2717die(_("invalid number of threads specified (%d)"),2718 delta_search_threads);2719if(!HAVE_THREADS && delta_search_threads !=1) {2720warning(_("no threads support, ignoring%s"), k);2721 delta_search_threads =0;2722}2723return0;2724}2725if(!strcmp(k,"pack.indexversion")) {2726 pack_idx_opts.version =git_config_int(k, v);2727if(pack_idx_opts.version >2)2728die(_("bad pack.indexversion=%"PRIu32),2729 pack_idx_opts.version);2730return0;2731}2732returngit_default_config(k, v, cb);2733}27342735static voidread_object_list_from_stdin(void)2736{2737char line[GIT_MAX_HEXSZ +1+ PATH_MAX +2];2738struct object_id oid;2739const char*p;27402741for(;;) {2742if(!fgets(line,sizeof(line), stdin)) {2743if(feof(stdin))2744break;2745if(!ferror(stdin))2746die("BUG: fgets returned NULL, not EOF, not error!");2747if(errno != EINTR)2748die_errno("fgets");2749clearerr(stdin);2750continue;2751}2752if(line[0] =='-') {2753if(get_oid_hex(line+1, &oid))2754die(_("expected edge object ID, got garbage:\n%s"),2755 line);2756add_preferred_base(&oid);2757continue;2758}2759if(parse_oid_hex(line, &oid, &p))2760die(_("expected object ID, got garbage:\n%s"), line);27612762add_preferred_base_object(p +1);2763add_object_entry(&oid, OBJ_NONE, p +1,0);2764}2765}27662767/* Remember to update object flag allocation in object.h */2768#define OBJECT_ADDED (1u<<20)27692770static voidshow_commit(struct commit *commit,void*data)2771{2772add_object_entry(&commit->object.oid, OBJ_COMMIT, NULL,0);2773 commit->object.flags |= OBJECT_ADDED;27742775if(write_bitmap_index)2776index_commit_for_bitmap(commit);27772778if(use_delta_islands)2779propagate_island_marks(commit);2780}27812782static voidshow_object(struct object *obj,const char*name,void*data)2783{2784add_preferred_base_object(name);2785add_object_entry(&obj->oid, obj->type, name,0);2786 obj->flags |= OBJECT_ADDED;27872788if(use_delta_islands) {2789const char*p;2790unsigned depth;2791struct object_entry *ent;27922793/* the empty string is a root tree, which is depth 0 */2794 depth = *name ?1:0;2795for(p =strchr(name,'/'); p; p =strchr(p +1,'/'))2796 depth++;27972798 ent =packlist_find(&to_pack, obj->oid.hash, NULL);2799if(ent && depth >oe_tree_depth(&to_pack, ent))2800oe_set_tree_depth(&to_pack, ent, depth);2801}2802}28032804static voidshow_object__ma_allow_any(struct object *obj,const char*name,void*data)2805{2806assert(arg_missing_action == MA_ALLOW_ANY);28072808/*2809 * Quietly ignore ALL missing objects. This avoids problems with2810 * staging them now and getting an odd error later.2811 */2812if(!has_object_file(&obj->oid))2813return;28142815show_object(obj, name, data);2816}28172818static voidshow_object__ma_allow_promisor(struct object *obj,const char*name,void*data)2819{2820assert(arg_missing_action == MA_ALLOW_PROMISOR);28212822/*2823 * Quietly ignore EXPECTED missing objects. This avoids problems with2824 * staging them now and getting an odd error later.2825 */2826if(!has_object_file(&obj->oid) &&is_promisor_object(&obj->oid))2827return;28282829show_object(obj, name, data);2830}28312832static intoption_parse_missing_action(const struct option *opt,2833const char*arg,int unset)2834{2835assert(arg);2836assert(!unset);28372838if(!strcmp(arg,"error")) {2839 arg_missing_action = MA_ERROR;2840 fn_show_object = show_object;2841return0;2842}28432844if(!strcmp(arg,"allow-any")) {2845 arg_missing_action = MA_ALLOW_ANY;2846 fetch_if_missing =0;2847 fn_show_object = show_object__ma_allow_any;2848return0;2849}28502851if(!strcmp(arg,"allow-promisor")) {2852 arg_missing_action = MA_ALLOW_PROMISOR;2853 fetch_if_missing =0;2854 fn_show_object = show_object__ma_allow_promisor;2855return0;2856}28572858die(_("invalid value for --missing"));2859return0;2860}28612862static voidshow_edge(struct commit *commit)2863{2864add_preferred_base(&commit->object.oid);2865}28662867struct in_pack_object {2868 off_t offset;2869struct object *object;2870};28712872struct in_pack {2873unsigned int alloc;2874unsigned int nr;2875struct in_pack_object *array;2876};28772878static voidmark_in_pack_object(struct object *object,struct packed_git *p,struct in_pack *in_pack)2879{2880 in_pack->array[in_pack->nr].offset =find_pack_entry_one(object->oid.hash, p);2881 in_pack->array[in_pack->nr].object = object;2882 in_pack->nr++;2883}28842885/*2886 * Compare the objects in the offset order, in order to emulate the2887 * "git rev-list --objects" output that produced the pack originally.2888 */2889static intofscmp(const void*a_,const void*b_)2890{2891struct in_pack_object *a = (struct in_pack_object *)a_;2892struct in_pack_object *b = (struct in_pack_object *)b_;28932894if(a->offset < b->offset)2895return-1;2896else if(a->offset > b->offset)2897return1;2898else2899returnoidcmp(&a->object->oid, &b->object->oid);2900}29012902static voidadd_objects_in_unpacked_packs(void)2903{2904struct packed_git *p;2905struct in_pack in_pack;2906uint32_t i;29072908memset(&in_pack,0,sizeof(in_pack));29092910for(p =get_all_packs(the_repository); p; p = p->next) {2911struct object_id oid;2912struct object *o;29132914if(!p->pack_local || p->pack_keep || p->pack_keep_in_core)2915continue;2916if(open_pack_index(p))2917die(_("cannot open pack index"));29182919ALLOC_GROW(in_pack.array,2920 in_pack.nr + p->num_objects,2921 in_pack.alloc);29222923for(i =0; i < p->num_objects; i++) {2924nth_packed_object_oid(&oid, p, i);2925 o =lookup_unknown_object(oid.hash);2926if(!(o->flags & OBJECT_ADDED))2927mark_in_pack_object(o, p, &in_pack);2928 o->flags |= OBJECT_ADDED;2929}2930}29312932if(in_pack.nr) {2933QSORT(in_pack.array, in_pack.nr, ofscmp);2934for(i =0; i < in_pack.nr; i++) {2935struct object *o = in_pack.array[i].object;2936add_object_entry(&o->oid, o->type,"",0);2937}2938}2939free(in_pack.array);2940}29412942static intadd_loose_object(const struct object_id *oid,const char*path,2943void*data)2944{2945enum object_type type =oid_object_info(the_repository, oid, NULL);29462947if(type <0) {2948warning(_("loose object at%scould not be examined"), path);2949return0;2950}29512952add_object_entry(oid, type,"",0);2953return0;2954}29552956/*2957 * We actually don't even have to worry about reachability here.2958 * add_object_entry will weed out duplicates, so we just add every2959 * loose object we find.2960 */2961static voidadd_unreachable_loose_objects(void)2962{2963for_each_loose_file_in_objdir(get_object_directory(),2964 add_loose_object,2965 NULL, NULL, NULL);2966}29672968static inthas_sha1_pack_kept_or_nonlocal(const struct object_id *oid)2969{2970static struct packed_git *last_found = (void*)1;2971struct packed_git *p;29722973 p = (last_found != (void*)1) ? last_found :2974get_all_packs(the_repository);29752976while(p) {2977if((!p->pack_local || p->pack_keep ||2978 p->pack_keep_in_core) &&2979find_pack_entry_one(oid->hash, p)) {2980 last_found = p;2981return1;2982}2983if(p == last_found)2984 p =get_all_packs(the_repository);2985else2986 p = p->next;2987if(p == last_found)2988 p = p->next;2989}2990return0;2991}29922993/*2994 * Store a list of sha1s that are should not be discarded2995 * because they are either written too recently, or are2996 * reachable from another object that was.2997 *2998 * This is filled by get_object_list.2999 */3000static struct oid_array recent_objects;30013002static intloosened_object_can_be_discarded(const struct object_id *oid,3003 timestamp_t mtime)3004{3005if(!unpack_unreachable_expiration)3006return0;3007if(mtime > unpack_unreachable_expiration)3008return0;3009if(oid_array_lookup(&recent_objects, oid) >=0)3010return0;3011return1;3012}30133014static voidloosen_unused_packed_objects(void)3015{3016struct packed_git *p;3017uint32_t i;3018struct object_id oid;30193020for(p =get_all_packs(the_repository); p; p = p->next) {3021if(!p->pack_local || p->pack_keep || p->pack_keep_in_core)3022continue;30233024if(open_pack_index(p))3025die(_("cannot open pack index"));30263027for(i =0; i < p->num_objects; i++) {3028nth_packed_object_oid(&oid, p, i);3029if(!packlist_find(&to_pack, oid.hash, NULL) &&3030!has_sha1_pack_kept_or_nonlocal(&oid) &&3031!loosened_object_can_be_discarded(&oid, p->mtime))3032if(force_object_loose(&oid, p->mtime))3033die(_("unable to force loose object"));3034}3035}3036}30373038/*3039 * This tracks any options which pack-reuse code expects to be on, or which a3040 * reader of the pack might not understand, and which would therefore prevent3041 * blind reuse of what we have on disk.3042 */3043static intpack_options_allow_reuse(void)3044{3045return pack_to_stdout &&3046 allow_ofs_delta &&3047!ignore_packed_keep_on_disk &&3048!ignore_packed_keep_in_core &&3049(!local || !have_non_local_packs) &&3050!incremental;3051}30523053static intget_object_list_from_bitmap(struct rev_info *revs)3054{3055if(!(bitmap_git =prepare_bitmap_walk(revs)))3056return-1;30573058if(pack_options_allow_reuse() &&3059!reuse_partial_packfile_from_bitmap(3060 bitmap_git,3061&reuse_packfile,3062&reuse_packfile_objects,3063&reuse_packfile_offset)) {3064assert(reuse_packfile_objects);3065 nr_result += reuse_packfile_objects;3066display_progress(progress_state, nr_result);3067}30683069traverse_bitmap_commit_list(bitmap_git, &add_object_entry_from_bitmap);3070return0;3071}30723073static voidrecord_recent_object(struct object *obj,3074const char*name,3075void*data)3076{3077oid_array_append(&recent_objects, &obj->oid);3078}30793080static voidrecord_recent_commit(struct commit *commit,void*data)3081{3082oid_array_append(&recent_objects, &commit->object.oid);3083}30843085static voidget_object_list(int ac,const char**av)3086{3087struct rev_info revs;3088struct setup_revision_opt s_r_opt = {3089.allow_exclude_promisor_objects =1,3090};3091char line[1000];3092int flags =0;3093int save_warning;30943095repo_init_revisions(the_repository, &revs, NULL);3096 save_commit_buffer =0;3097setup_revisions(ac, av, &revs, &s_r_opt);30983099/* make sure shallows are read */3100is_repository_shallow(the_repository);31013102 save_warning = warn_on_object_refname_ambiguity;3103 warn_on_object_refname_ambiguity =0;31043105while(fgets(line,sizeof(line), stdin) != NULL) {3106int len =strlen(line);3107if(len && line[len -1] =='\n')3108 line[--len] =0;3109if(!len)3110break;3111if(*line =='-') {3112if(!strcmp(line,"--not")) {3113 flags ^= UNINTERESTING;3114 write_bitmap_index =0;3115continue;3116}3117if(starts_with(line,"--shallow ")) {3118struct object_id oid;3119if(get_oid_hex(line +10, &oid))3120die("not an SHA-1 '%s'", line +10);3121register_shallow(the_repository, &oid);3122 use_bitmap_index =0;3123continue;3124}3125die(_("not a rev '%s'"), line);3126}3127if(handle_revision_arg(line, &revs, flags, REVARG_CANNOT_BE_FILENAME))3128die(_("bad revision '%s'"), line);3129}31303131 warn_on_object_refname_ambiguity = save_warning;31323133if(use_bitmap_index && !get_object_list_from_bitmap(&revs))3134return;31353136if(use_delta_islands)3137load_delta_islands(the_repository);31383139if(prepare_revision_walk(&revs))3140die(_("revision walk setup failed"));3141mark_edges_uninteresting(&revs, show_edge, sparse);31423143if(!fn_show_object)3144 fn_show_object = show_object;3145traverse_commit_list_filtered(&filter_options, &revs,3146 show_commit, fn_show_object, NULL,3147 NULL);31483149if(unpack_unreachable_expiration) {3150 revs.ignore_missing_links =1;3151if(add_unseen_recent_objects_to_traversal(&revs,3152 unpack_unreachable_expiration))3153die(_("unable to add recent objects"));3154if(prepare_revision_walk(&revs))3155die(_("revision walk setup failed"));3156traverse_commit_list(&revs, record_recent_commit,3157 record_recent_object, NULL);3158}31593160if(keep_unreachable)3161add_objects_in_unpacked_packs();3162if(pack_loose_unreachable)3163add_unreachable_loose_objects();3164if(unpack_unreachable)3165loosen_unused_packed_objects();31663167oid_array_clear(&recent_objects);3168}31693170static voidadd_extra_kept_packs(const struct string_list *names)3171{3172struct packed_git *p;31733174if(!names->nr)3175return;31763177for(p =get_all_packs(the_repository); p; p = p->next) {3178const char*name =basename(p->pack_name);3179int i;31803181if(!p->pack_local)3182continue;31833184for(i =0; i < names->nr; i++)3185if(!fspathcmp(name, names->items[i].string))3186break;31873188if(i < names->nr) {3189 p->pack_keep_in_core =1;3190 ignore_packed_keep_in_core =1;3191continue;3192}3193}3194}31953196static intoption_parse_index_version(const struct option *opt,3197const char*arg,int unset)3198{3199char*c;3200const char*val = arg;32013202BUG_ON_OPT_NEG(unset);32033204 pack_idx_opts.version =strtoul(val, &c,10);3205if(pack_idx_opts.version >2)3206die(_("unsupported index version%s"), val);3207if(*c ==','&& c[1])3208 pack_idx_opts.off32_limit =strtoul(c+1, &c,0);3209if(*c || pack_idx_opts.off32_limit &0x80000000)3210die(_("bad index version '%s'"), val);3211return0;3212}32133214static intoption_parse_unpack_unreachable(const struct option *opt,3215const char*arg,int unset)3216{3217if(unset) {3218 unpack_unreachable =0;3219 unpack_unreachable_expiration =0;3220}3221else{3222 unpack_unreachable =1;3223if(arg)3224 unpack_unreachable_expiration =approxidate(arg);3225}3226return0;3227}32283229intcmd_pack_objects(int argc,const char**argv,const char*prefix)3230{3231int use_internal_rev_list =0;3232int shallow =0;3233int all_progress_implied =0;3234struct argv_array rp = ARGV_ARRAY_INIT;3235int rev_list_unpacked =0, rev_list_all =0, rev_list_reflog =0;3236int rev_list_index =0;3237struct string_list keep_pack_list = STRING_LIST_INIT_NODUP;3238struct option pack_objects_options[] = {3239OPT_SET_INT('q',"quiet", &progress,3240N_("do not show progress meter"),0),3241OPT_SET_INT(0,"progress", &progress,3242N_("show progress meter"),1),3243OPT_SET_INT(0,"all-progress", &progress,3244N_("show progress meter during object writing phase"),2),3245OPT_BOOL(0,"all-progress-implied",3246&all_progress_implied,3247N_("similar to --all-progress when progress meter is shown")),3248{ OPTION_CALLBACK,0,"index-version", NULL,N_("<version>[,<offset>]"),3249N_("write the pack index file in the specified idx format version"),3250 PARSE_OPT_NONEG, option_parse_index_version },3251OPT_MAGNITUDE(0,"max-pack-size", &pack_size_limit,3252N_("maximum size of each output pack file")),3253OPT_BOOL(0,"local", &local,3254N_("ignore borrowed objects from alternate object store")),3255OPT_BOOL(0,"incremental", &incremental,3256N_("ignore packed objects")),3257OPT_INTEGER(0,"window", &window,3258N_("limit pack window by objects")),3259OPT_MAGNITUDE(0,"window-memory", &window_memory_limit,3260N_("limit pack window by memory in addition to object limit")),3261OPT_INTEGER(0,"depth", &depth,3262N_("maximum length of delta chain allowed in the resulting pack")),3263OPT_BOOL(0,"reuse-delta", &reuse_delta,3264N_("reuse existing deltas")),3265OPT_BOOL(0,"reuse-object", &reuse_object,3266N_("reuse existing objects")),3267OPT_BOOL(0,"delta-base-offset", &allow_ofs_delta,3268N_("use OFS_DELTA objects")),3269OPT_INTEGER(0,"threads", &delta_search_threads,3270N_("use threads when searching for best delta matches")),3271OPT_BOOL(0,"non-empty", &non_empty,3272N_("do not create an empty pack output")),3273OPT_BOOL(0,"revs", &use_internal_rev_list,3274N_("read revision arguments from standard input")),3275OPT_SET_INT_F(0,"unpacked", &rev_list_unpacked,3276N_("limit the objects to those that are not yet packed"),32771, PARSE_OPT_NONEG),3278OPT_SET_INT_F(0,"all", &rev_list_all,3279N_("include objects reachable from any reference"),32801, PARSE_OPT_NONEG),3281OPT_SET_INT_F(0,"reflog", &rev_list_reflog,3282N_("include objects referred by reflog entries"),32831, PARSE_OPT_NONEG),3284OPT_SET_INT_F(0,"indexed-objects", &rev_list_index,3285N_("include objects referred to by the index"),32861, PARSE_OPT_NONEG),3287OPT_BOOL(0,"stdout", &pack_to_stdout,3288N_("output pack to stdout")),3289OPT_BOOL(0,"include-tag", &include_tag,3290N_("include tag objects that refer to objects to be packed")),3291OPT_BOOL(0,"keep-unreachable", &keep_unreachable,3292N_("keep unreachable objects")),3293OPT_BOOL(0,"pack-loose-unreachable", &pack_loose_unreachable,3294N_("pack loose unreachable objects")),3295{ OPTION_CALLBACK,0,"unpack-unreachable", NULL,N_("time"),3296N_("unpack unreachable objects newer than <time>"),3297 PARSE_OPT_OPTARG, option_parse_unpack_unreachable },3298OPT_BOOL(0,"sparse", &sparse,3299N_("use the sparse reachability algorithm")),3300OPT_BOOL(0,"thin", &thin,3301N_("create thin packs")),3302OPT_BOOL(0,"shallow", &shallow,3303N_("create packs suitable for shallow fetches")),3304OPT_BOOL(0,"honor-pack-keep", &ignore_packed_keep_on_disk,3305N_("ignore packs that have companion .keep file")),3306OPT_STRING_LIST(0,"keep-pack", &keep_pack_list,N_("name"),3307N_("ignore this pack")),3308OPT_INTEGER(0,"compression", &pack_compression_level,3309N_("pack compression level")),3310OPT_SET_INT(0,"keep-true-parents", &grafts_replace_parents,3311N_("do not hide commits by grafts"),0),3312OPT_BOOL(0,"use-bitmap-index", &use_bitmap_index,3313N_("use a bitmap index if available to speed up counting objects")),3314OPT_BOOL(0,"write-bitmap-index", &write_bitmap_index,3315N_("write a bitmap index together with the pack index")),3316OPT_PARSE_LIST_OBJECTS_FILTER(&filter_options),3317{ OPTION_CALLBACK,0,"missing", NULL,N_("action"),3318N_("handling for missing objects"), PARSE_OPT_NONEG,3319 option_parse_missing_action },3320OPT_BOOL(0,"exclude-promisor-objects", &exclude_promisor_objects,3321N_("do not pack objects in promisor packfiles")),3322OPT_BOOL(0,"delta-islands", &use_delta_islands,3323N_("respect islands during delta compression")),3324OPT_END(),3325};33263327if(DFS_NUM_STATES > (1<< OE_DFS_STATE_BITS))3328BUG("too many dfs states, increase OE_DFS_STATE_BITS");33293330 read_replace_refs =0;33313332 sparse =git_env_bool("GIT_TEST_PACK_SPARSE",0);3333reset_pack_idx_option(&pack_idx_opts);3334git_config(git_pack_config, NULL);33353336 progress =isatty(2);3337 argc =parse_options(argc, argv, prefix, pack_objects_options,3338 pack_usage,0);33393340if(argc) {3341 base_name = argv[0];3342 argc--;3343}3344if(pack_to_stdout != !base_name || argc)3345usage_with_options(pack_usage, pack_objects_options);33463347if(depth >= (1<< OE_DEPTH_BITS)) {3348warning(_("delta chain depth%dis too deep, forcing%d"),3349 depth, (1<< OE_DEPTH_BITS) -1);3350 depth = (1<< OE_DEPTH_BITS) -1;3351}3352if(cache_max_small_delta_size >= (1U<< OE_Z_DELTA_BITS)) {3353warning(_("pack.deltaCacheLimit is too high, forcing%d"),3354(1U<< OE_Z_DELTA_BITS) -1);3355 cache_max_small_delta_size = (1U<< OE_Z_DELTA_BITS) -1;3356}33573358argv_array_push(&rp,"pack-objects");3359if(thin) {3360 use_internal_rev_list =1;3361argv_array_push(&rp, shallow3362?"--objects-edge-aggressive"3363:"--objects-edge");3364}else3365argv_array_push(&rp,"--objects");33663367if(rev_list_all) {3368 use_internal_rev_list =1;3369argv_array_push(&rp,"--all");3370}3371if(rev_list_reflog) {3372 use_internal_rev_list =1;3373argv_array_push(&rp,"--reflog");3374}3375if(rev_list_index) {3376 use_internal_rev_list =1;3377argv_array_push(&rp,"--indexed-objects");3378}3379if(rev_list_unpacked) {3380 use_internal_rev_list =1;3381argv_array_push(&rp,"--unpacked");3382}33833384if(exclude_promisor_objects) {3385 use_internal_rev_list =1;3386 fetch_if_missing =0;3387argv_array_push(&rp,"--exclude-promisor-objects");3388}3389if(unpack_unreachable || keep_unreachable || pack_loose_unreachable)3390 use_internal_rev_list =1;33913392if(!reuse_object)3393 reuse_delta =0;3394if(pack_compression_level == -1)3395 pack_compression_level = Z_DEFAULT_COMPRESSION;3396else if(pack_compression_level <0|| pack_compression_level > Z_BEST_COMPRESSION)3397die(_("bad pack compression level%d"), pack_compression_level);33983399if(!delta_search_threads)/* --threads=0 means autodetect */3400 delta_search_threads =online_cpus();34013402if(!HAVE_THREADS && delta_search_threads !=1)3403warning(_("no threads support, ignoring --threads"));3404if(!pack_to_stdout && !pack_size_limit)3405 pack_size_limit = pack_size_limit_cfg;3406if(pack_to_stdout && pack_size_limit)3407die(_("--max-pack-size cannot be used to build a pack for transfer"));3408if(pack_size_limit && pack_size_limit <1024*1024) {3409warning(_("minimum pack size limit is 1 MiB"));3410 pack_size_limit =1024*1024;3411}34123413if(!pack_to_stdout && thin)3414die(_("--thin cannot be used to build an indexable pack"));34153416if(keep_unreachable && unpack_unreachable)3417die(_("--keep-unreachable and --unpack-unreachable are incompatible"));3418if(!rev_list_all || !rev_list_reflog || !rev_list_index)3419 unpack_unreachable_expiration =0;34203421if(filter_options.choice) {3422if(!pack_to_stdout)3423die(_("cannot use --filter without --stdout"));3424 use_bitmap_index =0;3425}34263427/*3428 * "soft" reasons not to use bitmaps - for on-disk repack by default we want3429 *3430 * - to produce good pack (with bitmap index not-yet-packed objects are3431 * packed in suboptimal order).3432 *3433 * - to use more robust pack-generation codepath (avoiding possible3434 * bugs in bitmap code and possible bitmap index corruption).3435 */3436if(!pack_to_stdout)3437 use_bitmap_index_default =0;34383439if(use_bitmap_index <0)3440 use_bitmap_index = use_bitmap_index_default;34413442/* "hard" reasons not to use bitmaps; these just won't work at all */3443if(!use_internal_rev_list || (!pack_to_stdout && write_bitmap_index) ||is_repository_shallow(the_repository))3444 use_bitmap_index =0;34453446if(pack_to_stdout || !rev_list_all)3447 write_bitmap_index =0;34483449if(use_delta_islands)3450argv_array_push(&rp,"--topo-order");34513452if(progress && all_progress_implied)3453 progress =2;34543455add_extra_kept_packs(&keep_pack_list);3456if(ignore_packed_keep_on_disk) {3457struct packed_git *p;3458for(p =get_all_packs(the_repository); p; p = p->next)3459if(p->pack_local && p->pack_keep)3460break;3461if(!p)/* no keep-able packs found */3462 ignore_packed_keep_on_disk =0;3463}3464if(local) {3465/*3466 * unlike ignore_packed_keep_on_disk above, we do not3467 * want to unset "local" based on looking at packs, as3468 * it also covers non-local objects3469 */3470struct packed_git *p;3471for(p =get_all_packs(the_repository); p; p = p->next) {3472if(!p->pack_local) {3473 have_non_local_packs =1;3474break;3475}3476}3477}34783479trace2_region_enter("pack-objects","enumerate-objects",3480 the_repository);3481prepare_packing_data(the_repository, &to_pack);34823483if(progress)3484 progress_state =start_progress(_("Enumerating objects"),0);3485if(!use_internal_rev_list)3486read_object_list_from_stdin();3487else{3488get_object_list(rp.argc, rp.argv);3489argv_array_clear(&rp);3490}3491cleanup_preferred_base();3492if(include_tag && nr_result)3493for_each_ref(add_ref_tag, NULL);3494stop_progress(&progress_state);3495trace2_region_leave("pack-objects","enumerate-objects",3496 the_repository);34973498if(non_empty && !nr_result)3499return0;3500if(nr_result) {3501trace2_region_enter("pack-objects","prepare-pack",3502 the_repository);3503prepare_pack(window, depth);3504trace2_region_leave("pack-objects","prepare-pack",3505 the_repository);3506}35073508trace2_region_enter("pack-objects","write-pack-file", the_repository);3509write_pack_file();3510trace2_region_leave("pack-objects","write-pack-file", the_repository);35113512if(progress)3513fprintf_ln(stderr,3514_("Total %"PRIu32" (delta %"PRIu32"),"3515" reused %"PRIu32" (delta %"PRIu32")"),3516 written, written_delta, reused, reused_delta);3517return0;3518}