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