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