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