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