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