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