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