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