builtin / pack-objects.con commit pack-objects: do not truncate result in-pack object size on 32-bit systems (af92a64)
   1#include "builtin.h"
   2#include "cache.h"
   3#include "attr.h"
   4#include "object.h"
   5#include "blob.h"
   6#include "commit.h"
   7#include "tag.h"
   8#include "tree.h"
   9#include "delta.h"
  10#include "pack.h"
  11#include "pack-revindex.h"
  12#include "csum-file.h"
  13#include "tree-walk.h"
  14#include "diff.h"
  15#include "revision.h"
  16#include "list-objects.h"
  17#include "pack-objects.h"
  18#include "progress.h"
  19#include "refs.h"
  20#include "streaming.h"
  21#include "thread-utils.h"
  22#include "pack-bitmap.h"
  23#include "reachable.h"
  24#include "sha1-array.h"
  25#include "argv-array.h"
  26
  27static const char *pack_usage[] = {
  28        N_("git pack-objects --stdout [<options>...] [< <ref-list> | < <object-list>]"),
  29        N_("git pack-objects [<options>...] <base-name> [< <ref-list> | < <object-list>]"),
  30        NULL
  31};
  32
  33/*
  34 * Objects we are going to pack are collected in the `to_pack` structure.
  35 * It contains an array (dynamically expanded) of the object data, and a map
  36 * that can resolve SHA1s to their position in the array.
  37 */
  38static struct packing_data to_pack;
  39
  40static struct pack_idx_entry **written_list;
  41static uint32_t nr_result, nr_written;
  42
  43static int non_empty;
  44static int reuse_delta = 1, reuse_object = 1;
  45static int keep_unreachable, unpack_unreachable, include_tag;
  46static unsigned long unpack_unreachable_expiration;
  47static int local;
  48static int incremental;
  49static int ignore_packed_keep;
  50static int allow_ofs_delta;
  51static struct pack_idx_option pack_idx_opts;
  52static const char *base_name;
  53static int progress = 1;
  54static int window = 10;
  55static unsigned long pack_size_limit;
  56static int depth = 50;
  57static int delta_search_threads;
  58static int pack_to_stdout;
  59static int num_preferred_base;
  60static struct progress *progress_state;
  61static int pack_compression_level = Z_DEFAULT_COMPRESSION;
  62static int pack_compression_seen;
  63
  64static struct packed_git *reuse_packfile;
  65static uint32_t reuse_packfile_objects;
  66static off_t reuse_packfile_offset;
  67
  68static int use_bitmap_index = 1;
  69static int write_bitmap_index;
  70static uint16_t write_bitmap_options;
  71
  72static unsigned long delta_cache_size = 0;
  73static unsigned long max_delta_cache_size = 256 * 1024 * 1024;
  74static unsigned long cache_max_small_delta_size = 1000;
  75
  76static unsigned long window_memory_limit = 0;
  77
  78/*
  79 * stats
  80 */
  81static uint32_t written, written_delta;
  82static uint32_t reused, reused_delta;
  83
  84/*
  85 * Indexed commits
  86 */
  87static struct commit **indexed_commits;
  88static unsigned int indexed_commits_nr;
  89static unsigned int indexed_commits_alloc;
  90
  91static void index_commit_for_bitmap(struct commit *commit)
  92{
  93        if (indexed_commits_nr >= indexed_commits_alloc) {
  94                indexed_commits_alloc = (indexed_commits_alloc + 32) * 2;
  95                REALLOC_ARRAY(indexed_commits, indexed_commits_alloc);
  96        }
  97
  98        indexed_commits[indexed_commits_nr++] = commit;
  99}
 100
 101static void *get_delta(struct object_entry *entry)
 102{
 103        unsigned long size, base_size, delta_size;
 104        void *buf, *base_buf, *delta_buf;
 105        enum object_type type;
 106
 107        buf = read_sha1_file(entry->idx.sha1, &type, &size);
 108        if (!buf)
 109                die("unable to read %s", sha1_to_hex(entry->idx.sha1));
 110        base_buf = read_sha1_file(entry->delta->idx.sha1, &type, &base_size);
 111        if (!base_buf)
 112                die("unable to read %s", sha1_to_hex(entry->delta->idx.sha1));
 113        delta_buf = diff_delta(base_buf, base_size,
 114                               buf, size, &delta_size, 0);
 115        if (!delta_buf || delta_size != entry->delta_size)
 116                die("delta size changed");
 117        free(buf);
 118        free(base_buf);
 119        return delta_buf;
 120}
 121
 122static unsigned long do_compress(void **pptr, unsigned long size)
 123{
 124        git_zstream stream;
 125        void *in, *out;
 126        unsigned long maxsize;
 127
 128        git_deflate_init(&stream, pack_compression_level);
 129        maxsize = git_deflate_bound(&stream, size);
 130
 131        in = *pptr;
 132        out = xmalloc(maxsize);
 133        *pptr = out;
 134
 135        stream.next_in = in;
 136        stream.avail_in = size;
 137        stream.next_out = out;
 138        stream.avail_out = maxsize;
 139        while (git_deflate(&stream, Z_FINISH) == Z_OK)
 140                ; /* nothing */
 141        git_deflate_end(&stream);
 142
 143        free(in);
 144        return stream.total_out;
 145}
 146
 147static unsigned long write_large_blob_data(struct git_istream *st, struct sha1file *f,
 148                                           const unsigned char *sha1)
 149{
 150        git_zstream stream;
 151        unsigned char ibuf[1024 * 16];
 152        unsigned char obuf[1024 * 16];
 153        unsigned long olen = 0;
 154
 155        git_deflate_init(&stream, pack_compression_level);
 156
 157        for (;;) {
 158                ssize_t readlen;
 159                int zret = Z_OK;
 160                readlen = read_istream(st, ibuf, sizeof(ibuf));
 161                if (readlen == -1)
 162                        die(_("unable to read %s"), sha1_to_hex(sha1));
 163
 164                stream.next_in = ibuf;
 165                stream.avail_in = readlen;
 166                while ((stream.avail_in || readlen == 0) &&
 167                       (zret == Z_OK || zret == Z_BUF_ERROR)) {
 168                        stream.next_out = obuf;
 169                        stream.avail_out = sizeof(obuf);
 170                        zret = git_deflate(&stream, readlen ? 0 : Z_FINISH);
 171                        sha1write(f, obuf, stream.next_out - obuf);
 172                        olen += stream.next_out - obuf;
 173                }
 174                if (stream.avail_in)
 175                        die(_("deflate error (%d)"), zret);
 176                if (readlen == 0) {
 177                        if (zret != Z_STREAM_END)
 178                                die(_("deflate error (%d)"), zret);
 179                        break;
 180                }
 181        }
 182        git_deflate_end(&stream);
 183        return olen;
 184}
 185
 186/*
 187 * we are going to reuse the existing object data as is.  make
 188 * sure it is not corrupt.
 189 */
 190static int check_pack_inflate(struct packed_git *p,
 191                struct pack_window **w_curs,
 192                off_t offset,
 193                off_t len,
 194                unsigned long expect)
 195{
 196        git_zstream stream;
 197        unsigned char fakebuf[4096], *in;
 198        int st;
 199
 200        memset(&stream, 0, sizeof(stream));
 201        git_inflate_init(&stream);
 202        do {
 203                in = use_pack(p, w_curs, offset, &stream.avail_in);
 204                stream.next_in = in;
 205                stream.next_out = fakebuf;
 206                stream.avail_out = sizeof(fakebuf);
 207                st = git_inflate(&stream, Z_FINISH);
 208                offset += stream.next_in - in;
 209        } while (st == Z_OK || st == Z_BUF_ERROR);
 210        git_inflate_end(&stream);
 211        return (st == Z_STREAM_END &&
 212                stream.total_out == expect &&
 213                stream.total_in == len) ? 0 : -1;
 214}
 215
 216static void copy_pack_data(struct sha1file *f,
 217                struct packed_git *p,
 218                struct pack_window **w_curs,
 219                off_t offset,
 220                off_t len)
 221{
 222        unsigned char *in;
 223        unsigned long avail;
 224
 225        while (len) {
 226                in = use_pack(p, w_curs, offset, &avail);
 227                if (avail > len)
 228                        avail = (unsigned long)len;
 229                sha1write(f, in, avail);
 230                offset += avail;
 231                len -= avail;
 232        }
 233}
 234
 235/* Return 0 if we will bust the pack-size limit */
 236static unsigned long write_no_reuse_object(struct sha1file *f, struct object_entry *entry,
 237                                           unsigned long limit, int usable_delta)
 238{
 239        unsigned long size, datalen;
 240        unsigned char header[10], dheader[10];
 241        unsigned hdrlen;
 242        enum object_type type;
 243        void *buf;
 244        struct git_istream *st = NULL;
 245
 246        if (!usable_delta) {
 247                if (entry->type == OBJ_BLOB &&
 248                    entry->size > big_file_threshold &&
 249                    (st = open_istream(entry->idx.sha1, &type, &size, NULL)) != NULL)
 250                        buf = NULL;
 251                else {
 252                        buf = read_sha1_file(entry->idx.sha1, &type, &size);
 253                        if (!buf)
 254                                die(_("unable to read %s"), sha1_to_hex(entry->idx.sha1));
 255                }
 256                /*
 257                 * make sure no cached delta data remains from a
 258                 * previous attempt before a pack split occurred.
 259                 */
 260                free(entry->delta_data);
 261                entry->delta_data = NULL;
 262                entry->z_delta_size = 0;
 263        } else if (entry->delta_data) {
 264                size = entry->delta_size;
 265                buf = entry->delta_data;
 266                entry->delta_data = NULL;
 267                type = (allow_ofs_delta && entry->delta->idx.offset) ?
 268                        OBJ_OFS_DELTA : OBJ_REF_DELTA;
 269        } else {
 270                buf = get_delta(entry);
 271                size = entry->delta_size;
 272                type = (allow_ofs_delta && entry->delta->idx.offset) ?
 273                        OBJ_OFS_DELTA : OBJ_REF_DELTA;
 274        }
 275
 276        if (st) /* large blob case, just assume we don't compress well */
 277                datalen = size;
 278        else if (entry->z_delta_size)
 279                datalen = entry->z_delta_size;
 280        else
 281                datalen = do_compress(&buf, size);
 282
 283        /*
 284         * The object header is a byte of 'type' followed by zero or
 285         * more bytes of length.
 286         */
 287        hdrlen = encode_in_pack_object_header(type, size, header);
 288
 289        if (type == OBJ_OFS_DELTA) {
 290                /*
 291                 * Deltas with relative base contain an additional
 292                 * encoding of the relative offset for the delta
 293                 * base from this object's position in the pack.
 294                 */
 295                off_t ofs = entry->idx.offset - entry->delta->idx.offset;
 296                unsigned pos = sizeof(dheader) - 1;
 297                dheader[pos] = ofs & 127;
 298                while (ofs >>= 7)
 299                        dheader[--pos] = 128 | (--ofs & 127);
 300                if (limit && hdrlen + sizeof(dheader) - pos + datalen + 20 >= limit) {
 301                        if (st)
 302                                close_istream(st);
 303                        free(buf);
 304                        return 0;
 305                }
 306                sha1write(f, header, hdrlen);
 307                sha1write(f, dheader + pos, sizeof(dheader) - pos);
 308                hdrlen += sizeof(dheader) - pos;
 309        } else if (type == OBJ_REF_DELTA) {
 310                /*
 311                 * Deltas with a base reference contain
 312                 * an additional 20 bytes for the base sha1.
 313                 */
 314                if (limit && hdrlen + 20 + datalen + 20 >= limit) {
 315                        if (st)
 316                                close_istream(st);
 317                        free(buf);
 318                        return 0;
 319                }
 320                sha1write(f, header, hdrlen);
 321                sha1write(f, entry->delta->idx.sha1, 20);
 322                hdrlen += 20;
 323        } else {
 324                if (limit && hdrlen + datalen + 20 >= limit) {
 325                        if (st)
 326                                close_istream(st);
 327                        free(buf);
 328                        return 0;
 329                }
 330                sha1write(f, header, hdrlen);
 331        }
 332        if (st) {
 333                datalen = write_large_blob_data(st, f, entry->idx.sha1);
 334                close_istream(st);
 335        } else {
 336                sha1write(f, buf, datalen);
 337                free(buf);
 338        }
 339
 340        return hdrlen + datalen;
 341}
 342
 343/* Return 0 if we will bust the pack-size limit */
 344static off_t write_reuse_object(struct sha1file *f, struct object_entry *entry,
 345                                unsigned long limit, int usable_delta)
 346{
 347        struct packed_git *p = entry->in_pack;
 348        struct pack_window *w_curs = NULL;
 349        struct revindex_entry *revidx;
 350        off_t offset;
 351        enum object_type type = entry->type;
 352        off_t datalen;
 353        unsigned char header[10], dheader[10];
 354        unsigned hdrlen;
 355
 356        if (entry->delta)
 357                type = (allow_ofs_delta && entry->delta->idx.offset) ?
 358                        OBJ_OFS_DELTA : OBJ_REF_DELTA;
 359        hdrlen = encode_in_pack_object_header(type, entry->size, header);
 360
 361        offset = entry->in_pack_offset;
 362        revidx = find_pack_revindex(p, offset);
 363        datalen = revidx[1].offset - offset;
 364        if (!pack_to_stdout && p->index_version > 1 &&
 365            check_pack_crc(p, &w_curs, offset, datalen, revidx->nr)) {
 366                error("bad packed object CRC for %s", sha1_to_hex(entry->idx.sha1));
 367                unuse_pack(&w_curs);
 368                return write_no_reuse_object(f, entry, limit, usable_delta);
 369        }
 370
 371        offset += entry->in_pack_header_size;
 372        datalen -= entry->in_pack_header_size;
 373
 374        if (!pack_to_stdout && p->index_version == 1 &&
 375            check_pack_inflate(p, &w_curs, offset, datalen, entry->size)) {
 376                error("corrupt packed object for %s", sha1_to_hex(entry->idx.sha1));
 377                unuse_pack(&w_curs);
 378                return write_no_reuse_object(f, entry, limit, usable_delta);
 379        }
 380
 381        if (type == OBJ_OFS_DELTA) {
 382                off_t ofs = entry->idx.offset - entry->delta->idx.offset;
 383                unsigned pos = sizeof(dheader) - 1;
 384                dheader[pos] = ofs & 127;
 385                while (ofs >>= 7)
 386                        dheader[--pos] = 128 | (--ofs & 127);
 387                if (limit && hdrlen + sizeof(dheader) - pos + datalen + 20 >= limit) {
 388                        unuse_pack(&w_curs);
 389                        return 0;
 390                }
 391                sha1write(f, header, hdrlen);
 392                sha1write(f, dheader + pos, sizeof(dheader) - pos);
 393                hdrlen += sizeof(dheader) - pos;
 394                reused_delta++;
 395        } else if (type == OBJ_REF_DELTA) {
 396                if (limit && hdrlen + 20 + datalen + 20 >= limit) {
 397                        unuse_pack(&w_curs);
 398                        return 0;
 399                }
 400                sha1write(f, header, hdrlen);
 401                sha1write(f, entry->delta->idx.sha1, 20);
 402                hdrlen += 20;
 403                reused_delta++;
 404        } else {
 405                if (limit && hdrlen + datalen + 20 >= limit) {
 406                        unuse_pack(&w_curs);
 407                        return 0;
 408                }
 409                sha1write(f, header, hdrlen);
 410        }
 411        copy_pack_data(f, p, &w_curs, offset, datalen);
 412        unuse_pack(&w_curs);
 413        reused++;
 414        return hdrlen + datalen;
 415}
 416
 417/* Return 0 if we will bust the pack-size limit */
 418static off_t write_object(struct sha1file *f,
 419                          struct object_entry *entry,
 420                          off_t write_offset)
 421{
 422        unsigned long limit;
 423        off_t len;
 424        int usable_delta, to_reuse;
 425
 426        if (!pack_to_stdout)
 427                crc32_begin(f);
 428
 429        /* apply size limit if limited packsize and not first object */
 430        if (!pack_size_limit || !nr_written)
 431                limit = 0;
 432        else if (pack_size_limit <= write_offset)
 433                /*
 434                 * the earlier object did not fit the limit; avoid
 435                 * mistaking this with unlimited (i.e. limit = 0).
 436                 */
 437                limit = 1;
 438        else
 439                limit = pack_size_limit - write_offset;
 440
 441        if (!entry->delta)
 442                usable_delta = 0;       /* no delta */
 443        else if (!pack_size_limit)
 444               usable_delta = 1;        /* unlimited packfile */
 445        else if (entry->delta->idx.offset == (off_t)-1)
 446                usable_delta = 0;       /* base was written to another pack */
 447        else if (entry->delta->idx.offset)
 448                usable_delta = 1;       /* base already exists in this pack */
 449        else
 450                usable_delta = 0;       /* base could end up in another pack */
 451
 452        if (!reuse_object)
 453                to_reuse = 0;   /* explicit */
 454        else if (!entry->in_pack)
 455                to_reuse = 0;   /* can't reuse what we don't have */
 456        else if (entry->type == OBJ_REF_DELTA || entry->type == OBJ_OFS_DELTA)
 457                                /* check_object() decided it for us ... */
 458                to_reuse = usable_delta;
 459                                /* ... but pack split may override that */
 460        else if (entry->type != entry->in_pack_type)
 461                to_reuse = 0;   /* pack has delta which is unusable */
 462        else if (entry->delta)
 463                to_reuse = 0;   /* we want to pack afresh */
 464        else
 465                to_reuse = 1;   /* we have it in-pack undeltified,
 466                                 * and we do not need to deltify it.
 467                                 */
 468
 469        if (!to_reuse)
 470                len = write_no_reuse_object(f, entry, limit, usable_delta);
 471        else
 472                len = write_reuse_object(f, entry, limit, usable_delta);
 473        if (!len)
 474                return 0;
 475
 476        if (usable_delta)
 477                written_delta++;
 478        written++;
 479        if (!pack_to_stdout)
 480                entry->idx.crc32 = crc32_end(f);
 481        return len;
 482}
 483
 484enum write_one_status {
 485        WRITE_ONE_SKIP = -1, /* already written */
 486        WRITE_ONE_BREAK = 0, /* writing this will bust the limit; not written */
 487        WRITE_ONE_WRITTEN = 1, /* normal */
 488        WRITE_ONE_RECURSIVE = 2 /* already scheduled to be written */
 489};
 490
 491static enum write_one_status write_one(struct sha1file *f,
 492                                       struct object_entry *e,
 493                                       off_t *offset)
 494{
 495        off_t size;
 496        int recursing;
 497
 498        /*
 499         * we set offset to 1 (which is an impossible value) to mark
 500         * the fact that this object is involved in "write its base
 501         * first before writing a deltified object" recursion.
 502         */
 503        recursing = (e->idx.offset == 1);
 504        if (recursing) {
 505                warning("recursive delta detected for object %s",
 506                        sha1_to_hex(e->idx.sha1));
 507                return WRITE_ONE_RECURSIVE;
 508        } else if (e->idx.offset || e->preferred_base) {
 509                /* offset is non zero if object is written already. */
 510                return WRITE_ONE_SKIP;
 511        }
 512
 513        /* if we are deltified, write out base object first. */
 514        if (e->delta) {
 515                e->idx.offset = 1; /* now recurse */
 516                switch (write_one(f, e->delta, offset)) {
 517                case WRITE_ONE_RECURSIVE:
 518                        /* we cannot depend on this one */
 519                        e->delta = NULL;
 520                        break;
 521                default:
 522                        break;
 523                case WRITE_ONE_BREAK:
 524                        e->idx.offset = recursing;
 525                        return WRITE_ONE_BREAK;
 526                }
 527        }
 528
 529        e->idx.offset = *offset;
 530        size = write_object(f, e, *offset);
 531        if (!size) {
 532                e->idx.offset = recursing;
 533                return WRITE_ONE_BREAK;
 534        }
 535        written_list[nr_written++] = &e->idx;
 536
 537        /* make sure off_t is sufficiently large not to wrap */
 538        if (signed_add_overflows(*offset, size))
 539                die("pack too large for current definition of off_t");
 540        *offset += size;
 541        return WRITE_ONE_WRITTEN;
 542}
 543
 544static int mark_tagged(const char *path, const struct object_id *oid, int flag,
 545                       void *cb_data)
 546{
 547        unsigned char peeled[20];
 548        struct object_entry *entry = packlist_find(&to_pack, oid->hash, NULL);
 549
 550        if (entry)
 551                entry->tagged = 1;
 552        if (!peel_ref(path, peeled)) {
 553                entry = packlist_find(&to_pack, peeled, NULL);
 554                if (entry)
 555                        entry->tagged = 1;
 556        }
 557        return 0;
 558}
 559
 560static inline void add_to_write_order(struct object_entry **wo,
 561                               unsigned int *endp,
 562                               struct object_entry *e)
 563{
 564        if (e->filled)
 565                return;
 566        wo[(*endp)++] = e;
 567        e->filled = 1;
 568}
 569
 570static void add_descendants_to_write_order(struct object_entry **wo,
 571                                           unsigned int *endp,
 572                                           struct object_entry *e)
 573{
 574        int add_to_order = 1;
 575        while (e) {
 576                if (add_to_order) {
 577                        struct object_entry *s;
 578                        /* add this node... */
 579                        add_to_write_order(wo, endp, e);
 580                        /* all its siblings... */
 581                        for (s = e->delta_sibling; s; s = s->delta_sibling) {
 582                                add_to_write_order(wo, endp, s);
 583                        }
 584                }
 585                /* drop down a level to add left subtree nodes if possible */
 586                if (e->delta_child) {
 587                        add_to_order = 1;
 588                        e = e->delta_child;
 589                } else {
 590                        add_to_order = 0;
 591                        /* our sibling might have some children, it is next */
 592                        if (e->delta_sibling) {
 593                                e = e->delta_sibling;
 594                                continue;
 595                        }
 596                        /* go back to our parent node */
 597                        e = e->delta;
 598                        while (e && !e->delta_sibling) {
 599                                /* we're on the right side of a subtree, keep
 600                                 * going up until we can go right again */
 601                                e = e->delta;
 602                        }
 603                        if (!e) {
 604                                /* done- we hit our original root node */
 605                                return;
 606                        }
 607                        /* pass it off to sibling at this level */
 608                        e = e->delta_sibling;
 609                }
 610        };
 611}
 612
 613static void add_family_to_write_order(struct object_entry **wo,
 614                                      unsigned int *endp,
 615                                      struct object_entry *e)
 616{
 617        struct object_entry *root;
 618
 619        for (root = e; root->delta; root = root->delta)
 620                ; /* nothing */
 621        add_descendants_to_write_order(wo, endp, root);
 622}
 623
 624static struct object_entry **compute_write_order(void)
 625{
 626        unsigned int i, wo_end, last_untagged;
 627
 628        struct object_entry **wo;
 629        struct object_entry *objects = to_pack.objects;
 630
 631        for (i = 0; i < to_pack.nr_objects; i++) {
 632                objects[i].tagged = 0;
 633                objects[i].filled = 0;
 634                objects[i].delta_child = NULL;
 635                objects[i].delta_sibling = NULL;
 636        }
 637
 638        /*
 639         * Fully connect delta_child/delta_sibling network.
 640         * Make sure delta_sibling is sorted in the original
 641         * recency order.
 642         */
 643        for (i = to_pack.nr_objects; i > 0;) {
 644                struct object_entry *e = &objects[--i];
 645                if (!e->delta)
 646                        continue;
 647                /* Mark me as the first child */
 648                e->delta_sibling = e->delta->delta_child;
 649                e->delta->delta_child = e;
 650        }
 651
 652        /*
 653         * Mark objects that are at the tip of tags.
 654         */
 655        for_each_tag_ref(mark_tagged, NULL);
 656
 657        /*
 658         * Give the objects in the original recency order until
 659         * we see a tagged tip.
 660         */
 661        ALLOC_ARRAY(wo, to_pack.nr_objects);
 662        for (i = wo_end = 0; i < to_pack.nr_objects; i++) {
 663                if (objects[i].tagged)
 664                        break;
 665                add_to_write_order(wo, &wo_end, &objects[i]);
 666        }
 667        last_untagged = i;
 668
 669        /*
 670         * Then fill all the tagged tips.
 671         */
 672        for (; i < to_pack.nr_objects; i++) {
 673                if (objects[i].tagged)
 674                        add_to_write_order(wo, &wo_end, &objects[i]);
 675        }
 676
 677        /*
 678         * And then all remaining commits and tags.
 679         */
 680        for (i = last_untagged; i < to_pack.nr_objects; i++) {
 681                if (objects[i].type != OBJ_COMMIT &&
 682                    objects[i].type != OBJ_TAG)
 683                        continue;
 684                add_to_write_order(wo, &wo_end, &objects[i]);
 685        }
 686
 687        /*
 688         * And then all the trees.
 689         */
 690        for (i = last_untagged; i < to_pack.nr_objects; i++) {
 691                if (objects[i].type != OBJ_TREE)
 692                        continue;
 693                add_to_write_order(wo, &wo_end, &objects[i]);
 694        }
 695
 696        /*
 697         * Finally all the rest in really tight order
 698         */
 699        for (i = last_untagged; i < to_pack.nr_objects; i++) {
 700                if (!objects[i].filled)
 701                        add_family_to_write_order(wo, &wo_end, &objects[i]);
 702        }
 703
 704        if (wo_end != to_pack.nr_objects)
 705                die("ordered %u objects, expected %"PRIu32, wo_end, to_pack.nr_objects);
 706
 707        return wo;
 708}
 709
 710static off_t write_reused_pack(struct sha1file *f)
 711{
 712        unsigned char buffer[8192];
 713        off_t to_write, total;
 714        int fd;
 715
 716        if (!is_pack_valid(reuse_packfile))
 717                die("packfile is invalid: %s", reuse_packfile->pack_name);
 718
 719        fd = git_open_noatime(reuse_packfile->pack_name);
 720        if (fd < 0)
 721                die_errno("unable to open packfile for reuse: %s",
 722                          reuse_packfile->pack_name);
 723
 724        if (lseek(fd, sizeof(struct pack_header), SEEK_SET) == -1)
 725                die_errno("unable to seek in reused packfile");
 726
 727        if (reuse_packfile_offset < 0)
 728                reuse_packfile_offset = reuse_packfile->pack_size - 20;
 729
 730        total = to_write = reuse_packfile_offset - sizeof(struct pack_header);
 731
 732        while (to_write) {
 733                int read_pack = xread(fd, buffer, sizeof(buffer));
 734
 735                if (read_pack <= 0)
 736                        die_errno("unable to read from reused packfile");
 737
 738                if (read_pack > to_write)
 739                        read_pack = to_write;
 740
 741                sha1write(f, buffer, read_pack);
 742                to_write -= read_pack;
 743
 744                /*
 745                 * We don't know the actual number of objects written,
 746                 * only how many bytes written, how many bytes total, and
 747                 * how many objects total. So we can fake it by pretending all
 748                 * objects we are writing are the same size. This gives us a
 749                 * smooth progress meter, and at the end it matches the true
 750                 * answer.
 751                 */
 752                written = reuse_packfile_objects *
 753                                (((double)(total - to_write)) / total);
 754                display_progress(progress_state, written);
 755        }
 756
 757        close(fd);
 758        written = reuse_packfile_objects;
 759        display_progress(progress_state, written);
 760        return reuse_packfile_offset - sizeof(struct pack_header);
 761}
 762
 763static const char no_split_warning[] = N_(
 764"disabling bitmap writing, packs are split due to pack.packSizeLimit"
 765);
 766
 767static void write_pack_file(void)
 768{
 769        uint32_t i = 0, j;
 770        struct sha1file *f;
 771        off_t offset;
 772        uint32_t nr_remaining = nr_result;
 773        time_t last_mtime = 0;
 774        struct object_entry **write_order;
 775
 776        if (progress > pack_to_stdout)
 777                progress_state = start_progress(_("Writing objects"), nr_result);
 778        ALLOC_ARRAY(written_list, to_pack.nr_objects);
 779        write_order = compute_write_order();
 780
 781        do {
 782                unsigned char sha1[20];
 783                char *pack_tmp_name = NULL;
 784
 785                if (pack_to_stdout)
 786                        f = sha1fd_throughput(1, "<stdout>", progress_state);
 787                else
 788                        f = create_tmp_packfile(&pack_tmp_name);
 789
 790                offset = write_pack_header(f, nr_remaining);
 791
 792                if (reuse_packfile) {
 793                        off_t packfile_size;
 794                        assert(pack_to_stdout);
 795
 796                        packfile_size = write_reused_pack(f);
 797                        offset += packfile_size;
 798                }
 799
 800                nr_written = 0;
 801                for (; i < to_pack.nr_objects; i++) {
 802                        struct object_entry *e = write_order[i];
 803                        if (write_one(f, e, &offset) == WRITE_ONE_BREAK)
 804                                break;
 805                        display_progress(progress_state, written);
 806                }
 807
 808                /*
 809                 * Did we write the wrong # entries in the header?
 810                 * If so, rewrite it like in fast-import
 811                 */
 812                if (pack_to_stdout) {
 813                        sha1close(f, sha1, CSUM_CLOSE);
 814                } else if (nr_written == nr_remaining) {
 815                        sha1close(f, sha1, CSUM_FSYNC);
 816                } else {
 817                        int fd = sha1close(f, sha1, 0);
 818                        fixup_pack_header_footer(fd, sha1, pack_tmp_name,
 819                                                 nr_written, sha1, offset);
 820                        close(fd);
 821                        if (write_bitmap_index) {
 822                                warning(_(no_split_warning));
 823                                write_bitmap_index = 0;
 824                        }
 825                }
 826
 827                if (!pack_to_stdout) {
 828                        struct stat st;
 829                        struct strbuf tmpname = STRBUF_INIT;
 830
 831                        /*
 832                         * Packs are runtime accessed in their mtime
 833                         * order since newer packs are more likely to contain
 834                         * younger objects.  So if we are creating multiple
 835                         * packs then we should modify the mtime of later ones
 836                         * to preserve this property.
 837                         */
 838                        if (stat(pack_tmp_name, &st) < 0) {
 839                                warning("failed to stat %s: %s",
 840                                        pack_tmp_name, strerror(errno));
 841                        } else if (!last_mtime) {
 842                                last_mtime = st.st_mtime;
 843                        } else {
 844                                struct utimbuf utb;
 845                                utb.actime = st.st_atime;
 846                                utb.modtime = --last_mtime;
 847                                if (utime(pack_tmp_name, &utb) < 0)
 848                                        warning("failed utime() on %s: %s",
 849                                                pack_tmp_name, strerror(errno));
 850                        }
 851
 852                        strbuf_addf(&tmpname, "%s-", base_name);
 853
 854                        if (write_bitmap_index) {
 855                                bitmap_writer_set_checksum(sha1);
 856                                bitmap_writer_build_type_index(written_list, nr_written);
 857                        }
 858
 859                        finish_tmp_packfile(&tmpname, pack_tmp_name,
 860                                            written_list, nr_written,
 861                                            &pack_idx_opts, sha1);
 862
 863                        if (write_bitmap_index) {
 864                                strbuf_addf(&tmpname, "%s.bitmap", sha1_to_hex(sha1));
 865
 866                                stop_progress(&progress_state);
 867
 868                                bitmap_writer_show_progress(progress);
 869                                bitmap_writer_reuse_bitmaps(&to_pack);
 870                                bitmap_writer_select_commits(indexed_commits, indexed_commits_nr, -1);
 871                                bitmap_writer_build(&to_pack);
 872                                bitmap_writer_finish(written_list, nr_written,
 873                                                     tmpname.buf, write_bitmap_options);
 874                                write_bitmap_index = 0;
 875                        }
 876
 877                        strbuf_release(&tmpname);
 878                        free(pack_tmp_name);
 879                        puts(sha1_to_hex(sha1));
 880                }
 881
 882                /* mark written objects as written to previous pack */
 883                for (j = 0; j < nr_written; j++) {
 884                        written_list[j]->offset = (off_t)-1;
 885                }
 886                nr_remaining -= nr_written;
 887        } while (nr_remaining && i < to_pack.nr_objects);
 888
 889        free(written_list);
 890        free(write_order);
 891        stop_progress(&progress_state);
 892        if (written != nr_result)
 893                die("wrote %"PRIu32" objects while expecting %"PRIu32,
 894                        written, nr_result);
 895}
 896
 897static void setup_delta_attr_check(struct git_attr_check *check)
 898{
 899        static struct git_attr *attr_delta;
 900
 901        if (!attr_delta)
 902                attr_delta = git_attr("delta");
 903
 904        check[0].attr = attr_delta;
 905}
 906
 907static int no_try_delta(const char *path)
 908{
 909        struct git_attr_check check[1];
 910
 911        setup_delta_attr_check(check);
 912        if (git_check_attr(path, ARRAY_SIZE(check), check))
 913                return 0;
 914        if (ATTR_FALSE(check->value))
 915                return 1;
 916        return 0;
 917}
 918
 919/*
 920 * When adding an object, check whether we have already added it
 921 * to our packing list. If so, we can skip. However, if we are
 922 * being asked to excludei t, but the previous mention was to include
 923 * it, make sure to adjust its flags and tweak our numbers accordingly.
 924 *
 925 * As an optimization, we pass out the index position where we would have
 926 * found the item, since that saves us from having to look it up again a
 927 * few lines later when we want to add the new entry.
 928 */
 929static int have_duplicate_entry(const unsigned char *sha1,
 930                                int exclude,
 931                                uint32_t *index_pos)
 932{
 933        struct object_entry *entry;
 934
 935        entry = packlist_find(&to_pack, sha1, index_pos);
 936        if (!entry)
 937                return 0;
 938
 939        if (exclude) {
 940                if (!entry->preferred_base)
 941                        nr_result--;
 942                entry->preferred_base = 1;
 943        }
 944
 945        return 1;
 946}
 947
 948/*
 949 * Check whether we want the object in the pack (e.g., we do not want
 950 * objects found in non-local stores if the "--local" option was used).
 951 *
 952 * As a side effect of this check, we will find the packed version of this
 953 * object, if any. We therefore pass out the pack information to avoid having
 954 * to look it up again later.
 955 */
 956static int want_object_in_pack(const unsigned char *sha1,
 957                               int exclude,
 958                               struct packed_git **found_pack,
 959                               off_t *found_offset)
 960{
 961        struct packed_git *p;
 962
 963        if (!exclude && local && has_loose_object_nonlocal(sha1))
 964                return 0;
 965
 966        *found_pack = NULL;
 967        *found_offset = 0;
 968
 969        for (p = packed_git; p; p = p->next) {
 970                off_t offset = find_pack_entry_one(sha1, p);
 971                if (offset) {
 972                        if (!*found_pack) {
 973                                if (!is_pack_valid(p))
 974                                        continue;
 975                                *found_offset = offset;
 976                                *found_pack = p;
 977                        }
 978                        if (exclude)
 979                                return 1;
 980                        if (incremental)
 981                                return 0;
 982                        if (local && !p->pack_local)
 983                                return 0;
 984                        if (ignore_packed_keep && p->pack_local && p->pack_keep)
 985                                return 0;
 986                }
 987        }
 988
 989        return 1;
 990}
 991
 992static void create_object_entry(const unsigned char *sha1,
 993                                enum object_type type,
 994                                uint32_t hash,
 995                                int exclude,
 996                                int no_try_delta,
 997                                uint32_t index_pos,
 998                                struct packed_git *found_pack,
 999                                off_t found_offset)
1000{
1001        struct object_entry *entry;
1002
1003        entry = packlist_alloc(&to_pack, sha1, index_pos);
1004        entry->hash = hash;
1005        if (type)
1006                entry->type = type;
1007        if (exclude)
1008                entry->preferred_base = 1;
1009        else
1010                nr_result++;
1011        if (found_pack) {
1012                entry->in_pack = found_pack;
1013                entry->in_pack_offset = found_offset;
1014        }
1015
1016        entry->no_try_delta = no_try_delta;
1017}
1018
1019static const char no_closure_warning[] = N_(
1020"disabling bitmap writing, as some objects are not being packed"
1021);
1022
1023static int add_object_entry(const unsigned char *sha1, enum object_type type,
1024                            const char *name, int exclude)
1025{
1026        struct packed_git *found_pack;
1027        off_t found_offset;
1028        uint32_t index_pos;
1029
1030        if (have_duplicate_entry(sha1, exclude, &index_pos))
1031                return 0;
1032
1033        if (!want_object_in_pack(sha1, exclude, &found_pack, &found_offset)) {
1034                /* The pack is missing an object, so it will not have closure */
1035                if (write_bitmap_index) {
1036                        warning(_(no_closure_warning));
1037                        write_bitmap_index = 0;
1038                }
1039                return 0;
1040        }
1041
1042        create_object_entry(sha1, type, pack_name_hash(name),
1043                            exclude, name && no_try_delta(name),
1044                            index_pos, found_pack, found_offset);
1045
1046        display_progress(progress_state, nr_result);
1047        return 1;
1048}
1049
1050static int add_object_entry_from_bitmap(const unsigned char *sha1,
1051                                        enum object_type type,
1052                                        int flags, uint32_t name_hash,
1053                                        struct packed_git *pack, off_t offset)
1054{
1055        uint32_t index_pos;
1056
1057        if (have_duplicate_entry(sha1, 0, &index_pos))
1058                return 0;
1059
1060        create_object_entry(sha1, type, name_hash, 0, 0, index_pos, pack, offset);
1061
1062        display_progress(progress_state, nr_result);
1063        return 1;
1064}
1065
1066struct pbase_tree_cache {
1067        unsigned char sha1[20];
1068        int ref;
1069        int temporary;
1070        void *tree_data;
1071        unsigned long tree_size;
1072};
1073
1074static struct pbase_tree_cache *(pbase_tree_cache[256]);
1075static int pbase_tree_cache_ix(const unsigned char *sha1)
1076{
1077        return sha1[0] % ARRAY_SIZE(pbase_tree_cache);
1078}
1079static int pbase_tree_cache_ix_incr(int ix)
1080{
1081        return (ix+1) % ARRAY_SIZE(pbase_tree_cache);
1082}
1083
1084static struct pbase_tree {
1085        struct pbase_tree *next;
1086        /* This is a phony "cache" entry; we are not
1087         * going to evict it or find it through _get()
1088         * mechanism -- this is for the toplevel node that
1089         * would almost always change with any commit.
1090         */
1091        struct pbase_tree_cache pcache;
1092} *pbase_tree;
1093
1094static struct pbase_tree_cache *pbase_tree_get(const unsigned char *sha1)
1095{
1096        struct pbase_tree_cache *ent, *nent;
1097        void *data;
1098        unsigned long size;
1099        enum object_type type;
1100        int neigh;
1101        int my_ix = pbase_tree_cache_ix(sha1);
1102        int available_ix = -1;
1103
1104        /* pbase-tree-cache acts as a limited hashtable.
1105         * your object will be found at your index or within a few
1106         * slots after that slot if it is cached.
1107         */
1108        for (neigh = 0; neigh < 8; neigh++) {
1109                ent = pbase_tree_cache[my_ix];
1110                if (ent && !hashcmp(ent->sha1, sha1)) {
1111                        ent->ref++;
1112                        return ent;
1113                }
1114                else if (((available_ix < 0) && (!ent || !ent->ref)) ||
1115                         ((0 <= available_ix) &&
1116                          (!ent && pbase_tree_cache[available_ix])))
1117                        available_ix = my_ix;
1118                if (!ent)
1119                        break;
1120                my_ix = pbase_tree_cache_ix_incr(my_ix);
1121        }
1122
1123        /* Did not find one.  Either we got a bogus request or
1124         * we need to read and perhaps cache.
1125         */
1126        data = read_sha1_file(sha1, &type, &size);
1127        if (!data)
1128                return NULL;
1129        if (type != OBJ_TREE) {
1130                free(data);
1131                return NULL;
1132        }
1133
1134        /* We need to either cache or return a throwaway copy */
1135
1136        if (available_ix < 0)
1137                ent = NULL;
1138        else {
1139                ent = pbase_tree_cache[available_ix];
1140                my_ix = available_ix;
1141        }
1142
1143        if (!ent) {
1144                nent = xmalloc(sizeof(*nent));
1145                nent->temporary = (available_ix < 0);
1146        }
1147        else {
1148                /* evict and reuse */
1149                free(ent->tree_data);
1150                nent = ent;
1151        }
1152        hashcpy(nent->sha1, sha1);
1153        nent->tree_data = data;
1154        nent->tree_size = size;
1155        nent->ref = 1;
1156        if (!nent->temporary)
1157                pbase_tree_cache[my_ix] = nent;
1158        return nent;
1159}
1160
1161static void pbase_tree_put(struct pbase_tree_cache *cache)
1162{
1163        if (!cache->temporary) {
1164                cache->ref--;
1165                return;
1166        }
1167        free(cache->tree_data);
1168        free(cache);
1169}
1170
1171static int name_cmp_len(const char *name)
1172{
1173        int i;
1174        for (i = 0; name[i] && name[i] != '\n' && name[i] != '/'; i++)
1175                ;
1176        return i;
1177}
1178
1179static void add_pbase_object(struct tree_desc *tree,
1180                             const char *name,
1181                             int cmplen,
1182                             const char *fullname)
1183{
1184        struct name_entry entry;
1185        int cmp;
1186
1187        while (tree_entry(tree,&entry)) {
1188                if (S_ISGITLINK(entry.mode))
1189                        continue;
1190                cmp = tree_entry_len(&entry) != cmplen ? 1 :
1191                      memcmp(name, entry.path, cmplen);
1192                if (cmp > 0)
1193                        continue;
1194                if (cmp < 0)
1195                        return;
1196                if (name[cmplen] != '/') {
1197                        add_object_entry(entry.sha1,
1198                                         object_type(entry.mode),
1199                                         fullname, 1);
1200                        return;
1201                }
1202                if (S_ISDIR(entry.mode)) {
1203                        struct tree_desc sub;
1204                        struct pbase_tree_cache *tree;
1205                        const char *down = name+cmplen+1;
1206                        int downlen = name_cmp_len(down);
1207
1208                        tree = pbase_tree_get(entry.sha1);
1209                        if (!tree)
1210                                return;
1211                        init_tree_desc(&sub, tree->tree_data, tree->tree_size);
1212
1213                        add_pbase_object(&sub, down, downlen, fullname);
1214                        pbase_tree_put(tree);
1215                }
1216        }
1217}
1218
1219static unsigned *done_pbase_paths;
1220static int done_pbase_paths_num;
1221static int done_pbase_paths_alloc;
1222static int done_pbase_path_pos(unsigned hash)
1223{
1224        int lo = 0;
1225        int hi = done_pbase_paths_num;
1226        while (lo < hi) {
1227                int mi = (hi + lo) / 2;
1228                if (done_pbase_paths[mi] == hash)
1229                        return mi;
1230                if (done_pbase_paths[mi] < hash)
1231                        hi = mi;
1232                else
1233                        lo = mi + 1;
1234        }
1235        return -lo-1;
1236}
1237
1238static int check_pbase_path(unsigned hash)
1239{
1240        int pos = (!done_pbase_paths) ? -1 : done_pbase_path_pos(hash);
1241        if (0 <= pos)
1242                return 1;
1243        pos = -pos - 1;
1244        ALLOC_GROW(done_pbase_paths,
1245                   done_pbase_paths_num + 1,
1246                   done_pbase_paths_alloc);
1247        done_pbase_paths_num++;
1248        if (pos < done_pbase_paths_num)
1249                memmove(done_pbase_paths + pos + 1,
1250                        done_pbase_paths + pos,
1251                        (done_pbase_paths_num - pos - 1) * sizeof(unsigned));
1252        done_pbase_paths[pos] = hash;
1253        return 0;
1254}
1255
1256static void add_preferred_base_object(const char *name)
1257{
1258        struct pbase_tree *it;
1259        int cmplen;
1260        unsigned hash = pack_name_hash(name);
1261
1262        if (!num_preferred_base || check_pbase_path(hash))
1263                return;
1264
1265        cmplen = name_cmp_len(name);
1266        for (it = pbase_tree; it; it = it->next) {
1267                if (cmplen == 0) {
1268                        add_object_entry(it->pcache.sha1, OBJ_TREE, NULL, 1);
1269                }
1270                else {
1271                        struct tree_desc tree;
1272                        init_tree_desc(&tree, it->pcache.tree_data, it->pcache.tree_size);
1273                        add_pbase_object(&tree, name, cmplen, name);
1274                }
1275        }
1276}
1277
1278static void add_preferred_base(unsigned char *sha1)
1279{
1280        struct pbase_tree *it;
1281        void *data;
1282        unsigned long size;
1283        unsigned char tree_sha1[20];
1284
1285        if (window <= num_preferred_base++)
1286                return;
1287
1288        data = read_object_with_reference(sha1, tree_type, &size, tree_sha1);
1289        if (!data)
1290                return;
1291
1292        for (it = pbase_tree; it; it = it->next) {
1293                if (!hashcmp(it->pcache.sha1, tree_sha1)) {
1294                        free(data);
1295                        return;
1296                }
1297        }
1298
1299        it = xcalloc(1, sizeof(*it));
1300        it->next = pbase_tree;
1301        pbase_tree = it;
1302
1303        hashcpy(it->pcache.sha1, tree_sha1);
1304        it->pcache.tree_data = data;
1305        it->pcache.tree_size = size;
1306}
1307
1308static void cleanup_preferred_base(void)
1309{
1310        struct pbase_tree *it;
1311        unsigned i;
1312
1313        it = pbase_tree;
1314        pbase_tree = NULL;
1315        while (it) {
1316                struct pbase_tree *this = it;
1317                it = this->next;
1318                free(this->pcache.tree_data);
1319                free(this);
1320        }
1321
1322        for (i = 0; i < ARRAY_SIZE(pbase_tree_cache); i++) {
1323                if (!pbase_tree_cache[i])
1324                        continue;
1325                free(pbase_tree_cache[i]->tree_data);
1326                free(pbase_tree_cache[i]);
1327                pbase_tree_cache[i] = NULL;
1328        }
1329
1330        free(done_pbase_paths);
1331        done_pbase_paths = NULL;
1332        done_pbase_paths_num = done_pbase_paths_alloc = 0;
1333}
1334
1335static void check_object(struct object_entry *entry)
1336{
1337        if (entry->in_pack) {
1338                struct packed_git *p = entry->in_pack;
1339                struct pack_window *w_curs = NULL;
1340                const unsigned char *base_ref = NULL;
1341                struct object_entry *base_entry;
1342                unsigned long used, used_0;
1343                unsigned long avail;
1344                off_t ofs;
1345                unsigned char *buf, c;
1346
1347                buf = use_pack(p, &w_curs, entry->in_pack_offset, &avail);
1348
1349                /*
1350                 * We want in_pack_type even if we do not reuse delta
1351                 * since non-delta representations could still be reused.
1352                 */
1353                used = unpack_object_header_buffer(buf, avail,
1354                                                   &entry->in_pack_type,
1355                                                   &entry->size);
1356                if (used == 0)
1357                        goto give_up;
1358
1359                /*
1360                 * Determine if this is a delta and if so whether we can
1361                 * reuse it or not.  Otherwise let's find out as cheaply as
1362                 * possible what the actual type and size for this object is.
1363                 */
1364                switch (entry->in_pack_type) {
1365                default:
1366                        /* Not a delta hence we've already got all we need. */
1367                        entry->type = entry->in_pack_type;
1368                        entry->in_pack_header_size = used;
1369                        if (entry->type < OBJ_COMMIT || entry->type > OBJ_BLOB)
1370                                goto give_up;
1371                        unuse_pack(&w_curs);
1372                        return;
1373                case OBJ_REF_DELTA:
1374                        if (reuse_delta && !entry->preferred_base)
1375                                base_ref = use_pack(p, &w_curs,
1376                                                entry->in_pack_offset + used, NULL);
1377                        entry->in_pack_header_size = used + 20;
1378                        break;
1379                case OBJ_OFS_DELTA:
1380                        buf = use_pack(p, &w_curs,
1381                                       entry->in_pack_offset + used, NULL);
1382                        used_0 = 0;
1383                        c = buf[used_0++];
1384                        ofs = c & 127;
1385                        while (c & 128) {
1386                                ofs += 1;
1387                                if (!ofs || MSB(ofs, 7)) {
1388                                        error("delta base offset overflow in pack for %s",
1389                                              sha1_to_hex(entry->idx.sha1));
1390                                        goto give_up;
1391                                }
1392                                c = buf[used_0++];
1393                                ofs = (ofs << 7) + (c & 127);
1394                        }
1395                        ofs = entry->in_pack_offset - ofs;
1396                        if (ofs <= 0 || ofs >= entry->in_pack_offset) {
1397                                error("delta base offset out of bound for %s",
1398                                      sha1_to_hex(entry->idx.sha1));
1399                                goto give_up;
1400                        }
1401                        if (reuse_delta && !entry->preferred_base) {
1402                                struct revindex_entry *revidx;
1403                                revidx = find_pack_revindex(p, ofs);
1404                                if (!revidx)
1405                                        goto give_up;
1406                                base_ref = nth_packed_object_sha1(p, revidx->nr);
1407                        }
1408                        entry->in_pack_header_size = used + used_0;
1409                        break;
1410                }
1411
1412                if (base_ref && (base_entry = packlist_find(&to_pack, base_ref, NULL))) {
1413                        /*
1414                         * If base_ref was set above that means we wish to
1415                         * reuse delta data, and we even found that base
1416                         * in the list of objects we want to pack. Goodie!
1417                         *
1418                         * Depth value does not matter - find_deltas() will
1419                         * never consider reused delta as the base object to
1420                         * deltify other objects against, in order to avoid
1421                         * circular deltas.
1422                         */
1423                        entry->type = entry->in_pack_type;
1424                        entry->delta = base_entry;
1425                        entry->delta_size = entry->size;
1426                        entry->delta_sibling = base_entry->delta_child;
1427                        base_entry->delta_child = entry;
1428                        unuse_pack(&w_curs);
1429                        return;
1430                }
1431
1432                if (entry->type) {
1433                        /*
1434                         * This must be a delta and we already know what the
1435                         * final object type is.  Let's extract the actual
1436                         * object size from the delta header.
1437                         */
1438                        entry->size = get_size_from_delta(p, &w_curs,
1439                                        entry->in_pack_offset + entry->in_pack_header_size);
1440                        if (entry->size == 0)
1441                                goto give_up;
1442                        unuse_pack(&w_curs);
1443                        return;
1444                }
1445
1446                /*
1447                 * No choice but to fall back to the recursive delta walk
1448                 * with sha1_object_info() to find about the object type
1449                 * at this point...
1450                 */
1451                give_up:
1452                unuse_pack(&w_curs);
1453        }
1454
1455        entry->type = sha1_object_info(entry->idx.sha1, &entry->size);
1456        /*
1457         * The error condition is checked in prepare_pack().  This is
1458         * to permit a missing preferred base object to be ignored
1459         * as a preferred base.  Doing so can result in a larger
1460         * pack file, but the transfer will still take place.
1461         */
1462}
1463
1464static int pack_offset_sort(const void *_a, const void *_b)
1465{
1466        const struct object_entry *a = *(struct object_entry **)_a;
1467        const struct object_entry *b = *(struct object_entry **)_b;
1468
1469        /* avoid filesystem trashing with loose objects */
1470        if (!a->in_pack && !b->in_pack)
1471                return hashcmp(a->idx.sha1, b->idx.sha1);
1472
1473        if (a->in_pack < b->in_pack)
1474                return -1;
1475        if (a->in_pack > b->in_pack)
1476                return 1;
1477        return a->in_pack_offset < b->in_pack_offset ? -1 :
1478                        (a->in_pack_offset > b->in_pack_offset);
1479}
1480
1481static void get_object_details(void)
1482{
1483        uint32_t i;
1484        struct object_entry **sorted_by_offset;
1485
1486        sorted_by_offset = xcalloc(to_pack.nr_objects, sizeof(struct object_entry *));
1487        for (i = 0; i < to_pack.nr_objects; i++)
1488                sorted_by_offset[i] = to_pack.objects + i;
1489        qsort(sorted_by_offset, to_pack.nr_objects, sizeof(*sorted_by_offset), pack_offset_sort);
1490
1491        for (i = 0; i < to_pack.nr_objects; i++) {
1492                struct object_entry *entry = sorted_by_offset[i];
1493                check_object(entry);
1494                if (big_file_threshold < entry->size)
1495                        entry->no_try_delta = 1;
1496        }
1497
1498        free(sorted_by_offset);
1499}
1500
1501/*
1502 * We search for deltas in a list sorted by type, by filename hash, and then
1503 * by size, so that we see progressively smaller and smaller files.
1504 * That's because we prefer deltas to be from the bigger file
1505 * to the smaller -- deletes are potentially cheaper, but perhaps
1506 * more importantly, the bigger file is likely the more recent
1507 * one.  The deepest deltas are therefore the oldest objects which are
1508 * less susceptible to be accessed often.
1509 */
1510static int type_size_sort(const void *_a, const void *_b)
1511{
1512        const struct object_entry *a = *(struct object_entry **)_a;
1513        const struct object_entry *b = *(struct object_entry **)_b;
1514
1515        if (a->type > b->type)
1516                return -1;
1517        if (a->type < b->type)
1518                return 1;
1519        if (a->hash > b->hash)
1520                return -1;
1521        if (a->hash < b->hash)
1522                return 1;
1523        if (a->preferred_base > b->preferred_base)
1524                return -1;
1525        if (a->preferred_base < b->preferred_base)
1526                return 1;
1527        if (a->size > b->size)
1528                return -1;
1529        if (a->size < b->size)
1530                return 1;
1531        return a < b ? -1 : (a > b);  /* newest first */
1532}
1533
1534struct unpacked {
1535        struct object_entry *entry;
1536        void *data;
1537        struct delta_index *index;
1538        unsigned depth;
1539};
1540
1541static int delta_cacheable(unsigned long src_size, unsigned long trg_size,
1542                           unsigned long delta_size)
1543{
1544        if (max_delta_cache_size && delta_cache_size + delta_size > max_delta_cache_size)
1545                return 0;
1546
1547        if (delta_size < cache_max_small_delta_size)
1548                return 1;
1549
1550        /* cache delta, if objects are large enough compared to delta size */
1551        if ((src_size >> 20) + (trg_size >> 21) > (delta_size >> 10))
1552                return 1;
1553
1554        return 0;
1555}
1556
1557#ifndef NO_PTHREADS
1558
1559static pthread_mutex_t read_mutex;
1560#define read_lock()             pthread_mutex_lock(&read_mutex)
1561#define read_unlock()           pthread_mutex_unlock(&read_mutex)
1562
1563static pthread_mutex_t cache_mutex;
1564#define cache_lock()            pthread_mutex_lock(&cache_mutex)
1565#define cache_unlock()          pthread_mutex_unlock(&cache_mutex)
1566
1567static pthread_mutex_t progress_mutex;
1568#define progress_lock()         pthread_mutex_lock(&progress_mutex)
1569#define progress_unlock()       pthread_mutex_unlock(&progress_mutex)
1570
1571#else
1572
1573#define read_lock()             (void)0
1574#define read_unlock()           (void)0
1575#define cache_lock()            (void)0
1576#define cache_unlock()          (void)0
1577#define progress_lock()         (void)0
1578#define progress_unlock()       (void)0
1579
1580#endif
1581
1582static int try_delta(struct unpacked *trg, struct unpacked *src,
1583                     unsigned max_depth, unsigned long *mem_usage)
1584{
1585        struct object_entry *trg_entry = trg->entry;
1586        struct object_entry *src_entry = src->entry;
1587        unsigned long trg_size, src_size, delta_size, sizediff, max_size, sz;
1588        unsigned ref_depth;
1589        enum object_type type;
1590        void *delta_buf;
1591
1592        /* Don't bother doing diffs between different types */
1593        if (trg_entry->type != src_entry->type)
1594                return -1;
1595
1596        /*
1597         * We do not bother to try a delta that we discarded on an
1598         * earlier try, but only when reusing delta data.  Note that
1599         * src_entry that is marked as the preferred_base should always
1600         * be considered, as even if we produce a suboptimal delta against
1601         * it, we will still save the transfer cost, as we already know
1602         * the other side has it and we won't send src_entry at all.
1603         */
1604        if (reuse_delta && trg_entry->in_pack &&
1605            trg_entry->in_pack == src_entry->in_pack &&
1606            !src_entry->preferred_base &&
1607            trg_entry->in_pack_type != OBJ_REF_DELTA &&
1608            trg_entry->in_pack_type != OBJ_OFS_DELTA)
1609                return 0;
1610
1611        /* Let's not bust the allowed depth. */
1612        if (src->depth >= max_depth)
1613                return 0;
1614
1615        /* Now some size filtering heuristics. */
1616        trg_size = trg_entry->size;
1617        if (!trg_entry->delta) {
1618                max_size = trg_size/2 - 20;
1619                ref_depth = 1;
1620        } else {
1621                max_size = trg_entry->delta_size;
1622                ref_depth = trg->depth;
1623        }
1624        max_size = (uint64_t)max_size * (max_depth - src->depth) /
1625                                                (max_depth - ref_depth + 1);
1626        if (max_size == 0)
1627                return 0;
1628        src_size = src_entry->size;
1629        sizediff = src_size < trg_size ? trg_size - src_size : 0;
1630        if (sizediff >= max_size)
1631                return 0;
1632        if (trg_size < src_size / 32)
1633                return 0;
1634
1635        /* Load data if not already done */
1636        if (!trg->data) {
1637                read_lock();
1638                trg->data = read_sha1_file(trg_entry->idx.sha1, &type, &sz);
1639                read_unlock();
1640                if (!trg->data)
1641                        die("object %s cannot be read",
1642                            sha1_to_hex(trg_entry->idx.sha1));
1643                if (sz != trg_size)
1644                        die("object %s inconsistent object length (%lu vs %lu)",
1645                            sha1_to_hex(trg_entry->idx.sha1), sz, trg_size);
1646                *mem_usage += sz;
1647        }
1648        if (!src->data) {
1649                read_lock();
1650                src->data = read_sha1_file(src_entry->idx.sha1, &type, &sz);
1651                read_unlock();
1652                if (!src->data) {
1653                        if (src_entry->preferred_base) {
1654                                static int warned = 0;
1655                                if (!warned++)
1656                                        warning("object %s cannot be read",
1657                                                sha1_to_hex(src_entry->idx.sha1));
1658                                /*
1659                                 * Those objects are not included in the
1660                                 * resulting pack.  Be resilient and ignore
1661                                 * them if they can't be read, in case the
1662                                 * pack could be created nevertheless.
1663                                 */
1664                                return 0;
1665                        }
1666                        die("object %s cannot be read",
1667                            sha1_to_hex(src_entry->idx.sha1));
1668                }
1669                if (sz != src_size)
1670                        die("object %s inconsistent object length (%lu vs %lu)",
1671                            sha1_to_hex(src_entry->idx.sha1), sz, src_size);
1672                *mem_usage += sz;
1673        }
1674        if (!src->index) {
1675                src->index = create_delta_index(src->data, src_size);
1676                if (!src->index) {
1677                        static int warned = 0;
1678                        if (!warned++)
1679                                warning("suboptimal pack - out of memory");
1680                        return 0;
1681                }
1682                *mem_usage += sizeof_delta_index(src->index);
1683        }
1684
1685        delta_buf = create_delta(src->index, trg->data, trg_size, &delta_size, max_size);
1686        if (!delta_buf)
1687                return 0;
1688
1689        if (trg_entry->delta) {
1690                /* Prefer only shallower same-sized deltas. */
1691                if (delta_size == trg_entry->delta_size &&
1692                    src->depth + 1 >= trg->depth) {
1693                        free(delta_buf);
1694                        return 0;
1695                }
1696        }
1697
1698        /*
1699         * Handle memory allocation outside of the cache
1700         * accounting lock.  Compiler will optimize the strangeness
1701         * away when NO_PTHREADS is defined.
1702         */
1703        free(trg_entry->delta_data);
1704        cache_lock();
1705        if (trg_entry->delta_data) {
1706                delta_cache_size -= trg_entry->delta_size;
1707                trg_entry->delta_data = NULL;
1708        }
1709        if (delta_cacheable(src_size, trg_size, delta_size)) {
1710                delta_cache_size += delta_size;
1711                cache_unlock();
1712                trg_entry->delta_data = xrealloc(delta_buf, delta_size);
1713        } else {
1714                cache_unlock();
1715                free(delta_buf);
1716        }
1717
1718        trg_entry->delta = src_entry;
1719        trg_entry->delta_size = delta_size;
1720        trg->depth = src->depth + 1;
1721
1722        return 1;
1723}
1724
1725static unsigned int check_delta_limit(struct object_entry *me, unsigned int n)
1726{
1727        struct object_entry *child = me->delta_child;
1728        unsigned int m = n;
1729        while (child) {
1730                unsigned int c = check_delta_limit(child, n + 1);
1731                if (m < c)
1732                        m = c;
1733                child = child->delta_sibling;
1734        }
1735        return m;
1736}
1737
1738static unsigned long free_unpacked(struct unpacked *n)
1739{
1740        unsigned long freed_mem = sizeof_delta_index(n->index);
1741        free_delta_index(n->index);
1742        n->index = NULL;
1743        if (n->data) {
1744                freed_mem += n->entry->size;
1745                free(n->data);
1746                n->data = NULL;
1747        }
1748        n->entry = NULL;
1749        n->depth = 0;
1750        return freed_mem;
1751}
1752
1753static void find_deltas(struct object_entry **list, unsigned *list_size,
1754                        int window, int depth, unsigned *processed)
1755{
1756        uint32_t i, idx = 0, count = 0;
1757        struct unpacked *array;
1758        unsigned long mem_usage = 0;
1759
1760        array = xcalloc(window, sizeof(struct unpacked));
1761
1762        for (;;) {
1763                struct object_entry *entry;
1764                struct unpacked *n = array + idx;
1765                int j, max_depth, best_base = -1;
1766
1767                progress_lock();
1768                if (!*list_size) {
1769                        progress_unlock();
1770                        break;
1771                }
1772                entry = *list++;
1773                (*list_size)--;
1774                if (!entry->preferred_base) {
1775                        (*processed)++;
1776                        display_progress(progress_state, *processed);
1777                }
1778                progress_unlock();
1779
1780                mem_usage -= free_unpacked(n);
1781                n->entry = entry;
1782
1783                while (window_memory_limit &&
1784                       mem_usage > window_memory_limit &&
1785                       count > 1) {
1786                        uint32_t tail = (idx + window - count) % window;
1787                        mem_usage -= free_unpacked(array + tail);
1788                        count--;
1789                }
1790
1791                /* We do not compute delta to *create* objects we are not
1792                 * going to pack.
1793                 */
1794                if (entry->preferred_base)
1795                        goto next;
1796
1797                /*
1798                 * If the current object is at pack edge, take the depth the
1799                 * objects that depend on the current object into account
1800                 * otherwise they would become too deep.
1801                 */
1802                max_depth = depth;
1803                if (entry->delta_child) {
1804                        max_depth -= check_delta_limit(entry, 0);
1805                        if (max_depth <= 0)
1806                                goto next;
1807                }
1808
1809                j = window;
1810                while (--j > 0) {
1811                        int ret;
1812                        uint32_t other_idx = idx + j;
1813                        struct unpacked *m;
1814                        if (other_idx >= window)
1815                                other_idx -= window;
1816                        m = array + other_idx;
1817                        if (!m->entry)
1818                                break;
1819                        ret = try_delta(n, m, max_depth, &mem_usage);
1820                        if (ret < 0)
1821                                break;
1822                        else if (ret > 0)
1823                                best_base = other_idx;
1824                }
1825
1826                /*
1827                 * If we decided to cache the delta data, then it is best
1828                 * to compress it right away.  First because we have to do
1829                 * it anyway, and doing it here while we're threaded will
1830                 * save a lot of time in the non threaded write phase,
1831                 * as well as allow for caching more deltas within
1832                 * the same cache size limit.
1833                 * ...
1834                 * But only if not writing to stdout, since in that case
1835                 * the network is most likely throttling writes anyway,
1836                 * and therefore it is best to go to the write phase ASAP
1837                 * instead, as we can afford spending more time compressing
1838                 * between writes at that moment.
1839                 */
1840                if (entry->delta_data && !pack_to_stdout) {
1841                        entry->z_delta_size = do_compress(&entry->delta_data,
1842                                                          entry->delta_size);
1843                        cache_lock();
1844                        delta_cache_size -= entry->delta_size;
1845                        delta_cache_size += entry->z_delta_size;
1846                        cache_unlock();
1847                }
1848
1849                /* if we made n a delta, and if n is already at max
1850                 * depth, leaving it in the window is pointless.  we
1851                 * should evict it first.
1852                 */
1853                if (entry->delta && max_depth <= n->depth)
1854                        continue;
1855
1856                /*
1857                 * Move the best delta base up in the window, after the
1858                 * currently deltified object, to keep it longer.  It will
1859                 * be the first base object to be attempted next.
1860                 */
1861                if (entry->delta) {
1862                        struct unpacked swap = array[best_base];
1863                        int dist = (window + idx - best_base) % window;
1864                        int dst = best_base;
1865                        while (dist--) {
1866                                int src = (dst + 1) % window;
1867                                array[dst] = array[src];
1868                                dst = src;
1869                        }
1870                        array[dst] = swap;
1871                }
1872
1873                next:
1874                idx++;
1875                if (count + 1 < window)
1876                        count++;
1877                if (idx >= window)
1878                        idx = 0;
1879        }
1880
1881        for (i = 0; i < window; ++i) {
1882                free_delta_index(array[i].index);
1883                free(array[i].data);
1884        }
1885        free(array);
1886}
1887
1888#ifndef NO_PTHREADS
1889
1890static void try_to_free_from_threads(size_t size)
1891{
1892        read_lock();
1893        release_pack_memory(size);
1894        read_unlock();
1895}
1896
1897static try_to_free_t old_try_to_free_routine;
1898
1899/*
1900 * The main thread waits on the condition that (at least) one of the workers
1901 * has stopped working (which is indicated in the .working member of
1902 * struct thread_params).
1903 * When a work thread has completed its work, it sets .working to 0 and
1904 * signals the main thread and waits on the condition that .data_ready
1905 * becomes 1.
1906 */
1907
1908struct thread_params {
1909        pthread_t thread;
1910        struct object_entry **list;
1911        unsigned list_size;
1912        unsigned remaining;
1913        int window;
1914        int depth;
1915        int working;
1916        int data_ready;
1917        pthread_mutex_t mutex;
1918        pthread_cond_t cond;
1919        unsigned *processed;
1920};
1921
1922static pthread_cond_t progress_cond;
1923
1924/*
1925 * Mutex and conditional variable can't be statically-initialized on Windows.
1926 */
1927static void init_threaded_search(void)
1928{
1929        init_recursive_mutex(&read_mutex);
1930        pthread_mutex_init(&cache_mutex, NULL);
1931        pthread_mutex_init(&progress_mutex, NULL);
1932        pthread_cond_init(&progress_cond, NULL);
1933        old_try_to_free_routine = set_try_to_free_routine(try_to_free_from_threads);
1934}
1935
1936static void cleanup_threaded_search(void)
1937{
1938        set_try_to_free_routine(old_try_to_free_routine);
1939        pthread_cond_destroy(&progress_cond);
1940        pthread_mutex_destroy(&read_mutex);
1941        pthread_mutex_destroy(&cache_mutex);
1942        pthread_mutex_destroy(&progress_mutex);
1943}
1944
1945static void *threaded_find_deltas(void *arg)
1946{
1947        struct thread_params *me = arg;
1948
1949        while (me->remaining) {
1950                find_deltas(me->list, &me->remaining,
1951                            me->window, me->depth, me->processed);
1952
1953                progress_lock();
1954                me->working = 0;
1955                pthread_cond_signal(&progress_cond);
1956                progress_unlock();
1957
1958                /*
1959                 * We must not set ->data_ready before we wait on the
1960                 * condition because the main thread may have set it to 1
1961                 * before we get here. In order to be sure that new
1962                 * work is available if we see 1 in ->data_ready, it
1963                 * was initialized to 0 before this thread was spawned
1964                 * and we reset it to 0 right away.
1965                 */
1966                pthread_mutex_lock(&me->mutex);
1967                while (!me->data_ready)
1968                        pthread_cond_wait(&me->cond, &me->mutex);
1969                me->data_ready = 0;
1970                pthread_mutex_unlock(&me->mutex);
1971        }
1972        /* leave ->working 1 so that this doesn't get more work assigned */
1973        return NULL;
1974}
1975
1976static void ll_find_deltas(struct object_entry **list, unsigned list_size,
1977                           int window, int depth, unsigned *processed)
1978{
1979        struct thread_params *p;
1980        int i, ret, active_threads = 0;
1981
1982        init_threaded_search();
1983
1984        if (delta_search_threads <= 1) {
1985                find_deltas(list, &list_size, window, depth, processed);
1986                cleanup_threaded_search();
1987                return;
1988        }
1989        if (progress > pack_to_stdout)
1990                fprintf(stderr, "Delta compression using up to %d threads.\n",
1991                                delta_search_threads);
1992        p = xcalloc(delta_search_threads, sizeof(*p));
1993
1994        /* Partition the work amongst work threads. */
1995        for (i = 0; i < delta_search_threads; i++) {
1996                unsigned sub_size = list_size / (delta_search_threads - i);
1997
1998                /* don't use too small segments or no deltas will be found */
1999                if (sub_size < 2*window && i+1 < delta_search_threads)
2000                        sub_size = 0;
2001
2002                p[i].window = window;
2003                p[i].depth = depth;
2004                p[i].processed = processed;
2005                p[i].working = 1;
2006                p[i].data_ready = 0;
2007
2008                /* try to split chunks on "path" boundaries */
2009                while (sub_size && sub_size < list_size &&
2010                       list[sub_size]->hash &&
2011                       list[sub_size]->hash == list[sub_size-1]->hash)
2012                        sub_size++;
2013
2014                p[i].list = list;
2015                p[i].list_size = sub_size;
2016                p[i].remaining = sub_size;
2017
2018                list += sub_size;
2019                list_size -= sub_size;
2020        }
2021
2022        /* Start work threads. */
2023        for (i = 0; i < delta_search_threads; i++) {
2024                if (!p[i].list_size)
2025                        continue;
2026                pthread_mutex_init(&p[i].mutex, NULL);
2027                pthread_cond_init(&p[i].cond, NULL);
2028                ret = pthread_create(&p[i].thread, NULL,
2029                                     threaded_find_deltas, &p[i]);
2030                if (ret)
2031                        die("unable to create thread: %s", strerror(ret));
2032                active_threads++;
2033        }
2034
2035        /*
2036         * Now let's wait for work completion.  Each time a thread is done
2037         * with its work, we steal half of the remaining work from the
2038         * thread with the largest number of unprocessed objects and give
2039         * it to that newly idle thread.  This ensure good load balancing
2040         * until the remaining object list segments are simply too short
2041         * to be worth splitting anymore.
2042         */
2043        while (active_threads) {
2044                struct thread_params *target = NULL;
2045                struct thread_params *victim = NULL;
2046                unsigned sub_size = 0;
2047
2048                progress_lock();
2049                for (;;) {
2050                        for (i = 0; !target && i < delta_search_threads; i++)
2051                                if (!p[i].working)
2052                                        target = &p[i];
2053                        if (target)
2054                                break;
2055                        pthread_cond_wait(&progress_cond, &progress_mutex);
2056                }
2057
2058                for (i = 0; i < delta_search_threads; i++)
2059                        if (p[i].remaining > 2*window &&
2060                            (!victim || victim->remaining < p[i].remaining))
2061                                victim = &p[i];
2062                if (victim) {
2063                        sub_size = victim->remaining / 2;
2064                        list = victim->list + victim->list_size - sub_size;
2065                        while (sub_size && list[0]->hash &&
2066                               list[0]->hash == list[-1]->hash) {
2067                                list++;
2068                                sub_size--;
2069                        }
2070                        if (!sub_size) {
2071                                /*
2072                                 * It is possible for some "paths" to have
2073                                 * so many objects that no hash boundary
2074                                 * might be found.  Let's just steal the
2075                                 * exact half in that case.
2076                                 */
2077                                sub_size = victim->remaining / 2;
2078                                list -= sub_size;
2079                        }
2080                        target->list = list;
2081                        victim->list_size -= sub_size;
2082                        victim->remaining -= sub_size;
2083                }
2084                target->list_size = sub_size;
2085                target->remaining = sub_size;
2086                target->working = 1;
2087                progress_unlock();
2088
2089                pthread_mutex_lock(&target->mutex);
2090                target->data_ready = 1;
2091                pthread_cond_signal(&target->cond);
2092                pthread_mutex_unlock(&target->mutex);
2093
2094                if (!sub_size) {
2095                        pthread_join(target->thread, NULL);
2096                        pthread_cond_destroy(&target->cond);
2097                        pthread_mutex_destroy(&target->mutex);
2098                        active_threads--;
2099                }
2100        }
2101        cleanup_threaded_search();
2102        free(p);
2103}
2104
2105#else
2106#define ll_find_deltas(l, s, w, d, p)   find_deltas(l, &s, w, d, p)
2107#endif
2108
2109static int add_ref_tag(const char *path, const struct object_id *oid, int flag, void *cb_data)
2110{
2111        struct object_id peeled;
2112
2113        if (starts_with(path, "refs/tags/") && /* is a tag? */
2114            !peel_ref(path, peeled.hash)    && /* peelable? */
2115            packlist_find(&to_pack, peeled.hash, NULL))      /* object packed? */
2116                add_object_entry(oid->hash, OBJ_TAG, NULL, 0);
2117        return 0;
2118}
2119
2120static void prepare_pack(int window, int depth)
2121{
2122        struct object_entry **delta_list;
2123        uint32_t i, nr_deltas;
2124        unsigned n;
2125
2126        get_object_details();
2127
2128        /*
2129         * If we're locally repacking then we need to be doubly careful
2130         * from now on in order to make sure no stealth corruption gets
2131         * propagated to the new pack.  Clients receiving streamed packs
2132         * should validate everything they get anyway so no need to incur
2133         * the additional cost here in that case.
2134         */
2135        if (!pack_to_stdout)
2136                do_check_packed_object_crc = 1;
2137
2138        if (!to_pack.nr_objects || !window || !depth)
2139                return;
2140
2141        ALLOC_ARRAY(delta_list, to_pack.nr_objects);
2142        nr_deltas = n = 0;
2143
2144        for (i = 0; i < to_pack.nr_objects; i++) {
2145                struct object_entry *entry = to_pack.objects + i;
2146
2147                if (entry->delta)
2148                        /* This happens if we decided to reuse existing
2149                         * delta from a pack.  "reuse_delta &&" is implied.
2150                         */
2151                        continue;
2152
2153                if (entry->size < 50)
2154                        continue;
2155
2156                if (entry->no_try_delta)
2157                        continue;
2158
2159                if (!entry->preferred_base) {
2160                        nr_deltas++;
2161                        if (entry->type < 0)
2162                                die("unable to get type of object %s",
2163                                    sha1_to_hex(entry->idx.sha1));
2164                } else {
2165                        if (entry->type < 0) {
2166                                /*
2167                                 * This object is not found, but we
2168                                 * don't have to include it anyway.
2169                                 */
2170                                continue;
2171                        }
2172                }
2173
2174                delta_list[n++] = entry;
2175        }
2176
2177        if (nr_deltas && n > 1) {
2178                unsigned nr_done = 0;
2179                if (progress)
2180                        progress_state = start_progress(_("Compressing objects"),
2181                                                        nr_deltas);
2182                qsort(delta_list, n, sizeof(*delta_list), type_size_sort);
2183                ll_find_deltas(delta_list, n, window+1, depth, &nr_done);
2184                stop_progress(&progress_state);
2185                if (nr_done != nr_deltas)
2186                        die("inconsistency with delta count");
2187        }
2188        free(delta_list);
2189}
2190
2191static int git_pack_config(const char *k, const char *v, void *cb)
2192{
2193        if (!strcmp(k, "pack.window")) {
2194                window = git_config_int(k, v);
2195                return 0;
2196        }
2197        if (!strcmp(k, "pack.windowmemory")) {
2198                window_memory_limit = git_config_ulong(k, v);
2199                return 0;
2200        }
2201        if (!strcmp(k, "pack.depth")) {
2202                depth = git_config_int(k, v);
2203                return 0;
2204        }
2205        if (!strcmp(k, "pack.compression")) {
2206                int level = git_config_int(k, v);
2207                if (level == -1)
2208                        level = Z_DEFAULT_COMPRESSION;
2209                else if (level < 0 || level > Z_BEST_COMPRESSION)
2210                        die("bad pack compression level %d", level);
2211                pack_compression_level = level;
2212                pack_compression_seen = 1;
2213                return 0;
2214        }
2215        if (!strcmp(k, "pack.deltacachesize")) {
2216                max_delta_cache_size = git_config_int(k, v);
2217                return 0;
2218        }
2219        if (!strcmp(k, "pack.deltacachelimit")) {
2220                cache_max_small_delta_size = git_config_int(k, v);
2221                return 0;
2222        }
2223        if (!strcmp(k, "pack.writebitmaphashcache")) {
2224                if (git_config_bool(k, v))
2225                        write_bitmap_options |= BITMAP_OPT_HASH_CACHE;
2226                else
2227                        write_bitmap_options &= ~BITMAP_OPT_HASH_CACHE;
2228        }
2229        if (!strcmp(k, "pack.usebitmaps")) {
2230                use_bitmap_index = git_config_bool(k, v);
2231                return 0;
2232        }
2233        if (!strcmp(k, "pack.threads")) {
2234                delta_search_threads = git_config_int(k, v);
2235                if (delta_search_threads < 0)
2236                        die("invalid number of threads specified (%d)",
2237                            delta_search_threads);
2238#ifdef NO_PTHREADS
2239                if (delta_search_threads != 1)
2240                        warning("no threads support, ignoring %s", k);
2241#endif
2242                return 0;
2243        }
2244        if (!strcmp(k, "pack.indexversion")) {
2245                pack_idx_opts.version = git_config_int(k, v);
2246                if (pack_idx_opts.version > 2)
2247                        die("bad pack.indexversion=%"PRIu32,
2248                            pack_idx_opts.version);
2249                return 0;
2250        }
2251        return git_default_config(k, v, cb);
2252}
2253
2254static void read_object_list_from_stdin(void)
2255{
2256        char line[40 + 1 + PATH_MAX + 2];
2257        unsigned char sha1[20];
2258
2259        for (;;) {
2260                if (!fgets(line, sizeof(line), stdin)) {
2261                        if (feof(stdin))
2262                                break;
2263                        if (!ferror(stdin))
2264                                die("fgets returned NULL, not EOF, not error!");
2265                        if (errno != EINTR)
2266                                die_errno("fgets");
2267                        clearerr(stdin);
2268                        continue;
2269                }
2270                if (line[0] == '-') {
2271                        if (get_sha1_hex(line+1, sha1))
2272                                die("expected edge sha1, got garbage:\n %s",
2273                                    line);
2274                        add_preferred_base(sha1);
2275                        continue;
2276                }
2277                if (get_sha1_hex(line, sha1))
2278                        die("expected sha1, got garbage:\n %s", line);
2279
2280                add_preferred_base_object(line+41);
2281                add_object_entry(sha1, 0, line+41, 0);
2282        }
2283}
2284
2285#define OBJECT_ADDED (1u<<20)
2286
2287static void show_commit(struct commit *commit, void *data)
2288{
2289        add_object_entry(commit->object.oid.hash, OBJ_COMMIT, NULL, 0);
2290        commit->object.flags |= OBJECT_ADDED;
2291
2292        if (write_bitmap_index)
2293                index_commit_for_bitmap(commit);
2294}
2295
2296static void show_object(struct object *obj, const char *name, void *data)
2297{
2298        add_preferred_base_object(name);
2299        add_object_entry(obj->oid.hash, obj->type, name, 0);
2300        obj->flags |= OBJECT_ADDED;
2301}
2302
2303static void show_edge(struct commit *commit)
2304{
2305        add_preferred_base(commit->object.oid.hash);
2306}
2307
2308struct in_pack_object {
2309        off_t offset;
2310        struct object *object;
2311};
2312
2313struct in_pack {
2314        int alloc;
2315        int nr;
2316        struct in_pack_object *array;
2317};
2318
2319static void mark_in_pack_object(struct object *object, struct packed_git *p, struct in_pack *in_pack)
2320{
2321        in_pack->array[in_pack->nr].offset = find_pack_entry_one(object->oid.hash, p);
2322        in_pack->array[in_pack->nr].object = object;
2323        in_pack->nr++;
2324}
2325
2326/*
2327 * Compare the objects in the offset order, in order to emulate the
2328 * "git rev-list --objects" output that produced the pack originally.
2329 */
2330static int ofscmp(const void *a_, const void *b_)
2331{
2332        struct in_pack_object *a = (struct in_pack_object *)a_;
2333        struct in_pack_object *b = (struct in_pack_object *)b_;
2334
2335        if (a->offset < b->offset)
2336                return -1;
2337        else if (a->offset > b->offset)
2338                return 1;
2339        else
2340                return oidcmp(&a->object->oid, &b->object->oid);
2341}
2342
2343static void add_objects_in_unpacked_packs(struct rev_info *revs)
2344{
2345        struct packed_git *p;
2346        struct in_pack in_pack;
2347        uint32_t i;
2348
2349        memset(&in_pack, 0, sizeof(in_pack));
2350
2351        for (p = packed_git; p; p = p->next) {
2352                const unsigned char *sha1;
2353                struct object *o;
2354
2355                if (!p->pack_local || p->pack_keep)
2356                        continue;
2357                if (open_pack_index(p))
2358                        die("cannot open pack index");
2359
2360                ALLOC_GROW(in_pack.array,
2361                           in_pack.nr + p->num_objects,
2362                           in_pack.alloc);
2363
2364                for (i = 0; i < p->num_objects; i++) {
2365                        sha1 = nth_packed_object_sha1(p, i);
2366                        o = lookup_unknown_object(sha1);
2367                        if (!(o->flags & OBJECT_ADDED))
2368                                mark_in_pack_object(o, p, &in_pack);
2369                        o->flags |= OBJECT_ADDED;
2370                }
2371        }
2372
2373        if (in_pack.nr) {
2374                qsort(in_pack.array, in_pack.nr, sizeof(in_pack.array[0]),
2375                      ofscmp);
2376                for (i = 0; i < in_pack.nr; i++) {
2377                        struct object *o = in_pack.array[i].object;
2378                        add_object_entry(o->oid.hash, o->type, "", 0);
2379                }
2380        }
2381        free(in_pack.array);
2382}
2383
2384static int has_sha1_pack_kept_or_nonlocal(const unsigned char *sha1)
2385{
2386        static struct packed_git *last_found = (void *)1;
2387        struct packed_git *p;
2388
2389        p = (last_found != (void *)1) ? last_found : packed_git;
2390
2391        while (p) {
2392                if ((!p->pack_local || p->pack_keep) &&
2393                        find_pack_entry_one(sha1, p)) {
2394                        last_found = p;
2395                        return 1;
2396                }
2397                if (p == last_found)
2398                        p = packed_git;
2399                else
2400                        p = p->next;
2401                if (p == last_found)
2402                        p = p->next;
2403        }
2404        return 0;
2405}
2406
2407/*
2408 * Store a list of sha1s that are should not be discarded
2409 * because they are either written too recently, or are
2410 * reachable from another object that was.
2411 *
2412 * This is filled by get_object_list.
2413 */
2414static struct sha1_array recent_objects;
2415
2416static int loosened_object_can_be_discarded(const unsigned char *sha1,
2417                                            unsigned long mtime)
2418{
2419        if (!unpack_unreachable_expiration)
2420                return 0;
2421        if (mtime > unpack_unreachable_expiration)
2422                return 0;
2423        if (sha1_array_lookup(&recent_objects, sha1) >= 0)
2424                return 0;
2425        return 1;
2426}
2427
2428static void loosen_unused_packed_objects(struct rev_info *revs)
2429{
2430        struct packed_git *p;
2431        uint32_t i;
2432        const unsigned char *sha1;
2433
2434        for (p = packed_git; p; p = p->next) {
2435                if (!p->pack_local || p->pack_keep)
2436                        continue;
2437
2438                if (open_pack_index(p))
2439                        die("cannot open pack index");
2440
2441                for (i = 0; i < p->num_objects; i++) {
2442                        sha1 = nth_packed_object_sha1(p, i);
2443                        if (!packlist_find(&to_pack, sha1, NULL) &&
2444                            !has_sha1_pack_kept_or_nonlocal(sha1) &&
2445                            !loosened_object_can_be_discarded(sha1, p->mtime))
2446                                if (force_object_loose(sha1, p->mtime))
2447                                        die("unable to force loose object");
2448                }
2449        }
2450}
2451
2452/*
2453 * This tracks any options which a reader of the pack might
2454 * not understand, and which would therefore prevent blind reuse
2455 * of what we have on disk.
2456 */
2457static int pack_options_allow_reuse(void)
2458{
2459        return allow_ofs_delta;
2460}
2461
2462static int get_object_list_from_bitmap(struct rev_info *revs)
2463{
2464        if (prepare_bitmap_walk(revs) < 0)
2465                return -1;
2466
2467        if (pack_options_allow_reuse() &&
2468            !reuse_partial_packfile_from_bitmap(
2469                        &reuse_packfile,
2470                        &reuse_packfile_objects,
2471                        &reuse_packfile_offset)) {
2472                assert(reuse_packfile_objects);
2473                nr_result += reuse_packfile_objects;
2474                display_progress(progress_state, nr_result);
2475        }
2476
2477        traverse_bitmap_commit_list(&add_object_entry_from_bitmap);
2478        return 0;
2479}
2480
2481static void record_recent_object(struct object *obj,
2482                                 const char *name,
2483                                 void *data)
2484{
2485        sha1_array_append(&recent_objects, obj->oid.hash);
2486}
2487
2488static void record_recent_commit(struct commit *commit, void *data)
2489{
2490        sha1_array_append(&recent_objects, commit->object.oid.hash);
2491}
2492
2493static void get_object_list(int ac, const char **av)
2494{
2495        struct rev_info revs;
2496        char line[1000];
2497        int flags = 0;
2498
2499        init_revisions(&revs, NULL);
2500        save_commit_buffer = 0;
2501        setup_revisions(ac, av, &revs, NULL);
2502
2503        /* make sure shallows are read */
2504        is_repository_shallow();
2505
2506        while (fgets(line, sizeof(line), stdin) != NULL) {
2507                int len = strlen(line);
2508                if (len && line[len - 1] == '\n')
2509                        line[--len] = 0;
2510                if (!len)
2511                        break;
2512                if (*line == '-') {
2513                        if (!strcmp(line, "--not")) {
2514                                flags ^= UNINTERESTING;
2515                                write_bitmap_index = 0;
2516                                continue;
2517                        }
2518                        if (starts_with(line, "--shallow ")) {
2519                                unsigned char sha1[20];
2520                                if (get_sha1_hex(line + 10, sha1))
2521                                        die("not an SHA-1 '%s'", line + 10);
2522                                register_shallow(sha1);
2523                                use_bitmap_index = 0;
2524                                continue;
2525                        }
2526                        die("not a rev '%s'", line);
2527                }
2528                if (handle_revision_arg(line, &revs, flags, REVARG_CANNOT_BE_FILENAME))
2529                        die("bad revision '%s'", line);
2530        }
2531
2532        if (use_bitmap_index && !get_object_list_from_bitmap(&revs))
2533                return;
2534
2535        if (prepare_revision_walk(&revs))
2536                die("revision walk setup failed");
2537        mark_edges_uninteresting(&revs, show_edge);
2538        traverse_commit_list(&revs, show_commit, show_object, NULL);
2539
2540        if (unpack_unreachable_expiration) {
2541                revs.ignore_missing_links = 1;
2542                if (add_unseen_recent_objects_to_traversal(&revs,
2543                                unpack_unreachable_expiration))
2544                        die("unable to add recent objects");
2545                if (prepare_revision_walk(&revs))
2546                        die("revision walk setup failed");
2547                traverse_commit_list(&revs, record_recent_commit,
2548                                     record_recent_object, NULL);
2549        }
2550
2551        if (keep_unreachable)
2552                add_objects_in_unpacked_packs(&revs);
2553        if (unpack_unreachable)
2554                loosen_unused_packed_objects(&revs);
2555
2556        sha1_array_clear(&recent_objects);
2557}
2558
2559static int option_parse_index_version(const struct option *opt,
2560                                      const char *arg, int unset)
2561{
2562        char *c;
2563        const char *val = arg;
2564        pack_idx_opts.version = strtoul(val, &c, 10);
2565        if (pack_idx_opts.version > 2)
2566                die(_("unsupported index version %s"), val);
2567        if (*c == ',' && c[1])
2568                pack_idx_opts.off32_limit = strtoul(c+1, &c, 0);
2569        if (*c || pack_idx_opts.off32_limit & 0x80000000)
2570                die(_("bad index version '%s'"), val);
2571        return 0;
2572}
2573
2574static int option_parse_unpack_unreachable(const struct option *opt,
2575                                           const char *arg, int unset)
2576{
2577        if (unset) {
2578                unpack_unreachable = 0;
2579                unpack_unreachable_expiration = 0;
2580        }
2581        else {
2582                unpack_unreachable = 1;
2583                if (arg)
2584                        unpack_unreachable_expiration = approxidate(arg);
2585        }
2586        return 0;
2587}
2588
2589int cmd_pack_objects(int argc, const char **argv, const char *prefix)
2590{
2591        int use_internal_rev_list = 0;
2592        int thin = 0;
2593        int shallow = 0;
2594        int all_progress_implied = 0;
2595        struct argv_array rp = ARGV_ARRAY_INIT;
2596        int rev_list_unpacked = 0, rev_list_all = 0, rev_list_reflog = 0;
2597        int rev_list_index = 0;
2598        struct option pack_objects_options[] = {
2599                OPT_SET_INT('q', "quiet", &progress,
2600                            N_("do not show progress meter"), 0),
2601                OPT_SET_INT(0, "progress", &progress,
2602                            N_("show progress meter"), 1),
2603                OPT_SET_INT(0, "all-progress", &progress,
2604                            N_("show progress meter during object writing phase"), 2),
2605                OPT_BOOL(0, "all-progress-implied",
2606                         &all_progress_implied,
2607                         N_("similar to --all-progress when progress meter is shown")),
2608                { OPTION_CALLBACK, 0, "index-version", NULL, N_("version[,offset]"),
2609                  N_("write the pack index file in the specified idx format version"),
2610                  0, option_parse_index_version },
2611                OPT_MAGNITUDE(0, "max-pack-size", &pack_size_limit,
2612                              N_("maximum size of each output pack file")),
2613                OPT_BOOL(0, "local", &local,
2614                         N_("ignore borrowed objects from alternate object store")),
2615                OPT_BOOL(0, "incremental", &incremental,
2616                         N_("ignore packed objects")),
2617                OPT_INTEGER(0, "window", &window,
2618                            N_("limit pack window by objects")),
2619                OPT_MAGNITUDE(0, "window-memory", &window_memory_limit,
2620                              N_("limit pack window by memory in addition to object limit")),
2621                OPT_INTEGER(0, "depth", &depth,
2622                            N_("maximum length of delta chain allowed in the resulting pack")),
2623                OPT_BOOL(0, "reuse-delta", &reuse_delta,
2624                         N_("reuse existing deltas")),
2625                OPT_BOOL(0, "reuse-object", &reuse_object,
2626                         N_("reuse existing objects")),
2627                OPT_BOOL(0, "delta-base-offset", &allow_ofs_delta,
2628                         N_("use OFS_DELTA objects")),
2629                OPT_INTEGER(0, "threads", &delta_search_threads,
2630                            N_("use threads when searching for best delta matches")),
2631                OPT_BOOL(0, "non-empty", &non_empty,
2632                         N_("do not create an empty pack output")),
2633                OPT_BOOL(0, "revs", &use_internal_rev_list,
2634                         N_("read revision arguments from standard input")),
2635                { OPTION_SET_INT, 0, "unpacked", &rev_list_unpacked, NULL,
2636                  N_("limit the objects to those that are not yet packed"),
2637                  PARSE_OPT_NOARG | PARSE_OPT_NONEG, NULL, 1 },
2638                { OPTION_SET_INT, 0, "all", &rev_list_all, NULL,
2639                  N_("include objects reachable from any reference"),
2640                  PARSE_OPT_NOARG | PARSE_OPT_NONEG, NULL, 1 },
2641                { OPTION_SET_INT, 0, "reflog", &rev_list_reflog, NULL,
2642                  N_("include objects referred by reflog entries"),
2643                  PARSE_OPT_NOARG | PARSE_OPT_NONEG, NULL, 1 },
2644                { OPTION_SET_INT, 0, "indexed-objects", &rev_list_index, NULL,
2645                  N_("include objects referred to by the index"),
2646                  PARSE_OPT_NOARG | PARSE_OPT_NONEG, NULL, 1 },
2647                OPT_BOOL(0, "stdout", &pack_to_stdout,
2648                         N_("output pack to stdout")),
2649                OPT_BOOL(0, "include-tag", &include_tag,
2650                         N_("include tag objects that refer to objects to be packed")),
2651                OPT_BOOL(0, "keep-unreachable", &keep_unreachable,
2652                         N_("keep unreachable objects")),
2653                { OPTION_CALLBACK, 0, "unpack-unreachable", NULL, N_("time"),
2654                  N_("unpack unreachable objects newer than <time>"),
2655                  PARSE_OPT_OPTARG, option_parse_unpack_unreachable },
2656                OPT_BOOL(0, "thin", &thin,
2657                         N_("create thin packs")),
2658                OPT_BOOL(0, "shallow", &shallow,
2659                         N_("create packs suitable for shallow fetches")),
2660                OPT_BOOL(0, "honor-pack-keep", &ignore_packed_keep,
2661                         N_("ignore packs that have companion .keep file")),
2662                OPT_INTEGER(0, "compression", &pack_compression_level,
2663                            N_("pack compression level")),
2664                OPT_SET_INT(0, "keep-true-parents", &grafts_replace_parents,
2665                            N_("do not hide commits by grafts"), 0),
2666                OPT_BOOL(0, "use-bitmap-index", &use_bitmap_index,
2667                         N_("use a bitmap index if available to speed up counting objects")),
2668                OPT_BOOL(0, "write-bitmap-index", &write_bitmap_index,
2669                         N_("write a bitmap index together with the pack index")),
2670                OPT_END(),
2671        };
2672
2673        check_replace_refs = 0;
2674
2675        reset_pack_idx_option(&pack_idx_opts);
2676        git_config(git_pack_config, NULL);
2677        if (!pack_compression_seen && core_compression_seen)
2678                pack_compression_level = core_compression_level;
2679
2680        progress = isatty(2);
2681        argc = parse_options(argc, argv, prefix, pack_objects_options,
2682                             pack_usage, 0);
2683
2684        if (argc) {
2685                base_name = argv[0];
2686                argc--;
2687        }
2688        if (pack_to_stdout != !base_name || argc)
2689                usage_with_options(pack_usage, pack_objects_options);
2690
2691        argv_array_push(&rp, "pack-objects");
2692        if (thin) {
2693                use_internal_rev_list = 1;
2694                argv_array_push(&rp, shallow
2695                                ? "--objects-edge-aggressive"
2696                                : "--objects-edge");
2697        } else
2698                argv_array_push(&rp, "--objects");
2699
2700        if (rev_list_all) {
2701                use_internal_rev_list = 1;
2702                argv_array_push(&rp, "--all");
2703        }
2704        if (rev_list_reflog) {
2705                use_internal_rev_list = 1;
2706                argv_array_push(&rp, "--reflog");
2707        }
2708        if (rev_list_index) {
2709                use_internal_rev_list = 1;
2710                argv_array_push(&rp, "--indexed-objects");
2711        }
2712        if (rev_list_unpacked) {
2713                use_internal_rev_list = 1;
2714                argv_array_push(&rp, "--unpacked");
2715        }
2716
2717        if (!reuse_object)
2718                reuse_delta = 0;
2719        if (pack_compression_level == -1)
2720                pack_compression_level = Z_DEFAULT_COMPRESSION;
2721        else if (pack_compression_level < 0 || pack_compression_level > Z_BEST_COMPRESSION)
2722                die("bad pack compression level %d", pack_compression_level);
2723
2724        if (!delta_search_threads)      /* --threads=0 means autodetect */
2725                delta_search_threads = online_cpus();
2726
2727#ifdef NO_PTHREADS
2728        if (delta_search_threads != 1)
2729                warning("no threads support, ignoring --threads");
2730#endif
2731        if (!pack_to_stdout && !pack_size_limit)
2732                pack_size_limit = pack_size_limit_cfg;
2733        if (pack_to_stdout && pack_size_limit)
2734                die("--max-pack-size cannot be used to build a pack for transfer.");
2735        if (pack_size_limit && pack_size_limit < 1024*1024) {
2736                warning("minimum pack size limit is 1 MiB");
2737                pack_size_limit = 1024*1024;
2738        }
2739
2740        if (!pack_to_stdout && thin)
2741                die("--thin cannot be used to build an indexable pack.");
2742
2743        if (keep_unreachable && unpack_unreachable)
2744                die("--keep-unreachable and --unpack-unreachable are incompatible.");
2745        if (!rev_list_all || !rev_list_reflog || !rev_list_index)
2746                unpack_unreachable_expiration = 0;
2747
2748        if (!use_internal_rev_list || !pack_to_stdout || is_repository_shallow())
2749                use_bitmap_index = 0;
2750
2751        if (pack_to_stdout || !rev_list_all)
2752                write_bitmap_index = 0;
2753
2754        if (progress && all_progress_implied)
2755                progress = 2;
2756
2757        prepare_packed_git();
2758
2759        if (progress)
2760                progress_state = start_progress(_("Counting objects"), 0);
2761        if (!use_internal_rev_list)
2762                read_object_list_from_stdin();
2763        else {
2764                get_object_list(rp.argc, rp.argv);
2765                argv_array_clear(&rp);
2766        }
2767        cleanup_preferred_base();
2768        if (include_tag && nr_result)
2769                for_each_ref(add_ref_tag, NULL);
2770        stop_progress(&progress_state);
2771
2772        if (non_empty && !nr_result)
2773                return 0;
2774        if (nr_result)
2775                prepare_pack(window, depth);
2776        write_pack_file();
2777        if (progress)
2778                fprintf(stderr, "Total %"PRIu32" (delta %"PRIu32"),"
2779                        " reused %"PRIu32" (delta %"PRIu32")\n",
2780                        written, written_delta, reused, reused_delta);
2781        return 0;
2782}