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