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