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