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