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