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