4e014ff6e3b189ebb7c92634703df7233920dbf4
   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)
  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
  77        m->signature = get_be32(m->data);
  78        if (m->signature != MIDX_SIGNATURE) {
  79                error(_("multi-pack-index signature 0x%08x does not match signature 0x%08x"),
  80                      m->signature, MIDX_SIGNATURE);
  81                goto cleanup_fail;
  82        }
  83
  84        m->version = m->data[MIDX_BYTE_FILE_VERSION];
  85        if (m->version != MIDX_VERSION) {
  86                error(_("multi-pack-index version %d not recognized"),
  87                      m->version);
  88                goto cleanup_fail;
  89        }
  90
  91        hash_version = m->data[MIDX_BYTE_HASH_VERSION];
  92        if (hash_version != MIDX_HASH_VERSION) {
  93                error(_("hash version %u does not match"), hash_version);
  94                goto cleanup_fail;
  95        }
  96        m->hash_len = MIDX_HASH_LEN;
  97
  98        m->num_chunks = m->data[MIDX_BYTE_NUM_CHUNKS];
  99
 100        m->num_packs = get_be32(m->data + MIDX_BYTE_NUM_PACKS);
 101
 102        for (i = 0; i < m->num_chunks; i++) {
 103                uint32_t chunk_id = get_be32(m->data + MIDX_HEADER_SIZE +
 104                                             MIDX_CHUNKLOOKUP_WIDTH * i);
 105                uint64_t chunk_offset = get_be64(m->data + MIDX_HEADER_SIZE + 4 +
 106                                                 MIDX_CHUNKLOOKUP_WIDTH * i);
 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                        error(_("multi-pack-index pack names out of order: '%s' before '%s'"),
 164                              m->pack_names[i - 1],
 165                              m->pack_names[i]);
 166                        goto cleanup_fail;
 167                }
 168        }
 169
 170        return m;
 171
 172cleanup_fail:
 173        free(m);
 174        free(midx_name);
 175        if (midx_map)
 176                munmap(midx_map, midx_size);
 177        if (0 <= fd)
 178                close(fd);
 179        return NULL;
 180}
 181
 182static int prepare_midx_pack(struct multi_pack_index *m, uint32_t pack_int_id)
 183{
 184        struct strbuf pack_name = STRBUF_INIT;
 185
 186        if (pack_int_id >= m->num_packs)
 187                BUG("bad pack-int-id");
 188
 189        if (m->packs[pack_int_id])
 190                return 0;
 191
 192        strbuf_addf(&pack_name, "%s/pack/%s", m->object_dir,
 193                    m->pack_names[pack_int_id]);
 194
 195        m->packs[pack_int_id] = add_packed_git(pack_name.buf, pack_name.len, 1);
 196        strbuf_release(&pack_name);
 197        return !m->packs[pack_int_id];
 198}
 199
 200int bsearch_midx(const struct object_id *oid, struct multi_pack_index *m, uint32_t *result)
 201{
 202        return bsearch_hash(oid->hash, m->chunk_oid_fanout, m->chunk_oid_lookup,
 203                            MIDX_HASH_LEN, result);
 204}
 205
 206struct object_id *nth_midxed_object_oid(struct object_id *oid,
 207                                        struct multi_pack_index *m,
 208                                        uint32_t n)
 209{
 210        if (n >= m->num_objects)
 211                return NULL;
 212
 213        hashcpy(oid->hash, m->chunk_oid_lookup + m->hash_len * n);
 214        return oid;
 215}
 216
 217static off_t nth_midxed_offset(struct multi_pack_index *m, uint32_t pos)
 218{
 219        const unsigned char *offset_data;
 220        uint32_t offset32;
 221
 222        offset_data = m->chunk_object_offsets + pos * MIDX_CHUNK_OFFSET_WIDTH;
 223        offset32 = get_be32(offset_data + sizeof(uint32_t));
 224
 225        if (m->chunk_large_offsets && offset32 & MIDX_LARGE_OFFSET_NEEDED) {
 226                if (sizeof(offset32) < sizeof(uint64_t))
 227                        die(_("multi-pack-index stores a 64-bit offset, but off_t is too small"));
 228
 229                offset32 ^= MIDX_LARGE_OFFSET_NEEDED;
 230                return get_be64(m->chunk_large_offsets + sizeof(uint64_t) * offset32);
 231        }
 232
 233        return offset32;
 234}
 235
 236static uint32_t nth_midxed_pack_int_id(struct multi_pack_index *m, uint32_t pos)
 237{
 238        return get_be32(m->chunk_object_offsets + pos * MIDX_CHUNK_OFFSET_WIDTH);
 239}
 240
 241static int nth_midxed_pack_entry(struct multi_pack_index *m, struct pack_entry *e, uint32_t pos)
 242{
 243        uint32_t pack_int_id;
 244        struct packed_git *p;
 245
 246        if (pos >= m->num_objects)
 247                return 0;
 248
 249        pack_int_id = nth_midxed_pack_int_id(m, pos);
 250
 251        if (prepare_midx_pack(m, pack_int_id))
 252                die(_("error preparing packfile from multi-pack-index"));
 253        p = m->packs[pack_int_id];
 254
 255        /*
 256        * We are about to tell the caller where they can locate the
 257        * requested object.  We better make sure the packfile is
 258        * still here and can be accessed before supplying that
 259        * answer, as it may have been deleted since the MIDX was
 260        * loaded!
 261        */
 262        if (!is_pack_valid(p))
 263                return 0;
 264
 265        e->offset = nth_midxed_offset(m, pos);
 266        e->p = p;
 267
 268        return 1;
 269}
 270
 271int fill_midx_entry(const struct object_id *oid, struct pack_entry *e, struct multi_pack_index *m)
 272{
 273        uint32_t pos;
 274
 275        if (!bsearch_midx(oid, m, &pos))
 276                return 0;
 277
 278        return nth_midxed_pack_entry(m, e, pos);
 279}
 280
 281int prepare_multi_pack_index_one(struct repository *r, const char *object_dir)
 282{
 283        struct multi_pack_index *m = r->objects->multi_pack_index;
 284        struct multi_pack_index *m_search;
 285        int config_value;
 286
 287        if (repo_config_get_bool(r, "core.multipackindex", &config_value) ||
 288            !config_value)
 289                return 0;
 290
 291        for (m_search = m; m_search; m_search = m_search->next)
 292                if (!strcmp(object_dir, m_search->object_dir))
 293                        return 1;
 294
 295        r->objects->multi_pack_index = load_multi_pack_index(object_dir);
 296
 297        if (r->objects->multi_pack_index) {
 298                r->objects->multi_pack_index->next = m;
 299                return 1;
 300        }
 301
 302        return 0;
 303}
 304
 305static size_t write_midx_header(struct hashfile *f,
 306                                unsigned char num_chunks,
 307                                uint32_t num_packs)
 308{
 309        unsigned char byte_values[4];
 310
 311        hashwrite_be32(f, MIDX_SIGNATURE);
 312        byte_values[0] = MIDX_VERSION;
 313        byte_values[1] = MIDX_HASH_VERSION;
 314        byte_values[2] = num_chunks;
 315        byte_values[3] = 0; /* unused */
 316        hashwrite(f, byte_values, sizeof(byte_values));
 317        hashwrite_be32(f, num_packs);
 318
 319        return MIDX_HEADER_SIZE;
 320}
 321
 322struct pack_list {
 323        struct packed_git **list;
 324        char **names;
 325        uint32_t nr;
 326        uint32_t alloc_list;
 327        uint32_t alloc_names;
 328        size_t pack_name_concat_len;
 329};
 330
 331static void add_pack_to_midx(const char *full_path, size_t full_path_len,
 332                             const char *file_name, void *data)
 333{
 334        struct pack_list *packs = (struct pack_list *)data;
 335
 336        if (ends_with(file_name, ".idx")) {
 337                ALLOC_GROW(packs->list, packs->nr + 1, packs->alloc_list);
 338                ALLOC_GROW(packs->names, packs->nr + 1, packs->alloc_names);
 339
 340                packs->list[packs->nr] = add_packed_git(full_path,
 341                                                        full_path_len,
 342                                                        0);
 343
 344                if (!packs->list[packs->nr]) {
 345                        warning(_("failed to add packfile '%s'"),
 346                                full_path);
 347                        return;
 348                }
 349
 350                if (open_pack_index(packs->list[packs->nr])) {
 351                        warning(_("failed to open pack-index '%s'"),
 352                                full_path);
 353                        close_pack(packs->list[packs->nr]);
 354                        FREE_AND_NULL(packs->list[packs->nr]);
 355                        return;
 356                }
 357
 358                packs->names[packs->nr] = xstrdup(file_name);
 359                packs->pack_name_concat_len += strlen(file_name) + 1;
 360                packs->nr++;
 361        }
 362}
 363
 364struct pack_pair {
 365        uint32_t pack_int_id;
 366        char *pack_name;
 367};
 368
 369static int pack_pair_compare(const void *_a, const void *_b)
 370{
 371        struct pack_pair *a = (struct pack_pair *)_a;
 372        struct pack_pair *b = (struct pack_pair *)_b;
 373        return strcmp(a->pack_name, b->pack_name);
 374}
 375
 376static void sort_packs_by_name(char **pack_names, uint32_t nr_packs, uint32_t *perm)
 377{
 378        uint32_t i;
 379        struct pack_pair *pairs;
 380
 381        ALLOC_ARRAY(pairs, nr_packs);
 382
 383        for (i = 0; i < nr_packs; i++) {
 384                pairs[i].pack_int_id = i;
 385                pairs[i].pack_name = pack_names[i];
 386        }
 387
 388        QSORT(pairs, nr_packs, pack_pair_compare);
 389
 390        for (i = 0; i < nr_packs; i++) {
 391                pack_names[i] = pairs[i].pack_name;
 392                perm[pairs[i].pack_int_id] = i;
 393        }
 394
 395        free(pairs);
 396}
 397
 398struct pack_midx_entry {
 399        struct object_id oid;
 400        uint32_t pack_int_id;
 401        time_t pack_mtime;
 402        uint64_t offset;
 403};
 404
 405static int midx_oid_compare(const void *_a, const void *_b)
 406{
 407        const struct pack_midx_entry *a = (const struct pack_midx_entry *)_a;
 408        const struct pack_midx_entry *b = (const struct pack_midx_entry *)_b;
 409        int cmp = oidcmp(&a->oid, &b->oid);
 410
 411        if (cmp)
 412                return cmp;
 413
 414        if (a->pack_mtime > b->pack_mtime)
 415                return -1;
 416        else if (a->pack_mtime < b->pack_mtime)
 417                return 1;
 418
 419        return a->pack_int_id - b->pack_int_id;
 420}
 421
 422static void fill_pack_entry(uint32_t pack_int_id,
 423                            struct packed_git *p,
 424                            uint32_t cur_object,
 425                            struct pack_midx_entry *entry)
 426{
 427        if (!nth_packed_object_oid(&entry->oid, p, cur_object))
 428                die(_("failed to locate object %d in packfile"), cur_object);
 429
 430        entry->pack_int_id = pack_int_id;
 431        entry->pack_mtime = p->mtime;
 432
 433        entry->offset = nth_packed_object_offset(p, cur_object);
 434}
 435
 436/*
 437 * It is possible to artificially get into a state where there are many
 438 * duplicate copies of objects. That can create high memory pressure if
 439 * we are to create a list of all objects before de-duplication. To reduce
 440 * this memory pressure without a significant performance drop, automatically
 441 * group objects by the first byte of their object id. Use the IDX fanout
 442 * tables to group the data, copy to a local array, then sort.
 443 *
 444 * Copy only the de-duplicated entries (selected by most-recent modified time
 445 * of a packfile containing the object).
 446 */
 447static struct pack_midx_entry *get_sorted_entries(struct packed_git **p,
 448                                                  uint32_t *perm,
 449                                                  uint32_t nr_packs,
 450                                                  uint32_t *nr_objects)
 451{
 452        uint32_t cur_fanout, cur_pack, cur_object;
 453        uint32_t alloc_fanout, alloc_objects, total_objects = 0;
 454        struct pack_midx_entry *entries_by_fanout = NULL;
 455        struct pack_midx_entry *deduplicated_entries = NULL;
 456
 457        for (cur_pack = 0; cur_pack < nr_packs; cur_pack++)
 458                total_objects += p[cur_pack]->num_objects;
 459
 460        /*
 461         * As we de-duplicate by fanout value, we expect the fanout
 462         * slices to be evenly distributed, with some noise. Hence,
 463         * allocate slightly more than one 256th.
 464         */
 465        alloc_objects = alloc_fanout = total_objects > 3200 ? total_objects / 200 : 16;
 466
 467        ALLOC_ARRAY(entries_by_fanout, alloc_fanout);
 468        ALLOC_ARRAY(deduplicated_entries, alloc_objects);
 469        *nr_objects = 0;
 470
 471        for (cur_fanout = 0; cur_fanout < 256; cur_fanout++) {
 472                uint32_t nr_fanout = 0;
 473
 474                for (cur_pack = 0; cur_pack < nr_packs; cur_pack++) {
 475                        uint32_t start = 0, end;
 476
 477                        if (cur_fanout)
 478                                start = get_pack_fanout(p[cur_pack], cur_fanout - 1);
 479                        end = get_pack_fanout(p[cur_pack], cur_fanout);
 480
 481                        for (cur_object = start; cur_object < end; cur_object++) {
 482                                ALLOC_GROW(entries_by_fanout, nr_fanout + 1, alloc_fanout);
 483                                fill_pack_entry(perm[cur_pack], p[cur_pack], cur_object, &entries_by_fanout[nr_fanout]);
 484                                nr_fanout++;
 485                        }
 486                }
 487
 488                QSORT(entries_by_fanout, nr_fanout, midx_oid_compare);
 489
 490                /*
 491                 * The batch is now sorted by OID and then mtime (descending).
 492                 * Take only the first duplicate.
 493                 */
 494                for (cur_object = 0; cur_object < nr_fanout; cur_object++) {
 495                        if (cur_object && !oidcmp(&entries_by_fanout[cur_object - 1].oid,
 496                                                  &entries_by_fanout[cur_object].oid))
 497                                continue;
 498
 499                        ALLOC_GROW(deduplicated_entries, *nr_objects + 1, alloc_objects);
 500                        memcpy(&deduplicated_entries[*nr_objects],
 501                               &entries_by_fanout[cur_object],
 502                               sizeof(struct pack_midx_entry));
 503                        (*nr_objects)++;
 504                }
 505        }
 506
 507        free(entries_by_fanout);
 508        return deduplicated_entries;
 509}
 510
 511static size_t write_midx_pack_names(struct hashfile *f,
 512                                    char **pack_names,
 513                                    uint32_t num_packs)
 514{
 515        uint32_t i;
 516        unsigned char padding[MIDX_CHUNK_ALIGNMENT];
 517        size_t written = 0;
 518
 519        for (i = 0; i < num_packs; i++) {
 520                size_t writelen = strlen(pack_names[i]) + 1;
 521
 522                if (i && strcmp(pack_names[i], pack_names[i - 1]) <= 0)
 523                        BUG("incorrect pack-file order: %s before %s",
 524                            pack_names[i - 1],
 525                            pack_names[i]);
 526
 527                hashwrite(f, pack_names[i], writelen);
 528                written += writelen;
 529        }
 530
 531        /* add padding to be aligned */
 532        i = MIDX_CHUNK_ALIGNMENT - (written % MIDX_CHUNK_ALIGNMENT);
 533        if (i < MIDX_CHUNK_ALIGNMENT) {
 534                memset(padding, 0, sizeof(padding));
 535                hashwrite(f, padding, i);
 536                written += i;
 537        }
 538
 539        return written;
 540}
 541
 542static size_t write_midx_oid_fanout(struct hashfile *f,
 543                                    struct pack_midx_entry *objects,
 544                                    uint32_t nr_objects)
 545{
 546        struct pack_midx_entry *list = objects;
 547        struct pack_midx_entry *last = objects + nr_objects;
 548        uint32_t count = 0;
 549        uint32_t i;
 550
 551        /*
 552        * Write the first-level table (the list is sorted,
 553        * but we use a 256-entry lookup to be able to avoid
 554        * having to do eight extra binary search iterations).
 555        */
 556        for (i = 0; i < 256; i++) {
 557                struct pack_midx_entry *next = list;
 558
 559                while (next < last && next->oid.hash[0] == i) {
 560                        count++;
 561                        next++;
 562                }
 563
 564                hashwrite_be32(f, count);
 565                list = next;
 566        }
 567
 568        return MIDX_CHUNK_FANOUT_SIZE;
 569}
 570
 571static size_t write_midx_oid_lookup(struct hashfile *f, unsigned char hash_len,
 572                                    struct pack_midx_entry *objects,
 573                                    uint32_t nr_objects)
 574{
 575        struct pack_midx_entry *list = objects;
 576        uint32_t i;
 577        size_t written = 0;
 578
 579        for (i = 0; i < nr_objects; i++) {
 580                struct pack_midx_entry *obj = list++;
 581
 582                if (i < nr_objects - 1) {
 583                        struct pack_midx_entry *next = list;
 584                        if (oidcmp(&obj->oid, &next->oid) >= 0)
 585                                BUG("OIDs not in order: %s >= %s",
 586                                    oid_to_hex(&obj->oid),
 587                                    oid_to_hex(&next->oid));
 588                }
 589
 590                hashwrite(f, obj->oid.hash, (int)hash_len);
 591                written += hash_len;
 592        }
 593
 594        return written;
 595}
 596
 597static size_t write_midx_object_offsets(struct hashfile *f, int large_offset_needed,
 598                                        struct pack_midx_entry *objects, uint32_t nr_objects)
 599{
 600        struct pack_midx_entry *list = objects;
 601        uint32_t i, nr_large_offset = 0;
 602        size_t written = 0;
 603
 604        for (i = 0; i < nr_objects; i++) {
 605                struct pack_midx_entry *obj = list++;
 606
 607                hashwrite_be32(f, obj->pack_int_id);
 608
 609                if (large_offset_needed && obj->offset >> 31)
 610                        hashwrite_be32(f, MIDX_LARGE_OFFSET_NEEDED | nr_large_offset++);
 611                else if (!large_offset_needed && obj->offset >> 32)
 612                        BUG("object %s requires a large offset (%"PRIx64") but the MIDX is not writing large offsets!",
 613                            oid_to_hex(&obj->oid),
 614                            obj->offset);
 615                else
 616                        hashwrite_be32(f, (uint32_t)obj->offset);
 617
 618                written += MIDX_CHUNK_OFFSET_WIDTH;
 619        }
 620
 621        return written;
 622}
 623
 624static size_t write_midx_large_offsets(struct hashfile *f, uint32_t nr_large_offset,
 625                                       struct pack_midx_entry *objects, uint32_t nr_objects)
 626{
 627        struct pack_midx_entry *list = objects;
 628        size_t written = 0;
 629
 630        while (nr_large_offset) {
 631                struct pack_midx_entry *obj = list++;
 632                uint64_t offset = obj->offset;
 633
 634                if (!(offset >> 31))
 635                        continue;
 636
 637                hashwrite_be32(f, offset >> 32);
 638                hashwrite_be32(f, offset & 0xffffffffUL);
 639                written += 2 * sizeof(uint32_t);
 640
 641                nr_large_offset--;
 642        }
 643
 644        return written;
 645}
 646
 647int write_midx_file(const char *object_dir)
 648{
 649        unsigned char cur_chunk, num_chunks = 0;
 650        char *midx_name;
 651        uint32_t i;
 652        struct hashfile *f = NULL;
 653        struct lock_file lk;
 654        struct pack_list packs;
 655        uint32_t *pack_perm = NULL;
 656        uint64_t written = 0;
 657        uint32_t chunk_ids[MIDX_MAX_CHUNKS + 1];
 658        uint64_t chunk_offsets[MIDX_MAX_CHUNKS + 1];
 659        uint32_t nr_entries, num_large_offsets = 0;
 660        struct pack_midx_entry *entries = NULL;
 661        int large_offsets_needed = 0;
 662
 663        midx_name = get_midx_filename(object_dir);
 664        if (safe_create_leading_directories(midx_name)) {
 665                UNLEAK(midx_name);
 666                die_errno(_("unable to create leading directories of %s"),
 667                          midx_name);
 668        }
 669
 670        packs.nr = 0;
 671        packs.alloc_list = 16;
 672        packs.alloc_names = 16;
 673        packs.list = NULL;
 674        packs.pack_name_concat_len = 0;
 675        ALLOC_ARRAY(packs.list, packs.alloc_list);
 676        ALLOC_ARRAY(packs.names, packs.alloc_names);
 677
 678        for_each_file_in_pack_dir(object_dir, add_pack_to_midx, &packs);
 679
 680        if (packs.pack_name_concat_len % MIDX_CHUNK_ALIGNMENT)
 681                packs.pack_name_concat_len += MIDX_CHUNK_ALIGNMENT -
 682                                              (packs.pack_name_concat_len % MIDX_CHUNK_ALIGNMENT);
 683
 684        ALLOC_ARRAY(pack_perm, packs.nr);
 685        sort_packs_by_name(packs.names, packs.nr, pack_perm);
 686
 687        entries = get_sorted_entries(packs.list, pack_perm, packs.nr, &nr_entries);
 688        for (i = 0; i < nr_entries; i++) {
 689                if (entries[i].offset > 0x7fffffff)
 690                        num_large_offsets++;
 691                if (entries[i].offset > 0xffffffff)
 692                        large_offsets_needed = 1;
 693        }
 694
 695        hold_lock_file_for_update(&lk, midx_name, LOCK_DIE_ON_ERROR);
 696        f = hashfd(lk.tempfile->fd, lk.tempfile->filename.buf);
 697        FREE_AND_NULL(midx_name);
 698
 699        cur_chunk = 0;
 700        num_chunks = large_offsets_needed ? 5 : 4;
 701
 702        written = write_midx_header(f, num_chunks, packs.nr);
 703
 704        chunk_ids[cur_chunk] = MIDX_CHUNKID_PACKNAMES;
 705        chunk_offsets[cur_chunk] = written + (num_chunks + 1) * MIDX_CHUNKLOOKUP_WIDTH;
 706
 707        cur_chunk++;
 708        chunk_ids[cur_chunk] = MIDX_CHUNKID_OIDFANOUT;
 709        chunk_offsets[cur_chunk] = chunk_offsets[cur_chunk - 1] + packs.pack_name_concat_len;
 710
 711        cur_chunk++;
 712        chunk_ids[cur_chunk] = MIDX_CHUNKID_OIDLOOKUP;
 713        chunk_offsets[cur_chunk] = chunk_offsets[cur_chunk - 1] + MIDX_CHUNK_FANOUT_SIZE;
 714
 715        cur_chunk++;
 716        chunk_ids[cur_chunk] = MIDX_CHUNKID_OBJECTOFFSETS;
 717        chunk_offsets[cur_chunk] = chunk_offsets[cur_chunk - 1] + nr_entries * MIDX_HASH_LEN;
 718
 719        cur_chunk++;
 720        chunk_offsets[cur_chunk] = chunk_offsets[cur_chunk - 1] + nr_entries * MIDX_CHUNK_OFFSET_WIDTH;
 721        if (large_offsets_needed) {
 722                chunk_ids[cur_chunk] = MIDX_CHUNKID_LARGEOFFSETS;
 723
 724                cur_chunk++;
 725                chunk_offsets[cur_chunk] = chunk_offsets[cur_chunk - 1] +
 726                                           num_large_offsets * MIDX_CHUNK_LARGE_OFFSET_WIDTH;
 727        }
 728
 729        chunk_ids[cur_chunk] = 0;
 730
 731        for (i = 0; i <= num_chunks; i++) {
 732                if (i && chunk_offsets[i] < chunk_offsets[i - 1])
 733                        BUG("incorrect chunk offsets: %"PRIu64" before %"PRIu64,
 734                            chunk_offsets[i - 1],
 735                            chunk_offsets[i]);
 736
 737                if (chunk_offsets[i] % MIDX_CHUNK_ALIGNMENT)
 738                        BUG("chunk offset %"PRIu64" is not properly aligned",
 739                            chunk_offsets[i]);
 740
 741                hashwrite_be32(f, chunk_ids[i]);
 742                hashwrite_be32(f, chunk_offsets[i] >> 32);
 743                hashwrite_be32(f, chunk_offsets[i]);
 744
 745                written += MIDX_CHUNKLOOKUP_WIDTH;
 746        }
 747
 748        for (i = 0; i < num_chunks; i++) {
 749                if (written != chunk_offsets[i])
 750                        BUG("incorrect chunk offset (%"PRIu64" != %"PRIu64") for chunk id %"PRIx32,
 751                            chunk_offsets[i],
 752                            written,
 753                            chunk_ids[i]);
 754
 755                switch (chunk_ids[i]) {
 756                        case MIDX_CHUNKID_PACKNAMES:
 757                                written += write_midx_pack_names(f, packs.names, packs.nr);
 758                                break;
 759
 760                        case MIDX_CHUNKID_OIDFANOUT:
 761                                written += write_midx_oid_fanout(f, entries, nr_entries);
 762                                break;
 763
 764                        case MIDX_CHUNKID_OIDLOOKUP:
 765                                written += write_midx_oid_lookup(f, MIDX_HASH_LEN, entries, nr_entries);
 766                                break;
 767
 768                        case MIDX_CHUNKID_OBJECTOFFSETS:
 769                                written += write_midx_object_offsets(f, large_offsets_needed, entries, nr_entries);
 770                                break;
 771
 772                        case MIDX_CHUNKID_LARGEOFFSETS:
 773                                written += write_midx_large_offsets(f, num_large_offsets, entries, nr_entries);
 774                                break;
 775
 776                        default:
 777                                BUG("trying to write unknown chunk id %"PRIx32,
 778                                    chunk_ids[i]);
 779                }
 780        }
 781
 782        if (written != chunk_offsets[num_chunks])
 783                BUG("incorrect final offset %"PRIu64" != %"PRIu64,
 784                    written,
 785                    chunk_offsets[num_chunks]);
 786
 787        finalize_hashfile(f, NULL, CSUM_FSYNC | CSUM_HASH_IN_STREAM);
 788        commit_lock_file(&lk);
 789
 790        for (i = 0; i < packs.nr; i++) {
 791                if (packs.list[i]) {
 792                        close_pack(packs.list[i]);
 793                        free(packs.list[i]);
 794                }
 795                free(packs.names[i]);
 796        }
 797
 798        free(packs.list);
 799        free(packs.names);
 800        free(entries);
 801        return 0;
 802}