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