bloom: encode out-of-bounds filters as non-empty
[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         int count_bloom_filter_computed;
970         int count_bloom_filter_not_computed;
971         int count_bloom_filter_trunc_empty;
972         int count_bloom_filter_trunc_large;
973 };
974
975 static int write_graph_chunk_fanout(struct hashfile *f,
976                                     struct write_commit_graph_context *ctx)
977 {
978         int i, count = 0;
979         struct commit **list = ctx->commits.list;
980
981         /*
982          * Write the first-level table (the list is sorted,
983          * but we use a 256-entry lookup to be able to avoid
984          * having to do eight extra binary search iterations).
985          */
986         for (i = 0; i < 256; i++) {
987                 while (count < ctx->commits.nr) {
988                         if ((*list)->object.oid.hash[0] != i)
989                                 break;
990                         display_progress(ctx->progress, ++ctx->progress_cnt);
991                         count++;
992                         list++;
993                 }
994
995                 hashwrite_be32(f, count);
996         }
997
998         return 0;
999 }
1000
1001 static int write_graph_chunk_oids(struct hashfile *f,
1002                                   struct write_commit_graph_context *ctx)
1003 {
1004         struct commit **list = ctx->commits.list;
1005         int count;
1006         for (count = 0; count < ctx->commits.nr; count++, list++) {
1007                 display_progress(ctx->progress, ++ctx->progress_cnt);
1008                 hashwrite(f, (*list)->object.oid.hash, the_hash_algo->rawsz);
1009         }
1010
1011         return 0;
1012 }
1013
1014 static const unsigned char *commit_to_sha1(size_t index, void *table)
1015 {
1016         struct commit **commits = table;
1017         return commits[index]->object.oid.hash;
1018 }
1019
1020 static int write_graph_chunk_data(struct hashfile *f,
1021                                   struct write_commit_graph_context *ctx)
1022 {
1023         struct commit **list = ctx->commits.list;
1024         struct commit **last = ctx->commits.list + ctx->commits.nr;
1025         uint32_t num_extra_edges = 0;
1026
1027         while (list < last) {
1028                 struct commit_list *parent;
1029                 struct object_id *tree;
1030                 int edge_value;
1031                 uint32_t packedDate[2];
1032                 display_progress(ctx->progress, ++ctx->progress_cnt);
1033
1034                 if (parse_commit_no_graph(*list))
1035                         die(_("unable to parse commit %s"),
1036                                 oid_to_hex(&(*list)->object.oid));
1037                 tree = get_commit_tree_oid(*list);
1038                 hashwrite(f, tree->hash, the_hash_algo->rawsz);
1039
1040                 parent = (*list)->parents;
1041
1042                 if (!parent)
1043                         edge_value = GRAPH_PARENT_NONE;
1044                 else {
1045                         edge_value = sha1_pos(parent->item->object.oid.hash,
1046                                               ctx->commits.list,
1047                                               ctx->commits.nr,
1048                                               commit_to_sha1);
1049
1050                         if (edge_value >= 0)
1051                                 edge_value += ctx->new_num_commits_in_base;
1052                         else if (ctx->new_base_graph) {
1053                                 uint32_t pos;
1054                                 if (find_commit_in_graph(parent->item,
1055                                                          ctx->new_base_graph,
1056                                                          &pos))
1057                                         edge_value = pos;
1058                         }
1059
1060                         if (edge_value < 0)
1061                                 BUG("missing parent %s for commit %s",
1062                                     oid_to_hex(&parent->item->object.oid),
1063                                     oid_to_hex(&(*list)->object.oid));
1064                 }
1065
1066                 hashwrite_be32(f, edge_value);
1067
1068                 if (parent)
1069                         parent = parent->next;
1070
1071                 if (!parent)
1072                         edge_value = GRAPH_PARENT_NONE;
1073                 else if (parent->next)
1074                         edge_value = GRAPH_EXTRA_EDGES_NEEDED | num_extra_edges;
1075                 else {
1076                         edge_value = sha1_pos(parent->item->object.oid.hash,
1077                                               ctx->commits.list,
1078                                               ctx->commits.nr,
1079                                               commit_to_sha1);
1080
1081                         if (edge_value >= 0)
1082                                 edge_value += ctx->new_num_commits_in_base;
1083                         else if (ctx->new_base_graph) {
1084                                 uint32_t pos;
1085                                 if (find_commit_in_graph(parent->item,
1086                                                          ctx->new_base_graph,
1087                                                          &pos))
1088                                         edge_value = pos;
1089                         }
1090
1091                         if (edge_value < 0)
1092                                 BUG("missing parent %s for commit %s",
1093                                     oid_to_hex(&parent->item->object.oid),
1094                                     oid_to_hex(&(*list)->object.oid));
1095                 }
1096
1097                 hashwrite_be32(f, edge_value);
1098
1099                 if (edge_value & GRAPH_EXTRA_EDGES_NEEDED) {
1100                         do {
1101                                 num_extra_edges++;
1102                                 parent = parent->next;
1103                         } while (parent);
1104                 }
1105
1106                 if (sizeof((*list)->date) > 4)
1107                         packedDate[0] = htonl(((*list)->date >> 32) & 0x3);
1108                 else
1109                         packedDate[0] = 0;
1110
1111                 packedDate[0] |= htonl(commit_graph_data_at(*list)->generation << 2);
1112
1113                 packedDate[1] = htonl((*list)->date);
1114                 hashwrite(f, packedDate, 8);
1115
1116                 list++;
1117         }
1118
1119         return 0;
1120 }
1121
1122 static int write_graph_chunk_extra_edges(struct hashfile *f,
1123                                          struct write_commit_graph_context *ctx)
1124 {
1125         struct commit **list = ctx->commits.list;
1126         struct commit **last = ctx->commits.list + ctx->commits.nr;
1127         struct commit_list *parent;
1128
1129         while (list < last) {
1130                 int num_parents = 0;
1131
1132                 display_progress(ctx->progress, ++ctx->progress_cnt);
1133
1134                 for (parent = (*list)->parents; num_parents < 3 && parent;
1135                      parent = parent->next)
1136                         num_parents++;
1137
1138                 if (num_parents <= 2) {
1139                         list++;
1140                         continue;
1141                 }
1142
1143                 /* Since num_parents > 2, this initializer is safe. */
1144                 for (parent = (*list)->parents->next; parent; parent = parent->next) {
1145                         int edge_value = sha1_pos(parent->item->object.oid.hash,
1146                                                   ctx->commits.list,
1147                                                   ctx->commits.nr,
1148                                                   commit_to_sha1);
1149
1150                         if (edge_value >= 0)
1151                                 edge_value += ctx->new_num_commits_in_base;
1152                         else if (ctx->new_base_graph) {
1153                                 uint32_t pos;
1154                                 if (find_commit_in_graph(parent->item,
1155                                                          ctx->new_base_graph,
1156                                                          &pos))
1157                                         edge_value = pos;
1158                         }
1159
1160                         if (edge_value < 0)
1161                                 BUG("missing parent %s for commit %s",
1162                                     oid_to_hex(&parent->item->object.oid),
1163                                     oid_to_hex(&(*list)->object.oid));
1164                         else if (!parent->next)
1165                                 edge_value |= GRAPH_LAST_EDGE;
1166
1167                         hashwrite_be32(f, edge_value);
1168                 }
1169
1170                 list++;
1171         }
1172
1173         return 0;
1174 }
1175
1176 static int write_graph_chunk_bloom_indexes(struct hashfile *f,
1177                                            struct write_commit_graph_context *ctx)
1178 {
1179         struct commit **list = ctx->commits.list;
1180         struct commit **last = ctx->commits.list + ctx->commits.nr;
1181         uint32_t cur_pos = 0;
1182
1183         while (list < last) {
1184                 struct bloom_filter *filter = get_bloom_filter(ctx->r, *list);
1185                 size_t len = filter ? filter->len : 0;
1186                 cur_pos += len;
1187                 display_progress(ctx->progress, ++ctx->progress_cnt);
1188                 hashwrite_be32(f, cur_pos);
1189                 list++;
1190         }
1191
1192         return 0;
1193 }
1194
1195 static void trace2_bloom_filter_settings(struct write_commit_graph_context *ctx)
1196 {
1197         struct json_writer jw = JSON_WRITER_INIT;
1198
1199         jw_object_begin(&jw, 0);
1200         jw_object_intmax(&jw, "hash_version", ctx->bloom_settings->hash_version);
1201         jw_object_intmax(&jw, "num_hashes", ctx->bloom_settings->num_hashes);
1202         jw_object_intmax(&jw, "bits_per_entry", ctx->bloom_settings->bits_per_entry);
1203         jw_object_intmax(&jw, "max_changed_paths", ctx->bloom_settings->max_changed_paths);
1204         jw_end(&jw);
1205
1206         trace2_data_json("bloom", ctx->r, "settings", &jw);
1207
1208         jw_release(&jw);
1209 }
1210
1211 static int write_graph_chunk_bloom_data(struct hashfile *f,
1212                                         struct write_commit_graph_context *ctx)
1213 {
1214         struct commit **list = ctx->commits.list;
1215         struct commit **last = ctx->commits.list + ctx->commits.nr;
1216
1217         trace2_bloom_filter_settings(ctx);
1218
1219         hashwrite_be32(f, ctx->bloom_settings->hash_version);
1220         hashwrite_be32(f, ctx->bloom_settings->num_hashes);
1221         hashwrite_be32(f, ctx->bloom_settings->bits_per_entry);
1222
1223         while (list < last) {
1224                 struct bloom_filter *filter = get_bloom_filter(ctx->r, *list);
1225                 size_t len = filter ? filter->len : 0;
1226
1227                 display_progress(ctx->progress, ++ctx->progress_cnt);
1228                 if (len)
1229                         hashwrite(f, filter->data, len * sizeof(unsigned char));
1230                 list++;
1231         }
1232
1233         return 0;
1234 }
1235
1236 static int oid_compare(const void *_a, const void *_b)
1237 {
1238         const struct object_id *a = (const struct object_id *)_a;
1239         const struct object_id *b = (const struct object_id *)_b;
1240         return oidcmp(a, b);
1241 }
1242
1243 static int add_packed_commits(const struct object_id *oid,
1244                               struct packed_git *pack,
1245                               uint32_t pos,
1246                               void *data)
1247 {
1248         struct write_commit_graph_context *ctx = (struct write_commit_graph_context*)data;
1249         enum object_type type;
1250         off_t offset = nth_packed_object_offset(pack, pos);
1251         struct object_info oi = OBJECT_INFO_INIT;
1252
1253         if (ctx->progress)
1254                 display_progress(ctx->progress, ++ctx->progress_done);
1255
1256         oi.typep = &type;
1257         if (packed_object_info(ctx->r, pack, offset, &oi) < 0)
1258                 die(_("unable to get type of object %s"), oid_to_hex(oid));
1259
1260         if (type != OBJ_COMMIT)
1261                 return 0;
1262
1263         ALLOC_GROW(ctx->oids.list, ctx->oids.nr + 1, ctx->oids.alloc);
1264         oidcpy(&(ctx->oids.list[ctx->oids.nr]), oid);
1265         ctx->oids.nr++;
1266
1267         set_commit_pos(ctx->r, oid);
1268
1269         return 0;
1270 }
1271
1272 static void add_missing_parents(struct write_commit_graph_context *ctx, struct commit *commit)
1273 {
1274         struct commit_list *parent;
1275         for (parent = commit->parents; parent; parent = parent->next) {
1276                 if (!(parent->item->object.flags & REACHABLE)) {
1277                         ALLOC_GROW(ctx->oids.list, ctx->oids.nr + 1, ctx->oids.alloc);
1278                         oidcpy(&ctx->oids.list[ctx->oids.nr], &(parent->item->object.oid));
1279                         ctx->oids.nr++;
1280                         parent->item->object.flags |= REACHABLE;
1281                 }
1282         }
1283 }
1284
1285 static void close_reachable(struct write_commit_graph_context *ctx)
1286 {
1287         int i;
1288         struct commit *commit;
1289         enum commit_graph_split_flags flags = ctx->split_opts ?
1290                 ctx->split_opts->flags : COMMIT_GRAPH_SPLIT_UNSPECIFIED;
1291
1292         if (ctx->report_progress)
1293                 ctx->progress = start_delayed_progress(
1294                                         _("Loading known commits in commit graph"),
1295                                         ctx->oids.nr);
1296         for (i = 0; i < ctx->oids.nr; i++) {
1297                 display_progress(ctx->progress, i + 1);
1298                 commit = lookup_commit(ctx->r, &ctx->oids.list[i]);
1299                 if (commit)
1300                         commit->object.flags |= REACHABLE;
1301         }
1302         stop_progress(&ctx->progress);
1303
1304         /*
1305          * As this loop runs, ctx->oids.nr may grow, but not more
1306          * than the number of missing commits in the reachable
1307          * closure.
1308          */
1309         if (ctx->report_progress)
1310                 ctx->progress = start_delayed_progress(
1311                                         _("Expanding reachable commits in commit graph"),
1312                                         0);
1313         for (i = 0; i < ctx->oids.nr; i++) {
1314                 display_progress(ctx->progress, i + 1);
1315                 commit = lookup_commit(ctx->r, &ctx->oids.list[i]);
1316
1317                 if (!commit)
1318                         continue;
1319                 if (ctx->split) {
1320                         if ((!parse_commit(commit) &&
1321                              commit_graph_position(commit) == COMMIT_NOT_FROM_GRAPH) ||
1322                             flags == COMMIT_GRAPH_SPLIT_REPLACE)
1323                                 add_missing_parents(ctx, commit);
1324                 } else if (!parse_commit_no_graph(commit))
1325                         add_missing_parents(ctx, commit);
1326         }
1327         stop_progress(&ctx->progress);
1328
1329         if (ctx->report_progress)
1330                 ctx->progress = start_delayed_progress(
1331                                         _("Clearing commit marks in commit graph"),
1332                                         ctx->oids.nr);
1333         for (i = 0; i < ctx->oids.nr; i++) {
1334                 display_progress(ctx->progress, i + 1);
1335                 commit = lookup_commit(ctx->r, &ctx->oids.list[i]);
1336
1337                 if (commit)
1338                         commit->object.flags &= ~REACHABLE;
1339         }
1340         stop_progress(&ctx->progress);
1341 }
1342
1343 static void compute_generation_numbers(struct write_commit_graph_context *ctx)
1344 {
1345         int i;
1346         struct commit_list *list = NULL;
1347
1348         if (ctx->report_progress)
1349                 ctx->progress = start_delayed_progress(
1350                                         _("Computing commit graph generation numbers"),
1351                                         ctx->commits.nr);
1352         for (i = 0; i < ctx->commits.nr; i++) {
1353                 uint32_t generation = commit_graph_data_at(ctx->commits.list[i])->generation;
1354
1355                 display_progress(ctx->progress, i + 1);
1356                 if (generation != GENERATION_NUMBER_INFINITY &&
1357                     generation != GENERATION_NUMBER_ZERO)
1358                         continue;
1359
1360                 commit_list_insert(ctx->commits.list[i], &list);
1361                 while (list) {
1362                         struct commit *current = list->item;
1363                         struct commit_list *parent;
1364                         int all_parents_computed = 1;
1365                         uint32_t max_generation = 0;
1366
1367                         for (parent = current->parents; parent; parent = parent->next) {
1368                                 generation = commit_graph_data_at(parent->item)->generation;
1369
1370                                 if (generation == GENERATION_NUMBER_INFINITY ||
1371                                     generation == GENERATION_NUMBER_ZERO) {
1372                                         all_parents_computed = 0;
1373                                         commit_list_insert(parent->item, &list);
1374                                         break;
1375                                 } else if (generation > max_generation) {
1376                                         max_generation = generation;
1377                                 }
1378                         }
1379
1380                         if (all_parents_computed) {
1381                                 struct commit_graph_data *data = commit_graph_data_at(current);
1382
1383                                 data->generation = max_generation + 1;
1384                                 pop_commit(&list);
1385
1386                                 if (data->generation > GENERATION_NUMBER_MAX)
1387                                         data->generation = GENERATION_NUMBER_MAX;
1388                         }
1389                 }
1390         }
1391         stop_progress(&ctx->progress);
1392 }
1393
1394 static void trace2_bloom_filter_write_statistics(struct write_commit_graph_context *ctx)
1395 {
1396         trace2_data_intmax("commit-graph", ctx->r, "filter-computed",
1397                            ctx->count_bloom_filter_computed);
1398         trace2_data_intmax("commit-graph", ctx->r, "filter-not-computed",
1399                            ctx->count_bloom_filter_not_computed);
1400         trace2_data_intmax("commit-graph", ctx->r, "filter-trunc-empty",
1401                            ctx->count_bloom_filter_trunc_empty);
1402         trace2_data_intmax("commit-graph", ctx->r, "filter-trunc-large",
1403                            ctx->count_bloom_filter_trunc_large);
1404 }
1405
1406 static void compute_bloom_filters(struct write_commit_graph_context *ctx)
1407 {
1408         int i;
1409         struct progress *progress = NULL;
1410         struct commit **sorted_commits;
1411
1412         init_bloom_filters();
1413
1414         if (ctx->report_progress)
1415                 progress = start_delayed_progress(
1416                         _("Computing commit changed paths Bloom filters"),
1417                         ctx->commits.nr);
1418
1419         ALLOC_ARRAY(sorted_commits, ctx->commits.nr);
1420         COPY_ARRAY(sorted_commits, ctx->commits.list, ctx->commits.nr);
1421
1422         if (ctx->order_by_pack)
1423                 QSORT(sorted_commits, ctx->commits.nr, commit_pos_cmp);
1424         else
1425                 QSORT(sorted_commits, ctx->commits.nr, commit_gen_cmp);
1426
1427         for (i = 0; i < ctx->commits.nr; i++) {
1428                 enum bloom_filter_computed computed = 0;
1429                 struct commit *c = sorted_commits[i];
1430                 struct bloom_filter *filter = get_or_compute_bloom_filter(
1431                         ctx->r,
1432                         c,
1433                         1,
1434                         ctx->bloom_settings,
1435                         &computed);
1436                 if (computed & BLOOM_COMPUTED) {
1437                         ctx->count_bloom_filter_computed++;
1438                         if (computed & BLOOM_TRUNC_EMPTY)
1439                                 ctx->count_bloom_filter_trunc_empty++;
1440                         if (computed & BLOOM_TRUNC_LARGE)
1441                                 ctx->count_bloom_filter_trunc_large++;
1442                 } else if (computed & BLOOM_NOT_COMPUTED)
1443                         ctx->count_bloom_filter_not_computed++;
1444                 ctx->total_bloom_filter_data_size += sizeof(unsigned char) * filter->len;
1445                 display_progress(progress, i + 1);
1446         }
1447
1448         if (trace2_is_enabled())
1449                 trace2_bloom_filter_write_statistics(ctx);
1450
1451         free(sorted_commits);
1452         stop_progress(&progress);
1453 }
1454
1455 struct refs_cb_data {
1456         struct oidset *commits;
1457         struct progress *progress;
1458 };
1459
1460 static int add_ref_to_set(const char *refname,
1461                           const struct object_id *oid,
1462                           int flags, void *cb_data)
1463 {
1464         struct object_id peeled;
1465         struct refs_cb_data *data = (struct refs_cb_data *)cb_data;
1466
1467         if (!peel_ref(refname, &peeled))
1468                 oid = &peeled;
1469         if (oid_object_info(the_repository, oid, NULL) == OBJ_COMMIT)
1470                 oidset_insert(data->commits, oid);
1471
1472         display_progress(data->progress, oidset_size(data->commits));
1473
1474         return 0;
1475 }
1476
1477 int write_commit_graph_reachable(struct object_directory *odb,
1478                                  enum commit_graph_write_flags flags,
1479                                  const struct split_commit_graph_opts *split_opts)
1480 {
1481         struct oidset commits = OIDSET_INIT;
1482         struct refs_cb_data data;
1483         int result;
1484
1485         memset(&data, 0, sizeof(data));
1486         data.commits = &commits;
1487         if (flags & COMMIT_GRAPH_WRITE_PROGRESS)
1488                 data.progress = start_delayed_progress(
1489                         _("Collecting referenced commits"), 0);
1490
1491         for_each_ref(add_ref_to_set, &data);
1492
1493         stop_progress(&data.progress);
1494
1495         result = write_commit_graph(odb, NULL, &commits,
1496                                     flags, split_opts);
1497
1498         oidset_clear(&commits);
1499         return result;
1500 }
1501
1502 static int fill_oids_from_packs(struct write_commit_graph_context *ctx,
1503                                 struct string_list *pack_indexes)
1504 {
1505         uint32_t i;
1506         struct strbuf progress_title = STRBUF_INIT;
1507         struct strbuf packname = STRBUF_INIT;
1508         int dirlen;
1509
1510         strbuf_addf(&packname, "%s/pack/", ctx->odb->path);
1511         dirlen = packname.len;
1512         if (ctx->report_progress) {
1513                 strbuf_addf(&progress_title,
1514                             Q_("Finding commits for commit graph in %d pack",
1515                                "Finding commits for commit graph in %d packs",
1516                                pack_indexes->nr),
1517                             pack_indexes->nr);
1518                 ctx->progress = start_delayed_progress(progress_title.buf, 0);
1519                 ctx->progress_done = 0;
1520         }
1521         for (i = 0; i < pack_indexes->nr; i++) {
1522                 struct packed_git *p;
1523                 strbuf_setlen(&packname, dirlen);
1524                 strbuf_addstr(&packname, pack_indexes->items[i].string);
1525                 p = add_packed_git(packname.buf, packname.len, 1);
1526                 if (!p) {
1527                         error(_("error adding pack %s"), packname.buf);
1528                         return -1;
1529                 }
1530                 if (open_pack_index(p)) {
1531                         error(_("error opening index for %s"), packname.buf);
1532                         return -1;
1533                 }
1534                 for_each_object_in_pack(p, add_packed_commits, ctx,
1535                                         FOR_EACH_OBJECT_PACK_ORDER);
1536                 close_pack(p);
1537                 free(p);
1538         }
1539
1540         stop_progress(&ctx->progress);
1541         strbuf_release(&progress_title);
1542         strbuf_release(&packname);
1543
1544         return 0;
1545 }
1546
1547 static int fill_oids_from_commits(struct write_commit_graph_context *ctx,
1548                                   struct oidset *commits)
1549 {
1550         struct oidset_iter iter;
1551         struct object_id *oid;
1552
1553         if (!oidset_size(commits))
1554                 return 0;
1555
1556         oidset_iter_init(commits, &iter);
1557         while ((oid = oidset_iter_next(&iter))) {
1558                 ALLOC_GROW(ctx->oids.list, ctx->oids.nr + 1, ctx->oids.alloc);
1559                 oidcpy(&ctx->oids.list[ctx->oids.nr], oid);
1560                 ctx->oids.nr++;
1561         }
1562
1563         return 0;
1564 }
1565
1566 static void fill_oids_from_all_packs(struct write_commit_graph_context *ctx)
1567 {
1568         if (ctx->report_progress)
1569                 ctx->progress = start_delayed_progress(
1570                         _("Finding commits for commit graph among packed objects"),
1571                         ctx->approx_nr_objects);
1572         for_each_packed_object(add_packed_commits, ctx,
1573                                FOR_EACH_OBJECT_PACK_ORDER);
1574         if (ctx->progress_done < ctx->approx_nr_objects)
1575                 display_progress(ctx->progress, ctx->approx_nr_objects);
1576         stop_progress(&ctx->progress);
1577 }
1578
1579 static uint32_t count_distinct_commits(struct write_commit_graph_context *ctx)
1580 {
1581         uint32_t i, count_distinct = 1;
1582
1583         if (ctx->report_progress)
1584                 ctx->progress = start_delayed_progress(
1585                         _("Counting distinct commits in commit graph"),
1586                         ctx->oids.nr);
1587         display_progress(ctx->progress, 0); /* TODO: Measure QSORT() progress */
1588         QSORT(ctx->oids.list, ctx->oids.nr, oid_compare);
1589
1590         for (i = 1; i < ctx->oids.nr; i++) {
1591                 display_progress(ctx->progress, i + 1);
1592                 if (!oideq(&ctx->oids.list[i - 1], &ctx->oids.list[i])) {
1593                         if (ctx->split) {
1594                                 struct commit *c = lookup_commit(ctx->r, &ctx->oids.list[i]);
1595
1596                                 if (!c || commit_graph_position(c) != COMMIT_NOT_FROM_GRAPH)
1597                                         continue;
1598                         }
1599
1600                         count_distinct++;
1601                 }
1602         }
1603         stop_progress(&ctx->progress);
1604
1605         return count_distinct;
1606 }
1607
1608 static void copy_oids_to_commits(struct write_commit_graph_context *ctx)
1609 {
1610         uint32_t i;
1611         enum commit_graph_split_flags flags = ctx->split_opts ?
1612                 ctx->split_opts->flags : COMMIT_GRAPH_SPLIT_UNSPECIFIED;
1613
1614         ctx->num_extra_edges = 0;
1615         if (ctx->report_progress)
1616                 ctx->progress = start_delayed_progress(
1617                         _("Finding extra edges in commit graph"),
1618                         ctx->oids.nr);
1619         for (i = 0; i < ctx->oids.nr; i++) {
1620                 unsigned int num_parents;
1621
1622                 display_progress(ctx->progress, i + 1);
1623                 if (i > 0 && oideq(&ctx->oids.list[i - 1], &ctx->oids.list[i]))
1624                         continue;
1625
1626                 ALLOC_GROW(ctx->commits.list, ctx->commits.nr + 1, ctx->commits.alloc);
1627                 ctx->commits.list[ctx->commits.nr] = lookup_commit(ctx->r, &ctx->oids.list[i]);
1628
1629                 if (ctx->split && flags != COMMIT_GRAPH_SPLIT_REPLACE &&
1630                     commit_graph_position(ctx->commits.list[ctx->commits.nr]) != COMMIT_NOT_FROM_GRAPH)
1631                         continue;
1632
1633                 if (ctx->split && flags == COMMIT_GRAPH_SPLIT_REPLACE)
1634                         parse_commit(ctx->commits.list[ctx->commits.nr]);
1635                 else
1636                         parse_commit_no_graph(ctx->commits.list[ctx->commits.nr]);
1637
1638                 num_parents = commit_list_count(ctx->commits.list[ctx->commits.nr]->parents);
1639                 if (num_parents > 2)
1640                         ctx->num_extra_edges += num_parents - 1;
1641
1642                 ctx->commits.nr++;
1643         }
1644         stop_progress(&ctx->progress);
1645 }
1646
1647 static int write_graph_chunk_base_1(struct hashfile *f,
1648                                     struct commit_graph *g)
1649 {
1650         int num = 0;
1651
1652         if (!g)
1653                 return 0;
1654
1655         num = write_graph_chunk_base_1(f, g->base_graph);
1656         hashwrite(f, g->oid.hash, the_hash_algo->rawsz);
1657         return num + 1;
1658 }
1659
1660 static int write_graph_chunk_base(struct hashfile *f,
1661                                   struct write_commit_graph_context *ctx)
1662 {
1663         int num = write_graph_chunk_base_1(f, ctx->new_base_graph);
1664
1665         if (num != ctx->num_commit_graphs_after - 1) {
1666                 error(_("failed to write correct number of base graph ids"));
1667                 return -1;
1668         }
1669
1670         return 0;
1671 }
1672
1673 typedef int (*chunk_write_fn)(struct hashfile *f,
1674                               struct write_commit_graph_context *ctx);
1675
1676 struct chunk_info {
1677         uint32_t id;
1678         uint64_t size;
1679         chunk_write_fn write_fn;
1680 };
1681
1682 static int write_commit_graph_file(struct write_commit_graph_context *ctx)
1683 {
1684         uint32_t i;
1685         int fd;
1686         struct hashfile *f;
1687         struct lock_file lk = LOCK_INIT;
1688         struct chunk_info chunks[MAX_NUM_CHUNKS + 1];
1689         const unsigned hashsz = the_hash_algo->rawsz;
1690         struct strbuf progress_title = STRBUF_INIT;
1691         int num_chunks = 3;
1692         uint64_t chunk_offset;
1693         struct object_id file_hash;
1694
1695         if (ctx->split) {
1696                 struct strbuf tmp_file = STRBUF_INIT;
1697
1698                 strbuf_addf(&tmp_file,
1699                             "%s/info/commit-graphs/tmp_graph_XXXXXX",
1700                             ctx->odb->path);
1701                 ctx->graph_name = strbuf_detach(&tmp_file, NULL);
1702         } else {
1703                 ctx->graph_name = get_commit_graph_filename(ctx->odb);
1704         }
1705
1706         if (safe_create_leading_directories(ctx->graph_name)) {
1707                 UNLEAK(ctx->graph_name);
1708                 error(_("unable to create leading directories of %s"),
1709                         ctx->graph_name);
1710                 return -1;
1711         }
1712
1713         if (ctx->split) {
1714                 char *lock_name = get_chain_filename(ctx->odb);
1715
1716                 hold_lock_file_for_update_mode(&lk, lock_name,
1717                                                LOCK_DIE_ON_ERROR, 0444);
1718
1719                 fd = git_mkstemp_mode(ctx->graph_name, 0444);
1720                 if (fd < 0) {
1721                         error(_("unable to create temporary graph layer"));
1722                         return -1;
1723                 }
1724
1725                 if (adjust_shared_perm(ctx->graph_name)) {
1726                         error(_("unable to adjust shared permissions for '%s'"),
1727                               ctx->graph_name);
1728                         return -1;
1729                 }
1730
1731                 f = hashfd(fd, ctx->graph_name);
1732         } else {
1733                 hold_lock_file_for_update_mode(&lk, ctx->graph_name,
1734                                                LOCK_DIE_ON_ERROR, 0444);
1735                 fd = lk.tempfile->fd;
1736                 f = hashfd(lk.tempfile->fd, lk.tempfile->filename.buf);
1737         }
1738
1739         chunks[0].id = GRAPH_CHUNKID_OIDFANOUT;
1740         chunks[0].size = GRAPH_FANOUT_SIZE;
1741         chunks[0].write_fn = write_graph_chunk_fanout;
1742         chunks[1].id = GRAPH_CHUNKID_OIDLOOKUP;
1743         chunks[1].size = hashsz * ctx->commits.nr;
1744         chunks[1].write_fn = write_graph_chunk_oids;
1745         chunks[2].id = GRAPH_CHUNKID_DATA;
1746         chunks[2].size = (hashsz + 16) * ctx->commits.nr;
1747         chunks[2].write_fn = write_graph_chunk_data;
1748         if (ctx->num_extra_edges) {
1749                 chunks[num_chunks].id = GRAPH_CHUNKID_EXTRAEDGES;
1750                 chunks[num_chunks].size = 4 * ctx->num_extra_edges;
1751                 chunks[num_chunks].write_fn = write_graph_chunk_extra_edges;
1752                 num_chunks++;
1753         }
1754         if (ctx->changed_paths) {
1755                 chunks[num_chunks].id = GRAPH_CHUNKID_BLOOMINDEXES;
1756                 chunks[num_chunks].size = sizeof(uint32_t) * ctx->commits.nr;
1757                 chunks[num_chunks].write_fn = write_graph_chunk_bloom_indexes;
1758                 num_chunks++;
1759                 chunks[num_chunks].id = GRAPH_CHUNKID_BLOOMDATA;
1760                 chunks[num_chunks].size = sizeof(uint32_t) * 3
1761                                           + ctx->total_bloom_filter_data_size;
1762                 chunks[num_chunks].write_fn = write_graph_chunk_bloom_data;
1763                 num_chunks++;
1764         }
1765         if (ctx->num_commit_graphs_after > 1) {
1766                 chunks[num_chunks].id = GRAPH_CHUNKID_BASE;
1767                 chunks[num_chunks].size = hashsz * (ctx->num_commit_graphs_after - 1);
1768                 chunks[num_chunks].write_fn = write_graph_chunk_base;
1769                 num_chunks++;
1770         }
1771
1772         chunks[num_chunks].id = 0;
1773         chunks[num_chunks].size = 0;
1774
1775         hashwrite_be32(f, GRAPH_SIGNATURE);
1776
1777         hashwrite_u8(f, GRAPH_VERSION);
1778         hashwrite_u8(f, oid_version());
1779         hashwrite_u8(f, num_chunks);
1780         hashwrite_u8(f, ctx->num_commit_graphs_after - 1);
1781
1782         chunk_offset = 8 + (num_chunks + 1) * GRAPH_CHUNKLOOKUP_WIDTH;
1783         for (i = 0; i <= num_chunks; i++) {
1784                 uint32_t chunk_write[3];
1785
1786                 chunk_write[0] = htonl(chunks[i].id);
1787                 chunk_write[1] = htonl(chunk_offset >> 32);
1788                 chunk_write[2] = htonl(chunk_offset & 0xffffffff);
1789                 hashwrite(f, chunk_write, 12);
1790
1791                 chunk_offset += chunks[i].size;
1792         }
1793
1794         if (ctx->report_progress) {
1795                 strbuf_addf(&progress_title,
1796                             Q_("Writing out commit graph in %d pass",
1797                                "Writing out commit graph in %d passes",
1798                                num_chunks),
1799                             num_chunks);
1800                 ctx->progress = start_delayed_progress(
1801                         progress_title.buf,
1802                         num_chunks * ctx->commits.nr);
1803         }
1804
1805         for (i = 0; i < num_chunks; i++) {
1806                 uint64_t start_offset = f->total + f->offset;
1807
1808                 if (chunks[i].write_fn(f, ctx))
1809                         return -1;
1810
1811                 if (f->total + f->offset != start_offset + chunks[i].size)
1812                         BUG("expected to write %"PRId64" bytes to chunk %"PRIx32", but wrote %"PRId64" instead",
1813                             chunks[i].size, chunks[i].id,
1814                             f->total + f->offset - start_offset);
1815         }
1816
1817         stop_progress(&ctx->progress);
1818         strbuf_release(&progress_title);
1819
1820         if (ctx->split && ctx->base_graph_name && ctx->num_commit_graphs_after > 1) {
1821                 char *new_base_hash = xstrdup(oid_to_hex(&ctx->new_base_graph->oid));
1822                 char *new_base_name = get_split_graph_filename(ctx->new_base_graph->odb, new_base_hash);
1823
1824                 free(ctx->commit_graph_filenames_after[ctx->num_commit_graphs_after - 2]);
1825                 free(ctx->commit_graph_hash_after[ctx->num_commit_graphs_after - 2]);
1826                 ctx->commit_graph_filenames_after[ctx->num_commit_graphs_after - 2] = new_base_name;
1827                 ctx->commit_graph_hash_after[ctx->num_commit_graphs_after - 2] = new_base_hash;
1828         }
1829
1830         close_commit_graph(ctx->r->objects);
1831         finalize_hashfile(f, file_hash.hash, CSUM_HASH_IN_STREAM | CSUM_FSYNC);
1832
1833         if (ctx->split) {
1834                 FILE *chainf = fdopen_lock_file(&lk, "w");
1835                 char *final_graph_name;
1836                 int result;
1837
1838                 close(fd);
1839
1840                 if (!chainf) {
1841                         error(_("unable to open commit-graph chain file"));
1842                         return -1;
1843                 }
1844
1845                 if (ctx->base_graph_name) {
1846                         const char *dest;
1847                         int idx = ctx->num_commit_graphs_after - 1;
1848                         if (ctx->num_commit_graphs_after > 1)
1849                                 idx--;
1850
1851                         dest = ctx->commit_graph_filenames_after[idx];
1852
1853                         if (strcmp(ctx->base_graph_name, dest)) {
1854                                 result = rename(ctx->base_graph_name, dest);
1855
1856                                 if (result) {
1857                                         error(_("failed to rename base commit-graph file"));
1858                                         return -1;
1859                                 }
1860                         }
1861                 } else {
1862                         char *graph_name = get_commit_graph_filename(ctx->odb);
1863                         unlink(graph_name);
1864                 }
1865
1866                 ctx->commit_graph_hash_after[ctx->num_commit_graphs_after - 1] = xstrdup(oid_to_hex(&file_hash));
1867                 final_graph_name = get_split_graph_filename(ctx->odb,
1868                                         ctx->commit_graph_hash_after[ctx->num_commit_graphs_after - 1]);
1869                 ctx->commit_graph_filenames_after[ctx->num_commit_graphs_after - 1] = final_graph_name;
1870
1871                 result = rename(ctx->graph_name, final_graph_name);
1872
1873                 for (i = 0; i < ctx->num_commit_graphs_after; i++)
1874                         fprintf(lk.tempfile->fp, "%s\n", ctx->commit_graph_hash_after[i]);
1875
1876                 if (result) {
1877                         error(_("failed to rename temporary commit-graph file"));
1878                         return -1;
1879                 }
1880         }
1881
1882         commit_lock_file(&lk);
1883
1884         return 0;
1885 }
1886
1887 static void split_graph_merge_strategy(struct write_commit_graph_context *ctx)
1888 {
1889         struct commit_graph *g;
1890         uint32_t num_commits;
1891         enum commit_graph_split_flags flags = COMMIT_GRAPH_SPLIT_UNSPECIFIED;
1892         uint32_t i;
1893
1894         int max_commits = 0;
1895         int size_mult = 2;
1896
1897         if (ctx->split_opts) {
1898                 max_commits = ctx->split_opts->max_commits;
1899
1900                 if (ctx->split_opts->size_multiple)
1901                         size_mult = ctx->split_opts->size_multiple;
1902
1903                 flags = ctx->split_opts->flags;
1904         }
1905
1906         g = ctx->r->objects->commit_graph;
1907         num_commits = ctx->commits.nr;
1908         if (flags == COMMIT_GRAPH_SPLIT_REPLACE)
1909                 ctx->num_commit_graphs_after = 1;
1910         else
1911                 ctx->num_commit_graphs_after = ctx->num_commit_graphs_before + 1;
1912
1913         if (flags != COMMIT_GRAPH_SPLIT_MERGE_PROHIBITED &&
1914             flags != COMMIT_GRAPH_SPLIT_REPLACE) {
1915                 while (g && (g->num_commits <= size_mult * num_commits ||
1916                             (max_commits && num_commits > max_commits))) {
1917                         if (g->odb != ctx->odb)
1918                                 break;
1919
1920                         num_commits += g->num_commits;
1921                         g = g->base_graph;
1922
1923                         ctx->num_commit_graphs_after--;
1924                 }
1925         }
1926
1927         if (flags != COMMIT_GRAPH_SPLIT_REPLACE)
1928                 ctx->new_base_graph = g;
1929         else if (ctx->num_commit_graphs_after != 1)
1930                 BUG("split_graph_merge_strategy: num_commit_graphs_after "
1931                     "should be 1 with --split=replace");
1932
1933         if (ctx->num_commit_graphs_after == 2) {
1934                 char *old_graph_name = get_commit_graph_filename(g->odb);
1935
1936                 if (!strcmp(g->filename, old_graph_name) &&
1937                     g->odb != ctx->odb) {
1938                         ctx->num_commit_graphs_after = 1;
1939                         ctx->new_base_graph = NULL;
1940                 }
1941
1942                 free(old_graph_name);
1943         }
1944
1945         CALLOC_ARRAY(ctx->commit_graph_filenames_after, ctx->num_commit_graphs_after);
1946         CALLOC_ARRAY(ctx->commit_graph_hash_after, ctx->num_commit_graphs_after);
1947
1948         for (i = 0; i < ctx->num_commit_graphs_after &&
1949                     i < ctx->num_commit_graphs_before; i++)
1950                 ctx->commit_graph_filenames_after[i] = xstrdup(ctx->commit_graph_filenames_before[i]);
1951
1952         i = ctx->num_commit_graphs_before - 1;
1953         g = ctx->r->objects->commit_graph;
1954
1955         while (g) {
1956                 if (i < ctx->num_commit_graphs_after)
1957                         ctx->commit_graph_hash_after[i] = xstrdup(oid_to_hex(&g->oid));
1958
1959                 i--;
1960                 g = g->base_graph;
1961         }
1962 }
1963
1964 static void merge_commit_graph(struct write_commit_graph_context *ctx,
1965                                struct commit_graph *g)
1966 {
1967         uint32_t i;
1968         uint32_t offset = g->num_commits_in_base;
1969
1970         ALLOC_GROW(ctx->commits.list, ctx->commits.nr + g->num_commits, ctx->commits.alloc);
1971
1972         for (i = 0; i < g->num_commits; i++) {
1973                 struct object_id oid;
1974                 struct commit *result;
1975
1976                 display_progress(ctx->progress, i + 1);
1977
1978                 load_oid_from_graph(g, i + offset, &oid);
1979
1980                 /* only add commits if they still exist in the repo */
1981                 result = lookup_commit_reference_gently(ctx->r, &oid, 1);
1982
1983                 if (result) {
1984                         ctx->commits.list[ctx->commits.nr] = result;
1985                         ctx->commits.nr++;
1986                 }
1987         }
1988 }
1989
1990 static int commit_compare(const void *_a, const void *_b)
1991 {
1992         const struct commit *a = *(const struct commit **)_a;
1993         const struct commit *b = *(const struct commit **)_b;
1994         return oidcmp(&a->object.oid, &b->object.oid);
1995 }
1996
1997 static void sort_and_scan_merged_commits(struct write_commit_graph_context *ctx)
1998 {
1999         uint32_t i;
2000
2001         if (ctx->report_progress)
2002                 ctx->progress = start_delayed_progress(
2003                                         _("Scanning merged commits"),
2004                                         ctx->commits.nr);
2005
2006         QSORT(ctx->commits.list, ctx->commits.nr, commit_compare);
2007
2008         ctx->num_extra_edges = 0;
2009         for (i = 0; i < ctx->commits.nr; i++) {
2010                 display_progress(ctx->progress, i);
2011
2012                 if (i && oideq(&ctx->commits.list[i - 1]->object.oid,
2013                           &ctx->commits.list[i]->object.oid)) {
2014                         die(_("unexpected duplicate commit id %s"),
2015                             oid_to_hex(&ctx->commits.list[i]->object.oid));
2016                 } else {
2017                         unsigned int num_parents;
2018
2019                         num_parents = commit_list_count(ctx->commits.list[i]->parents);
2020                         if (num_parents > 2)
2021                                 ctx->num_extra_edges += num_parents - 1;
2022                 }
2023         }
2024
2025         stop_progress(&ctx->progress);
2026 }
2027
2028 static void merge_commit_graphs(struct write_commit_graph_context *ctx)
2029 {
2030         struct commit_graph *g = ctx->r->objects->commit_graph;
2031         uint32_t current_graph_number = ctx->num_commit_graphs_before;
2032
2033         while (g && current_graph_number >= ctx->num_commit_graphs_after) {
2034                 current_graph_number--;
2035
2036                 if (ctx->report_progress)
2037                         ctx->progress = start_delayed_progress(_("Merging commit-graph"), 0);
2038
2039                 merge_commit_graph(ctx, g);
2040                 stop_progress(&ctx->progress);
2041
2042                 g = g->base_graph;
2043         }
2044
2045         if (g) {
2046                 ctx->new_base_graph = g;
2047                 ctx->new_num_commits_in_base = g->num_commits + g->num_commits_in_base;
2048         }
2049
2050         if (ctx->new_base_graph)
2051                 ctx->base_graph_name = xstrdup(ctx->new_base_graph->filename);
2052
2053         sort_and_scan_merged_commits(ctx);
2054 }
2055
2056 static void mark_commit_graphs(struct write_commit_graph_context *ctx)
2057 {
2058         uint32_t i;
2059         time_t now = time(NULL);
2060
2061         for (i = ctx->num_commit_graphs_after - 1; i < ctx->num_commit_graphs_before; i++) {
2062                 struct stat st;
2063                 struct utimbuf updated_time;
2064
2065                 stat(ctx->commit_graph_filenames_before[i], &st);
2066
2067                 updated_time.actime = st.st_atime;
2068                 updated_time.modtime = now;
2069                 utime(ctx->commit_graph_filenames_before[i], &updated_time);
2070         }
2071 }
2072
2073 static void expire_commit_graphs(struct write_commit_graph_context *ctx)
2074 {
2075         struct strbuf path = STRBUF_INIT;
2076         DIR *dir;
2077         struct dirent *de;
2078         size_t dirnamelen;
2079         timestamp_t expire_time = time(NULL);
2080
2081         if (ctx->split_opts && ctx->split_opts->expire_time)
2082                 expire_time = ctx->split_opts->expire_time;
2083         if (!ctx->split) {
2084                 char *chain_file_name = get_chain_filename(ctx->odb);
2085                 unlink(chain_file_name);
2086                 free(chain_file_name);
2087                 ctx->num_commit_graphs_after = 0;
2088         }
2089
2090         strbuf_addstr(&path, ctx->odb->path);
2091         strbuf_addstr(&path, "/info/commit-graphs");
2092         dir = opendir(path.buf);
2093
2094         if (!dir)
2095                 goto out;
2096
2097         strbuf_addch(&path, '/');
2098         dirnamelen = path.len;
2099         while ((de = readdir(dir)) != NULL) {
2100                 struct stat st;
2101                 uint32_t i, found = 0;
2102
2103                 strbuf_setlen(&path, dirnamelen);
2104                 strbuf_addstr(&path, de->d_name);
2105
2106                 stat(path.buf, &st);
2107
2108                 if (st.st_mtime > expire_time)
2109                         continue;
2110                 if (path.len < 6 || strcmp(path.buf + path.len - 6, ".graph"))
2111                         continue;
2112
2113                 for (i = 0; i < ctx->num_commit_graphs_after; i++) {
2114                         if (!strcmp(ctx->commit_graph_filenames_after[i],
2115                                     path.buf)) {
2116                                 found = 1;
2117                                 break;
2118                         }
2119                 }
2120
2121                 if (!found)
2122                         unlink(path.buf);
2123         }
2124
2125 out:
2126         strbuf_release(&path);
2127 }
2128
2129 int write_commit_graph(struct object_directory *odb,
2130                        struct string_list *pack_indexes,
2131                        struct oidset *commits,
2132                        enum commit_graph_write_flags flags,
2133                        const struct split_commit_graph_opts *split_opts)
2134 {
2135         struct write_commit_graph_context *ctx;
2136         uint32_t i, count_distinct = 0;
2137         int res = 0;
2138         int replace = 0;
2139         struct bloom_filter_settings bloom_settings = DEFAULT_BLOOM_FILTER_SETTINGS;
2140
2141         if (!commit_graph_compatible(the_repository))
2142                 return 0;
2143
2144         ctx = xcalloc(1, sizeof(struct write_commit_graph_context));
2145         ctx->r = the_repository;
2146         ctx->odb = odb;
2147         ctx->append = flags & COMMIT_GRAPH_WRITE_APPEND ? 1 : 0;
2148         ctx->report_progress = flags & COMMIT_GRAPH_WRITE_PROGRESS ? 1 : 0;
2149         ctx->split = flags & COMMIT_GRAPH_WRITE_SPLIT ? 1 : 0;
2150         ctx->split_opts = split_opts;
2151         ctx->total_bloom_filter_data_size = 0;
2152
2153         bloom_settings.bits_per_entry = git_env_ulong("GIT_TEST_BLOOM_SETTINGS_BITS_PER_ENTRY",
2154                                                       bloom_settings.bits_per_entry);
2155         bloom_settings.num_hashes = git_env_ulong("GIT_TEST_BLOOM_SETTINGS_NUM_HASHES",
2156                                                   bloom_settings.num_hashes);
2157         bloom_settings.max_changed_paths = git_env_ulong("GIT_TEST_BLOOM_SETTINGS_MAX_CHANGED_PATHS",
2158                                                          bloom_settings.max_changed_paths);
2159         ctx->bloom_settings = &bloom_settings;
2160
2161         if (flags & COMMIT_GRAPH_WRITE_BLOOM_FILTERS)
2162                 ctx->changed_paths = 1;
2163         if (!(flags & COMMIT_GRAPH_NO_WRITE_BLOOM_FILTERS)) {
2164                 struct commit_graph *g;
2165                 prepare_commit_graph_one(ctx->r, ctx->odb);
2166
2167                 g = ctx->r->objects->commit_graph;
2168
2169                 /* We have changed-paths already. Keep them in the next graph */
2170                 if (g && g->chunk_bloom_data) {
2171                         ctx->changed_paths = 1;
2172                         ctx->bloom_settings = g->bloom_filter_settings;
2173                 }
2174         }
2175
2176         if (ctx->split) {
2177                 struct commit_graph *g;
2178                 prepare_commit_graph(ctx->r);
2179
2180                 g = ctx->r->objects->commit_graph;
2181
2182                 while (g) {
2183                         ctx->num_commit_graphs_before++;
2184                         g = g->base_graph;
2185                 }
2186
2187                 if (ctx->num_commit_graphs_before) {
2188                         ALLOC_ARRAY(ctx->commit_graph_filenames_before, ctx->num_commit_graphs_before);
2189                         i = ctx->num_commit_graphs_before;
2190                         g = ctx->r->objects->commit_graph;
2191
2192                         while (g) {
2193                                 ctx->commit_graph_filenames_before[--i] = xstrdup(g->filename);
2194                                 g = g->base_graph;
2195                         }
2196                 }
2197
2198                 if (ctx->split_opts)
2199                         replace = ctx->split_opts->flags & COMMIT_GRAPH_SPLIT_REPLACE;
2200         }
2201
2202         ctx->approx_nr_objects = approximate_object_count();
2203         ctx->oids.alloc = ctx->approx_nr_objects / 32;
2204
2205         if (ctx->split && split_opts && ctx->oids.alloc > split_opts->max_commits)
2206                 ctx->oids.alloc = split_opts->max_commits;
2207
2208         if (ctx->append) {
2209                 prepare_commit_graph_one(ctx->r, ctx->odb);
2210                 if (ctx->r->objects->commit_graph)
2211                         ctx->oids.alloc += ctx->r->objects->commit_graph->num_commits;
2212         }
2213
2214         if (ctx->oids.alloc < 1024)
2215                 ctx->oids.alloc = 1024;
2216         ALLOC_ARRAY(ctx->oids.list, ctx->oids.alloc);
2217
2218         if (ctx->append && ctx->r->objects->commit_graph) {
2219                 struct commit_graph *g = ctx->r->objects->commit_graph;
2220                 for (i = 0; i < g->num_commits; i++) {
2221                         const unsigned char *hash = g->chunk_oid_lookup + g->hash_len * i;
2222                         hashcpy(ctx->oids.list[ctx->oids.nr++].hash, hash);
2223                 }
2224         }
2225
2226         if (pack_indexes) {
2227                 ctx->order_by_pack = 1;
2228                 if ((res = fill_oids_from_packs(ctx, pack_indexes)))
2229                         goto cleanup;
2230         }
2231
2232         if (commits) {
2233                 if ((res = fill_oids_from_commits(ctx, commits)))
2234                         goto cleanup;
2235         }
2236
2237         if (!pack_indexes && !commits) {
2238                 ctx->order_by_pack = 1;
2239                 fill_oids_from_all_packs(ctx);
2240         }
2241
2242         close_reachable(ctx);
2243
2244         count_distinct = count_distinct_commits(ctx);
2245
2246         if (count_distinct >= GRAPH_EDGE_LAST_MASK) {
2247                 error(_("the commit graph format cannot write %d commits"), count_distinct);
2248                 res = -1;
2249                 goto cleanup;
2250         }
2251
2252         ctx->commits.alloc = count_distinct;
2253         ALLOC_ARRAY(ctx->commits.list, ctx->commits.alloc);
2254
2255         copy_oids_to_commits(ctx);
2256
2257         if (ctx->commits.nr >= GRAPH_EDGE_LAST_MASK) {
2258                 error(_("too many commits to write graph"));
2259                 res = -1;
2260                 goto cleanup;
2261         }
2262
2263         if (!ctx->commits.nr && !replace)
2264                 goto cleanup;
2265
2266         if (ctx->split) {
2267                 split_graph_merge_strategy(ctx);
2268
2269                 if (!replace)
2270                         merge_commit_graphs(ctx);
2271         } else
2272                 ctx->num_commit_graphs_after = 1;
2273
2274         compute_generation_numbers(ctx);
2275
2276         if (ctx->changed_paths)
2277                 compute_bloom_filters(ctx);
2278
2279         res = write_commit_graph_file(ctx);
2280
2281         if (ctx->split)
2282                 mark_commit_graphs(ctx);
2283
2284         expire_commit_graphs(ctx);
2285
2286 cleanup:
2287         free(ctx->graph_name);
2288         free(ctx->commits.list);
2289         free(ctx->oids.list);
2290
2291         if (ctx->commit_graph_filenames_after) {
2292                 for (i = 0; i < ctx->num_commit_graphs_after; i++) {
2293                         free(ctx->commit_graph_filenames_after[i]);
2294                         free(ctx->commit_graph_hash_after[i]);
2295                 }
2296
2297                 for (i = 0; i < ctx->num_commit_graphs_before; i++)
2298                         free(ctx->commit_graph_filenames_before[i]);
2299
2300                 free(ctx->commit_graph_filenames_after);
2301                 free(ctx->commit_graph_filenames_before);
2302                 free(ctx->commit_graph_hash_after);
2303         }
2304
2305         free(ctx);
2306
2307         return res;
2308 }
2309
2310 #define VERIFY_COMMIT_GRAPH_ERROR_HASH 2
2311 static int verify_commit_graph_error;
2312
2313 static void graph_report(const char *fmt, ...)
2314 {
2315         va_list ap;
2316
2317         verify_commit_graph_error = 1;
2318         va_start(ap, fmt);
2319         vfprintf(stderr, fmt, ap);
2320         fprintf(stderr, "\n");
2321         va_end(ap);
2322 }
2323
2324 #define GENERATION_ZERO_EXISTS 1
2325 #define GENERATION_NUMBER_EXISTS 2
2326
2327 int verify_commit_graph(struct repository *r, struct commit_graph *g, int flags)
2328 {
2329         uint32_t i, cur_fanout_pos = 0;
2330         struct object_id prev_oid, cur_oid, checksum;
2331         int generation_zero = 0;
2332         struct hashfile *f;
2333         int devnull;
2334         struct progress *progress = NULL;
2335         int local_error = 0;
2336
2337         if (!g) {
2338                 graph_report("no commit-graph file loaded");
2339                 return 1;
2340         }
2341
2342         verify_commit_graph_error = verify_commit_graph_lite(g);
2343         if (verify_commit_graph_error)
2344                 return verify_commit_graph_error;
2345
2346         devnull = open("/dev/null", O_WRONLY);
2347         f = hashfd(devnull, NULL);
2348         hashwrite(f, g->data, g->data_len - g->hash_len);
2349         finalize_hashfile(f, checksum.hash, CSUM_CLOSE);
2350         if (!hasheq(checksum.hash, g->data + g->data_len - g->hash_len)) {
2351                 graph_report(_("the commit-graph file has incorrect checksum and is likely corrupt"));
2352                 verify_commit_graph_error = VERIFY_COMMIT_GRAPH_ERROR_HASH;
2353         }
2354
2355         for (i = 0; i < g->num_commits; i++) {
2356                 struct commit *graph_commit;
2357
2358                 hashcpy(cur_oid.hash, g->chunk_oid_lookup + g->hash_len * i);
2359
2360                 if (i && oidcmp(&prev_oid, &cur_oid) >= 0)
2361                         graph_report(_("commit-graph has incorrect OID order: %s then %s"),
2362                                      oid_to_hex(&prev_oid),
2363                                      oid_to_hex(&cur_oid));
2364
2365                 oidcpy(&prev_oid, &cur_oid);
2366
2367                 while (cur_oid.hash[0] > cur_fanout_pos) {
2368                         uint32_t fanout_value = get_be32(g->chunk_oid_fanout + cur_fanout_pos);
2369
2370                         if (i != fanout_value)
2371                                 graph_report(_("commit-graph has incorrect fanout value: fanout[%d] = %u != %u"),
2372                                              cur_fanout_pos, fanout_value, i);
2373                         cur_fanout_pos++;
2374                 }
2375
2376                 graph_commit = lookup_commit(r, &cur_oid);
2377                 if (!parse_commit_in_graph_one(r, g, graph_commit))
2378                         graph_report(_("failed to parse commit %s from commit-graph"),
2379                                      oid_to_hex(&cur_oid));
2380         }
2381
2382         while (cur_fanout_pos < 256) {
2383                 uint32_t fanout_value = get_be32(g->chunk_oid_fanout + cur_fanout_pos);
2384
2385                 if (g->num_commits != fanout_value)
2386                         graph_report(_("commit-graph has incorrect fanout value: fanout[%d] = %u != %u"),
2387                                      cur_fanout_pos, fanout_value, i);
2388
2389                 cur_fanout_pos++;
2390         }
2391
2392         if (verify_commit_graph_error & ~VERIFY_COMMIT_GRAPH_ERROR_HASH)
2393                 return verify_commit_graph_error;
2394
2395         if (flags & COMMIT_GRAPH_WRITE_PROGRESS)
2396                 progress = start_progress(_("Verifying commits in commit graph"),
2397                                         g->num_commits);
2398
2399         for (i = 0; i < g->num_commits; i++) {
2400                 struct commit *graph_commit, *odb_commit;
2401                 struct commit_list *graph_parents, *odb_parents;
2402                 uint32_t max_generation = 0;
2403                 uint32_t generation;
2404
2405                 display_progress(progress, i + 1);
2406                 hashcpy(cur_oid.hash, g->chunk_oid_lookup + g->hash_len * i);
2407
2408                 graph_commit = lookup_commit(r, &cur_oid);
2409                 odb_commit = (struct commit *)create_object(r, &cur_oid, alloc_commit_node(r));
2410                 if (parse_commit_internal(odb_commit, 0, 0)) {
2411                         graph_report(_("failed to parse commit %s from object database for commit-graph"),
2412                                      oid_to_hex(&cur_oid));
2413                         continue;
2414                 }
2415
2416                 if (!oideq(&get_commit_tree_in_graph_one(r, g, graph_commit)->object.oid,
2417                            get_commit_tree_oid(odb_commit)))
2418                         graph_report(_("root tree OID for commit %s in commit-graph is %s != %s"),
2419                                      oid_to_hex(&cur_oid),
2420                                      oid_to_hex(get_commit_tree_oid(graph_commit)),
2421                                      oid_to_hex(get_commit_tree_oid(odb_commit)));
2422
2423                 graph_parents = graph_commit->parents;
2424                 odb_parents = odb_commit->parents;
2425
2426                 while (graph_parents) {
2427                         if (odb_parents == NULL) {
2428                                 graph_report(_("commit-graph parent list for commit %s is too long"),
2429                                              oid_to_hex(&cur_oid));
2430                                 break;
2431                         }
2432
2433                         /* parse parent in case it is in a base graph */
2434                         parse_commit_in_graph_one(r, g, graph_parents->item);
2435
2436                         if (!oideq(&graph_parents->item->object.oid, &odb_parents->item->object.oid))
2437                                 graph_report(_("commit-graph parent for %s is %s != %s"),
2438                                              oid_to_hex(&cur_oid),
2439                                              oid_to_hex(&graph_parents->item->object.oid),
2440                                              oid_to_hex(&odb_parents->item->object.oid));
2441
2442                         generation = commit_graph_generation(graph_parents->item);
2443                         if (generation > max_generation)
2444                                 max_generation = generation;
2445
2446                         graph_parents = graph_parents->next;
2447                         odb_parents = odb_parents->next;
2448                 }
2449
2450                 if (odb_parents != NULL)
2451                         graph_report(_("commit-graph parent list for commit %s terminates early"),
2452                                      oid_to_hex(&cur_oid));
2453
2454                 if (!commit_graph_generation(graph_commit)) {
2455                         if (generation_zero == GENERATION_NUMBER_EXISTS)
2456                                 graph_report(_("commit-graph has generation number zero for commit %s, but non-zero elsewhere"),
2457                                              oid_to_hex(&cur_oid));
2458                         generation_zero = GENERATION_ZERO_EXISTS;
2459                 } else if (generation_zero == GENERATION_ZERO_EXISTS)
2460                         graph_report(_("commit-graph has non-zero generation number for commit %s, but zero elsewhere"),
2461                                      oid_to_hex(&cur_oid));
2462
2463                 if (generation_zero == GENERATION_ZERO_EXISTS)
2464                         continue;
2465
2466                 /*
2467                  * If one of our parents has generation GENERATION_NUMBER_MAX, then
2468                  * our generation is also GENERATION_NUMBER_MAX. Decrement to avoid
2469                  * extra logic in the following condition.
2470                  */
2471                 if (max_generation == GENERATION_NUMBER_MAX)
2472                         max_generation--;
2473
2474                 generation = commit_graph_generation(graph_commit);
2475                 if (generation != max_generation + 1)
2476                         graph_report(_("commit-graph generation for commit %s is %u != %u"),
2477                                      oid_to_hex(&cur_oid),
2478                                      generation,
2479                                      max_generation + 1);
2480
2481                 if (graph_commit->date != odb_commit->date)
2482                         graph_report(_("commit date for commit %s in commit-graph is %"PRItime" != %"PRItime),
2483                                      oid_to_hex(&cur_oid),
2484                                      graph_commit->date,
2485                                      odb_commit->date);
2486         }
2487         stop_progress(&progress);
2488
2489         local_error = verify_commit_graph_error;
2490
2491         if (!(flags & COMMIT_GRAPH_VERIFY_SHALLOW) && g->base_graph)
2492                 local_error |= verify_commit_graph(r, g->base_graph, flags);
2493
2494         return local_error;
2495 }
2496
2497 void free_commit_graph(struct commit_graph *g)
2498 {
2499         if (!g)
2500                 return;
2501         if (g->data) {
2502                 munmap((void *)g->data, g->data_len);
2503                 g->data = NULL;
2504         }
2505         free(g->filename);
2506         free(g->bloom_filter_settings);
2507         free(g);
2508 }
2509
2510 void disable_commit_graph(struct repository *r)
2511 {
2512         r->commit_graph_disabled = 1;
2513 }