packfile.con commit pack: move unpack_object_header_buffer() (32b42e1)
   1#include "cache.h"
   2#include "mru.h"
   3#include "pack.h"
   4#include "dir.h"
   5#include "mergesort.h"
   6#include "packfile.h"
   7
   8char *odb_pack_name(struct strbuf *buf,
   9                    const unsigned char *sha1,
  10                    const char *ext)
  11{
  12        strbuf_reset(buf);
  13        strbuf_addf(buf, "%s/pack/pack-%s.%s", get_object_directory(),
  14                    sha1_to_hex(sha1), ext);
  15        return buf->buf;
  16}
  17
  18char *sha1_pack_name(const unsigned char *sha1)
  19{
  20        static struct strbuf buf = STRBUF_INIT;
  21        return odb_pack_name(&buf, sha1, "pack");
  22}
  23
  24char *sha1_pack_index_name(const unsigned char *sha1)
  25{
  26        static struct strbuf buf = STRBUF_INIT;
  27        return odb_pack_name(&buf, sha1, "idx");
  28}
  29
  30static unsigned int pack_used_ctr;
  31static unsigned int pack_mmap_calls;
  32static unsigned int peak_pack_open_windows;
  33static unsigned int pack_open_windows;
  34static unsigned int pack_open_fds;
  35static unsigned int pack_max_fds;
  36static size_t peak_pack_mapped;
  37static size_t pack_mapped;
  38struct packed_git *packed_git;
  39
  40static struct mru packed_git_mru_storage;
  41struct mru *packed_git_mru = &packed_git_mru_storage;
  42
  43#define SZ_FMT PRIuMAX
  44static inline uintmax_t sz_fmt(size_t s) { return s; }
  45
  46void pack_report(void)
  47{
  48        fprintf(stderr,
  49                "pack_report: getpagesize()            = %10" SZ_FMT "\n"
  50                "pack_report: core.packedGitWindowSize = %10" SZ_FMT "\n"
  51                "pack_report: core.packedGitLimit      = %10" SZ_FMT "\n",
  52                sz_fmt(getpagesize()),
  53                sz_fmt(packed_git_window_size),
  54                sz_fmt(packed_git_limit));
  55        fprintf(stderr,
  56                "pack_report: pack_used_ctr            = %10u\n"
  57                "pack_report: pack_mmap_calls          = %10u\n"
  58                "pack_report: pack_open_windows        = %10u / %10u\n"
  59                "pack_report: pack_mapped              = "
  60                        "%10" SZ_FMT " / %10" SZ_FMT "\n",
  61                pack_used_ctr,
  62                pack_mmap_calls,
  63                pack_open_windows, peak_pack_open_windows,
  64                sz_fmt(pack_mapped), sz_fmt(peak_pack_mapped));
  65}
  66
  67/*
  68 * Open and mmap the index file at path, perform a couple of
  69 * consistency checks, then record its information to p.  Return 0 on
  70 * success.
  71 */
  72static int check_packed_git_idx(const char *path, struct packed_git *p)
  73{
  74        void *idx_map;
  75        struct pack_idx_header *hdr;
  76        size_t idx_size;
  77        uint32_t version, nr, i, *index;
  78        int fd = git_open(path);
  79        struct stat st;
  80
  81        if (fd < 0)
  82                return -1;
  83        if (fstat(fd, &st)) {
  84                close(fd);
  85                return -1;
  86        }
  87        idx_size = xsize_t(st.st_size);
  88        if (idx_size < 4 * 256 + 20 + 20) {
  89                close(fd);
  90                return error("index file %s is too small", path);
  91        }
  92        idx_map = xmmap(NULL, idx_size, PROT_READ, MAP_PRIVATE, fd, 0);
  93        close(fd);
  94
  95        hdr = idx_map;
  96        if (hdr->idx_signature == htonl(PACK_IDX_SIGNATURE)) {
  97                version = ntohl(hdr->idx_version);
  98                if (version < 2 || version > 2) {
  99                        munmap(idx_map, idx_size);
 100                        return error("index file %s is version %"PRIu32
 101                                     " and is not supported by this binary"
 102                                     " (try upgrading GIT to a newer version)",
 103                                     path, version);
 104                }
 105        } else
 106                version = 1;
 107
 108        nr = 0;
 109        index = idx_map;
 110        if (version > 1)
 111                index += 2;  /* skip index header */
 112        for (i = 0; i < 256; i++) {
 113                uint32_t n = ntohl(index[i]);
 114                if (n < nr) {
 115                        munmap(idx_map, idx_size);
 116                        return error("non-monotonic index %s", path);
 117                }
 118                nr = n;
 119        }
 120
 121        if (version == 1) {
 122                /*
 123                 * Total size:
 124                 *  - 256 index entries 4 bytes each
 125                 *  - 24-byte entries * nr (20-byte sha1 + 4-byte offset)
 126                 *  - 20-byte SHA1 of the packfile
 127                 *  - 20-byte SHA1 file checksum
 128                 */
 129                if (idx_size != 4*256 + nr * 24 + 20 + 20) {
 130                        munmap(idx_map, idx_size);
 131                        return error("wrong index v1 file size in %s", path);
 132                }
 133        } else if (version == 2) {
 134                /*
 135                 * Minimum size:
 136                 *  - 8 bytes of header
 137                 *  - 256 index entries 4 bytes each
 138                 *  - 20-byte sha1 entry * nr
 139                 *  - 4-byte crc entry * nr
 140                 *  - 4-byte offset entry * nr
 141                 *  - 20-byte SHA1 of the packfile
 142                 *  - 20-byte SHA1 file checksum
 143                 * And after the 4-byte offset table might be a
 144                 * variable sized table containing 8-byte entries
 145                 * for offsets larger than 2^31.
 146                 */
 147                unsigned long min_size = 8 + 4*256 + nr*(20 + 4 + 4) + 20 + 20;
 148                unsigned long max_size = min_size;
 149                if (nr)
 150                        max_size += (nr - 1)*8;
 151                if (idx_size < min_size || idx_size > max_size) {
 152                        munmap(idx_map, idx_size);
 153                        return error("wrong index v2 file size in %s", path);
 154                }
 155                if (idx_size != min_size &&
 156                    /*
 157                     * make sure we can deal with large pack offsets.
 158                     * 31-bit signed offset won't be enough, neither
 159                     * 32-bit unsigned one will be.
 160                     */
 161                    (sizeof(off_t) <= 4)) {
 162                        munmap(idx_map, idx_size);
 163                        return error("pack too large for current definition of off_t in %s", path);
 164                }
 165        }
 166
 167        p->index_version = version;
 168        p->index_data = idx_map;
 169        p->index_size = idx_size;
 170        p->num_objects = nr;
 171        return 0;
 172}
 173
 174int open_pack_index(struct packed_git *p)
 175{
 176        char *idx_name;
 177        size_t len;
 178        int ret;
 179
 180        if (p->index_data)
 181                return 0;
 182
 183        if (!strip_suffix(p->pack_name, ".pack", &len))
 184                die("BUG: pack_name does not end in .pack");
 185        idx_name = xstrfmt("%.*s.idx", (int)len, p->pack_name);
 186        ret = check_packed_git_idx(idx_name, p);
 187        free(idx_name);
 188        return ret;
 189}
 190
 191static struct packed_git *alloc_packed_git(int extra)
 192{
 193        struct packed_git *p = xmalloc(st_add(sizeof(*p), extra));
 194        memset(p, 0, sizeof(*p));
 195        p->pack_fd = -1;
 196        return p;
 197}
 198
 199struct packed_git *parse_pack_index(unsigned char *sha1, const char *idx_path)
 200{
 201        const char *path = sha1_pack_name(sha1);
 202        size_t alloc = st_add(strlen(path), 1);
 203        struct packed_git *p = alloc_packed_git(alloc);
 204
 205        memcpy(p->pack_name, path, alloc); /* includes NUL */
 206        hashcpy(p->sha1, sha1);
 207        if (check_packed_git_idx(idx_path, p)) {
 208                free(p);
 209                return NULL;
 210        }
 211
 212        return p;
 213}
 214
 215static void scan_windows(struct packed_git *p,
 216        struct packed_git **lru_p,
 217        struct pack_window **lru_w,
 218        struct pack_window **lru_l)
 219{
 220        struct pack_window *w, *w_l;
 221
 222        for (w_l = NULL, w = p->windows; w; w = w->next) {
 223                if (!w->inuse_cnt) {
 224                        if (!*lru_w || w->last_used < (*lru_w)->last_used) {
 225                                *lru_p = p;
 226                                *lru_w = w;
 227                                *lru_l = w_l;
 228                        }
 229                }
 230                w_l = w;
 231        }
 232}
 233
 234static int unuse_one_window(struct packed_git *current)
 235{
 236        struct packed_git *p, *lru_p = NULL;
 237        struct pack_window *lru_w = NULL, *lru_l = NULL;
 238
 239        if (current)
 240                scan_windows(current, &lru_p, &lru_w, &lru_l);
 241        for (p = packed_git; p; p = p->next)
 242                scan_windows(p, &lru_p, &lru_w, &lru_l);
 243        if (lru_p) {
 244                munmap(lru_w->base, lru_w->len);
 245                pack_mapped -= lru_w->len;
 246                if (lru_l)
 247                        lru_l->next = lru_w->next;
 248                else
 249                        lru_p->windows = lru_w->next;
 250                free(lru_w);
 251                pack_open_windows--;
 252                return 1;
 253        }
 254        return 0;
 255}
 256
 257void release_pack_memory(size_t need)
 258{
 259        size_t cur = pack_mapped;
 260        while (need >= (cur - pack_mapped) && unuse_one_window(NULL))
 261                ; /* nothing */
 262}
 263
 264void close_pack_windows(struct packed_git *p)
 265{
 266        while (p->windows) {
 267                struct pack_window *w = p->windows;
 268
 269                if (w->inuse_cnt)
 270                        die("pack '%s' still has open windows to it",
 271                            p->pack_name);
 272                munmap(w->base, w->len);
 273                pack_mapped -= w->len;
 274                pack_open_windows--;
 275                p->windows = w->next;
 276                free(w);
 277        }
 278}
 279
 280static int close_pack_fd(struct packed_git *p)
 281{
 282        if (p->pack_fd < 0)
 283                return 0;
 284
 285        close(p->pack_fd);
 286        pack_open_fds--;
 287        p->pack_fd = -1;
 288
 289        return 1;
 290}
 291
 292void close_pack_index(struct packed_git *p)
 293{
 294        if (p->index_data) {
 295                munmap((void *)p->index_data, p->index_size);
 296                p->index_data = NULL;
 297        }
 298}
 299
 300static void close_pack(struct packed_git *p)
 301{
 302        close_pack_windows(p);
 303        close_pack_fd(p);
 304        close_pack_index(p);
 305}
 306
 307void close_all_packs(void)
 308{
 309        struct packed_git *p;
 310
 311        for (p = packed_git; p; p = p->next)
 312                if (p->do_not_close)
 313                        die("BUG: want to close pack marked 'do-not-close'");
 314                else
 315                        close_pack(p);
 316}
 317
 318/*
 319 * The LRU pack is the one with the oldest MRU window, preferring packs
 320 * with no used windows, or the oldest mtime if it has no windows allocated.
 321 */
 322static void find_lru_pack(struct packed_git *p, struct packed_git **lru_p, struct pack_window **mru_w, int *accept_windows_inuse)
 323{
 324        struct pack_window *w, *this_mru_w;
 325        int has_windows_inuse = 0;
 326
 327        /*
 328         * Reject this pack if it has windows and the previously selected
 329         * one does not.  If this pack does not have windows, reject
 330         * it if the pack file is newer than the previously selected one.
 331         */
 332        if (*lru_p && !*mru_w && (p->windows || p->mtime > (*lru_p)->mtime))
 333                return;
 334
 335        for (w = this_mru_w = p->windows; w; w = w->next) {
 336                /*
 337                 * Reject this pack if any of its windows are in use,
 338                 * but the previously selected pack did not have any
 339                 * inuse windows.  Otherwise, record that this pack
 340                 * has windows in use.
 341                 */
 342                if (w->inuse_cnt) {
 343                        if (*accept_windows_inuse)
 344                                has_windows_inuse = 1;
 345                        else
 346                                return;
 347                }
 348
 349                if (w->last_used > this_mru_w->last_used)
 350                        this_mru_w = w;
 351
 352                /*
 353                 * Reject this pack if it has windows that have been
 354                 * used more recently than the previously selected pack.
 355                 * If the previously selected pack had windows inuse and
 356                 * we have not encountered a window in this pack that is
 357                 * inuse, skip this check since we prefer a pack with no
 358                 * inuse windows to one that has inuse windows.
 359                 */
 360                if (*mru_w && *accept_windows_inuse == has_windows_inuse &&
 361                    this_mru_w->last_used > (*mru_w)->last_used)
 362                        return;
 363        }
 364
 365        /*
 366         * Select this pack.
 367         */
 368        *mru_w = this_mru_w;
 369        *lru_p = p;
 370        *accept_windows_inuse = has_windows_inuse;
 371}
 372
 373static int close_one_pack(void)
 374{
 375        struct packed_git *p, *lru_p = NULL;
 376        struct pack_window *mru_w = NULL;
 377        int accept_windows_inuse = 1;
 378
 379        for (p = packed_git; p; p = p->next) {
 380                if (p->pack_fd == -1)
 381                        continue;
 382                find_lru_pack(p, &lru_p, &mru_w, &accept_windows_inuse);
 383        }
 384
 385        if (lru_p)
 386                return close_pack_fd(lru_p);
 387
 388        return 0;
 389}
 390
 391static unsigned int get_max_fd_limit(void)
 392{
 393#ifdef RLIMIT_NOFILE
 394        {
 395                struct rlimit lim;
 396
 397                if (!getrlimit(RLIMIT_NOFILE, &lim))
 398                        return lim.rlim_cur;
 399        }
 400#endif
 401
 402#ifdef _SC_OPEN_MAX
 403        {
 404                long open_max = sysconf(_SC_OPEN_MAX);
 405                if (0 < open_max)
 406                        return open_max;
 407                /*
 408                 * Otherwise, we got -1 for one of the two
 409                 * reasons:
 410                 *
 411                 * (1) sysconf() did not understand _SC_OPEN_MAX
 412                 *     and signaled an error with -1; or
 413                 * (2) sysconf() said there is no limit.
 414                 *
 415                 * We _could_ clear errno before calling sysconf() to
 416                 * tell these two cases apart and return a huge number
 417                 * in the latter case to let the caller cap it to a
 418                 * value that is not so selfish, but letting the
 419                 * fallback OPEN_MAX codepath take care of these cases
 420                 * is a lot simpler.
 421                 */
 422        }
 423#endif
 424
 425#ifdef OPEN_MAX
 426        return OPEN_MAX;
 427#else
 428        return 1; /* see the caller ;-) */
 429#endif
 430}
 431
 432/*
 433 * Do not call this directly as this leaks p->pack_fd on error return;
 434 * call open_packed_git() instead.
 435 */
 436static int open_packed_git_1(struct packed_git *p)
 437{
 438        struct stat st;
 439        struct pack_header hdr;
 440        unsigned char sha1[20];
 441        unsigned char *idx_sha1;
 442        long fd_flag;
 443
 444        if (!p->index_data && open_pack_index(p))
 445                return error("packfile %s index unavailable", p->pack_name);
 446
 447        if (!pack_max_fds) {
 448                unsigned int max_fds = get_max_fd_limit();
 449
 450                /* Save 3 for stdin/stdout/stderr, 22 for work */
 451                if (25 < max_fds)
 452                        pack_max_fds = max_fds - 25;
 453                else
 454                        pack_max_fds = 1;
 455        }
 456
 457        while (pack_max_fds <= pack_open_fds && close_one_pack())
 458                ; /* nothing */
 459
 460        p->pack_fd = git_open(p->pack_name);
 461        if (p->pack_fd < 0 || fstat(p->pack_fd, &st))
 462                return -1;
 463        pack_open_fds++;
 464
 465        /* If we created the struct before we had the pack we lack size. */
 466        if (!p->pack_size) {
 467                if (!S_ISREG(st.st_mode))
 468                        return error("packfile %s not a regular file", p->pack_name);
 469                p->pack_size = st.st_size;
 470        } else if (p->pack_size != st.st_size)
 471                return error("packfile %s size changed", p->pack_name);
 472
 473        /* We leave these file descriptors open with sliding mmap;
 474         * there is no point keeping them open across exec(), though.
 475         */
 476        fd_flag = fcntl(p->pack_fd, F_GETFD, 0);
 477        if (fd_flag < 0)
 478                return error("cannot determine file descriptor flags");
 479        fd_flag |= FD_CLOEXEC;
 480        if (fcntl(p->pack_fd, F_SETFD, fd_flag) == -1)
 481                return error("cannot set FD_CLOEXEC");
 482
 483        /* Verify we recognize this pack file format. */
 484        if (read_in_full(p->pack_fd, &hdr, sizeof(hdr)) != sizeof(hdr))
 485                return error("file %s is far too short to be a packfile", p->pack_name);
 486        if (hdr.hdr_signature != htonl(PACK_SIGNATURE))
 487                return error("file %s is not a GIT packfile", p->pack_name);
 488        if (!pack_version_ok(hdr.hdr_version))
 489                return error("packfile %s is version %"PRIu32" and not"
 490                        " supported (try upgrading GIT to a newer version)",
 491                        p->pack_name, ntohl(hdr.hdr_version));
 492
 493        /* Verify the pack matches its index. */
 494        if (p->num_objects != ntohl(hdr.hdr_entries))
 495                return error("packfile %s claims to have %"PRIu32" objects"
 496                             " while index indicates %"PRIu32" objects",
 497                             p->pack_name, ntohl(hdr.hdr_entries),
 498                             p->num_objects);
 499        if (lseek(p->pack_fd, p->pack_size - sizeof(sha1), SEEK_SET) == -1)
 500                return error("end of packfile %s is unavailable", p->pack_name);
 501        if (read_in_full(p->pack_fd, sha1, sizeof(sha1)) != sizeof(sha1))
 502                return error("packfile %s signature is unavailable", p->pack_name);
 503        idx_sha1 = ((unsigned char *)p->index_data) + p->index_size - 40;
 504        if (hashcmp(sha1, idx_sha1))
 505                return error("packfile %s does not match index", p->pack_name);
 506        return 0;
 507}
 508
 509int open_packed_git(struct packed_git *p)
 510{
 511        if (!open_packed_git_1(p))
 512                return 0;
 513        close_pack_fd(p);
 514        return -1;
 515}
 516
 517static int in_window(struct pack_window *win, off_t offset)
 518{
 519        /* We must promise at least 20 bytes (one hash) after the
 520         * offset is available from this window, otherwise the offset
 521         * is not actually in this window and a different window (which
 522         * has that one hash excess) must be used.  This is to support
 523         * the object header and delta base parsing routines below.
 524         */
 525        off_t win_off = win->offset;
 526        return win_off <= offset
 527                && (offset + 20) <= (win_off + win->len);
 528}
 529
 530unsigned char *use_pack(struct packed_git *p,
 531                struct pack_window **w_cursor,
 532                off_t offset,
 533                unsigned long *left)
 534{
 535        struct pack_window *win = *w_cursor;
 536
 537        /* Since packfiles end in a hash of their content and it's
 538         * pointless to ask for an offset into the middle of that
 539         * hash, and the in_window function above wouldn't match
 540         * don't allow an offset too close to the end of the file.
 541         */
 542        if (!p->pack_size && p->pack_fd == -1 && open_packed_git(p))
 543                die("packfile %s cannot be accessed", p->pack_name);
 544        if (offset > (p->pack_size - 20))
 545                die("offset beyond end of packfile (truncated pack?)");
 546        if (offset < 0)
 547                die(_("offset before end of packfile (broken .idx?)"));
 548
 549        if (!win || !in_window(win, offset)) {
 550                if (win)
 551                        win->inuse_cnt--;
 552                for (win = p->windows; win; win = win->next) {
 553                        if (in_window(win, offset))
 554                                break;
 555                }
 556                if (!win) {
 557                        size_t window_align = packed_git_window_size / 2;
 558                        off_t len;
 559
 560                        if (p->pack_fd == -1 && open_packed_git(p))
 561                                die("packfile %s cannot be accessed", p->pack_name);
 562
 563                        win = xcalloc(1, sizeof(*win));
 564                        win->offset = (offset / window_align) * window_align;
 565                        len = p->pack_size - win->offset;
 566                        if (len > packed_git_window_size)
 567                                len = packed_git_window_size;
 568                        win->len = (size_t)len;
 569                        pack_mapped += win->len;
 570                        while (packed_git_limit < pack_mapped
 571                                && unuse_one_window(p))
 572                                ; /* nothing */
 573                        win->base = xmmap(NULL, win->len,
 574                                PROT_READ, MAP_PRIVATE,
 575                                p->pack_fd, win->offset);
 576                        if (win->base == MAP_FAILED)
 577                                die_errno("packfile %s cannot be mapped",
 578                                          p->pack_name);
 579                        if (!win->offset && win->len == p->pack_size
 580                                && !p->do_not_close)
 581                                close_pack_fd(p);
 582                        pack_mmap_calls++;
 583                        pack_open_windows++;
 584                        if (pack_mapped > peak_pack_mapped)
 585                                peak_pack_mapped = pack_mapped;
 586                        if (pack_open_windows > peak_pack_open_windows)
 587                                peak_pack_open_windows = pack_open_windows;
 588                        win->next = p->windows;
 589                        p->windows = win;
 590                }
 591        }
 592        if (win != *w_cursor) {
 593                win->last_used = pack_used_ctr++;
 594                win->inuse_cnt++;
 595                *w_cursor = win;
 596        }
 597        offset -= win->offset;
 598        if (left)
 599                *left = win->len - xsize_t(offset);
 600        return win->base + offset;
 601}
 602
 603void unuse_pack(struct pack_window **w_cursor)
 604{
 605        struct pack_window *w = *w_cursor;
 606        if (w) {
 607                w->inuse_cnt--;
 608                *w_cursor = NULL;
 609        }
 610}
 611
 612static void try_to_free_pack_memory(size_t size)
 613{
 614        release_pack_memory(size);
 615}
 616
 617struct packed_git *add_packed_git(const char *path, size_t path_len, int local)
 618{
 619        static int have_set_try_to_free_routine;
 620        struct stat st;
 621        size_t alloc;
 622        struct packed_git *p;
 623
 624        if (!have_set_try_to_free_routine) {
 625                have_set_try_to_free_routine = 1;
 626                set_try_to_free_routine(try_to_free_pack_memory);
 627        }
 628
 629        /*
 630         * Make sure a corresponding .pack file exists and that
 631         * the index looks sane.
 632         */
 633        if (!strip_suffix_mem(path, &path_len, ".idx"))
 634                return NULL;
 635
 636        /*
 637         * ".pack" is long enough to hold any suffix we're adding (and
 638         * the use xsnprintf double-checks that)
 639         */
 640        alloc = st_add3(path_len, strlen(".pack"), 1);
 641        p = alloc_packed_git(alloc);
 642        memcpy(p->pack_name, path, path_len);
 643
 644        xsnprintf(p->pack_name + path_len, alloc - path_len, ".keep");
 645        if (!access(p->pack_name, F_OK))
 646                p->pack_keep = 1;
 647
 648        xsnprintf(p->pack_name + path_len, alloc - path_len, ".pack");
 649        if (stat(p->pack_name, &st) || !S_ISREG(st.st_mode)) {
 650                free(p);
 651                return NULL;
 652        }
 653
 654        /* ok, it looks sane as far as we can check without
 655         * actually mapping the pack file.
 656         */
 657        p->pack_size = st.st_size;
 658        p->pack_local = local;
 659        p->mtime = st.st_mtime;
 660        if (path_len < 40 || get_sha1_hex(path + path_len - 40, p->sha1))
 661                hashclr(p->sha1);
 662        return p;
 663}
 664
 665void install_packed_git(struct packed_git *pack)
 666{
 667        if (pack->pack_fd != -1)
 668                pack_open_fds++;
 669
 670        pack->next = packed_git;
 671        packed_git = pack;
 672}
 673
 674void (*report_garbage)(unsigned seen_bits, const char *path);
 675
 676static void report_helper(const struct string_list *list,
 677                          int seen_bits, int first, int last)
 678{
 679        if (seen_bits == (PACKDIR_FILE_PACK|PACKDIR_FILE_IDX))
 680                return;
 681
 682        for (; first < last; first++)
 683                report_garbage(seen_bits, list->items[first].string);
 684}
 685
 686static void report_pack_garbage(struct string_list *list)
 687{
 688        int i, baselen = -1, first = 0, seen_bits = 0;
 689
 690        if (!report_garbage)
 691                return;
 692
 693        string_list_sort(list);
 694
 695        for (i = 0; i < list->nr; i++) {
 696                const char *path = list->items[i].string;
 697                if (baselen != -1 &&
 698                    strncmp(path, list->items[first].string, baselen)) {
 699                        report_helper(list, seen_bits, first, i);
 700                        baselen = -1;
 701                        seen_bits = 0;
 702                }
 703                if (baselen == -1) {
 704                        const char *dot = strrchr(path, '.');
 705                        if (!dot) {
 706                                report_garbage(PACKDIR_FILE_GARBAGE, path);
 707                                continue;
 708                        }
 709                        baselen = dot - path + 1;
 710                        first = i;
 711                }
 712                if (!strcmp(path + baselen, "pack"))
 713                        seen_bits |= 1;
 714                else if (!strcmp(path + baselen, "idx"))
 715                        seen_bits |= 2;
 716        }
 717        report_helper(list, seen_bits, first, list->nr);
 718}
 719
 720static void prepare_packed_git_one(char *objdir, int local)
 721{
 722        struct strbuf path = STRBUF_INIT;
 723        size_t dirnamelen;
 724        DIR *dir;
 725        struct dirent *de;
 726        struct string_list garbage = STRING_LIST_INIT_DUP;
 727
 728        strbuf_addstr(&path, objdir);
 729        strbuf_addstr(&path, "/pack");
 730        dir = opendir(path.buf);
 731        if (!dir) {
 732                if (errno != ENOENT)
 733                        error_errno("unable to open object pack directory: %s",
 734                                    path.buf);
 735                strbuf_release(&path);
 736                return;
 737        }
 738        strbuf_addch(&path, '/');
 739        dirnamelen = path.len;
 740        while ((de = readdir(dir)) != NULL) {
 741                struct packed_git *p;
 742                size_t base_len;
 743
 744                if (is_dot_or_dotdot(de->d_name))
 745                        continue;
 746
 747                strbuf_setlen(&path, dirnamelen);
 748                strbuf_addstr(&path, de->d_name);
 749
 750                base_len = path.len;
 751                if (strip_suffix_mem(path.buf, &base_len, ".idx")) {
 752                        /* Don't reopen a pack we already have. */
 753                        for (p = packed_git; p; p = p->next) {
 754                                size_t len;
 755                                if (strip_suffix(p->pack_name, ".pack", &len) &&
 756                                    len == base_len &&
 757                                    !memcmp(p->pack_name, path.buf, len))
 758                                        break;
 759                        }
 760                        if (p == NULL &&
 761                            /*
 762                             * See if it really is a valid .idx file with
 763                             * corresponding .pack file that we can map.
 764                             */
 765                            (p = add_packed_git(path.buf, path.len, local)) != NULL)
 766                                install_packed_git(p);
 767                }
 768
 769                if (!report_garbage)
 770                        continue;
 771
 772                if (ends_with(de->d_name, ".idx") ||
 773                    ends_with(de->d_name, ".pack") ||
 774                    ends_with(de->d_name, ".bitmap") ||
 775                    ends_with(de->d_name, ".keep"))
 776                        string_list_append(&garbage, path.buf);
 777                else
 778                        report_garbage(PACKDIR_FILE_GARBAGE, path.buf);
 779        }
 780        closedir(dir);
 781        report_pack_garbage(&garbage);
 782        string_list_clear(&garbage, 0);
 783        strbuf_release(&path);
 784}
 785
 786static int approximate_object_count_valid;
 787
 788/*
 789 * Give a fast, rough count of the number of objects in the repository. This
 790 * ignores loose objects completely. If you have a lot of them, then either
 791 * you should repack because your performance will be awful, or they are
 792 * all unreachable objects about to be pruned, in which case they're not really
 793 * interesting as a measure of repo size in the first place.
 794 */
 795unsigned long approximate_object_count(void)
 796{
 797        static unsigned long count;
 798        if (!approximate_object_count_valid) {
 799                struct packed_git *p;
 800
 801                prepare_packed_git();
 802                count = 0;
 803                for (p = packed_git; p; p = p->next) {
 804                        if (open_pack_index(p))
 805                                continue;
 806                        count += p->num_objects;
 807                }
 808        }
 809        return count;
 810}
 811
 812static void *get_next_packed_git(const void *p)
 813{
 814        return ((const struct packed_git *)p)->next;
 815}
 816
 817static void set_next_packed_git(void *p, void *next)
 818{
 819        ((struct packed_git *)p)->next = next;
 820}
 821
 822static int sort_pack(const void *a_, const void *b_)
 823{
 824        const struct packed_git *a = a_;
 825        const struct packed_git *b = b_;
 826        int st;
 827
 828        /*
 829         * Local packs tend to contain objects specific to our
 830         * variant of the project than remote ones.  In addition,
 831         * remote ones could be on a network mounted filesystem.
 832         * Favor local ones for these reasons.
 833         */
 834        st = a->pack_local - b->pack_local;
 835        if (st)
 836                return -st;
 837
 838        /*
 839         * Younger packs tend to contain more recent objects,
 840         * and more recent objects tend to get accessed more
 841         * often.
 842         */
 843        if (a->mtime < b->mtime)
 844                return 1;
 845        else if (a->mtime == b->mtime)
 846                return 0;
 847        return -1;
 848}
 849
 850static void rearrange_packed_git(void)
 851{
 852        packed_git = llist_mergesort(packed_git, get_next_packed_git,
 853                                     set_next_packed_git, sort_pack);
 854}
 855
 856static void prepare_packed_git_mru(void)
 857{
 858        struct packed_git *p;
 859
 860        mru_clear(packed_git_mru);
 861        for (p = packed_git; p; p = p->next)
 862                mru_append(packed_git_mru, p);
 863}
 864
 865static int prepare_packed_git_run_once = 0;
 866void prepare_packed_git(void)
 867{
 868        struct alternate_object_database *alt;
 869
 870        if (prepare_packed_git_run_once)
 871                return;
 872        prepare_packed_git_one(get_object_directory(), 1);
 873        prepare_alt_odb();
 874        for (alt = alt_odb_list; alt; alt = alt->next)
 875                prepare_packed_git_one(alt->path, 0);
 876        rearrange_packed_git();
 877        prepare_packed_git_mru();
 878        prepare_packed_git_run_once = 1;
 879}
 880
 881void reprepare_packed_git(void)
 882{
 883        approximate_object_count_valid = 0;
 884        prepare_packed_git_run_once = 0;
 885        prepare_packed_git();
 886}
 887
 888unsigned long unpack_object_header_buffer(const unsigned char *buf,
 889                unsigned long len, enum object_type *type, unsigned long *sizep)
 890{
 891        unsigned shift;
 892        unsigned long size, c;
 893        unsigned long used = 0;
 894
 895        c = buf[used++];
 896        *type = (c >> 4) & 7;
 897        size = c & 15;
 898        shift = 4;
 899        while (c & 0x80) {
 900                if (len <= used || bitsizeof(long) <= shift) {
 901                        error("bad object header");
 902                        size = used = 0;
 903                        break;
 904                }
 905                c = buf[used++];
 906                size += (c & 0x7f) << shift;
 907                shift += 7;
 908        }
 909        *sizep = size;
 910        return used;
 911}