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 36#define IN_PACK(obj) oe_in_pack(&to_pack, obj) 37#define SIZE(obj) oe_size(&to_pack, obj) 38#define SET_SIZE(obj,size) oe_set_size(&to_pack, obj, size) 39#define DELTA_SIZE(obj) oe_delta_size(&to_pack, obj) 40#define DELTA(obj) oe_delta(&to_pack, obj) 41#define DELTA_CHILD(obj) oe_delta_child(&to_pack, obj) 42#define DELTA_SIBLING(obj) oe_delta_sibling(&to_pack, obj) 43#define SET_DELTA(obj, val) oe_set_delta(&to_pack, obj, val) 44#define SET_DELTA_SIZE(obj, val) oe_set_delta_size(&to_pack, obj, val) 45#define SET_DELTA_CHILD(obj, val) oe_set_delta_child(&to_pack, obj, val) 46#define SET_DELTA_SIBLING(obj, val) oe_set_delta_sibling(&to_pack, obj, val) 47 48static const char *pack_usage[] = { 49 N_("git pack-objects --stdout [<options>...] [< <ref-list> | < <object-list>]"), 50 N_("git pack-objects [<options>...] <base-name> [< <ref-list> | < <object-list>]"), 51 NULL 52}; 53 54/* 55 * Objects we are going to pack are collected in the `to_pack` structure. 56 * It contains an array (dynamically expanded) of the object data, and a map 57 * that can resolve SHA1s to their position in the array. 58 */ 59static struct packing_data to_pack; 60 61static struct pack_idx_entry **written_list; 62static uint32_t nr_result, nr_written, nr_seen; 63static uint32_t write_layer; 64 65static int non_empty; 66static int reuse_delta = 1, reuse_object = 1; 67static int keep_unreachable, unpack_unreachable, include_tag; 68static timestamp_t unpack_unreachable_expiration; 69static int pack_loose_unreachable; 70static int local; 71static int have_non_local_packs; 72static int incremental; 73static int ignore_packed_keep_on_disk; 74static int ignore_packed_keep_in_core; 75static int allow_ofs_delta; 76static struct pack_idx_option pack_idx_opts; 77static const char *base_name; 78static int progress = 1; 79static int window = 10; 80static unsigned long pack_size_limit; 81static int depth = 50; 82static int delta_search_threads; 83static int pack_to_stdout; 84static int num_preferred_base; 85static struct progress *progress_state; 86 87static struct packed_git *reuse_packfile; 88static uint32_t reuse_packfile_objects; 89static off_t reuse_packfile_offset; 90 91static int use_bitmap_index_default = 1; 92static int use_bitmap_index = -1; 93static int write_bitmap_index; 94static uint16_t write_bitmap_options; 95 96static int exclude_promisor_objects; 97 98static int use_delta_islands; 99 100static unsigned long delta_cache_size = 0; 101static unsigned long max_delta_cache_size = DEFAULT_DELTA_CACHE_SIZE; 102static unsigned long cache_max_small_delta_size = 1000; 103 104static unsigned long window_memory_limit = 0; 105 106static struct list_objects_filter_options filter_options; 107 108enum missing_action { 109 MA_ERROR = 0, /* fail if any missing objects are encountered */ 110 MA_ALLOW_ANY, /* silently allow ALL missing objects */ 111 MA_ALLOW_PROMISOR, /* silently allow all missing PROMISOR objects */ 112}; 113static enum missing_action arg_missing_action; 114static show_object_fn fn_show_object; 115 116/* 117 * stats 118 */ 119static uint32_t written, written_delta; 120static uint32_t reused, reused_delta; 121 122/* 123 * Indexed commits 124 */ 125static struct commit **indexed_commits; 126static unsigned int indexed_commits_nr; 127static unsigned int indexed_commits_alloc; 128 129static void index_commit_for_bitmap(struct commit *commit) 130{ 131 if (indexed_commits_nr >= indexed_commits_alloc) { 132 indexed_commits_alloc = (indexed_commits_alloc + 32) * 2; 133 REALLOC_ARRAY(indexed_commits, indexed_commits_alloc); 134 } 135 136 indexed_commits[indexed_commits_nr++] = commit; 137} 138 139static void *get_delta(struct object_entry *entry) 140{ 141 unsigned long size, base_size, delta_size; 142 void *buf, *base_buf, *delta_buf; 143 enum object_type type; 144 145 buf = read_object_file(&entry->idx.oid, &type, &size); 146 if (!buf) 147 die("unable to read %s", oid_to_hex(&entry->idx.oid)); 148 base_buf = read_object_file(&DELTA(entry)->idx.oid, &type, 149 &base_size); 150 if (!base_buf) 151 die("unable to read %s", 152 oid_to_hex(&DELTA(entry)->idx.oid)); 153 delta_buf = diff_delta(base_buf, base_size, 154 buf, size, &delta_size, 0); 155 if (!delta_buf || delta_size != DELTA_SIZE(entry)) 156 die("delta size changed"); 157 free(buf); 158 free(base_buf); 159 return delta_buf; 160} 161 162static unsigned long do_compress(void **pptr, unsigned long size) 163{ 164 git_zstream stream; 165 void *in, *out; 166 unsigned long maxsize; 167 168 git_deflate_init(&stream, pack_compression_level); 169 maxsize = git_deflate_bound(&stream, size); 170 171 in = *pptr; 172 out = xmalloc(maxsize); 173 *pptr = out; 174 175 stream.next_in = in; 176 stream.avail_in = size; 177 stream.next_out = out; 178 stream.avail_out = maxsize; 179 while (git_deflate(&stream, Z_FINISH) == Z_OK) 180 ; /* nothing */ 181 git_deflate_end(&stream); 182 183 free(in); 184 return stream.total_out; 185} 186 187static unsigned long write_large_blob_data(struct git_istream *st, struct hashfile *f, 188 const struct object_id *oid) 189{ 190 git_zstream stream; 191 unsigned char ibuf[1024 * 16]; 192 unsigned char obuf[1024 * 16]; 193 unsigned long olen = 0; 194 195 git_deflate_init(&stream, pack_compression_level); 196 197 for (;;) { 198 ssize_t readlen; 199 int zret = Z_OK; 200 readlen = read_istream(st, ibuf, sizeof(ibuf)); 201 if (readlen == -1) 202 die(_("unable to read %s"), oid_to_hex(oid)); 203 204 stream.next_in = ibuf; 205 stream.avail_in = readlen; 206 while ((stream.avail_in || readlen == 0) && 207 (zret == Z_OK || zret == Z_BUF_ERROR)) { 208 stream.next_out = obuf; 209 stream.avail_out = sizeof(obuf); 210 zret = git_deflate(&stream, readlen ? 0 : Z_FINISH); 211 hashwrite(f, obuf, stream.next_out - obuf); 212 olen += stream.next_out - obuf; 213 } 214 if (stream.avail_in) 215 die(_("deflate error (%d)"), zret); 216 if (readlen == 0) { 217 if (zret != Z_STREAM_END) 218 die(_("deflate error (%d)"), zret); 219 break; 220 } 221 } 222 git_deflate_end(&stream); 223 return olen; 224} 225 226/* 227 * we are going to reuse the existing object data as is. make 228 * sure it is not corrupt. 229 */ 230static int check_pack_inflate(struct packed_git *p, 231 struct pack_window **w_curs, 232 off_t offset, 233 off_t len, 234 unsigned long expect) 235{ 236 git_zstream stream; 237 unsigned char fakebuf[4096], *in; 238 int st; 239 240 memset(&stream, 0, sizeof(stream)); 241 git_inflate_init(&stream); 242 do { 243 in = use_pack(p, w_curs, offset, &stream.avail_in); 244 stream.next_in = in; 245 stream.next_out = fakebuf; 246 stream.avail_out = sizeof(fakebuf); 247 st = git_inflate(&stream, Z_FINISH); 248 offset += stream.next_in - in; 249 } while (st == Z_OK || st == Z_BUF_ERROR); 250 git_inflate_end(&stream); 251 return (st == Z_STREAM_END && 252 stream.total_out == expect && 253 stream.total_in == len) ? 0 : -1; 254} 255 256static void copy_pack_data(struct hashfile *f, 257 struct packed_git *p, 258 struct pack_window **w_curs, 259 off_t offset, 260 off_t len) 261{ 262 unsigned char *in; 263 unsigned long avail; 264 265 while (len) { 266 in = use_pack(p, w_curs, offset, &avail); 267 if (avail > len) 268 avail = (unsigned long)len; 269 hashwrite(f, in, avail); 270 offset += avail; 271 len -= avail; 272 } 273} 274 275/* Return 0 if we will bust the pack-size limit */ 276static unsigned long write_no_reuse_object(struct hashfile *f, struct object_entry *entry, 277 unsigned long limit, int usable_delta) 278{ 279 unsigned long size, datalen; 280 unsigned char header[MAX_PACK_OBJECT_HEADER], 281 dheader[MAX_PACK_OBJECT_HEADER]; 282 unsigned hdrlen; 283 enum object_type type; 284 void *buf; 285 struct git_istream *st = NULL; 286 const unsigned hashsz = the_hash_algo->rawsz; 287 288 if (!usable_delta) { 289 if (oe_type(entry) == OBJ_BLOB && 290 oe_size_greater_than(&to_pack, entry, big_file_threshold) && 291 (st = open_istream(&entry->idx.oid, &type, &size, NULL)) != NULL) 292 buf = NULL; 293 else { 294 buf = read_object_file(&entry->idx.oid, &type, &size); 295 if (!buf) 296 die(_("unable to read %s"), 297 oid_to_hex(&entry->idx.oid)); 298 } 299 /* 300 * make sure no cached delta data remains from a 301 * previous attempt before a pack split occurred. 302 */ 303 FREE_AND_NULL(entry->delta_data); 304 entry->z_delta_size = 0; 305 } else if (entry->delta_data) { 306 size = DELTA_SIZE(entry); 307 buf = entry->delta_data; 308 entry->delta_data = NULL; 309 type = (allow_ofs_delta && DELTA(entry)->idx.offset) ? 310 OBJ_OFS_DELTA : OBJ_REF_DELTA; 311 } else { 312 buf = get_delta(entry); 313 size = DELTA_SIZE(entry); 314 type = (allow_ofs_delta && DELTA(entry)->idx.offset) ? 315 OBJ_OFS_DELTA : OBJ_REF_DELTA; 316 } 317 318 if (st) /* large blob case, just assume we don't compress well */ 319 datalen = size; 320 else if (entry->z_delta_size) 321 datalen = entry->z_delta_size; 322 else 323 datalen = do_compress(&buf, size); 324 325 /* 326 * The object header is a byte of 'type' followed by zero or 327 * more bytes of length. 328 */ 329 hdrlen = encode_in_pack_object_header(header, sizeof(header), 330 type, size); 331 332 if (type == OBJ_OFS_DELTA) { 333 /* 334 * Deltas with relative base contain an additional 335 * encoding of the relative offset for the delta 336 * base from this object's position in the pack. 337 */ 338 off_t ofs = entry->idx.offset - DELTA(entry)->idx.offset; 339 unsigned pos = sizeof(dheader) - 1; 340 dheader[pos] = ofs & 127; 341 while (ofs >>= 7) 342 dheader[--pos] = 128 | (--ofs & 127); 343 if (limit && hdrlen + sizeof(dheader) - pos + datalen + hashsz >= limit) { 344 if (st) 345 close_istream(st); 346 free(buf); 347 return 0; 348 } 349 hashwrite(f, header, hdrlen); 350 hashwrite(f, dheader + pos, sizeof(dheader) - pos); 351 hdrlen += sizeof(dheader) - pos; 352 } else if (type == OBJ_REF_DELTA) { 353 /* 354 * Deltas with a base reference contain 355 * additional bytes for the base object ID. 356 */ 357 if (limit && hdrlen + hashsz + datalen + hashsz >= limit) { 358 if (st) 359 close_istream(st); 360 free(buf); 361 return 0; 362 } 363 hashwrite(f, header, hdrlen); 364 hashwrite(f, DELTA(entry)->idx.oid.hash, hashsz); 365 hdrlen += hashsz; 366 } else { 367 if (limit && hdrlen + datalen + hashsz >= limit) { 368 if (st) 369 close_istream(st); 370 free(buf); 371 return 0; 372 } 373 hashwrite(f, header, hdrlen); 374 } 375 if (st) { 376 datalen = write_large_blob_data(st, f, &entry->idx.oid); 377 close_istream(st); 378 } else { 379 hashwrite(f, buf, datalen); 380 free(buf); 381 } 382 383 return hdrlen + datalen; 384} 385 386/* Return 0 if we will bust the pack-size limit */ 387static off_t write_reuse_object(struct hashfile *f, struct object_entry *entry, 388 unsigned long limit, int usable_delta) 389{ 390 struct packed_git *p = IN_PACK(entry); 391 struct pack_window *w_curs = NULL; 392 struct revindex_entry *revidx; 393 off_t offset; 394 enum object_type type = oe_type(entry); 395 off_t datalen; 396 unsigned char header[MAX_PACK_OBJECT_HEADER], 397 dheader[MAX_PACK_OBJECT_HEADER]; 398 unsigned hdrlen; 399 const unsigned hashsz = the_hash_algo->rawsz; 400 unsigned long entry_size = SIZE(entry); 401 402 if (DELTA(entry)) 403 type = (allow_ofs_delta && DELTA(entry)->idx.offset) ? 404 OBJ_OFS_DELTA : OBJ_REF_DELTA; 405 hdrlen = encode_in_pack_object_header(header, sizeof(header), 406 type, entry_size); 407 408 offset = entry->in_pack_offset; 409 revidx = find_pack_revindex(p, offset); 410 datalen = revidx[1].offset - offset; 411 if (!pack_to_stdout && p->index_version > 1 && 412 check_pack_crc(p, &w_curs, offset, datalen, revidx->nr)) { 413 error("bad packed object CRC for %s", 414 oid_to_hex(&entry->idx.oid)); 415 unuse_pack(&w_curs); 416 return write_no_reuse_object(f, entry, limit, usable_delta); 417 } 418 419 offset += entry->in_pack_header_size; 420 datalen -= entry->in_pack_header_size; 421 422 if (!pack_to_stdout && p->index_version == 1 && 423 check_pack_inflate(p, &w_curs, offset, datalen, entry_size)) { 424 error("corrupt packed object for %s", 425 oid_to_hex(&entry->idx.oid)); 426 unuse_pack(&w_curs); 427 return write_no_reuse_object(f, entry, limit, usable_delta); 428 } 429 430 if (type == OBJ_OFS_DELTA) { 431 off_t ofs = entry->idx.offset - DELTA(entry)->idx.offset; 432 unsigned pos = sizeof(dheader) - 1; 433 dheader[pos] = ofs & 127; 434 while (ofs >>= 7) 435 dheader[--pos] = 128 | (--ofs & 127); 436 if (limit && hdrlen + sizeof(dheader) - pos + datalen + hashsz >= limit) { 437 unuse_pack(&w_curs); 438 return 0; 439 } 440 hashwrite(f, header, hdrlen); 441 hashwrite(f, dheader + pos, sizeof(dheader) - pos); 442 hdrlen += sizeof(dheader) - pos; 443 reused_delta++; 444 } else if (type == OBJ_REF_DELTA) { 445 if (limit && hdrlen + hashsz + datalen + hashsz >= limit) { 446 unuse_pack(&w_curs); 447 return 0; 448 } 449 hashwrite(f, header, hdrlen); 450 hashwrite(f, DELTA(entry)->idx.oid.hash, hashsz); 451 hdrlen += hashsz; 452 reused_delta++; 453 } else { 454 if (limit && hdrlen + datalen + hashsz >= limit) { 455 unuse_pack(&w_curs); 456 return 0; 457 } 458 hashwrite(f, header, hdrlen); 459 } 460 copy_pack_data(f, p, &w_curs, offset, datalen); 461 unuse_pack(&w_curs); 462 reused++; 463 return hdrlen + datalen; 464} 465 466/* Return 0 if we will bust the pack-size limit */ 467static off_t write_object(struct hashfile *f, 468 struct object_entry *entry, 469 off_t write_offset) 470{ 471 unsigned long limit; 472 off_t len; 473 int usable_delta, to_reuse; 474 475 if (!pack_to_stdout) 476 crc32_begin(f); 477 478 /* apply size limit if limited packsize and not first object */ 479 if (!pack_size_limit || !nr_written) 480 limit = 0; 481 else if (pack_size_limit <= write_offset) 482 /* 483 * the earlier object did not fit the limit; avoid 484 * mistaking this with unlimited (i.e. limit = 0). 485 */ 486 limit = 1; 487 else 488 limit = pack_size_limit - write_offset; 489 490 if (!DELTA(entry)) 491 usable_delta = 0; /* no delta */ 492 else if (!pack_size_limit) 493 usable_delta = 1; /* unlimited packfile */ 494 else if (DELTA(entry)->idx.offset == (off_t)-1) 495 usable_delta = 0; /* base was written to another pack */ 496 else if (DELTA(entry)->idx.offset) 497 usable_delta = 1; /* base already exists in this pack */ 498 else 499 usable_delta = 0; /* base could end up in another pack */ 500 501 if (!reuse_object) 502 to_reuse = 0; /* explicit */ 503 else if (!IN_PACK(entry)) 504 to_reuse = 0; /* can't reuse what we don't have */ 505 else if (oe_type(entry) == OBJ_REF_DELTA || 506 oe_type(entry) == OBJ_OFS_DELTA) 507 /* check_object() decided it for us ... */ 508 to_reuse = usable_delta; 509 /* ... but pack split may override that */ 510 else if (oe_type(entry) != entry->in_pack_type) 511 to_reuse = 0; /* pack has delta which is unusable */ 512 else if (DELTA(entry)) 513 to_reuse = 0; /* we want to pack afresh */ 514 else 515 to_reuse = 1; /* we have it in-pack undeltified, 516 * and we do not need to deltify it. 517 */ 518 519 if (!to_reuse) 520 len = write_no_reuse_object(f, entry, limit, usable_delta); 521 else 522 len = write_reuse_object(f, entry, limit, usable_delta); 523 if (!len) 524 return 0; 525 526 if (usable_delta) 527 written_delta++; 528 written++; 529 if (!pack_to_stdout) 530 entry->idx.crc32 = crc32_end(f); 531 return len; 532} 533 534enum write_one_status { 535 WRITE_ONE_SKIP = -1, /* already written */ 536 WRITE_ONE_BREAK = 0, /* writing this will bust the limit; not written */ 537 WRITE_ONE_WRITTEN = 1, /* normal */ 538 WRITE_ONE_RECURSIVE = 2 /* already scheduled to be written */ 539}; 540 541static enum write_one_status write_one(struct hashfile *f, 542 struct object_entry *e, 543 off_t *offset) 544{ 545 off_t size; 546 int recursing; 547 548 /* 549 * we set offset to 1 (which is an impossible value) to mark 550 * the fact that this object is involved in "write its base 551 * first before writing a deltified object" recursion. 552 */ 553 recursing = (e->idx.offset == 1); 554 if (recursing) { 555 warning("recursive delta detected for object %s", 556 oid_to_hex(&e->idx.oid)); 557 return WRITE_ONE_RECURSIVE; 558 } else if (e->idx.offset || e->preferred_base) { 559 /* offset is non zero if object is written already. */ 560 return WRITE_ONE_SKIP; 561 } 562 563 /* if we are deltified, write out base object first. */ 564 if (DELTA(e)) { 565 e->idx.offset = 1; /* now recurse */ 566 switch (write_one(f, DELTA(e), offset)) { 567 case WRITE_ONE_RECURSIVE: 568 /* we cannot depend on this one */ 569 SET_DELTA(e, NULL); 570 break; 571 default: 572 break; 573 case WRITE_ONE_BREAK: 574 e->idx.offset = recursing; 575 return WRITE_ONE_BREAK; 576 } 577 } 578 579 e->idx.offset = *offset; 580 size = write_object(f, e, *offset); 581 if (!size) { 582 e->idx.offset = recursing; 583 return WRITE_ONE_BREAK; 584 } 585 written_list[nr_written++] = &e->idx; 586 587 /* make sure off_t is sufficiently large not to wrap */ 588 if (signed_add_overflows(*offset, size)) 589 die("pack too large for current definition of off_t"); 590 *offset += size; 591 return WRITE_ONE_WRITTEN; 592} 593 594static int mark_tagged(const char *path, const struct object_id *oid, int flag, 595 void *cb_data) 596{ 597 struct object_id peeled; 598 struct object_entry *entry = packlist_find(&to_pack, oid->hash, NULL); 599 600 if (entry) 601 entry->tagged = 1; 602 if (!peel_ref(path, &peeled)) { 603 entry = packlist_find(&to_pack, peeled.hash, NULL); 604 if (entry) 605 entry->tagged = 1; 606 } 607 return 0; 608} 609 610static inline void add_to_write_order(struct object_entry **wo, 611 unsigned int *endp, 612 struct object_entry *e) 613{ 614 if (e->filled || e->layer != write_layer) 615 return; 616 wo[(*endp)++] = e; 617 e->filled = 1; 618} 619 620static void add_descendants_to_write_order(struct object_entry **wo, 621 unsigned int *endp, 622 struct object_entry *e) 623{ 624 int add_to_order = 1; 625 while (e) { 626 if (add_to_order) { 627 struct object_entry *s; 628 /* add this node... */ 629 add_to_write_order(wo, endp, e); 630 /* all its siblings... */ 631 for (s = DELTA_SIBLING(e); s; s = DELTA_SIBLING(s)) { 632 add_to_write_order(wo, endp, s); 633 } 634 } 635 /* drop down a level to add left subtree nodes if possible */ 636 if (DELTA_CHILD(e)) { 637 add_to_order = 1; 638 e = DELTA_CHILD(e); 639 } else { 640 add_to_order = 0; 641 /* our sibling might have some children, it is next */ 642 if (DELTA_SIBLING(e)) { 643 e = DELTA_SIBLING(e); 644 continue; 645 } 646 /* go back to our parent node */ 647 e = DELTA(e); 648 while (e && !DELTA_SIBLING(e)) { 649 /* we're on the right side of a subtree, keep 650 * going up until we can go right again */ 651 e = DELTA(e); 652 } 653 if (!e) { 654 /* done- we hit our original root node */ 655 return; 656 } 657 /* pass it off to sibling at this level */ 658 e = DELTA_SIBLING(e); 659 } 660 }; 661} 662 663static void add_family_to_write_order(struct object_entry **wo, 664 unsigned int *endp, 665 struct object_entry *e) 666{ 667 struct object_entry *root; 668 669 for (root = e; DELTA(root); root = DELTA(root)) 670 ; /* nothing */ 671 add_descendants_to_write_order(wo, endp, root); 672} 673 674static void compute_layer_order(struct object_entry **wo, unsigned int *wo_end) 675{ 676 unsigned int i, last_untagged; 677 struct object_entry *objects = to_pack.objects; 678 679 for (i = 0; i < to_pack.nr_objects; i++) { 680 if (objects[i].tagged) 681 break; 682 add_to_write_order(wo, wo_end, &objects[i]); 683 } 684 last_untagged = i; 685 686 /* 687 * Then fill all the tagged tips. 688 */ 689 for (; i < to_pack.nr_objects; i++) { 690 if (objects[i].tagged) 691 add_to_write_order(wo, wo_end, &objects[i]); 692 } 693 694 /* 695 * And then all remaining commits and tags. 696 */ 697 for (i = last_untagged; i < to_pack.nr_objects; i++) { 698 if (oe_type(&objects[i]) != OBJ_COMMIT && 699 oe_type(&objects[i]) != OBJ_TAG) 700 continue; 701 add_to_write_order(wo, wo_end, &objects[i]); 702 } 703 704 /* 705 * And then all the trees. 706 */ 707 for (i = last_untagged; i < to_pack.nr_objects; i++) { 708 if (oe_type(&objects[i]) != OBJ_TREE) 709 continue; 710 add_to_write_order(wo, wo_end, &objects[i]); 711 } 712 713 /* 714 * Finally all the rest in really tight order 715 */ 716 for (i = last_untagged; i < to_pack.nr_objects; i++) { 717 if (!objects[i].filled && objects[i].layer == write_layer) 718 add_family_to_write_order(wo, wo_end, &objects[i]); 719 } 720} 721 722static struct object_entry **compute_write_order(void) 723{ 724 uint32_t max_layers = 1; 725 unsigned int i, wo_end; 726 727 struct object_entry **wo; 728 struct object_entry *objects = to_pack.objects; 729 730 for (i = 0; i < to_pack.nr_objects; i++) { 731 objects[i].tagged = 0; 732 objects[i].filled = 0; 733 SET_DELTA_CHILD(&objects[i], NULL); 734 SET_DELTA_SIBLING(&objects[i], NULL); 735 } 736 737 /* 738 * Fully connect delta_child/delta_sibling network. 739 * Make sure delta_sibling is sorted in the original 740 * recency order. 741 */ 742 for (i = to_pack.nr_objects; i > 0;) { 743 struct object_entry *e = &objects[--i]; 744 if (!DELTA(e)) 745 continue; 746 /* Mark me as the first child */ 747 e->delta_sibling_idx = DELTA(e)->delta_child_idx; 748 SET_DELTA_CHILD(DELTA(e), e); 749 } 750 751 /* 752 * Mark objects that are at the tip of tags. 753 */ 754 for_each_tag_ref(mark_tagged, NULL); 755 756 if (use_delta_islands) 757 max_layers = compute_pack_layers(&to_pack); 758 759 ALLOC_ARRAY(wo, to_pack.nr_objects); 760 wo_end = 0; 761 762 for (; write_layer < max_layers; ++write_layer) 763 compute_layer_order(wo, &wo_end); 764 765 if (wo_end != to_pack.nr_objects) 766 die("ordered %u objects, expected %"PRIu32, wo_end, to_pack.nr_objects); 767 768 return wo; 769} 770 771static off_t write_reused_pack(struct hashfile *f) 772{ 773 unsigned char buffer[8192]; 774 off_t to_write, total; 775 int fd; 776 777 if (!is_pack_valid(reuse_packfile)) 778 die("packfile is invalid: %s", reuse_packfile->pack_name); 779 780 fd = git_open(reuse_packfile->pack_name); 781 if (fd < 0) 782 die_errno("unable to open packfile for reuse: %s", 783 reuse_packfile->pack_name); 784 785 if (lseek(fd, sizeof(struct pack_header), SEEK_SET) == -1) 786 die_errno("unable to seek in reused packfile"); 787 788 if (reuse_packfile_offset < 0) 789 reuse_packfile_offset = reuse_packfile->pack_size - the_hash_algo->rawsz; 790 791 total = to_write = reuse_packfile_offset - sizeof(struct pack_header); 792 793 while (to_write) { 794 int read_pack = xread(fd, buffer, sizeof(buffer)); 795 796 if (read_pack <= 0) 797 die_errno("unable to read from reused packfile"); 798 799 if (read_pack > to_write) 800 read_pack = to_write; 801 802 hashwrite(f, buffer, read_pack); 803 to_write -= read_pack; 804 805 /* 806 * We don't know the actual number of objects written, 807 * only how many bytes written, how many bytes total, and 808 * how many objects total. So we can fake it by pretending all 809 * objects we are writing are the same size. This gives us a 810 * smooth progress meter, and at the end it matches the true 811 * answer. 812 */ 813 written = reuse_packfile_objects * 814 (((double)(total - to_write)) / total); 815 display_progress(progress_state, written); 816 } 817 818 close(fd); 819 written = reuse_packfile_objects; 820 display_progress(progress_state, written); 821 return reuse_packfile_offset - sizeof(struct pack_header); 822} 823 824static const char no_split_warning[] = N_( 825"disabling bitmap writing, packs are split due to pack.packSizeLimit" 826); 827 828static void write_pack_file(void) 829{ 830 uint32_t i = 0, j; 831 struct hashfile *f; 832 off_t offset; 833 uint32_t nr_remaining = nr_result; 834 time_t last_mtime = 0; 835 struct object_entry **write_order; 836 837 if (progress > pack_to_stdout) 838 progress_state = start_progress(_("Writing objects"), nr_result); 839 ALLOC_ARRAY(written_list, to_pack.nr_objects); 840 write_order = compute_write_order(); 841 842 do { 843 struct object_id oid; 844 char *pack_tmp_name = NULL; 845 846 if (pack_to_stdout) 847 f = hashfd_throughput(1, "<stdout>", progress_state); 848 else 849 f = create_tmp_packfile(&pack_tmp_name); 850 851 offset = write_pack_header(f, nr_remaining); 852 853 if (reuse_packfile) { 854 off_t packfile_size; 855 assert(pack_to_stdout); 856 857 packfile_size = write_reused_pack(f); 858 offset += packfile_size; 859 } 860 861 nr_written = 0; 862 for (; i < to_pack.nr_objects; i++) { 863 struct object_entry *e = write_order[i]; 864 if (write_one(f, e, &offset) == WRITE_ONE_BREAK) 865 break; 866 display_progress(progress_state, written); 867 } 868 869 /* 870 * Did we write the wrong # entries in the header? 871 * If so, rewrite it like in fast-import 872 */ 873 if (pack_to_stdout) { 874 finalize_hashfile(f, oid.hash, CSUM_HASH_IN_STREAM | CSUM_CLOSE); 875 } else if (nr_written == nr_remaining) { 876 finalize_hashfile(f, oid.hash, CSUM_HASH_IN_STREAM | CSUM_FSYNC | CSUM_CLOSE); 877 } else { 878 int fd = finalize_hashfile(f, oid.hash, 0); 879 fixup_pack_header_footer(fd, oid.hash, pack_tmp_name, 880 nr_written, oid.hash, offset); 881 close(fd); 882 if (write_bitmap_index) { 883 warning(_(no_split_warning)); 884 write_bitmap_index = 0; 885 } 886 } 887 888 if (!pack_to_stdout) { 889 struct stat st; 890 struct strbuf tmpname = STRBUF_INIT; 891 892 /* 893 * Packs are runtime accessed in their mtime 894 * order since newer packs are more likely to contain 895 * younger objects. So if we are creating multiple 896 * packs then we should modify the mtime of later ones 897 * to preserve this property. 898 */ 899 if (stat(pack_tmp_name, &st) < 0) { 900 warning_errno("failed to stat %s", pack_tmp_name); 901 } else if (!last_mtime) { 902 last_mtime = st.st_mtime; 903 } else { 904 struct utimbuf utb; 905 utb.actime = st.st_atime; 906 utb.modtime = --last_mtime; 907 if (utime(pack_tmp_name, &utb) < 0) 908 warning_errno("failed utime() on %s", pack_tmp_name); 909 } 910 911 strbuf_addf(&tmpname, "%s-", base_name); 912 913 if (write_bitmap_index) { 914 bitmap_writer_set_checksum(oid.hash); 915 bitmap_writer_build_type_index( 916 &to_pack, written_list, nr_written); 917 } 918 919 finish_tmp_packfile(&tmpname, pack_tmp_name, 920 written_list, nr_written, 921 &pack_idx_opts, oid.hash); 922 923 if (write_bitmap_index) { 924 strbuf_addf(&tmpname, "%s.bitmap", oid_to_hex(&oid)); 925 926 stop_progress(&progress_state); 927 928 bitmap_writer_show_progress(progress); 929 bitmap_writer_reuse_bitmaps(&to_pack); 930 bitmap_writer_select_commits(indexed_commits, indexed_commits_nr, -1); 931 bitmap_writer_build(&to_pack); 932 bitmap_writer_finish(written_list, nr_written, 933 tmpname.buf, write_bitmap_options); 934 write_bitmap_index = 0; 935 } 936 937 strbuf_release(&tmpname); 938 free(pack_tmp_name); 939 puts(oid_to_hex(&oid)); 940 } 941 942 /* mark written objects as written to previous pack */ 943 for (j = 0; j < nr_written; j++) { 944 written_list[j]->offset = (off_t)-1; 945 } 946 nr_remaining -= nr_written; 947 } while (nr_remaining && i < to_pack.nr_objects); 948 949 free(written_list); 950 free(write_order); 951 stop_progress(&progress_state); 952 if (written != nr_result) 953 die("wrote %"PRIu32" objects while expecting %"PRIu32, 954 written, nr_result); 955} 956 957static int no_try_delta(const char *path) 958{ 959 static struct attr_check *check; 960 961 if (!check) 962 check = attr_check_initl("delta", NULL); 963 if (git_check_attr(path, check)) 964 return 0; 965 if (ATTR_FALSE(check->items[0].value)) 966 return 1; 967 return 0; 968} 969 970/* 971 * When adding an object, check whether we have already added it 972 * to our packing list. If so, we can skip. However, if we are 973 * being asked to excludei t, but the previous mention was to include 974 * it, make sure to adjust its flags and tweak our numbers accordingly. 975 * 976 * As an optimization, we pass out the index position where we would have 977 * found the item, since that saves us from having to look it up again a 978 * few lines later when we want to add the new entry. 979 */ 980static int have_duplicate_entry(const struct object_id *oid, 981 int exclude, 982 uint32_t *index_pos) 983{ 984 struct object_entry *entry; 985 986 entry = packlist_find(&to_pack, oid->hash, index_pos); 987 if (!entry) 988 return 0; 989 990 if (exclude) { 991 if (!entry->preferred_base) 992 nr_result--; 993 entry->preferred_base = 1; 994 } 995 996 return 1; 997} 998 999static int want_found_object(int exclude, struct packed_git *p)1000{1001 if (exclude)1002 return 1;1003 if (incremental)1004 return 0;10051006 /*1007 * When asked to do --local (do not include an object that appears in a1008 * pack we borrow from elsewhere) or --honor-pack-keep (do not include1009 * an object that appears in a pack marked with .keep), finding a pack1010 * that matches the criteria is sufficient for us to decide to omit it.1011 * However, even if this pack does not satisfy the criteria, we need to1012 * make sure no copy of this object appears in _any_ pack that makes us1013 * to omit the object, so we need to check all the packs.1014 *1015 * We can however first check whether these options can possible matter;1016 * if they do not matter we know we want the object in generated pack.1017 * Otherwise, we signal "-1" at the end to tell the caller that we do1018 * not know either way, and it needs to check more packs.1019 */1020 if (!ignore_packed_keep_on_disk &&1021 !ignore_packed_keep_in_core &&1022 (!local || !have_non_local_packs))1023 return 1;10241025 if (local && !p->pack_local)1026 return 0;1027 if (p->pack_local &&1028 ((ignore_packed_keep_on_disk && p->pack_keep) ||1029 (ignore_packed_keep_in_core && p->pack_keep_in_core)))1030 return 0;10311032 /* we don't know yet; keep looking for more packs */1033 return -1;1034}10351036/*1037 * Check whether we want the object in the pack (e.g., we do not want1038 * objects found in non-local stores if the "--local" option was used).1039 *1040 * If the caller already knows an existing pack it wants to take the object1041 * from, that is passed in *found_pack and *found_offset; otherwise this1042 * function finds if there is any pack that has the object and returns the pack1043 * and its offset in these variables.1044 */1045static int want_object_in_pack(const struct object_id *oid,1046 int exclude,1047 struct packed_git **found_pack,1048 off_t *found_offset)1049{1050 int want;1051 struct list_head *pos;10521053 if (!exclude && local && has_loose_object_nonlocal(oid))1054 return 0;10551056 /*1057 * If we already know the pack object lives in, start checks from that1058 * pack - in the usual case when neither --local was given nor .keep files1059 * are present we will determine the answer right now.1060 */1061 if (*found_pack) {1062 want = want_found_object(exclude, *found_pack);1063 if (want != -1)1064 return want;1065 }1066 list_for_each(pos, get_packed_git_mru(the_repository)) {1067 struct packed_git *p = list_entry(pos, struct packed_git, mru);1068 off_t offset;10691070 if (p == *found_pack)1071 offset = *found_offset;1072 else1073 offset = find_pack_entry_one(oid->hash, p);10741075 if (offset) {1076 if (!*found_pack) {1077 if (!is_pack_valid(p))1078 continue;1079 *found_offset = offset;1080 *found_pack = p;1081 }1082 want = want_found_object(exclude, p);1083 if (!exclude && want > 0)1084 list_move(&p->mru,1085 get_packed_git_mru(the_repository));1086 if (want != -1)1087 return want;1088 }1089 }10901091 return 1;1092}10931094static void create_object_entry(const struct object_id *oid,1095 enum object_type type,1096 uint32_t hash,1097 int exclude,1098 int no_try_delta,1099 uint32_t index_pos,1100 struct packed_git *found_pack,1101 off_t found_offset)1102{1103 struct object_entry *entry;11041105 entry = packlist_alloc(&to_pack, oid->hash, index_pos);1106 entry->hash = hash;1107 oe_set_type(entry, type);1108 if (exclude)1109 entry->preferred_base = 1;1110 else1111 nr_result++;1112 if (found_pack) {1113 oe_set_in_pack(&to_pack, entry, found_pack);1114 entry->in_pack_offset = found_offset;1115 }11161117 entry->no_try_delta = no_try_delta;1118}11191120static const char no_closure_warning[] = N_(1121"disabling bitmap writing, as some objects are not being packed"1122);11231124static int add_object_entry(const struct object_id *oid, enum object_type type,1125 const char *name, int exclude)1126{1127 struct packed_git *found_pack = NULL;1128 off_t found_offset = 0;1129 uint32_t index_pos;11301131 display_progress(progress_state, ++nr_seen);11321133 if (have_duplicate_entry(oid, exclude, &index_pos))1134 return 0;11351136 if (!want_object_in_pack(oid, exclude, &found_pack, &found_offset)) {1137 /* The pack is missing an object, so it will not have closure */1138 if (write_bitmap_index) {1139 warning(_(no_closure_warning));1140 write_bitmap_index = 0;1141 }1142 return 0;1143 }11441145 create_object_entry(oid, type, pack_name_hash(name),1146 exclude, name && no_try_delta(name),1147 index_pos, found_pack, found_offset);1148 return 1;1149}11501151static int add_object_entry_from_bitmap(const struct object_id *oid,1152 enum object_type type,1153 int flags, uint32_t name_hash,1154 struct packed_git *pack, off_t offset)1155{1156 uint32_t index_pos;11571158 display_progress(progress_state, ++nr_seen);11591160 if (have_duplicate_entry(oid, 0, &index_pos))1161 return 0;11621163 if (!want_object_in_pack(oid, 0, &pack, &offset))1164 return 0;11651166 create_object_entry(oid, type, name_hash, 0, 0, index_pos, pack, offset);1167 return 1;1168}11691170struct pbase_tree_cache {1171 struct object_id oid;1172 int ref;1173 int temporary;1174 void *tree_data;1175 unsigned long tree_size;1176};11771178static struct pbase_tree_cache *(pbase_tree_cache[256]);1179static int pbase_tree_cache_ix(const struct object_id *oid)1180{1181 return oid->hash[0] % ARRAY_SIZE(pbase_tree_cache);1182}1183static int pbase_tree_cache_ix_incr(int ix)1184{1185 return (ix+1) % ARRAY_SIZE(pbase_tree_cache);1186}11871188static struct pbase_tree {1189 struct pbase_tree *next;1190 /* This is a phony "cache" entry; we are not1191 * going to evict it or find it through _get()1192 * mechanism -- this is for the toplevel node that1193 * would almost always change with any commit.1194 */1195 struct pbase_tree_cache pcache;1196} *pbase_tree;11971198static struct pbase_tree_cache *pbase_tree_get(const struct object_id *oid)1199{1200 struct pbase_tree_cache *ent, *nent;1201 void *data;1202 unsigned long size;1203 enum object_type type;1204 int neigh;1205 int my_ix = pbase_tree_cache_ix(oid);1206 int available_ix = -1;12071208 /* pbase-tree-cache acts as a limited hashtable.1209 * your object will be found at your index or within a few1210 * slots after that slot if it is cached.1211 */1212 for (neigh = 0; neigh < 8; neigh++) {1213 ent = pbase_tree_cache[my_ix];1214 if (ent && !oidcmp(&ent->oid, oid)) {1215 ent->ref++;1216 return ent;1217 }1218 else if (((available_ix < 0) && (!ent || !ent->ref)) ||1219 ((0 <= available_ix) &&1220 (!ent && pbase_tree_cache[available_ix])))1221 available_ix = my_ix;1222 if (!ent)1223 break;1224 my_ix = pbase_tree_cache_ix_incr(my_ix);1225 }12261227 /* Did not find one. Either we got a bogus request or1228 * we need to read and perhaps cache.1229 */1230 data = read_object_file(oid, &type, &size);1231 if (!data)1232 return NULL;1233 if (type != OBJ_TREE) {1234 free(data);1235 return NULL;1236 }12371238 /* We need to either cache or return a throwaway copy */12391240 if (available_ix < 0)1241 ent = NULL;1242 else {1243 ent = pbase_tree_cache[available_ix];1244 my_ix = available_ix;1245 }12461247 if (!ent) {1248 nent = xmalloc(sizeof(*nent));1249 nent->temporary = (available_ix < 0);1250 }1251 else {1252 /* evict and reuse */1253 free(ent->tree_data);1254 nent = ent;1255 }1256 oidcpy(&nent->oid, oid);1257 nent->tree_data = data;1258 nent->tree_size = size;1259 nent->ref = 1;1260 if (!nent->temporary)1261 pbase_tree_cache[my_ix] = nent;1262 return nent;1263}12641265static void pbase_tree_put(struct pbase_tree_cache *cache)1266{1267 if (!cache->temporary) {1268 cache->ref--;1269 return;1270 }1271 free(cache->tree_data);1272 free(cache);1273}12741275static int name_cmp_len(const char *name)1276{1277 int i;1278 for (i = 0; name[i] && name[i] != '\n' && name[i] != '/'; i++)1279 ;1280 return i;1281}12821283static void add_pbase_object(struct tree_desc *tree,1284 const char *name,1285 int cmplen,1286 const char *fullname)1287{1288 struct name_entry entry;1289 int cmp;12901291 while (tree_entry(tree,&entry)) {1292 if (S_ISGITLINK(entry.mode))1293 continue;1294 cmp = tree_entry_len(&entry) != cmplen ? 1 :1295 memcmp(name, entry.path, cmplen);1296 if (cmp > 0)1297 continue;1298 if (cmp < 0)1299 return;1300 if (name[cmplen] != '/') {1301 add_object_entry(entry.oid,1302 object_type(entry.mode),1303 fullname, 1);1304 return;1305 }1306 if (S_ISDIR(entry.mode)) {1307 struct tree_desc sub;1308 struct pbase_tree_cache *tree;1309 const char *down = name+cmplen+1;1310 int downlen = name_cmp_len(down);13111312 tree = pbase_tree_get(entry.oid);1313 if (!tree)1314 return;1315 init_tree_desc(&sub, tree->tree_data, tree->tree_size);13161317 add_pbase_object(&sub, down, downlen, fullname);1318 pbase_tree_put(tree);1319 }1320 }1321}13221323static unsigned *done_pbase_paths;1324static int done_pbase_paths_num;1325static int done_pbase_paths_alloc;1326static int done_pbase_path_pos(unsigned hash)1327{1328 int lo = 0;1329 int hi = done_pbase_paths_num;1330 while (lo < hi) {1331 int mi = lo + (hi - lo) / 2;1332 if (done_pbase_paths[mi] == hash)1333 return mi;1334 if (done_pbase_paths[mi] < hash)1335 hi = mi;1336 else1337 lo = mi + 1;1338 }1339 return -lo-1;1340}13411342static int check_pbase_path(unsigned hash)1343{1344 int pos = done_pbase_path_pos(hash);1345 if (0 <= pos)1346 return 1;1347 pos = -pos - 1;1348 ALLOC_GROW(done_pbase_paths,1349 done_pbase_paths_num + 1,1350 done_pbase_paths_alloc);1351 done_pbase_paths_num++;1352 if (pos < done_pbase_paths_num)1353 MOVE_ARRAY(done_pbase_paths + pos + 1, done_pbase_paths + pos,1354 done_pbase_paths_num - pos - 1);1355 done_pbase_paths[pos] = hash;1356 return 0;1357}13581359static void add_preferred_base_object(const char *name)1360{1361 struct pbase_tree *it;1362 int cmplen;1363 unsigned hash = pack_name_hash(name);13641365 if (!num_preferred_base || check_pbase_path(hash))1366 return;13671368 cmplen = name_cmp_len(name);1369 for (it = pbase_tree; it; it = it->next) {1370 if (cmplen == 0) {1371 add_object_entry(&it->pcache.oid, OBJ_TREE, NULL, 1);1372 }1373 else {1374 struct tree_desc tree;1375 init_tree_desc(&tree, it->pcache.tree_data, it->pcache.tree_size);1376 add_pbase_object(&tree, name, cmplen, name);1377 }1378 }1379}13801381static void add_preferred_base(struct object_id *oid)1382{1383 struct pbase_tree *it;1384 void *data;1385 unsigned long size;1386 struct object_id tree_oid;13871388 if (window <= num_preferred_base++)1389 return;13901391 data = read_object_with_reference(oid, tree_type, &size, &tree_oid);1392 if (!data)1393 return;13941395 for (it = pbase_tree; it; it = it->next) {1396 if (!oidcmp(&it->pcache.oid, &tree_oid)) {1397 free(data);1398 return;1399 }1400 }14011402 it = xcalloc(1, sizeof(*it));1403 it->next = pbase_tree;1404 pbase_tree = it;14051406 oidcpy(&it->pcache.oid, &tree_oid);1407 it->pcache.tree_data = data;1408 it->pcache.tree_size = size;1409}14101411static void cleanup_preferred_base(void)1412{1413 struct pbase_tree *it;1414 unsigned i;14151416 it = pbase_tree;1417 pbase_tree = NULL;1418 while (it) {1419 struct pbase_tree *tmp = it;1420 it = tmp->next;1421 free(tmp->pcache.tree_data);1422 free(tmp);1423 }14241425 for (i = 0; i < ARRAY_SIZE(pbase_tree_cache); i++) {1426 if (!pbase_tree_cache[i])1427 continue;1428 free(pbase_tree_cache[i]->tree_data);1429 FREE_AND_NULL(pbase_tree_cache[i]);1430 }14311432 FREE_AND_NULL(done_pbase_paths);1433 done_pbase_paths_num = done_pbase_paths_alloc = 0;1434}14351436static void check_object(struct object_entry *entry)1437{1438 unsigned long canonical_size;14391440 if (IN_PACK(entry)) {1441 struct packed_git *p = IN_PACK(entry);1442 struct pack_window *w_curs = NULL;1443 const unsigned char *base_ref = NULL;1444 struct object_entry *base_entry;1445 unsigned long used, used_0;1446 unsigned long avail;1447 off_t ofs;1448 unsigned char *buf, c;1449 enum object_type type;1450 unsigned long in_pack_size;14511452 buf = use_pack(p, &w_curs, entry->in_pack_offset, &avail);14531454 /*1455 * We want in_pack_type even if we do not reuse delta1456 * since non-delta representations could still be reused.1457 */1458 used = unpack_object_header_buffer(buf, avail,1459 &type,1460 &in_pack_size);1461 if (used == 0)1462 goto give_up;14631464 if (type < 0)1465 BUG("invalid type %d", type);1466 entry->in_pack_type = type;14671468 /*1469 * Determine if this is a delta and if so whether we can1470 * reuse it or not. Otherwise let's find out as cheaply as1471 * possible what the actual type and size for this object is.1472 */1473 switch (entry->in_pack_type) {1474 default:1475 /* Not a delta hence we've already got all we need. */1476 oe_set_type(entry, entry->in_pack_type);1477 SET_SIZE(entry, in_pack_size);1478 entry->in_pack_header_size = used;1479 if (oe_type(entry) < OBJ_COMMIT || oe_type(entry) > OBJ_BLOB)1480 goto give_up;1481 unuse_pack(&w_curs);1482 return;1483 case OBJ_REF_DELTA:1484 if (reuse_delta && !entry->preferred_base)1485 base_ref = use_pack(p, &w_curs,1486 entry->in_pack_offset + used, NULL);1487 entry->in_pack_header_size = used + the_hash_algo->rawsz;1488 break;1489 case OBJ_OFS_DELTA:1490 buf = use_pack(p, &w_curs,1491 entry->in_pack_offset + used, NULL);1492 used_0 = 0;1493 c = buf[used_0++];1494 ofs = c & 127;1495 while (c & 128) {1496 ofs += 1;1497 if (!ofs || MSB(ofs, 7)) {1498 error("delta base offset overflow in pack for %s",1499 oid_to_hex(&entry->idx.oid));1500 goto give_up;1501 }1502 c = buf[used_0++];1503 ofs = (ofs << 7) + (c & 127);1504 }1505 ofs = entry->in_pack_offset - ofs;1506 if (ofs <= 0 || ofs >= entry->in_pack_offset) {1507 error("delta base offset out of bound for %s",1508 oid_to_hex(&entry->idx.oid));1509 goto give_up;1510 }1511 if (reuse_delta && !entry->preferred_base) {1512 struct revindex_entry *revidx;1513 revidx = find_pack_revindex(p, ofs);1514 if (!revidx)1515 goto give_up;1516 base_ref = nth_packed_object_sha1(p, revidx->nr);1517 }1518 entry->in_pack_header_size = used + used_0;1519 break;1520 }15211522 if (base_ref && (base_entry = packlist_find(&to_pack, base_ref, NULL)) &&1523 in_same_island(&entry->idx.oid, &base_entry->idx.oid)) {1524 /*1525 * If base_ref was set above that means we wish to1526 * reuse delta data, and we even found that base1527 * in the list of objects we want to pack. Goodie!1528 *1529 * Depth value does not matter - find_deltas() will1530 * never consider reused delta as the base object to1531 * deltify other objects against, in order to avoid1532 * circular deltas.1533 */1534 oe_set_type(entry, entry->in_pack_type);1535 SET_SIZE(entry, in_pack_size); /* delta size */1536 SET_DELTA(entry, base_entry);1537 SET_DELTA_SIZE(entry, in_pack_size);1538 entry->delta_sibling_idx = base_entry->delta_child_idx;1539 SET_DELTA_CHILD(base_entry, entry);1540 unuse_pack(&w_curs);1541 return;1542 }15431544 if (oe_type(entry)) {1545 off_t delta_pos;15461547 /*1548 * This must be a delta and we already know what the1549 * final object type is. Let's extract the actual1550 * object size from the delta header.1551 */1552 delta_pos = entry->in_pack_offset + entry->in_pack_header_size;1553 canonical_size = get_size_from_delta(p, &w_curs, delta_pos);1554 if (canonical_size == 0)1555 goto give_up;1556 SET_SIZE(entry, canonical_size);1557 unuse_pack(&w_curs);1558 return;1559 }15601561 /*1562 * No choice but to fall back to the recursive delta walk1563 * with sha1_object_info() to find about the object type1564 * at this point...1565 */1566 give_up:1567 unuse_pack(&w_curs);1568 }15691570 oe_set_type(entry,1571 oid_object_info(the_repository, &entry->idx.oid, &canonical_size));1572 if (entry->type_valid) {1573 SET_SIZE(entry, canonical_size);1574 } else {1575 /*1576 * Bad object type is checked in prepare_pack(). This is1577 * to permit a missing preferred base object to be ignored1578 * as a preferred base. Doing so can result in a larger1579 * pack file, but the transfer will still take place.1580 */1581 }1582}15831584static int pack_offset_sort(const void *_a, const void *_b)1585{1586 const struct object_entry *a = *(struct object_entry **)_a;1587 const struct object_entry *b = *(struct object_entry **)_b;1588 const struct packed_git *a_in_pack = IN_PACK(a);1589 const struct packed_git *b_in_pack = IN_PACK(b);15901591 /* avoid filesystem trashing with loose objects */1592 if (!a_in_pack && !b_in_pack)1593 return oidcmp(&a->idx.oid, &b->idx.oid);15941595 if (a_in_pack < b_in_pack)1596 return -1;1597 if (a_in_pack > b_in_pack)1598 return 1;1599 return a->in_pack_offset < b->in_pack_offset ? -1 :1600 (a->in_pack_offset > b->in_pack_offset);1601}16021603/*1604 * Drop an on-disk delta we were planning to reuse. Naively, this would1605 * just involve blanking out the "delta" field, but we have to deal1606 * with some extra book-keeping:1607 *1608 * 1. Removing ourselves from the delta_sibling linked list.1609 *1610 * 2. Updating our size/type to the non-delta representation. These were1611 * either not recorded initially (size) or overwritten with the delta type1612 * (type) when check_object() decided to reuse the delta.1613 *1614 * 3. Resetting our delta depth, as we are now a base object.1615 */1616static void drop_reused_delta(struct object_entry *entry)1617{1618 unsigned *idx = &to_pack.objects[entry->delta_idx - 1].delta_child_idx;1619 struct object_info oi = OBJECT_INFO_INIT;1620 enum object_type type;1621 unsigned long size;16221623 while (*idx) {1624 struct object_entry *oe = &to_pack.objects[*idx - 1];16251626 if (oe == entry)1627 *idx = oe->delta_sibling_idx;1628 else1629 idx = &oe->delta_sibling_idx;1630 }1631 SET_DELTA(entry, NULL);1632 entry->depth = 0;16331634 oi.sizep = &size;1635 oi.typep = &type;1636 if (packed_object_info(the_repository, IN_PACK(entry), entry->in_pack_offset, &oi) < 0) {1637 /*1638 * We failed to get the info from this pack for some reason;1639 * fall back to sha1_object_info, which may find another copy.1640 * And if that fails, the error will be recorded in oe_type(entry)1641 * and dealt with in prepare_pack().1642 */1643 oe_set_type(entry,1644 oid_object_info(the_repository, &entry->idx.oid, &size));1645 } else {1646 oe_set_type(entry, type);1647 }1648 SET_SIZE(entry, size);1649}16501651/*1652 * Follow the chain of deltas from this entry onward, throwing away any links1653 * that cause us to hit a cycle (as determined by the DFS state flags in1654 * the entries).1655 *1656 * We also detect too-long reused chains that would violate our --depth1657 * limit.1658 */1659static void break_delta_chains(struct object_entry *entry)1660{1661 /*1662 * The actual depth of each object we will write is stored as an int,1663 * as it cannot exceed our int "depth" limit. But before we break1664 * changes based no that limit, we may potentially go as deep as the1665 * number of objects, which is elsewhere bounded to a uint32_t.1666 */1667 uint32_t total_depth;1668 struct object_entry *cur, *next;16691670 for (cur = entry, total_depth = 0;1671 cur;1672 cur = DELTA(cur), total_depth++) {1673 if (cur->dfs_state == DFS_DONE) {1674 /*1675 * We've already seen this object and know it isn't1676 * part of a cycle. We do need to append its depth1677 * to our count.1678 */1679 total_depth += cur->depth;1680 break;1681 }16821683 /*1684 * We break cycles before looping, so an ACTIVE state (or any1685 * other cruft which made its way into the state variable)1686 * is a bug.1687 */1688 if (cur->dfs_state != DFS_NONE)1689 BUG("confusing delta dfs state in first pass: %d",1690 cur->dfs_state);16911692 /*1693 * Now we know this is the first time we've seen the object. If1694 * it's not a delta, we're done traversing, but we'll mark it1695 * done to save time on future traversals.1696 */1697 if (!DELTA(cur)) {1698 cur->dfs_state = DFS_DONE;1699 break;1700 }17011702 /*1703 * Mark ourselves as active and see if the next step causes1704 * us to cycle to another active object. It's important to do1705 * this _before_ we loop, because it impacts where we make the1706 * cut, and thus how our total_depth counter works.1707 * E.g., We may see a partial loop like:1708 *1709 * A -> B -> C -> D -> B1710 *1711 * Cutting B->C breaks the cycle. But now the depth of A is1712 * only 1, and our total_depth counter is at 3. The size of the1713 * error is always one less than the size of the cycle we1714 * broke. Commits C and D were "lost" from A's chain.1715 *1716 * If we instead cut D->B, then the depth of A is correct at 3.1717 * We keep all commits in the chain that we examined.1718 */1719 cur->dfs_state = DFS_ACTIVE;1720 if (DELTA(cur)->dfs_state == DFS_ACTIVE) {1721 drop_reused_delta(cur);1722 cur->dfs_state = DFS_DONE;1723 break;1724 }1725 }17261727 /*1728 * And now that we've gone all the way to the bottom of the chain, we1729 * need to clear the active flags and set the depth fields as1730 * appropriate. Unlike the loop above, which can quit when it drops a1731 * delta, we need to keep going to look for more depth cuts. So we need1732 * an extra "next" pointer to keep going after we reset cur->delta.1733 */1734 for (cur = entry; cur; cur = next) {1735 next = DELTA(cur);17361737 /*1738 * We should have a chain of zero or more ACTIVE states down to1739 * a final DONE. We can quit after the DONE, because either it1740 * has no bases, or we've already handled them in a previous1741 * call.1742 */1743 if (cur->dfs_state == DFS_DONE)1744 break;1745 else if (cur->dfs_state != DFS_ACTIVE)1746 BUG("confusing delta dfs state in second pass: %d",1747 cur->dfs_state);17481749 /*1750 * If the total_depth is more than depth, then we need to snip1751 * the chain into two or more smaller chains that don't exceed1752 * the maximum depth. Most of the resulting chains will contain1753 * (depth + 1) entries (i.e., depth deltas plus one base), and1754 * the last chain (i.e., the one containing entry) will contain1755 * whatever entries are left over, namely1756 * (total_depth % (depth + 1)) of them.1757 *1758 * Since we are iterating towards decreasing depth, we need to1759 * decrement total_depth as we go, and we need to write to the1760 * entry what its final depth will be after all of the1761 * snipping. Since we're snipping into chains of length (depth1762 * + 1) entries, the final depth of an entry will be its1763 * original depth modulo (depth + 1). Any time we encounter an1764 * entry whose final depth is supposed to be zero, we snip it1765 * from its delta base, thereby making it so.1766 */1767 cur->depth = (total_depth--) % (depth + 1);1768 if (!cur->depth)1769 drop_reused_delta(cur);17701771 cur->dfs_state = DFS_DONE;1772 }1773}17741775static void get_object_details(void)1776{1777 uint32_t i;1778 struct object_entry **sorted_by_offset;17791780 if (progress)1781 progress_state = start_progress(_("Counting objects"),1782 to_pack.nr_objects);17831784 sorted_by_offset = xcalloc(to_pack.nr_objects, sizeof(struct object_entry *));1785 for (i = 0; i < to_pack.nr_objects; i++)1786 sorted_by_offset[i] = to_pack.objects + i;1787 QSORT(sorted_by_offset, to_pack.nr_objects, pack_offset_sort);17881789 for (i = 0; i < to_pack.nr_objects; i++) {1790 struct object_entry *entry = sorted_by_offset[i];1791 check_object(entry);1792 if (entry->type_valid &&1793 oe_size_greater_than(&to_pack, entry, big_file_threshold))1794 entry->no_try_delta = 1;1795 display_progress(progress_state, i + 1);1796 }1797 stop_progress(&progress_state);17981799 /*1800 * This must happen in a second pass, since we rely on the delta1801 * information for the whole list being completed.1802 */1803 for (i = 0; i < to_pack.nr_objects; i++)1804 break_delta_chains(&to_pack.objects[i]);18051806 free(sorted_by_offset);1807}18081809/*1810 * We search for deltas in a list sorted by type, by filename hash, and then1811 * by size, so that we see progressively smaller and smaller files.1812 * That's because we prefer deltas to be from the bigger file1813 * to the smaller -- deletes are potentially cheaper, but perhaps1814 * more importantly, the bigger file is likely the more recent1815 * one. The deepest deltas are therefore the oldest objects which are1816 * less susceptible to be accessed often.1817 */1818static int type_size_sort(const void *_a, const void *_b)1819{1820 const struct object_entry *a = *(struct object_entry **)_a;1821 const struct object_entry *b = *(struct object_entry **)_b;1822 enum object_type a_type = oe_type(a);1823 enum object_type b_type = oe_type(b);1824 unsigned long a_size = SIZE(a);1825 unsigned long b_size = SIZE(b);18261827 if (a_type > b_type)1828 return -1;1829 if (a_type < b_type)1830 return 1;1831 if (a->hash > b->hash)1832 return -1;1833 if (a->hash < b->hash)1834 return 1;1835 if (a->preferred_base > b->preferred_base)1836 return -1;1837 if (a->preferred_base < b->preferred_base)1838 return 1;1839 if (use_delta_islands) {1840 int island_cmp = island_delta_cmp(&a->idx.oid, &b->idx.oid);1841 if (island_cmp)1842 return island_cmp;1843 }1844 if (a_size > b_size)1845 return -1;1846 if (a_size < b_size)1847 return 1;1848 return a < b ? -1 : (a > b); /* newest first */1849}18501851struct unpacked {1852 struct object_entry *entry;1853 void *data;1854 struct delta_index *index;1855 unsigned depth;1856};18571858static int delta_cacheable(unsigned long src_size, unsigned long trg_size,1859 unsigned long delta_size)1860{1861 if (max_delta_cache_size && delta_cache_size + delta_size > max_delta_cache_size)1862 return 0;18631864 if (delta_size < cache_max_small_delta_size)1865 return 1;18661867 /* cache delta, if objects are large enough compared to delta size */1868 if ((src_size >> 20) + (trg_size >> 21) > (delta_size >> 10))1869 return 1;18701871 return 0;1872}18731874#ifndef NO_PTHREADS18751876static pthread_mutex_t read_mutex;1877#define read_lock() pthread_mutex_lock(&read_mutex)1878#define read_unlock() pthread_mutex_unlock(&read_mutex)18791880static pthread_mutex_t cache_mutex;1881#define cache_lock() pthread_mutex_lock(&cache_mutex)1882#define cache_unlock() pthread_mutex_unlock(&cache_mutex)18831884static pthread_mutex_t progress_mutex;1885#define progress_lock() pthread_mutex_lock(&progress_mutex)1886#define progress_unlock() pthread_mutex_unlock(&progress_mutex)18871888#else18891890#define read_lock() (void)01891#define read_unlock() (void)01892#define cache_lock() (void)01893#define cache_unlock() (void)01894#define progress_lock() (void)01895#define progress_unlock() (void)018961897#endif18981899/*1900 * Return the size of the object without doing any delta1901 * reconstruction (so non-deltas are true object sizes, but deltas1902 * return the size of the delta data).1903 */1904unsigned long oe_get_size_slow(struct packing_data *pack,1905 const struct object_entry *e)1906{1907 struct packed_git *p;1908 struct pack_window *w_curs;1909 unsigned char *buf;1910 enum object_type type;1911 unsigned long used, avail, size;19121913 if (e->type_ != OBJ_OFS_DELTA && e->type_ != OBJ_REF_DELTA) {1914 read_lock();1915 if (oid_object_info(the_repository, &e->idx.oid, &size) < 0)1916 die(_("unable to get size of %s"),1917 oid_to_hex(&e->idx.oid));1918 read_unlock();1919 return size;1920 }19211922 p = oe_in_pack(pack, e);1923 if (!p)1924 BUG("when e->type is a delta, it must belong to a pack");19251926 read_lock();1927 w_curs = NULL;1928 buf = use_pack(p, &w_curs, e->in_pack_offset, &avail);1929 used = unpack_object_header_buffer(buf, avail, &type, &size);1930 if (used == 0)1931 die(_("unable to parse object header of %s"),1932 oid_to_hex(&e->idx.oid));19331934 unuse_pack(&w_curs);1935 read_unlock();1936 return size;1937}19381939static int try_delta(struct unpacked *trg, struct unpacked *src,1940 unsigned max_depth, unsigned long *mem_usage)1941{1942 struct object_entry *trg_entry = trg->entry;1943 struct object_entry *src_entry = src->entry;1944 unsigned long trg_size, src_size, delta_size, sizediff, max_size, sz;1945 unsigned ref_depth;1946 enum object_type type;1947 void *delta_buf;19481949 /* Don't bother doing diffs between different types */1950 if (oe_type(trg_entry) != oe_type(src_entry))1951 return -1;19521953 /*1954 * We do not bother to try a delta that we discarded on an1955 * earlier try, but only when reusing delta data. Note that1956 * src_entry that is marked as the preferred_base should always1957 * be considered, as even if we produce a suboptimal delta against1958 * it, we will still save the transfer cost, as we already know1959 * the other side has it and we won't send src_entry at all.1960 */1961 if (reuse_delta && IN_PACK(trg_entry) &&1962 IN_PACK(trg_entry) == IN_PACK(src_entry) &&1963 !src_entry->preferred_base &&1964 trg_entry->in_pack_type != OBJ_REF_DELTA &&1965 trg_entry->in_pack_type != OBJ_OFS_DELTA)1966 return 0;19671968 /* Let's not bust the allowed depth. */1969 if (src->depth >= max_depth)1970 return 0;19711972 /* Now some size filtering heuristics. */1973 trg_size = SIZE(trg_entry);1974 if (!DELTA(trg_entry)) {1975 max_size = trg_size/2 - the_hash_algo->rawsz;1976 ref_depth = 1;1977 } else {1978 max_size = DELTA_SIZE(trg_entry);1979 ref_depth = trg->depth;1980 }1981 max_size = (uint64_t)max_size * (max_depth - src->depth) /1982 (max_depth - ref_depth + 1);1983 if (max_size == 0)1984 return 0;1985 src_size = SIZE(src_entry);1986 sizediff = src_size < trg_size ? trg_size - src_size : 0;1987 if (sizediff >= max_size)1988 return 0;1989 if (trg_size < src_size / 32)1990 return 0;19911992 if (!in_same_island(&trg->entry->idx.oid, &src->entry->idx.oid))1993 return 0;19941995 /* Load data if not already done */1996 if (!trg->data) {1997 read_lock();1998 trg->data = read_object_file(&trg_entry->idx.oid, &type, &sz);1999 read_unlock();2000 if (!trg->data)2001 die("object %s cannot be read",2002 oid_to_hex(&trg_entry->idx.oid));2003 if (sz != trg_size)2004 die("object %s inconsistent object length (%lu vs %lu)",2005 oid_to_hex(&trg_entry->idx.oid), sz,2006 trg_size);2007 *mem_usage += sz;2008 }2009 if (!src->data) {2010 read_lock();2011 src->data = read_object_file(&src_entry->idx.oid, &type, &sz);2012 read_unlock();2013 if (!src->data) {2014 if (src_entry->preferred_base) {2015 static int warned = 0;2016 if (!warned++)2017 warning("object %s cannot be read",2018 oid_to_hex(&src_entry->idx.oid));2019 /*2020 * Those objects are not included in the2021 * resulting pack. Be resilient and ignore2022 * them if they can't be read, in case the2023 * pack could be created nevertheless.2024 */2025 return 0;2026 }2027 die("object %s cannot be read",2028 oid_to_hex(&src_entry->idx.oid));2029 }2030 if (sz != src_size)2031 die("object %s inconsistent object length (%lu vs %lu)",2032 oid_to_hex(&src_entry->idx.oid), sz,2033 src_size);2034 *mem_usage += sz;2035 }2036 if (!src->index) {2037 src->index = create_delta_index(src->data, src_size);2038 if (!src->index) {2039 static int warned = 0;2040 if (!warned++)2041 warning("suboptimal pack - out of memory");2042 return 0;2043 }2044 *mem_usage += sizeof_delta_index(src->index);2045 }20462047 delta_buf = create_delta(src->index, trg->data, trg_size, &delta_size, max_size);2048 if (!delta_buf)2049 return 0;2050 if (delta_size >= (1U << OE_DELTA_SIZE_BITS)) {2051 free(delta_buf);2052 return 0;2053 }20542055 if (DELTA(trg_entry)) {2056 /* Prefer only shallower same-sized deltas. */2057 if (delta_size == DELTA_SIZE(trg_entry) &&2058 src->depth + 1 >= trg->depth) {2059 free(delta_buf);2060 return 0;2061 }2062 }20632064 /*2065 * Handle memory allocation outside of the cache2066 * accounting lock. Compiler will optimize the strangeness2067 * away when NO_PTHREADS is defined.2068 */2069 free(trg_entry->delta_data);2070 cache_lock();2071 if (trg_entry->delta_data) {2072 delta_cache_size -= DELTA_SIZE(trg_entry);2073 trg_entry->delta_data = NULL;2074 }2075 if (delta_cacheable(src_size, trg_size, delta_size)) {2076 delta_cache_size += delta_size;2077 cache_unlock();2078 trg_entry->delta_data = xrealloc(delta_buf, delta_size);2079 } else {2080 cache_unlock();2081 free(delta_buf);2082 }20832084 SET_DELTA(trg_entry, src_entry);2085 SET_DELTA_SIZE(trg_entry, delta_size);2086 trg->depth = src->depth + 1;20872088 return 1;2089}20902091static unsigned int check_delta_limit(struct object_entry *me, unsigned int n)2092{2093 struct object_entry *child = DELTA_CHILD(me);2094 unsigned int m = n;2095 while (child) {2096 unsigned int c = check_delta_limit(child, n + 1);2097 if (m < c)2098 m = c;2099 child = DELTA_SIBLING(child);2100 }2101 return m;2102}21032104static unsigned long free_unpacked(struct unpacked *n)2105{2106 unsigned long freed_mem = sizeof_delta_index(n->index);2107 free_delta_index(n->index);2108 n->index = NULL;2109 if (n->data) {2110 freed_mem += SIZE(n->entry);2111 FREE_AND_NULL(n->data);2112 }2113 n->entry = NULL;2114 n->depth = 0;2115 return freed_mem;2116}21172118static void find_deltas(struct object_entry **list, unsigned *list_size,2119 int window, int depth, unsigned *processed)2120{2121 uint32_t i, idx = 0, count = 0;2122 struct unpacked *array;2123 unsigned long mem_usage = 0;21242125 array = xcalloc(window, sizeof(struct unpacked));21262127 for (;;) {2128 struct object_entry *entry;2129 struct unpacked *n = array + idx;2130 int j, max_depth, best_base = -1;21312132 progress_lock();2133 if (!*list_size) {2134 progress_unlock();2135 break;2136 }2137 entry = *list++;2138 (*list_size)--;2139 if (!entry->preferred_base) {2140 (*processed)++;2141 display_progress(progress_state, *processed);2142 }2143 progress_unlock();21442145 mem_usage -= free_unpacked(n);2146 n->entry = entry;21472148 while (window_memory_limit &&2149 mem_usage > window_memory_limit &&2150 count > 1) {2151 uint32_t tail = (idx + window - count) % window;2152 mem_usage -= free_unpacked(array + tail);2153 count--;2154 }21552156 /* We do not compute delta to *create* objects we are not2157 * going to pack.2158 */2159 if (entry->preferred_base)2160 goto next;21612162 /*2163 * If the current object is at pack edge, take the depth the2164 * objects that depend on the current object into account2165 * otherwise they would become too deep.2166 */2167 max_depth = depth;2168 if (DELTA_CHILD(entry)) {2169 max_depth -= check_delta_limit(entry, 0);2170 if (max_depth <= 0)2171 goto next;2172 }21732174 j = window;2175 while (--j > 0) {2176 int ret;2177 uint32_t other_idx = idx + j;2178 struct unpacked *m;2179 if (other_idx >= window)2180 other_idx -= window;2181 m = array + other_idx;2182 if (!m->entry)2183 break;2184 ret = try_delta(n, m, max_depth, &mem_usage);2185 if (ret < 0)2186 break;2187 else if (ret > 0)2188 best_base = other_idx;2189 }21902191 /*2192 * If we decided to cache the delta data, then it is best2193 * to compress it right away. First because we have to do2194 * it anyway, and doing it here while we're threaded will2195 * save a lot of time in the non threaded write phase,2196 * as well as allow for caching more deltas within2197 * the same cache size limit.2198 * ...2199 * But only if not writing to stdout, since in that case2200 * the network is most likely throttling writes anyway,2201 * and therefore it is best to go to the write phase ASAP2202 * instead, as we can afford spending more time compressing2203 * between writes at that moment.2204 */2205 if (entry->delta_data && !pack_to_stdout) {2206 unsigned long size;22072208 size = do_compress(&entry->delta_data, DELTA_SIZE(entry));2209 if (size < (1U << OE_Z_DELTA_BITS)) {2210 entry->z_delta_size = size;2211 cache_lock();2212 delta_cache_size -= DELTA_SIZE(entry);2213 delta_cache_size += entry->z_delta_size;2214 cache_unlock();2215 } else {2216 FREE_AND_NULL(entry->delta_data);2217 entry->z_delta_size = 0;2218 }2219 }22202221 /* if we made n a delta, and if n is already at max2222 * depth, leaving it in the window is pointless. we2223 * should evict it first.2224 */2225 if (DELTA(entry) && max_depth <= n->depth)2226 continue;22272228 /*2229 * Move the best delta base up in the window, after the2230 * currently deltified object, to keep it longer. It will2231 * be the first base object to be attempted next.2232 */2233 if (DELTA(entry)) {2234 struct unpacked swap = array[best_base];2235 int dist = (window + idx - best_base) % window;2236 int dst = best_base;2237 while (dist--) {2238 int src = (dst + 1) % window;2239 array[dst] = array[src];2240 dst = src;2241 }2242 array[dst] = swap;2243 }22442245 next:2246 idx++;2247 if (count + 1 < window)2248 count++;2249 if (idx >= window)2250 idx = 0;2251 }22522253 for (i = 0; i < window; ++i) {2254 free_delta_index(array[i].index);2255 free(array[i].data);2256 }2257 free(array);2258}22592260#ifndef NO_PTHREADS22612262static void try_to_free_from_threads(size_t size)2263{2264 read_lock();2265 release_pack_memory(size);2266 read_unlock();2267}22682269static try_to_free_t old_try_to_free_routine;22702271/*2272 * The main thread waits on the condition that (at least) one of the workers2273 * has stopped working (which is indicated in the .working member of2274 * struct thread_params).2275 * When a work thread has completed its work, it sets .working to 0 and2276 * signals the main thread and waits on the condition that .data_ready2277 * becomes 1.2278 */22792280struct thread_params {2281 pthread_t thread;2282 struct object_entry **list;2283 unsigned list_size;2284 unsigned remaining;2285 int window;2286 int depth;2287 int working;2288 int data_ready;2289 pthread_mutex_t mutex;2290 pthread_cond_t cond;2291 unsigned *processed;2292};22932294static pthread_cond_t progress_cond;22952296/*2297 * Mutex and conditional variable can't be statically-initialized on Windows.2298 */2299static void init_threaded_search(void)2300{2301 init_recursive_mutex(&read_mutex);2302 pthread_mutex_init(&cache_mutex, NULL);2303 pthread_mutex_init(&progress_mutex, NULL);2304 pthread_cond_init(&progress_cond, NULL);2305 old_try_to_free_routine = set_try_to_free_routine(try_to_free_from_threads);2306}23072308static void cleanup_threaded_search(void)2309{2310 set_try_to_free_routine(old_try_to_free_routine);2311 pthread_cond_destroy(&progress_cond);2312 pthread_mutex_destroy(&read_mutex);2313 pthread_mutex_destroy(&cache_mutex);2314 pthread_mutex_destroy(&progress_mutex);2315}23162317static void *threaded_find_deltas(void *arg)2318{2319 struct thread_params *me = arg;23202321 progress_lock();2322 while (me->remaining) {2323 progress_unlock();23242325 find_deltas(me->list, &me->remaining,2326 me->window, me->depth, me->processed);23272328 progress_lock();2329 me->working = 0;2330 pthread_cond_signal(&progress_cond);2331 progress_unlock();23322333 /*2334 * We must not set ->data_ready before we wait on the2335 * condition because the main thread may have set it to 12336 * before we get here. In order to be sure that new2337 * work is available if we see 1 in ->data_ready, it2338 * was initialized to 0 before this thread was spawned2339 * and we reset it to 0 right away.2340 */2341 pthread_mutex_lock(&me->mutex);2342 while (!me->data_ready)2343 pthread_cond_wait(&me->cond, &me->mutex);2344 me->data_ready = 0;2345 pthread_mutex_unlock(&me->mutex);23462347 progress_lock();2348 }2349 progress_unlock();2350 /* leave ->working 1 so that this doesn't get more work assigned */2351 return NULL;2352}23532354static void ll_find_deltas(struct object_entry **list, unsigned list_size,2355 int window, int depth, unsigned *processed)2356{2357 struct thread_params *p;2358 int i, ret, active_threads = 0;23592360 init_threaded_search();23612362 if (delta_search_threads <= 1) {2363 find_deltas(list, &list_size, window, depth, processed);2364 cleanup_threaded_search();2365 return;2366 }2367 if (progress > pack_to_stdout)2368 fprintf(stderr, "Delta compression using up to %d threads.\n",2369 delta_search_threads);2370 p = xcalloc(delta_search_threads, sizeof(*p));23712372 /* Partition the work amongst work threads. */2373 for (i = 0; i < delta_search_threads; i++) {2374 unsigned sub_size = list_size / (delta_search_threads - i);23752376 /* don't use too small segments or no deltas will be found */2377 if (sub_size < 2*window && i+1 < delta_search_threads)2378 sub_size = 0;23792380 p[i].window = window;2381 p[i].depth = depth;2382 p[i].processed = processed;2383 p[i].working = 1;2384 p[i].data_ready = 0;23852386 /* try to split chunks on "path" boundaries */2387 while (sub_size && sub_size < list_size &&2388 list[sub_size]->hash &&2389 list[sub_size]->hash == list[sub_size-1]->hash)2390 sub_size++;23912392 p[i].list = list;2393 p[i].list_size = sub_size;2394 p[i].remaining = sub_size;23952396 list += sub_size;2397 list_size -= sub_size;2398 }23992400 /* Start work threads. */2401 for (i = 0; i < delta_search_threads; i++) {2402 if (!p[i].list_size)2403 continue;2404 pthread_mutex_init(&p[i].mutex, NULL);2405 pthread_cond_init(&p[i].cond, NULL);2406 ret = pthread_create(&p[i].thread, NULL,2407 threaded_find_deltas, &p[i]);2408 if (ret)2409 die("unable to create thread: %s", strerror(ret));2410 active_threads++;2411 }24122413 /*2414 * Now let's wait for work completion. Each time a thread is done2415 * with its work, we steal half of the remaining work from the2416 * thread with the largest number of unprocessed objects and give2417 * it to that newly idle thread. This ensure good load balancing2418 * until the remaining object list segments are simply too short2419 * to be worth splitting anymore.2420 */2421 while (active_threads) {2422 struct thread_params *target = NULL;2423 struct thread_params *victim = NULL;2424 unsigned sub_size = 0;24252426 progress_lock();2427 for (;;) {2428 for (i = 0; !target && i < delta_search_threads; i++)2429 if (!p[i].working)2430 target = &p[i];2431 if (target)2432 break;2433 pthread_cond_wait(&progress_cond, &progress_mutex);2434 }24352436 for (i = 0; i < delta_search_threads; i++)2437 if (p[i].remaining > 2*window &&2438 (!victim || victim->remaining < p[i].remaining))2439 victim = &p[i];2440 if (victim) {2441 sub_size = victim->remaining / 2;2442 list = victim->list + victim->list_size - sub_size;2443 while (sub_size && list[0]->hash &&2444 list[0]->hash == list[-1]->hash) {2445 list++;2446 sub_size--;2447 }2448 if (!sub_size) {2449 /*2450 * It is possible for some "paths" to have2451 * so many objects that no hash boundary2452 * might be found. Let's just steal the2453 * exact half in that case.2454 */2455 sub_size = victim->remaining / 2;2456 list -= sub_size;2457 }2458 target->list = list;2459 victim->list_size -= sub_size;2460 victim->remaining -= sub_size;2461 }2462 target->list_size = sub_size;2463 target->remaining = sub_size;2464 target->working = 1;2465 progress_unlock();24662467 pthread_mutex_lock(&target->mutex);2468 target->data_ready = 1;2469 pthread_cond_signal(&target->cond);2470 pthread_mutex_unlock(&target->mutex);24712472 if (!sub_size) {2473 pthread_join(target->thread, NULL);2474 pthread_cond_destroy(&target->cond);2475 pthread_mutex_destroy(&target->mutex);2476 active_threads--;2477 }2478 }2479 cleanup_threaded_search();2480 free(p);2481}24822483#else2484#define ll_find_deltas(l, s, w, d, p) find_deltas(l, &s, w, d, p)2485#endif24862487static void add_tag_chain(const struct object_id *oid)2488{2489 struct tag *tag;24902491 /*2492 * We catch duplicates already in add_object_entry(), but we'd2493 * prefer to do this extra check to avoid having to parse the2494 * tag at all if we already know that it's being packed (e.g., if2495 * it was included via bitmaps, we would not have parsed it2496 * previously).2497 */2498 if (packlist_find(&to_pack, oid->hash, NULL))2499 return;25002501 tag = lookup_tag(the_repository, oid);2502 while (1) {2503 if (!tag || parse_tag(tag) || !tag->tagged)2504 die("unable to pack objects reachable from tag %s",2505 oid_to_hex(oid));25062507 add_object_entry(&tag->object.oid, OBJ_TAG, NULL, 0);25082509 if (tag->tagged->type != OBJ_TAG)2510 return;25112512 tag = (struct tag *)tag->tagged;2513 }2514}25152516static int add_ref_tag(const char *path, const struct object_id *oid, int flag, void *cb_data)2517{2518 struct object_id peeled;25192520 if (starts_with(path, "refs/tags/") && /* is a tag? */2521 !peel_ref(path, &peeled) && /* peelable? */2522 packlist_find(&to_pack, peeled.hash, NULL)) /* object packed? */2523 add_tag_chain(oid);2524 return 0;2525}25262527static void prepare_pack(int window, int depth)2528{2529 struct object_entry **delta_list;2530 uint32_t i, nr_deltas;2531 unsigned n;25322533 if (use_delta_islands)2534 resolve_tree_islands(progress, &to_pack);25352536 get_object_details();25372538 /*2539 * If we're locally repacking then we need to be doubly careful2540 * from now on in order to make sure no stealth corruption gets2541 * propagated to the new pack. Clients receiving streamed packs2542 * should validate everything they get anyway so no need to incur2543 * the additional cost here in that case.2544 */2545 if (!pack_to_stdout)2546 do_check_packed_object_crc = 1;25472548 if (!to_pack.nr_objects || !window || !depth)2549 return;25502551 ALLOC_ARRAY(delta_list, to_pack.nr_objects);2552 nr_deltas = n = 0;25532554 for (i = 0; i < to_pack.nr_objects; i++) {2555 struct object_entry *entry = to_pack.objects + i;25562557 if (DELTA(entry))2558 /* This happens if we decided to reuse existing2559 * delta from a pack. "reuse_delta &&" is implied.2560 */2561 continue;25622563 if (!entry->type_valid ||2564 oe_size_less_than(&to_pack, entry, 50))2565 continue;25662567 if (entry->no_try_delta)2568 continue;25692570 if (!entry->preferred_base) {2571 nr_deltas++;2572 if (oe_type(entry) < 0)2573 die("unable to get type of object %s",2574 oid_to_hex(&entry->idx.oid));2575 } else {2576 if (oe_type(entry) < 0) {2577 /*2578 * This object is not found, but we2579 * don't have to include it anyway.2580 */2581 continue;2582 }2583 }25842585 delta_list[n++] = entry;2586 }25872588 if (nr_deltas && n > 1) {2589 unsigned nr_done = 0;2590 if (progress)2591 progress_state = start_progress(_("Compressing objects"),2592 nr_deltas);2593 QSORT(delta_list, n, type_size_sort);2594 ll_find_deltas(delta_list, n, window+1, depth, &nr_done);2595 stop_progress(&progress_state);2596 if (nr_done != nr_deltas)2597 die("inconsistency with delta count");2598 }2599 free(delta_list);2600}26012602static int git_pack_config(const char *k, const char *v, void *cb)2603{2604 if (!strcmp(k, "pack.window")) {2605 window = git_config_int(k, v);2606 return 0;2607 }2608 if (!strcmp(k, "pack.windowmemory")) {2609 window_memory_limit = git_config_ulong(k, v);2610 return 0;2611 }2612 if (!strcmp(k, "pack.depth")) {2613 depth = git_config_int(k, v);2614 return 0;2615 }2616 if (!strcmp(k, "pack.deltacachesize")) {2617 max_delta_cache_size = git_config_int(k, v);2618 return 0;2619 }2620 if (!strcmp(k, "pack.deltacachelimit")) {2621 cache_max_small_delta_size = git_config_int(k, v);2622 return 0;2623 }2624 if (!strcmp(k, "pack.writebitmaphashcache")) {2625 if (git_config_bool(k, v))2626 write_bitmap_options |= BITMAP_OPT_HASH_CACHE;2627 else2628 write_bitmap_options &= ~BITMAP_OPT_HASH_CACHE;2629 }2630 if (!strcmp(k, "pack.usebitmaps")) {2631 use_bitmap_index_default = git_config_bool(k, v);2632 return 0;2633 }2634 if (!strcmp(k, "pack.threads")) {2635 delta_search_threads = git_config_int(k, v);2636 if (delta_search_threads < 0)2637 die("invalid number of threads specified (%d)",2638 delta_search_threads);2639#ifdef NO_PTHREADS2640 if (delta_search_threads != 1) {2641 warning("no threads support, ignoring %s", k);2642 delta_search_threads = 0;2643 }2644#endif2645 return 0;2646 }2647 if (!strcmp(k, "pack.indexversion")) {2648 pack_idx_opts.version = git_config_int(k, v);2649 if (pack_idx_opts.version > 2)2650 die("bad pack.indexversion=%"PRIu32,2651 pack_idx_opts.version);2652 return 0;2653 }2654 return git_default_config(k, v, cb);2655}26562657static void read_object_list_from_stdin(void)2658{2659 char line[GIT_MAX_HEXSZ + 1 + PATH_MAX + 2];2660 struct object_id oid;2661 const char *p;26622663 for (;;) {2664 if (!fgets(line, sizeof(line), stdin)) {2665 if (feof(stdin))2666 break;2667 if (!ferror(stdin))2668 die("fgets returned NULL, not EOF, not error!");2669 if (errno != EINTR)2670 die_errno("fgets");2671 clearerr(stdin);2672 continue;2673 }2674 if (line[0] == '-') {2675 if (get_oid_hex(line+1, &oid))2676 die("expected edge object ID, got garbage:\n %s",2677 line);2678 add_preferred_base(&oid);2679 continue;2680 }2681 if (parse_oid_hex(line, &oid, &p))2682 die("expected object ID, got garbage:\n %s", line);26832684 add_preferred_base_object(p + 1);2685 add_object_entry(&oid, OBJ_NONE, p + 1, 0);2686 }2687}26882689/* Remember to update object flag allocation in object.h */2690#define OBJECT_ADDED (1u<<20)26912692static void show_commit(struct commit *commit, void *data)2693{2694 add_object_entry(&commit->object.oid, OBJ_COMMIT, NULL, 0);2695 commit->object.flags |= OBJECT_ADDED;26962697 if (write_bitmap_index)2698 index_commit_for_bitmap(commit);26992700 if (use_delta_islands)2701 propagate_island_marks(commit);2702}27032704static void show_object(struct object *obj, const char *name, void *data)2705{2706 add_preferred_base_object(name);2707 add_object_entry(&obj->oid, obj->type, name, 0);2708 obj->flags |= OBJECT_ADDED;27092710 if (use_delta_islands) {2711 const char *p;2712 unsigned depth = 0;2713 struct object_entry *ent;27142715 for (p = strchr(name, '/'); p; p = strchr(p + 1, '/'))2716 depth++;27172718 ent = packlist_find(&to_pack, obj->oid.hash, NULL);2719 if (ent && depth > oe_tree_depth(&to_pack, ent))2720 oe_set_tree_depth(&to_pack, ent, depth);2721 }2722}27232724static void show_object__ma_allow_any(struct object *obj, const char *name, void *data)2725{2726 assert(arg_missing_action == MA_ALLOW_ANY);27272728 /*2729 * Quietly ignore ALL missing objects. This avoids problems with2730 * staging them now and getting an odd error later.2731 */2732 if (!has_object_file(&obj->oid))2733 return;27342735 show_object(obj, name, data);2736}27372738static void show_object__ma_allow_promisor(struct object *obj, const char *name, void *data)2739{2740 assert(arg_missing_action == MA_ALLOW_PROMISOR);27412742 /*2743 * Quietly ignore EXPECTED missing objects. This avoids problems with2744 * staging them now and getting an odd error later.2745 */2746 if (!has_object_file(&obj->oid) && is_promisor_object(&obj->oid))2747 return;27482749 show_object(obj, name, data);2750}27512752static int option_parse_missing_action(const struct option *opt,2753 const char *arg, int unset)2754{2755 assert(arg);2756 assert(!unset);27572758 if (!strcmp(arg, "error")) {2759 arg_missing_action = MA_ERROR;2760 fn_show_object = show_object;2761 return 0;2762 }27632764 if (!strcmp(arg, "allow-any")) {2765 arg_missing_action = MA_ALLOW_ANY;2766 fetch_if_missing = 0;2767 fn_show_object = show_object__ma_allow_any;2768 return 0;2769 }27702771 if (!strcmp(arg, "allow-promisor")) {2772 arg_missing_action = MA_ALLOW_PROMISOR;2773 fetch_if_missing = 0;2774 fn_show_object = show_object__ma_allow_promisor;2775 return 0;2776 }27772778 die(_("invalid value for --missing"));2779 return 0;2780}27812782static void show_edge(struct commit *commit)2783{2784 add_preferred_base(&commit->object.oid);2785}27862787struct in_pack_object {2788 off_t offset;2789 struct object *object;2790};27912792struct in_pack {2793 unsigned int alloc;2794 unsigned int nr;2795 struct in_pack_object *array;2796};27972798static void mark_in_pack_object(struct object *object, struct packed_git *p, struct in_pack *in_pack)2799{2800 in_pack->array[in_pack->nr].offset = find_pack_entry_one(object->oid.hash, p);2801 in_pack->array[in_pack->nr].object = object;2802 in_pack->nr++;2803}28042805/*2806 * Compare the objects in the offset order, in order to emulate the2807 * "git rev-list --objects" output that produced the pack originally.2808 */2809static int ofscmp(const void *a_, const void *b_)2810{2811 struct in_pack_object *a = (struct in_pack_object *)a_;2812 struct in_pack_object *b = (struct in_pack_object *)b_;28132814 if (a->offset < b->offset)2815 return -1;2816 else if (a->offset > b->offset)2817 return 1;2818 else2819 return oidcmp(&a->object->oid, &b->object->oid);2820}28212822static void add_objects_in_unpacked_packs(struct rev_info *revs)2823{2824 struct packed_git *p;2825 struct in_pack in_pack;2826 uint32_t i;28272828 memset(&in_pack, 0, sizeof(in_pack));28292830 for (p = get_packed_git(the_repository); p; p = p->next) {2831 struct object_id oid;2832 struct object *o;28332834 if (!p->pack_local || p->pack_keep || p->pack_keep_in_core)2835 continue;2836 if (open_pack_index(p))2837 die("cannot open pack index");28382839 ALLOC_GROW(in_pack.array,2840 in_pack.nr + p->num_objects,2841 in_pack.alloc);28422843 for (i = 0; i < p->num_objects; i++) {2844 nth_packed_object_oid(&oid, p, i);2845 o = lookup_unknown_object(oid.hash);2846 if (!(o->flags & OBJECT_ADDED))2847 mark_in_pack_object(o, p, &in_pack);2848 o->flags |= OBJECT_ADDED;2849 }2850 }28512852 if (in_pack.nr) {2853 QSORT(in_pack.array, in_pack.nr, ofscmp);2854 for (i = 0; i < in_pack.nr; i++) {2855 struct object *o = in_pack.array[i].object;2856 add_object_entry(&o->oid, o->type, "", 0);2857 }2858 }2859 free(in_pack.array);2860}28612862static int add_loose_object(const struct object_id *oid, const char *path,2863 void *data)2864{2865 enum object_type type = oid_object_info(the_repository, oid, NULL);28662867 if (type < 0) {2868 warning("loose object at %s could not be examined", path);2869 return 0;2870 }28712872 add_object_entry(oid, type, "", 0);2873 return 0;2874}28752876/*2877 * We actually don't even have to worry about reachability here.2878 * add_object_entry will weed out duplicates, so we just add every2879 * loose object we find.2880 */2881static void add_unreachable_loose_objects(void)2882{2883 for_each_loose_file_in_objdir(get_object_directory(),2884 add_loose_object,2885 NULL, NULL, NULL);2886}28872888static int has_sha1_pack_kept_or_nonlocal(const struct object_id *oid)2889{2890 static struct packed_git *last_found = (void *)1;2891 struct packed_git *p;28922893 p = (last_found != (void *)1) ? last_found :2894 get_packed_git(the_repository);28952896 while (p) {2897 if ((!p->pack_local || p->pack_keep ||2898 p->pack_keep_in_core) &&2899 find_pack_entry_one(oid->hash, p)) {2900 last_found = p;2901 return 1;2902 }2903 if (p == last_found)2904 p = get_packed_git(the_repository);2905 else2906 p = p->next;2907 if (p == last_found)2908 p = p->next;2909 }2910 return 0;2911}29122913/*2914 * Store a list of sha1s that are should not be discarded2915 * because they are either written too recently, or are2916 * reachable from another object that was.2917 *2918 * This is filled by get_object_list.2919 */2920static struct oid_array recent_objects;29212922static int loosened_object_can_be_discarded(const struct object_id *oid,2923 timestamp_t mtime)2924{2925 if (!unpack_unreachable_expiration)2926 return 0;2927 if (mtime > unpack_unreachable_expiration)2928 return 0;2929 if (oid_array_lookup(&recent_objects, oid) >= 0)2930 return 0;2931 return 1;2932}29332934static void loosen_unused_packed_objects(struct rev_info *revs)2935{2936 struct packed_git *p;2937 uint32_t i;2938 struct object_id oid;29392940 for (p = get_packed_git(the_repository); p; p = p->next) {2941 if (!p->pack_local || p->pack_keep || p->pack_keep_in_core)2942 continue;29432944 if (open_pack_index(p))2945 die("cannot open pack index");29462947 for (i = 0; i < p->num_objects; i++) {2948 nth_packed_object_oid(&oid, p, i);2949 if (!packlist_find(&to_pack, oid.hash, NULL) &&2950 !has_sha1_pack_kept_or_nonlocal(&oid) &&2951 !loosened_object_can_be_discarded(&oid, p->mtime))2952 if (force_object_loose(&oid, p->mtime))2953 die("unable to force loose object");2954 }2955 }2956}29572958/*2959 * This tracks any options which pack-reuse code expects to be on, or which a2960 * reader of the pack might not understand, and which would therefore prevent2961 * blind reuse of what we have on disk.2962 */2963static int pack_options_allow_reuse(void)2964{2965 return pack_to_stdout &&2966 allow_ofs_delta &&2967 !ignore_packed_keep_on_disk &&2968 !ignore_packed_keep_in_core &&2969 (!local || !have_non_local_packs) &&2970 !incremental;2971}29722973static int get_object_list_from_bitmap(struct rev_info *revs)2974{2975 struct bitmap_index *bitmap_git;2976 if (!(bitmap_git = prepare_bitmap_walk(revs)))2977 return -1;29782979 if (pack_options_allow_reuse() &&2980 !reuse_partial_packfile_from_bitmap(2981 bitmap_git,2982 &reuse_packfile,2983 &reuse_packfile_objects,2984 &reuse_packfile_offset)) {2985 assert(reuse_packfile_objects);2986 nr_result += reuse_packfile_objects;2987 display_progress(progress_state, nr_result);2988 }29892990 traverse_bitmap_commit_list(bitmap_git, &add_object_entry_from_bitmap);2991 free_bitmap_index(bitmap_git);2992 return 0;2993}29942995static void record_recent_object(struct object *obj,2996 const char *name,2997 void *data)2998{2999 oid_array_append(&recent_objects, &obj->oid);3000}30013002static void record_recent_commit(struct commit *commit, void *data)3003{3004 oid_array_append(&recent_objects, &commit->object.oid);3005}30063007static void get_object_list(int ac, const char **av)3008{3009 struct rev_info revs;3010 char line[1000];3011 int flags = 0;30123013 init_revisions(&revs, NULL);3014 save_commit_buffer = 0;3015 setup_revisions(ac, av, &revs, NULL);30163017 /* make sure shallows are read */3018 is_repository_shallow(the_repository);30193020 while (fgets(line, sizeof(line), stdin) != NULL) {3021 int len = strlen(line);3022 if (len && line[len - 1] == '\n')3023 line[--len] = 0;3024 if (!len)3025 break;3026 if (*line == '-') {3027 if (!strcmp(line, "--not")) {3028 flags ^= UNINTERESTING;3029 write_bitmap_index = 0;3030 continue;3031 }3032 if (starts_with(line, "--shallow ")) {3033 struct object_id oid;3034 if (get_oid_hex(line + 10, &oid))3035 die("not an SHA-1 '%s'", line + 10);3036 register_shallow(the_repository, &oid);3037 use_bitmap_index = 0;3038 continue;3039 }3040 die("not a rev '%s'", line);3041 }3042 if (handle_revision_arg(line, &revs, flags, REVARG_CANNOT_BE_FILENAME))3043 die("bad revision '%s'", line);3044 }30453046 if (use_bitmap_index && !get_object_list_from_bitmap(&revs))3047 return;30483049 if (use_delta_islands)3050 load_delta_islands();30513052 if (prepare_revision_walk(&revs))3053 die("revision walk setup failed");3054 mark_edges_uninteresting(&revs, show_edge);30553056 if (!fn_show_object)3057 fn_show_object = show_object;3058 traverse_commit_list_filtered(&filter_options, &revs,3059 show_commit, fn_show_object, NULL,3060 NULL);30613062 if (unpack_unreachable_expiration) {3063 revs.ignore_missing_links = 1;3064 if (add_unseen_recent_objects_to_traversal(&revs,3065 unpack_unreachable_expiration))3066 die("unable to add recent objects");3067 if (prepare_revision_walk(&revs))3068 die("revision walk setup failed");3069 traverse_commit_list(&revs, record_recent_commit,3070 record_recent_object, NULL);3071 }30723073 if (keep_unreachable)3074 add_objects_in_unpacked_packs(&revs);3075 if (pack_loose_unreachable)3076 add_unreachable_loose_objects();3077 if (unpack_unreachable)3078 loosen_unused_packed_objects(&revs);30793080 oid_array_clear(&recent_objects);3081}30823083static void add_extra_kept_packs(const struct string_list *names)3084{3085 struct packed_git *p;30863087 if (!names->nr)3088 return;30893090 for (p = get_packed_git(the_repository); p; p = p->next) {3091 const char *name = basename(p->pack_name);3092 int i;30933094 if (!p->pack_local)3095 continue;30963097 for (i = 0; i < names->nr; i++)3098 if (!fspathcmp(name, names->items[i].string))3099 break;31003101 if (i < names->nr) {3102 p->pack_keep_in_core = 1;3103 ignore_packed_keep_in_core = 1;3104 continue;3105 }3106 }3107}31083109static int option_parse_index_version(const struct option *opt,3110 const char *arg, int unset)3111{3112 char *c;3113 const char *val = arg;3114 pack_idx_opts.version = strtoul(val, &c, 10);3115 if (pack_idx_opts.version > 2)3116 die(_("unsupported index version %s"), val);3117 if (*c == ',' && c[1])3118 pack_idx_opts.off32_limit = strtoul(c+1, &c, 0);3119 if (*c || pack_idx_opts.off32_limit & 0x80000000)3120 die(_("bad index version '%s'"), val);3121 return 0;3122}31233124static int option_parse_unpack_unreachable(const struct option *opt,3125 const char *arg, int unset)3126{3127 if (unset) {3128 unpack_unreachable = 0;3129 unpack_unreachable_expiration = 0;3130 }3131 else {3132 unpack_unreachable = 1;3133 if (arg)3134 unpack_unreachable_expiration = approxidate(arg);3135 }3136 return 0;3137}31383139int cmd_pack_objects(int argc, const char **argv, const char *prefix)3140{3141 int use_internal_rev_list = 0;3142 int thin = 0;3143 int shallow = 0;3144 int all_progress_implied = 0;3145 struct argv_array rp = ARGV_ARRAY_INIT;3146 int rev_list_unpacked = 0, rev_list_all = 0, rev_list_reflog = 0;3147 int rev_list_index = 0;3148 struct string_list keep_pack_list = STRING_LIST_INIT_NODUP;3149 struct option pack_objects_options[] = {3150 OPT_SET_INT('q', "quiet", &progress,3151 N_("do not show progress meter"), 0),3152 OPT_SET_INT(0, "progress", &progress,3153 N_("show progress meter"), 1),3154 OPT_SET_INT(0, "all-progress", &progress,3155 N_("show progress meter during object writing phase"), 2),3156 OPT_BOOL(0, "all-progress-implied",3157 &all_progress_implied,3158 N_("similar to --all-progress when progress meter is shown")),3159 { OPTION_CALLBACK, 0, "index-version", NULL, N_("version[,offset]"),3160 N_("write the pack index file in the specified idx format version"),3161 0, option_parse_index_version },3162 OPT_MAGNITUDE(0, "max-pack-size", &pack_size_limit,3163 N_("maximum size of each output pack file")),3164 OPT_BOOL(0, "local", &local,3165 N_("ignore borrowed objects from alternate object store")),3166 OPT_BOOL(0, "incremental", &incremental,3167 N_("ignore packed objects")),3168 OPT_INTEGER(0, "window", &window,3169 N_("limit pack window by objects")),3170 OPT_MAGNITUDE(0, "window-memory", &window_memory_limit,3171 N_("limit pack window by memory in addition to object limit")),3172 OPT_INTEGER(0, "depth", &depth,3173 N_("maximum length of delta chain allowed in the resulting pack")),3174 OPT_BOOL(0, "reuse-delta", &reuse_delta,3175 N_("reuse existing deltas")),3176 OPT_BOOL(0, "reuse-object", &reuse_object,3177 N_("reuse existing objects")),3178 OPT_BOOL(0, "delta-base-offset", &allow_ofs_delta,3179 N_("use OFS_DELTA objects")),3180 OPT_INTEGER(0, "threads", &delta_search_threads,3181 N_("use threads when searching for best delta matches")),3182 OPT_BOOL(0, "non-empty", &non_empty,3183 N_("do not create an empty pack output")),3184 OPT_BOOL(0, "revs", &use_internal_rev_list,3185 N_("read revision arguments from standard input")),3186 OPT_SET_INT_F(0, "unpacked", &rev_list_unpacked,3187 N_("limit the objects to those that are not yet packed"),3188 1, PARSE_OPT_NONEG),3189 OPT_SET_INT_F(0, "all", &rev_list_all,3190 N_("include objects reachable from any reference"),3191 1, PARSE_OPT_NONEG),3192 OPT_SET_INT_F(0, "reflog", &rev_list_reflog,3193 N_("include objects referred by reflog entries"),3194 1, PARSE_OPT_NONEG),3195 OPT_SET_INT_F(0, "indexed-objects", &rev_list_index,3196 N_("include objects referred to by the index"),3197 1, PARSE_OPT_NONEG),3198 OPT_BOOL(0, "stdout", &pack_to_stdout,3199 N_("output pack to stdout")),3200 OPT_BOOL(0, "include-tag", &include_tag,3201 N_("include tag objects that refer to objects to be packed")),3202 OPT_BOOL(0, "keep-unreachable", &keep_unreachable,3203 N_("keep unreachable objects")),3204 OPT_BOOL(0, "pack-loose-unreachable", &pack_loose_unreachable,3205 N_("pack loose unreachable objects")),3206 { OPTION_CALLBACK, 0, "unpack-unreachable", NULL, N_("time"),3207 N_("unpack unreachable objects newer than <time>"),3208 PARSE_OPT_OPTARG, option_parse_unpack_unreachable },3209 OPT_BOOL(0, "thin", &thin,3210 N_("create thin packs")),3211 OPT_BOOL(0, "shallow", &shallow,3212 N_("create packs suitable for shallow fetches")),3213 OPT_BOOL(0, "honor-pack-keep", &ignore_packed_keep_on_disk,3214 N_("ignore packs that have companion .keep file")),3215 OPT_STRING_LIST(0, "keep-pack", &keep_pack_list, N_("name"),3216 N_("ignore this pack")),3217 OPT_INTEGER(0, "compression", &pack_compression_level,3218 N_("pack compression level")),3219 OPT_SET_INT(0, "keep-true-parents", &grafts_replace_parents,3220 N_("do not hide commits by grafts"), 0),3221 OPT_BOOL(0, "use-bitmap-index", &use_bitmap_index,3222 N_("use a bitmap index if available to speed up counting objects")),3223 OPT_BOOL(0, "write-bitmap-index", &write_bitmap_index,3224 N_("write a bitmap index together with the pack index")),3225 OPT_PARSE_LIST_OBJECTS_FILTER(&filter_options),3226 { OPTION_CALLBACK, 0, "missing", NULL, N_("action"),3227 N_("handling for missing objects"), PARSE_OPT_NONEG,3228 option_parse_missing_action },3229 OPT_BOOL(0, "exclude-promisor-objects", &exclude_promisor_objects,3230 N_("do not pack objects in promisor packfiles")),3231 OPT_BOOL(0, "delta-islands", &use_delta_islands,3232 N_("respect islands during delta compression")),3233 OPT_END(),3234 };32353236 if (DFS_NUM_STATES > (1 << OE_DFS_STATE_BITS))3237 BUG("too many dfs states, increase OE_DFS_STATE_BITS");32383239 check_replace_refs = 0;32403241 reset_pack_idx_option(&pack_idx_opts);3242 git_config(git_pack_config, NULL);32433244 progress = isatty(2);3245 argc = parse_options(argc, argv, prefix, pack_objects_options,3246 pack_usage, 0);32473248 if (argc) {3249 base_name = argv[0];3250 argc--;3251 }3252 if (pack_to_stdout != !base_name || argc)3253 usage_with_options(pack_usage, pack_objects_options);32543255 if (depth >= (1 << OE_DEPTH_BITS)) {3256 warning(_("delta chain depth %d is too deep, forcing %d"),3257 depth, (1 << OE_DEPTH_BITS) - 1);3258 depth = (1 << OE_DEPTH_BITS) - 1;3259 }3260 if (cache_max_small_delta_size >= (1U << OE_Z_DELTA_BITS)) {3261 warning(_("pack.deltaCacheLimit is too high, forcing %d"),3262 (1U << OE_Z_DELTA_BITS) - 1);3263 cache_max_small_delta_size = (1U << OE_Z_DELTA_BITS) - 1;3264 }32653266 argv_array_push(&rp, "pack-objects");3267 if (thin) {3268 use_internal_rev_list = 1;3269 argv_array_push(&rp, shallow3270 ? "--objects-edge-aggressive"3271 : "--objects-edge");3272 } else3273 argv_array_push(&rp, "--objects");32743275 if (rev_list_all) {3276 use_internal_rev_list = 1;3277 argv_array_push(&rp, "--all");3278 }3279 if (rev_list_reflog) {3280 use_internal_rev_list = 1;3281 argv_array_push(&rp, "--reflog");3282 }3283 if (rev_list_index) {3284 use_internal_rev_list = 1;3285 argv_array_push(&rp, "--indexed-objects");3286 }3287 if (rev_list_unpacked) {3288 use_internal_rev_list = 1;3289 argv_array_push(&rp, "--unpacked");3290 }32913292 if (exclude_promisor_objects) {3293 use_internal_rev_list = 1;3294 fetch_if_missing = 0;3295 argv_array_push(&rp, "--exclude-promisor-objects");3296 }3297 if (unpack_unreachable || keep_unreachable || pack_loose_unreachable)3298 use_internal_rev_list = 1;32993300 if (!reuse_object)3301 reuse_delta = 0;3302 if (pack_compression_level == -1)3303 pack_compression_level = Z_DEFAULT_COMPRESSION;3304 else if (pack_compression_level < 0 || pack_compression_level > Z_BEST_COMPRESSION)3305 die("bad pack compression level %d", pack_compression_level);33063307 if (!delta_search_threads) /* --threads=0 means autodetect */3308 delta_search_threads = online_cpus();33093310#ifdef NO_PTHREADS3311 if (delta_search_threads != 1)3312 warning("no threads support, ignoring --threads");3313#endif3314 if (!pack_to_stdout && !pack_size_limit)3315 pack_size_limit = pack_size_limit_cfg;3316 if (pack_to_stdout && pack_size_limit)3317 die("--max-pack-size cannot be used to build a pack for transfer.");3318 if (pack_size_limit && pack_size_limit < 1024*1024) {3319 warning("minimum pack size limit is 1 MiB");3320 pack_size_limit = 1024*1024;3321 }33223323 if (!pack_to_stdout && thin)3324 die("--thin cannot be used to build an indexable pack.");33253326 if (keep_unreachable && unpack_unreachable)3327 die("--keep-unreachable and --unpack-unreachable are incompatible.");3328 if (!rev_list_all || !rev_list_reflog || !rev_list_index)3329 unpack_unreachable_expiration = 0;33303331 if (filter_options.choice) {3332 if (!pack_to_stdout)3333 die("cannot use --filter without --stdout.");3334 use_bitmap_index = 0;3335 }33363337 /*3338 * "soft" reasons not to use bitmaps - for on-disk repack by default we want3339 *3340 * - to produce good pack (with bitmap index not-yet-packed objects are3341 * packed in suboptimal order).3342 *3343 * - to use more robust pack-generation codepath (avoiding possible3344 * bugs in bitmap code and possible bitmap index corruption).3345 */3346 if (!pack_to_stdout)3347 use_bitmap_index_default = 0;33483349 if (use_bitmap_index < 0)3350 use_bitmap_index = use_bitmap_index_default;33513352 /* "hard" reasons not to use bitmaps; these just won't work at all */3353 if (!use_internal_rev_list || (!pack_to_stdout && write_bitmap_index) || is_repository_shallow(the_repository))3354 use_bitmap_index = 0;33553356 if (pack_to_stdout || !rev_list_all)3357 write_bitmap_index = 0;33583359 if (use_delta_islands)3360 argv_array_push(&rp, "--topo-order");33613362 if (progress && all_progress_implied)3363 progress = 2;33643365 add_extra_kept_packs(&keep_pack_list);3366 if (ignore_packed_keep_on_disk) {3367 struct packed_git *p;3368 for (p = get_packed_git(the_repository); p; p = p->next)3369 if (p->pack_local && p->pack_keep)3370 break;3371 if (!p) /* no keep-able packs found */3372 ignore_packed_keep_on_disk = 0;3373 }3374 if (local) {3375 /*3376 * unlike ignore_packed_keep_on_disk above, we do not3377 * want to unset "local" based on looking at packs, as3378 * it also covers non-local objects3379 */3380 struct packed_git *p;3381 for (p = get_packed_git(the_repository); p; p = p->next) {3382 if (!p->pack_local) {3383 have_non_local_packs = 1;3384 break;3385 }3386 }3387 }33883389 prepare_packing_data(&to_pack);33903391 if (progress)3392 progress_state = start_progress(_("Enumerating objects"), 0);3393 if (!use_internal_rev_list)3394 read_object_list_from_stdin();3395 else {3396 get_object_list(rp.argc, rp.argv);3397 argv_array_clear(&rp);3398 }3399 cleanup_preferred_base();3400 if (include_tag && nr_result)3401 for_each_ref(add_ref_tag, NULL);3402 stop_progress(&progress_state);34033404 if (non_empty && !nr_result)3405 return 0;3406 if (nr_result)3407 prepare_pack(window, depth);3408 write_pack_file();3409 if (progress)3410 fprintf(stderr, "Total %"PRIu32" (delta %"PRIu32"),"3411 " reused %"PRIu32" (delta %"PRIu32")\n",3412 written, written_delta, reused, reused_delta);3413 return 0;3414}