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