builtin-pack-objects.con commit git-p4: Fix the sorting of changelists when cloning a Perforce repository. (7da660f)
   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 "csum-file.h"
  12#include "tree-walk.h"
  13#include "diff.h"
  14#include "revision.h"
  15#include "list-objects.h"
  16#include "progress.h"
  17
  18static const char pack_usage[] = "\
  19git-pack-objects [{ -q | --progress | --all-progress }] \n\
  20        [--max-pack-size=N] [--local] [--incremental] \n\
  21        [--window=N] [--window-memory=N] [--depth=N] \n\
  22        [--no-reuse-delta] [--no-reuse-object] [--delta-base-offset] \n\
  23        [--non-empty] [--revs [--unpacked | --all]*] [--reflog] \n\
  24        [--stdout | base-name] [<ref-list | <object-list]";
  25
  26struct object_entry {
  27        struct pack_idx_entry idx;
  28        unsigned long size;     /* uncompressed size */
  29        struct packed_git *in_pack;     /* already in pack */
  30        off_t in_pack_offset;
  31        struct object_entry *delta;     /* delta base object */
  32        struct object_entry *delta_child; /* deltified objects who bases me */
  33        struct object_entry *delta_sibling; /* other deltified objects who
  34                                             * uses the same base as me
  35                                             */
  36        void *delta_data;       /* cached delta (uncompressed) */
  37        unsigned long delta_size;       /* delta data size (uncompressed) */
  38        unsigned int hash;      /* name hint hash */
  39        enum object_type type;
  40        enum object_type in_pack_type;  /* could be delta */
  41        unsigned char in_pack_header_size;
  42        unsigned char preferred_base; /* we do not pack this, but is available
  43                                       * to be used as the base object to delta
  44                                       * objects against.
  45                                       */
  46        unsigned char no_try_delta;
  47};
  48
  49/*
  50 * Objects we are going to pack are collected in objects array (dynamically
  51 * expanded).  nr_objects & nr_alloc controls this array.  They are stored
  52 * in the order we see -- typically rev-list --objects order that gives us
  53 * nice "minimum seek" order.
  54 */
  55static struct object_entry *objects;
  56static struct object_entry **written_list;
  57static uint32_t nr_objects, nr_alloc, nr_result, nr_written;
  58
  59static int non_empty;
  60static int no_reuse_delta, no_reuse_object;
  61static int local;
  62static int incremental;
  63static int allow_ofs_delta;
  64static const char *pack_tmp_name, *idx_tmp_name;
  65static char tmpname[PATH_MAX];
  66static const char *base_name;
  67static int progress = 1;
  68static int window = 10;
  69static uint32_t pack_size_limit;
  70static int depth = 50;
  71static int pack_to_stdout;
  72static int num_preferred_base;
  73static struct progress progress_state;
  74static int pack_compression_level = Z_DEFAULT_COMPRESSION;
  75static int pack_compression_seen;
  76
  77static unsigned long delta_cache_size = 0;
  78static unsigned long max_delta_cache_size = 0;
  79static unsigned long cache_max_small_delta_size = 1000;
  80
  81static unsigned long window_memory_usage = 0;
  82static unsigned long window_memory_limit = 0;
  83
  84/*
  85 * The object names in objects array are hashed with this hashtable,
  86 * to help looking up the entry by object name.
  87 * This hashtable is built after all the objects are seen.
  88 */
  89static int *object_ix;
  90static int object_ix_hashsz;
  91
  92/*
  93 * Pack index for existing packs give us easy access to the offsets into
  94 * corresponding pack file where each object's data starts, but the entries
  95 * do not store the size of the compressed representation (uncompressed
  96 * size is easily available by examining the pack entry header).  It is
  97 * also rather expensive to find the sha1 for an object given its offset.
  98 *
  99 * We build a hashtable of existing packs (pack_revindex), and keep reverse
 100 * index here -- pack index file is sorted by object name mapping to offset;
 101 * this pack_revindex[].revindex array is a list of offset/index_nr pairs
 102 * ordered by offset, so if you know the offset of an object, next offset
 103 * is where its packed representation ends and the index_nr can be used to
 104 * get the object sha1 from the main index.
 105 */
 106struct revindex_entry {
 107        off_t offset;
 108        unsigned int nr;
 109};
 110struct pack_revindex {
 111        struct packed_git *p;
 112        struct revindex_entry *revindex;
 113};
 114static struct  pack_revindex *pack_revindex;
 115static int pack_revindex_hashsz;
 116
 117/*
 118 * stats
 119 */
 120static uint32_t written, written_delta;
 121static uint32_t reused, reused_delta;
 122
 123static int pack_revindex_ix(struct packed_git *p)
 124{
 125        unsigned long ui = (unsigned long)p;
 126        int i;
 127
 128        ui = ui ^ (ui >> 16); /* defeat structure alignment */
 129        i = (int)(ui % pack_revindex_hashsz);
 130        while (pack_revindex[i].p) {
 131                if (pack_revindex[i].p == p)
 132                        return i;
 133                if (++i == pack_revindex_hashsz)
 134                        i = 0;
 135        }
 136        return -1 - i;
 137}
 138
 139static void prepare_pack_ix(void)
 140{
 141        int num;
 142        struct packed_git *p;
 143        for (num = 0, p = packed_git; p; p = p->next)
 144                num++;
 145        if (!num)
 146                return;
 147        pack_revindex_hashsz = num * 11;
 148        pack_revindex = xcalloc(sizeof(*pack_revindex), pack_revindex_hashsz);
 149        for (p = packed_git; p; p = p->next) {
 150                num = pack_revindex_ix(p);
 151                num = - 1 - num;
 152                pack_revindex[num].p = p;
 153        }
 154        /* revindex elements are lazily initialized */
 155}
 156
 157static int cmp_offset(const void *a_, const void *b_)
 158{
 159        const struct revindex_entry *a = a_;
 160        const struct revindex_entry *b = b_;
 161        return (a->offset < b->offset) ? -1 : (a->offset > b->offset) ? 1 : 0;
 162}
 163
 164/*
 165 * Ordered list of offsets of objects in the pack.
 166 */
 167static void prepare_pack_revindex(struct pack_revindex *rix)
 168{
 169        struct packed_git *p = rix->p;
 170        int num_ent = p->num_objects;
 171        int i;
 172        const char *index = p->index_data;
 173
 174        rix->revindex = xmalloc(sizeof(*rix->revindex) * (num_ent + 1));
 175        index += 4 * 256;
 176
 177        if (p->index_version > 1) {
 178                const uint32_t *off_32 =
 179                        (uint32_t *)(index + 8 + p->num_objects * (20 + 4));
 180                const uint32_t *off_64 = off_32 + p->num_objects;
 181                for (i = 0; i < num_ent; i++) {
 182                        uint32_t off = ntohl(*off_32++);
 183                        if (!(off & 0x80000000)) {
 184                                rix->revindex[i].offset = off;
 185                        } else {
 186                                rix->revindex[i].offset =
 187                                        ((uint64_t)ntohl(*off_64++)) << 32;
 188                                rix->revindex[i].offset |=
 189                                        ntohl(*off_64++);
 190                        }
 191                        rix->revindex[i].nr = i;
 192                }
 193        } else {
 194                for (i = 0; i < num_ent; i++) {
 195                        uint32_t hl = *((uint32_t *)(index + 24 * i));
 196                        rix->revindex[i].offset = ntohl(hl);
 197                        rix->revindex[i].nr = i;
 198                }
 199        }
 200
 201        /* This knows the pack format -- the 20-byte trailer
 202         * follows immediately after the last object data.
 203         */
 204        rix->revindex[num_ent].offset = p->pack_size - 20;
 205        rix->revindex[num_ent].nr = -1;
 206        qsort(rix->revindex, num_ent, sizeof(*rix->revindex), cmp_offset);
 207}
 208
 209static struct revindex_entry * find_packed_object(struct packed_git *p,
 210                                                  off_t ofs)
 211{
 212        int num;
 213        int lo, hi;
 214        struct pack_revindex *rix;
 215        struct revindex_entry *revindex;
 216        num = pack_revindex_ix(p);
 217        if (num < 0)
 218                die("internal error: pack revindex uninitialized");
 219        rix = &pack_revindex[num];
 220        if (!rix->revindex)
 221                prepare_pack_revindex(rix);
 222        revindex = rix->revindex;
 223        lo = 0;
 224        hi = p->num_objects + 1;
 225        do {
 226                int mi = (lo + hi) / 2;
 227                if (revindex[mi].offset == ofs) {
 228                        return revindex + mi;
 229                }
 230                else if (ofs < revindex[mi].offset)
 231                        hi = mi;
 232                else
 233                        lo = mi + 1;
 234        } while (lo < hi);
 235        die("internal error: pack revindex corrupt");
 236}
 237
 238static const unsigned char *find_packed_object_name(struct packed_git *p,
 239                                                    off_t ofs)
 240{
 241        struct revindex_entry *entry = find_packed_object(p, ofs);
 242        return nth_packed_object_sha1(p, entry->nr);
 243}
 244
 245static void *delta_against(void *buf, unsigned long size, struct object_entry *entry)
 246{
 247        unsigned long othersize, delta_size;
 248        enum object_type type;
 249        void *otherbuf = read_sha1_file(entry->delta->idx.sha1, &type, &othersize);
 250        void *delta_buf;
 251
 252        if (!otherbuf)
 253                die("unable to read %s", sha1_to_hex(entry->delta->idx.sha1));
 254        delta_buf = diff_delta(otherbuf, othersize,
 255                               buf, size, &delta_size, 0);
 256        if (!delta_buf || delta_size != entry->delta_size)
 257                die("delta size changed");
 258        free(buf);
 259        free(otherbuf);
 260        return delta_buf;
 261}
 262
 263/*
 264 * The per-object header is a pretty dense thing, which is
 265 *  - first byte: low four bits are "size", then three bits of "type",
 266 *    and the high bit is "size continues".
 267 *  - each byte afterwards: low seven bits are size continuation,
 268 *    with the high bit being "size continues"
 269 */
 270static int encode_header(enum object_type type, unsigned long size, unsigned char *hdr)
 271{
 272        int n = 1;
 273        unsigned char c;
 274
 275        if (type < OBJ_COMMIT || type > OBJ_REF_DELTA)
 276                die("bad type %d", type);
 277
 278        c = (type << 4) | (size & 15);
 279        size >>= 4;
 280        while (size) {
 281                *hdr++ = c | 0x80;
 282                c = size & 0x7f;
 283                size >>= 7;
 284                n++;
 285        }
 286        *hdr = c;
 287        return n;
 288}
 289
 290/*
 291 * we are going to reuse the existing object data as is.  make
 292 * sure it is not corrupt.
 293 */
 294static int check_pack_inflate(struct packed_git *p,
 295                struct pack_window **w_curs,
 296                off_t offset,
 297                off_t len,
 298                unsigned long expect)
 299{
 300        z_stream stream;
 301        unsigned char fakebuf[4096], *in;
 302        int st;
 303
 304        memset(&stream, 0, sizeof(stream));
 305        inflateInit(&stream);
 306        do {
 307                in = use_pack(p, w_curs, offset, &stream.avail_in);
 308                stream.next_in = in;
 309                stream.next_out = fakebuf;
 310                stream.avail_out = sizeof(fakebuf);
 311                st = inflate(&stream, Z_FINISH);
 312                offset += stream.next_in - in;
 313        } while (st == Z_OK || st == Z_BUF_ERROR);
 314        inflateEnd(&stream);
 315        return (st == Z_STREAM_END &&
 316                stream.total_out == expect &&
 317                stream.total_in == len) ? 0 : -1;
 318}
 319
 320static int check_pack_crc(struct packed_git *p, struct pack_window **w_curs,
 321                          off_t offset, off_t len, unsigned int nr)
 322{
 323        const uint32_t *index_crc;
 324        uint32_t data_crc = crc32(0, Z_NULL, 0);
 325
 326        do {
 327                unsigned int avail;
 328                void *data = use_pack(p, w_curs, offset, &avail);
 329                if (avail > len)
 330                        avail = len;
 331                data_crc = crc32(data_crc, data, avail);
 332                offset += avail;
 333                len -= avail;
 334        } while (len);
 335
 336        index_crc = p->index_data;
 337        index_crc += 2 + 256 + p->num_objects * (20/4) + nr;
 338
 339        return data_crc != ntohl(*index_crc);
 340}
 341
 342static void copy_pack_data(struct sha1file *f,
 343                struct packed_git *p,
 344                struct pack_window **w_curs,
 345                off_t offset,
 346                off_t len)
 347{
 348        unsigned char *in;
 349        unsigned int avail;
 350
 351        while (len) {
 352                in = use_pack(p, w_curs, offset, &avail);
 353                if (avail > len)
 354                        avail = (unsigned int)len;
 355                sha1write(f, in, avail);
 356                offset += avail;
 357                len -= avail;
 358        }
 359}
 360
 361static unsigned long write_object(struct sha1file *f,
 362                                  struct object_entry *entry,
 363                                  off_t write_offset)
 364{
 365        unsigned long size;
 366        enum object_type type;
 367        void *buf;
 368        unsigned char header[10];
 369        unsigned char dheader[10];
 370        unsigned hdrlen;
 371        off_t datalen;
 372        enum object_type obj_type;
 373        int to_reuse = 0;
 374        /* write limit if limited packsize and not first object */
 375        unsigned long limit = pack_size_limit && nr_written ?
 376                                pack_size_limit - write_offset : 0;
 377                                /* no if no delta */
 378        int usable_delta =      !entry->delta ? 0 :
 379                                /* yes if unlimited packfile */
 380                                !pack_size_limit ? 1 :
 381                                /* no if base written to previous pack */
 382                                entry->delta->idx.offset == (off_t)-1 ? 0 :
 383                                /* otherwise double-check written to this
 384                                 * pack,  like we do below
 385                                 */
 386                                entry->delta->idx.offset ? 1 : 0;
 387
 388        if (!pack_to_stdout)
 389                crc32_begin(f);
 390
 391        obj_type = entry->type;
 392        if (no_reuse_object)
 393                to_reuse = 0;   /* explicit */
 394        else if (!entry->in_pack)
 395                to_reuse = 0;   /* can't reuse what we don't have */
 396        else if (obj_type == OBJ_REF_DELTA || obj_type == OBJ_OFS_DELTA)
 397                                /* check_object() decided it for us ... */
 398                to_reuse = usable_delta;
 399                                /* ... but pack split may override that */
 400        else if (obj_type != entry->in_pack_type)
 401                to_reuse = 0;   /* pack has delta which is unusable */
 402        else if (entry->delta)
 403                to_reuse = 0;   /* we want to pack afresh */
 404        else
 405                to_reuse = 1;   /* we have it in-pack undeltified,
 406                                 * and we do not need to deltify it.
 407                                 */
 408
 409        if (!to_reuse) {
 410                z_stream stream;
 411                unsigned long maxsize;
 412                void *out;
 413                if (!usable_delta) {
 414                        buf = read_sha1_file(entry->idx.sha1, &obj_type, &size);
 415                        if (!buf)
 416                                die("unable to read %s", sha1_to_hex(entry->idx.sha1));
 417                } else if (entry->delta_data) {
 418                        size = entry->delta_size;
 419                        buf = entry->delta_data;
 420                        entry->delta_data = NULL;
 421                        obj_type = (allow_ofs_delta && entry->delta->idx.offset) ?
 422                                OBJ_OFS_DELTA : OBJ_REF_DELTA;
 423                } else {
 424                        buf = read_sha1_file(entry->idx.sha1, &type, &size);
 425                        if (!buf)
 426                                die("unable to read %s", sha1_to_hex(entry->idx.sha1));
 427                        buf = delta_against(buf, size, entry);
 428                        size = entry->delta_size;
 429                        obj_type = (allow_ofs_delta && entry->delta->idx.offset) ?
 430                                OBJ_OFS_DELTA : OBJ_REF_DELTA;
 431                }
 432                /* compress the data to store and put compressed length in datalen */
 433                memset(&stream, 0, sizeof(stream));
 434                deflateInit(&stream, pack_compression_level);
 435                maxsize = deflateBound(&stream, size);
 436                out = xmalloc(maxsize);
 437                /* Compress it */
 438                stream.next_in = buf;
 439                stream.avail_in = size;
 440                stream.next_out = out;
 441                stream.avail_out = maxsize;
 442                while (deflate(&stream, Z_FINISH) == Z_OK)
 443                        /* nothing */;
 444                deflateEnd(&stream);
 445                datalen = stream.total_out;
 446                deflateEnd(&stream);
 447                /*
 448                 * The object header is a byte of 'type' followed by zero or
 449                 * more bytes of length.
 450                 */
 451                hdrlen = encode_header(obj_type, size, header);
 452
 453                if (obj_type == OBJ_OFS_DELTA) {
 454                        /*
 455                         * Deltas with relative base contain an additional
 456                         * encoding of the relative offset for the delta
 457                         * base from this object's position in the pack.
 458                         */
 459                        off_t ofs = entry->idx.offset - entry->delta->idx.offset;
 460                        unsigned pos = sizeof(dheader) - 1;
 461                        dheader[pos] = ofs & 127;
 462                        while (ofs >>= 7)
 463                                dheader[--pos] = 128 | (--ofs & 127);
 464                        if (limit && hdrlen + sizeof(dheader) - pos + datalen + 20 >= limit) {
 465                                free(out);
 466                                free(buf);
 467                                return 0;
 468                        }
 469                        sha1write(f, header, hdrlen);
 470                        sha1write(f, dheader + pos, sizeof(dheader) - pos);
 471                        hdrlen += sizeof(dheader) - pos;
 472                } else if (obj_type == OBJ_REF_DELTA) {
 473                        /*
 474                         * Deltas with a base reference contain
 475                         * an additional 20 bytes for the base sha1.
 476                         */
 477                        if (limit && hdrlen + 20 + datalen + 20 >= limit) {
 478                                free(out);
 479                                free(buf);
 480                                return 0;
 481                        }
 482                        sha1write(f, header, hdrlen);
 483                        sha1write(f, entry->delta->idx.sha1, 20);
 484                        hdrlen += 20;
 485                } else {
 486                        if (limit && hdrlen + datalen + 20 >= limit) {
 487                                free(out);
 488                                free(buf);
 489                                return 0;
 490                        }
 491                        sha1write(f, header, hdrlen);
 492                }
 493                sha1write(f, out, datalen);
 494                free(out);
 495                free(buf);
 496        }
 497        else {
 498                struct packed_git *p = entry->in_pack;
 499                struct pack_window *w_curs = NULL;
 500                struct revindex_entry *revidx;
 501                off_t offset;
 502
 503                if (entry->delta) {
 504                        obj_type = (allow_ofs_delta && entry->delta->idx.offset) ?
 505                                OBJ_OFS_DELTA : OBJ_REF_DELTA;
 506                        reused_delta++;
 507                }
 508                hdrlen = encode_header(obj_type, entry->size, header);
 509                offset = entry->in_pack_offset;
 510                revidx = find_packed_object(p, offset);
 511                datalen = revidx[1].offset - offset;
 512                if (!pack_to_stdout && p->index_version > 1 &&
 513                    check_pack_crc(p, &w_curs, offset, datalen, revidx->nr))
 514                        die("bad packed object CRC for %s", sha1_to_hex(entry->idx.sha1));
 515                offset += entry->in_pack_header_size;
 516                datalen -= entry->in_pack_header_size;
 517                if (obj_type == OBJ_OFS_DELTA) {
 518                        off_t ofs = entry->idx.offset - entry->delta->idx.offset;
 519                        unsigned pos = sizeof(dheader) - 1;
 520                        dheader[pos] = ofs & 127;
 521                        while (ofs >>= 7)
 522                                dheader[--pos] = 128 | (--ofs & 127);
 523                        if (limit && hdrlen + sizeof(dheader) - pos + datalen + 20 >= limit)
 524                                return 0;
 525                        sha1write(f, header, hdrlen);
 526                        sha1write(f, dheader + pos, sizeof(dheader) - pos);
 527                        hdrlen += sizeof(dheader) - pos;
 528                } else if (obj_type == OBJ_REF_DELTA) {
 529                        if (limit && hdrlen + 20 + datalen + 20 >= limit)
 530                                return 0;
 531                        sha1write(f, header, hdrlen);
 532                        sha1write(f, entry->delta->idx.sha1, 20);
 533                        hdrlen += 20;
 534                } else {
 535                        if (limit && hdrlen + datalen + 20 >= limit)
 536                                return 0;
 537                        sha1write(f, header, hdrlen);
 538                }
 539
 540                if (!pack_to_stdout && p->index_version == 1 &&
 541                    check_pack_inflate(p, &w_curs, offset, datalen, entry->size))
 542                        die("corrupt packed object for %s", sha1_to_hex(entry->idx.sha1));
 543                copy_pack_data(f, p, &w_curs, offset, datalen);
 544                unuse_pack(&w_curs);
 545                reused++;
 546        }
 547        if (usable_delta)
 548                written_delta++;
 549        written++;
 550        if (!pack_to_stdout)
 551                entry->idx.crc32 = crc32_end(f);
 552        return hdrlen + datalen;
 553}
 554
 555static off_t write_one(struct sha1file *f,
 556                               struct object_entry *e,
 557                               off_t offset)
 558{
 559        unsigned long size;
 560
 561        /* offset is non zero if object is written already. */
 562        if (e->idx.offset || e->preferred_base)
 563                return offset;
 564
 565        /* if we are deltified, write out base object first. */
 566        if (e->delta) {
 567                offset = write_one(f, e->delta, offset);
 568                if (!offset)
 569                        return 0;
 570        }
 571
 572        e->idx.offset = offset;
 573        size = write_object(f, e, offset);
 574        if (!size) {
 575                e->idx.offset = 0;
 576                return 0;
 577        }
 578        written_list[nr_written++] = e;
 579
 580        /* make sure off_t is sufficiently large not to wrap */
 581        if (offset > offset + size)
 582                die("pack too large for current definition of off_t");
 583        return offset + size;
 584}
 585
 586static int open_object_dir_tmp(const char *path)
 587{
 588    snprintf(tmpname, sizeof(tmpname), "%s/%s", get_object_directory(), path);
 589    return mkstemp(tmpname);
 590}
 591
 592/* forward declaration for write_pack_file */
 593static int adjust_perm(const char *path, mode_t mode);
 594
 595static void write_pack_file(void)
 596{
 597        uint32_t i = 0, j;
 598        struct sha1file *f;
 599        off_t offset, offset_one, last_obj_offset = 0;
 600        struct pack_header hdr;
 601        int do_progress = progress >> pack_to_stdout;
 602        uint32_t nr_remaining = nr_result;
 603
 604        if (do_progress)
 605                start_progress(&progress_state, "Writing %u objects...", "", nr_result);
 606        written_list = xmalloc(nr_objects * sizeof(struct object_entry *));
 607
 608        do {
 609                unsigned char sha1[20];
 610
 611                if (pack_to_stdout) {
 612                        f = sha1fd(1, "<stdout>");
 613                } else {
 614                        int fd = open_object_dir_tmp("tmp_pack_XXXXXX");
 615                        if (fd < 0)
 616                                die("unable to create %s: %s\n", tmpname, strerror(errno));
 617                        pack_tmp_name = xstrdup(tmpname);
 618                        f = sha1fd(fd, pack_tmp_name);
 619                }
 620
 621                hdr.hdr_signature = htonl(PACK_SIGNATURE);
 622                hdr.hdr_version = htonl(PACK_VERSION);
 623                hdr.hdr_entries = htonl(nr_remaining);
 624                sha1write(f, &hdr, sizeof(hdr));
 625                offset = sizeof(hdr);
 626                nr_written = 0;
 627                for (; i < nr_objects; i++) {
 628                        last_obj_offset = offset;
 629                        offset_one = write_one(f, objects + i, offset);
 630                        if (!offset_one)
 631                                break;
 632                        offset = offset_one;
 633                        if (do_progress)
 634                                display_progress(&progress_state, written);
 635                }
 636
 637                /*
 638                 * Did we write the wrong # entries in the header?
 639                 * If so, rewrite it like in fast-import
 640                 */
 641                if (pack_to_stdout || nr_written == nr_remaining) {
 642                        sha1close(f, sha1, 1);
 643                } else {
 644                        sha1close(f, sha1, 0);
 645                        fixup_pack_header_footer(f->fd, sha1, pack_tmp_name, nr_written);
 646                        close(f->fd);
 647                }
 648
 649                if (!pack_to_stdout) {
 650                        mode_t mode = umask(0);
 651
 652                        umask(mode);
 653                        mode = 0444 & ~mode;
 654
 655                        idx_tmp_name = write_idx_file(NULL,
 656                                (struct pack_idx_entry **) written_list, nr_written, sha1);
 657                        snprintf(tmpname, sizeof(tmpname), "%s-%s.pack",
 658                                 base_name, sha1_to_hex(sha1));
 659                        if (adjust_perm(pack_tmp_name, mode))
 660                                die("unable to make temporary pack file readable: %s",
 661                                    strerror(errno));
 662                        if (rename(pack_tmp_name, tmpname))
 663                                die("unable to rename temporary pack file: %s",
 664                                    strerror(errno));
 665                        snprintf(tmpname, sizeof(tmpname), "%s-%s.idx",
 666                                 base_name, sha1_to_hex(sha1));
 667                        if (adjust_perm(idx_tmp_name, mode))
 668                                die("unable to make temporary index file readable: %s",
 669                                    strerror(errno));
 670                        if (rename(idx_tmp_name, tmpname))
 671                                die("unable to rename temporary index file: %s",
 672                                    strerror(errno));
 673                        puts(sha1_to_hex(sha1));
 674                }
 675
 676                /* mark written objects as written to previous pack */
 677                for (j = 0; j < nr_written; j++) {
 678                        written_list[j]->idx.offset = (off_t)-1;
 679                }
 680                nr_remaining -= nr_written;
 681        } while (nr_remaining && i < nr_objects);
 682
 683        free(written_list);
 684        if (do_progress)
 685                stop_progress(&progress_state);
 686        if (written != nr_result)
 687                die("wrote %u objects while expecting %u", written, nr_result);
 688        /*
 689         * We have scanned through [0 ... i).  Since we have written
 690         * the correct number of objects,  the remaining [i ... nr_objects)
 691         * items must be either already written (due to out-of-order delta base)
 692         * or a preferred base.  Count those which are neither and complain if any.
 693         */
 694        for (j = 0; i < nr_objects; i++) {
 695                struct object_entry *e = objects + i;
 696                j += !e->idx.offset && !e->preferred_base;
 697        }
 698        if (j)
 699                die("wrote %u objects as expected but %u unwritten", written, j);
 700}
 701
 702static int locate_object_entry_hash(const unsigned char *sha1)
 703{
 704        int i;
 705        unsigned int ui;
 706        memcpy(&ui, sha1, sizeof(unsigned int));
 707        i = ui % object_ix_hashsz;
 708        while (0 < object_ix[i]) {
 709                if (!hashcmp(sha1, objects[object_ix[i] - 1].idx.sha1))
 710                        return i;
 711                if (++i == object_ix_hashsz)
 712                        i = 0;
 713        }
 714        return -1 - i;
 715}
 716
 717static struct object_entry *locate_object_entry(const unsigned char *sha1)
 718{
 719        int i;
 720
 721        if (!object_ix_hashsz)
 722                return NULL;
 723
 724        i = locate_object_entry_hash(sha1);
 725        if (0 <= i)
 726                return &objects[object_ix[i]-1];
 727        return NULL;
 728}
 729
 730static void rehash_objects(void)
 731{
 732        uint32_t i;
 733        struct object_entry *oe;
 734
 735        object_ix_hashsz = nr_objects * 3;
 736        if (object_ix_hashsz < 1024)
 737                object_ix_hashsz = 1024;
 738        object_ix = xrealloc(object_ix, sizeof(int) * object_ix_hashsz);
 739        memset(object_ix, 0, sizeof(int) * object_ix_hashsz);
 740        for (i = 0, oe = objects; i < nr_objects; i++, oe++) {
 741                int ix = locate_object_entry_hash(oe->idx.sha1);
 742                if (0 <= ix)
 743                        continue;
 744                ix = -1 - ix;
 745                object_ix[ix] = i + 1;
 746        }
 747}
 748
 749static unsigned name_hash(const char *name)
 750{
 751        unsigned char c;
 752        unsigned hash = 0;
 753
 754        if (!name)
 755                return 0;
 756
 757        /*
 758         * This effectively just creates a sortable number from the
 759         * last sixteen non-whitespace characters. Last characters
 760         * count "most", so things that end in ".c" sort together.
 761         */
 762        while ((c = *name++) != 0) {
 763                if (isspace(c))
 764                        continue;
 765                hash = (hash >> 2) + (c << 24);
 766        }
 767        return hash;
 768}
 769
 770static void setup_delta_attr_check(struct git_attr_check *check)
 771{
 772        static struct git_attr *attr_delta;
 773
 774        if (!attr_delta)
 775                attr_delta = git_attr("delta", 5);
 776
 777        check[0].attr = attr_delta;
 778}
 779
 780static int no_try_delta(const char *path)
 781{
 782        struct git_attr_check check[1];
 783
 784        setup_delta_attr_check(check);
 785        if (git_checkattr(path, ARRAY_SIZE(check), check))
 786                return 0;
 787        if (ATTR_FALSE(check->value))
 788                return 1;
 789        return 0;
 790}
 791
 792static int add_object_entry(const unsigned char *sha1, enum object_type type,
 793                            const char *name, int exclude)
 794{
 795        struct object_entry *entry;
 796        struct packed_git *p, *found_pack = NULL;
 797        off_t found_offset = 0;
 798        int ix;
 799        unsigned hash = name_hash(name);
 800
 801        ix = nr_objects ? locate_object_entry_hash(sha1) : -1;
 802        if (ix >= 0) {
 803                if (exclude) {
 804                        entry = objects + object_ix[ix] - 1;
 805                        if (!entry->preferred_base)
 806                                nr_result--;
 807                        entry->preferred_base = 1;
 808                }
 809                return 0;
 810        }
 811
 812        for (p = packed_git; p; p = p->next) {
 813                off_t offset = find_pack_entry_one(sha1, p);
 814                if (offset) {
 815                        if (!found_pack) {
 816                                found_offset = offset;
 817                                found_pack = p;
 818                        }
 819                        if (exclude)
 820                                break;
 821                        if (incremental)
 822                                return 0;
 823                        if (local && !p->pack_local)
 824                                return 0;
 825                }
 826        }
 827
 828        if (nr_objects >= nr_alloc) {
 829                nr_alloc = (nr_alloc  + 1024) * 3 / 2;
 830                objects = xrealloc(objects, nr_alloc * sizeof(*entry));
 831        }
 832
 833        entry = objects + nr_objects++;
 834        memset(entry, 0, sizeof(*entry));
 835        hashcpy(entry->idx.sha1, sha1);
 836        entry->hash = hash;
 837        if (type)
 838                entry->type = type;
 839        if (exclude)
 840                entry->preferred_base = 1;
 841        else
 842                nr_result++;
 843        if (found_pack) {
 844                entry->in_pack = found_pack;
 845                entry->in_pack_offset = found_offset;
 846        }
 847
 848        if (object_ix_hashsz * 3 <= nr_objects * 4)
 849                rehash_objects();
 850        else
 851                object_ix[-1 - ix] = nr_objects;
 852
 853        if (progress)
 854                display_progress(&progress_state, nr_objects);
 855
 856        if (name && no_try_delta(name))
 857                entry->no_try_delta = 1;
 858
 859        return 1;
 860}
 861
 862struct pbase_tree_cache {
 863        unsigned char sha1[20];
 864        int ref;
 865        int temporary;
 866        void *tree_data;
 867        unsigned long tree_size;
 868};
 869
 870static struct pbase_tree_cache *(pbase_tree_cache[256]);
 871static int pbase_tree_cache_ix(const unsigned char *sha1)
 872{
 873        return sha1[0] % ARRAY_SIZE(pbase_tree_cache);
 874}
 875static int pbase_tree_cache_ix_incr(int ix)
 876{
 877        return (ix+1) % ARRAY_SIZE(pbase_tree_cache);
 878}
 879
 880static struct pbase_tree {
 881        struct pbase_tree *next;
 882        /* This is a phony "cache" entry; we are not
 883         * going to evict it nor find it through _get()
 884         * mechanism -- this is for the toplevel node that
 885         * would almost always change with any commit.
 886         */
 887        struct pbase_tree_cache pcache;
 888} *pbase_tree;
 889
 890static struct pbase_tree_cache *pbase_tree_get(const unsigned char *sha1)
 891{
 892        struct pbase_tree_cache *ent, *nent;
 893        void *data;
 894        unsigned long size;
 895        enum object_type type;
 896        int neigh;
 897        int my_ix = pbase_tree_cache_ix(sha1);
 898        int available_ix = -1;
 899
 900        /* pbase-tree-cache acts as a limited hashtable.
 901         * your object will be found at your index or within a few
 902         * slots after that slot if it is cached.
 903         */
 904        for (neigh = 0; neigh < 8; neigh++) {
 905                ent = pbase_tree_cache[my_ix];
 906                if (ent && !hashcmp(ent->sha1, sha1)) {
 907                        ent->ref++;
 908                        return ent;
 909                }
 910                else if (((available_ix < 0) && (!ent || !ent->ref)) ||
 911                         ((0 <= available_ix) &&
 912                          (!ent && pbase_tree_cache[available_ix])))
 913                        available_ix = my_ix;
 914                if (!ent)
 915                        break;
 916                my_ix = pbase_tree_cache_ix_incr(my_ix);
 917        }
 918
 919        /* Did not find one.  Either we got a bogus request or
 920         * we need to read and perhaps cache.
 921         */
 922        data = read_sha1_file(sha1, &type, &size);
 923        if (!data)
 924                return NULL;
 925        if (type != OBJ_TREE) {
 926                free(data);
 927                return NULL;
 928        }
 929
 930        /* We need to either cache or return a throwaway copy */
 931
 932        if (available_ix < 0)
 933                ent = NULL;
 934        else {
 935                ent = pbase_tree_cache[available_ix];
 936                my_ix = available_ix;
 937        }
 938
 939        if (!ent) {
 940                nent = xmalloc(sizeof(*nent));
 941                nent->temporary = (available_ix < 0);
 942        }
 943        else {
 944                /* evict and reuse */
 945                free(ent->tree_data);
 946                nent = ent;
 947        }
 948        hashcpy(nent->sha1, sha1);
 949        nent->tree_data = data;
 950        nent->tree_size = size;
 951        nent->ref = 1;
 952        if (!nent->temporary)
 953                pbase_tree_cache[my_ix] = nent;
 954        return nent;
 955}
 956
 957static void pbase_tree_put(struct pbase_tree_cache *cache)
 958{
 959        if (!cache->temporary) {
 960                cache->ref--;
 961                return;
 962        }
 963        free(cache->tree_data);
 964        free(cache);
 965}
 966
 967static int name_cmp_len(const char *name)
 968{
 969        int i;
 970        for (i = 0; name[i] && name[i] != '\n' && name[i] != '/'; i++)
 971                ;
 972        return i;
 973}
 974
 975static void add_pbase_object(struct tree_desc *tree,
 976                             const char *name,
 977                             int cmplen,
 978                             const char *fullname)
 979{
 980        struct name_entry entry;
 981        int cmp;
 982
 983        while (tree_entry(tree,&entry)) {
 984                cmp = tree_entry_len(entry.path, entry.sha1) != cmplen ? 1 :
 985                      memcmp(name, entry.path, cmplen);
 986                if (cmp > 0)
 987                        continue;
 988                if (cmp < 0)
 989                        return;
 990                if (name[cmplen] != '/') {
 991                        add_object_entry(entry.sha1,
 992                                         S_ISDIR(entry.mode) ? OBJ_TREE : OBJ_BLOB,
 993                                         fullname, 1);
 994                        return;
 995                }
 996                if (S_ISDIR(entry.mode)) {
 997                        struct tree_desc sub;
 998                        struct pbase_tree_cache *tree;
 999                        const char *down = name+cmplen+1;
1000                        int downlen = name_cmp_len(down);
1001
1002                        tree = pbase_tree_get(entry.sha1);
1003                        if (!tree)
1004                                return;
1005                        init_tree_desc(&sub, tree->tree_data, tree->tree_size);
1006
1007                        add_pbase_object(&sub, down, downlen, fullname);
1008                        pbase_tree_put(tree);
1009                }
1010        }
1011}
1012
1013static unsigned *done_pbase_paths;
1014static int done_pbase_paths_num;
1015static int done_pbase_paths_alloc;
1016static int done_pbase_path_pos(unsigned hash)
1017{
1018        int lo = 0;
1019        int hi = done_pbase_paths_num;
1020        while (lo < hi) {
1021                int mi = (hi + lo) / 2;
1022                if (done_pbase_paths[mi] == hash)
1023                        return mi;
1024                if (done_pbase_paths[mi] < hash)
1025                        hi = mi;
1026                else
1027                        lo = mi + 1;
1028        }
1029        return -lo-1;
1030}
1031
1032static int check_pbase_path(unsigned hash)
1033{
1034        int pos = (!done_pbase_paths) ? -1 : done_pbase_path_pos(hash);
1035        if (0 <= pos)
1036                return 1;
1037        pos = -pos - 1;
1038        if (done_pbase_paths_alloc <= done_pbase_paths_num) {
1039                done_pbase_paths_alloc = alloc_nr(done_pbase_paths_alloc);
1040                done_pbase_paths = xrealloc(done_pbase_paths,
1041                                            done_pbase_paths_alloc *
1042                                            sizeof(unsigned));
1043        }
1044        done_pbase_paths_num++;
1045        if (pos < done_pbase_paths_num)
1046                memmove(done_pbase_paths + pos + 1,
1047                        done_pbase_paths + pos,
1048                        (done_pbase_paths_num - pos - 1) * sizeof(unsigned));
1049        done_pbase_paths[pos] = hash;
1050        return 0;
1051}
1052
1053static void add_preferred_base_object(const char *name)
1054{
1055        struct pbase_tree *it;
1056        int cmplen;
1057        unsigned hash = name_hash(name);
1058
1059        if (!num_preferred_base || check_pbase_path(hash))
1060                return;
1061
1062        cmplen = name_cmp_len(name);
1063        for (it = pbase_tree; it; it = it->next) {
1064                if (cmplen == 0) {
1065                        add_object_entry(it->pcache.sha1, OBJ_TREE, NULL, 1);
1066                }
1067                else {
1068                        struct tree_desc tree;
1069                        init_tree_desc(&tree, it->pcache.tree_data, it->pcache.tree_size);
1070                        add_pbase_object(&tree, name, cmplen, name);
1071                }
1072        }
1073}
1074
1075static void add_preferred_base(unsigned char *sha1)
1076{
1077        struct pbase_tree *it;
1078        void *data;
1079        unsigned long size;
1080        unsigned char tree_sha1[20];
1081
1082        if (window <= num_preferred_base++)
1083                return;
1084
1085        data = read_object_with_reference(sha1, tree_type, &size, tree_sha1);
1086        if (!data)
1087                return;
1088
1089        for (it = pbase_tree; it; it = it->next) {
1090                if (!hashcmp(it->pcache.sha1, tree_sha1)) {
1091                        free(data);
1092                        return;
1093                }
1094        }
1095
1096        it = xcalloc(1, sizeof(*it));
1097        it->next = pbase_tree;
1098        pbase_tree = it;
1099
1100        hashcpy(it->pcache.sha1, tree_sha1);
1101        it->pcache.tree_data = data;
1102        it->pcache.tree_size = size;
1103}
1104
1105static void check_object(struct object_entry *entry)
1106{
1107        if (entry->in_pack) {
1108                struct packed_git *p = entry->in_pack;
1109                struct pack_window *w_curs = NULL;
1110                const unsigned char *base_ref = NULL;
1111                struct object_entry *base_entry;
1112                unsigned long used, used_0;
1113                unsigned int avail;
1114                off_t ofs;
1115                unsigned char *buf, c;
1116
1117                buf = use_pack(p, &w_curs, entry->in_pack_offset, &avail);
1118
1119                /*
1120                 * We want in_pack_type even if we do not reuse delta
1121                 * since non-delta representations could still be reused.
1122                 */
1123                used = unpack_object_header_gently(buf, avail,
1124                                                   &entry->in_pack_type,
1125                                                   &entry->size);
1126
1127                /*
1128                 * Determine if this is a delta and if so whether we can
1129                 * reuse it or not.  Otherwise let's find out as cheaply as
1130                 * possible what the actual type and size for this object is.
1131                 */
1132                switch (entry->in_pack_type) {
1133                default:
1134                        /* Not a delta hence we've already got all we need. */
1135                        entry->type = entry->in_pack_type;
1136                        entry->in_pack_header_size = used;
1137                        unuse_pack(&w_curs);
1138                        return;
1139                case OBJ_REF_DELTA:
1140                        if (!no_reuse_delta && !entry->preferred_base)
1141                                base_ref = use_pack(p, &w_curs,
1142                                                entry->in_pack_offset + used, NULL);
1143                        entry->in_pack_header_size = used + 20;
1144                        break;
1145                case OBJ_OFS_DELTA:
1146                        buf = use_pack(p, &w_curs,
1147                                       entry->in_pack_offset + used, NULL);
1148                        used_0 = 0;
1149                        c = buf[used_0++];
1150                        ofs = c & 127;
1151                        while (c & 128) {
1152                                ofs += 1;
1153                                if (!ofs || MSB(ofs, 7))
1154                                        die("delta base offset overflow in pack for %s",
1155                                            sha1_to_hex(entry->idx.sha1));
1156                                c = buf[used_0++];
1157                                ofs = (ofs << 7) + (c & 127);
1158                        }
1159                        if (ofs >= entry->in_pack_offset)
1160                                die("delta base offset out of bound for %s",
1161                                    sha1_to_hex(entry->idx.sha1));
1162                        ofs = entry->in_pack_offset - ofs;
1163                        if (!no_reuse_delta && !entry->preferred_base)
1164                                base_ref = find_packed_object_name(p, ofs);
1165                        entry->in_pack_header_size = used + used_0;
1166                        break;
1167                }
1168
1169                if (base_ref && (base_entry = locate_object_entry(base_ref))) {
1170                        /*
1171                         * If base_ref was set above that means we wish to
1172                         * reuse delta data, and we even found that base
1173                         * in the list of objects we want to pack. Goodie!
1174                         *
1175                         * Depth value does not matter - find_deltas() will
1176                         * never consider reused delta as the base object to
1177                         * deltify other objects against, in order to avoid
1178                         * circular deltas.
1179                         */
1180                        entry->type = entry->in_pack_type;
1181                        entry->delta = base_entry;
1182                        entry->delta_sibling = base_entry->delta_child;
1183                        base_entry->delta_child = entry;
1184                        unuse_pack(&w_curs);
1185                        return;
1186                }
1187
1188                if (entry->type) {
1189                        /*
1190                         * This must be a delta and we already know what the
1191                         * final object type is.  Let's extract the actual
1192                         * object size from the delta header.
1193                         */
1194                        entry->size = get_size_from_delta(p, &w_curs,
1195                                        entry->in_pack_offset + entry->in_pack_header_size);
1196                        unuse_pack(&w_curs);
1197                        return;
1198                }
1199
1200                /*
1201                 * No choice but to fall back to the recursive delta walk
1202                 * with sha1_object_info() to find about the object type
1203                 * at this point...
1204                 */
1205                unuse_pack(&w_curs);
1206        }
1207
1208        entry->type = sha1_object_info(entry->idx.sha1, &entry->size);
1209        if (entry->type < 0)
1210                die("unable to get type of object %s",
1211                    sha1_to_hex(entry->idx.sha1));
1212}
1213
1214static int pack_offset_sort(const void *_a, const void *_b)
1215{
1216        const struct object_entry *a = *(struct object_entry **)_a;
1217        const struct object_entry *b = *(struct object_entry **)_b;
1218
1219        /* avoid filesystem trashing with loose objects */
1220        if (!a->in_pack && !b->in_pack)
1221                return hashcmp(a->idx.sha1, b->idx.sha1);
1222
1223        if (a->in_pack < b->in_pack)
1224                return -1;
1225        if (a->in_pack > b->in_pack)
1226                return 1;
1227        return a->in_pack_offset < b->in_pack_offset ? -1 :
1228                        (a->in_pack_offset > b->in_pack_offset);
1229}
1230
1231static void get_object_details(void)
1232{
1233        uint32_t i;
1234        struct object_entry **sorted_by_offset;
1235
1236        sorted_by_offset = xcalloc(nr_objects, sizeof(struct object_entry *));
1237        for (i = 0; i < nr_objects; i++)
1238                sorted_by_offset[i] = objects + i;
1239        qsort(sorted_by_offset, nr_objects, sizeof(*sorted_by_offset), pack_offset_sort);
1240
1241        prepare_pack_ix();
1242        for (i = 0; i < nr_objects; i++)
1243                check_object(sorted_by_offset[i]);
1244        free(sorted_by_offset);
1245}
1246
1247static int type_size_sort(const void *_a, const void *_b)
1248{
1249        const struct object_entry *a = *(struct object_entry **)_a;
1250        const struct object_entry *b = *(struct object_entry **)_b;
1251
1252        if (a->type < b->type)
1253                return -1;
1254        if (a->type > b->type)
1255                return 1;
1256        if (a->hash < b->hash)
1257                return -1;
1258        if (a->hash > b->hash)
1259                return 1;
1260        if (a->preferred_base < b->preferred_base)
1261                return -1;
1262        if (a->preferred_base > b->preferred_base)
1263                return 1;
1264        if (a->size < b->size)
1265                return -1;
1266        if (a->size > b->size)
1267                return 1;
1268        return a > b ? -1 : (a < b);  /* newest last */
1269}
1270
1271struct unpacked {
1272        struct object_entry *entry;
1273        void *data;
1274        struct delta_index *index;
1275        unsigned depth;
1276};
1277
1278static int delta_cacheable(struct unpacked *trg, struct unpacked *src,
1279                            unsigned long src_size, unsigned long trg_size,
1280                            unsigned long delta_size)
1281{
1282        if (max_delta_cache_size && delta_cache_size + delta_size > max_delta_cache_size)
1283                return 0;
1284
1285        if (delta_size < cache_max_small_delta_size)
1286                return 1;
1287
1288        /* cache delta, if objects are large enough compared to delta size */
1289        if ((src_size >> 20) + (trg_size >> 21) > (delta_size >> 10))
1290                return 1;
1291
1292        return 0;
1293}
1294
1295/*
1296 * We search for deltas _backwards_ in a list sorted by type and
1297 * by size, so that we see progressively smaller and smaller files.
1298 * That's because we prefer deltas to be from the bigger file
1299 * to the smaller - deletes are potentially cheaper, but perhaps
1300 * more importantly, the bigger file is likely the more recent
1301 * one.
1302 */
1303static int try_delta(struct unpacked *trg, struct unpacked *src,
1304                     unsigned max_depth)
1305{
1306        struct object_entry *trg_entry = trg->entry;
1307        struct object_entry *src_entry = src->entry;
1308        unsigned long trg_size, src_size, delta_size, sizediff, max_size, sz;
1309        unsigned ref_depth;
1310        enum object_type type;
1311        void *delta_buf;
1312
1313        /* Don't bother doing diffs between different types */
1314        if (trg_entry->type != src_entry->type)
1315                return -1;
1316
1317        /* We do not compute delta to *create* objects we are not
1318         * going to pack.
1319         */
1320        if (trg_entry->preferred_base)
1321                return -1;
1322
1323        /*
1324         * We do not bother to try a delta that we discarded
1325         * on an earlier try, but only when reusing delta data.
1326         */
1327        if (!no_reuse_delta && trg_entry->in_pack &&
1328            trg_entry->in_pack == src_entry->in_pack &&
1329            trg_entry->in_pack_type != OBJ_REF_DELTA &&
1330            trg_entry->in_pack_type != OBJ_OFS_DELTA)
1331                return 0;
1332
1333        /* Let's not bust the allowed depth. */
1334        if (src->depth >= max_depth)
1335                return 0;
1336
1337        /* Now some size filtering heuristics. */
1338        trg_size = trg_entry->size;
1339        if (!trg_entry->delta) {
1340                max_size = trg_size/2 - 20;
1341                ref_depth = 1;
1342        } else {
1343                max_size = trg_entry->delta_size;
1344                ref_depth = trg->depth;
1345        }
1346        max_size = max_size * (max_depth - src->depth) /
1347                                                (max_depth - ref_depth + 1);
1348        if (max_size == 0)
1349                return 0;
1350        src_size = src_entry->size;
1351        sizediff = src_size < trg_size ? trg_size - src_size : 0;
1352        if (sizediff >= max_size)
1353                return 0;
1354        if (trg_size < src_size / 32)
1355                return 0;
1356
1357        /* Load data if not already done */
1358        if (!trg->data) {
1359                trg->data = read_sha1_file(trg_entry->idx.sha1, &type, &sz);
1360                if (sz != trg_size)
1361                        die("object %s inconsistent object length (%lu vs %lu)",
1362                            sha1_to_hex(trg_entry->idx.sha1), sz, trg_size);
1363                window_memory_usage += sz;
1364        }
1365        if (!src->data) {
1366                src->data = read_sha1_file(src_entry->idx.sha1, &type, &sz);
1367                if (sz != src_size)
1368                        die("object %s inconsistent object length (%lu vs %lu)",
1369                            sha1_to_hex(src_entry->idx.sha1), sz, src_size);
1370                window_memory_usage += sz;
1371        }
1372        if (!src->index) {
1373                src->index = create_delta_index(src->data, src_size);
1374                if (!src->index) {
1375                        static int warned = 0;
1376                        if (!warned++)
1377                                warning("suboptimal pack - out of memory");
1378                        return 0;
1379                }
1380                window_memory_usage += sizeof_delta_index(src->index);
1381        }
1382
1383        delta_buf = create_delta(src->index, trg->data, trg_size, &delta_size, max_size);
1384        if (!delta_buf)
1385                return 0;
1386
1387        if (trg_entry->delta_data) {
1388                /* Prefer only shallower same-sized deltas. */
1389                if (delta_size == trg_entry->delta_size &&
1390                    src->depth + 1 >= trg->depth) {
1391                        free(delta_buf);
1392                        return 0;
1393                }
1394                delta_cache_size -= trg_entry->delta_size;
1395                free(trg_entry->delta_data);
1396                trg_entry->delta_data = NULL;
1397        }
1398        trg_entry->delta = src_entry;
1399        trg_entry->delta_size = delta_size;
1400        trg->depth = src->depth + 1;
1401
1402        if (delta_cacheable(src, trg, src_size, trg_size, delta_size)) {
1403                trg_entry->delta_data = xrealloc(delta_buf, delta_size);
1404                delta_cache_size += trg_entry->delta_size;
1405        } else
1406                free(delta_buf);
1407        return 1;
1408}
1409
1410static unsigned int check_delta_limit(struct object_entry *me, unsigned int n)
1411{
1412        struct object_entry *child = me->delta_child;
1413        unsigned int m = n;
1414        while (child) {
1415                unsigned int c = check_delta_limit(child, n + 1);
1416                if (m < c)
1417                        m = c;
1418                child = child->delta_sibling;
1419        }
1420        return m;
1421}
1422
1423static void free_unpacked(struct unpacked *n)
1424{
1425        window_memory_usage -= sizeof_delta_index(n->index);
1426        free_delta_index(n->index);
1427        n->index = NULL;
1428        if (n->data) {
1429                free(n->data);
1430                n->data = NULL;
1431                window_memory_usage -= n->entry->size;
1432        }
1433        n->entry = NULL;
1434        n->depth = 0;
1435}
1436
1437static void find_deltas(struct object_entry **list, int window, int depth)
1438{
1439        uint32_t i = nr_objects, idx = 0, count = 0, processed = 0;
1440        unsigned int array_size = window * sizeof(struct unpacked);
1441        struct unpacked *array;
1442        int max_depth;
1443
1444        if (!nr_objects)
1445                return;
1446        array = xmalloc(array_size);
1447        memset(array, 0, array_size);
1448        if (progress)
1449                start_progress(&progress_state, "Deltifying %u objects...", "", nr_result);
1450
1451        do {
1452                struct object_entry *entry = list[--i];
1453                struct unpacked *n = array + idx;
1454                int j;
1455
1456                if (!entry->preferred_base)
1457                        processed++;
1458
1459                if (progress)
1460                        display_progress(&progress_state, processed);
1461
1462                if (entry->delta)
1463                        /* This happens if we decided to reuse existing
1464                         * delta from a pack.  "!no_reuse_delta &&" is implied.
1465                         */
1466                        continue;
1467
1468                if (entry->size < 50)
1469                        continue;
1470
1471                if (entry->no_try_delta)
1472                        continue;
1473
1474                free_unpacked(n);
1475                n->entry = entry;
1476
1477                while (window_memory_limit &&
1478                       window_memory_usage > window_memory_limit &&
1479                       count > 1) {
1480                        uint32_t tail = (idx + window - count) % window;
1481                        free_unpacked(array + tail);
1482                        count--;
1483                }
1484
1485                /*
1486                 * If the current object is at pack edge, take the depth the
1487                 * objects that depend on the current object into account
1488                 * otherwise they would become too deep.
1489                 */
1490                max_depth = depth;
1491                if (entry->delta_child) {
1492                        max_depth -= check_delta_limit(entry, 0);
1493                        if (max_depth <= 0)
1494                                goto next;
1495                }
1496
1497                j = window;
1498                while (--j > 0) {
1499                        uint32_t other_idx = idx + j;
1500                        struct unpacked *m;
1501                        if (other_idx >= window)
1502                                other_idx -= window;
1503                        m = array + other_idx;
1504                        if (!m->entry)
1505                                break;
1506                        if (try_delta(n, m, max_depth) < 0)
1507                                break;
1508                }
1509
1510                /* if we made n a delta, and if n is already at max
1511                 * depth, leaving it in the window is pointless.  we
1512                 * should evict it first.
1513                 */
1514                if (entry->delta && depth <= n->depth)
1515                        continue;
1516
1517                next:
1518                idx++;
1519                if (count + 1 < window)
1520                        count++;
1521                if (idx >= window)
1522                        idx = 0;
1523        } while (i > 0);
1524
1525        if (progress)
1526                stop_progress(&progress_state);
1527
1528        for (i = 0; i < window; ++i) {
1529                free_delta_index(array[i].index);
1530                free(array[i].data);
1531        }
1532        free(array);
1533}
1534
1535static void prepare_pack(int window, int depth)
1536{
1537        struct object_entry **delta_list;
1538        uint32_t i;
1539
1540        get_object_details();
1541
1542        if (!window || !depth)
1543                return;
1544
1545        delta_list = xmalloc(nr_objects * sizeof(*delta_list));
1546        for (i = 0; i < nr_objects; i++)
1547                delta_list[i] = objects + i;
1548        qsort(delta_list, nr_objects, sizeof(*delta_list), type_size_sort);
1549        find_deltas(delta_list, window+1, depth);
1550        free(delta_list);
1551}
1552
1553static int git_pack_config(const char *k, const char *v)
1554{
1555        if(!strcmp(k, "pack.window")) {
1556                window = git_config_int(k, v);
1557                return 0;
1558        }
1559        if (!strcmp(k, "pack.windowmemory")) {
1560                window_memory_limit = git_config_ulong(k, v);
1561                return 0;
1562        }
1563        if (!strcmp(k, "pack.depth")) {
1564                depth = git_config_int(k, v);
1565                return 0;
1566        }
1567        if (!strcmp(k, "pack.compression")) {
1568                int level = git_config_int(k, v);
1569                if (level == -1)
1570                        level = Z_DEFAULT_COMPRESSION;
1571                else if (level < 0 || level > Z_BEST_COMPRESSION)
1572                        die("bad pack compression level %d", level);
1573                pack_compression_level = level;
1574                pack_compression_seen = 1;
1575                return 0;
1576        }
1577        if (!strcmp(k, "pack.deltacachesize")) {
1578                max_delta_cache_size = git_config_int(k, v);
1579                return 0;
1580        }
1581        if (!strcmp(k, "pack.deltacachelimit")) {
1582                cache_max_small_delta_size = git_config_int(k, v);
1583                return 0;
1584        }
1585        return git_default_config(k, v);
1586}
1587
1588static void read_object_list_from_stdin(void)
1589{
1590        char line[40 + 1 + PATH_MAX + 2];
1591        unsigned char sha1[20];
1592
1593        for (;;) {
1594                if (!fgets(line, sizeof(line), stdin)) {
1595                        if (feof(stdin))
1596                                break;
1597                        if (!ferror(stdin))
1598                                die("fgets returned NULL, not EOF, not error!");
1599                        if (errno != EINTR)
1600                                die("fgets: %s", strerror(errno));
1601                        clearerr(stdin);
1602                        continue;
1603                }
1604                if (line[0] == '-') {
1605                        if (get_sha1_hex(line+1, sha1))
1606                                die("expected edge sha1, got garbage:\n %s",
1607                                    line);
1608                        add_preferred_base(sha1);
1609                        continue;
1610                }
1611                if (get_sha1_hex(line, sha1))
1612                        die("expected sha1, got garbage:\n %s", line);
1613
1614                add_preferred_base_object(line+41);
1615                add_object_entry(sha1, 0, line+41, 0);
1616        }
1617}
1618
1619static void show_commit(struct commit *commit)
1620{
1621        add_object_entry(commit->object.sha1, OBJ_COMMIT, NULL, 0);
1622}
1623
1624static void show_object(struct object_array_entry *p)
1625{
1626        add_preferred_base_object(p->name);
1627        add_object_entry(p->item->sha1, p->item->type, p->name, 0);
1628}
1629
1630static void show_edge(struct commit *commit)
1631{
1632        add_preferred_base(commit->object.sha1);
1633}
1634
1635static void get_object_list(int ac, const char **av)
1636{
1637        struct rev_info revs;
1638        char line[1000];
1639        int flags = 0;
1640
1641        init_revisions(&revs, NULL);
1642        save_commit_buffer = 0;
1643        track_object_refs = 0;
1644        setup_revisions(ac, av, &revs, NULL);
1645
1646        while (fgets(line, sizeof(line), stdin) != NULL) {
1647                int len = strlen(line);
1648                if (line[len - 1] == '\n')
1649                        line[--len] = 0;
1650                if (!len)
1651                        break;
1652                if (*line == '-') {
1653                        if (!strcmp(line, "--not")) {
1654                                flags ^= UNINTERESTING;
1655                                continue;
1656                        }
1657                        die("not a rev '%s'", line);
1658                }
1659                if (handle_revision_arg(line, &revs, flags, 1))
1660                        die("bad revision '%s'", line);
1661        }
1662
1663        prepare_revision_walk(&revs);
1664        mark_edges_uninteresting(revs.commits, &revs, show_edge);
1665        traverse_commit_list(&revs, show_commit, show_object);
1666}
1667
1668static int adjust_perm(const char *path, mode_t mode)
1669{
1670        if (chmod(path, mode))
1671                return -1;
1672        return adjust_shared_perm(path);
1673}
1674
1675int cmd_pack_objects(int argc, const char **argv, const char *prefix)
1676{
1677        int use_internal_rev_list = 0;
1678        int thin = 0;
1679        uint32_t i;
1680        const char **rp_av;
1681        int rp_ac_alloc = 64;
1682        int rp_ac;
1683
1684        rp_av = xcalloc(rp_ac_alloc, sizeof(*rp_av));
1685
1686        rp_av[0] = "pack-objects";
1687        rp_av[1] = "--objects"; /* --thin will make it --objects-edge */
1688        rp_ac = 2;
1689
1690        git_config(git_pack_config);
1691        if (!pack_compression_seen && core_compression_seen)
1692                pack_compression_level = core_compression_level;
1693
1694        progress = isatty(2);
1695        for (i = 1; i < argc; i++) {
1696                const char *arg = argv[i];
1697
1698                if (*arg != '-')
1699                        break;
1700
1701                if (!strcmp("--non-empty", arg)) {
1702                        non_empty = 1;
1703                        continue;
1704                }
1705                if (!strcmp("--local", arg)) {
1706                        local = 1;
1707                        continue;
1708                }
1709                if (!strcmp("--incremental", arg)) {
1710                        incremental = 1;
1711                        continue;
1712                }
1713                if (!prefixcmp(arg, "--compression=")) {
1714                        char *end;
1715                        int level = strtoul(arg+14, &end, 0);
1716                        if (!arg[14] || *end)
1717                                usage(pack_usage);
1718                        if (level == -1)
1719                                level = Z_DEFAULT_COMPRESSION;
1720                        else if (level < 0 || level > Z_BEST_COMPRESSION)
1721                                die("bad pack compression level %d", level);
1722                        pack_compression_level = level;
1723                        continue;
1724                }
1725                if (!prefixcmp(arg, "--max-pack-size=")) {
1726                        char *end;
1727                        pack_size_limit = strtoul(arg+16, &end, 0) * 1024 * 1024;
1728                        if (!arg[16] || *end)
1729                                usage(pack_usage);
1730                        continue;
1731                }
1732                if (!prefixcmp(arg, "--window=")) {
1733                        char *end;
1734                        window = strtoul(arg+9, &end, 0);
1735                        if (!arg[9] || *end)
1736                                usage(pack_usage);
1737                        continue;
1738                }
1739                if (!prefixcmp(arg, "--window-memory=")) {
1740                        if (!git_parse_ulong(arg+16, &window_memory_limit))
1741                                usage(pack_usage);
1742                        continue;
1743                }
1744                if (!prefixcmp(arg, "--depth=")) {
1745                        char *end;
1746                        depth = strtoul(arg+8, &end, 0);
1747                        if (!arg[8] || *end)
1748                                usage(pack_usage);
1749                        continue;
1750                }
1751                if (!strcmp("--progress", arg)) {
1752                        progress = 1;
1753                        continue;
1754                }
1755                if (!strcmp("--all-progress", arg)) {
1756                        progress = 2;
1757                        continue;
1758                }
1759                if (!strcmp("-q", arg)) {
1760                        progress = 0;
1761                        continue;
1762                }
1763                if (!strcmp("--no-reuse-delta", arg)) {
1764                        no_reuse_delta = 1;
1765                        continue;
1766                }
1767                if (!strcmp("--no-reuse-object", arg)) {
1768                        no_reuse_object = no_reuse_delta = 1;
1769                        continue;
1770                }
1771                if (!strcmp("--delta-base-offset", arg)) {
1772                        allow_ofs_delta = 1;
1773                        continue;
1774                }
1775                if (!strcmp("--stdout", arg)) {
1776                        pack_to_stdout = 1;
1777                        continue;
1778                }
1779                if (!strcmp("--revs", arg)) {
1780                        use_internal_rev_list = 1;
1781                        continue;
1782                }
1783                if (!strcmp("--unpacked", arg) ||
1784                    !prefixcmp(arg, "--unpacked=") ||
1785                    !strcmp("--reflog", arg) ||
1786                    !strcmp("--all", arg)) {
1787                        use_internal_rev_list = 1;
1788                        if (rp_ac >= rp_ac_alloc - 1) {
1789                                rp_ac_alloc = alloc_nr(rp_ac_alloc);
1790                                rp_av = xrealloc(rp_av,
1791                                                 rp_ac_alloc * sizeof(*rp_av));
1792                        }
1793                        rp_av[rp_ac++] = arg;
1794                        continue;
1795                }
1796                if (!strcmp("--thin", arg)) {
1797                        use_internal_rev_list = 1;
1798                        thin = 1;
1799                        rp_av[1] = "--objects-edge";
1800                        continue;
1801                }
1802                if (!prefixcmp(arg, "--index-version=")) {
1803                        char *c;
1804                        pack_idx_default_version = strtoul(arg + 16, &c, 10);
1805                        if (pack_idx_default_version > 2)
1806                                die("bad %s", arg);
1807                        if (*c == ',')
1808                                pack_idx_off32_limit = strtoul(c+1, &c, 0);
1809                        if (*c || pack_idx_off32_limit & 0x80000000)
1810                                die("bad %s", arg);
1811                        continue;
1812                }
1813                usage(pack_usage);
1814        }
1815
1816        /* Traditionally "pack-objects [options] base extra" failed;
1817         * we would however want to take refs parameter that would
1818         * have been given to upstream rev-list ourselves, which means
1819         * we somehow want to say what the base name is.  So the
1820         * syntax would be:
1821         *
1822         * pack-objects [options] base <refs...>
1823         *
1824         * in other words, we would treat the first non-option as the
1825         * base_name and send everything else to the internal revision
1826         * walker.
1827         */
1828
1829        if (!pack_to_stdout)
1830                base_name = argv[i++];
1831
1832        if (pack_to_stdout != !base_name)
1833                usage(pack_usage);
1834
1835        if (pack_to_stdout && pack_size_limit)
1836                die("--max-pack-size cannot be used to build a pack for transfer.");
1837
1838        if (!pack_to_stdout && thin)
1839                die("--thin cannot be used to build an indexable pack.");
1840
1841        prepare_packed_git();
1842
1843        if (progress)
1844                start_progress(&progress_state, "Generating pack...",
1845                               "Counting objects: ", 0);
1846        if (!use_internal_rev_list)
1847                read_object_list_from_stdin();
1848        else {
1849                rp_av[rp_ac] = NULL;
1850                get_object_list(rp_ac, rp_av);
1851        }
1852        if (progress) {
1853                stop_progress(&progress_state);
1854                fprintf(stderr, "Done counting %u objects.\n", nr_objects);
1855        }
1856
1857        if (non_empty && !nr_result)
1858                return 0;
1859        if (progress && (nr_objects != nr_result))
1860                fprintf(stderr, "Result has %u objects.\n", nr_result);
1861        if (nr_result)
1862                prepare_pack(window, depth);
1863        write_pack_file();
1864        if (progress)
1865                fprintf(stderr, "Total %u (delta %u), reused %u (delta %u)\n",
1866                        written, written_delta, reused, reused_delta);
1867        return 0;
1868}