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