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