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