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