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