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