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