fetch-pack: clear alternate shallow in one more place
[git] / pack-bitmap.c
1 #include "cache.h"
2 #include "commit.h"
3 #include "tag.h"
4 #include "diff.h"
5 #include "revision.h"
6 #include "progress.h"
7 #include "list-objects.h"
8 #include "pack.h"
9 #include "pack-bitmap.h"
10 #include "pack-revindex.h"
11 #include "pack-objects.h"
12 #include "packfile.h"
13 #include "repository.h"
14 #include "object-store.h"
15
16 /*
17  * An entry on the bitmap index, representing the bitmap for a given
18  * commit.
19  */
20 struct stored_bitmap {
21         unsigned char sha1[20];
22         struct ewah_bitmap *root;
23         struct stored_bitmap *xor;
24         int flags;
25 };
26
27 /*
28  * The active bitmap index for a repository. By design, repositories only have
29  * a single bitmap index available (the index for the biggest packfile in
30  * the repository), since bitmap indexes need full closure.
31  *
32  * If there is more than one bitmap index available (e.g. because of alternates),
33  * the active bitmap index is the largest one.
34  */
35 struct bitmap_index {
36         /* Packfile to which this bitmap index belongs to */
37         struct packed_git *pack;
38
39         /*
40          * Mark the first `reuse_objects` in the packfile as reused:
41          * they will be sent as-is without using them for repacking
42          * calculations
43          */
44         uint32_t reuse_objects;
45
46         /* mmapped buffer of the whole bitmap index */
47         unsigned char *map;
48         size_t map_size; /* size of the mmaped buffer */
49         size_t map_pos; /* current position when loading the index */
50
51         /*
52          * Type indexes.
53          *
54          * Each bitmap marks which objects in the packfile  are of the given
55          * type. This provides type information when yielding the objects from
56          * the packfile during a walk, which allows for better delta bases.
57          */
58         struct ewah_bitmap *commits;
59         struct ewah_bitmap *trees;
60         struct ewah_bitmap *blobs;
61         struct ewah_bitmap *tags;
62
63         /* Map from SHA1 -> `stored_bitmap` for all the bitmapped commits */
64         khash_sha1 *bitmaps;
65
66         /* Number of bitmapped commits */
67         uint32_t entry_count;
68
69         /* If not NULL, this is a name-hash cache pointing into map. */
70         uint32_t *hashes;
71
72         /*
73          * Extended index.
74          *
75          * When trying to perform bitmap operations with objects that are not
76          * packed in `pack`, these objects are added to this "fake index" and
77          * are assumed to appear at the end of the packfile for all operations
78          */
79         struct eindex {
80                 struct object **objects;
81                 uint32_t *hashes;
82                 uint32_t count, alloc;
83                 khash_sha1_pos *positions;
84         } ext_index;
85
86         /* Bitmap result of the last performed walk */
87         struct bitmap *result;
88
89         /* "have" bitmap from the last performed walk */
90         struct bitmap *haves;
91
92         /* Version of the bitmap index */
93         unsigned int version;
94 };
95
96 static struct ewah_bitmap *lookup_stored_bitmap(struct stored_bitmap *st)
97 {
98         struct ewah_bitmap *parent;
99         struct ewah_bitmap *composed;
100
101         if (st->xor == NULL)
102                 return st->root;
103
104         composed = ewah_pool_new();
105         parent = lookup_stored_bitmap(st->xor);
106         ewah_xor(st->root, parent, composed);
107
108         ewah_pool_free(st->root);
109         st->root = composed;
110         st->xor = NULL;
111
112         return composed;
113 }
114
115 /*
116  * Read a bitmap from the current read position on the mmaped
117  * index, and increase the read position accordingly
118  */
119 static struct ewah_bitmap *read_bitmap_1(struct bitmap_index *index)
120 {
121         struct ewah_bitmap *b = ewah_pool_new();
122
123         ssize_t bitmap_size = ewah_read_mmap(b,
124                 index->map + index->map_pos,
125                 index->map_size - index->map_pos);
126
127         if (bitmap_size < 0) {
128                 error("Failed to load bitmap index (corrupted?)");
129                 ewah_pool_free(b);
130                 return NULL;
131         }
132
133         index->map_pos += bitmap_size;
134         return b;
135 }
136
137 static int load_bitmap_header(struct bitmap_index *index)
138 {
139         struct bitmap_disk_header *header = (void *)index->map;
140
141         if (index->map_size < sizeof(*header) + 20)
142                 return error("Corrupted bitmap index (missing header data)");
143
144         if (memcmp(header->magic, BITMAP_IDX_SIGNATURE, sizeof(BITMAP_IDX_SIGNATURE)) != 0)
145                 return error("Corrupted bitmap index file (wrong header)");
146
147         index->version = ntohs(header->version);
148         if (index->version != 1)
149                 return error("Unsupported version for bitmap index file (%d)", index->version);
150
151         /* Parse known bitmap format options */
152         {
153                 uint32_t flags = ntohs(header->options);
154
155                 if ((flags & BITMAP_OPT_FULL_DAG) == 0)
156                         return error("Unsupported options for bitmap index file "
157                                 "(Git requires BITMAP_OPT_FULL_DAG)");
158
159                 if (flags & BITMAP_OPT_HASH_CACHE) {
160                         unsigned char *end = index->map + index->map_size - 20;
161                         index->hashes = ((uint32_t *)end) - index->pack->num_objects;
162                 }
163         }
164
165         index->entry_count = ntohl(header->entry_count);
166         index->map_pos += sizeof(*header);
167         return 0;
168 }
169
170 static struct stored_bitmap *store_bitmap(struct bitmap_index *index,
171                                           struct ewah_bitmap *root,
172                                           const unsigned char *sha1,
173                                           struct stored_bitmap *xor_with,
174                                           int flags)
175 {
176         struct stored_bitmap *stored;
177         khiter_t hash_pos;
178         int ret;
179
180         stored = xmalloc(sizeof(struct stored_bitmap));
181         stored->root = root;
182         stored->xor = xor_with;
183         stored->flags = flags;
184         hashcpy(stored->sha1, sha1);
185
186         hash_pos = kh_put_sha1(index->bitmaps, stored->sha1, &ret);
187
188         /* a 0 return code means the insertion succeeded with no changes,
189          * because the SHA1 already existed on the map. this is bad, there
190          * shouldn't be duplicated commits in the index */
191         if (ret == 0) {
192                 error("Duplicate entry in bitmap index: %s", sha1_to_hex(sha1));
193                 return NULL;
194         }
195
196         kh_value(index->bitmaps, hash_pos) = stored;
197         return stored;
198 }
199
200 static inline uint32_t read_be32(const unsigned char *buffer, size_t *pos)
201 {
202         uint32_t result = get_be32(buffer + *pos);
203         (*pos) += sizeof(result);
204         return result;
205 }
206
207 static inline uint8_t read_u8(const unsigned char *buffer, size_t *pos)
208 {
209         return buffer[(*pos)++];
210 }
211
212 #define MAX_XOR_OFFSET 160
213
214 static int load_bitmap_entries_v1(struct bitmap_index *index)
215 {
216         uint32_t i;
217         struct stored_bitmap *recent_bitmaps[MAX_XOR_OFFSET] = { NULL };
218
219         for (i = 0; i < index->entry_count; ++i) {
220                 int xor_offset, flags;
221                 struct ewah_bitmap *bitmap = NULL;
222                 struct stored_bitmap *xor_bitmap = NULL;
223                 uint32_t commit_idx_pos;
224                 const unsigned char *sha1;
225
226                 commit_idx_pos = read_be32(index->map, &index->map_pos);
227                 xor_offset = read_u8(index->map, &index->map_pos);
228                 flags = read_u8(index->map, &index->map_pos);
229
230                 sha1 = nth_packed_object_sha1(index->pack, commit_idx_pos);
231
232                 bitmap = read_bitmap_1(index);
233                 if (!bitmap)
234                         return -1;
235
236                 if (xor_offset > MAX_XOR_OFFSET || xor_offset > i)
237                         return error("Corrupted bitmap pack index");
238
239                 if (xor_offset > 0) {
240                         xor_bitmap = recent_bitmaps[(i - xor_offset) % MAX_XOR_OFFSET];
241
242                         if (xor_bitmap == NULL)
243                                 return error("Invalid XOR offset in bitmap pack index");
244                 }
245
246                 recent_bitmaps[i % MAX_XOR_OFFSET] = store_bitmap(
247                         index, bitmap, sha1, xor_bitmap, flags);
248         }
249
250         return 0;
251 }
252
253 static char *pack_bitmap_filename(struct packed_git *p)
254 {
255         size_t len;
256
257         if (!strip_suffix(p->pack_name, ".pack", &len))
258                 BUG("pack_name does not end in .pack");
259         return xstrfmt("%.*s.bitmap", (int)len, p->pack_name);
260 }
261
262 static int open_pack_bitmap_1(struct bitmap_index *bitmap_git, struct packed_git *packfile)
263 {
264         int fd;
265         struct stat st;
266         char *idx_name;
267
268         if (open_pack_index(packfile))
269                 return -1;
270
271         idx_name = pack_bitmap_filename(packfile);
272         fd = git_open(idx_name);
273         free(idx_name);
274
275         if (fd < 0)
276                 return -1;
277
278         if (fstat(fd, &st)) {
279                 close(fd);
280                 return -1;
281         }
282
283         if (bitmap_git->pack) {
284                 warning("ignoring extra bitmap file: %s", packfile->pack_name);
285                 close(fd);
286                 return -1;
287         }
288
289         bitmap_git->pack = packfile;
290         bitmap_git->map_size = xsize_t(st.st_size);
291         bitmap_git->map = xmmap(NULL, bitmap_git->map_size, PROT_READ, MAP_PRIVATE, fd, 0);
292         bitmap_git->map_pos = 0;
293         close(fd);
294
295         if (load_bitmap_header(bitmap_git) < 0) {
296                 munmap(bitmap_git->map, bitmap_git->map_size);
297                 bitmap_git->map = NULL;
298                 bitmap_git->map_size = 0;
299                 return -1;
300         }
301
302         return 0;
303 }
304
305 static int load_pack_bitmap(struct bitmap_index *bitmap_git)
306 {
307         assert(bitmap_git->map);
308
309         bitmap_git->bitmaps = kh_init_sha1();
310         bitmap_git->ext_index.positions = kh_init_sha1_pos();
311         load_pack_revindex(bitmap_git->pack);
312
313         if (!(bitmap_git->commits = read_bitmap_1(bitmap_git)) ||
314                 !(bitmap_git->trees = read_bitmap_1(bitmap_git)) ||
315                 !(bitmap_git->blobs = read_bitmap_1(bitmap_git)) ||
316                 !(bitmap_git->tags = read_bitmap_1(bitmap_git)))
317                 goto failed;
318
319         if (load_bitmap_entries_v1(bitmap_git) < 0)
320                 goto failed;
321
322         return 0;
323
324 failed:
325         munmap(bitmap_git->map, bitmap_git->map_size);
326         bitmap_git->map = NULL;
327         bitmap_git->map_size = 0;
328         return -1;
329 }
330
331 static int open_pack_bitmap(struct repository *r,
332                             struct bitmap_index *bitmap_git)
333 {
334         struct packed_git *p;
335         int ret = -1;
336
337         assert(!bitmap_git->map);
338
339         for (p = get_all_packs(r); p; p = p->next) {
340                 if (open_pack_bitmap_1(bitmap_git, p) == 0)
341                         ret = 0;
342         }
343
344         return ret;
345 }
346
347 struct bitmap_index *prepare_bitmap_git(struct repository *r)
348 {
349         struct bitmap_index *bitmap_git = xcalloc(1, sizeof(*bitmap_git));
350
351         if (!open_pack_bitmap(r, bitmap_git) && !load_pack_bitmap(bitmap_git))
352                 return bitmap_git;
353
354         free_bitmap_index(bitmap_git);
355         return NULL;
356 }
357
358 struct include_data {
359         struct bitmap_index *bitmap_git;
360         struct bitmap *base;
361         struct bitmap *seen;
362 };
363
364 static inline int bitmap_position_extended(struct bitmap_index *bitmap_git,
365                                            const unsigned char *sha1)
366 {
367         khash_sha1_pos *positions = bitmap_git->ext_index.positions;
368         khiter_t pos = kh_get_sha1_pos(positions, sha1);
369
370         if (pos < kh_end(positions)) {
371                 int bitmap_pos = kh_value(positions, pos);
372                 return bitmap_pos + bitmap_git->pack->num_objects;
373         }
374
375         return -1;
376 }
377
378 static inline int bitmap_position_packfile(struct bitmap_index *bitmap_git,
379                                            const unsigned char *sha1)
380 {
381         off_t offset = find_pack_entry_one(sha1, bitmap_git->pack);
382         if (!offset)
383                 return -1;
384
385         return find_revindex_position(bitmap_git->pack, offset);
386 }
387
388 static int bitmap_position(struct bitmap_index *bitmap_git,
389                            const unsigned char *sha1)
390 {
391         int pos = bitmap_position_packfile(bitmap_git, sha1);
392         return (pos >= 0) ? pos : bitmap_position_extended(bitmap_git, sha1);
393 }
394
395 static int ext_index_add_object(struct bitmap_index *bitmap_git,
396                                 struct object *object, const char *name)
397 {
398         struct eindex *eindex = &bitmap_git->ext_index;
399
400         khiter_t hash_pos;
401         int hash_ret;
402         int bitmap_pos;
403
404         hash_pos = kh_put_sha1_pos(eindex->positions, object->oid.hash, &hash_ret);
405         if (hash_ret > 0) {
406                 if (eindex->count >= eindex->alloc) {
407                         eindex->alloc = (eindex->alloc + 16) * 3 / 2;
408                         REALLOC_ARRAY(eindex->objects, eindex->alloc);
409                         REALLOC_ARRAY(eindex->hashes, eindex->alloc);
410                 }
411
412                 bitmap_pos = eindex->count;
413                 eindex->objects[eindex->count] = object;
414                 eindex->hashes[eindex->count] = pack_name_hash(name);
415                 kh_value(eindex->positions, hash_pos) = bitmap_pos;
416                 eindex->count++;
417         } else {
418                 bitmap_pos = kh_value(eindex->positions, hash_pos);
419         }
420
421         return bitmap_pos + bitmap_git->pack->num_objects;
422 }
423
424 struct bitmap_show_data {
425         struct bitmap_index *bitmap_git;
426         struct bitmap *base;
427 };
428
429 static void show_object(struct object *object, const char *name, void *data_)
430 {
431         struct bitmap_show_data *data = data_;
432         int bitmap_pos;
433
434         bitmap_pos = bitmap_position(data->bitmap_git, object->oid.hash);
435
436         if (bitmap_pos < 0)
437                 bitmap_pos = ext_index_add_object(data->bitmap_git, object,
438                                                   name);
439
440         bitmap_set(data->base, bitmap_pos);
441 }
442
443 static void show_commit(struct commit *commit, void *data)
444 {
445 }
446
447 static int add_to_include_set(struct bitmap_index *bitmap_git,
448                               struct include_data *data,
449                               const unsigned char *sha1,
450                               int bitmap_pos)
451 {
452         khiter_t hash_pos;
453
454         if (data->seen && bitmap_get(data->seen, bitmap_pos))
455                 return 0;
456
457         if (bitmap_get(data->base, bitmap_pos))
458                 return 0;
459
460         hash_pos = kh_get_sha1(bitmap_git->bitmaps, sha1);
461         if (hash_pos < kh_end(bitmap_git->bitmaps)) {
462                 struct stored_bitmap *st = kh_value(bitmap_git->bitmaps, hash_pos);
463                 bitmap_or_ewah(data->base, lookup_stored_bitmap(st));
464                 return 0;
465         }
466
467         bitmap_set(data->base, bitmap_pos);
468         return 1;
469 }
470
471 static int should_include(struct commit *commit, void *_data)
472 {
473         struct include_data *data = _data;
474         int bitmap_pos;
475
476         bitmap_pos = bitmap_position(data->bitmap_git, commit->object.oid.hash);
477         if (bitmap_pos < 0)
478                 bitmap_pos = ext_index_add_object(data->bitmap_git,
479                                                   (struct object *)commit,
480                                                   NULL);
481
482         if (!add_to_include_set(data->bitmap_git, data, commit->object.oid.hash,
483                                 bitmap_pos)) {
484                 struct commit_list *parent = commit->parents;
485
486                 while (parent) {
487                         parent->item->object.flags |= SEEN;
488                         parent = parent->next;
489                 }
490
491                 return 0;
492         }
493
494         return 1;
495 }
496
497 static struct bitmap *find_objects(struct bitmap_index *bitmap_git,
498                                    struct rev_info *revs,
499                                    struct object_list *roots,
500                                    struct bitmap *seen)
501 {
502         struct bitmap *base = NULL;
503         int needs_walk = 0;
504
505         struct object_list *not_mapped = NULL;
506
507         /*
508          * Go through all the roots for the walk. The ones that have bitmaps
509          * on the bitmap index will be `or`ed together to form an initial
510          * global reachability analysis.
511          *
512          * The ones without bitmaps in the index will be stored in the
513          * `not_mapped_list` for further processing.
514          */
515         while (roots) {
516                 struct object *object = roots->item;
517                 roots = roots->next;
518
519                 if (object->type == OBJ_COMMIT) {
520                         khiter_t pos = kh_get_sha1(bitmap_git->bitmaps, object->oid.hash);
521
522                         if (pos < kh_end(bitmap_git->bitmaps)) {
523                                 struct stored_bitmap *st = kh_value(bitmap_git->bitmaps, pos);
524                                 struct ewah_bitmap *or_with = lookup_stored_bitmap(st);
525
526                                 if (base == NULL)
527                                         base = ewah_to_bitmap(or_with);
528                                 else
529                                         bitmap_or_ewah(base, or_with);
530
531                                 object->flags |= SEEN;
532                                 continue;
533                         }
534                 }
535
536                 object_list_insert(object, &not_mapped);
537         }
538
539         /*
540          * Best case scenario: We found bitmaps for all the roots,
541          * so the resulting `or` bitmap has the full reachability analysis
542          */
543         if (not_mapped == NULL)
544                 return base;
545
546         roots = not_mapped;
547
548         /*
549          * Let's iterate through all the roots that don't have bitmaps to
550          * check if we can determine them to be reachable from the existing
551          * global bitmap.
552          *
553          * If we cannot find them in the existing global bitmap, we'll need
554          * to push them to an actual walk and run it until we can confirm
555          * they are reachable
556          */
557         while (roots) {
558                 struct object *object = roots->item;
559                 int pos;
560
561                 roots = roots->next;
562                 pos = bitmap_position(bitmap_git, object->oid.hash);
563
564                 if (pos < 0 || base == NULL || !bitmap_get(base, pos)) {
565                         object->flags &= ~UNINTERESTING;
566                         add_pending_object(revs, object, "");
567                         needs_walk = 1;
568                 } else {
569                         object->flags |= SEEN;
570                 }
571         }
572
573         if (needs_walk) {
574                 struct include_data incdata;
575                 struct bitmap_show_data show_data;
576
577                 if (base == NULL)
578                         base = bitmap_new();
579
580                 incdata.bitmap_git = bitmap_git;
581                 incdata.base = base;
582                 incdata.seen = seen;
583
584                 revs->include_check = should_include;
585                 revs->include_check_data = &incdata;
586
587                 if (prepare_revision_walk(revs))
588                         die("revision walk setup failed");
589
590                 show_data.bitmap_git = bitmap_git;
591                 show_data.base = base;
592
593                 traverse_commit_list(revs, show_commit, show_object,
594                                      &show_data);
595         }
596
597         return base;
598 }
599
600 static void show_extended_objects(struct bitmap_index *bitmap_git,
601                                   show_reachable_fn show_reach)
602 {
603         struct bitmap *objects = bitmap_git->result;
604         struct eindex *eindex = &bitmap_git->ext_index;
605         uint32_t i;
606
607         for (i = 0; i < eindex->count; ++i) {
608                 struct object *obj;
609
610                 if (!bitmap_get(objects, bitmap_git->pack->num_objects + i))
611                         continue;
612
613                 obj = eindex->objects[i];
614                 show_reach(&obj->oid, obj->type, 0, eindex->hashes[i], NULL, 0);
615         }
616 }
617
618 static void show_objects_for_type(
619         struct bitmap_index *bitmap_git,
620         struct ewah_bitmap *type_filter,
621         enum object_type object_type,
622         show_reachable_fn show_reach)
623 {
624         size_t pos = 0, i = 0;
625         uint32_t offset;
626
627         struct ewah_iterator it;
628         eword_t filter;
629
630         struct bitmap *objects = bitmap_git->result;
631
632         if (bitmap_git->reuse_objects == bitmap_git->pack->num_objects)
633                 return;
634
635         ewah_iterator_init(&it, type_filter);
636
637         while (i < objects->word_alloc && ewah_iterator_next(&filter, &it)) {
638                 eword_t word = objects->words[i] & filter;
639
640                 for (offset = 0; offset < BITS_IN_EWORD; ++offset) {
641                         struct object_id oid;
642                         struct revindex_entry *entry;
643                         uint32_t hash = 0;
644
645                         if ((word >> offset) == 0)
646                                 break;
647
648                         offset += ewah_bit_ctz64(word >> offset);
649
650                         if (pos + offset < bitmap_git->reuse_objects)
651                                 continue;
652
653                         entry = &bitmap_git->pack->revindex[pos + offset];
654                         nth_packed_object_oid(&oid, bitmap_git->pack, entry->nr);
655
656                         if (bitmap_git->hashes)
657                                 hash = get_be32(bitmap_git->hashes + entry->nr);
658
659                         show_reach(&oid, object_type, 0, hash, bitmap_git->pack, entry->offset);
660                 }
661
662                 pos += BITS_IN_EWORD;
663                 i++;
664         }
665 }
666
667 static int in_bitmapped_pack(struct bitmap_index *bitmap_git,
668                              struct object_list *roots)
669 {
670         while (roots) {
671                 struct object *object = roots->item;
672                 roots = roots->next;
673
674                 if (find_pack_entry_one(object->oid.hash, bitmap_git->pack) > 0)
675                         return 1;
676         }
677
678         return 0;
679 }
680
681 struct bitmap_index *prepare_bitmap_walk(struct rev_info *revs)
682 {
683         unsigned int i;
684
685         struct object_list *wants = NULL;
686         struct object_list *haves = NULL;
687
688         struct bitmap *wants_bitmap = NULL;
689         struct bitmap *haves_bitmap = NULL;
690
691         struct bitmap_index *bitmap_git = xcalloc(1, sizeof(*bitmap_git));
692         /* try to open a bitmapped pack, but don't parse it yet
693          * because we may not need to use it */
694         if (open_pack_bitmap(revs->repo, bitmap_git) < 0)
695                 goto cleanup;
696
697         for (i = 0; i < revs->pending.nr; ++i) {
698                 struct object *object = revs->pending.objects[i].item;
699
700                 if (object->type == OBJ_NONE)
701                         parse_object_or_die(&object->oid, NULL);
702
703                 while (object->type == OBJ_TAG) {
704                         struct tag *tag = (struct tag *) object;
705
706                         if (object->flags & UNINTERESTING)
707                                 object_list_insert(object, &haves);
708                         else
709                                 object_list_insert(object, &wants);
710
711                         if (!tag->tagged)
712                                 die("bad tag");
713                         object = parse_object_or_die(&tag->tagged->oid, NULL);
714                 }
715
716                 if (object->flags & UNINTERESTING)
717                         object_list_insert(object, &haves);
718                 else
719                         object_list_insert(object, &wants);
720         }
721
722         /*
723          * if we have a HAVES list, but none of those haves is contained
724          * in the packfile that has a bitmap, we don't have anything to
725          * optimize here
726          */
727         if (haves && !in_bitmapped_pack(bitmap_git, haves))
728                 goto cleanup;
729
730         /* if we don't want anything, we're done here */
731         if (!wants)
732                 goto cleanup;
733
734         /*
735          * now we're going to use bitmaps, so load the actual bitmap entries
736          * from disk. this is the point of no return; after this the rev_list
737          * becomes invalidated and we must perform the revwalk through bitmaps
738          */
739         if (load_pack_bitmap(bitmap_git) < 0)
740                 goto cleanup;
741
742         object_array_clear(&revs->pending);
743
744         if (haves) {
745                 revs->ignore_missing_links = 1;
746                 haves_bitmap = find_objects(bitmap_git, revs, haves, NULL);
747                 reset_revision_walk();
748                 revs->ignore_missing_links = 0;
749
750                 if (haves_bitmap == NULL)
751                         BUG("failed to perform bitmap walk");
752         }
753
754         wants_bitmap = find_objects(bitmap_git, revs, wants, haves_bitmap);
755
756         if (!wants_bitmap)
757                 BUG("failed to perform bitmap walk");
758
759         if (haves_bitmap)
760                 bitmap_and_not(wants_bitmap, haves_bitmap);
761
762         bitmap_git->result = wants_bitmap;
763         bitmap_git->haves = haves_bitmap;
764
765         return bitmap_git;
766
767 cleanup:
768         free_bitmap_index(bitmap_git);
769         return NULL;
770 }
771
772 int reuse_partial_packfile_from_bitmap(struct bitmap_index *bitmap_git,
773                                        struct packed_git **packfile,
774                                        uint32_t *entries,
775                                        off_t *up_to)
776 {
777         /*
778          * Reuse the packfile content if we need more than
779          * 90% of its objects
780          */
781         static const double REUSE_PERCENT = 0.9;
782
783         struct bitmap *result = bitmap_git->result;
784         uint32_t reuse_threshold;
785         uint32_t i, reuse_objects = 0;
786
787         assert(result);
788
789         for (i = 0; i < result->word_alloc; ++i) {
790                 if (result->words[i] != (eword_t)~0) {
791                         reuse_objects += ewah_bit_ctz64(~result->words[i]);
792                         break;
793                 }
794
795                 reuse_objects += BITS_IN_EWORD;
796         }
797
798 #ifdef GIT_BITMAP_DEBUG
799         {
800                 const unsigned char *sha1;
801                 struct revindex_entry *entry;
802
803                 entry = &bitmap_git->reverse_index->revindex[reuse_objects];
804                 sha1 = nth_packed_object_sha1(bitmap_git->pack, entry->nr);
805
806                 fprintf(stderr, "Failed to reuse at %d (%016llx)\n",
807                         reuse_objects, result->words[i]);
808                 fprintf(stderr, " %s\n", sha1_to_hex(sha1));
809         }
810 #endif
811
812         if (!reuse_objects)
813                 return -1;
814
815         if (reuse_objects >= bitmap_git->pack->num_objects) {
816                 bitmap_git->reuse_objects = *entries = bitmap_git->pack->num_objects;
817                 *up_to = -1; /* reuse the full pack */
818                 *packfile = bitmap_git->pack;
819                 return 0;
820         }
821
822         reuse_threshold = bitmap_popcount(bitmap_git->result) * REUSE_PERCENT;
823
824         if (reuse_objects < reuse_threshold)
825                 return -1;
826
827         bitmap_git->reuse_objects = *entries = reuse_objects;
828         *up_to = bitmap_git->pack->revindex[reuse_objects].offset;
829         *packfile = bitmap_git->pack;
830
831         return 0;
832 }
833
834 void traverse_bitmap_commit_list(struct bitmap_index *bitmap_git,
835                                  show_reachable_fn show_reachable)
836 {
837         assert(bitmap_git->result);
838
839         show_objects_for_type(bitmap_git, bitmap_git->commits,
840                 OBJ_COMMIT, show_reachable);
841         show_objects_for_type(bitmap_git, bitmap_git->trees,
842                 OBJ_TREE, show_reachable);
843         show_objects_for_type(bitmap_git, bitmap_git->blobs,
844                 OBJ_BLOB, show_reachable);
845         show_objects_for_type(bitmap_git, bitmap_git->tags,
846                 OBJ_TAG, show_reachable);
847
848         show_extended_objects(bitmap_git, show_reachable);
849 }
850
851 static uint32_t count_object_type(struct bitmap_index *bitmap_git,
852                                   enum object_type type)
853 {
854         struct bitmap *objects = bitmap_git->result;
855         struct eindex *eindex = &bitmap_git->ext_index;
856
857         uint32_t i = 0, count = 0;
858         struct ewah_iterator it;
859         eword_t filter;
860
861         switch (type) {
862         case OBJ_COMMIT:
863                 ewah_iterator_init(&it, bitmap_git->commits);
864                 break;
865
866         case OBJ_TREE:
867                 ewah_iterator_init(&it, bitmap_git->trees);
868                 break;
869
870         case OBJ_BLOB:
871                 ewah_iterator_init(&it, bitmap_git->blobs);
872                 break;
873
874         case OBJ_TAG:
875                 ewah_iterator_init(&it, bitmap_git->tags);
876                 break;
877
878         default:
879                 return 0;
880         }
881
882         while (i < objects->word_alloc && ewah_iterator_next(&filter, &it)) {
883                 eword_t word = objects->words[i++] & filter;
884                 count += ewah_bit_popcount64(word);
885         }
886
887         for (i = 0; i < eindex->count; ++i) {
888                 if (eindex->objects[i]->type == type &&
889                         bitmap_get(objects, bitmap_git->pack->num_objects + i))
890                         count++;
891         }
892
893         return count;
894 }
895
896 void count_bitmap_commit_list(struct bitmap_index *bitmap_git,
897                               uint32_t *commits, uint32_t *trees,
898                               uint32_t *blobs, uint32_t *tags)
899 {
900         assert(bitmap_git->result);
901
902         if (commits)
903                 *commits = count_object_type(bitmap_git, OBJ_COMMIT);
904
905         if (trees)
906                 *trees = count_object_type(bitmap_git, OBJ_TREE);
907
908         if (blobs)
909                 *blobs = count_object_type(bitmap_git, OBJ_BLOB);
910
911         if (tags)
912                 *tags = count_object_type(bitmap_git, OBJ_TAG);
913 }
914
915 struct bitmap_test_data {
916         struct bitmap_index *bitmap_git;
917         struct bitmap *base;
918         struct progress *prg;
919         size_t seen;
920 };
921
922 static void test_show_object(struct object *object, const char *name,
923                              void *data)
924 {
925         struct bitmap_test_data *tdata = data;
926         int bitmap_pos;
927
928         bitmap_pos = bitmap_position(tdata->bitmap_git, object->oid.hash);
929         if (bitmap_pos < 0)
930                 die("Object not in bitmap: %s\n", oid_to_hex(&object->oid));
931
932         bitmap_set(tdata->base, bitmap_pos);
933         display_progress(tdata->prg, ++tdata->seen);
934 }
935
936 static void test_show_commit(struct commit *commit, void *data)
937 {
938         struct bitmap_test_data *tdata = data;
939         int bitmap_pos;
940
941         bitmap_pos = bitmap_position(tdata->bitmap_git,
942                                      commit->object.oid.hash);
943         if (bitmap_pos < 0)
944                 die("Object not in bitmap: %s\n", oid_to_hex(&commit->object.oid));
945
946         bitmap_set(tdata->base, bitmap_pos);
947         display_progress(tdata->prg, ++tdata->seen);
948 }
949
950 void test_bitmap_walk(struct rev_info *revs)
951 {
952         struct object *root;
953         struct bitmap *result = NULL;
954         khiter_t pos;
955         size_t result_popcnt;
956         struct bitmap_test_data tdata;
957         struct bitmap_index *bitmap_git;
958
959         if (!(bitmap_git = prepare_bitmap_git(revs->repo)))
960                 die("failed to load bitmap indexes");
961
962         if (revs->pending.nr != 1)
963                 die("you must specify exactly one commit to test");
964
965         fprintf(stderr, "Bitmap v%d test (%d entries loaded)\n",
966                 bitmap_git->version, bitmap_git->entry_count);
967
968         root = revs->pending.objects[0].item;
969         pos = kh_get_sha1(bitmap_git->bitmaps, root->oid.hash);
970
971         if (pos < kh_end(bitmap_git->bitmaps)) {
972                 struct stored_bitmap *st = kh_value(bitmap_git->bitmaps, pos);
973                 struct ewah_bitmap *bm = lookup_stored_bitmap(st);
974
975                 fprintf(stderr, "Found bitmap for %s. %d bits / %08x checksum\n",
976                         oid_to_hex(&root->oid), (int)bm->bit_size, ewah_checksum(bm));
977
978                 result = ewah_to_bitmap(bm);
979         }
980
981         if (result == NULL)
982                 die("Commit %s doesn't have an indexed bitmap", oid_to_hex(&root->oid));
983
984         revs->tag_objects = 1;
985         revs->tree_objects = 1;
986         revs->blob_objects = 1;
987
988         result_popcnt = bitmap_popcount(result);
989
990         if (prepare_revision_walk(revs))
991                 die("revision walk setup failed");
992
993         tdata.bitmap_git = bitmap_git;
994         tdata.base = bitmap_new();
995         tdata.prg = start_progress("Verifying bitmap entries", result_popcnt);
996         tdata.seen = 0;
997
998         traverse_commit_list(revs, &test_show_commit, &test_show_object, &tdata);
999
1000         stop_progress(&tdata.prg);
1001
1002         if (bitmap_equals(result, tdata.base))
1003                 fprintf(stderr, "OK!\n");
1004         else
1005                 fprintf(stderr, "Mismatch!\n");
1006
1007         free_bitmap_index(bitmap_git);
1008 }
1009
1010 static int rebuild_bitmap(uint32_t *reposition,
1011                           struct ewah_bitmap *source,
1012                           struct bitmap *dest)
1013 {
1014         uint32_t pos = 0;
1015         struct ewah_iterator it;
1016         eword_t word;
1017
1018         ewah_iterator_init(&it, source);
1019
1020         while (ewah_iterator_next(&word, &it)) {
1021                 uint32_t offset, bit_pos;
1022
1023                 for (offset = 0; offset < BITS_IN_EWORD; ++offset) {
1024                         if ((word >> offset) == 0)
1025                                 break;
1026
1027                         offset += ewah_bit_ctz64(word >> offset);
1028
1029                         bit_pos = reposition[pos + offset];
1030                         if (bit_pos > 0)
1031                                 bitmap_set(dest, bit_pos - 1);
1032                         else /* can't reuse, we don't have the object */
1033                                 return -1;
1034                 }
1035
1036                 pos += BITS_IN_EWORD;
1037         }
1038         return 0;
1039 }
1040
1041 int rebuild_existing_bitmaps(struct bitmap_index *bitmap_git,
1042                              struct packing_data *mapping,
1043                              khash_sha1 *reused_bitmaps,
1044                              int show_progress)
1045 {
1046         uint32_t i, num_objects;
1047         uint32_t *reposition;
1048         struct bitmap *rebuild;
1049         struct stored_bitmap *stored;
1050         struct progress *progress = NULL;
1051
1052         khiter_t hash_pos;
1053         int hash_ret;
1054
1055         num_objects = bitmap_git->pack->num_objects;
1056         reposition = xcalloc(num_objects, sizeof(uint32_t));
1057
1058         for (i = 0; i < num_objects; ++i) {
1059                 const unsigned char *sha1;
1060                 struct revindex_entry *entry;
1061                 struct object_entry *oe;
1062
1063                 entry = &bitmap_git->pack->revindex[i];
1064                 sha1 = nth_packed_object_sha1(bitmap_git->pack, entry->nr);
1065                 oe = packlist_find(mapping, sha1, NULL);
1066
1067                 if (oe)
1068                         reposition[i] = oe_in_pack_pos(mapping, oe) + 1;
1069         }
1070
1071         rebuild = bitmap_new();
1072         i = 0;
1073
1074         if (show_progress)
1075                 progress = start_progress("Reusing bitmaps", 0);
1076
1077         kh_foreach_value(bitmap_git->bitmaps, stored, {
1078                 if (stored->flags & BITMAP_FLAG_REUSE) {
1079                         if (!rebuild_bitmap(reposition,
1080                                             lookup_stored_bitmap(stored),
1081                                             rebuild)) {
1082                                 hash_pos = kh_put_sha1(reused_bitmaps,
1083                                                        stored->sha1,
1084                                                        &hash_ret);
1085                                 kh_value(reused_bitmaps, hash_pos) =
1086                                         bitmap_to_ewah(rebuild);
1087                         }
1088                         bitmap_reset(rebuild);
1089                         display_progress(progress, ++i);
1090                 }
1091         });
1092
1093         stop_progress(&progress);
1094
1095         free(reposition);
1096         bitmap_free(rebuild);
1097         return 0;
1098 }
1099
1100 void free_bitmap_index(struct bitmap_index *b)
1101 {
1102         if (!b)
1103                 return;
1104
1105         if (b->map)
1106                 munmap(b->map, b->map_size);
1107         ewah_pool_free(b->commits);
1108         ewah_pool_free(b->trees);
1109         ewah_pool_free(b->blobs);
1110         ewah_pool_free(b->tags);
1111         kh_destroy_sha1(b->bitmaps);
1112         free(b->ext_index.objects);
1113         free(b->ext_index.hashes);
1114         bitmap_free(b->result);
1115         bitmap_free(b->haves);
1116         free(b);
1117 }
1118
1119 int bitmap_has_sha1_in_uninteresting(struct bitmap_index *bitmap_git,
1120                                      const unsigned char *sha1)
1121 {
1122         int pos;
1123
1124         if (!bitmap_git)
1125                 return 0; /* no bitmap loaded */
1126         if (!bitmap_git->haves)
1127                 return 0; /* walk had no "haves" */
1128
1129         pos = bitmap_position_packfile(bitmap_git, sha1);
1130         if (pos < 0)
1131                 return 0;
1132
1133         return bitmap_get(bitmap_git->haves, pos);
1134 }