3acc032c1b59d0b35a9422319458613320ca60a5
   1#include "cache.h"
   2#include "config.h"
   3#include "dir.h"
   4#include "git-compat-util.h"
   5#include "lockfile.h"
   6#include "pack.h"
   7#include "packfile.h"
   8#include "commit.h"
   9#include "object.h"
  10#include "refs.h"
  11#include "revision.h"
  12#include "sha1-lookup.h"
  13#include "commit-graph.h"
  14#include "object-store.h"
  15#include "alloc.h"
  16#include "hashmap.h"
  17#include "replace-object.h"
  18#include "progress.h"
  19
  20#define GRAPH_SIGNATURE 0x43475048 /* "CGPH" */
  21#define GRAPH_CHUNKID_OIDFANOUT 0x4f494446 /* "OIDF" */
  22#define GRAPH_CHUNKID_OIDLOOKUP 0x4f49444c /* "OIDL" */
  23#define GRAPH_CHUNKID_DATA 0x43444154 /* "CDAT" */
  24#define GRAPH_CHUNKID_EXTRAEDGES 0x45444745 /* "EDGE" */
  25
  26#define GRAPH_DATA_WIDTH (the_hash_algo->rawsz + 16)
  27
  28#define GRAPH_VERSION_1 0x1
  29#define GRAPH_VERSION GRAPH_VERSION_1
  30
  31#define GRAPH_EXTRA_EDGES_NEEDED 0x80000000
  32#define GRAPH_EDGE_LAST_MASK 0x7fffffff
  33#define GRAPH_PARENT_NONE 0x70000000
  34
  35#define GRAPH_LAST_EDGE 0x80000000
  36
  37#define GRAPH_HEADER_SIZE 8
  38#define GRAPH_FANOUT_SIZE (4 * 256)
  39#define GRAPH_CHUNKLOOKUP_WIDTH 12
  40#define GRAPH_MIN_SIZE (GRAPH_HEADER_SIZE + 4 * GRAPH_CHUNKLOOKUP_WIDTH \
  41                        + GRAPH_FANOUT_SIZE + the_hash_algo->rawsz)
  42
  43char *get_commit_graph_filename(const char *obj_dir)
  44{
  45        return xstrfmt("%s/info/commit-graph", obj_dir);
  46}
  47
  48static uint8_t oid_version(void)
  49{
  50        return 1;
  51}
  52
  53static struct commit_graph *alloc_commit_graph(void)
  54{
  55        struct commit_graph *g = xcalloc(1, sizeof(*g));
  56        g->graph_fd = -1;
  57
  58        return g;
  59}
  60
  61extern int read_replace_refs;
  62
  63static int commit_graph_compatible(struct repository *r)
  64{
  65        if (!r->gitdir)
  66                return 0;
  67
  68        if (read_replace_refs) {
  69                prepare_replace_object(r);
  70                if (hashmap_get_size(&r->objects->replace_map->map))
  71                        return 0;
  72        }
  73
  74        prepare_commit_graft(r);
  75        if (r->parsed_objects && r->parsed_objects->grafts_nr)
  76                return 0;
  77        if (is_repository_shallow(r))
  78                return 0;
  79
  80        return 1;
  81}
  82
  83int open_commit_graph(const char *graph_file, int *fd, struct stat *st)
  84{
  85        *fd = git_open(graph_file);
  86        if (*fd < 0)
  87                return 0;
  88        if (fstat(*fd, st)) {
  89                close(*fd);
  90                return 0;
  91        }
  92        return 1;
  93}
  94
  95struct commit_graph *load_commit_graph_one_fd_st(const char *graph_file,
  96                                                 int fd, struct stat *st)
  97{
  98        void *graph_map;
  99        size_t graph_size;
 100        struct commit_graph *ret;
 101
 102        graph_size = xsize_t(st->st_size);
 103
 104        if (graph_size < GRAPH_MIN_SIZE) {
 105                close(fd);
 106                error(_("graph file %s is too small"), graph_file);
 107                return NULL;
 108        }
 109        graph_map = xmmap(NULL, graph_size, PROT_READ, MAP_PRIVATE, fd, 0);
 110        ret = parse_commit_graph(graph_map, fd, graph_size);
 111
 112        if (!ret) {
 113                munmap(graph_map, graph_size);
 114                close(fd);
 115        }
 116
 117        return ret;
 118}
 119
 120static int verify_commit_graph_lite(struct commit_graph *g)
 121{
 122        /*
 123         * Basic validation shared between parse_commit_graph()
 124         * which'll be called every time the graph is used, and the
 125         * much more expensive verify_commit_graph() used by
 126         * "commit-graph verify".
 127         *
 128         * There should only be very basic checks here to ensure that
 129         * we don't e.g. segfault in fill_commit_in_graph(), but
 130         * because this is a very hot codepath nothing that e.g. loops
 131         * over g->num_commits, or runs a checksum on the commit-graph
 132         * itself.
 133         */
 134        if (!g->chunk_oid_fanout) {
 135                error("commit-graph is missing the OID Fanout chunk");
 136                return 1;
 137        }
 138        if (!g->chunk_oid_lookup) {
 139                error("commit-graph is missing the OID Lookup chunk");
 140                return 1;
 141        }
 142        if (!g->chunk_commit_data) {
 143                error("commit-graph is missing the Commit Data chunk");
 144                return 1;
 145        }
 146
 147        return 0;
 148}
 149
 150struct commit_graph *parse_commit_graph(void *graph_map, int fd,
 151                                        size_t graph_size)
 152{
 153        const unsigned char *data, *chunk_lookup;
 154        uint32_t i;
 155        struct commit_graph *graph;
 156        uint64_t last_chunk_offset;
 157        uint32_t last_chunk_id;
 158        uint32_t graph_signature;
 159        unsigned char graph_version, hash_version;
 160
 161        if (!graph_map)
 162                return NULL;
 163
 164        if (graph_size < GRAPH_MIN_SIZE)
 165                return NULL;
 166
 167        data = (const unsigned char *)graph_map;
 168
 169        graph_signature = get_be32(data);
 170        if (graph_signature != GRAPH_SIGNATURE) {
 171                error(_("graph signature %X does not match signature %X"),
 172                      graph_signature, GRAPH_SIGNATURE);
 173                return NULL;
 174        }
 175
 176        graph_version = *(unsigned char*)(data + 4);
 177        if (graph_version != GRAPH_VERSION) {
 178                error(_("graph version %X does not match version %X"),
 179                      graph_version, GRAPH_VERSION);
 180                return NULL;
 181        }
 182
 183        hash_version = *(unsigned char*)(data + 5);
 184        if (hash_version != oid_version()) {
 185                error(_("hash version %X does not match version %X"),
 186                      hash_version, oid_version());
 187                return NULL;
 188        }
 189
 190        graph = alloc_commit_graph();
 191
 192        graph->hash_len = the_hash_algo->rawsz;
 193        graph->num_chunks = *(unsigned char*)(data + 6);
 194        graph->graph_fd = fd;
 195        graph->data = graph_map;
 196        graph->data_len = graph_size;
 197
 198        last_chunk_id = 0;
 199        last_chunk_offset = 8;
 200        chunk_lookup = data + 8;
 201        for (i = 0; i < graph->num_chunks; i++) {
 202                uint32_t chunk_id;
 203                uint64_t chunk_offset;
 204                int chunk_repeated = 0;
 205
 206                if (data + graph_size - chunk_lookup <
 207                    GRAPH_CHUNKLOOKUP_WIDTH) {
 208                        error(_("chunk lookup table entry missing; graph file may be incomplete"));
 209                        free(graph);
 210                        return NULL;
 211                }
 212
 213                chunk_id = get_be32(chunk_lookup + 0);
 214                chunk_offset = get_be64(chunk_lookup + 4);
 215
 216                chunk_lookup += GRAPH_CHUNKLOOKUP_WIDTH;
 217
 218                if (chunk_offset > graph_size - the_hash_algo->rawsz) {
 219                        error(_("improper chunk offset %08x%08x"), (uint32_t)(chunk_offset >> 32),
 220                              (uint32_t)chunk_offset);
 221                        free(graph);
 222                        return NULL;
 223                }
 224
 225                switch (chunk_id) {
 226                case GRAPH_CHUNKID_OIDFANOUT:
 227                        if (graph->chunk_oid_fanout)
 228                                chunk_repeated = 1;
 229                        else
 230                                graph->chunk_oid_fanout = (uint32_t*)(data + chunk_offset);
 231                        break;
 232
 233                case GRAPH_CHUNKID_OIDLOOKUP:
 234                        if (graph->chunk_oid_lookup)
 235                                chunk_repeated = 1;
 236                        else
 237                                graph->chunk_oid_lookup = data + chunk_offset;
 238                        break;
 239
 240                case GRAPH_CHUNKID_DATA:
 241                        if (graph->chunk_commit_data)
 242                                chunk_repeated = 1;
 243                        else
 244                                graph->chunk_commit_data = data + chunk_offset;
 245                        break;
 246
 247                case GRAPH_CHUNKID_EXTRAEDGES:
 248                        if (graph->chunk_extra_edges)
 249                                chunk_repeated = 1;
 250                        else
 251                                graph->chunk_extra_edges = data + chunk_offset;
 252                        break;
 253                }
 254
 255                if (chunk_repeated) {
 256                        error(_("chunk id %08x appears multiple times"), chunk_id);
 257                        free(graph);
 258                        return NULL;
 259                }
 260
 261                if (last_chunk_id == GRAPH_CHUNKID_OIDLOOKUP)
 262                {
 263                        graph->num_commits = (chunk_offset - last_chunk_offset)
 264                                             / graph->hash_len;
 265                }
 266
 267                last_chunk_id = chunk_id;
 268                last_chunk_offset = chunk_offset;
 269        }
 270
 271        if (verify_commit_graph_lite(graph))
 272                return NULL;
 273
 274        return graph;
 275}
 276
 277static struct commit_graph *load_commit_graph_one(const char *graph_file)
 278{
 279
 280        struct stat st;
 281        int fd;
 282        int open_ok = open_commit_graph(graph_file, &fd, &st);
 283
 284        if (!open_ok)
 285                return NULL;
 286
 287        return load_commit_graph_one_fd_st(graph_file, fd, &st);
 288}
 289
 290static void prepare_commit_graph_one(struct repository *r, const char *obj_dir)
 291{
 292        char *graph_name;
 293
 294        if (r->objects->commit_graph)
 295                return;
 296
 297        graph_name = get_commit_graph_filename(obj_dir);
 298        r->objects->commit_graph =
 299                load_commit_graph_one(graph_name);
 300
 301        FREE_AND_NULL(graph_name);
 302}
 303
 304/*
 305 * Return 1 if commit_graph is non-NULL, and 0 otherwise.
 306 *
 307 * On the first invocation, this function attemps to load the commit
 308 * graph if the_repository is configured to have one.
 309 */
 310static int prepare_commit_graph(struct repository *r)
 311{
 312        struct object_directory *odb;
 313        int config_value;
 314
 315        if (r->objects->commit_graph_attempted)
 316                return !!r->objects->commit_graph;
 317        r->objects->commit_graph_attempted = 1;
 318
 319        if (!git_env_bool(GIT_TEST_COMMIT_GRAPH, 0) &&
 320            (repo_config_get_bool(r, "core.commitgraph", &config_value) ||
 321            !config_value))
 322                /*
 323                 * This repository is not configured to use commit graphs, so
 324                 * do not load one. (But report commit_graph_attempted anyway
 325                 * so that commit graph loading is not attempted again for this
 326                 * repository.)
 327                 */
 328                return 0;
 329
 330        if (!commit_graph_compatible(r))
 331                return 0;
 332
 333        prepare_alt_odb(r);
 334        for (odb = r->objects->odb;
 335             !r->objects->commit_graph && odb;
 336             odb = odb->next)
 337                prepare_commit_graph_one(r, odb->path);
 338        return !!r->objects->commit_graph;
 339}
 340
 341int generation_numbers_enabled(struct repository *r)
 342{
 343        uint32_t first_generation;
 344        struct commit_graph *g;
 345        if (!prepare_commit_graph(r))
 346               return 0;
 347
 348        g = r->objects->commit_graph;
 349
 350        if (!g->num_commits)
 351                return 0;
 352
 353        first_generation = get_be32(g->chunk_commit_data +
 354                                    g->hash_len + 8) >> 2;
 355
 356        return !!first_generation;
 357}
 358
 359void close_commit_graph(struct repository *r)
 360{
 361        free_commit_graph(r->objects->commit_graph);
 362        r->objects->commit_graph = NULL;
 363}
 364
 365static int bsearch_graph(struct commit_graph *g, struct object_id *oid, uint32_t *pos)
 366{
 367        return bsearch_hash(oid->hash, g->chunk_oid_fanout,
 368                            g->chunk_oid_lookup, g->hash_len, pos);
 369}
 370
 371static struct commit_list **insert_parent_or_die(struct repository *r,
 372                                                 struct commit_graph *g,
 373                                                 uint64_t pos,
 374                                                 struct commit_list **pptr)
 375{
 376        struct commit *c;
 377        struct object_id oid;
 378
 379        if (pos >= g->num_commits)
 380                die("invalid parent position %"PRIu64, pos);
 381
 382        hashcpy(oid.hash, g->chunk_oid_lookup + g->hash_len * pos);
 383        c = lookup_commit(r, &oid);
 384        if (!c)
 385                die(_("could not find commit %s"), oid_to_hex(&oid));
 386        c->graph_pos = pos;
 387        return &commit_list_insert(c, pptr)->next;
 388}
 389
 390static void fill_commit_graph_info(struct commit *item, struct commit_graph *g, uint32_t pos)
 391{
 392        const unsigned char *commit_data = g->chunk_commit_data + GRAPH_DATA_WIDTH * pos;
 393        item->graph_pos = pos;
 394        item->generation = get_be32(commit_data + g->hash_len + 8) >> 2;
 395}
 396
 397static int fill_commit_in_graph(struct repository *r,
 398                                struct commit *item,
 399                                struct commit_graph *g, uint32_t pos)
 400{
 401        uint32_t edge_value;
 402        uint32_t *parent_data_ptr;
 403        uint64_t date_low, date_high;
 404        struct commit_list **pptr;
 405        const unsigned char *commit_data = g->chunk_commit_data + (g->hash_len + 16) * pos;
 406
 407        item->object.parsed = 1;
 408        item->graph_pos = pos;
 409
 410        item->maybe_tree = NULL;
 411
 412        date_high = get_be32(commit_data + g->hash_len + 8) & 0x3;
 413        date_low = get_be32(commit_data + g->hash_len + 12);
 414        item->date = (timestamp_t)((date_high << 32) | date_low);
 415
 416        item->generation = get_be32(commit_data + g->hash_len + 8) >> 2;
 417
 418        pptr = &item->parents;
 419
 420        edge_value = get_be32(commit_data + g->hash_len);
 421        if (edge_value == GRAPH_PARENT_NONE)
 422                return 1;
 423        pptr = insert_parent_or_die(r, g, edge_value, pptr);
 424
 425        edge_value = get_be32(commit_data + g->hash_len + 4);
 426        if (edge_value == GRAPH_PARENT_NONE)
 427                return 1;
 428        if (!(edge_value & GRAPH_EXTRA_EDGES_NEEDED)) {
 429                pptr = insert_parent_or_die(r, g, edge_value, pptr);
 430                return 1;
 431        }
 432
 433        parent_data_ptr = (uint32_t*)(g->chunk_extra_edges +
 434                          4 * (uint64_t)(edge_value & GRAPH_EDGE_LAST_MASK));
 435        do {
 436                edge_value = get_be32(parent_data_ptr);
 437                pptr = insert_parent_or_die(r, g,
 438                                            edge_value & GRAPH_EDGE_LAST_MASK,
 439                                            pptr);
 440                parent_data_ptr++;
 441        } while (!(edge_value & GRAPH_LAST_EDGE));
 442
 443        return 1;
 444}
 445
 446static int find_commit_in_graph(struct commit *item, struct commit_graph *g, uint32_t *pos)
 447{
 448        if (item->graph_pos != COMMIT_NOT_FROM_GRAPH) {
 449                *pos = item->graph_pos;
 450                return 1;
 451        } else {
 452                return bsearch_graph(g, &(item->object.oid), pos);
 453        }
 454}
 455
 456static int parse_commit_in_graph_one(struct repository *r,
 457                                     struct commit_graph *g,
 458                                     struct commit *item)
 459{
 460        uint32_t pos;
 461
 462        if (item->object.parsed)
 463                return 1;
 464
 465        if (find_commit_in_graph(item, g, &pos))
 466                return fill_commit_in_graph(r, item, g, pos);
 467
 468        return 0;
 469}
 470
 471int parse_commit_in_graph(struct repository *r, struct commit *item)
 472{
 473        if (!prepare_commit_graph(r))
 474                return 0;
 475        return parse_commit_in_graph_one(r, r->objects->commit_graph, item);
 476}
 477
 478void load_commit_graph_info(struct repository *r, struct commit *item)
 479{
 480        uint32_t pos;
 481        if (!prepare_commit_graph(r))
 482                return;
 483        if (find_commit_in_graph(item, r->objects->commit_graph, &pos))
 484                fill_commit_graph_info(item, r->objects->commit_graph, pos);
 485}
 486
 487static struct tree *load_tree_for_commit(struct repository *r,
 488                                         struct commit_graph *g,
 489                                         struct commit *c)
 490{
 491        struct object_id oid;
 492        const unsigned char *commit_data = g->chunk_commit_data +
 493                                           GRAPH_DATA_WIDTH * (c->graph_pos);
 494
 495        hashcpy(oid.hash, commit_data);
 496        c->maybe_tree = lookup_tree(r, &oid);
 497
 498        return c->maybe_tree;
 499}
 500
 501static struct tree *get_commit_tree_in_graph_one(struct repository *r,
 502                                                 struct commit_graph *g,
 503                                                 const struct commit *c)
 504{
 505        if (c->maybe_tree)
 506                return c->maybe_tree;
 507        if (c->graph_pos == COMMIT_NOT_FROM_GRAPH)
 508                BUG("get_commit_tree_in_graph_one called from non-commit-graph commit");
 509
 510        return load_tree_for_commit(r, g, (struct commit *)c);
 511}
 512
 513struct tree *get_commit_tree_in_graph(struct repository *r, const struct commit *c)
 514{
 515        return get_commit_tree_in_graph_one(r, r->objects->commit_graph, c);
 516}
 517
 518static void write_graph_chunk_fanout(struct hashfile *f,
 519                                     struct commit **commits,
 520                                     int nr_commits,
 521                                     struct progress *progress,
 522                                     uint64_t *progress_cnt)
 523{
 524        int i, count = 0;
 525        struct commit **list = commits;
 526
 527        /*
 528         * Write the first-level table (the list is sorted,
 529         * but we use a 256-entry lookup to be able to avoid
 530         * having to do eight extra binary search iterations).
 531         */
 532        for (i = 0; i < 256; i++) {
 533                while (count < nr_commits) {
 534                        if ((*list)->object.oid.hash[0] != i)
 535                                break;
 536                        display_progress(progress, ++*progress_cnt);
 537                        count++;
 538                        list++;
 539                }
 540
 541                hashwrite_be32(f, count);
 542        }
 543}
 544
 545static void write_graph_chunk_oids(struct hashfile *f, int hash_len,
 546                                   struct commit **commits, int nr_commits,
 547                                   struct progress *progress,
 548                                   uint64_t *progress_cnt)
 549{
 550        struct commit **list = commits;
 551        int count;
 552        for (count = 0; count < nr_commits; count++, list++) {
 553                display_progress(progress, ++*progress_cnt);
 554                hashwrite(f, (*list)->object.oid.hash, (int)hash_len);
 555        }
 556}
 557
 558static const unsigned char *commit_to_sha1(size_t index, void *table)
 559{
 560        struct commit **commits = table;
 561        return commits[index]->object.oid.hash;
 562}
 563
 564static void write_graph_chunk_data(struct hashfile *f, int hash_len,
 565                                   struct commit **commits, int nr_commits,
 566                                   struct progress *progress,
 567                                   uint64_t *progress_cnt)
 568{
 569        struct commit **list = commits;
 570        struct commit **last = commits + nr_commits;
 571        uint32_t num_extra_edges = 0;
 572
 573        while (list < last) {
 574                struct commit_list *parent;
 575                int edge_value;
 576                uint32_t packedDate[2];
 577                display_progress(progress, ++*progress_cnt);
 578
 579                parse_commit(*list);
 580                hashwrite(f, get_commit_tree_oid(*list)->hash, hash_len);
 581
 582                parent = (*list)->parents;
 583
 584                if (!parent)
 585                        edge_value = GRAPH_PARENT_NONE;
 586                else {
 587                        edge_value = sha1_pos(parent->item->object.oid.hash,
 588                                              commits,
 589                                              nr_commits,
 590                                              commit_to_sha1);
 591
 592                        if (edge_value < 0)
 593                                BUG("missing parent %s for commit %s",
 594                                    oid_to_hex(&parent->item->object.oid),
 595                                    oid_to_hex(&(*list)->object.oid));
 596                }
 597
 598                hashwrite_be32(f, edge_value);
 599
 600                if (parent)
 601                        parent = parent->next;
 602
 603                if (!parent)
 604                        edge_value = GRAPH_PARENT_NONE;
 605                else if (parent->next)
 606                        edge_value = GRAPH_EXTRA_EDGES_NEEDED | num_extra_edges;
 607                else {
 608                        edge_value = sha1_pos(parent->item->object.oid.hash,
 609                                              commits,
 610                                              nr_commits,
 611                                              commit_to_sha1);
 612                        if (edge_value < 0)
 613                                BUG("missing parent %s for commit %s",
 614                                    oid_to_hex(&parent->item->object.oid),
 615                                    oid_to_hex(&(*list)->object.oid));
 616                }
 617
 618                hashwrite_be32(f, edge_value);
 619
 620                if (edge_value & GRAPH_EXTRA_EDGES_NEEDED) {
 621                        do {
 622                                num_extra_edges++;
 623                                parent = parent->next;
 624                        } while (parent);
 625                }
 626
 627                if (sizeof((*list)->date) > 4)
 628                        packedDate[0] = htonl(((*list)->date >> 32) & 0x3);
 629                else
 630                        packedDate[0] = 0;
 631
 632                packedDate[0] |= htonl((*list)->generation << 2);
 633
 634                packedDate[1] = htonl((*list)->date);
 635                hashwrite(f, packedDate, 8);
 636
 637                list++;
 638        }
 639}
 640
 641static void write_graph_chunk_extra_edges(struct hashfile *f,
 642                                          struct commit **commits,
 643                                          int nr_commits,
 644                                          struct progress *progress,
 645                                          uint64_t *progress_cnt)
 646{
 647        struct commit **list = commits;
 648        struct commit **last = commits + nr_commits;
 649        struct commit_list *parent;
 650
 651        while (list < last) {
 652                int num_parents = 0;
 653
 654                display_progress(progress, ++*progress_cnt);
 655
 656                for (parent = (*list)->parents; num_parents < 3 && parent;
 657                     parent = parent->next)
 658                        num_parents++;
 659
 660                if (num_parents <= 2) {
 661                        list++;
 662                        continue;
 663                }
 664
 665                /* Since num_parents > 2, this initializer is safe. */
 666                for (parent = (*list)->parents->next; parent; parent = parent->next) {
 667                        int edge_value = sha1_pos(parent->item->object.oid.hash,
 668                                                  commits,
 669                                                  nr_commits,
 670                                                  commit_to_sha1);
 671
 672                        if (edge_value < 0)
 673                                BUG("missing parent %s for commit %s",
 674                                    oid_to_hex(&parent->item->object.oid),
 675                                    oid_to_hex(&(*list)->object.oid));
 676                        else if (!parent->next)
 677                                edge_value |= GRAPH_LAST_EDGE;
 678
 679                        hashwrite_be32(f, edge_value);
 680                }
 681
 682                list++;
 683        }
 684}
 685
 686static int commit_compare(const void *_a, const void *_b)
 687{
 688        const struct object_id *a = (const struct object_id *)_a;
 689        const struct object_id *b = (const struct object_id *)_b;
 690        return oidcmp(a, b);
 691}
 692
 693struct packed_commit_list {
 694        struct commit **list;
 695        int nr;
 696        int alloc;
 697};
 698
 699struct packed_oid_list {
 700        struct object_id *list;
 701        int nr;
 702        int alloc;
 703        struct progress *progress;
 704        int progress_done;
 705};
 706
 707static int add_packed_commits(const struct object_id *oid,
 708                              struct packed_git *pack,
 709                              uint32_t pos,
 710                              void *data)
 711{
 712        struct packed_oid_list *list = (struct packed_oid_list*)data;
 713        enum object_type type;
 714        off_t offset = nth_packed_object_offset(pack, pos);
 715        struct object_info oi = OBJECT_INFO_INIT;
 716
 717        if (list->progress)
 718                display_progress(list->progress, ++list->progress_done);
 719
 720        oi.typep = &type;
 721        if (packed_object_info(the_repository, pack, offset, &oi) < 0)
 722                die(_("unable to get type of object %s"), oid_to_hex(oid));
 723
 724        if (type != OBJ_COMMIT)
 725                return 0;
 726
 727        ALLOC_GROW(list->list, list->nr + 1, list->alloc);
 728        oidcpy(&(list->list[list->nr]), oid);
 729        list->nr++;
 730
 731        return 0;
 732}
 733
 734static void add_missing_parents(struct packed_oid_list *oids, struct commit *commit)
 735{
 736        struct commit_list *parent;
 737        for (parent = commit->parents; parent; parent = parent->next) {
 738                if (!(parent->item->object.flags & UNINTERESTING)) {
 739                        ALLOC_GROW(oids->list, oids->nr + 1, oids->alloc);
 740                        oidcpy(&oids->list[oids->nr], &(parent->item->object.oid));
 741                        oids->nr++;
 742                        parent->item->object.flags |= UNINTERESTING;
 743                }
 744        }
 745}
 746
 747static void close_reachable(struct packed_oid_list *oids, int report_progress)
 748{
 749        int i;
 750        struct commit *commit;
 751        struct progress *progress = NULL;
 752
 753        if (report_progress)
 754                progress = start_delayed_progress(
 755                        _("Loading known commits in commit graph"), oids->nr);
 756        for (i = 0; i < oids->nr; i++) {
 757                display_progress(progress, i + 1);
 758                commit = lookup_commit(the_repository, &oids->list[i]);
 759                if (commit)
 760                        commit->object.flags |= UNINTERESTING;
 761        }
 762        stop_progress(&progress);
 763
 764        /*
 765         * As this loop runs, oids->nr may grow, but not more
 766         * than the number of missing commits in the reachable
 767         * closure.
 768         */
 769        if (report_progress)
 770                progress = start_delayed_progress(
 771                        _("Expanding reachable commits in commit graph"), oids->nr);
 772        for (i = 0; i < oids->nr; i++) {
 773                display_progress(progress, i + 1);
 774                commit = lookup_commit(the_repository, &oids->list[i]);
 775
 776                if (commit && !parse_commit(commit))
 777                        add_missing_parents(oids, commit);
 778        }
 779        stop_progress(&progress);
 780
 781        if (report_progress)
 782                progress = start_delayed_progress(
 783                        _("Clearing commit marks in commit graph"), oids->nr);
 784        for (i = 0; i < oids->nr; i++) {
 785                display_progress(progress, i + 1);
 786                commit = lookup_commit(the_repository, &oids->list[i]);
 787
 788                if (commit)
 789                        commit->object.flags &= ~UNINTERESTING;
 790        }
 791        stop_progress(&progress);
 792}
 793
 794static void compute_generation_numbers(struct packed_commit_list* commits,
 795                                       int report_progress)
 796{
 797        int i;
 798        struct commit_list *list = NULL;
 799        struct progress *progress = NULL;
 800
 801        if (report_progress)
 802                progress = start_progress(
 803                        _("Computing commit graph generation numbers"),
 804                        commits->nr);
 805        for (i = 0; i < commits->nr; i++) {
 806                display_progress(progress, i + 1);
 807                if (commits->list[i]->generation != GENERATION_NUMBER_INFINITY &&
 808                    commits->list[i]->generation != GENERATION_NUMBER_ZERO)
 809                        continue;
 810
 811                commit_list_insert(commits->list[i], &list);
 812                while (list) {
 813                        struct commit *current = list->item;
 814                        struct commit_list *parent;
 815                        int all_parents_computed = 1;
 816                        uint32_t max_generation = 0;
 817
 818                        for (parent = current->parents; parent; parent = parent->next) {
 819                                if (parent->item->generation == GENERATION_NUMBER_INFINITY ||
 820                                    parent->item->generation == GENERATION_NUMBER_ZERO) {
 821                                        all_parents_computed = 0;
 822                                        commit_list_insert(parent->item, &list);
 823                                        break;
 824                                } else if (parent->item->generation > max_generation) {
 825                                        max_generation = parent->item->generation;
 826                                }
 827                        }
 828
 829                        if (all_parents_computed) {
 830                                current->generation = max_generation + 1;
 831                                pop_commit(&list);
 832
 833                                if (current->generation > GENERATION_NUMBER_MAX)
 834                                        current->generation = GENERATION_NUMBER_MAX;
 835                        }
 836                }
 837        }
 838        stop_progress(&progress);
 839}
 840
 841static int add_ref_to_list(const char *refname,
 842                           const struct object_id *oid,
 843                           int flags, void *cb_data)
 844{
 845        struct string_list *list = (struct string_list *)cb_data;
 846
 847        string_list_append(list, oid_to_hex(oid));
 848        return 0;
 849}
 850
 851void write_commit_graph_reachable(const char *obj_dir, int append,
 852                                  int report_progress)
 853{
 854        struct string_list list = STRING_LIST_INIT_DUP;
 855
 856        for_each_ref(add_ref_to_list, &list);
 857        write_commit_graph(obj_dir, NULL, &list, append, report_progress);
 858
 859        string_list_clear(&list, 0);
 860}
 861
 862void write_commit_graph(const char *obj_dir,
 863                        struct string_list *pack_indexes,
 864                        struct string_list *commit_hex,
 865                        int append, int report_progress)
 866{
 867        struct packed_oid_list oids;
 868        struct packed_commit_list commits;
 869        struct hashfile *f;
 870        uint32_t i, count_distinct = 0;
 871        char *graph_name;
 872        struct lock_file lk = LOCK_INIT;
 873        uint32_t chunk_ids[5];
 874        uint64_t chunk_offsets[5];
 875        int num_chunks;
 876        int num_extra_edges;
 877        struct commit_list *parent;
 878        struct progress *progress = NULL;
 879        const unsigned hashsz = the_hash_algo->rawsz;
 880        uint64_t progress_cnt = 0;
 881        struct strbuf progress_title = STRBUF_INIT;
 882        unsigned long approx_nr_objects;
 883
 884        if (!commit_graph_compatible(the_repository))
 885                return;
 886
 887        oids.nr = 0;
 888        approx_nr_objects = approximate_object_count();
 889        oids.alloc = approx_nr_objects / 32;
 890        oids.progress = NULL;
 891        oids.progress_done = 0;
 892
 893        if (append) {
 894                prepare_commit_graph_one(the_repository, obj_dir);
 895                if (the_repository->objects->commit_graph)
 896                        oids.alloc += the_repository->objects->commit_graph->num_commits;
 897        }
 898
 899        if (oids.alloc < 1024)
 900                oids.alloc = 1024;
 901        ALLOC_ARRAY(oids.list, oids.alloc);
 902
 903        if (append && the_repository->objects->commit_graph) {
 904                struct commit_graph *commit_graph =
 905                        the_repository->objects->commit_graph;
 906                for (i = 0; i < commit_graph->num_commits; i++) {
 907                        const unsigned char *hash = commit_graph->chunk_oid_lookup +
 908                                commit_graph->hash_len * i;
 909                        hashcpy(oids.list[oids.nr++].hash, hash);
 910                }
 911        }
 912
 913        if (pack_indexes) {
 914                struct strbuf packname = STRBUF_INIT;
 915                int dirlen;
 916                strbuf_addf(&packname, "%s/pack/", obj_dir);
 917                dirlen = packname.len;
 918                if (report_progress) {
 919                        strbuf_addf(&progress_title,
 920                                    Q_("Finding commits for commit graph in %d pack",
 921                                       "Finding commits for commit graph in %d packs",
 922                                       pack_indexes->nr),
 923                                    pack_indexes->nr);
 924                        oids.progress = start_delayed_progress(progress_title.buf, 0);
 925                        oids.progress_done = 0;
 926                }
 927                for (i = 0; i < pack_indexes->nr; i++) {
 928                        struct packed_git *p;
 929                        strbuf_setlen(&packname, dirlen);
 930                        strbuf_addstr(&packname, pack_indexes->items[i].string);
 931                        p = add_packed_git(packname.buf, packname.len, 1);
 932                        if (!p)
 933                                die(_("error adding pack %s"), packname.buf);
 934                        if (open_pack_index(p))
 935                                die(_("error opening index for %s"), packname.buf);
 936                        for_each_object_in_pack(p, add_packed_commits, &oids,
 937                                                FOR_EACH_OBJECT_PACK_ORDER);
 938                        close_pack(p);
 939                        free(p);
 940                }
 941                stop_progress(&oids.progress);
 942                strbuf_reset(&progress_title);
 943                strbuf_release(&packname);
 944        }
 945
 946        if (commit_hex) {
 947                if (report_progress) {
 948                        strbuf_addf(&progress_title,
 949                                    Q_("Finding commits for commit graph from %d ref",
 950                                       "Finding commits for commit graph from %d refs",
 951                                       commit_hex->nr),
 952                                    commit_hex->nr);
 953                        progress = start_delayed_progress(progress_title.buf,
 954                                                          commit_hex->nr);
 955                }
 956                for (i = 0; i < commit_hex->nr; i++) {
 957                        const char *end;
 958                        struct object_id oid;
 959                        struct commit *result;
 960
 961                        display_progress(progress, i + 1);
 962                        if (commit_hex->items[i].string &&
 963                            parse_oid_hex(commit_hex->items[i].string, &oid, &end))
 964                                continue;
 965
 966                        result = lookup_commit_reference_gently(the_repository, &oid, 1);
 967
 968                        if (result) {
 969                                ALLOC_GROW(oids.list, oids.nr + 1, oids.alloc);
 970                                oidcpy(&oids.list[oids.nr], &(result->object.oid));
 971                                oids.nr++;
 972                        }
 973                }
 974                stop_progress(&progress);
 975                strbuf_reset(&progress_title);
 976        }
 977
 978        if (!pack_indexes && !commit_hex) {
 979                if (report_progress)
 980                        oids.progress = start_delayed_progress(
 981                                _("Finding commits for commit graph among packed objects"),
 982                                approx_nr_objects);
 983                for_each_packed_object(add_packed_commits, &oids,
 984                                       FOR_EACH_OBJECT_PACK_ORDER);
 985                if (oids.progress_done < approx_nr_objects)
 986                        display_progress(oids.progress, approx_nr_objects);
 987                stop_progress(&oids.progress);
 988        }
 989
 990        close_reachable(&oids, report_progress);
 991
 992        if (report_progress)
 993                progress = start_delayed_progress(
 994                        _("Counting distinct commits in commit graph"),
 995                        oids.nr);
 996        display_progress(progress, 0); /* TODO: Measure QSORT() progress */
 997        QSORT(oids.list, oids.nr, commit_compare);
 998        count_distinct = 1;
 999        for (i = 1; i < oids.nr; i++) {
1000                display_progress(progress, i + 1);
1001                if (!oideq(&oids.list[i - 1], &oids.list[i]))
1002                        count_distinct++;
1003        }
1004        stop_progress(&progress);
1005
1006        if (count_distinct >= GRAPH_EDGE_LAST_MASK)
1007                die(_("the commit graph format cannot write %d commits"), count_distinct);
1008
1009        commits.nr = 0;
1010        commits.alloc = count_distinct;
1011        ALLOC_ARRAY(commits.list, commits.alloc);
1012
1013        num_extra_edges = 0;
1014        if (report_progress)
1015                progress = start_delayed_progress(
1016                        _("Finding extra edges in commit graph"),
1017                        oids.nr);
1018        for (i = 0; i < oids.nr; i++) {
1019                int num_parents = 0;
1020                display_progress(progress, i + 1);
1021                if (i > 0 && oideq(&oids.list[i - 1], &oids.list[i]))
1022                        continue;
1023
1024                commits.list[commits.nr] = lookup_commit(the_repository, &oids.list[i]);
1025                parse_commit(commits.list[commits.nr]);
1026
1027                for (parent = commits.list[commits.nr]->parents;
1028                     parent; parent = parent->next)
1029                        num_parents++;
1030
1031                if (num_parents > 2)
1032                        num_extra_edges += num_parents - 1;
1033
1034                commits.nr++;
1035        }
1036        num_chunks = num_extra_edges ? 4 : 3;
1037        stop_progress(&progress);
1038
1039        if (commits.nr >= GRAPH_EDGE_LAST_MASK)
1040                die(_("too many commits to write graph"));
1041
1042        compute_generation_numbers(&commits, report_progress);
1043
1044        graph_name = get_commit_graph_filename(obj_dir);
1045        if (safe_create_leading_directories(graph_name)) {
1046                UNLEAK(graph_name);
1047                die_errno(_("unable to create leading directories of %s"),
1048                          graph_name);
1049        }
1050
1051        hold_lock_file_for_update(&lk, graph_name, LOCK_DIE_ON_ERROR);
1052        f = hashfd(lk.tempfile->fd, lk.tempfile->filename.buf);
1053
1054        hashwrite_be32(f, GRAPH_SIGNATURE);
1055
1056        hashwrite_u8(f, GRAPH_VERSION);
1057        hashwrite_u8(f, oid_version());
1058        hashwrite_u8(f, num_chunks);
1059        hashwrite_u8(f, 0); /* unused padding byte */
1060
1061        chunk_ids[0] = GRAPH_CHUNKID_OIDFANOUT;
1062        chunk_ids[1] = GRAPH_CHUNKID_OIDLOOKUP;
1063        chunk_ids[2] = GRAPH_CHUNKID_DATA;
1064        if (num_extra_edges)
1065                chunk_ids[3] = GRAPH_CHUNKID_EXTRAEDGES;
1066        else
1067                chunk_ids[3] = 0;
1068        chunk_ids[4] = 0;
1069
1070        chunk_offsets[0] = 8 + (num_chunks + 1) * GRAPH_CHUNKLOOKUP_WIDTH;
1071        chunk_offsets[1] = chunk_offsets[0] + GRAPH_FANOUT_SIZE;
1072        chunk_offsets[2] = chunk_offsets[1] + hashsz * commits.nr;
1073        chunk_offsets[3] = chunk_offsets[2] + (hashsz + 16) * commits.nr;
1074        chunk_offsets[4] = chunk_offsets[3] + 4 * num_extra_edges;
1075
1076        for (i = 0; i <= num_chunks; i++) {
1077                uint32_t chunk_write[3];
1078
1079                chunk_write[0] = htonl(chunk_ids[i]);
1080                chunk_write[1] = htonl(chunk_offsets[i] >> 32);
1081                chunk_write[2] = htonl(chunk_offsets[i] & 0xffffffff);
1082                hashwrite(f, chunk_write, 12);
1083        }
1084
1085        if (report_progress) {
1086                strbuf_addf(&progress_title,
1087                            Q_("Writing out commit graph in %d pass",
1088                               "Writing out commit graph in %d passes",
1089                               num_chunks),
1090                            num_chunks);
1091                progress = start_delayed_progress(
1092                        progress_title.buf,
1093                        num_chunks * commits.nr);
1094        }
1095        write_graph_chunk_fanout(f, commits.list, commits.nr, progress, &progress_cnt);
1096        write_graph_chunk_oids(f, hashsz, commits.list, commits.nr, progress, &progress_cnt);
1097        write_graph_chunk_data(f, hashsz, commits.list, commits.nr, progress, &progress_cnt);
1098        if (num_extra_edges)
1099                write_graph_chunk_extra_edges(f, commits.list, commits.nr, progress, &progress_cnt);
1100        stop_progress(&progress);
1101        strbuf_release(&progress_title);
1102
1103        close_commit_graph(the_repository);
1104        finalize_hashfile(f, NULL, CSUM_HASH_IN_STREAM | CSUM_FSYNC);
1105        commit_lock_file(&lk);
1106
1107        free(graph_name);
1108        free(commits.list);
1109        free(oids.list);
1110}
1111
1112#define VERIFY_COMMIT_GRAPH_ERROR_HASH 2
1113static int verify_commit_graph_error;
1114
1115static void graph_report(const char *fmt, ...)
1116{
1117        va_list ap;
1118
1119        verify_commit_graph_error = 1;
1120        va_start(ap, fmt);
1121        vfprintf(stderr, fmt, ap);
1122        fprintf(stderr, "\n");
1123        va_end(ap);
1124}
1125
1126#define GENERATION_ZERO_EXISTS 1
1127#define GENERATION_NUMBER_EXISTS 2
1128
1129int verify_commit_graph(struct repository *r, struct commit_graph *g)
1130{
1131        uint32_t i, cur_fanout_pos = 0;
1132        struct object_id prev_oid, cur_oid, checksum;
1133        int generation_zero = 0;
1134        struct hashfile *f;
1135        int devnull;
1136        struct progress *progress = NULL;
1137
1138        if (!g) {
1139                graph_report("no commit-graph file loaded");
1140                return 1;
1141        }
1142
1143        verify_commit_graph_error = verify_commit_graph_lite(g);
1144        if (verify_commit_graph_error)
1145                return verify_commit_graph_error;
1146
1147        devnull = open("/dev/null", O_WRONLY);
1148        f = hashfd(devnull, NULL);
1149        hashwrite(f, g->data, g->data_len - g->hash_len);
1150        finalize_hashfile(f, checksum.hash, CSUM_CLOSE);
1151        if (!hasheq(checksum.hash, g->data + g->data_len - g->hash_len)) {
1152                graph_report(_("the commit-graph file has incorrect checksum and is likely corrupt"));
1153                verify_commit_graph_error = VERIFY_COMMIT_GRAPH_ERROR_HASH;
1154        }
1155
1156        for (i = 0; i < g->num_commits; i++) {
1157                struct commit *graph_commit;
1158
1159                hashcpy(cur_oid.hash, g->chunk_oid_lookup + g->hash_len * i);
1160
1161                if (i && oidcmp(&prev_oid, &cur_oid) >= 0)
1162                        graph_report("commit-graph has incorrect OID order: %s then %s",
1163                                     oid_to_hex(&prev_oid),
1164                                     oid_to_hex(&cur_oid));
1165
1166                oidcpy(&prev_oid, &cur_oid);
1167
1168                while (cur_oid.hash[0] > cur_fanout_pos) {
1169                        uint32_t fanout_value = get_be32(g->chunk_oid_fanout + cur_fanout_pos);
1170
1171                        if (i != fanout_value)
1172                                graph_report("commit-graph has incorrect fanout value: fanout[%d] = %u != %u",
1173                                             cur_fanout_pos, fanout_value, i);
1174                        cur_fanout_pos++;
1175                }
1176
1177                graph_commit = lookup_commit(r, &cur_oid);
1178                if (!parse_commit_in_graph_one(r, g, graph_commit))
1179                        graph_report("failed to parse %s from commit-graph",
1180                                     oid_to_hex(&cur_oid));
1181        }
1182
1183        while (cur_fanout_pos < 256) {
1184                uint32_t fanout_value = get_be32(g->chunk_oid_fanout + cur_fanout_pos);
1185
1186                if (g->num_commits != fanout_value)
1187                        graph_report("commit-graph has incorrect fanout value: fanout[%d] = %u != %u",
1188                                     cur_fanout_pos, fanout_value, i);
1189
1190                cur_fanout_pos++;
1191        }
1192
1193        if (verify_commit_graph_error & ~VERIFY_COMMIT_GRAPH_ERROR_HASH)
1194                return verify_commit_graph_error;
1195
1196        progress = start_progress(_("Verifying commits in commit graph"),
1197                                  g->num_commits);
1198        for (i = 0; i < g->num_commits; i++) {
1199                struct commit *graph_commit, *odb_commit;
1200                struct commit_list *graph_parents, *odb_parents;
1201                uint32_t max_generation = 0;
1202
1203                display_progress(progress, i + 1);
1204                hashcpy(cur_oid.hash, g->chunk_oid_lookup + g->hash_len * i);
1205
1206                graph_commit = lookup_commit(r, &cur_oid);
1207                odb_commit = (struct commit *)create_object(r, cur_oid.hash, alloc_commit_node(r));
1208                if (parse_commit_internal(odb_commit, 0, 0)) {
1209                        graph_report("failed to parse %s from object database",
1210                                     oid_to_hex(&cur_oid));
1211                        continue;
1212                }
1213
1214                if (!oideq(&get_commit_tree_in_graph_one(r, g, graph_commit)->object.oid,
1215                           get_commit_tree_oid(odb_commit)))
1216                        graph_report("root tree OID for commit %s in commit-graph is %s != %s",
1217                                     oid_to_hex(&cur_oid),
1218                                     oid_to_hex(get_commit_tree_oid(graph_commit)),
1219                                     oid_to_hex(get_commit_tree_oid(odb_commit)));
1220
1221                graph_parents = graph_commit->parents;
1222                odb_parents = odb_commit->parents;
1223
1224                while (graph_parents) {
1225                        if (odb_parents == NULL) {
1226                                graph_report("commit-graph parent list for commit %s is too long",
1227                                             oid_to_hex(&cur_oid));
1228                                break;
1229                        }
1230
1231                        if (!oideq(&graph_parents->item->object.oid, &odb_parents->item->object.oid))
1232                                graph_report("commit-graph parent for %s is %s != %s",
1233                                             oid_to_hex(&cur_oid),
1234                                             oid_to_hex(&graph_parents->item->object.oid),
1235                                             oid_to_hex(&odb_parents->item->object.oid));
1236
1237                        if (graph_parents->item->generation > max_generation)
1238                                max_generation = graph_parents->item->generation;
1239
1240                        graph_parents = graph_parents->next;
1241                        odb_parents = odb_parents->next;
1242                }
1243
1244                if (odb_parents != NULL)
1245                        graph_report("commit-graph parent list for commit %s terminates early",
1246                                     oid_to_hex(&cur_oid));
1247
1248                if (!graph_commit->generation) {
1249                        if (generation_zero == GENERATION_NUMBER_EXISTS)
1250                                graph_report("commit-graph has generation number zero for commit %s, but non-zero elsewhere",
1251                                             oid_to_hex(&cur_oid));
1252                        generation_zero = GENERATION_ZERO_EXISTS;
1253                } else if (generation_zero == GENERATION_ZERO_EXISTS)
1254                        graph_report("commit-graph has non-zero generation number for commit %s, but zero elsewhere",
1255                                     oid_to_hex(&cur_oid));
1256
1257                if (generation_zero == GENERATION_ZERO_EXISTS)
1258                        continue;
1259
1260                /*
1261                 * If one of our parents has generation GENERATION_NUMBER_MAX, then
1262                 * our generation is also GENERATION_NUMBER_MAX. Decrement to avoid
1263                 * extra logic in the following condition.
1264                 */
1265                if (max_generation == GENERATION_NUMBER_MAX)
1266                        max_generation--;
1267
1268                if (graph_commit->generation != max_generation + 1)
1269                        graph_report("commit-graph generation for commit %s is %u != %u",
1270                                     oid_to_hex(&cur_oid),
1271                                     graph_commit->generation,
1272                                     max_generation + 1);
1273
1274                if (graph_commit->date != odb_commit->date)
1275                        graph_report("commit date for commit %s in commit-graph is %"PRItime" != %"PRItime,
1276                                     oid_to_hex(&cur_oid),
1277                                     graph_commit->date,
1278                                     odb_commit->date);
1279        }
1280        stop_progress(&progress);
1281
1282        return verify_commit_graph_error;
1283}
1284
1285void free_commit_graph(struct commit_graph *g)
1286{
1287        if (!g)
1288                return;
1289        if (g->graph_fd >= 0) {
1290                munmap((void *)g->data, g->data_len);
1291                g->data = NULL;
1292                close(g->graph_fd);
1293        }
1294        free(g);
1295}