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