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