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