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