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