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