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