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