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