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