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