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