commit-graph: collapse parameters into flags
[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
26 #define GRAPH_DATA_WIDTH (the_hash_algo->rawsz + 16)
27
28 #define GRAPH_VERSION_1 0x1
29 #define GRAPH_VERSION GRAPH_VERSION_1
30
31 #define GRAPH_EXTRA_EDGES_NEEDED 0x80000000
32 #define GRAPH_EDGE_LAST_MASK 0x7fffffff
33 #define GRAPH_PARENT_NONE 0x70000000
34
35 #define GRAPH_LAST_EDGE 0x80000000
36
37 #define GRAPH_HEADER_SIZE 8
38 #define GRAPH_FANOUT_SIZE (4 * 256)
39 #define GRAPH_CHUNKLOOKUP_WIDTH 12
40 #define GRAPH_MIN_SIZE (GRAPH_HEADER_SIZE + 4 * GRAPH_CHUNKLOOKUP_WIDTH \
41                         + GRAPH_FANOUT_SIZE + the_hash_algo->rawsz)
42
43 char *get_commit_graph_filename(const char *obj_dir)
44 {
45         return xstrfmt("%s/info/commit-graph", obj_dir);
46 }
47
48 static uint8_t oid_version(void)
49 {
50         return 1;
51 }
52
53 static struct commit_graph *alloc_commit_graph(void)
54 {
55         struct commit_graph *g = xcalloc(1, sizeof(*g));
56         g->graph_fd = -1;
57
58         return g;
59 }
60
61 extern int read_replace_refs;
62
63 static int commit_graph_compatible(struct repository *r)
64 {
65         if (!r->gitdir)
66                 return 0;
67
68         if (read_replace_refs) {
69                 prepare_replace_object(r);
70                 if (hashmap_get_size(&r->objects->replace_map->map))
71                         return 0;
72         }
73
74         prepare_commit_graft(r);
75         if (r->parsed_objects && r->parsed_objects->grafts_nr)
76                 return 0;
77         if (is_repository_shallow(r))
78                 return 0;
79
80         return 1;
81 }
82
83 int open_commit_graph(const char *graph_file, int *fd, struct stat *st)
84 {
85         *fd = git_open(graph_file);
86         if (*fd < 0)
87                 return 0;
88         if (fstat(*fd, st)) {
89                 close(*fd);
90                 return 0;
91         }
92         return 1;
93 }
94
95 struct commit_graph *load_commit_graph_one_fd_st(int fd, struct stat *st)
96 {
97         void *graph_map;
98         size_t graph_size;
99         struct commit_graph *ret;
100
101         graph_size = xsize_t(st->st_size);
102
103         if (graph_size < GRAPH_MIN_SIZE) {
104                 close(fd);
105                 error(_("commit-graph file is too small"));
106                 return NULL;
107         }
108         graph_map = xmmap(NULL, graph_size, PROT_READ, MAP_PRIVATE, fd, 0);
109         ret = parse_commit_graph(graph_map, fd, graph_size);
110
111         if (!ret) {
112                 munmap(graph_map, graph_size);
113                 close(fd);
114         }
115
116         return ret;
117 }
118
119 static int verify_commit_graph_lite(struct commit_graph *g)
120 {
121         /*
122          * Basic validation shared between parse_commit_graph()
123          * which'll be called every time the graph is used, and the
124          * much more expensive verify_commit_graph() used by
125          * "commit-graph verify".
126          *
127          * There should only be very basic checks here to ensure that
128          * we don't e.g. segfault in fill_commit_in_graph(), but
129          * because this is a very hot codepath nothing that e.g. loops
130          * over g->num_commits, or runs a checksum on the commit-graph
131          * itself.
132          */
133         if (!g->chunk_oid_fanout) {
134                 error("commit-graph is missing the OID Fanout chunk");
135                 return 1;
136         }
137         if (!g->chunk_oid_lookup) {
138                 error("commit-graph is missing the OID Lookup chunk");
139                 return 1;
140         }
141         if (!g->chunk_commit_data) {
142                 error("commit-graph is missing the Commit Data chunk");
143                 return 1;
144         }
145
146         return 0;
147 }
148
149 struct commit_graph *parse_commit_graph(void *graph_map, int fd,
150                                         size_t graph_size)
151 {
152         const unsigned char *data, *chunk_lookup;
153         uint32_t i;
154         struct commit_graph *graph;
155         uint64_t last_chunk_offset;
156         uint32_t last_chunk_id;
157         uint32_t graph_signature;
158         unsigned char graph_version, hash_version;
159
160         if (!graph_map)
161                 return NULL;
162
163         if (graph_size < GRAPH_MIN_SIZE)
164                 return NULL;
165
166         data = (const unsigned char *)graph_map;
167
168         graph_signature = get_be32(data);
169         if (graph_signature != GRAPH_SIGNATURE) {
170                 error(_("commit-graph signature %X does not match signature %X"),
171                       graph_signature, GRAPH_SIGNATURE);
172                 return NULL;
173         }
174
175         graph_version = *(unsigned char*)(data + 4);
176         if (graph_version != GRAPH_VERSION) {
177                 error(_("commit-graph version %X does not match version %X"),
178                       graph_version, GRAPH_VERSION);
179                 return NULL;
180         }
181
182         hash_version = *(unsigned char*)(data + 5);
183         if (hash_version != oid_version()) {
184                 error(_("commit-graph hash version %X does not match version %X"),
185                       hash_version, oid_version());
186                 return NULL;
187         }
188
189         graph = alloc_commit_graph();
190
191         graph->hash_len = the_hash_algo->rawsz;
192         graph->num_chunks = *(unsigned char*)(data + 6);
193         graph->graph_fd = fd;
194         graph->data = graph_map;
195         graph->data_len = graph_size;
196
197         last_chunk_id = 0;
198         last_chunk_offset = 8;
199         chunk_lookup = data + 8;
200         for (i = 0; i < graph->num_chunks; i++) {
201                 uint32_t chunk_id;
202                 uint64_t chunk_offset;
203                 int chunk_repeated = 0;
204
205                 if (data + graph_size - chunk_lookup <
206                     GRAPH_CHUNKLOOKUP_WIDTH) {
207                         error(_("commit-graph chunk lookup table entry missing; file may be incomplete"));
208                         free(graph);
209                         return NULL;
210                 }
211
212                 chunk_id = get_be32(chunk_lookup + 0);
213                 chunk_offset = get_be64(chunk_lookup + 4);
214
215                 chunk_lookup += GRAPH_CHUNKLOOKUP_WIDTH;
216
217                 if (chunk_offset > graph_size - the_hash_algo->rawsz) {
218                         error(_("commit-graph improper chunk offset %08x%08x"), (uint32_t)(chunk_offset >> 32),
219                               (uint32_t)chunk_offset);
220                         free(graph);
221                         return NULL;
222                 }
223
224                 switch (chunk_id) {
225                 case GRAPH_CHUNKID_OIDFANOUT:
226                         if (graph->chunk_oid_fanout)
227                                 chunk_repeated = 1;
228                         else
229                                 graph->chunk_oid_fanout = (uint32_t*)(data + chunk_offset);
230                         break;
231
232                 case GRAPH_CHUNKID_OIDLOOKUP:
233                         if (graph->chunk_oid_lookup)
234                                 chunk_repeated = 1;
235                         else
236                                 graph->chunk_oid_lookup = data + chunk_offset;
237                         break;
238
239                 case GRAPH_CHUNKID_DATA:
240                         if (graph->chunk_commit_data)
241                                 chunk_repeated = 1;
242                         else
243                                 graph->chunk_commit_data = data + chunk_offset;
244                         break;
245
246                 case GRAPH_CHUNKID_EXTRAEDGES:
247                         if (graph->chunk_extra_edges)
248                                 chunk_repeated = 1;
249                         else
250                                 graph->chunk_extra_edges = data + chunk_offset;
251                         break;
252                 }
253
254                 if (chunk_repeated) {
255                         error(_("commit-graph chunk id %08x appears multiple times"), chunk_id);
256                         free(graph);
257                         return NULL;
258                 }
259
260                 if (last_chunk_id == GRAPH_CHUNKID_OIDLOOKUP)
261                 {
262                         graph->num_commits = (chunk_offset - last_chunk_offset)
263                                              / graph->hash_len;
264                 }
265
266                 last_chunk_id = chunk_id;
267                 last_chunk_offset = chunk_offset;
268         }
269
270         if (verify_commit_graph_lite(graph))
271                 return NULL;
272
273         return graph;
274 }
275
276 static struct commit_graph *load_commit_graph_one(const char *graph_file)
277 {
278
279         struct stat st;
280         int fd;
281         int open_ok = open_commit_graph(graph_file, &fd, &st);
282
283         if (!open_ok)
284                 return NULL;
285
286         return load_commit_graph_one_fd_st(fd, &st);
287 }
288
289 static void prepare_commit_graph_one(struct repository *r, const char *obj_dir)
290 {
291         char *graph_name;
292
293         if (r->objects->commit_graph)
294                 return;
295
296         graph_name = get_commit_graph_filename(obj_dir);
297         r->objects->commit_graph =
298                 load_commit_graph_one(graph_name);
299
300         FREE_AND_NULL(graph_name);
301 }
302
303 /*
304  * Return 1 if commit_graph is non-NULL, and 0 otherwise.
305  *
306  * On the first invocation, this function attemps to load the commit
307  * graph if the_repository is configured to have one.
308  */
309 static int prepare_commit_graph(struct repository *r)
310 {
311         struct object_directory *odb;
312         int config_value;
313
314         if (git_env_bool(GIT_TEST_COMMIT_GRAPH_DIE_ON_LOAD, 0))
315                 die("dying as requested by the '%s' variable on commit-graph load!",
316                     GIT_TEST_COMMIT_GRAPH_DIE_ON_LOAD);
317
318         if (r->objects->commit_graph_attempted)
319                 return !!r->objects->commit_graph;
320         r->objects->commit_graph_attempted = 1;
321
322         if (!git_env_bool(GIT_TEST_COMMIT_GRAPH, 0) &&
323             (repo_config_get_bool(r, "core.commitgraph", &config_value) ||
324             !config_value))
325                 /*
326                  * This repository is not configured to use commit graphs, so
327                  * do not load one. (But report commit_graph_attempted anyway
328                  * so that commit graph loading is not attempted again for this
329                  * repository.)
330                  */
331                 return 0;
332
333         if (!commit_graph_compatible(r))
334                 return 0;
335
336         prepare_alt_odb(r);
337         for (odb = r->objects->odb;
338              !r->objects->commit_graph && odb;
339              odb = odb->next)
340                 prepare_commit_graph_one(r, odb->path);
341         return !!r->objects->commit_graph;
342 }
343
344 int generation_numbers_enabled(struct repository *r)
345 {
346         uint32_t first_generation;
347         struct commit_graph *g;
348         if (!prepare_commit_graph(r))
349                return 0;
350
351         g = r->objects->commit_graph;
352
353         if (!g->num_commits)
354                 return 0;
355
356         first_generation = get_be32(g->chunk_commit_data +
357                                     g->hash_len + 8) >> 2;
358
359         return !!first_generation;
360 }
361
362 void close_commit_graph(struct repository *r)
363 {
364         free_commit_graph(r->objects->commit_graph);
365         r->objects->commit_graph = NULL;
366 }
367
368 static int bsearch_graph(struct commit_graph *g, struct object_id *oid, uint32_t *pos)
369 {
370         return bsearch_hash(oid->hash, g->chunk_oid_fanout,
371                             g->chunk_oid_lookup, g->hash_len, pos);
372 }
373
374 static struct commit_list **insert_parent_or_die(struct repository *r,
375                                                  struct commit_graph *g,
376                                                  uint64_t pos,
377                                                  struct commit_list **pptr)
378 {
379         struct commit *c;
380         struct object_id oid;
381
382         if (pos >= g->num_commits)
383                 die("invalid parent position %"PRIu64, pos);
384
385         hashcpy(oid.hash, g->chunk_oid_lookup + g->hash_len * pos);
386         c = lookup_commit(r, &oid);
387         if (!c)
388                 die(_("could not find commit %s"), oid_to_hex(&oid));
389         c->graph_pos = pos;
390         return &commit_list_insert(c, pptr)->next;
391 }
392
393 static void fill_commit_graph_info(struct commit *item, struct commit_graph *g, uint32_t pos)
394 {
395         const unsigned char *commit_data = g->chunk_commit_data + GRAPH_DATA_WIDTH * pos;
396         item->graph_pos = pos;
397         item->generation = get_be32(commit_data + g->hash_len + 8) >> 2;
398 }
399
400 static int fill_commit_in_graph(struct repository *r,
401                                 struct commit *item,
402                                 struct commit_graph *g, uint32_t pos)
403 {
404         uint32_t edge_value;
405         uint32_t *parent_data_ptr;
406         uint64_t date_low, date_high;
407         struct commit_list **pptr;
408         const unsigned char *commit_data = g->chunk_commit_data + (g->hash_len + 16) * pos;
409
410         item->object.parsed = 1;
411         item->graph_pos = pos;
412
413         item->maybe_tree = NULL;
414
415         date_high = get_be32(commit_data + g->hash_len + 8) & 0x3;
416         date_low = get_be32(commit_data + g->hash_len + 12);
417         item->date = (timestamp_t)((date_high << 32) | date_low);
418
419         item->generation = get_be32(commit_data + g->hash_len + 8) >> 2;
420
421         pptr = &item->parents;
422
423         edge_value = get_be32(commit_data + g->hash_len);
424         if (edge_value == GRAPH_PARENT_NONE)
425                 return 1;
426         pptr = insert_parent_or_die(r, g, edge_value, pptr);
427
428         edge_value = get_be32(commit_data + g->hash_len + 4);
429         if (edge_value == GRAPH_PARENT_NONE)
430                 return 1;
431         if (!(edge_value & GRAPH_EXTRA_EDGES_NEEDED)) {
432                 pptr = insert_parent_or_die(r, g, edge_value, pptr);
433                 return 1;
434         }
435
436         parent_data_ptr = (uint32_t*)(g->chunk_extra_edges +
437                           4 * (uint64_t)(edge_value & GRAPH_EDGE_LAST_MASK));
438         do {
439                 edge_value = get_be32(parent_data_ptr);
440                 pptr = insert_parent_or_die(r, g,
441                                             edge_value & GRAPH_EDGE_LAST_MASK,
442                                             pptr);
443                 parent_data_ptr++;
444         } while (!(edge_value & GRAPH_LAST_EDGE));
445
446         return 1;
447 }
448
449 static int find_commit_in_graph(struct commit *item, struct commit_graph *g, uint32_t *pos)
450 {
451         if (item->graph_pos != COMMIT_NOT_FROM_GRAPH) {
452                 *pos = item->graph_pos;
453                 return 1;
454         } else {
455                 return bsearch_graph(g, &(item->object.oid), pos);
456         }
457 }
458
459 static int parse_commit_in_graph_one(struct repository *r,
460                                      struct commit_graph *g,
461                                      struct commit *item)
462 {
463         uint32_t pos;
464
465         if (item->object.parsed)
466                 return 1;
467
468         if (find_commit_in_graph(item, g, &pos))
469                 return fill_commit_in_graph(r, item, g, pos);
470
471         return 0;
472 }
473
474 int parse_commit_in_graph(struct repository *r, struct commit *item)
475 {
476         if (!prepare_commit_graph(r))
477                 return 0;
478         return parse_commit_in_graph_one(r, r->objects->commit_graph, item);
479 }
480
481 void load_commit_graph_info(struct repository *r, struct commit *item)
482 {
483         uint32_t pos;
484         if (!prepare_commit_graph(r))
485                 return;
486         if (find_commit_in_graph(item, r->objects->commit_graph, &pos))
487                 fill_commit_graph_info(item, r->objects->commit_graph, pos);
488 }
489
490 static struct tree *load_tree_for_commit(struct repository *r,
491                                          struct commit_graph *g,
492                                          struct commit *c)
493 {
494         struct object_id oid;
495         const unsigned char *commit_data = g->chunk_commit_data +
496                                            GRAPH_DATA_WIDTH * (c->graph_pos);
497
498         hashcpy(oid.hash, commit_data);
499         c->maybe_tree = lookup_tree(r, &oid);
500
501         return c->maybe_tree;
502 }
503
504 static struct tree *get_commit_tree_in_graph_one(struct repository *r,
505                                                  struct commit_graph *g,
506                                                  const struct commit *c)
507 {
508         if (c->maybe_tree)
509                 return c->maybe_tree;
510         if (c->graph_pos == COMMIT_NOT_FROM_GRAPH)
511                 BUG("get_commit_tree_in_graph_one called from non-commit-graph commit");
512
513         return load_tree_for_commit(r, g, (struct commit *)c);
514 }
515
516 struct tree *get_commit_tree_in_graph(struct repository *r, const struct commit *c)
517 {
518         return get_commit_tree_in_graph_one(r, r->objects->commit_graph, c);
519 }
520
521 static void write_graph_chunk_fanout(struct hashfile *f,
522                                      struct commit **commits,
523                                      int nr_commits,
524                                      struct progress *progress,
525                                      uint64_t *progress_cnt)
526 {
527         int i, count = 0;
528         struct commit **list = commits;
529
530         /*
531          * Write the first-level table (the list is sorted,
532          * but we use a 256-entry lookup to be able to avoid
533          * having to do eight extra binary search iterations).
534          */
535         for (i = 0; i < 256; i++) {
536                 while (count < nr_commits) {
537                         if ((*list)->object.oid.hash[0] != i)
538                                 break;
539                         display_progress(progress, ++*progress_cnt);
540                         count++;
541                         list++;
542                 }
543
544                 hashwrite_be32(f, count);
545         }
546 }
547
548 static void write_graph_chunk_oids(struct hashfile *f, int hash_len,
549                                    struct commit **commits, int nr_commits,
550                                    struct progress *progress,
551                                    uint64_t *progress_cnt)
552 {
553         struct commit **list = commits;
554         int count;
555         for (count = 0; count < nr_commits; count++, list++) {
556                 display_progress(progress, ++*progress_cnt);
557                 hashwrite(f, (*list)->object.oid.hash, (int)hash_len);
558         }
559 }
560
561 static const unsigned char *commit_to_sha1(size_t index, void *table)
562 {
563         struct commit **commits = table;
564         return commits[index]->object.oid.hash;
565 }
566
567 static void write_graph_chunk_data(struct hashfile *f, int hash_len,
568                                    struct commit **commits, int nr_commits,
569                                    struct progress *progress,
570                                    uint64_t *progress_cnt)
571 {
572         struct commit **list = commits;
573         struct commit **last = commits + nr_commits;
574         uint32_t num_extra_edges = 0;
575
576         while (list < last) {
577                 struct commit_list *parent;
578                 int edge_value;
579                 uint32_t packedDate[2];
580                 display_progress(progress, ++*progress_cnt);
581
582                 parse_commit_no_graph(*list);
583                 hashwrite(f, get_commit_tree_oid(*list)->hash, hash_len);
584
585                 parent = (*list)->parents;
586
587                 if (!parent)
588                         edge_value = GRAPH_PARENT_NONE;
589                 else {
590                         edge_value = sha1_pos(parent->item->object.oid.hash,
591                                               commits,
592                                               nr_commits,
593                                               commit_to_sha1);
594
595                         if (edge_value < 0)
596                                 BUG("missing parent %s for commit %s",
597                                     oid_to_hex(&parent->item->object.oid),
598                                     oid_to_hex(&(*list)->object.oid));
599                 }
600
601                 hashwrite_be32(f, edge_value);
602
603                 if (parent)
604                         parent = parent->next;
605
606                 if (!parent)
607                         edge_value = GRAPH_PARENT_NONE;
608                 else if (parent->next)
609                         edge_value = GRAPH_EXTRA_EDGES_NEEDED | num_extra_edges;
610                 else {
611                         edge_value = sha1_pos(parent->item->object.oid.hash,
612                                               commits,
613                                               nr_commits,
614                                               commit_to_sha1);
615                         if (edge_value < 0)
616                                 BUG("missing parent %s for commit %s",
617                                     oid_to_hex(&parent->item->object.oid),
618                                     oid_to_hex(&(*list)->object.oid));
619                 }
620
621                 hashwrite_be32(f, edge_value);
622
623                 if (edge_value & GRAPH_EXTRA_EDGES_NEEDED) {
624                         do {
625                                 num_extra_edges++;
626                                 parent = parent->next;
627                         } while (parent);
628                 }
629
630                 if (sizeof((*list)->date) > 4)
631                         packedDate[0] = htonl(((*list)->date >> 32) & 0x3);
632                 else
633                         packedDate[0] = 0;
634
635                 packedDate[0] |= htonl((*list)->generation << 2);
636
637                 packedDate[1] = htonl((*list)->date);
638                 hashwrite(f, packedDate, 8);
639
640                 list++;
641         }
642 }
643
644 static void write_graph_chunk_extra_edges(struct hashfile *f,
645                                           struct commit **commits,
646                                           int nr_commits,
647                                           struct progress *progress,
648                                           uint64_t *progress_cnt)
649 {
650         struct commit **list = commits;
651         struct commit **last = commits + nr_commits;
652         struct commit_list *parent;
653
654         while (list < last) {
655                 int num_parents = 0;
656
657                 display_progress(progress, ++*progress_cnt);
658
659                 for (parent = (*list)->parents; num_parents < 3 && parent;
660                      parent = parent->next)
661                         num_parents++;
662
663                 if (num_parents <= 2) {
664                         list++;
665                         continue;
666                 }
667
668                 /* Since num_parents > 2, this initializer is safe. */
669                 for (parent = (*list)->parents->next; parent; parent = parent->next) {
670                         int edge_value = sha1_pos(parent->item->object.oid.hash,
671                                                   commits,
672                                                   nr_commits,
673                                                   commit_to_sha1);
674
675                         if (edge_value < 0)
676                                 BUG("missing parent %s for commit %s",
677                                     oid_to_hex(&parent->item->object.oid),
678                                     oid_to_hex(&(*list)->object.oid));
679                         else if (!parent->next)
680                                 edge_value |= GRAPH_LAST_EDGE;
681
682                         hashwrite_be32(f, edge_value);
683                 }
684
685                 list++;
686         }
687 }
688
689 static int commit_compare(const void *_a, const void *_b)
690 {
691         const struct object_id *a = (const struct object_id *)_a;
692         const struct object_id *b = (const struct object_id *)_b;
693         return oidcmp(a, b);
694 }
695
696 struct packed_commit_list {
697         struct commit **list;
698         int nr;
699         int alloc;
700 };
701
702 struct packed_oid_list {
703         struct object_id *list;
704         int nr;
705         int alloc;
706         struct progress *progress;
707         int progress_done;
708 };
709
710 static int add_packed_commits(const struct object_id *oid,
711                               struct packed_git *pack,
712                               uint32_t pos,
713                               void *data)
714 {
715         struct packed_oid_list *list = (struct packed_oid_list*)data;
716         enum object_type type;
717         off_t offset = nth_packed_object_offset(pack, pos);
718         struct object_info oi = OBJECT_INFO_INIT;
719
720         if (list->progress)
721                 display_progress(list->progress, ++list->progress_done);
722
723         oi.typep = &type;
724         if (packed_object_info(the_repository, pack, offset, &oi) < 0)
725                 die(_("unable to get type of object %s"), oid_to_hex(oid));
726
727         if (type != OBJ_COMMIT)
728                 return 0;
729
730         ALLOC_GROW(list->list, list->nr + 1, list->alloc);
731         oidcpy(&(list->list[list->nr]), oid);
732         list->nr++;
733
734         return 0;
735 }
736
737 static void add_missing_parents(struct packed_oid_list *oids, struct commit *commit)
738 {
739         struct commit_list *parent;
740         for (parent = commit->parents; parent; parent = parent->next) {
741                 if (!(parent->item->object.flags & UNINTERESTING)) {
742                         ALLOC_GROW(oids->list, oids->nr + 1, oids->alloc);
743                         oidcpy(&oids->list[oids->nr], &(parent->item->object.oid));
744                         oids->nr++;
745                         parent->item->object.flags |= UNINTERESTING;
746                 }
747         }
748 }
749
750 static void close_reachable(struct packed_oid_list *oids, int report_progress)
751 {
752         int i;
753         struct commit *commit;
754         struct progress *progress = NULL;
755
756         if (report_progress)
757                 progress = start_delayed_progress(
758                         _("Loading known commits in commit graph"), oids->nr);
759         for (i = 0; i < oids->nr; i++) {
760                 display_progress(progress, i + 1);
761                 commit = lookup_commit(the_repository, &oids->list[i]);
762                 if (commit)
763                         commit->object.flags |= UNINTERESTING;
764         }
765         stop_progress(&progress);
766
767         /*
768          * As this loop runs, oids->nr may grow, but not more
769          * than the number of missing commits in the reachable
770          * closure.
771          */
772         if (report_progress)
773                 progress = start_delayed_progress(
774                         _("Expanding reachable commits in commit graph"), oids->nr);
775         for (i = 0; i < oids->nr; i++) {
776                 display_progress(progress, i + 1);
777                 commit = lookup_commit(the_repository, &oids->list[i]);
778
779                 if (commit && !parse_commit_no_graph(commit))
780                         add_missing_parents(oids, commit);
781         }
782         stop_progress(&progress);
783
784         if (report_progress)
785                 progress = start_delayed_progress(
786                         _("Clearing commit marks in commit graph"), oids->nr);
787         for (i = 0; i < oids->nr; i++) {
788                 display_progress(progress, i + 1);
789                 commit = lookup_commit(the_repository, &oids->list[i]);
790
791                 if (commit)
792                         commit->object.flags &= ~UNINTERESTING;
793         }
794         stop_progress(&progress);
795 }
796
797 static void compute_generation_numbers(struct packed_commit_list* commits,
798                                        int report_progress)
799 {
800         int i;
801         struct commit_list *list = NULL;
802         struct progress *progress = NULL;
803
804         if (report_progress)
805                 progress = start_progress(
806                         _("Computing commit graph generation numbers"),
807                         commits->nr);
808         for (i = 0; i < commits->nr; i++) {
809                 display_progress(progress, i + 1);
810                 if (commits->list[i]->generation != GENERATION_NUMBER_INFINITY &&
811                     commits->list[i]->generation != GENERATION_NUMBER_ZERO)
812                         continue;
813
814                 commit_list_insert(commits->list[i], &list);
815                 while (list) {
816                         struct commit *current = list->item;
817                         struct commit_list *parent;
818                         int all_parents_computed = 1;
819                         uint32_t max_generation = 0;
820
821                         for (parent = current->parents; parent; parent = parent->next) {
822                                 if (parent->item->generation == GENERATION_NUMBER_INFINITY ||
823                                     parent->item->generation == GENERATION_NUMBER_ZERO) {
824                                         all_parents_computed = 0;
825                                         commit_list_insert(parent->item, &list);
826                                         break;
827                                 } else if (parent->item->generation > max_generation) {
828                                         max_generation = parent->item->generation;
829                                 }
830                         }
831
832                         if (all_parents_computed) {
833                                 current->generation = max_generation + 1;
834                                 pop_commit(&list);
835
836                                 if (current->generation > GENERATION_NUMBER_MAX)
837                                         current->generation = GENERATION_NUMBER_MAX;
838                         }
839                 }
840         }
841         stop_progress(&progress);
842 }
843
844 static int add_ref_to_list(const char *refname,
845                            const struct object_id *oid,
846                            int flags, void *cb_data)
847 {
848         struct string_list *list = (struct string_list *)cb_data;
849
850         string_list_append(list, oid_to_hex(oid));
851         return 0;
852 }
853
854 int write_commit_graph_reachable(const char *obj_dir, unsigned int flags)
855 {
856         struct string_list list = STRING_LIST_INIT_DUP;
857         int result;
858
859         for_each_ref(add_ref_to_list, &list);
860         result = write_commit_graph(obj_dir, NULL, &list,
861                                     flags);
862
863         string_list_clear(&list, 0);
864         return result;
865 }
866
867 int write_commit_graph(const char *obj_dir,
868                        struct string_list *pack_indexes,
869                        struct string_list *commit_hex,
870                        unsigned int flags)
871 {
872         struct packed_oid_list oids;
873         struct packed_commit_list commits;
874         struct hashfile *f;
875         uint32_t i, count_distinct = 0;
876         char *graph_name = NULL;
877         struct lock_file lk = LOCK_INIT;
878         uint32_t chunk_ids[5];
879         uint64_t chunk_offsets[5];
880         int num_chunks;
881         int num_extra_edges;
882         struct commit_list *parent;
883         struct progress *progress = NULL;
884         const unsigned hashsz = the_hash_algo->rawsz;
885         uint64_t progress_cnt = 0;
886         struct strbuf progress_title = STRBUF_INIT;
887         unsigned long approx_nr_objects;
888         int res = 0;
889         int append = flags & COMMIT_GRAPH_APPEND;
890         int report_progress = flags & COMMIT_GRAPH_PROGRESS;
891
892         if (!commit_graph_compatible(the_repository))
893                 return 0;
894
895         oids.nr = 0;
896         approx_nr_objects = approximate_object_count();
897         oids.alloc = approx_nr_objects / 32;
898         oids.progress = NULL;
899         oids.progress_done = 0;
900         commits.list = NULL;
901
902         if (append) {
903                 prepare_commit_graph_one(the_repository, obj_dir);
904                 if (the_repository->objects->commit_graph)
905                         oids.alloc += the_repository->objects->commit_graph->num_commits;
906         }
907
908         if (oids.alloc < 1024)
909                 oids.alloc = 1024;
910         ALLOC_ARRAY(oids.list, oids.alloc);
911
912         if (append && the_repository->objects->commit_graph) {
913                 struct commit_graph *commit_graph =
914                         the_repository->objects->commit_graph;
915                 for (i = 0; i < commit_graph->num_commits; i++) {
916                         const unsigned char *hash = commit_graph->chunk_oid_lookup +
917                                 commit_graph->hash_len * i;
918                         hashcpy(oids.list[oids.nr++].hash, hash);
919                 }
920         }
921
922         if (pack_indexes) {
923                 struct strbuf packname = STRBUF_INIT;
924                 int dirlen;
925                 strbuf_addf(&packname, "%s/pack/", obj_dir);
926                 dirlen = packname.len;
927                 if (report_progress) {
928                         strbuf_addf(&progress_title,
929                                     Q_("Finding commits for commit graph in %d pack",
930                                        "Finding commits for commit graph in %d packs",
931                                        pack_indexes->nr),
932                                     pack_indexes->nr);
933                         oids.progress = start_delayed_progress(progress_title.buf, 0);
934                         oids.progress_done = 0;
935                 }
936                 for (i = 0; i < pack_indexes->nr; i++) {
937                         struct packed_git *p;
938                         strbuf_setlen(&packname, dirlen);
939                         strbuf_addstr(&packname, pack_indexes->items[i].string);
940                         p = add_packed_git(packname.buf, packname.len, 1);
941                         if (!p) {
942                                 error(_("error adding pack %s"), packname.buf);
943                                 res = -1;
944                                 goto cleanup;
945                         }
946                         if (open_pack_index(p)) {
947                                 error(_("error opening index for %s"), packname.buf);
948                                 res = -1;
949                                 goto cleanup;
950                         }
951                         for_each_object_in_pack(p, add_packed_commits, &oids,
952                                                 FOR_EACH_OBJECT_PACK_ORDER);
953                         close_pack(p);
954                         free(p);
955                 }
956                 stop_progress(&oids.progress);
957                 strbuf_reset(&progress_title);
958                 strbuf_release(&packname);
959         }
960
961         if (commit_hex) {
962                 if (report_progress) {
963                         strbuf_addf(&progress_title,
964                                     Q_("Finding commits for commit graph from %d ref",
965                                        "Finding commits for commit graph from %d refs",
966                                        commit_hex->nr),
967                                     commit_hex->nr);
968                         progress = start_delayed_progress(progress_title.buf,
969                                                           commit_hex->nr);
970                 }
971                 for (i = 0; i < commit_hex->nr; i++) {
972                         const char *end;
973                         struct object_id oid;
974                         struct commit *result;
975
976                         display_progress(progress, i + 1);
977                         if (commit_hex->items[i].string &&
978                             parse_oid_hex(commit_hex->items[i].string, &oid, &end))
979                                 continue;
980
981                         result = lookup_commit_reference_gently(the_repository, &oid, 1);
982
983                         if (result) {
984                                 ALLOC_GROW(oids.list, oids.nr + 1, oids.alloc);
985                                 oidcpy(&oids.list[oids.nr], &(result->object.oid));
986                                 oids.nr++;
987                         }
988                 }
989                 stop_progress(&progress);
990                 strbuf_reset(&progress_title);
991         }
992
993         if (!pack_indexes && !commit_hex) {
994                 if (report_progress)
995                         oids.progress = start_delayed_progress(
996                                 _("Finding commits for commit graph among packed objects"),
997                                 approx_nr_objects);
998                 for_each_packed_object(add_packed_commits, &oids,
999                                        FOR_EACH_OBJECT_PACK_ORDER);
1000                 if (oids.progress_done < approx_nr_objects)
1001                         display_progress(oids.progress, approx_nr_objects);
1002                 stop_progress(&oids.progress);
1003         }
1004
1005         close_reachable(&oids, report_progress);
1006
1007         if (report_progress)
1008                 progress = start_delayed_progress(
1009                         _("Counting distinct commits in commit graph"),
1010                         oids.nr);
1011         display_progress(progress, 0); /* TODO: Measure QSORT() progress */
1012         QSORT(oids.list, oids.nr, commit_compare);
1013         count_distinct = 1;
1014         for (i = 1; i < oids.nr; i++) {
1015                 display_progress(progress, i + 1);
1016                 if (!oideq(&oids.list[i - 1], &oids.list[i]))
1017                         count_distinct++;
1018         }
1019         stop_progress(&progress);
1020
1021         if (count_distinct >= GRAPH_EDGE_LAST_MASK) {
1022                 error(_("the commit graph format cannot write %d commits"), count_distinct);
1023                 res = -1;
1024                 goto cleanup;
1025         }
1026
1027         commits.nr = 0;
1028         commits.alloc = count_distinct;
1029         ALLOC_ARRAY(commits.list, commits.alloc);
1030
1031         num_extra_edges = 0;
1032         if (report_progress)
1033                 progress = start_delayed_progress(
1034                         _("Finding extra edges in commit graph"),
1035                         oids.nr);
1036         for (i = 0; i < oids.nr; i++) {
1037                 int num_parents = 0;
1038                 display_progress(progress, i + 1);
1039                 if (i > 0 && oideq(&oids.list[i - 1], &oids.list[i]))
1040                         continue;
1041
1042                 commits.list[commits.nr] = lookup_commit(the_repository, &oids.list[i]);
1043                 parse_commit_no_graph(commits.list[commits.nr]);
1044
1045                 for (parent = commits.list[commits.nr]->parents;
1046                      parent; parent = parent->next)
1047                         num_parents++;
1048
1049                 if (num_parents > 2)
1050                         num_extra_edges += num_parents - 1;
1051
1052                 commits.nr++;
1053         }
1054         num_chunks = num_extra_edges ? 4 : 3;
1055         stop_progress(&progress);
1056
1057         if (commits.nr >= GRAPH_EDGE_LAST_MASK) {
1058                 error(_("too many commits to write graph"));
1059                 res = -1;
1060                 goto cleanup;
1061         }
1062
1063         compute_generation_numbers(&commits, report_progress);
1064
1065         graph_name = get_commit_graph_filename(obj_dir);
1066         if (safe_create_leading_directories(graph_name)) {
1067                 UNLEAK(graph_name);
1068                 error(_("unable to create leading directories of %s"),
1069                         graph_name);
1070                 res = -1;
1071                 goto cleanup;
1072         }
1073
1074         hold_lock_file_for_update(&lk, graph_name, LOCK_DIE_ON_ERROR);
1075         f = hashfd(lk.tempfile->fd, lk.tempfile->filename.buf);
1076
1077         hashwrite_be32(f, GRAPH_SIGNATURE);
1078
1079         hashwrite_u8(f, GRAPH_VERSION);
1080         hashwrite_u8(f, oid_version());
1081         hashwrite_u8(f, num_chunks);
1082         hashwrite_u8(f, 0); /* unused padding byte */
1083
1084         chunk_ids[0] = GRAPH_CHUNKID_OIDFANOUT;
1085         chunk_ids[1] = GRAPH_CHUNKID_OIDLOOKUP;
1086         chunk_ids[2] = GRAPH_CHUNKID_DATA;
1087         if (num_extra_edges)
1088                 chunk_ids[3] = GRAPH_CHUNKID_EXTRAEDGES;
1089         else
1090                 chunk_ids[3] = 0;
1091         chunk_ids[4] = 0;
1092
1093         chunk_offsets[0] = 8 + (num_chunks + 1) * GRAPH_CHUNKLOOKUP_WIDTH;
1094         chunk_offsets[1] = chunk_offsets[0] + GRAPH_FANOUT_SIZE;
1095         chunk_offsets[2] = chunk_offsets[1] + hashsz * commits.nr;
1096         chunk_offsets[3] = chunk_offsets[2] + (hashsz + 16) * commits.nr;
1097         chunk_offsets[4] = chunk_offsets[3] + 4 * num_extra_edges;
1098
1099         for (i = 0; i <= num_chunks; i++) {
1100                 uint32_t chunk_write[3];
1101
1102                 chunk_write[0] = htonl(chunk_ids[i]);
1103                 chunk_write[1] = htonl(chunk_offsets[i] >> 32);
1104                 chunk_write[2] = htonl(chunk_offsets[i] & 0xffffffff);
1105                 hashwrite(f, chunk_write, 12);
1106         }
1107
1108         if (report_progress) {
1109                 strbuf_addf(&progress_title,
1110                             Q_("Writing out commit graph in %d pass",
1111                                "Writing out commit graph in %d passes",
1112                                num_chunks),
1113                             num_chunks);
1114                 progress = start_delayed_progress(
1115                         progress_title.buf,
1116                         num_chunks * commits.nr);
1117         }
1118         write_graph_chunk_fanout(f, commits.list, commits.nr, progress, &progress_cnt);
1119         write_graph_chunk_oids(f, hashsz, commits.list, commits.nr, progress, &progress_cnt);
1120         write_graph_chunk_data(f, hashsz, commits.list, commits.nr, progress, &progress_cnt);
1121         if (num_extra_edges)
1122                 write_graph_chunk_extra_edges(f, commits.list, commits.nr, progress, &progress_cnt);
1123         stop_progress(&progress);
1124         strbuf_release(&progress_title);
1125
1126         close_commit_graph(the_repository);
1127         finalize_hashfile(f, NULL, CSUM_HASH_IN_STREAM | CSUM_FSYNC);
1128         commit_lock_file(&lk);
1129
1130 cleanup:
1131         free(graph_name);
1132         free(commits.list);
1133         free(oids.list);
1134
1135         return res;
1136 }
1137
1138 #define VERIFY_COMMIT_GRAPH_ERROR_HASH 2
1139 static int verify_commit_graph_error;
1140
1141 static void graph_report(const char *fmt, ...)
1142 {
1143         va_list ap;
1144
1145         verify_commit_graph_error = 1;
1146         va_start(ap, fmt);
1147         vfprintf(stderr, fmt, ap);
1148         fprintf(stderr, "\n");
1149         va_end(ap);
1150 }
1151
1152 #define GENERATION_ZERO_EXISTS 1
1153 #define GENERATION_NUMBER_EXISTS 2
1154
1155 int verify_commit_graph(struct repository *r, struct commit_graph *g)
1156 {
1157         uint32_t i, cur_fanout_pos = 0;
1158         struct object_id prev_oid, cur_oid, checksum;
1159         int generation_zero = 0;
1160         struct hashfile *f;
1161         int devnull;
1162         struct progress *progress = NULL;
1163
1164         if (!g) {
1165                 graph_report("no commit-graph file loaded");
1166                 return 1;
1167         }
1168
1169         verify_commit_graph_error = verify_commit_graph_lite(g);
1170         if (verify_commit_graph_error)
1171                 return verify_commit_graph_error;
1172
1173         devnull = open("/dev/null", O_WRONLY);
1174         f = hashfd(devnull, NULL);
1175         hashwrite(f, g->data, g->data_len - g->hash_len);
1176         finalize_hashfile(f, checksum.hash, CSUM_CLOSE);
1177         if (!hasheq(checksum.hash, g->data + g->data_len - g->hash_len)) {
1178                 graph_report(_("the commit-graph file has incorrect checksum and is likely corrupt"));
1179                 verify_commit_graph_error = VERIFY_COMMIT_GRAPH_ERROR_HASH;
1180         }
1181
1182         for (i = 0; i < g->num_commits; i++) {
1183                 struct commit *graph_commit;
1184
1185                 hashcpy(cur_oid.hash, g->chunk_oid_lookup + g->hash_len * i);
1186
1187                 if (i && oidcmp(&prev_oid, &cur_oid) >= 0)
1188                         graph_report(_("commit-graph has incorrect OID order: %s then %s"),
1189                                      oid_to_hex(&prev_oid),
1190                                      oid_to_hex(&cur_oid));
1191
1192                 oidcpy(&prev_oid, &cur_oid);
1193
1194                 while (cur_oid.hash[0] > cur_fanout_pos) {
1195                         uint32_t fanout_value = get_be32(g->chunk_oid_fanout + cur_fanout_pos);
1196
1197                         if (i != fanout_value)
1198                                 graph_report(_("commit-graph has incorrect fanout value: fanout[%d] = %u != %u"),
1199                                              cur_fanout_pos, fanout_value, i);
1200                         cur_fanout_pos++;
1201                 }
1202
1203                 graph_commit = lookup_commit(r, &cur_oid);
1204                 if (!parse_commit_in_graph_one(r, g, graph_commit))
1205                         graph_report(_("failed to parse commit %s from commit-graph"),
1206                                      oid_to_hex(&cur_oid));
1207         }
1208
1209         while (cur_fanout_pos < 256) {
1210                 uint32_t fanout_value = get_be32(g->chunk_oid_fanout + cur_fanout_pos);
1211
1212                 if (g->num_commits != fanout_value)
1213                         graph_report(_("commit-graph has incorrect fanout value: fanout[%d] = %u != %u"),
1214                                      cur_fanout_pos, fanout_value, i);
1215
1216                 cur_fanout_pos++;
1217         }
1218
1219         if (verify_commit_graph_error & ~VERIFY_COMMIT_GRAPH_ERROR_HASH)
1220                 return verify_commit_graph_error;
1221
1222         progress = start_progress(_("Verifying commits in commit graph"),
1223                                   g->num_commits);
1224         for (i = 0; i < g->num_commits; i++) {
1225                 struct commit *graph_commit, *odb_commit;
1226                 struct commit_list *graph_parents, *odb_parents;
1227                 uint32_t max_generation = 0;
1228
1229                 display_progress(progress, i + 1);
1230                 hashcpy(cur_oid.hash, g->chunk_oid_lookup + g->hash_len * i);
1231
1232                 graph_commit = lookup_commit(r, &cur_oid);
1233                 odb_commit = (struct commit *)create_object(r, cur_oid.hash, alloc_commit_node(r));
1234                 if (parse_commit_internal(odb_commit, 0, 0)) {
1235                         graph_report(_("failed to parse commit %s from object database for commit-graph"),
1236                                      oid_to_hex(&cur_oid));
1237                         continue;
1238                 }
1239
1240                 if (!oideq(&get_commit_tree_in_graph_one(r, g, graph_commit)->object.oid,
1241                            get_commit_tree_oid(odb_commit)))
1242                         graph_report(_("root tree OID for commit %s in commit-graph is %s != %s"),
1243                                      oid_to_hex(&cur_oid),
1244                                      oid_to_hex(get_commit_tree_oid(graph_commit)),
1245                                      oid_to_hex(get_commit_tree_oid(odb_commit)));
1246
1247                 graph_parents = graph_commit->parents;
1248                 odb_parents = odb_commit->parents;
1249
1250                 while (graph_parents) {
1251                         if (odb_parents == NULL) {
1252                                 graph_report(_("commit-graph parent list for commit %s is too long"),
1253                                              oid_to_hex(&cur_oid));
1254                                 break;
1255                         }
1256
1257                         if (!oideq(&graph_parents->item->object.oid, &odb_parents->item->object.oid))
1258                                 graph_report(_("commit-graph parent for %s is %s != %s"),
1259                                              oid_to_hex(&cur_oid),
1260                                              oid_to_hex(&graph_parents->item->object.oid),
1261                                              oid_to_hex(&odb_parents->item->object.oid));
1262
1263                         if (graph_parents->item->generation > max_generation)
1264                                 max_generation = graph_parents->item->generation;
1265
1266                         graph_parents = graph_parents->next;
1267                         odb_parents = odb_parents->next;
1268                 }
1269
1270                 if (odb_parents != NULL)
1271                         graph_report(_("commit-graph parent list for commit %s terminates early"),
1272                                      oid_to_hex(&cur_oid));
1273
1274                 if (!graph_commit->generation) {
1275                         if (generation_zero == GENERATION_NUMBER_EXISTS)
1276                                 graph_report(_("commit-graph has generation number zero for commit %s, but non-zero elsewhere"),
1277                                              oid_to_hex(&cur_oid));
1278                         generation_zero = GENERATION_ZERO_EXISTS;
1279                 } else if (generation_zero == GENERATION_ZERO_EXISTS)
1280                         graph_report(_("commit-graph has non-zero generation number for commit %s, but zero elsewhere"),
1281                                      oid_to_hex(&cur_oid));
1282
1283                 if (generation_zero == GENERATION_ZERO_EXISTS)
1284                         continue;
1285
1286                 /*
1287                  * If one of our parents has generation GENERATION_NUMBER_MAX, then
1288                  * our generation is also GENERATION_NUMBER_MAX. Decrement to avoid
1289                  * extra logic in the following condition.
1290                  */
1291                 if (max_generation == GENERATION_NUMBER_MAX)
1292                         max_generation--;
1293
1294                 if (graph_commit->generation != max_generation + 1)
1295                         graph_report(_("commit-graph generation for commit %s is %u != %u"),
1296                                      oid_to_hex(&cur_oid),
1297                                      graph_commit->generation,
1298                                      max_generation + 1);
1299
1300                 if (graph_commit->date != odb_commit->date)
1301                         graph_report(_("commit date for commit %s in commit-graph is %"PRItime" != %"PRItime),
1302                                      oid_to_hex(&cur_oid),
1303                                      graph_commit->date,
1304                                      odb_commit->date);
1305         }
1306         stop_progress(&progress);
1307
1308         return verify_commit_graph_error;
1309 }
1310
1311 void free_commit_graph(struct commit_graph *g)
1312 {
1313         if (!g)
1314                 return;
1315         if (g->graph_fd >= 0) {
1316                 munmap((void *)g->data, g->data_len);
1317                 g->data = NULL;
1318                 close(g->graph_fd);
1319         }
1320         free(g);
1321 }