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