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