6d4b84e243807108d51fce2df196af2963d7562a
   1#include "cache.h"
   2#include "config.h"
   3#include "csum-file.h"
   4#include "dir.h"
   5#include "lockfile.h"
   6#include "packfile.h"
   7#include "object-store.h"
   8#include "sha1-lookup.h"
   9#include "midx.h"
  10#include "progress.h"
  11#include "trace2.h"
  12
  13#define MIDX_SIGNATURE 0x4d494458 /* "MIDX" */
  14#define MIDX_VERSION 1
  15#define MIDX_BYTE_FILE_VERSION 4
  16#define MIDX_BYTE_HASH_VERSION 5
  17#define MIDX_BYTE_NUM_CHUNKS 6
  18#define MIDX_BYTE_NUM_PACKS 8
  19#define MIDX_HASH_VERSION 1
  20#define MIDX_HEADER_SIZE 12
  21#define MIDX_HASH_LEN 20
  22#define MIDX_MIN_SIZE (MIDX_HEADER_SIZE + MIDX_HASH_LEN)
  23
  24#define MIDX_MAX_CHUNKS 5
  25#define MIDX_CHUNK_ALIGNMENT 4
  26#define MIDX_CHUNKID_PACKNAMES 0x504e414d /* "PNAM" */
  27#define MIDX_CHUNKID_OIDFANOUT 0x4f494446 /* "OIDF" */
  28#define MIDX_CHUNKID_OIDLOOKUP 0x4f49444c /* "OIDL" */
  29#define MIDX_CHUNKID_OBJECTOFFSETS 0x4f4f4646 /* "OOFF" */
  30#define MIDX_CHUNKID_LARGEOFFSETS 0x4c4f4646 /* "LOFF" */
  31#define MIDX_CHUNKLOOKUP_WIDTH (sizeof(uint32_t) + sizeof(uint64_t))
  32#define MIDX_CHUNK_FANOUT_SIZE (sizeof(uint32_t) * 256)
  33#define MIDX_CHUNK_OFFSET_WIDTH (2 * sizeof(uint32_t))
  34#define MIDX_CHUNK_LARGE_OFFSET_WIDTH (sizeof(uint64_t))
  35#define MIDX_LARGE_OFFSET_NEEDED 0x80000000
  36
  37static char *get_midx_filename(const char *object_dir)
  38{
  39        return xstrfmt("%s/pack/multi-pack-index", object_dir);
  40}
  41
  42struct multi_pack_index *load_multi_pack_index(const char *object_dir, int local)
  43{
  44        struct multi_pack_index *m = NULL;
  45        int fd;
  46        struct stat st;
  47        size_t midx_size;
  48        void *midx_map = NULL;
  49        uint32_t hash_version;
  50        char *midx_name = get_midx_filename(object_dir);
  51        uint32_t i;
  52        const char *cur_pack_name;
  53
  54        fd = git_open(midx_name);
  55
  56        if (fd < 0)
  57                goto cleanup_fail;
  58        if (fstat(fd, &st)) {
  59                error_errno(_("failed to read %s"), midx_name);
  60                goto cleanup_fail;
  61        }
  62
  63        midx_size = xsize_t(st.st_size);
  64
  65        if (midx_size < MIDX_MIN_SIZE) {
  66                error(_("multi-pack-index file %s is too small"), midx_name);
  67                goto cleanup_fail;
  68        }
  69
  70        FREE_AND_NULL(midx_name);
  71
  72        midx_map = xmmap(NULL, midx_size, PROT_READ, MAP_PRIVATE, fd, 0);
  73
  74        FLEX_ALLOC_STR(m, object_dir, object_dir);
  75        m->fd = fd;
  76        m->data = midx_map;
  77        m->data_len = midx_size;
  78        m->local = local;
  79
  80        m->signature = get_be32(m->data);
  81        if (m->signature != MIDX_SIGNATURE)
  82                die(_("multi-pack-index signature 0x%08x does not match signature 0x%08x"),
  83                      m->signature, MIDX_SIGNATURE);
  84
  85        m->version = m->data[MIDX_BYTE_FILE_VERSION];
  86        if (m->version != MIDX_VERSION)
  87                die(_("multi-pack-index version %d not recognized"),
  88                      m->version);
  89
  90        hash_version = m->data[MIDX_BYTE_HASH_VERSION];
  91        if (hash_version != MIDX_HASH_VERSION)
  92                die(_("hash version %u does not match"), hash_version);
  93        m->hash_len = MIDX_HASH_LEN;
  94
  95        m->num_chunks = m->data[MIDX_BYTE_NUM_CHUNKS];
  96
  97        m->num_packs = get_be32(m->data + MIDX_BYTE_NUM_PACKS);
  98
  99        for (i = 0; i < m->num_chunks; i++) {
 100                uint32_t chunk_id = get_be32(m->data + MIDX_HEADER_SIZE +
 101                                             MIDX_CHUNKLOOKUP_WIDTH * i);
 102                uint64_t chunk_offset = get_be64(m->data + MIDX_HEADER_SIZE + 4 +
 103                                                 MIDX_CHUNKLOOKUP_WIDTH * i);
 104
 105                if (chunk_offset >= m->data_len)
 106                        die(_("invalid chunk offset (too large)"));
 107
 108                switch (chunk_id) {
 109                        case MIDX_CHUNKID_PACKNAMES:
 110                                m->chunk_pack_names = m->data + chunk_offset;
 111                                break;
 112
 113                        case MIDX_CHUNKID_OIDFANOUT:
 114                                m->chunk_oid_fanout = (uint32_t *)(m->data + chunk_offset);
 115                                break;
 116
 117                        case MIDX_CHUNKID_OIDLOOKUP:
 118                                m->chunk_oid_lookup = m->data + chunk_offset;
 119                                break;
 120
 121                        case MIDX_CHUNKID_OBJECTOFFSETS:
 122                                m->chunk_object_offsets = m->data + chunk_offset;
 123                                break;
 124
 125                        case MIDX_CHUNKID_LARGEOFFSETS:
 126                                m->chunk_large_offsets = m->data + chunk_offset;
 127                                break;
 128
 129                        case 0:
 130                                die(_("terminating multi-pack-index chunk id appears earlier than expected"));
 131                                break;
 132
 133                        default:
 134                                /*
 135                                 * Do nothing on unrecognized chunks, allowing future
 136                                 * extensions to add optional chunks.
 137                                 */
 138                                break;
 139                }
 140        }
 141
 142        if (!m->chunk_pack_names)
 143                die(_("multi-pack-index missing required pack-name chunk"));
 144        if (!m->chunk_oid_fanout)
 145                die(_("multi-pack-index missing required OID fanout chunk"));
 146        if (!m->chunk_oid_lookup)
 147                die(_("multi-pack-index missing required OID lookup chunk"));
 148        if (!m->chunk_object_offsets)
 149                die(_("multi-pack-index missing required object offsets chunk"));
 150
 151        m->num_objects = ntohl(m->chunk_oid_fanout[255]);
 152
 153        m->pack_names = xcalloc(m->num_packs, sizeof(*m->pack_names));
 154        m->packs = xcalloc(m->num_packs, sizeof(*m->packs));
 155
 156        cur_pack_name = (const char *)m->chunk_pack_names;
 157        for (i = 0; i < m->num_packs; i++) {
 158                m->pack_names[i] = cur_pack_name;
 159
 160                cur_pack_name += strlen(cur_pack_name) + 1;
 161
 162                if (i && strcmp(m->pack_names[i], m->pack_names[i - 1]) <= 0)
 163                        die(_("multi-pack-index pack names out of order: '%s' before '%s'"),
 164                              m->pack_names[i - 1],
 165                              m->pack_names[i]);
 166        }
 167
 168        trace2_data_intmax("midx", the_repository, "load/num_packs", m->num_packs);
 169        trace2_data_intmax("midx", the_repository, "load/num_objects", m->num_objects);
 170
 171        return m;
 172
 173cleanup_fail:
 174        free(m);
 175        free(midx_name);
 176        if (midx_map)
 177                munmap(midx_map, midx_size);
 178        if (0 <= fd)
 179                close(fd);
 180        return NULL;
 181}
 182
 183void close_midx(struct multi_pack_index *m)
 184{
 185        uint32_t i;
 186
 187        if (!m)
 188                return;
 189
 190        munmap((unsigned char *)m->data, m->data_len);
 191        close(m->fd);
 192        m->fd = -1;
 193
 194        for (i = 0; i < m->num_packs; i++) {
 195                if (m->packs[i])
 196                        m->packs[i]->multi_pack_index = 0;
 197        }
 198        FREE_AND_NULL(m->packs);
 199        FREE_AND_NULL(m->pack_names);
 200}
 201
 202int prepare_midx_pack(struct repository *r, struct multi_pack_index *m, uint32_t pack_int_id)
 203{
 204        struct strbuf pack_name = STRBUF_INIT;
 205        struct packed_git *p;
 206
 207        if (pack_int_id >= m->num_packs)
 208                die(_("bad pack-int-id: %u (%u total packs)"),
 209                    pack_int_id, m->num_packs);
 210
 211        if (m->packs[pack_int_id])
 212                return 0;
 213
 214        strbuf_addf(&pack_name, "%s/pack/%s", m->object_dir,
 215                    m->pack_names[pack_int_id]);
 216
 217        p = add_packed_git(pack_name.buf, pack_name.len, m->local);
 218        strbuf_release(&pack_name);
 219
 220        if (!p)
 221                return 1;
 222
 223        p->multi_pack_index = 1;
 224        m->packs[pack_int_id] = p;
 225        install_packed_git(r, p);
 226        list_add_tail(&p->mru, &r->objects->packed_git_mru);
 227
 228        return 0;
 229}
 230
 231int bsearch_midx(const struct object_id *oid, struct multi_pack_index *m, uint32_t *result)
 232{
 233        return bsearch_hash(oid->hash, m->chunk_oid_fanout, m->chunk_oid_lookup,
 234                            MIDX_HASH_LEN, result);
 235}
 236
 237struct object_id *nth_midxed_object_oid(struct object_id *oid,
 238                                        struct multi_pack_index *m,
 239                                        uint32_t n)
 240{
 241        if (n >= m->num_objects)
 242                return NULL;
 243
 244        hashcpy(oid->hash, m->chunk_oid_lookup + m->hash_len * n);
 245        return oid;
 246}
 247
 248static off_t nth_midxed_offset(struct multi_pack_index *m, uint32_t pos)
 249{
 250        const unsigned char *offset_data;
 251        uint32_t offset32;
 252
 253        offset_data = m->chunk_object_offsets + pos * MIDX_CHUNK_OFFSET_WIDTH;
 254        offset32 = get_be32(offset_data + sizeof(uint32_t));
 255
 256        if (m->chunk_large_offsets && offset32 & MIDX_LARGE_OFFSET_NEEDED) {
 257                if (sizeof(off_t) < sizeof(uint64_t))
 258                        die(_("multi-pack-index stores a 64-bit offset, but off_t is too small"));
 259
 260                offset32 ^= MIDX_LARGE_OFFSET_NEEDED;
 261                return get_be64(m->chunk_large_offsets + sizeof(uint64_t) * offset32);
 262        }
 263
 264        return offset32;
 265}
 266
 267static uint32_t nth_midxed_pack_int_id(struct multi_pack_index *m, uint32_t pos)
 268{
 269        return get_be32(m->chunk_object_offsets + pos * MIDX_CHUNK_OFFSET_WIDTH);
 270}
 271
 272static int nth_midxed_pack_entry(struct repository *r,
 273                                 struct multi_pack_index *m,
 274                                 struct pack_entry *e,
 275                                 uint32_t pos)
 276{
 277        uint32_t pack_int_id;
 278        struct packed_git *p;
 279
 280        if (pos >= m->num_objects)
 281                return 0;
 282
 283        pack_int_id = nth_midxed_pack_int_id(m, pos);
 284
 285        if (prepare_midx_pack(r, m, pack_int_id))
 286                die(_("error preparing packfile from multi-pack-index"));
 287        p = m->packs[pack_int_id];
 288
 289        /*
 290        * We are about to tell the caller where they can locate the
 291        * requested object.  We better make sure the packfile is
 292        * still here and can be accessed before supplying that
 293        * answer, as it may have been deleted since the MIDX was
 294        * loaded!
 295        */
 296        if (!is_pack_valid(p))
 297                return 0;
 298
 299        if (p->num_bad_objects) {
 300                uint32_t i;
 301                struct object_id oid;
 302                nth_midxed_object_oid(&oid, m, pos);
 303                for (i = 0; i < p->num_bad_objects; i++)
 304                        if (hasheq(oid.hash,
 305                                   p->bad_object_sha1 + the_hash_algo->rawsz * i))
 306                                return 0;
 307        }
 308
 309        e->offset = nth_midxed_offset(m, pos);
 310        e->p = p;
 311
 312        return 1;
 313}
 314
 315int fill_midx_entry(struct repository * r,
 316                    const struct object_id *oid,
 317                    struct pack_entry *e,
 318                    struct multi_pack_index *m)
 319{
 320        uint32_t pos;
 321
 322        if (!bsearch_midx(oid, m, &pos))
 323                return 0;
 324
 325        return nth_midxed_pack_entry(r, m, e, pos);
 326}
 327
 328/* Match "foo.idx" against either "foo.pack" _or_ "foo.idx". */
 329static int cmp_idx_or_pack_name(const char *idx_or_pack_name,
 330                                const char *idx_name)
 331{
 332        /* Skip past any initial matching prefix. */
 333        while (*idx_name && *idx_name == *idx_or_pack_name) {
 334                idx_name++;
 335                idx_or_pack_name++;
 336        }
 337
 338        /*
 339         * If we didn't match completely, we may have matched "pack-1234." and
 340         * be left with "idx" and "pack" respectively, which is also OK. We do
 341         * not have to check for "idx" and "idx", because that would have been
 342         * a complete match (and in that case these strcmps will be false, but
 343         * we'll correctly return 0 from the final strcmp() below.
 344         *
 345         * Technically this matches "fooidx" and "foopack", but we'd never have
 346         * such names in the first place.
 347         */
 348        if (!strcmp(idx_name, "idx") && !strcmp(idx_or_pack_name, "pack"))
 349                return 0;
 350
 351        /*
 352         * This not only checks for a complete match, but also orders based on
 353         * the first non-identical character, which means our ordering will
 354         * match a raw strcmp(). That makes it OK to use this to binary search
 355         * a naively-sorted list.
 356         */
 357        return strcmp(idx_or_pack_name, idx_name);
 358}
 359
 360int midx_contains_pack(struct multi_pack_index *m, const char *idx_or_pack_name)
 361{
 362        uint32_t first = 0, last = m->num_packs;
 363
 364        while (first < last) {
 365                uint32_t mid = first + (last - first) / 2;
 366                const char *current;
 367                int cmp;
 368
 369                current = m->pack_names[mid];
 370                cmp = cmp_idx_or_pack_name(idx_or_pack_name, current);
 371                if (!cmp)
 372                        return 1;
 373                if (cmp > 0) {
 374                        first = mid + 1;
 375                        continue;
 376                }
 377                last = mid;
 378        }
 379
 380        return 0;
 381}
 382
 383int prepare_multi_pack_index_one(struct repository *r, const char *object_dir, int local)
 384{
 385        struct multi_pack_index *m;
 386        struct multi_pack_index *m_search;
 387        int config_value;
 388        static int env_value = -1;
 389
 390        if (env_value < 0)
 391                env_value = git_env_bool(GIT_TEST_MULTI_PACK_INDEX, 0);
 392
 393        if (!env_value &&
 394            (repo_config_get_bool(r, "core.multipackindex", &config_value) ||
 395            !config_value))
 396                return 0;
 397
 398        for (m_search = r->objects->multi_pack_index; m_search; m_search = m_search->next)
 399                if (!strcmp(object_dir, m_search->object_dir))
 400                        return 1;
 401
 402        m = load_multi_pack_index(object_dir, local);
 403
 404        if (m) {
 405                m->next = r->objects->multi_pack_index;
 406                r->objects->multi_pack_index = m;
 407                return 1;
 408        }
 409
 410        return 0;
 411}
 412
 413static size_t write_midx_header(struct hashfile *f,
 414                                unsigned char num_chunks,
 415                                uint32_t num_packs)
 416{
 417        unsigned char byte_values[4];
 418
 419        hashwrite_be32(f, MIDX_SIGNATURE);
 420        byte_values[0] = MIDX_VERSION;
 421        byte_values[1] = MIDX_HASH_VERSION;
 422        byte_values[2] = num_chunks;
 423        byte_values[3] = 0; /* unused */
 424        hashwrite(f, byte_values, sizeof(byte_values));
 425        hashwrite_be32(f, num_packs);
 426
 427        return MIDX_HEADER_SIZE;
 428}
 429
 430struct pack_info {
 431        uint32_t orig_pack_int_id;
 432        char *pack_name;
 433        struct packed_git *p;
 434};
 435
 436static int pack_info_compare(const void *_a, const void *_b)
 437{
 438        struct pack_info *a = (struct pack_info *)_a;
 439        struct pack_info *b = (struct pack_info *)_b;
 440        return strcmp(a->pack_name, b->pack_name);
 441}
 442
 443struct pack_list {
 444        struct pack_info *info;
 445        uint32_t nr;
 446        uint32_t alloc;
 447        struct multi_pack_index *m;
 448};
 449
 450static void add_pack_to_midx(const char *full_path, size_t full_path_len,
 451                             const char *file_name, void *data)
 452{
 453        struct pack_list *packs = (struct pack_list *)data;
 454
 455        if (ends_with(file_name, ".idx")) {
 456                if (packs->m && midx_contains_pack(packs->m, file_name))
 457                        return;
 458
 459                ALLOC_GROW(packs->info, packs->nr + 1, packs->alloc);
 460
 461                packs->info[packs->nr].p = add_packed_git(full_path,
 462                                                          full_path_len,
 463                                                          0);
 464
 465                if (!packs->info[packs->nr].p) {
 466                        warning(_("failed to add packfile '%s'"),
 467                                full_path);
 468                        return;
 469                }
 470
 471                if (open_pack_index(packs->info[packs->nr].p)) {
 472                        warning(_("failed to open pack-index '%s'"),
 473                                full_path);
 474                        close_pack(packs->info[packs->nr].p);
 475                        FREE_AND_NULL(packs->info[packs->nr].p);
 476                        return;
 477                }
 478
 479                packs->info[packs->nr].pack_name = xstrdup(file_name);
 480                packs->info[packs->nr].orig_pack_int_id = packs->nr;
 481                packs->nr++;
 482        }
 483}
 484
 485struct pack_midx_entry {
 486        struct object_id oid;
 487        uint32_t pack_int_id;
 488        time_t pack_mtime;
 489        uint64_t offset;
 490};
 491
 492static int midx_oid_compare(const void *_a, const void *_b)
 493{
 494        const struct pack_midx_entry *a = (const struct pack_midx_entry *)_a;
 495        const struct pack_midx_entry *b = (const struct pack_midx_entry *)_b;
 496        int cmp = oidcmp(&a->oid, &b->oid);
 497
 498        if (cmp)
 499                return cmp;
 500
 501        if (a->pack_mtime > b->pack_mtime)
 502                return -1;
 503        else if (a->pack_mtime < b->pack_mtime)
 504                return 1;
 505
 506        return a->pack_int_id - b->pack_int_id;
 507}
 508
 509static int nth_midxed_pack_midx_entry(struct multi_pack_index *m,
 510                                      struct pack_midx_entry *e,
 511                                      uint32_t pos)
 512{
 513        if (pos >= m->num_objects)
 514                return 1;
 515
 516        nth_midxed_object_oid(&e->oid, m, pos);
 517        e->pack_int_id = nth_midxed_pack_int_id(m, pos);
 518        e->offset = nth_midxed_offset(m, pos);
 519
 520        /* consider objects in midx to be from "old" packs */
 521        e->pack_mtime = 0;
 522        return 0;
 523}
 524
 525static void fill_pack_entry(uint32_t pack_int_id,
 526                            struct packed_git *p,
 527                            uint32_t cur_object,
 528                            struct pack_midx_entry *entry)
 529{
 530        if (!nth_packed_object_oid(&entry->oid, p, cur_object))
 531                die(_("failed to locate object %d in packfile"), cur_object);
 532
 533        entry->pack_int_id = pack_int_id;
 534        entry->pack_mtime = p->mtime;
 535
 536        entry->offset = nth_packed_object_offset(p, cur_object);
 537}
 538
 539/*
 540 * It is possible to artificially get into a state where there are many
 541 * duplicate copies of objects. That can create high memory pressure if
 542 * we are to create a list of all objects before de-duplication. To reduce
 543 * this memory pressure without a significant performance drop, automatically
 544 * group objects by the first byte of their object id. Use the IDX fanout
 545 * tables to group the data, copy to a local array, then sort.
 546 *
 547 * Copy only the de-duplicated entries (selected by most-recent modified time
 548 * of a packfile containing the object).
 549 */
 550static struct pack_midx_entry *get_sorted_entries(struct multi_pack_index *m,
 551                                                  struct pack_info *info,
 552                                                  uint32_t nr_packs,
 553                                                  uint32_t *nr_objects)
 554{
 555        uint32_t cur_fanout, cur_pack, cur_object;
 556        uint32_t alloc_fanout, alloc_objects, total_objects = 0;
 557        struct pack_midx_entry *entries_by_fanout = NULL;
 558        struct pack_midx_entry *deduplicated_entries = NULL;
 559        uint32_t start_pack = m ? m->num_packs : 0;
 560
 561        for (cur_pack = start_pack; cur_pack < nr_packs; cur_pack++)
 562                total_objects += info[cur_pack].p->num_objects;
 563
 564        /*
 565         * As we de-duplicate by fanout value, we expect the fanout
 566         * slices to be evenly distributed, with some noise. Hence,
 567         * allocate slightly more than one 256th.
 568         */
 569        alloc_objects = alloc_fanout = total_objects > 3200 ? total_objects / 200 : 16;
 570
 571        ALLOC_ARRAY(entries_by_fanout, alloc_fanout);
 572        ALLOC_ARRAY(deduplicated_entries, alloc_objects);
 573        *nr_objects = 0;
 574
 575        for (cur_fanout = 0; cur_fanout < 256; cur_fanout++) {
 576                uint32_t nr_fanout = 0;
 577
 578                if (m) {
 579                        uint32_t start = 0, end;
 580
 581                        if (cur_fanout)
 582                                start = ntohl(m->chunk_oid_fanout[cur_fanout - 1]);
 583                        end = ntohl(m->chunk_oid_fanout[cur_fanout]);
 584
 585                        for (cur_object = start; cur_object < end; cur_object++) {
 586                                ALLOC_GROW(entries_by_fanout, nr_fanout + 1, alloc_fanout);
 587                                nth_midxed_pack_midx_entry(m,
 588                                                           &entries_by_fanout[nr_fanout],
 589                                                           cur_object);
 590                                nr_fanout++;
 591                        }
 592                }
 593
 594                for (cur_pack = start_pack; cur_pack < nr_packs; cur_pack++) {
 595                        uint32_t start = 0, end;
 596
 597                        if (cur_fanout)
 598                                start = get_pack_fanout(info[cur_pack].p, cur_fanout - 1);
 599                        end = get_pack_fanout(info[cur_pack].p, cur_fanout);
 600
 601                        for (cur_object = start; cur_object < end; cur_object++) {
 602                                ALLOC_GROW(entries_by_fanout, nr_fanout + 1, alloc_fanout);
 603                                fill_pack_entry(cur_pack, info[cur_pack].p, cur_object, &entries_by_fanout[nr_fanout]);
 604                                nr_fanout++;
 605                        }
 606                }
 607
 608                QSORT(entries_by_fanout, nr_fanout, midx_oid_compare);
 609
 610                /*
 611                 * The batch is now sorted by OID and then mtime (descending).
 612                 * Take only the first duplicate.
 613                 */
 614                for (cur_object = 0; cur_object < nr_fanout; cur_object++) {
 615                        if (cur_object && oideq(&entries_by_fanout[cur_object - 1].oid,
 616                                                &entries_by_fanout[cur_object].oid))
 617                                continue;
 618
 619                        ALLOC_GROW(deduplicated_entries, *nr_objects + 1, alloc_objects);
 620                        memcpy(&deduplicated_entries[*nr_objects],
 621                               &entries_by_fanout[cur_object],
 622                               sizeof(struct pack_midx_entry));
 623                        (*nr_objects)++;
 624                }
 625        }
 626
 627        free(entries_by_fanout);
 628        return deduplicated_entries;
 629}
 630
 631static size_t write_midx_pack_names(struct hashfile *f,
 632                                    struct pack_info *info,
 633                                    uint32_t num_packs)
 634{
 635        uint32_t i;
 636        unsigned char padding[MIDX_CHUNK_ALIGNMENT];
 637        size_t written = 0;
 638
 639        for (i = 0; i < num_packs; i++) {
 640                size_t writelen = strlen(info[i].pack_name) + 1;
 641
 642                if (i && strcmp(info[i].pack_name, info[i - 1].pack_name) <= 0)
 643                        BUG("incorrect pack-file order: %s before %s",
 644                            info[i - 1].pack_name,
 645                            info[i].pack_name);
 646
 647                hashwrite(f, info[i].pack_name, writelen);
 648                written += writelen;
 649        }
 650
 651        /* add padding to be aligned */
 652        i = MIDX_CHUNK_ALIGNMENT - (written % MIDX_CHUNK_ALIGNMENT);
 653        if (i < MIDX_CHUNK_ALIGNMENT) {
 654                memset(padding, 0, sizeof(padding));
 655                hashwrite(f, padding, i);
 656                written += i;
 657        }
 658
 659        return written;
 660}
 661
 662static size_t write_midx_oid_fanout(struct hashfile *f,
 663                                    struct pack_midx_entry *objects,
 664                                    uint32_t nr_objects)
 665{
 666        struct pack_midx_entry *list = objects;
 667        struct pack_midx_entry *last = objects + nr_objects;
 668        uint32_t count = 0;
 669        uint32_t i;
 670
 671        /*
 672        * Write the first-level table (the list is sorted,
 673        * but we use a 256-entry lookup to be able to avoid
 674        * having to do eight extra binary search iterations).
 675        */
 676        for (i = 0; i < 256; i++) {
 677                struct pack_midx_entry *next = list;
 678
 679                while (next < last && next->oid.hash[0] == i) {
 680                        count++;
 681                        next++;
 682                }
 683
 684                hashwrite_be32(f, count);
 685                list = next;
 686        }
 687
 688        return MIDX_CHUNK_FANOUT_SIZE;
 689}
 690
 691static size_t write_midx_oid_lookup(struct hashfile *f, unsigned char hash_len,
 692                                    struct pack_midx_entry *objects,
 693                                    uint32_t nr_objects)
 694{
 695        struct pack_midx_entry *list = objects;
 696        uint32_t i;
 697        size_t written = 0;
 698
 699        for (i = 0; i < nr_objects; i++) {
 700                struct pack_midx_entry *obj = list++;
 701
 702                if (i < nr_objects - 1) {
 703                        struct pack_midx_entry *next = list;
 704                        if (oidcmp(&obj->oid, &next->oid) >= 0)
 705                                BUG("OIDs not in order: %s >= %s",
 706                                    oid_to_hex(&obj->oid),
 707                                    oid_to_hex(&next->oid));
 708                }
 709
 710                hashwrite(f, obj->oid.hash, (int)hash_len);
 711                written += hash_len;
 712        }
 713
 714        return written;
 715}
 716
 717static size_t write_midx_object_offsets(struct hashfile *f, int large_offset_needed,
 718                                        uint32_t *perm,
 719                                        struct pack_midx_entry *objects, uint32_t nr_objects)
 720{
 721        struct pack_midx_entry *list = objects;
 722        uint32_t i, nr_large_offset = 0;
 723        size_t written = 0;
 724
 725        for (i = 0; i < nr_objects; i++) {
 726                struct pack_midx_entry *obj = list++;
 727
 728                hashwrite_be32(f, perm[obj->pack_int_id]);
 729
 730                if (large_offset_needed && obj->offset >> 31)
 731                        hashwrite_be32(f, MIDX_LARGE_OFFSET_NEEDED | nr_large_offset++);
 732                else if (!large_offset_needed && obj->offset >> 32)
 733                        BUG("object %s requires a large offset (%"PRIx64") but the MIDX is not writing large offsets!",
 734                            oid_to_hex(&obj->oid),
 735                            obj->offset);
 736                else
 737                        hashwrite_be32(f, (uint32_t)obj->offset);
 738
 739                written += MIDX_CHUNK_OFFSET_WIDTH;
 740        }
 741
 742        return written;
 743}
 744
 745static size_t write_midx_large_offsets(struct hashfile *f, uint32_t nr_large_offset,
 746                                       struct pack_midx_entry *objects, uint32_t nr_objects)
 747{
 748        struct pack_midx_entry *list = objects, *end = objects + nr_objects;
 749        size_t written = 0;
 750
 751        while (nr_large_offset) {
 752                struct pack_midx_entry *obj;
 753                uint64_t offset;
 754
 755                if (list >= end)
 756                        BUG("too many large-offset objects");
 757
 758                obj = list++;
 759                offset = obj->offset;
 760
 761                if (!(offset >> 31))
 762                        continue;
 763
 764                hashwrite_be32(f, offset >> 32);
 765                hashwrite_be32(f, offset & 0xffffffffUL);
 766                written += 2 * sizeof(uint32_t);
 767
 768                nr_large_offset--;
 769        }
 770
 771        return written;
 772}
 773
 774int write_midx_file(const char *object_dir)
 775{
 776        unsigned char cur_chunk, num_chunks = 0;
 777        char *midx_name;
 778        uint32_t i;
 779        struct hashfile *f = NULL;
 780        struct lock_file lk;
 781        struct pack_list packs;
 782        uint32_t *pack_perm = NULL;
 783        uint64_t written = 0;
 784        uint32_t chunk_ids[MIDX_MAX_CHUNKS + 1];
 785        uint64_t chunk_offsets[MIDX_MAX_CHUNKS + 1];
 786        uint32_t nr_entries, num_large_offsets = 0;
 787        struct pack_midx_entry *entries = NULL;
 788        int large_offsets_needed = 0;
 789        int pack_name_concat_len = 0;
 790
 791        midx_name = get_midx_filename(object_dir);
 792        if (safe_create_leading_directories(midx_name)) {
 793                UNLEAK(midx_name);
 794                die_errno(_("unable to create leading directories of %s"),
 795                          midx_name);
 796        }
 797
 798        packs.m = load_multi_pack_index(object_dir, 1);
 799
 800        packs.nr = 0;
 801        packs.alloc = packs.m ? packs.m->num_packs : 16;
 802        packs.info = NULL;
 803        ALLOC_ARRAY(packs.info, packs.alloc);
 804
 805        if (packs.m) {
 806                for (i = 0; i < packs.m->num_packs; i++) {
 807                        ALLOC_GROW(packs.info, packs.nr + 1, packs.alloc);
 808
 809                        packs.info[packs.nr].orig_pack_int_id = i;
 810                        packs.info[packs.nr].pack_name = xstrdup(packs.m->pack_names[i]);
 811                        packs.info[packs.nr].p = NULL;
 812                        packs.nr++;
 813                }
 814        }
 815
 816        for_each_file_in_pack_dir(object_dir, add_pack_to_midx, &packs);
 817
 818        if (packs.m && packs.nr == packs.m->num_packs)
 819                goto cleanup;
 820
 821        entries = get_sorted_entries(packs.m, packs.info, packs.nr, &nr_entries);
 822
 823        for (i = 0; i < nr_entries; i++) {
 824                if (entries[i].offset > 0x7fffffff)
 825                        num_large_offsets++;
 826                if (entries[i].offset > 0xffffffff)
 827                        large_offsets_needed = 1;
 828        }
 829
 830        QSORT(packs.info, packs.nr, pack_info_compare);
 831
 832        /*
 833         * pack_perm stores a permutation between pack-int-ids from the
 834         * previous multi-pack-index to the new one we are writing:
 835         *
 836         * pack_perm[old_id] = new_id
 837         */
 838        ALLOC_ARRAY(pack_perm, packs.nr);
 839        for (i = 0; i < packs.nr; i++) {
 840                pack_perm[packs.info[i].orig_pack_int_id] = i;
 841        }
 842
 843        for (i = 0; i < packs.nr; i++)
 844                pack_name_concat_len += strlen(packs.info[i].pack_name) + 1;
 845
 846        if (pack_name_concat_len % MIDX_CHUNK_ALIGNMENT)
 847                pack_name_concat_len += MIDX_CHUNK_ALIGNMENT -
 848                                        (pack_name_concat_len % MIDX_CHUNK_ALIGNMENT);
 849
 850        hold_lock_file_for_update(&lk, midx_name, LOCK_DIE_ON_ERROR);
 851        f = hashfd(lk.tempfile->fd, lk.tempfile->filename.buf);
 852        FREE_AND_NULL(midx_name);
 853
 854        if (packs.m)
 855                close_midx(packs.m);
 856
 857        cur_chunk = 0;
 858        num_chunks = large_offsets_needed ? 5 : 4;
 859
 860        written = write_midx_header(f, num_chunks, packs.nr);
 861
 862        chunk_ids[cur_chunk] = MIDX_CHUNKID_PACKNAMES;
 863        chunk_offsets[cur_chunk] = written + (num_chunks + 1) * MIDX_CHUNKLOOKUP_WIDTH;
 864
 865        cur_chunk++;
 866        chunk_ids[cur_chunk] = MIDX_CHUNKID_OIDFANOUT;
 867        chunk_offsets[cur_chunk] = chunk_offsets[cur_chunk - 1] + pack_name_concat_len;
 868
 869        cur_chunk++;
 870        chunk_ids[cur_chunk] = MIDX_CHUNKID_OIDLOOKUP;
 871        chunk_offsets[cur_chunk] = chunk_offsets[cur_chunk - 1] + MIDX_CHUNK_FANOUT_SIZE;
 872
 873        cur_chunk++;
 874        chunk_ids[cur_chunk] = MIDX_CHUNKID_OBJECTOFFSETS;
 875        chunk_offsets[cur_chunk] = chunk_offsets[cur_chunk - 1] + nr_entries * MIDX_HASH_LEN;
 876
 877        cur_chunk++;
 878        chunk_offsets[cur_chunk] = chunk_offsets[cur_chunk - 1] + nr_entries * MIDX_CHUNK_OFFSET_WIDTH;
 879        if (large_offsets_needed) {
 880                chunk_ids[cur_chunk] = MIDX_CHUNKID_LARGEOFFSETS;
 881
 882                cur_chunk++;
 883                chunk_offsets[cur_chunk] = chunk_offsets[cur_chunk - 1] +
 884                                           num_large_offsets * MIDX_CHUNK_LARGE_OFFSET_WIDTH;
 885        }
 886
 887        chunk_ids[cur_chunk] = 0;
 888
 889        for (i = 0; i <= num_chunks; i++) {
 890                if (i && chunk_offsets[i] < chunk_offsets[i - 1])
 891                        BUG("incorrect chunk offsets: %"PRIu64" before %"PRIu64,
 892                            chunk_offsets[i - 1],
 893                            chunk_offsets[i]);
 894
 895                if (chunk_offsets[i] % MIDX_CHUNK_ALIGNMENT)
 896                        BUG("chunk offset %"PRIu64" is not properly aligned",
 897                            chunk_offsets[i]);
 898
 899                hashwrite_be32(f, chunk_ids[i]);
 900                hashwrite_be32(f, chunk_offsets[i] >> 32);
 901                hashwrite_be32(f, chunk_offsets[i]);
 902
 903                written += MIDX_CHUNKLOOKUP_WIDTH;
 904        }
 905
 906        for (i = 0; i < num_chunks; i++) {
 907                if (written != chunk_offsets[i])
 908                        BUG("incorrect chunk offset (%"PRIu64" != %"PRIu64") for chunk id %"PRIx32,
 909                            chunk_offsets[i],
 910                            written,
 911                            chunk_ids[i]);
 912
 913                switch (chunk_ids[i]) {
 914                        case MIDX_CHUNKID_PACKNAMES:
 915                                written += write_midx_pack_names(f, packs.info, packs.nr);
 916                                break;
 917
 918                        case MIDX_CHUNKID_OIDFANOUT:
 919                                written += write_midx_oid_fanout(f, entries, nr_entries);
 920                                break;
 921
 922                        case MIDX_CHUNKID_OIDLOOKUP:
 923                                written += write_midx_oid_lookup(f, MIDX_HASH_LEN, entries, nr_entries);
 924                                break;
 925
 926                        case MIDX_CHUNKID_OBJECTOFFSETS:
 927                                written += write_midx_object_offsets(f, large_offsets_needed, pack_perm, entries, nr_entries);
 928                                break;
 929
 930                        case MIDX_CHUNKID_LARGEOFFSETS:
 931                                written += write_midx_large_offsets(f, num_large_offsets, entries, nr_entries);
 932                                break;
 933
 934                        default:
 935                                BUG("trying to write unknown chunk id %"PRIx32,
 936                                    chunk_ids[i]);
 937                }
 938        }
 939
 940        if (written != chunk_offsets[num_chunks])
 941                BUG("incorrect final offset %"PRIu64" != %"PRIu64,
 942                    written,
 943                    chunk_offsets[num_chunks]);
 944
 945        finalize_hashfile(f, NULL, CSUM_FSYNC | CSUM_HASH_IN_STREAM);
 946        commit_lock_file(&lk);
 947
 948cleanup:
 949        for (i = 0; i < packs.nr; i++) {
 950                if (packs.info[i].p) {
 951                        close_pack(packs.info[i].p);
 952                        free(packs.info[i].p);
 953                }
 954                free(packs.info[i].pack_name);
 955        }
 956
 957        free(packs.info);
 958        free(entries);
 959        free(pack_perm);
 960        free(midx_name);
 961        return 0;
 962}
 963
 964void clear_midx_file(struct repository *r)
 965{
 966        char *midx = get_midx_filename(r->objects->odb->path);
 967
 968        if (r->objects && r->objects->multi_pack_index) {
 969                close_midx(r->objects->multi_pack_index);
 970                r->objects->multi_pack_index = NULL;
 971        }
 972
 973        if (remove_path(midx)) {
 974                UNLEAK(midx);
 975                die(_("failed to clear multi-pack-index at %s"), midx);
 976        }
 977
 978        free(midx);
 979}
 980
 981static int verify_midx_error;
 982
 983static void midx_report(const char *fmt, ...)
 984{
 985        va_list ap;
 986        verify_midx_error = 1;
 987        va_start(ap, fmt);
 988        vfprintf(stderr, fmt, ap);
 989        fprintf(stderr, "\n");
 990        va_end(ap);
 991}
 992
 993struct pair_pos_vs_id
 994{
 995        uint32_t pos;
 996        uint32_t pack_int_id;
 997};
 998
 999static int compare_pair_pos_vs_id(const void *_a, const void *_b)
1000{
1001        struct pair_pos_vs_id *a = (struct pair_pos_vs_id *)_a;
1002        struct pair_pos_vs_id *b = (struct pair_pos_vs_id *)_b;
1003
1004        return b->pack_int_id - a->pack_int_id;
1005}
1006
1007/*
1008 * Limit calls to display_progress() for performance reasons.
1009 * The interval here was arbitrarily chosen.
1010 */
1011#define SPARSE_PROGRESS_INTERVAL (1 << 12)
1012#define midx_display_sparse_progress(progress, n) \
1013        do { \
1014                uint64_t _n = (n); \
1015                if ((_n & (SPARSE_PROGRESS_INTERVAL - 1)) == 0) \
1016                        display_progress(progress, _n); \
1017        } while (0)
1018
1019int verify_midx_file(struct repository *r, const char *object_dir)
1020{
1021        struct pair_pos_vs_id *pairs = NULL;
1022        uint32_t i;
1023        struct progress *progress;
1024        struct multi_pack_index *m = load_multi_pack_index(object_dir, 1);
1025        verify_midx_error = 0;
1026
1027        if (!m)
1028                return 0;
1029
1030        progress = start_progress(_("Looking for referenced packfiles"),
1031                                  m->num_packs);
1032        for (i = 0; i < m->num_packs; i++) {
1033                if (prepare_midx_pack(r, m, i))
1034                        midx_report("failed to load pack in position %d", i);
1035
1036                display_progress(progress, i + 1);
1037        }
1038        stop_progress(&progress);
1039
1040        for (i = 0; i < 255; i++) {
1041                uint32_t oid_fanout1 = ntohl(m->chunk_oid_fanout[i]);
1042                uint32_t oid_fanout2 = ntohl(m->chunk_oid_fanout[i + 1]);
1043
1044                if (oid_fanout1 > oid_fanout2)
1045                        midx_report(_("oid fanout out of order: fanout[%d] = %"PRIx32" > %"PRIx32" = fanout[%d]"),
1046                                    i, oid_fanout1, oid_fanout2, i + 1);
1047        }
1048
1049        progress = start_sparse_progress(_("Verifying OID order in MIDX"),
1050                                         m->num_objects - 1);
1051        for (i = 0; i < m->num_objects - 1; i++) {
1052                struct object_id oid1, oid2;
1053
1054                nth_midxed_object_oid(&oid1, m, i);
1055                nth_midxed_object_oid(&oid2, m, i + 1);
1056
1057                if (oidcmp(&oid1, &oid2) >= 0)
1058                        midx_report(_("oid lookup out of order: oid[%d] = %s >= %s = oid[%d]"),
1059                                    i, oid_to_hex(&oid1), oid_to_hex(&oid2), i + 1);
1060
1061                midx_display_sparse_progress(progress, i + 1);
1062        }
1063        stop_progress(&progress);
1064
1065        /*
1066         * Create an array mapping each object to its packfile id.  Sort it
1067         * to group the objects by packfile.  Use this permutation to visit
1068         * each of the objects and only require 1 packfile to be open at a
1069         * time.
1070         */
1071        ALLOC_ARRAY(pairs, m->num_objects);
1072        for (i = 0; i < m->num_objects; i++) {
1073                pairs[i].pos = i;
1074                pairs[i].pack_int_id = nth_midxed_pack_int_id(m, i);
1075        }
1076
1077        progress = start_sparse_progress(_("Sorting objects by packfile"),
1078                                         m->num_objects);
1079        display_progress(progress, 0); /* TODO: Measure QSORT() progress */
1080        QSORT(pairs, m->num_objects, compare_pair_pos_vs_id);
1081        stop_progress(&progress);
1082
1083        progress = start_sparse_progress(_("Verifying object offsets"), m->num_objects);
1084        for (i = 0; i < m->num_objects; i++) {
1085                struct object_id oid;
1086                struct pack_entry e;
1087                off_t m_offset, p_offset;
1088
1089                if (i > 0 && pairs[i-1].pack_int_id != pairs[i].pack_int_id &&
1090                    m->packs[pairs[i-1].pack_int_id])
1091                {
1092                        close_pack_fd(m->packs[pairs[i-1].pack_int_id]);
1093                        close_pack_index(m->packs[pairs[i-1].pack_int_id]);
1094                }
1095
1096                nth_midxed_object_oid(&oid, m, pairs[i].pos);
1097
1098                if (!fill_midx_entry(r, &oid, &e, m)) {
1099                        midx_report(_("failed to load pack entry for oid[%d] = %s"),
1100                                    pairs[i].pos, oid_to_hex(&oid));
1101                        continue;
1102                }
1103
1104                if (open_pack_index(e.p)) {
1105                        midx_report(_("failed to load pack-index for packfile %s"),
1106                                    e.p->pack_name);
1107                        break;
1108                }
1109
1110                m_offset = e.offset;
1111                p_offset = find_pack_entry_one(oid.hash, e.p);
1112
1113                if (m_offset != p_offset)
1114                        midx_report(_("incorrect object offset for oid[%d] = %s: %"PRIx64" != %"PRIx64),
1115                                    pairs[i].pos, oid_to_hex(&oid), m_offset, p_offset);
1116
1117                midx_display_sparse_progress(progress, i + 1);
1118        }
1119        stop_progress(&progress);
1120
1121        free(pairs);
1122
1123        return verify_midx_error;
1124}
1125
1126int expire_midx_packs(struct repository *r, const char *object_dir)
1127{
1128        return 0;
1129}