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