Merge branch 'ds/chunked-file-api' into tb/reverse-midx
[git] / commit-graph.c
1 #include "git-compat-util.h"
2 #include "config.h"
3 #include "lockfile.h"
4 #include "pack.h"
5 #include "packfile.h"
6 #include "commit.h"
7 #include "object.h"
8 #include "refs.h"
9 #include "revision.h"
10 #include "hash-lookup.h"
11 #include "commit-graph.h"
12 #include "object-store.h"
13 #include "alloc.h"
14 #include "hashmap.h"
15 #include "replace-object.h"
16 #include "progress.h"
17 #include "bloom.h"
18 #include "commit-slab.h"
19 #include "shallow.h"
20 #include "json-writer.h"
21 #include "trace2.h"
22 #include "chunk-format.h"
23
24 void git_test_write_commit_graph_or_die(void)
25 {
26         int flags = 0;
27         if (!git_env_bool(GIT_TEST_COMMIT_GRAPH, 0))
28                 return;
29
30         if (git_env_bool(GIT_TEST_COMMIT_GRAPH_CHANGED_PATHS, 0))
31                 flags = COMMIT_GRAPH_WRITE_BLOOM_FILTERS;
32
33         if (write_commit_graph_reachable(the_repository->objects->odb,
34                                          flags, NULL))
35                 die("failed to write commit-graph under GIT_TEST_COMMIT_GRAPH");
36 }
37
38 #define GRAPH_SIGNATURE 0x43475048 /* "CGPH" */
39 #define GRAPH_CHUNKID_OIDFANOUT 0x4f494446 /* "OIDF" */
40 #define GRAPH_CHUNKID_OIDLOOKUP 0x4f49444c /* "OIDL" */
41 #define GRAPH_CHUNKID_DATA 0x43444154 /* "CDAT" */
42 #define GRAPH_CHUNKID_GENERATION_DATA 0x47444154 /* "GDAT" */
43 #define GRAPH_CHUNKID_GENERATION_DATA_OVERFLOW 0x47444f56 /* "GDOV" */
44 #define GRAPH_CHUNKID_EXTRAEDGES 0x45444745 /* "EDGE" */
45 #define GRAPH_CHUNKID_BLOOMINDEXES 0x42494458 /* "BIDX" */
46 #define GRAPH_CHUNKID_BLOOMDATA 0x42444154 /* "BDAT" */
47 #define GRAPH_CHUNKID_BASE 0x42415345 /* "BASE" */
48
49 #define GRAPH_DATA_WIDTH (the_hash_algo->rawsz + 16)
50
51 #define GRAPH_VERSION_1 0x1
52 #define GRAPH_VERSION GRAPH_VERSION_1
53
54 #define GRAPH_EXTRA_EDGES_NEEDED 0x80000000
55 #define GRAPH_EDGE_LAST_MASK 0x7fffffff
56 #define GRAPH_PARENT_NONE 0x70000000
57
58 #define GRAPH_LAST_EDGE 0x80000000
59
60 #define GRAPH_HEADER_SIZE 8
61 #define GRAPH_FANOUT_SIZE (4 * 256)
62 #define GRAPH_MIN_SIZE (GRAPH_HEADER_SIZE + 4 * CHUNK_TOC_ENTRY_SIZE \
63                         + GRAPH_FANOUT_SIZE + the_hash_algo->rawsz)
64
65 #define CORRECTED_COMMIT_DATE_OFFSET_OVERFLOW (1ULL << 31)
66
67 /* Remember to update object flag allocation in object.h */
68 #define REACHABLE       (1u<<15)
69
70 define_commit_slab(topo_level_slab, uint32_t);
71
72 /* Keep track of the order in which commits are added to our list. */
73 define_commit_slab(commit_pos, int);
74 static struct commit_pos commit_pos = COMMIT_SLAB_INIT(1, commit_pos);
75
76 static void set_commit_pos(struct repository *r, const struct object_id *oid)
77 {
78         static int32_t max_pos;
79         struct commit *commit = lookup_commit(r, oid);
80
81         if (!commit)
82                 return; /* should never happen, but be lenient */
83
84         *commit_pos_at(&commit_pos, commit) = max_pos++;
85 }
86
87 static int commit_pos_cmp(const void *va, const void *vb)
88 {
89         const struct commit *a = *(const struct commit **)va;
90         const struct commit *b = *(const struct commit **)vb;
91         return commit_pos_at(&commit_pos, a) -
92                commit_pos_at(&commit_pos, b);
93 }
94
95 define_commit_slab(commit_graph_data_slab, struct commit_graph_data);
96 static struct commit_graph_data_slab commit_graph_data_slab =
97         COMMIT_SLAB_INIT(1, commit_graph_data_slab);
98
99 uint32_t commit_graph_position(const struct commit *c)
100 {
101         struct commit_graph_data *data =
102                 commit_graph_data_slab_peek(&commit_graph_data_slab, c);
103
104         return data ? data->graph_pos : COMMIT_NOT_FROM_GRAPH;
105 }
106
107 timestamp_t commit_graph_generation(const struct commit *c)
108 {
109         struct commit_graph_data *data =
110                 commit_graph_data_slab_peek(&commit_graph_data_slab, c);
111
112         if (!data)
113                 return GENERATION_NUMBER_INFINITY;
114         else if (data->graph_pos == COMMIT_NOT_FROM_GRAPH)
115                 return GENERATION_NUMBER_INFINITY;
116
117         return data->generation;
118 }
119
120 static struct commit_graph_data *commit_graph_data_at(const struct commit *c)
121 {
122         unsigned int i, nth_slab;
123         struct commit_graph_data *data =
124                 commit_graph_data_slab_peek(&commit_graph_data_slab, c);
125
126         if (data)
127                 return data;
128
129         nth_slab = c->index / commit_graph_data_slab.slab_size;
130         data = commit_graph_data_slab_at(&commit_graph_data_slab, c);
131
132         /*
133          * commit-slab initializes elements with zero, overwrite this with
134          * COMMIT_NOT_FROM_GRAPH for graph_pos.
135          *
136          * We avoid initializing generation with checking if graph position
137          * is not COMMIT_NOT_FROM_GRAPH.
138          */
139         for (i = 0; i < commit_graph_data_slab.slab_size; i++) {
140                 commit_graph_data_slab.slab[nth_slab][i].graph_pos =
141                         COMMIT_NOT_FROM_GRAPH;
142         }
143
144         return data;
145 }
146
147 /*
148  * Should be used only while writing commit-graph as it compares
149  * generation value of commits by directly accessing commit-slab.
150  */
151 static int commit_gen_cmp(const void *va, const void *vb)
152 {
153         const struct commit *a = *(const struct commit **)va;
154         const struct commit *b = *(const struct commit **)vb;
155
156         const timestamp_t generation_a = commit_graph_data_at(a)->generation;
157         const timestamp_t generation_b = commit_graph_data_at(b)->generation;
158         /* lower generation commits first */
159         if (generation_a < generation_b)
160                 return -1;
161         else if (generation_a > generation_b)
162                 return 1;
163
164         /* use date as a heuristic when generations are equal */
165         if (a->date < b->date)
166                 return -1;
167         else if (a->date > b->date)
168                 return 1;
169         return 0;
170 }
171
172 char *get_commit_graph_filename(struct object_directory *obj_dir)
173 {
174         return xstrfmt("%s/info/commit-graph", obj_dir->path);
175 }
176
177 static char *get_split_graph_filename(struct object_directory *odb,
178                                       const char *oid_hex)
179 {
180         return xstrfmt("%s/info/commit-graphs/graph-%s.graph", odb->path,
181                        oid_hex);
182 }
183
184 char *get_commit_graph_chain_filename(struct object_directory *odb)
185 {
186         return xstrfmt("%s/info/commit-graphs/commit-graph-chain", odb->path);
187 }
188
189 static uint8_t oid_version(void)
190 {
191         switch (hash_algo_by_ptr(the_hash_algo)) {
192         case GIT_HASH_SHA1:
193                 return 1;
194         case GIT_HASH_SHA256:
195                 return 2;
196         default:
197                 die(_("invalid hash version"));
198         }
199 }
200
201 static struct commit_graph *alloc_commit_graph(void)
202 {
203         struct commit_graph *g = xcalloc(1, sizeof(*g));
204
205         return g;
206 }
207
208 extern int read_replace_refs;
209
210 static int commit_graph_compatible(struct repository *r)
211 {
212         if (!r->gitdir)
213                 return 0;
214
215         if (read_replace_refs) {
216                 prepare_replace_object(r);
217                 if (hashmap_get_size(&r->objects->replace_map->map)) {
218                         warning(_("repository contains replace objects; "
219                                "skipping commit-graph"));
220                         return 0;
221                 }
222         }
223
224         prepare_commit_graft(r);
225         if (r->parsed_objects &&
226             (r->parsed_objects->grafts_nr || r->parsed_objects->substituted_parent)) {
227                 warning(_("repository contains (deprecated) grafts; "
228                        "skipping commit-graph"));
229                 return 0;
230         }
231         if (is_repository_shallow(r)) {
232                 warning(_("repository is shallow; skipping commit-graph"));
233                 return 0;
234         }
235
236         return 1;
237 }
238
239 int open_commit_graph(const char *graph_file, int *fd, struct stat *st)
240 {
241         *fd = git_open(graph_file);
242         if (*fd < 0)
243                 return 0;
244         if (fstat(*fd, st)) {
245                 close(*fd);
246                 return 0;
247         }
248         return 1;
249 }
250
251 struct commit_graph *load_commit_graph_one_fd_st(struct repository *r,
252                                                  int fd, struct stat *st,
253                                                  struct object_directory *odb)
254 {
255         void *graph_map;
256         size_t graph_size;
257         struct commit_graph *ret;
258
259         graph_size = xsize_t(st->st_size);
260
261         if (graph_size < GRAPH_MIN_SIZE) {
262                 close(fd);
263                 error(_("commit-graph file is too small"));
264                 return NULL;
265         }
266         graph_map = xmmap(NULL, graph_size, PROT_READ, MAP_PRIVATE, fd, 0);
267         close(fd);
268         ret = parse_commit_graph(r, graph_map, graph_size);
269
270         if (ret)
271                 ret->odb = odb;
272         else
273                 munmap(graph_map, graph_size);
274
275         return ret;
276 }
277
278 static int verify_commit_graph_lite(struct commit_graph *g)
279 {
280         /*
281          * Basic validation shared between parse_commit_graph()
282          * which'll be called every time the graph is used, and the
283          * much more expensive verify_commit_graph() used by
284          * "commit-graph verify".
285          *
286          * There should only be very basic checks here to ensure that
287          * we don't e.g. segfault in fill_commit_in_graph(), but
288          * because this is a very hot codepath nothing that e.g. loops
289          * over g->num_commits, or runs a checksum on the commit-graph
290          * itself.
291          */
292         if (!g->chunk_oid_fanout) {
293                 error("commit-graph is missing the OID Fanout chunk");
294                 return 1;
295         }
296         if (!g->chunk_oid_lookup) {
297                 error("commit-graph is missing the OID Lookup chunk");
298                 return 1;
299         }
300         if (!g->chunk_commit_data) {
301                 error("commit-graph is missing the Commit Data chunk");
302                 return 1;
303         }
304
305         return 0;
306 }
307
308 static int graph_read_oid_lookup(const unsigned char *chunk_start,
309                                  size_t chunk_size, void *data)
310 {
311         struct commit_graph *g = data;
312         g->chunk_oid_lookup = chunk_start;
313         g->num_commits = chunk_size / g->hash_len;
314         return 0;
315 }
316
317 static int graph_read_bloom_data(const unsigned char *chunk_start,
318                                   size_t chunk_size, void *data)
319 {
320         struct commit_graph *g = data;
321         uint32_t hash_version;
322         g->chunk_bloom_data = chunk_start;
323         hash_version = get_be32(chunk_start);
324
325         if (hash_version != 1)
326                 return 0;
327
328         g->bloom_filter_settings = xmalloc(sizeof(struct bloom_filter_settings));
329         g->bloom_filter_settings->hash_version = hash_version;
330         g->bloom_filter_settings->num_hashes = get_be32(chunk_start + 4);
331         g->bloom_filter_settings->bits_per_entry = get_be32(chunk_start + 8);
332         g->bloom_filter_settings->max_changed_paths = DEFAULT_BLOOM_MAX_CHANGES;
333
334         return 0;
335 }
336
337 struct commit_graph *parse_commit_graph(struct repository *r,
338                                         void *graph_map, size_t graph_size)
339 {
340         const unsigned char *data;
341         struct commit_graph *graph;
342         uint32_t graph_signature;
343         unsigned char graph_version, hash_version;
344         struct chunkfile *cf = NULL;
345
346         if (!graph_map)
347                 return NULL;
348
349         if (graph_size < GRAPH_MIN_SIZE)
350                 return NULL;
351
352         data = (const unsigned char *)graph_map;
353
354         graph_signature = get_be32(data);
355         if (graph_signature != GRAPH_SIGNATURE) {
356                 error(_("commit-graph signature %X does not match signature %X"),
357                       graph_signature, GRAPH_SIGNATURE);
358                 return NULL;
359         }
360
361         graph_version = *(unsigned char*)(data + 4);
362         if (graph_version != GRAPH_VERSION) {
363                 error(_("commit-graph version %X does not match version %X"),
364                       graph_version, GRAPH_VERSION);
365                 return NULL;
366         }
367
368         hash_version = *(unsigned char*)(data + 5);
369         if (hash_version != oid_version()) {
370                 error(_("commit-graph hash version %X does not match version %X"),
371                       hash_version, oid_version());
372                 return NULL;
373         }
374
375         prepare_repo_settings(r);
376
377         graph = alloc_commit_graph();
378
379         graph->hash_len = the_hash_algo->rawsz;
380         graph->num_chunks = *(unsigned char*)(data + 6);
381         graph->data = graph_map;
382         graph->data_len = graph_size;
383
384         if (graph_size < GRAPH_HEADER_SIZE +
385                          (graph->num_chunks + 1) * CHUNK_TOC_ENTRY_SIZE +
386                          GRAPH_FANOUT_SIZE + the_hash_algo->rawsz) {
387                 error(_("commit-graph file is too small to hold %u chunks"),
388                       graph->num_chunks);
389                 free(graph);
390                 return NULL;
391         }
392
393         cf = init_chunkfile(NULL);
394
395         if (read_table_of_contents(cf, graph->data, graph_size,
396                                    GRAPH_HEADER_SIZE, graph->num_chunks))
397                 goto free_and_return;
398
399         pair_chunk(cf, GRAPH_CHUNKID_OIDFANOUT,
400                    (const unsigned char **)&graph->chunk_oid_fanout);
401         read_chunk(cf, GRAPH_CHUNKID_OIDLOOKUP, graph_read_oid_lookup, graph);
402         pair_chunk(cf, GRAPH_CHUNKID_DATA, &graph->chunk_commit_data);
403         pair_chunk(cf, GRAPH_CHUNKID_EXTRAEDGES, &graph->chunk_extra_edges);
404         pair_chunk(cf, GRAPH_CHUNKID_BASE, &graph->chunk_base_graphs);
405         pair_chunk(cf, GRAPH_CHUNKID_GENERATION_DATA,
406                    &graph->chunk_generation_data);
407         pair_chunk(cf, GRAPH_CHUNKID_GENERATION_DATA_OVERFLOW,
408                    &graph->chunk_generation_data_overflow);
409
410         if (r->settings.commit_graph_read_changed_paths) {
411                 pair_chunk(cf, GRAPH_CHUNKID_BLOOMINDEXES,
412                            &graph->chunk_bloom_indexes);
413                 read_chunk(cf, GRAPH_CHUNKID_BLOOMDATA,
414                            graph_read_bloom_data, graph);
415         }
416
417         if (graph->chunk_bloom_indexes && graph->chunk_bloom_data) {
418                 init_bloom_filters();
419         } else {
420                 /* We need both the bloom chunks to exist together. Else ignore the data */
421                 graph->chunk_bloom_indexes = NULL;
422                 graph->chunk_bloom_data = NULL;
423                 FREE_AND_NULL(graph->bloom_filter_settings);
424         }
425
426         hashcpy(graph->oid.hash, graph->data + graph->data_len - graph->hash_len);
427
428         if (verify_commit_graph_lite(graph))
429                 goto free_and_return;
430
431         free_chunkfile(cf);
432         return graph;
433
434 free_and_return:
435         free_chunkfile(cf);
436         free(graph->bloom_filter_settings);
437         free(graph);
438         return NULL;
439 }
440
441 static struct commit_graph *load_commit_graph_one(struct repository *r,
442                                                   const char *graph_file,
443                                                   struct object_directory *odb)
444 {
445
446         struct stat st;
447         int fd;
448         struct commit_graph *g;
449         int open_ok = open_commit_graph(graph_file, &fd, &st);
450
451         if (!open_ok)
452                 return NULL;
453
454         g = load_commit_graph_one_fd_st(r, fd, &st, odb);
455
456         if (g)
457                 g->filename = xstrdup(graph_file);
458
459         return g;
460 }
461
462 static struct commit_graph *load_commit_graph_v1(struct repository *r,
463                                                  struct object_directory *odb)
464 {
465         char *graph_name = get_commit_graph_filename(odb);
466         struct commit_graph *g = load_commit_graph_one(r, graph_name, odb);
467         free(graph_name);
468
469         return g;
470 }
471
472 static int add_graph_to_chain(struct commit_graph *g,
473                               struct commit_graph *chain,
474                               struct object_id *oids,
475                               int n)
476 {
477         struct commit_graph *cur_g = chain;
478
479         if (n && !g->chunk_base_graphs) {
480                 warning(_("commit-graph has no base graphs chunk"));
481                 return 0;
482         }
483
484         while (n) {
485                 n--;
486
487                 if (!cur_g ||
488                     !oideq(&oids[n], &cur_g->oid) ||
489                     !hasheq(oids[n].hash, g->chunk_base_graphs + g->hash_len * n)) {
490                         warning(_("commit-graph chain does not match"));
491                         return 0;
492                 }
493
494                 cur_g = cur_g->base_graph;
495         }
496
497         g->base_graph = chain;
498
499         if (chain)
500                 g->num_commits_in_base = chain->num_commits + chain->num_commits_in_base;
501
502         return 1;
503 }
504
505 static struct commit_graph *load_commit_graph_chain(struct repository *r,
506                                                     struct object_directory *odb)
507 {
508         struct commit_graph *graph_chain = NULL;
509         struct strbuf line = STRBUF_INIT;
510         struct stat st;
511         struct object_id *oids;
512         int i = 0, valid = 1, count;
513         char *chain_name = get_commit_graph_chain_filename(odb);
514         FILE *fp;
515         int stat_res;
516
517         fp = fopen(chain_name, "r");
518         stat_res = stat(chain_name, &st);
519         free(chain_name);
520
521         if (!fp ||
522             stat_res ||
523             st.st_size <= the_hash_algo->hexsz)
524                 return NULL;
525
526         count = st.st_size / (the_hash_algo->hexsz + 1);
527         oids = xcalloc(count, sizeof(struct object_id));
528
529         prepare_alt_odb(r);
530
531         for (i = 0; i < count; i++) {
532                 struct object_directory *odb;
533
534                 if (strbuf_getline_lf(&line, fp) == EOF)
535                         break;
536
537                 if (get_oid_hex(line.buf, &oids[i])) {
538                         warning(_("invalid commit-graph chain: line '%s' not a hash"),
539                                 line.buf);
540                         valid = 0;
541                         break;
542                 }
543
544                 valid = 0;
545                 for (odb = r->objects->odb; odb; odb = odb->next) {
546                         char *graph_name = get_split_graph_filename(odb, line.buf);
547                         struct commit_graph *g = load_commit_graph_one(r, graph_name, odb);
548
549                         free(graph_name);
550
551                         if (g) {
552                                 if (add_graph_to_chain(g, graph_chain, oids, i)) {
553                                         graph_chain = g;
554                                         valid = 1;
555                                 }
556
557                                 break;
558                         }
559                 }
560
561                 if (!valid) {
562                         warning(_("unable to find all commit-graph files"));
563                         break;
564                 }
565         }
566
567         free(oids);
568         fclose(fp);
569         strbuf_release(&line);
570
571         return graph_chain;
572 }
573
574 /*
575  * returns 1 if and only if all graphs in the chain have
576  * corrected commit dates stored in the generation_data chunk.
577  */
578 static int validate_mixed_generation_chain(struct commit_graph *g)
579 {
580         int read_generation_data = 1;
581         struct commit_graph *p = g;
582
583         while (read_generation_data && p) {
584                 read_generation_data = p->read_generation_data;
585                 p = p->base_graph;
586         }
587
588         if (read_generation_data)
589                 return 1;
590
591         while (g) {
592                 g->read_generation_data = 0;
593                 g = g->base_graph;
594         }
595
596         return 0;
597 }
598
599 struct commit_graph *read_commit_graph_one(struct repository *r,
600                                            struct object_directory *odb)
601 {
602         struct commit_graph *g = load_commit_graph_v1(r, odb);
603
604         if (!g)
605                 g = load_commit_graph_chain(r, odb);
606
607         validate_mixed_generation_chain(g);
608
609         return g;
610 }
611
612 static void prepare_commit_graph_one(struct repository *r,
613                                      struct object_directory *odb)
614 {
615
616         if (r->objects->commit_graph)
617                 return;
618
619         r->objects->commit_graph = read_commit_graph_one(r, odb);
620 }
621
622 /*
623  * Return 1 if commit_graph is non-NULL, and 0 otherwise.
624  *
625  * On the first invocation, this function attempts to load the commit
626  * graph if the_repository is configured to have one.
627  */
628 static int prepare_commit_graph(struct repository *r)
629 {
630         struct object_directory *odb;
631
632         /*
633          * This must come before the "already attempted?" check below, because
634          * we want to disable even an already-loaded graph file.
635          */
636         if (r->commit_graph_disabled)
637                 return 0;
638
639         if (r->objects->commit_graph_attempted)
640                 return !!r->objects->commit_graph;
641         r->objects->commit_graph_attempted = 1;
642
643         prepare_repo_settings(r);
644
645         if (!git_env_bool(GIT_TEST_COMMIT_GRAPH, 0) &&
646             r->settings.core_commit_graph != 1)
647                 /*
648                  * This repository is not configured to use commit graphs, so
649                  * do not load one. (But report commit_graph_attempted anyway
650                  * so that commit graph loading is not attempted again for this
651                  * repository.)
652                  */
653                 return 0;
654
655         if (!commit_graph_compatible(r))
656                 return 0;
657
658         prepare_alt_odb(r);
659         for (odb = r->objects->odb;
660              !r->objects->commit_graph && odb;
661              odb = odb->next)
662                 prepare_commit_graph_one(r, odb);
663         return !!r->objects->commit_graph;
664 }
665
666 int generation_numbers_enabled(struct repository *r)
667 {
668         uint32_t first_generation;
669         struct commit_graph *g;
670         if (!prepare_commit_graph(r))
671                return 0;
672
673         g = r->objects->commit_graph;
674
675         if (!g->num_commits)
676                 return 0;
677
678         first_generation = get_be32(g->chunk_commit_data +
679                                     g->hash_len + 8) >> 2;
680
681         return !!first_generation;
682 }
683
684 int corrected_commit_dates_enabled(struct repository *r)
685 {
686         struct commit_graph *g;
687         if (!prepare_commit_graph(r))
688                 return 0;
689
690         g = r->objects->commit_graph;
691
692         if (!g->num_commits)
693                 return 0;
694
695         return g->read_generation_data;
696 }
697
698 struct bloom_filter_settings *get_bloom_filter_settings(struct repository *r)
699 {
700         struct commit_graph *g = r->objects->commit_graph;
701         while (g) {
702                 if (g->bloom_filter_settings)
703                         return g->bloom_filter_settings;
704                 g = g->base_graph;
705         }
706         return NULL;
707 }
708
709 static void close_commit_graph_one(struct commit_graph *g)
710 {
711         if (!g)
712                 return;
713
714         close_commit_graph_one(g->base_graph);
715         free_commit_graph(g);
716 }
717
718 void close_commit_graph(struct raw_object_store *o)
719 {
720         close_commit_graph_one(o->commit_graph);
721         o->commit_graph = NULL;
722 }
723
724 static int bsearch_graph(struct commit_graph *g, struct object_id *oid, uint32_t *pos)
725 {
726         return bsearch_hash(oid->hash, g->chunk_oid_fanout,
727                             g->chunk_oid_lookup, g->hash_len, pos);
728 }
729
730 static void load_oid_from_graph(struct commit_graph *g,
731                                 uint32_t pos,
732                                 struct object_id *oid)
733 {
734         uint32_t lex_index;
735
736         while (g && pos < g->num_commits_in_base)
737                 g = g->base_graph;
738
739         if (!g)
740                 BUG("NULL commit-graph");
741
742         if (pos >= g->num_commits + g->num_commits_in_base)
743                 die(_("invalid commit position. commit-graph is likely corrupt"));
744
745         lex_index = pos - g->num_commits_in_base;
746
747         hashcpy(oid->hash, g->chunk_oid_lookup + g->hash_len * lex_index);
748 }
749
750 static struct commit_list **insert_parent_or_die(struct repository *r,
751                                                  struct commit_graph *g,
752                                                  uint32_t pos,
753                                                  struct commit_list **pptr)
754 {
755         struct commit *c;
756         struct object_id oid;
757
758         if (pos >= g->num_commits + g->num_commits_in_base)
759                 die("invalid parent position %"PRIu32, pos);
760
761         load_oid_from_graph(g, pos, &oid);
762         c = lookup_commit(r, &oid);
763         if (!c)
764                 die(_("could not find commit %s"), oid_to_hex(&oid));
765         commit_graph_data_at(c)->graph_pos = pos;
766         return &commit_list_insert(c, pptr)->next;
767 }
768
769 static void fill_commit_graph_info(struct commit *item, struct commit_graph *g, uint32_t pos)
770 {
771         const unsigned char *commit_data;
772         struct commit_graph_data *graph_data;
773         uint32_t lex_index, offset_pos;
774         uint64_t date_high, date_low, offset;
775
776         while (pos < g->num_commits_in_base)
777                 g = g->base_graph;
778
779         if (pos >= g->num_commits + g->num_commits_in_base)
780                 die(_("invalid commit position. commit-graph is likely corrupt"));
781
782         lex_index = pos - g->num_commits_in_base;
783         commit_data = g->chunk_commit_data + GRAPH_DATA_WIDTH * lex_index;
784
785         graph_data = commit_graph_data_at(item);
786         graph_data->graph_pos = pos;
787
788         date_high = get_be32(commit_data + g->hash_len + 8) & 0x3;
789         date_low = get_be32(commit_data + g->hash_len + 12);
790         item->date = (timestamp_t)((date_high << 32) | date_low);
791
792         if (g->read_generation_data) {
793                 offset = (timestamp_t)get_be32(g->chunk_generation_data + sizeof(uint32_t) * lex_index);
794
795                 if (offset & CORRECTED_COMMIT_DATE_OFFSET_OVERFLOW) {
796                         if (!g->chunk_generation_data_overflow)
797                                 die(_("commit-graph requires overflow generation data but has none"));
798
799                         offset_pos = offset ^ CORRECTED_COMMIT_DATE_OFFSET_OVERFLOW;
800                         graph_data->generation = get_be64(g->chunk_generation_data_overflow + 8 * offset_pos);
801                 } else
802                         graph_data->generation = item->date + offset;
803         } else
804                 graph_data->generation = get_be32(commit_data + g->hash_len + 8) >> 2;
805
806         if (g->topo_levels)
807                 *topo_level_slab_at(g->topo_levels, item) = get_be32(commit_data + g->hash_len + 8) >> 2;
808 }
809
810 static inline void set_commit_tree(struct commit *c, struct tree *t)
811 {
812         c->maybe_tree = t;
813 }
814
815 static int fill_commit_in_graph(struct repository *r,
816                                 struct commit *item,
817                                 struct commit_graph *g, uint32_t pos)
818 {
819         uint32_t edge_value;
820         uint32_t *parent_data_ptr;
821         struct commit_list **pptr;
822         const unsigned char *commit_data;
823         uint32_t lex_index;
824
825         while (pos < g->num_commits_in_base)
826                 g = g->base_graph;
827
828         fill_commit_graph_info(item, g, pos);
829
830         lex_index = pos - g->num_commits_in_base;
831         commit_data = g->chunk_commit_data + (g->hash_len + 16) * lex_index;
832
833         item->object.parsed = 1;
834
835         set_commit_tree(item, NULL);
836
837         pptr = &item->parents;
838
839         edge_value = get_be32(commit_data + g->hash_len);
840         if (edge_value == GRAPH_PARENT_NONE)
841                 return 1;
842         pptr = insert_parent_or_die(r, g, edge_value, pptr);
843
844         edge_value = get_be32(commit_data + g->hash_len + 4);
845         if (edge_value == GRAPH_PARENT_NONE)
846                 return 1;
847         if (!(edge_value & GRAPH_EXTRA_EDGES_NEEDED)) {
848                 pptr = insert_parent_or_die(r, g, edge_value, pptr);
849                 return 1;
850         }
851
852         parent_data_ptr = (uint32_t*)(g->chunk_extra_edges +
853                           4 * (uint64_t)(edge_value & GRAPH_EDGE_LAST_MASK));
854         do {
855                 edge_value = get_be32(parent_data_ptr);
856                 pptr = insert_parent_or_die(r, g,
857                                             edge_value & GRAPH_EDGE_LAST_MASK,
858                                             pptr);
859                 parent_data_ptr++;
860         } while (!(edge_value & GRAPH_LAST_EDGE));
861
862         return 1;
863 }
864
865 static int find_commit_in_graph(struct commit *item, struct commit_graph *g, uint32_t *pos)
866 {
867         uint32_t graph_pos = commit_graph_position(item);
868         if (graph_pos != COMMIT_NOT_FROM_GRAPH) {
869                 *pos = graph_pos;
870                 return 1;
871         } else {
872                 struct commit_graph *cur_g = g;
873                 uint32_t lex_index;
874
875                 while (cur_g && !bsearch_graph(cur_g, &(item->object.oid), &lex_index))
876                         cur_g = cur_g->base_graph;
877
878                 if (cur_g) {
879                         *pos = lex_index + cur_g->num_commits_in_base;
880                         return 1;
881                 }
882
883                 return 0;
884         }
885 }
886
887 static int parse_commit_in_graph_one(struct repository *r,
888                                      struct commit_graph *g,
889                                      struct commit *item)
890 {
891         uint32_t pos;
892
893         if (item->object.parsed)
894                 return 1;
895
896         if (find_commit_in_graph(item, g, &pos))
897                 return fill_commit_in_graph(r, item, g, pos);
898
899         return 0;
900 }
901
902 int parse_commit_in_graph(struct repository *r, struct commit *item)
903 {
904         static int checked_env = 0;
905
906         if (!checked_env &&
907             git_env_bool(GIT_TEST_COMMIT_GRAPH_DIE_ON_PARSE, 0))
908                 die("dying as requested by the '%s' variable on commit-graph parse!",
909                     GIT_TEST_COMMIT_GRAPH_DIE_ON_PARSE);
910         checked_env = 1;
911
912         if (!prepare_commit_graph(r))
913                 return 0;
914         return parse_commit_in_graph_one(r, r->objects->commit_graph, item);
915 }
916
917 void load_commit_graph_info(struct repository *r, struct commit *item)
918 {
919         uint32_t pos;
920         if (!prepare_commit_graph(r))
921                 return;
922         if (find_commit_in_graph(item, r->objects->commit_graph, &pos))
923                 fill_commit_graph_info(item, r->objects->commit_graph, pos);
924 }
925
926 static struct tree *load_tree_for_commit(struct repository *r,
927                                          struct commit_graph *g,
928                                          struct commit *c)
929 {
930         struct object_id oid;
931         const unsigned char *commit_data;
932         uint32_t graph_pos = commit_graph_position(c);
933
934         while (graph_pos < g->num_commits_in_base)
935                 g = g->base_graph;
936
937         commit_data = g->chunk_commit_data +
938                         GRAPH_DATA_WIDTH * (graph_pos - g->num_commits_in_base);
939
940         hashcpy(oid.hash, commit_data);
941         set_commit_tree(c, lookup_tree(r, &oid));
942
943         return c->maybe_tree;
944 }
945
946 static struct tree *get_commit_tree_in_graph_one(struct repository *r,
947                                                  struct commit_graph *g,
948                                                  const struct commit *c)
949 {
950         if (c->maybe_tree)
951                 return c->maybe_tree;
952         if (commit_graph_position(c) == COMMIT_NOT_FROM_GRAPH)
953                 BUG("get_commit_tree_in_graph_one called from non-commit-graph commit");
954
955         return load_tree_for_commit(r, g, (struct commit *)c);
956 }
957
958 struct tree *get_commit_tree_in_graph(struct repository *r, const struct commit *c)
959 {
960         return get_commit_tree_in_graph_one(r, r->objects->commit_graph, c);
961 }
962
963 struct packed_commit_list {
964         struct commit **list;
965         size_t nr;
966         size_t alloc;
967 };
968
969 struct write_commit_graph_context {
970         struct repository *r;
971         struct object_directory *odb;
972         char *graph_name;
973         struct oid_array oids;
974         struct packed_commit_list commits;
975         int num_extra_edges;
976         int num_generation_data_overflows;
977         unsigned long approx_nr_objects;
978         struct progress *progress;
979         int progress_done;
980         uint64_t progress_cnt;
981
982         char *base_graph_name;
983         int num_commit_graphs_before;
984         int num_commit_graphs_after;
985         char **commit_graph_filenames_before;
986         char **commit_graph_filenames_after;
987         char **commit_graph_hash_after;
988         uint32_t new_num_commits_in_base;
989         struct commit_graph *new_base_graph;
990
991         unsigned append:1,
992                  report_progress:1,
993                  split:1,
994                  changed_paths:1,
995                  order_by_pack:1,
996                  write_generation_data:1,
997                  trust_generation_numbers:1;
998
999         struct topo_level_slab *topo_levels;
1000         const struct commit_graph_opts *opts;
1001         size_t total_bloom_filter_data_size;
1002         const struct bloom_filter_settings *bloom_settings;
1003
1004         int count_bloom_filter_computed;
1005         int count_bloom_filter_not_computed;
1006         int count_bloom_filter_trunc_empty;
1007         int count_bloom_filter_trunc_large;
1008 };
1009
1010 static int write_graph_chunk_fanout(struct hashfile *f,
1011                                     void *data)
1012 {
1013         struct write_commit_graph_context *ctx = data;
1014         int i, count = 0;
1015         struct commit **list = ctx->commits.list;
1016
1017         /*
1018          * Write the first-level table (the list is sorted,
1019          * but we use a 256-entry lookup to be able to avoid
1020          * having to do eight extra binary search iterations).
1021          */
1022         for (i = 0; i < 256; i++) {
1023                 while (count < ctx->commits.nr) {
1024                         if ((*list)->object.oid.hash[0] != i)
1025                                 break;
1026                         display_progress(ctx->progress, ++ctx->progress_cnt);
1027                         count++;
1028                         list++;
1029                 }
1030
1031                 hashwrite_be32(f, count);
1032         }
1033
1034         return 0;
1035 }
1036
1037 static int write_graph_chunk_oids(struct hashfile *f,
1038                                   void *data)
1039 {
1040         struct write_commit_graph_context *ctx = data;
1041         struct commit **list = ctx->commits.list;
1042         int count;
1043         for (count = 0; count < ctx->commits.nr; count++, list++) {
1044                 display_progress(ctx->progress, ++ctx->progress_cnt);
1045                 hashwrite(f, (*list)->object.oid.hash, the_hash_algo->rawsz);
1046         }
1047
1048         return 0;
1049 }
1050
1051 static const struct object_id *commit_to_oid(size_t index, const void *table)
1052 {
1053         const struct commit * const *commits = table;
1054         return &commits[index]->object.oid;
1055 }
1056
1057 static int write_graph_chunk_data(struct hashfile *f,
1058                                   void *data)
1059 {
1060         struct write_commit_graph_context *ctx = data;
1061         struct commit **list = ctx->commits.list;
1062         struct commit **last = ctx->commits.list + ctx->commits.nr;
1063         uint32_t num_extra_edges = 0;
1064
1065         while (list < last) {
1066                 struct commit_list *parent;
1067                 struct object_id *tree;
1068                 int edge_value;
1069                 uint32_t packedDate[2];
1070                 display_progress(ctx->progress, ++ctx->progress_cnt);
1071
1072                 if (repo_parse_commit_no_graph(ctx->r, *list))
1073                         die(_("unable to parse commit %s"),
1074                                 oid_to_hex(&(*list)->object.oid));
1075                 tree = get_commit_tree_oid(*list);
1076                 hashwrite(f, tree->hash, the_hash_algo->rawsz);
1077
1078                 parent = (*list)->parents;
1079
1080                 if (!parent)
1081                         edge_value = GRAPH_PARENT_NONE;
1082                 else {
1083                         edge_value = oid_pos(&parent->item->object.oid,
1084                                              ctx->commits.list,
1085                                              ctx->commits.nr,
1086                                              commit_to_oid);
1087
1088                         if (edge_value >= 0)
1089                                 edge_value += ctx->new_num_commits_in_base;
1090                         else if (ctx->new_base_graph) {
1091                                 uint32_t pos;
1092                                 if (find_commit_in_graph(parent->item,
1093                                                          ctx->new_base_graph,
1094                                                          &pos))
1095                                         edge_value = pos;
1096                         }
1097
1098                         if (edge_value < 0)
1099                                 BUG("missing parent %s for commit %s",
1100                                     oid_to_hex(&parent->item->object.oid),
1101                                     oid_to_hex(&(*list)->object.oid));
1102                 }
1103
1104                 hashwrite_be32(f, edge_value);
1105
1106                 if (parent)
1107                         parent = parent->next;
1108
1109                 if (!parent)
1110                         edge_value = GRAPH_PARENT_NONE;
1111                 else if (parent->next)
1112                         edge_value = GRAPH_EXTRA_EDGES_NEEDED | num_extra_edges;
1113                 else {
1114                         edge_value = oid_pos(&parent->item->object.oid,
1115                                              ctx->commits.list,
1116                                              ctx->commits.nr,
1117                                              commit_to_oid);
1118
1119                         if (edge_value >= 0)
1120                                 edge_value += ctx->new_num_commits_in_base;
1121                         else if (ctx->new_base_graph) {
1122                                 uint32_t pos;
1123                                 if (find_commit_in_graph(parent->item,
1124                                                          ctx->new_base_graph,
1125                                                          &pos))
1126                                         edge_value = pos;
1127                         }
1128
1129                         if (edge_value < 0)
1130                                 BUG("missing parent %s for commit %s",
1131                                     oid_to_hex(&parent->item->object.oid),
1132                                     oid_to_hex(&(*list)->object.oid));
1133                 }
1134
1135                 hashwrite_be32(f, edge_value);
1136
1137                 if (edge_value & GRAPH_EXTRA_EDGES_NEEDED) {
1138                         do {
1139                                 num_extra_edges++;
1140                                 parent = parent->next;
1141                         } while (parent);
1142                 }
1143
1144                 if (sizeof((*list)->date) > 4)
1145                         packedDate[0] = htonl(((*list)->date >> 32) & 0x3);
1146                 else
1147                         packedDate[0] = 0;
1148
1149                 packedDate[0] |= htonl(*topo_level_slab_at(ctx->topo_levels, *list) << 2);
1150
1151                 packedDate[1] = htonl((*list)->date);
1152                 hashwrite(f, packedDate, 8);
1153
1154                 list++;
1155         }
1156
1157         return 0;
1158 }
1159
1160 static int write_graph_chunk_generation_data(struct hashfile *f,
1161                                              void *data)
1162 {
1163         struct write_commit_graph_context *ctx = data;
1164         int i, num_generation_data_overflows = 0;
1165
1166         for (i = 0; i < ctx->commits.nr; i++) {
1167                 struct commit *c = ctx->commits.list[i];
1168                 timestamp_t offset;
1169                 repo_parse_commit(ctx->r, c);
1170                 offset = commit_graph_data_at(c)->generation - c->date;
1171                 display_progress(ctx->progress, ++ctx->progress_cnt);
1172
1173                 if (offset > GENERATION_NUMBER_V2_OFFSET_MAX) {
1174                         offset = CORRECTED_COMMIT_DATE_OFFSET_OVERFLOW | num_generation_data_overflows;
1175                         num_generation_data_overflows++;
1176                 }
1177
1178                 hashwrite_be32(f, offset);
1179         }
1180
1181         return 0;
1182 }
1183
1184 static int write_graph_chunk_generation_data_overflow(struct hashfile *f,
1185                                                       void *data)
1186 {
1187         struct write_commit_graph_context *ctx = data;
1188         int i;
1189         for (i = 0; i < ctx->commits.nr; i++) {
1190                 struct commit *c = ctx->commits.list[i];
1191                 timestamp_t offset = commit_graph_data_at(c)->generation - c->date;
1192                 display_progress(ctx->progress, ++ctx->progress_cnt);
1193
1194                 if (offset > GENERATION_NUMBER_V2_OFFSET_MAX) {
1195                         hashwrite_be32(f, offset >> 32);
1196                         hashwrite_be32(f, (uint32_t) offset);
1197                 }
1198         }
1199
1200         return 0;
1201 }
1202
1203 static int write_graph_chunk_extra_edges(struct hashfile *f,
1204                                          void *data)
1205 {
1206         struct write_commit_graph_context *ctx = data;
1207         struct commit **list = ctx->commits.list;
1208         struct commit **last = ctx->commits.list + ctx->commits.nr;
1209         struct commit_list *parent;
1210
1211         while (list < last) {
1212                 int num_parents = 0;
1213
1214                 display_progress(ctx->progress, ++ctx->progress_cnt);
1215
1216                 for (parent = (*list)->parents; num_parents < 3 && parent;
1217                      parent = parent->next)
1218                         num_parents++;
1219
1220                 if (num_parents <= 2) {
1221                         list++;
1222                         continue;
1223                 }
1224
1225                 /* Since num_parents > 2, this initializer is safe. */
1226                 for (parent = (*list)->parents->next; parent; parent = parent->next) {
1227                         int edge_value = oid_pos(&parent->item->object.oid,
1228                                                  ctx->commits.list,
1229                                                  ctx->commits.nr,
1230                                                  commit_to_oid);
1231
1232                         if (edge_value >= 0)
1233                                 edge_value += ctx->new_num_commits_in_base;
1234                         else if (ctx->new_base_graph) {
1235                                 uint32_t pos;
1236                                 if (find_commit_in_graph(parent->item,
1237                                                          ctx->new_base_graph,
1238                                                          &pos))
1239                                         edge_value = pos;
1240                         }
1241
1242                         if (edge_value < 0)
1243                                 BUG("missing parent %s for commit %s",
1244                                     oid_to_hex(&parent->item->object.oid),
1245                                     oid_to_hex(&(*list)->object.oid));
1246                         else if (!parent->next)
1247                                 edge_value |= GRAPH_LAST_EDGE;
1248
1249                         hashwrite_be32(f, edge_value);
1250                 }
1251
1252                 list++;
1253         }
1254
1255         return 0;
1256 }
1257
1258 static int write_graph_chunk_bloom_indexes(struct hashfile *f,
1259                                            void *data)
1260 {
1261         struct write_commit_graph_context *ctx = data;
1262         struct commit **list = ctx->commits.list;
1263         struct commit **last = ctx->commits.list + ctx->commits.nr;
1264         uint32_t cur_pos = 0;
1265
1266         while (list < last) {
1267                 struct bloom_filter *filter = get_bloom_filter(ctx->r, *list);
1268                 size_t len = filter ? filter->len : 0;
1269                 cur_pos += len;
1270                 display_progress(ctx->progress, ++ctx->progress_cnt);
1271                 hashwrite_be32(f, cur_pos);
1272                 list++;
1273         }
1274
1275         return 0;
1276 }
1277
1278 static void trace2_bloom_filter_settings(struct write_commit_graph_context *ctx)
1279 {
1280         struct json_writer jw = JSON_WRITER_INIT;
1281
1282         jw_object_begin(&jw, 0);
1283         jw_object_intmax(&jw, "hash_version", ctx->bloom_settings->hash_version);
1284         jw_object_intmax(&jw, "num_hashes", ctx->bloom_settings->num_hashes);
1285         jw_object_intmax(&jw, "bits_per_entry", ctx->bloom_settings->bits_per_entry);
1286         jw_object_intmax(&jw, "max_changed_paths", ctx->bloom_settings->max_changed_paths);
1287         jw_end(&jw);
1288
1289         trace2_data_json("bloom", ctx->r, "settings", &jw);
1290
1291         jw_release(&jw);
1292 }
1293
1294 static int write_graph_chunk_bloom_data(struct hashfile *f,
1295                                         void *data)
1296 {
1297         struct write_commit_graph_context *ctx = data;
1298         struct commit **list = ctx->commits.list;
1299         struct commit **last = ctx->commits.list + ctx->commits.nr;
1300
1301         trace2_bloom_filter_settings(ctx);
1302
1303         hashwrite_be32(f, ctx->bloom_settings->hash_version);
1304         hashwrite_be32(f, ctx->bloom_settings->num_hashes);
1305         hashwrite_be32(f, ctx->bloom_settings->bits_per_entry);
1306
1307         while (list < last) {
1308                 struct bloom_filter *filter = get_bloom_filter(ctx->r, *list);
1309                 size_t len = filter ? filter->len : 0;
1310
1311                 display_progress(ctx->progress, ++ctx->progress_cnt);
1312                 if (len)
1313                         hashwrite(f, filter->data, len * sizeof(unsigned char));
1314                 list++;
1315         }
1316
1317         return 0;
1318 }
1319
1320 static int add_packed_commits(const struct object_id *oid,
1321                               struct packed_git *pack,
1322                               uint32_t pos,
1323                               void *data)
1324 {
1325         struct write_commit_graph_context *ctx = (struct write_commit_graph_context*)data;
1326         enum object_type type;
1327         off_t offset = nth_packed_object_offset(pack, pos);
1328         struct object_info oi = OBJECT_INFO_INIT;
1329
1330         if (ctx->progress)
1331                 display_progress(ctx->progress, ++ctx->progress_done);
1332
1333         oi.typep = &type;
1334         if (packed_object_info(ctx->r, pack, offset, &oi) < 0)
1335                 die(_("unable to get type of object %s"), oid_to_hex(oid));
1336
1337         if (type != OBJ_COMMIT)
1338                 return 0;
1339
1340         oid_array_append(&ctx->oids, oid);
1341         set_commit_pos(ctx->r, oid);
1342
1343         return 0;
1344 }
1345
1346 static void add_missing_parents(struct write_commit_graph_context *ctx, struct commit *commit)
1347 {
1348         struct commit_list *parent;
1349         for (parent = commit->parents; parent; parent = parent->next) {
1350                 if (!(parent->item->object.flags & REACHABLE)) {
1351                         oid_array_append(&ctx->oids, &parent->item->object.oid);
1352                         parent->item->object.flags |= REACHABLE;
1353                 }
1354         }
1355 }
1356
1357 static void close_reachable(struct write_commit_graph_context *ctx)
1358 {
1359         int i;
1360         struct commit *commit;
1361         enum commit_graph_split_flags flags = ctx->opts ?
1362                 ctx->opts->split_flags : COMMIT_GRAPH_SPLIT_UNSPECIFIED;
1363
1364         if (ctx->report_progress)
1365                 ctx->progress = start_delayed_progress(
1366                                         _("Loading known commits in commit graph"),
1367                                         ctx->oids.nr);
1368         for (i = 0; i < ctx->oids.nr; i++) {
1369                 display_progress(ctx->progress, i + 1);
1370                 commit = lookup_commit(ctx->r, &ctx->oids.oid[i]);
1371                 if (commit)
1372                         commit->object.flags |= REACHABLE;
1373         }
1374         stop_progress(&ctx->progress);
1375
1376         /*
1377          * As this loop runs, ctx->oids.nr may grow, but not more
1378          * than the number of missing commits in the reachable
1379          * closure.
1380          */
1381         if (ctx->report_progress)
1382                 ctx->progress = start_delayed_progress(
1383                                         _("Expanding reachable commits in commit graph"),
1384                                         0);
1385         for (i = 0; i < ctx->oids.nr; i++) {
1386                 display_progress(ctx->progress, i + 1);
1387                 commit = lookup_commit(ctx->r, &ctx->oids.oid[i]);
1388
1389                 if (!commit)
1390                         continue;
1391                 if (ctx->split) {
1392                         if ((!repo_parse_commit(ctx->r, commit) &&
1393                              commit_graph_position(commit) == COMMIT_NOT_FROM_GRAPH) ||
1394                             flags == COMMIT_GRAPH_SPLIT_REPLACE)
1395                                 add_missing_parents(ctx, commit);
1396                 } else if (!repo_parse_commit_no_graph(ctx->r, commit))
1397                         add_missing_parents(ctx, commit);
1398         }
1399         stop_progress(&ctx->progress);
1400
1401         if (ctx->report_progress)
1402                 ctx->progress = start_delayed_progress(
1403                                         _("Clearing commit marks in commit graph"),
1404                                         ctx->oids.nr);
1405         for (i = 0; i < ctx->oids.nr; i++) {
1406                 display_progress(ctx->progress, i + 1);
1407                 commit = lookup_commit(ctx->r, &ctx->oids.oid[i]);
1408
1409                 if (commit)
1410                         commit->object.flags &= ~REACHABLE;
1411         }
1412         stop_progress(&ctx->progress);
1413 }
1414
1415 static void compute_topological_levels(struct write_commit_graph_context *ctx)
1416 {
1417         int i;
1418         struct commit_list *list = NULL;
1419
1420         if (ctx->report_progress)
1421                 ctx->progress = start_delayed_progress(
1422                                         _("Computing commit graph topological levels"),
1423                                         ctx->commits.nr);
1424         for (i = 0; i < ctx->commits.nr; i++) {
1425                 struct commit *c = ctx->commits.list[i];
1426                 uint32_t level;
1427
1428                 repo_parse_commit(ctx->r, c);
1429                 level = *topo_level_slab_at(ctx->topo_levels, c);
1430
1431                 display_progress(ctx->progress, i + 1);
1432                 if (level != GENERATION_NUMBER_ZERO)
1433                         continue;
1434
1435                 commit_list_insert(c, &list);
1436                 while (list) {
1437                         struct commit *current = list->item;
1438                         struct commit_list *parent;
1439                         int all_parents_computed = 1;
1440                         uint32_t max_level = 0;
1441
1442                         for (parent = current->parents; parent; parent = parent->next) {
1443                                 repo_parse_commit(ctx->r, parent->item);
1444                                 level = *topo_level_slab_at(ctx->topo_levels, parent->item);
1445
1446                                 if (level == GENERATION_NUMBER_ZERO) {
1447                                         all_parents_computed = 0;
1448                                         commit_list_insert(parent->item, &list);
1449                                         break;
1450                                 }
1451
1452                                 if (level > max_level)
1453                                         max_level = level;
1454                         }
1455
1456                         if (all_parents_computed) {
1457                                 pop_commit(&list);
1458
1459                                 if (max_level > GENERATION_NUMBER_V1_MAX - 1)
1460                                         max_level = GENERATION_NUMBER_V1_MAX - 1;
1461                                 *topo_level_slab_at(ctx->topo_levels, current) = max_level + 1;
1462                         }
1463                 }
1464         }
1465         stop_progress(&ctx->progress);
1466 }
1467
1468 static void compute_generation_numbers(struct write_commit_graph_context *ctx)
1469 {
1470         int i;
1471         struct commit_list *list = NULL;
1472
1473         if (ctx->report_progress)
1474                 ctx->progress = start_delayed_progress(
1475                                         _("Computing commit graph generation numbers"),
1476                                         ctx->commits.nr);
1477
1478         if (!ctx->trust_generation_numbers) {
1479                 for (i = 0; i < ctx->commits.nr; i++) {
1480                         struct commit *c = ctx->commits.list[i];
1481                         repo_parse_commit(ctx->r, c);
1482                         commit_graph_data_at(c)->generation = GENERATION_NUMBER_ZERO;
1483                 }
1484         }
1485
1486         for (i = 0; i < ctx->commits.nr; i++) {
1487                 struct commit *c = ctx->commits.list[i];
1488                 timestamp_t corrected_commit_date;
1489
1490                 repo_parse_commit(ctx->r, c);
1491                 corrected_commit_date = commit_graph_data_at(c)->generation;
1492
1493                 display_progress(ctx->progress, i + 1);
1494                 if (corrected_commit_date != GENERATION_NUMBER_ZERO)
1495                         continue;
1496
1497                 commit_list_insert(c, &list);
1498                 while (list) {
1499                         struct commit *current = list->item;
1500                         struct commit_list *parent;
1501                         int all_parents_computed = 1;
1502                         timestamp_t max_corrected_commit_date = 0;
1503
1504                         for (parent = current->parents; parent; parent = parent->next) {
1505                                 repo_parse_commit(ctx->r, parent->item);
1506                                 corrected_commit_date = commit_graph_data_at(parent->item)->generation;
1507
1508                                 if (corrected_commit_date == GENERATION_NUMBER_ZERO) {
1509                                         all_parents_computed = 0;
1510                                         commit_list_insert(parent->item, &list);
1511                                         break;
1512                                 }
1513
1514                                 if (corrected_commit_date > max_corrected_commit_date)
1515                                         max_corrected_commit_date = corrected_commit_date;
1516                         }
1517
1518                         if (all_parents_computed) {
1519                                 pop_commit(&list);
1520
1521                                 if (current->date && current->date > max_corrected_commit_date)
1522                                         max_corrected_commit_date = current->date - 1;
1523                                 commit_graph_data_at(current)->generation = max_corrected_commit_date + 1;
1524
1525                                 if (commit_graph_data_at(current)->generation - current->date > GENERATION_NUMBER_V2_OFFSET_MAX)
1526                                         ctx->num_generation_data_overflows++;
1527                         }
1528                 }
1529         }
1530         stop_progress(&ctx->progress);
1531 }
1532
1533 static void trace2_bloom_filter_write_statistics(struct write_commit_graph_context *ctx)
1534 {
1535         trace2_data_intmax("commit-graph", ctx->r, "filter-computed",
1536                            ctx->count_bloom_filter_computed);
1537         trace2_data_intmax("commit-graph", ctx->r, "filter-not-computed",
1538                            ctx->count_bloom_filter_not_computed);
1539         trace2_data_intmax("commit-graph", ctx->r, "filter-trunc-empty",
1540                            ctx->count_bloom_filter_trunc_empty);
1541         trace2_data_intmax("commit-graph", ctx->r, "filter-trunc-large",
1542                            ctx->count_bloom_filter_trunc_large);
1543 }
1544
1545 static void compute_bloom_filters(struct write_commit_graph_context *ctx)
1546 {
1547         int i;
1548         struct progress *progress = NULL;
1549         struct commit **sorted_commits;
1550         int max_new_filters;
1551
1552         init_bloom_filters();
1553
1554         if (ctx->report_progress)
1555                 progress = start_delayed_progress(
1556                         _("Computing commit changed paths Bloom filters"),
1557                         ctx->commits.nr);
1558
1559         ALLOC_ARRAY(sorted_commits, ctx->commits.nr);
1560         COPY_ARRAY(sorted_commits, ctx->commits.list, ctx->commits.nr);
1561
1562         if (ctx->order_by_pack)
1563                 QSORT(sorted_commits, ctx->commits.nr, commit_pos_cmp);
1564         else
1565                 QSORT(sorted_commits, ctx->commits.nr, commit_gen_cmp);
1566
1567         max_new_filters = ctx->opts && ctx->opts->max_new_filters >= 0 ?
1568                 ctx->opts->max_new_filters : ctx->commits.nr;
1569
1570         for (i = 0; i < ctx->commits.nr; i++) {
1571                 enum bloom_filter_computed computed = 0;
1572                 struct commit *c = sorted_commits[i];
1573                 struct bloom_filter *filter = get_or_compute_bloom_filter(
1574                         ctx->r,
1575                         c,
1576                         ctx->count_bloom_filter_computed < max_new_filters,
1577                         ctx->bloom_settings,
1578                         &computed);
1579                 if (computed & BLOOM_COMPUTED) {
1580                         ctx->count_bloom_filter_computed++;
1581                         if (computed & BLOOM_TRUNC_EMPTY)
1582                                 ctx->count_bloom_filter_trunc_empty++;
1583                         if (computed & BLOOM_TRUNC_LARGE)
1584                                 ctx->count_bloom_filter_trunc_large++;
1585                 } else if (computed & BLOOM_NOT_COMPUTED)
1586                         ctx->count_bloom_filter_not_computed++;
1587                 ctx->total_bloom_filter_data_size += filter
1588                         ? sizeof(unsigned char) * filter->len : 0;
1589                 display_progress(progress, i + 1);
1590         }
1591
1592         if (trace2_is_enabled())
1593                 trace2_bloom_filter_write_statistics(ctx);
1594
1595         free(sorted_commits);
1596         stop_progress(&progress);
1597 }
1598
1599 struct refs_cb_data {
1600         struct oidset *commits;
1601         struct progress *progress;
1602 };
1603
1604 static int add_ref_to_set(const char *refname,
1605                           const struct object_id *oid,
1606                           int flags, void *cb_data)
1607 {
1608         struct object_id peeled;
1609         struct refs_cb_data *data = (struct refs_cb_data *)cb_data;
1610
1611         if (!peel_iterated_oid(oid, &peeled))
1612                 oid = &peeled;
1613         if (oid_object_info(the_repository, oid, NULL) == OBJ_COMMIT)
1614                 oidset_insert(data->commits, oid);
1615
1616         display_progress(data->progress, oidset_size(data->commits));
1617
1618         return 0;
1619 }
1620
1621 int write_commit_graph_reachable(struct object_directory *odb,
1622                                  enum commit_graph_write_flags flags,
1623                                  const struct commit_graph_opts *opts)
1624 {
1625         struct oidset commits = OIDSET_INIT;
1626         struct refs_cb_data data;
1627         int result;
1628
1629         memset(&data, 0, sizeof(data));
1630         data.commits = &commits;
1631         if (flags & COMMIT_GRAPH_WRITE_PROGRESS)
1632                 data.progress = start_delayed_progress(
1633                         _("Collecting referenced commits"), 0);
1634
1635         for_each_ref(add_ref_to_set, &data);
1636
1637         stop_progress(&data.progress);
1638
1639         result = write_commit_graph(odb, NULL, &commits,
1640                                     flags, opts);
1641
1642         oidset_clear(&commits);
1643         return result;
1644 }
1645
1646 static int fill_oids_from_packs(struct write_commit_graph_context *ctx,
1647                                 struct string_list *pack_indexes)
1648 {
1649         uint32_t i;
1650         struct strbuf progress_title = STRBUF_INIT;
1651         struct strbuf packname = STRBUF_INIT;
1652         int dirlen;
1653
1654         strbuf_addf(&packname, "%s/pack/", ctx->odb->path);
1655         dirlen = packname.len;
1656         if (ctx->report_progress) {
1657                 strbuf_addf(&progress_title,
1658                             Q_("Finding commits for commit graph in %d pack",
1659                                "Finding commits for commit graph in %d packs",
1660                                pack_indexes->nr),
1661                             pack_indexes->nr);
1662                 ctx->progress = start_delayed_progress(progress_title.buf, 0);
1663                 ctx->progress_done = 0;
1664         }
1665         for (i = 0; i < pack_indexes->nr; i++) {
1666                 struct packed_git *p;
1667                 strbuf_setlen(&packname, dirlen);
1668                 strbuf_addstr(&packname, pack_indexes->items[i].string);
1669                 p = add_packed_git(packname.buf, packname.len, 1);
1670                 if (!p) {
1671                         error(_("error adding pack %s"), packname.buf);
1672                         return -1;
1673                 }
1674                 if (open_pack_index(p)) {
1675                         error(_("error opening index for %s"), packname.buf);
1676                         return -1;
1677                 }
1678                 for_each_object_in_pack(p, add_packed_commits, ctx,
1679                                         FOR_EACH_OBJECT_PACK_ORDER);
1680                 close_pack(p);
1681                 free(p);
1682         }
1683
1684         stop_progress(&ctx->progress);
1685         strbuf_release(&progress_title);
1686         strbuf_release(&packname);
1687
1688         return 0;
1689 }
1690
1691 static int fill_oids_from_commits(struct write_commit_graph_context *ctx,
1692                                   struct oidset *commits)
1693 {
1694         struct oidset_iter iter;
1695         struct object_id *oid;
1696
1697         if (!oidset_size(commits))
1698                 return 0;
1699
1700         oidset_iter_init(commits, &iter);
1701         while ((oid = oidset_iter_next(&iter))) {
1702                 oid_array_append(&ctx->oids, oid);
1703         }
1704
1705         return 0;
1706 }
1707
1708 static void fill_oids_from_all_packs(struct write_commit_graph_context *ctx)
1709 {
1710         if (ctx->report_progress)
1711                 ctx->progress = start_delayed_progress(
1712                         _("Finding commits for commit graph among packed objects"),
1713                         ctx->approx_nr_objects);
1714         for_each_packed_object(add_packed_commits, ctx,
1715                                FOR_EACH_OBJECT_PACK_ORDER);
1716         if (ctx->progress_done < ctx->approx_nr_objects)
1717                 display_progress(ctx->progress, ctx->approx_nr_objects);
1718         stop_progress(&ctx->progress);
1719 }
1720
1721 static void copy_oids_to_commits(struct write_commit_graph_context *ctx)
1722 {
1723         uint32_t i;
1724         enum commit_graph_split_flags flags = ctx->opts ?
1725                 ctx->opts->split_flags : COMMIT_GRAPH_SPLIT_UNSPECIFIED;
1726
1727         ctx->num_extra_edges = 0;
1728         if (ctx->report_progress)
1729                 ctx->progress = start_delayed_progress(
1730                         _("Finding extra edges in commit graph"),
1731                         ctx->oids.nr);
1732         oid_array_sort(&ctx->oids);
1733         for (i = 0; i < ctx->oids.nr; i = oid_array_next_unique(&ctx->oids, i)) {
1734                 unsigned int num_parents;
1735
1736                 display_progress(ctx->progress, i + 1);
1737
1738                 ALLOC_GROW(ctx->commits.list, ctx->commits.nr + 1, ctx->commits.alloc);
1739                 ctx->commits.list[ctx->commits.nr] = lookup_commit(ctx->r, &ctx->oids.oid[i]);
1740
1741                 if (ctx->split && flags != COMMIT_GRAPH_SPLIT_REPLACE &&
1742                     commit_graph_position(ctx->commits.list[ctx->commits.nr]) != COMMIT_NOT_FROM_GRAPH)
1743                         continue;
1744
1745                 if (ctx->split && flags == COMMIT_GRAPH_SPLIT_REPLACE)
1746                         repo_parse_commit(ctx->r, ctx->commits.list[ctx->commits.nr]);
1747                 else
1748                         repo_parse_commit_no_graph(ctx->r, ctx->commits.list[ctx->commits.nr]);
1749
1750                 num_parents = commit_list_count(ctx->commits.list[ctx->commits.nr]->parents);
1751                 if (num_parents > 2)
1752                         ctx->num_extra_edges += num_parents - 1;
1753
1754                 ctx->commits.nr++;
1755         }
1756         stop_progress(&ctx->progress);
1757 }
1758
1759 static int write_graph_chunk_base_1(struct hashfile *f,
1760                                     struct commit_graph *g)
1761 {
1762         int num = 0;
1763
1764         if (!g)
1765                 return 0;
1766
1767         num = write_graph_chunk_base_1(f, g->base_graph);
1768         hashwrite(f, g->oid.hash, the_hash_algo->rawsz);
1769         return num + 1;
1770 }
1771
1772 static int write_graph_chunk_base(struct hashfile *f,
1773                                     void *data)
1774 {
1775         struct write_commit_graph_context *ctx = data;
1776         int num = write_graph_chunk_base_1(f, ctx->new_base_graph);
1777
1778         if (num != ctx->num_commit_graphs_after - 1) {
1779                 error(_("failed to write correct number of base graph ids"));
1780                 return -1;
1781         }
1782
1783         return 0;
1784 }
1785
1786 static int write_commit_graph_file(struct write_commit_graph_context *ctx)
1787 {
1788         uint32_t i;
1789         int fd;
1790         struct hashfile *f;
1791         struct lock_file lk = LOCK_INIT;
1792         const unsigned hashsz = the_hash_algo->rawsz;
1793         struct strbuf progress_title = STRBUF_INIT;
1794         struct object_id file_hash;
1795         struct chunkfile *cf;
1796
1797         if (ctx->split) {
1798                 struct strbuf tmp_file = STRBUF_INIT;
1799
1800                 strbuf_addf(&tmp_file,
1801                             "%s/info/commit-graphs/tmp_graph_XXXXXX",
1802                             ctx->odb->path);
1803                 ctx->graph_name = strbuf_detach(&tmp_file, NULL);
1804         } else {
1805                 ctx->graph_name = get_commit_graph_filename(ctx->odb);
1806         }
1807
1808         if (safe_create_leading_directories(ctx->graph_name)) {
1809                 UNLEAK(ctx->graph_name);
1810                 error(_("unable to create leading directories of %s"),
1811                         ctx->graph_name);
1812                 return -1;
1813         }
1814
1815         if (ctx->split) {
1816                 char *lock_name = get_commit_graph_chain_filename(ctx->odb);
1817
1818                 hold_lock_file_for_update_mode(&lk, lock_name,
1819                                                LOCK_DIE_ON_ERROR, 0444);
1820
1821                 fd = git_mkstemp_mode(ctx->graph_name, 0444);
1822                 if (fd < 0) {
1823                         error(_("unable to create temporary graph layer"));
1824                         return -1;
1825                 }
1826
1827                 if (adjust_shared_perm(ctx->graph_name)) {
1828                         error(_("unable to adjust shared permissions for '%s'"),
1829                               ctx->graph_name);
1830                         return -1;
1831                 }
1832
1833                 f = hashfd(fd, ctx->graph_name);
1834         } else {
1835                 hold_lock_file_for_update_mode(&lk, ctx->graph_name,
1836                                                LOCK_DIE_ON_ERROR, 0444);
1837                 fd = get_lock_file_fd(&lk);
1838                 f = hashfd(fd, get_lock_file_path(&lk));
1839         }
1840
1841         cf = init_chunkfile(f);
1842
1843         add_chunk(cf, GRAPH_CHUNKID_OIDFANOUT, GRAPH_FANOUT_SIZE,
1844                   write_graph_chunk_fanout);
1845         add_chunk(cf, GRAPH_CHUNKID_OIDLOOKUP, hashsz * ctx->commits.nr,
1846                   write_graph_chunk_oids);
1847         add_chunk(cf, GRAPH_CHUNKID_DATA, (hashsz + 16) * ctx->commits.nr,
1848                   write_graph_chunk_data);
1849
1850         if (git_env_bool(GIT_TEST_COMMIT_GRAPH_NO_GDAT, 0))
1851                 ctx->write_generation_data = 0;
1852         if (ctx->write_generation_data)
1853                 add_chunk(cf, GRAPH_CHUNKID_GENERATION_DATA,
1854                           sizeof(uint32_t) * ctx->commits.nr,
1855                           write_graph_chunk_generation_data);
1856         if (ctx->num_generation_data_overflows)
1857                 add_chunk(cf, GRAPH_CHUNKID_GENERATION_DATA_OVERFLOW,
1858                           sizeof(timestamp_t) * ctx->num_generation_data_overflows,
1859                           write_graph_chunk_generation_data_overflow);
1860         if (ctx->num_extra_edges)
1861                 add_chunk(cf, GRAPH_CHUNKID_EXTRAEDGES,
1862                           4 * ctx->num_extra_edges,
1863                           write_graph_chunk_extra_edges);
1864         if (ctx->changed_paths) {
1865                 add_chunk(cf, GRAPH_CHUNKID_BLOOMINDEXES,
1866                           sizeof(uint32_t) * ctx->commits.nr,
1867                           write_graph_chunk_bloom_indexes);
1868                 add_chunk(cf, GRAPH_CHUNKID_BLOOMDATA,
1869                           sizeof(uint32_t) * 3
1870                                 + ctx->total_bloom_filter_data_size,
1871                           write_graph_chunk_bloom_data);
1872         }
1873         if (ctx->num_commit_graphs_after > 1)
1874                 add_chunk(cf, GRAPH_CHUNKID_BASE,
1875                           hashsz * (ctx->num_commit_graphs_after - 1),
1876                           write_graph_chunk_base);
1877
1878         hashwrite_be32(f, GRAPH_SIGNATURE);
1879
1880         hashwrite_u8(f, GRAPH_VERSION);
1881         hashwrite_u8(f, oid_version());
1882         hashwrite_u8(f, get_num_chunks(cf));
1883         hashwrite_u8(f, ctx->num_commit_graphs_after - 1);
1884
1885         if (ctx->report_progress) {
1886                 strbuf_addf(&progress_title,
1887                             Q_("Writing out commit graph in %d pass",
1888                                "Writing out commit graph in %d passes",
1889                                get_num_chunks(cf)),
1890                             get_num_chunks(cf));
1891                 ctx->progress = start_delayed_progress(
1892                         progress_title.buf,
1893                         get_num_chunks(cf) * ctx->commits.nr);
1894         }
1895
1896         write_chunkfile(cf, ctx);
1897
1898         stop_progress(&ctx->progress);
1899         strbuf_release(&progress_title);
1900
1901         if (ctx->split && ctx->base_graph_name && ctx->num_commit_graphs_after > 1) {
1902                 char *new_base_hash = xstrdup(oid_to_hex(&ctx->new_base_graph->oid));
1903                 char *new_base_name = get_split_graph_filename(ctx->new_base_graph->odb, new_base_hash);
1904
1905                 free(ctx->commit_graph_filenames_after[ctx->num_commit_graphs_after - 2]);
1906                 free(ctx->commit_graph_hash_after[ctx->num_commit_graphs_after - 2]);
1907                 ctx->commit_graph_filenames_after[ctx->num_commit_graphs_after - 2] = new_base_name;
1908                 ctx->commit_graph_hash_after[ctx->num_commit_graphs_after - 2] = new_base_hash;
1909         }
1910
1911         close_commit_graph(ctx->r->objects);
1912         finalize_hashfile(f, file_hash.hash, CSUM_HASH_IN_STREAM | CSUM_FSYNC);
1913         free_chunkfile(cf);
1914
1915         if (ctx->split) {
1916                 FILE *chainf = fdopen_lock_file(&lk, "w");
1917                 char *final_graph_name;
1918                 int result;
1919
1920                 close(fd);
1921
1922                 if (!chainf) {
1923                         error(_("unable to open commit-graph chain file"));
1924                         return -1;
1925                 }
1926
1927                 if (ctx->base_graph_name) {
1928                         const char *dest;
1929                         int idx = ctx->num_commit_graphs_after - 1;
1930                         if (ctx->num_commit_graphs_after > 1)
1931                                 idx--;
1932
1933                         dest = ctx->commit_graph_filenames_after[idx];
1934
1935                         if (strcmp(ctx->base_graph_name, dest)) {
1936                                 result = rename(ctx->base_graph_name, dest);
1937
1938                                 if (result) {
1939                                         error(_("failed to rename base commit-graph file"));
1940                                         return -1;
1941                                 }
1942                         }
1943                 } else {
1944                         char *graph_name = get_commit_graph_filename(ctx->odb);
1945                         unlink(graph_name);
1946                 }
1947
1948                 ctx->commit_graph_hash_after[ctx->num_commit_graphs_after - 1] = xstrdup(oid_to_hex(&file_hash));
1949                 final_graph_name = get_split_graph_filename(ctx->odb,
1950                                         ctx->commit_graph_hash_after[ctx->num_commit_graphs_after - 1]);
1951                 ctx->commit_graph_filenames_after[ctx->num_commit_graphs_after - 1] = final_graph_name;
1952
1953                 result = rename(ctx->graph_name, final_graph_name);
1954
1955                 for (i = 0; i < ctx->num_commit_graphs_after; i++)
1956                         fprintf(get_lock_file_fp(&lk), "%s\n", ctx->commit_graph_hash_after[i]);
1957
1958                 if (result) {
1959                         error(_("failed to rename temporary commit-graph file"));
1960                         return -1;
1961                 }
1962         }
1963
1964         commit_lock_file(&lk);
1965
1966         return 0;
1967 }
1968
1969 static void split_graph_merge_strategy(struct write_commit_graph_context *ctx)
1970 {
1971         struct commit_graph *g;
1972         uint32_t num_commits;
1973         enum commit_graph_split_flags flags = COMMIT_GRAPH_SPLIT_UNSPECIFIED;
1974         uint32_t i;
1975
1976         int max_commits = 0;
1977         int size_mult = 2;
1978
1979         if (ctx->opts) {
1980                 max_commits = ctx->opts->max_commits;
1981
1982                 if (ctx->opts->size_multiple)
1983                         size_mult = ctx->opts->size_multiple;
1984
1985                 flags = ctx->opts->split_flags;
1986         }
1987
1988         g = ctx->r->objects->commit_graph;
1989         num_commits = ctx->commits.nr;
1990         if (flags == COMMIT_GRAPH_SPLIT_REPLACE)
1991                 ctx->num_commit_graphs_after = 1;
1992         else
1993                 ctx->num_commit_graphs_after = ctx->num_commit_graphs_before + 1;
1994
1995         if (flags != COMMIT_GRAPH_SPLIT_MERGE_PROHIBITED &&
1996             flags != COMMIT_GRAPH_SPLIT_REPLACE) {
1997                 while (g && (g->num_commits <= size_mult * num_commits ||
1998                             (max_commits && num_commits > max_commits))) {
1999                         if (g->odb != ctx->odb)
2000                                 break;
2001
2002                         num_commits += g->num_commits;
2003                         g = g->base_graph;
2004
2005                         ctx->num_commit_graphs_after--;
2006                 }
2007         }
2008
2009         if (flags != COMMIT_GRAPH_SPLIT_REPLACE)
2010                 ctx->new_base_graph = g;
2011         else if (ctx->num_commit_graphs_after != 1)
2012                 BUG("split_graph_merge_strategy: num_commit_graphs_after "
2013                     "should be 1 with --split=replace");
2014
2015         if (ctx->num_commit_graphs_after == 2) {
2016                 char *old_graph_name = get_commit_graph_filename(g->odb);
2017
2018                 if (!strcmp(g->filename, old_graph_name) &&
2019                     g->odb != ctx->odb) {
2020                         ctx->num_commit_graphs_after = 1;
2021                         ctx->new_base_graph = NULL;
2022                 }
2023
2024                 free(old_graph_name);
2025         }
2026
2027         CALLOC_ARRAY(ctx->commit_graph_filenames_after, ctx->num_commit_graphs_after);
2028         CALLOC_ARRAY(ctx->commit_graph_hash_after, ctx->num_commit_graphs_after);
2029
2030         for (i = 0; i < ctx->num_commit_graphs_after &&
2031                     i < ctx->num_commit_graphs_before; i++)
2032                 ctx->commit_graph_filenames_after[i] = xstrdup(ctx->commit_graph_filenames_before[i]);
2033
2034         i = ctx->num_commit_graphs_before - 1;
2035         g = ctx->r->objects->commit_graph;
2036
2037         while (g) {
2038                 if (i < ctx->num_commit_graphs_after)
2039                         ctx->commit_graph_hash_after[i] = xstrdup(oid_to_hex(&g->oid));
2040
2041                 /*
2042                  * If the topmost remaining layer has generation data chunk, the
2043                  * resultant layer also has generation data chunk.
2044                  */
2045                 if (i == ctx->num_commit_graphs_after - 2)
2046                         ctx->write_generation_data = !!g->chunk_generation_data;
2047
2048                 i--;
2049                 g = g->base_graph;
2050         }
2051 }
2052
2053 static void merge_commit_graph(struct write_commit_graph_context *ctx,
2054                                struct commit_graph *g)
2055 {
2056         uint32_t i;
2057         uint32_t offset = g->num_commits_in_base;
2058
2059         ALLOC_GROW(ctx->commits.list, ctx->commits.nr + g->num_commits, ctx->commits.alloc);
2060
2061         for (i = 0; i < g->num_commits; i++) {
2062                 struct object_id oid;
2063                 struct commit *result;
2064
2065                 display_progress(ctx->progress, i + 1);
2066
2067                 load_oid_from_graph(g, i + offset, &oid);
2068
2069                 /* only add commits if they still exist in the repo */
2070                 result = lookup_commit_reference_gently(ctx->r, &oid, 1);
2071
2072                 if (result) {
2073                         ctx->commits.list[ctx->commits.nr] = result;
2074                         ctx->commits.nr++;
2075                 }
2076         }
2077 }
2078
2079 static int commit_compare(const void *_a, const void *_b)
2080 {
2081         const struct commit *a = *(const struct commit **)_a;
2082         const struct commit *b = *(const struct commit **)_b;
2083         return oidcmp(&a->object.oid, &b->object.oid);
2084 }
2085
2086 static void sort_and_scan_merged_commits(struct write_commit_graph_context *ctx)
2087 {
2088         uint32_t i, dedup_i = 0;
2089
2090         if (ctx->report_progress)
2091                 ctx->progress = start_delayed_progress(
2092                                         _("Scanning merged commits"),
2093                                         ctx->commits.nr);
2094
2095         QSORT(ctx->commits.list, ctx->commits.nr, commit_compare);
2096
2097         ctx->num_extra_edges = 0;
2098         for (i = 0; i < ctx->commits.nr; i++) {
2099                 display_progress(ctx->progress, i);
2100
2101                 if (i && oideq(&ctx->commits.list[i - 1]->object.oid,
2102                           &ctx->commits.list[i]->object.oid)) {
2103                         /*
2104                          * Silently ignore duplicates. These were likely
2105                          * created due to a commit appearing in multiple
2106                          * layers of the chain, which is unexpected but
2107                          * not invalid. We should make sure there is a
2108                          * unique copy in the new layer.
2109                          */
2110                 } else {
2111                         unsigned int num_parents;
2112
2113                         ctx->commits.list[dedup_i] = ctx->commits.list[i];
2114                         dedup_i++;
2115
2116                         num_parents = commit_list_count(ctx->commits.list[i]->parents);
2117                         if (num_parents > 2)
2118                                 ctx->num_extra_edges += num_parents - 1;
2119                 }
2120         }
2121
2122         ctx->commits.nr = dedup_i;
2123
2124         stop_progress(&ctx->progress);
2125 }
2126
2127 static void merge_commit_graphs(struct write_commit_graph_context *ctx)
2128 {
2129         struct commit_graph *g = ctx->r->objects->commit_graph;
2130         uint32_t current_graph_number = ctx->num_commit_graphs_before;
2131
2132         while (g && current_graph_number >= ctx->num_commit_graphs_after) {
2133                 current_graph_number--;
2134
2135                 if (ctx->report_progress)
2136                         ctx->progress = start_delayed_progress(_("Merging commit-graph"), 0);
2137
2138                 merge_commit_graph(ctx, g);
2139                 stop_progress(&ctx->progress);
2140
2141                 g = g->base_graph;
2142         }
2143
2144         if (g) {
2145                 ctx->new_base_graph = g;
2146                 ctx->new_num_commits_in_base = g->num_commits + g->num_commits_in_base;
2147         }
2148
2149         if (ctx->new_base_graph)
2150                 ctx->base_graph_name = xstrdup(ctx->new_base_graph->filename);
2151
2152         sort_and_scan_merged_commits(ctx);
2153 }
2154
2155 static void mark_commit_graphs(struct write_commit_graph_context *ctx)
2156 {
2157         uint32_t i;
2158         time_t now = time(NULL);
2159
2160         for (i = ctx->num_commit_graphs_after - 1; i < ctx->num_commit_graphs_before; i++) {
2161                 struct stat st;
2162                 struct utimbuf updated_time;
2163
2164                 stat(ctx->commit_graph_filenames_before[i], &st);
2165
2166                 updated_time.actime = st.st_atime;
2167                 updated_time.modtime = now;
2168                 utime(ctx->commit_graph_filenames_before[i], &updated_time);
2169         }
2170 }
2171
2172 static void expire_commit_graphs(struct write_commit_graph_context *ctx)
2173 {
2174         struct strbuf path = STRBUF_INIT;
2175         DIR *dir;
2176         struct dirent *de;
2177         size_t dirnamelen;
2178         timestamp_t expire_time = time(NULL);
2179
2180         if (ctx->opts && ctx->opts->expire_time)
2181                 expire_time = ctx->opts->expire_time;
2182         if (!ctx->split) {
2183                 char *chain_file_name = get_commit_graph_chain_filename(ctx->odb);
2184                 unlink(chain_file_name);
2185                 free(chain_file_name);
2186                 ctx->num_commit_graphs_after = 0;
2187         }
2188
2189         strbuf_addstr(&path, ctx->odb->path);
2190         strbuf_addstr(&path, "/info/commit-graphs");
2191         dir = opendir(path.buf);
2192
2193         if (!dir)
2194                 goto out;
2195
2196         strbuf_addch(&path, '/');
2197         dirnamelen = path.len;
2198         while ((de = readdir(dir)) != NULL) {
2199                 struct stat st;
2200                 uint32_t i, found = 0;
2201
2202                 strbuf_setlen(&path, dirnamelen);
2203                 strbuf_addstr(&path, de->d_name);
2204
2205                 stat(path.buf, &st);
2206
2207                 if (st.st_mtime > expire_time)
2208                         continue;
2209                 if (path.len < 6 || strcmp(path.buf + path.len - 6, ".graph"))
2210                         continue;
2211
2212                 for (i = 0; i < ctx->num_commit_graphs_after; i++) {
2213                         if (!strcmp(ctx->commit_graph_filenames_after[i],
2214                                     path.buf)) {
2215                                 found = 1;
2216                                 break;
2217                         }
2218                 }
2219
2220                 if (!found)
2221                         unlink(path.buf);
2222         }
2223
2224 out:
2225         strbuf_release(&path);
2226 }
2227
2228 int write_commit_graph(struct object_directory *odb,
2229                        struct string_list *pack_indexes,
2230                        struct oidset *commits,
2231                        enum commit_graph_write_flags flags,
2232                        const struct commit_graph_opts *opts)
2233 {
2234         struct write_commit_graph_context *ctx;
2235         uint32_t i;
2236         int res = 0;
2237         int replace = 0;
2238         struct bloom_filter_settings bloom_settings = DEFAULT_BLOOM_FILTER_SETTINGS;
2239         struct topo_level_slab topo_levels;
2240
2241         prepare_repo_settings(the_repository);
2242         if (!the_repository->settings.core_commit_graph) {
2243                 warning(_("attempting to write a commit-graph, but 'core.commitGraph' is disabled"));
2244                 return 0;
2245         }
2246         if (!commit_graph_compatible(the_repository))
2247                 return 0;
2248
2249         ctx = xcalloc(1, sizeof(struct write_commit_graph_context));
2250         ctx->r = the_repository;
2251         ctx->odb = odb;
2252         ctx->append = flags & COMMIT_GRAPH_WRITE_APPEND ? 1 : 0;
2253         ctx->report_progress = flags & COMMIT_GRAPH_WRITE_PROGRESS ? 1 : 0;
2254         ctx->split = flags & COMMIT_GRAPH_WRITE_SPLIT ? 1 : 0;
2255         ctx->opts = opts;
2256         ctx->total_bloom_filter_data_size = 0;
2257         ctx->write_generation_data = 1;
2258         ctx->num_generation_data_overflows = 0;
2259
2260         bloom_settings.bits_per_entry = git_env_ulong("GIT_TEST_BLOOM_SETTINGS_BITS_PER_ENTRY",
2261                                                       bloom_settings.bits_per_entry);
2262         bloom_settings.num_hashes = git_env_ulong("GIT_TEST_BLOOM_SETTINGS_NUM_HASHES",
2263                                                   bloom_settings.num_hashes);
2264         bloom_settings.max_changed_paths = git_env_ulong("GIT_TEST_BLOOM_SETTINGS_MAX_CHANGED_PATHS",
2265                                                          bloom_settings.max_changed_paths);
2266         ctx->bloom_settings = &bloom_settings;
2267
2268         init_topo_level_slab(&topo_levels);
2269         ctx->topo_levels = &topo_levels;
2270
2271         prepare_commit_graph(ctx->r);
2272         if (ctx->r->objects->commit_graph) {
2273                 struct commit_graph *g = ctx->r->objects->commit_graph;
2274
2275                 while (g) {
2276                         g->topo_levels = &topo_levels;
2277                         g = g->base_graph;
2278                 }
2279         }
2280
2281         if (flags & COMMIT_GRAPH_WRITE_BLOOM_FILTERS)
2282                 ctx->changed_paths = 1;
2283         if (!(flags & COMMIT_GRAPH_NO_WRITE_BLOOM_FILTERS)) {
2284                 struct commit_graph *g;
2285
2286                 g = ctx->r->objects->commit_graph;
2287
2288                 /* We have changed-paths already. Keep them in the next graph */
2289                 if (g && g->chunk_bloom_data) {
2290                         ctx->changed_paths = 1;
2291                         ctx->bloom_settings = g->bloom_filter_settings;
2292                 }
2293         }
2294
2295         if (ctx->split) {
2296                 struct commit_graph *g = ctx->r->objects->commit_graph;
2297
2298                 while (g) {
2299                         ctx->num_commit_graphs_before++;
2300                         g = g->base_graph;
2301                 }
2302
2303                 if (ctx->num_commit_graphs_before) {
2304                         ALLOC_ARRAY(ctx->commit_graph_filenames_before, ctx->num_commit_graphs_before);
2305                         i = ctx->num_commit_graphs_before;
2306                         g = ctx->r->objects->commit_graph;
2307
2308                         while (g) {
2309                                 ctx->commit_graph_filenames_before[--i] = xstrdup(g->filename);
2310                                 g = g->base_graph;
2311                         }
2312                 }
2313
2314                 if (ctx->opts)
2315                         replace = ctx->opts->split_flags & COMMIT_GRAPH_SPLIT_REPLACE;
2316         }
2317
2318         ctx->approx_nr_objects = approximate_object_count();
2319
2320         if (ctx->append && ctx->r->objects->commit_graph) {
2321                 struct commit_graph *g = ctx->r->objects->commit_graph;
2322                 for (i = 0; i < g->num_commits; i++) {
2323                         struct object_id oid;
2324                         hashcpy(oid.hash, g->chunk_oid_lookup + g->hash_len * i);
2325                         oid_array_append(&ctx->oids, &oid);
2326                 }
2327         }
2328
2329         if (pack_indexes) {
2330                 ctx->order_by_pack = 1;
2331                 if ((res = fill_oids_from_packs(ctx, pack_indexes)))
2332                         goto cleanup;
2333         }
2334
2335         if (commits) {
2336                 if ((res = fill_oids_from_commits(ctx, commits)))
2337                         goto cleanup;
2338         }
2339
2340         if (!pack_indexes && !commits) {
2341                 ctx->order_by_pack = 1;
2342                 fill_oids_from_all_packs(ctx);
2343         }
2344
2345         close_reachable(ctx);
2346
2347         copy_oids_to_commits(ctx);
2348
2349         if (ctx->commits.nr >= GRAPH_EDGE_LAST_MASK) {
2350                 error(_("too many commits to write graph"));
2351                 res = -1;
2352                 goto cleanup;
2353         }
2354
2355         if (!ctx->commits.nr && !replace)
2356                 goto cleanup;
2357
2358         if (ctx->split) {
2359                 split_graph_merge_strategy(ctx);
2360
2361                 if (!replace)
2362                         merge_commit_graphs(ctx);
2363         } else
2364                 ctx->num_commit_graphs_after = 1;
2365
2366         ctx->trust_generation_numbers = validate_mixed_generation_chain(ctx->r->objects->commit_graph);
2367
2368         compute_topological_levels(ctx);
2369         if (ctx->write_generation_data)
2370                 compute_generation_numbers(ctx);
2371
2372         if (ctx->changed_paths)
2373                 compute_bloom_filters(ctx);
2374
2375         res = write_commit_graph_file(ctx);
2376
2377         if (ctx->split)
2378                 mark_commit_graphs(ctx);
2379
2380         expire_commit_graphs(ctx);
2381
2382 cleanup:
2383         free(ctx->graph_name);
2384         free(ctx->commits.list);
2385         oid_array_clear(&ctx->oids);
2386
2387         if (ctx->commit_graph_filenames_after) {
2388                 for (i = 0; i < ctx->num_commit_graphs_after; i++) {
2389                         free(ctx->commit_graph_filenames_after[i]);
2390                         free(ctx->commit_graph_hash_after[i]);
2391                 }
2392
2393                 for (i = 0; i < ctx->num_commit_graphs_before; i++)
2394                         free(ctx->commit_graph_filenames_before[i]);
2395
2396                 free(ctx->commit_graph_filenames_after);
2397                 free(ctx->commit_graph_filenames_before);
2398                 free(ctx->commit_graph_hash_after);
2399         }
2400
2401         free(ctx);
2402
2403         return res;
2404 }
2405
2406 #define VERIFY_COMMIT_GRAPH_ERROR_HASH 2
2407 static int verify_commit_graph_error;
2408
2409 static void graph_report(const char *fmt, ...)
2410 {
2411         va_list ap;
2412
2413         verify_commit_graph_error = 1;
2414         va_start(ap, fmt);
2415         vfprintf(stderr, fmt, ap);
2416         fprintf(stderr, "\n");
2417         va_end(ap);
2418 }
2419
2420 #define GENERATION_ZERO_EXISTS 1
2421 #define GENERATION_NUMBER_EXISTS 2
2422
2423 int verify_commit_graph(struct repository *r, struct commit_graph *g, int flags)
2424 {
2425         uint32_t i, cur_fanout_pos = 0;
2426         struct object_id prev_oid, cur_oid, checksum;
2427         int generation_zero = 0;
2428         struct hashfile *f;
2429         int devnull;
2430         struct progress *progress = NULL;
2431         int local_error = 0;
2432
2433         if (!g) {
2434                 graph_report("no commit-graph file loaded");
2435                 return 1;
2436         }
2437
2438         verify_commit_graph_error = verify_commit_graph_lite(g);
2439         if (verify_commit_graph_error)
2440                 return verify_commit_graph_error;
2441
2442         devnull = open("/dev/null", O_WRONLY);
2443         f = hashfd(devnull, NULL);
2444         hashwrite(f, g->data, g->data_len - g->hash_len);
2445         finalize_hashfile(f, checksum.hash, CSUM_CLOSE);
2446         if (!hasheq(checksum.hash, g->data + g->data_len - g->hash_len)) {
2447                 graph_report(_("the commit-graph file has incorrect checksum and is likely corrupt"));
2448                 verify_commit_graph_error = VERIFY_COMMIT_GRAPH_ERROR_HASH;
2449         }
2450
2451         for (i = 0; i < g->num_commits; i++) {
2452                 struct commit *graph_commit;
2453
2454                 hashcpy(cur_oid.hash, g->chunk_oid_lookup + g->hash_len * i);
2455
2456                 if (i && oidcmp(&prev_oid, &cur_oid) >= 0)
2457                         graph_report(_("commit-graph has incorrect OID order: %s then %s"),
2458                                      oid_to_hex(&prev_oid),
2459                                      oid_to_hex(&cur_oid));
2460
2461                 oidcpy(&prev_oid, &cur_oid);
2462
2463                 while (cur_oid.hash[0] > cur_fanout_pos) {
2464                         uint32_t fanout_value = get_be32(g->chunk_oid_fanout + cur_fanout_pos);
2465
2466                         if (i != fanout_value)
2467                                 graph_report(_("commit-graph has incorrect fanout value: fanout[%d] = %u != %u"),
2468                                              cur_fanout_pos, fanout_value, i);
2469                         cur_fanout_pos++;
2470                 }
2471
2472                 graph_commit = lookup_commit(r, &cur_oid);
2473                 if (!parse_commit_in_graph_one(r, g, graph_commit))
2474                         graph_report(_("failed to parse commit %s from commit-graph"),
2475                                      oid_to_hex(&cur_oid));
2476         }
2477
2478         while (cur_fanout_pos < 256) {
2479                 uint32_t fanout_value = get_be32(g->chunk_oid_fanout + cur_fanout_pos);
2480
2481                 if (g->num_commits != fanout_value)
2482                         graph_report(_("commit-graph has incorrect fanout value: fanout[%d] = %u != %u"),
2483                                      cur_fanout_pos, fanout_value, i);
2484
2485                 cur_fanout_pos++;
2486         }
2487
2488         if (verify_commit_graph_error & ~VERIFY_COMMIT_GRAPH_ERROR_HASH)
2489                 return verify_commit_graph_error;
2490
2491         if (flags & COMMIT_GRAPH_WRITE_PROGRESS)
2492                 progress = start_progress(_("Verifying commits in commit graph"),
2493                                         g->num_commits);
2494
2495         for (i = 0; i < g->num_commits; i++) {
2496                 struct commit *graph_commit, *odb_commit;
2497                 struct commit_list *graph_parents, *odb_parents;
2498                 timestamp_t max_generation = 0;
2499                 timestamp_t generation;
2500
2501                 display_progress(progress, i + 1);
2502                 hashcpy(cur_oid.hash, g->chunk_oid_lookup + g->hash_len * i);
2503
2504                 graph_commit = lookup_commit(r, &cur_oid);
2505                 odb_commit = (struct commit *)create_object(r, &cur_oid, alloc_commit_node(r));
2506                 if (parse_commit_internal(odb_commit, 0, 0)) {
2507                         graph_report(_("failed to parse commit %s from object database for commit-graph"),
2508                                      oid_to_hex(&cur_oid));
2509                         continue;
2510                 }
2511
2512                 if (!oideq(&get_commit_tree_in_graph_one(r, g, graph_commit)->object.oid,
2513                            get_commit_tree_oid(odb_commit)))
2514                         graph_report(_("root tree OID for commit %s in commit-graph is %s != %s"),
2515                                      oid_to_hex(&cur_oid),
2516                                      oid_to_hex(get_commit_tree_oid(graph_commit)),
2517                                      oid_to_hex(get_commit_tree_oid(odb_commit)));
2518
2519                 graph_parents = graph_commit->parents;
2520                 odb_parents = odb_commit->parents;
2521
2522                 while (graph_parents) {
2523                         if (odb_parents == NULL) {
2524                                 graph_report(_("commit-graph parent list for commit %s is too long"),
2525                                              oid_to_hex(&cur_oid));
2526                                 break;
2527                         }
2528
2529                         /* parse parent in case it is in a base graph */
2530                         parse_commit_in_graph_one(r, g, graph_parents->item);
2531
2532                         if (!oideq(&graph_parents->item->object.oid, &odb_parents->item->object.oid))
2533                                 graph_report(_("commit-graph parent for %s is %s != %s"),
2534                                              oid_to_hex(&cur_oid),
2535                                              oid_to_hex(&graph_parents->item->object.oid),
2536                                              oid_to_hex(&odb_parents->item->object.oid));
2537
2538                         generation = commit_graph_generation(graph_parents->item);
2539                         if (generation > max_generation)
2540                                 max_generation = generation;
2541
2542                         graph_parents = graph_parents->next;
2543                         odb_parents = odb_parents->next;
2544                 }
2545
2546                 if (odb_parents != NULL)
2547                         graph_report(_("commit-graph parent list for commit %s terminates early"),
2548                                      oid_to_hex(&cur_oid));
2549
2550                 if (!commit_graph_generation(graph_commit)) {
2551                         if (generation_zero == GENERATION_NUMBER_EXISTS)
2552                                 graph_report(_("commit-graph has generation number zero for commit %s, but non-zero elsewhere"),
2553                                              oid_to_hex(&cur_oid));
2554                         generation_zero = GENERATION_ZERO_EXISTS;
2555                 } else if (generation_zero == GENERATION_ZERO_EXISTS)
2556                         graph_report(_("commit-graph has non-zero generation number for commit %s, but zero elsewhere"),
2557                                      oid_to_hex(&cur_oid));
2558
2559                 if (generation_zero == GENERATION_ZERO_EXISTS)
2560                         continue;
2561
2562                 /*
2563                  * If we are using topological level and one of our parents has
2564                  * generation GENERATION_NUMBER_V1_MAX, then our generation is
2565                  * also GENERATION_NUMBER_V1_MAX. Decrement to avoid extra logic
2566                  * in the following condition.
2567                  */
2568                 if (!g->read_generation_data && max_generation == GENERATION_NUMBER_V1_MAX)
2569                         max_generation--;
2570
2571                 generation = commit_graph_generation(graph_commit);
2572                 if (generation < max_generation + 1)
2573                         graph_report(_("commit-graph generation for commit %s is %"PRItime" < %"PRItime),
2574                                      oid_to_hex(&cur_oid),
2575                                      generation,
2576                                      max_generation + 1);
2577
2578                 if (graph_commit->date != odb_commit->date)
2579                         graph_report(_("commit date for commit %s in commit-graph is %"PRItime" != %"PRItime),
2580                                      oid_to_hex(&cur_oid),
2581                                      graph_commit->date,
2582                                      odb_commit->date);
2583         }
2584         stop_progress(&progress);
2585
2586         local_error = verify_commit_graph_error;
2587
2588         if (!(flags & COMMIT_GRAPH_VERIFY_SHALLOW) && g->base_graph)
2589                 local_error |= verify_commit_graph(r, g->base_graph, flags);
2590
2591         return local_error;
2592 }
2593
2594 void free_commit_graph(struct commit_graph *g)
2595 {
2596         if (!g)
2597                 return;
2598         if (g->data) {
2599                 munmap((void *)g->data, g->data_len);
2600                 g->data = NULL;
2601         }
2602         free(g->filename);
2603         free(g->bloom_filter_settings);
2604         free(g);
2605 }
2606
2607 void disable_commit_graph(struct repository *r)
2608 {
2609         r->commit_graph_disabled = 1;
2610 }