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