1 // SPDX-License-Identifier: GPL-2.0
3 * Code for working with individual keys, and sorted sets of keys with in a
6 * Copyright 2012 Google, Inc.
9 #define pr_fmt(fmt) "bcache: %s() " fmt "\n", __func__
14 #include <linux/console.h>
15 #include <linux/sched/clock.h>
16 #include <linux/random.h>
17 #include <linux/prefetch.h>
19 #ifdef CONFIG_BCACHE_DEBUG
21 void bch_dump_bset(struct btree_keys *b, struct bset *i, unsigned int set)
23 struct bkey *k, *next;
25 for (k = i->start; k < bset_bkey_last(i); k = next) {
28 printk(KERN_ERR "block %u key %u/%u: ", set,
29 (unsigned int) ((u64 *) k - i->d), i->keys);
32 b->ops->key_dump(b, k);
34 printk("%llu:%llu\n", KEY_INODE(k), KEY_OFFSET(k));
36 if (next < bset_bkey_last(i) &&
37 bkey_cmp(k, b->ops->is_extents ?
38 &START_KEY(next) : next) > 0)
39 printk(KERN_ERR "Key skipped backwards\n");
43 void bch_dump_bucket(struct btree_keys *b)
48 for (i = 0; i <= b->nsets; i++)
49 bch_dump_bset(b, b->set[i].data,
50 bset_sector_offset(b, b->set[i].data));
54 int __bch_count_data(struct btree_keys *b)
57 struct btree_iter iter;
60 if (b->ops->is_extents)
61 for_each_key(b, k, &iter)
66 void __bch_check_keys(struct btree_keys *b, const char *fmt, ...)
69 struct bkey *k, *p = NULL;
70 struct btree_iter iter;
73 for_each_key(b, k, &iter) {
74 if (b->ops->is_extents) {
75 err = "Keys out of order";
76 if (p && bkey_cmp(&START_KEY(p), &START_KEY(k)) > 0)
79 if (bch_ptr_invalid(b, k))
82 err = "Overlapping keys";
83 if (p && bkey_cmp(p, &START_KEY(k)) > 0)
86 if (bch_ptr_bad(b, k))
89 err = "Duplicate keys";
90 if (p && !bkey_cmp(p, k))
96 err = "Key larger than btree node key";
97 if (p && bkey_cmp(p, &b->key) > 0)
108 panic("bch_check_keys error: %s:\n", err);
111 static void bch_btree_iter_next_check(struct btree_iter *iter)
113 struct bkey *k = iter->data->k, *next = bkey_next(k);
115 if (next < iter->data->end &&
116 bkey_cmp(k, iter->b->ops->is_extents ?
117 &START_KEY(next) : next) > 0) {
118 bch_dump_bucket(iter->b);
119 panic("Key skipped backwards\n");
125 static inline void bch_btree_iter_next_check(struct btree_iter *iter) {}
131 int __bch_keylist_realloc(struct keylist *l, unsigned int u64s)
133 size_t oldsize = bch_keylist_nkeys(l);
134 size_t newsize = oldsize + u64s;
135 uint64_t *old_keys = l->keys_p == l->inline_keys ? NULL : l->keys_p;
138 newsize = roundup_pow_of_two(newsize);
140 if (newsize <= KEYLIST_INLINE ||
141 roundup_pow_of_two(oldsize) == newsize)
144 new_keys = krealloc(old_keys, sizeof(uint64_t) * newsize, GFP_NOIO);
150 memcpy(new_keys, l->inline_keys, sizeof(uint64_t) * oldsize);
152 l->keys_p = new_keys;
153 l->top_p = new_keys + oldsize;
158 struct bkey *bch_keylist_pop(struct keylist *l)
160 struct bkey *k = l->keys;
165 while (bkey_next(k) != l->top)
171 void bch_keylist_pop_front(struct keylist *l)
173 l->top_p -= bkey_u64s(l->keys);
177 bch_keylist_bytes(l));
180 /* Key/pointer manipulation */
182 void bch_bkey_copy_single_ptr(struct bkey *dest, const struct bkey *src,
185 BUG_ON(i > KEY_PTRS(src));
187 /* Only copy the header, key, and one pointer. */
188 memcpy(dest, src, 2 * sizeof(uint64_t));
189 dest->ptr[0] = src->ptr[i];
190 SET_KEY_PTRS(dest, 1);
191 /* We didn't copy the checksum so clear that bit. */
192 SET_KEY_CSUM(dest, 0);
195 bool __bch_cut_front(const struct bkey *where, struct bkey *k)
197 unsigned int i, len = 0;
199 if (bkey_cmp(where, &START_KEY(k)) <= 0)
202 if (bkey_cmp(where, k) < 0)
203 len = KEY_OFFSET(k) - KEY_OFFSET(where);
205 bkey_copy_key(k, where);
207 for (i = 0; i < KEY_PTRS(k); i++)
208 SET_PTR_OFFSET(k, i, PTR_OFFSET(k, i) + KEY_SIZE(k) - len);
210 BUG_ON(len > KEY_SIZE(k));
211 SET_KEY_SIZE(k, len);
215 bool __bch_cut_back(const struct bkey *where, struct bkey *k)
217 unsigned int len = 0;
219 if (bkey_cmp(where, k) >= 0)
222 BUG_ON(KEY_INODE(where) != KEY_INODE(k));
224 if (bkey_cmp(where, &START_KEY(k)) > 0)
225 len = KEY_OFFSET(where) - KEY_START(k);
227 bkey_copy_key(k, where);
229 BUG_ON(len > KEY_SIZE(k));
230 SET_KEY_SIZE(k, len);
234 /* Auxiliary search trees */
237 #define BKEY_MID_BITS 3
238 #define BKEY_EXPONENT_BITS 7
239 #define BKEY_MANTISSA_BITS (32 - BKEY_MID_BITS - BKEY_EXPONENT_BITS)
240 #define BKEY_MANTISSA_MASK ((1 << BKEY_MANTISSA_BITS) - 1)
243 unsigned int exponent:BKEY_EXPONENT_BITS;
244 unsigned int m:BKEY_MID_BITS;
245 unsigned int mantissa:BKEY_MANTISSA_BITS;
249 * BSET_CACHELINE was originally intended to match the hardware cacheline size -
250 * it used to be 64, but I realized the lookup code would touch slightly less
251 * memory if it was 128.
253 * It definites the number of bytes (in struct bset) per struct bkey_float in
254 * the auxiliar search tree - when we're done searching the bset_float tree we
255 * have this many bytes left that we do a linear search over.
257 * Since (after level 5) every level of the bset_tree is on a new cacheline,
258 * we're touching one fewer cacheline in the bset tree in exchange for one more
259 * cacheline in the linear search - but the linear search might stop before it
260 * gets to the second cacheline.
263 #define BSET_CACHELINE 128
265 /* Space required for the btree node keys */
266 static inline size_t btree_keys_bytes(struct btree_keys *b)
268 return PAGE_SIZE << b->page_order;
271 static inline size_t btree_keys_cachelines(struct btree_keys *b)
273 return btree_keys_bytes(b) / BSET_CACHELINE;
276 /* Space required for the auxiliary search trees */
277 static inline size_t bset_tree_bytes(struct btree_keys *b)
279 return btree_keys_cachelines(b) * sizeof(struct bkey_float);
282 /* Space required for the prev pointers */
283 static inline size_t bset_prev_bytes(struct btree_keys *b)
285 return btree_keys_cachelines(b) * sizeof(uint8_t);
288 /* Memory allocation */
290 void bch_btree_keys_free(struct btree_keys *b)
292 struct bset_tree *t = b->set;
294 if (bset_prev_bytes(b) < PAGE_SIZE)
297 free_pages((unsigned long) t->prev,
298 get_order(bset_prev_bytes(b)));
300 if (bset_tree_bytes(b) < PAGE_SIZE)
303 free_pages((unsigned long) t->tree,
304 get_order(bset_tree_bytes(b)));
306 free_pages((unsigned long) t->data, b->page_order);
312 EXPORT_SYMBOL(bch_btree_keys_free);
314 int bch_btree_keys_alloc(struct btree_keys *b, unsigned int page_order, gfp_t gfp)
316 struct bset_tree *t = b->set;
320 b->page_order = page_order;
322 t->data = (void *) __get_free_pages(gfp, b->page_order);
326 t->tree = bset_tree_bytes(b) < PAGE_SIZE
327 ? kmalloc(bset_tree_bytes(b), gfp)
328 : (void *) __get_free_pages(gfp, get_order(bset_tree_bytes(b)));
332 t->prev = bset_prev_bytes(b) < PAGE_SIZE
333 ? kmalloc(bset_prev_bytes(b), gfp)
334 : (void *) __get_free_pages(gfp, get_order(bset_prev_bytes(b)));
340 bch_btree_keys_free(b);
343 EXPORT_SYMBOL(bch_btree_keys_alloc);
345 void bch_btree_keys_init(struct btree_keys *b, const struct btree_keys_ops *ops,
346 bool *expensive_debug_checks)
351 b->expensive_debug_checks = expensive_debug_checks;
353 b->last_set_unwritten = 0;
355 /* XXX: shouldn't be needed */
356 for (i = 0; i < MAX_BSETS; i++)
359 * Second loop starts at 1 because b->keys[0]->data is the memory we
362 for (i = 1; i < MAX_BSETS; i++)
363 b->set[i].data = NULL;
365 EXPORT_SYMBOL(bch_btree_keys_init);
367 /* Binary tree stuff for auxiliary search trees */
370 * return array index next to j when does in-order traverse
371 * of a binary tree which is stored in a linear array
373 static unsigned int inorder_next(unsigned int j, unsigned int size)
375 if (j * 2 + 1 < size) {
387 * return array index previous to j when does in-order traverse
388 * of a binary tree which is stored in a linear array
390 static unsigned int inorder_prev(unsigned int j, unsigned int size)
395 while (j * 2 + 1 < size)
403 /* I have no idea why this code works... and I'm the one who wrote it
405 * However, I do know what it does:
406 * Given a binary tree constructed in an array (i.e. how you normally implement
407 * a heap), it converts a node in the tree - referenced by array index - to the
408 * index it would have if you did an inorder traversal.
410 * Also tested for every j, size up to size somewhere around 6 million.
412 * The binary tree starts at array index 1, not 0
413 * extra is a function of size:
414 * extra = (size - rounddown_pow_of_two(size - 1)) << 1;
416 static unsigned int __to_inorder(unsigned int j,
420 unsigned int b = fls(j);
421 unsigned int shift = fls(size - 1) - b;
429 j -= (j - extra) >> 1;
435 * Return the cacheline index in bset_tree->data, where j is index
436 * from a linear array which stores the auxiliar binary tree
438 static unsigned int to_inorder(unsigned int j, struct bset_tree *t)
440 return __to_inorder(j, t->size, t->extra);
443 static unsigned int __inorder_to_tree(unsigned int j,
455 j |= roundup_pow_of_two(size) >> shift;
461 * Return an index from a linear array which stores the auxiliar binary
462 * tree, j is the cacheline index of t->data.
464 static unsigned int inorder_to_tree(unsigned int j, struct bset_tree *t)
466 return __inorder_to_tree(j, t->size, t->extra);
470 void inorder_test(void)
472 unsigned long done = 0;
473 ktime_t start = ktime_get();
475 for (unsigned int size = 2;
478 unsigned int extra = (size - rounddown_pow_of_two(size - 1)) << 1;
479 unsigned int i = 1, j = rounddown_pow_of_two(size - 1);
482 printk(KERN_NOTICE "loop %u, %llu per us\n", size,
483 done / ktime_us_delta(ktime_get(), start));
486 if (__inorder_to_tree(i, size, extra) != j)
487 panic("size %10u j %10u i %10u", size, j, i);
489 if (__to_inorder(j, size, extra) != i)
490 panic("size %10u j %10u i %10u", size, j, i);
492 if (j == rounddown_pow_of_two(size) - 1)
495 BUG_ON(inorder_prev(inorder_next(j, size), size) != j);
497 j = inorder_next(j, size);
507 * Cacheline/offset <-> bkey pointer arithmetic:
509 * t->tree is a binary search tree in an array; each node corresponds to a key
510 * in one cacheline in t->set (BSET_CACHELINE bytes).
512 * This means we don't have to store the full index of the key that a node in
513 * the binary tree points to; to_inorder() gives us the cacheline, and then
514 * bkey_float->m gives us the offset within that cacheline, in units of 8 bytes.
516 * cacheline_to_bkey() and friends abstract out all the pointer arithmetic to
519 * To construct the bfloat for an arbitrary key we need to know what the key
520 * immediately preceding it is: we have to check if the two keys differ in the
521 * bits we're going to store in bkey_float->mantissa. t->prev[j] stores the size
522 * of the previous key so we can walk backwards to it from t->tree[j]'s key.
525 static struct bkey *cacheline_to_bkey(struct bset_tree *t,
526 unsigned int cacheline,
529 return ((void *) t->data) + cacheline * BSET_CACHELINE + offset * 8;
532 static unsigned int bkey_to_cacheline(struct bset_tree *t, struct bkey *k)
534 return ((void *) k - (void *) t->data) / BSET_CACHELINE;
537 static unsigned int bkey_to_cacheline_offset(struct bset_tree *t,
538 unsigned int cacheline,
541 return (u64 *) k - (u64 *) cacheline_to_bkey(t, cacheline, 0);
544 static struct bkey *tree_to_bkey(struct bset_tree *t, unsigned int j)
546 return cacheline_to_bkey(t, to_inorder(j, t), t->tree[j].m);
549 static struct bkey *tree_to_prev_bkey(struct bset_tree *t, unsigned int j)
551 return (void *) (((uint64_t *) tree_to_bkey(t, j)) - t->prev[j]);
555 * For the write set - the one we're currently inserting keys into - we don't
556 * maintain a full search tree, we just keep a simple lookup table in t->prev.
558 static struct bkey *table_to_bkey(struct bset_tree *t, unsigned int cacheline)
560 return cacheline_to_bkey(t, cacheline, t->prev[cacheline]);
563 static inline uint64_t shrd128(uint64_t high, uint64_t low, uint8_t shift)
566 low |= (high << 1) << (63U - shift);
571 * Calculate mantissa value for struct bkey_float.
572 * If most significant bit of f->exponent is not set, then
573 * - f->exponent >> 6 is 0
574 * - p[0] points to bkey->low
575 * - p[-1] borrows bits from KEY_INODE() of bkey->high
576 * if most isgnificant bits of f->exponent is set, then
577 * - f->exponent >> 6 is 1
578 * - p[0] points to bits from KEY_INODE() of bkey->high
579 * - p[-1] points to other bits from KEY_INODE() of
581 * See make_bfloat() to check when most significant bit of f->exponent
584 static inline unsigned int bfloat_mantissa(const struct bkey *k,
585 struct bkey_float *f)
587 const uint64_t *p = &k->low - (f->exponent >> 6);
589 return shrd128(p[-1], p[0], f->exponent & 63) & BKEY_MANTISSA_MASK;
592 static void make_bfloat(struct bset_tree *t, unsigned int j)
594 struct bkey_float *f = &t->tree[j];
595 struct bkey *m = tree_to_bkey(t, j);
596 struct bkey *p = tree_to_prev_bkey(t, j);
598 struct bkey *l = is_power_of_2(j)
600 : tree_to_prev_bkey(t, j >> ffs(j));
602 struct bkey *r = is_power_of_2(j + 1)
603 ? bset_bkey_idx(t->data, t->data->keys - bkey_u64s(&t->end))
604 : tree_to_bkey(t, j >> (ffz(j) + 1));
606 BUG_ON(m < l || m > r);
607 BUG_ON(bkey_next(p) != m);
610 * If l and r have different KEY_INODE values (different backing
611 * device), f->exponent records how many least significant bits
612 * are different in KEY_INODE values and sets most significant
613 * bits to 1 (by +64).
614 * If l and r have same KEY_INODE value, f->exponent records
615 * how many different bits in least significant bits of bkey->low.
616 * See bfloat_mantiss() how the most significant bit of
617 * f->exponent is used to calculate bfloat mantissa value.
619 if (KEY_INODE(l) != KEY_INODE(r))
620 f->exponent = fls64(KEY_INODE(r) ^ KEY_INODE(l)) + 64;
622 f->exponent = fls64(r->low ^ l->low);
624 f->exponent = max_t(int, f->exponent - BKEY_MANTISSA_BITS, 0);
627 * Setting f->exponent = 127 flags this node as failed, and causes the
628 * lookup code to fall back to comparing against the original key.
631 if (bfloat_mantissa(m, f) != bfloat_mantissa(p, f))
632 f->mantissa = bfloat_mantissa(m, f) - 1;
637 static void bset_alloc_tree(struct btree_keys *b, struct bset_tree *t)
640 unsigned int j = roundup(t[-1].size,
641 64 / sizeof(struct bkey_float));
643 t->tree = t[-1].tree + j;
644 t->prev = t[-1].prev + j;
647 while (t < b->set + MAX_BSETS)
651 static void bch_bset_build_unwritten_tree(struct btree_keys *b)
653 struct bset_tree *t = bset_tree_last(b);
655 BUG_ON(b->last_set_unwritten);
656 b->last_set_unwritten = 1;
658 bset_alloc_tree(b, t);
660 if (t->tree != b->set->tree + btree_keys_cachelines(b)) {
661 t->prev[0] = bkey_to_cacheline_offset(t, 0, t->data->start);
666 void bch_bset_init_next(struct btree_keys *b, struct bset *i, uint64_t magic)
668 if (i != b->set->data) {
669 b->set[++b->nsets].data = i;
670 i->seq = b->set->data->seq;
672 get_random_bytes(&i->seq, sizeof(uint64_t));
678 bch_bset_build_unwritten_tree(b);
680 EXPORT_SYMBOL(bch_bset_init_next);
683 * Build auxiliary binary tree 'struct bset_tree *t', this tree is used to
684 * accelerate bkey search in a btree node (pointed by bset_tree->data in
685 * memory). After search in the auxiliar tree by calling bset_search_tree(),
686 * a struct bset_search_iter is returned which indicates range [l, r] from
687 * bset_tree->data where the searching bkey might be inside. Then a followed
688 * linear comparison does the exact search, see __bch_bset_search() for how
689 * the auxiliary tree is used.
691 void bch_bset_build_written_tree(struct btree_keys *b)
693 struct bset_tree *t = bset_tree_last(b);
694 struct bkey *prev = NULL, *k = t->data->start;
695 unsigned int j, cacheline = 1;
697 b->last_set_unwritten = 0;
699 bset_alloc_tree(b, t);
701 t->size = min_t(unsigned int,
702 bkey_to_cacheline(t, bset_bkey_last(t->data)),
703 b->set->tree + btree_keys_cachelines(b) - t->tree);
710 t->extra = (t->size - rounddown_pow_of_two(t->size - 1)) << 1;
712 /* First we figure out where the first key in each cacheline is */
713 for (j = inorder_next(0, t->size);
715 j = inorder_next(j, t->size)) {
716 while (bkey_to_cacheline(t, k) < cacheline)
717 prev = k, k = bkey_next(k);
719 t->prev[j] = bkey_u64s(prev);
720 t->tree[j].m = bkey_to_cacheline_offset(t, cacheline++, k);
723 while (bkey_next(k) != bset_bkey_last(t->data))
728 /* Then we build the tree */
729 for (j = inorder_next(0, t->size);
731 j = inorder_next(j, t->size))
734 EXPORT_SYMBOL(bch_bset_build_written_tree);
738 void bch_bset_fix_invalidated_key(struct btree_keys *b, struct bkey *k)
741 unsigned int inorder, j = 1;
743 for (t = b->set; t <= bset_tree_last(b); t++)
744 if (k < bset_bkey_last(t->data))
749 if (!t->size || !bset_written(b, t))
752 inorder = bkey_to_cacheline(t, k);
754 if (k == t->data->start)
757 if (bkey_next(k) == bset_bkey_last(t->data)) {
762 j = inorder_to_tree(inorder, t);
766 k == tree_to_bkey(t, j))
770 } while (j < t->size);
772 j = inorder_to_tree(inorder + 1, t);
776 k == tree_to_prev_bkey(t, j))
780 } while (j < t->size);
782 EXPORT_SYMBOL(bch_bset_fix_invalidated_key);
784 static void bch_bset_fix_lookup_table(struct btree_keys *b,
788 unsigned int shift = bkey_u64s(k);
789 unsigned int j = bkey_to_cacheline(t, k);
791 /* We're getting called from btree_split() or btree_gc, just bail out */
795 /* k is the key we just inserted; we need to find the entry in the
796 * lookup table for the first key that is strictly greater than k:
797 * it's either k's cacheline or the next one
799 while (j < t->size &&
800 table_to_bkey(t, j) <= k)
803 /* Adjust all the lookup table entries, and find a new key for any that
804 * have gotten too big
806 for (; j < t->size; j++) {
809 if (t->prev[j] > 7) {
810 k = table_to_bkey(t, j - 1);
812 while (k < cacheline_to_bkey(t, j, 0))
815 t->prev[j] = bkey_to_cacheline_offset(t, j, k);
819 if (t->size == b->set->tree + btree_keys_cachelines(b) - t->tree)
822 /* Possibly add a new entry to the end of the lookup table */
824 for (k = table_to_bkey(t, t->size - 1);
825 k != bset_bkey_last(t->data);
827 if (t->size == bkey_to_cacheline(t, k)) {
828 t->prev[t->size] = bkey_to_cacheline_offset(t, t->size, k);
834 * Tries to merge l and r: l should be lower than r
835 * Returns true if we were able to merge. If we did merge, l will be the merged
836 * key, r will be untouched.
838 bool bch_bkey_try_merge(struct btree_keys *b, struct bkey *l, struct bkey *r)
840 if (!b->ops->key_merge)
844 * Generic header checks
845 * Assumes left and right are in order
846 * Left and right must be exactly aligned
848 if (!bch_bkey_equal_header(l, r) ||
849 bkey_cmp(l, &START_KEY(r)))
852 return b->ops->key_merge(b, l, r);
854 EXPORT_SYMBOL(bch_bkey_try_merge);
856 void bch_bset_insert(struct btree_keys *b, struct bkey *where,
859 struct bset_tree *t = bset_tree_last(b);
861 BUG_ON(!b->last_set_unwritten);
862 BUG_ON(bset_byte_offset(b, t->data) +
863 __set_bytes(t->data, t->data->keys + bkey_u64s(insert)) >
864 PAGE_SIZE << b->page_order);
866 memmove((uint64_t *) where + bkey_u64s(insert),
868 (void *) bset_bkey_last(t->data) - (void *) where);
870 t->data->keys += bkey_u64s(insert);
871 bkey_copy(where, insert);
872 bch_bset_fix_lookup_table(b, t, where);
874 EXPORT_SYMBOL(bch_bset_insert);
876 unsigned int bch_btree_insert_key(struct btree_keys *b, struct bkey *k,
877 struct bkey *replace_key)
879 unsigned int status = BTREE_INSERT_STATUS_NO_INSERT;
880 struct bset *i = bset_tree_last(b)->data;
881 struct bkey *m, *prev = NULL;
882 struct btree_iter iter;
884 BUG_ON(b->ops->is_extents && !KEY_SIZE(k));
886 m = bch_btree_iter_init(b, &iter, b->ops->is_extents
887 ? PRECEDING_KEY(&START_KEY(k))
890 if (b->ops->insert_fixup(b, k, &iter, replace_key))
893 status = BTREE_INSERT_STATUS_INSERT;
895 while (m != bset_bkey_last(i) &&
896 bkey_cmp(k, b->ops->is_extents ? &START_KEY(m) : m) > 0)
897 prev = m, m = bkey_next(m);
899 /* prev is in the tree, if we merge we're done */
900 status = BTREE_INSERT_STATUS_BACK_MERGE;
902 bch_bkey_try_merge(b, prev, k))
905 status = BTREE_INSERT_STATUS_OVERWROTE;
906 if (m != bset_bkey_last(i) &&
907 KEY_PTRS(m) == KEY_PTRS(k) && !KEY_SIZE(m))
910 status = BTREE_INSERT_STATUS_FRONT_MERGE;
911 if (m != bset_bkey_last(i) &&
912 bch_bkey_try_merge(b, k, m))
915 bch_bset_insert(b, m, k);
916 copy: bkey_copy(m, k);
920 EXPORT_SYMBOL(bch_btree_insert_key);
924 struct bset_search_iter {
928 static struct bset_search_iter bset_search_write_set(struct bset_tree *t,
929 const struct bkey *search)
931 unsigned int li = 0, ri = t->size;
933 while (li + 1 != ri) {
934 unsigned int m = (li + ri) >> 1;
936 if (bkey_cmp(table_to_bkey(t, m), search) > 0)
942 return (struct bset_search_iter) {
943 table_to_bkey(t, li),
944 ri < t->size ? table_to_bkey(t, ri) : bset_bkey_last(t->data)
948 static struct bset_search_iter bset_search_tree(struct bset_tree *t,
949 const struct bkey *search)
952 struct bkey_float *f;
953 unsigned int inorder, j, n = 1;
958 * If p < t->size, (int)(p - t->size) is a minus value and
959 * the most significant bit is set, right shifting 31 bits
960 * gets 1. If p >= t->size, the most significant bit is
961 * not set, right shifting 31 bits gets 0.
962 * So the following 2 lines equals to
965 * but a branch instruction is avoided.
967 unsigned int p = n << 4;
969 p &= ((int) (p - t->size)) >> 31;
971 prefetch(&t->tree[p]);
977 * Similar bit trick, use subtract operation to avoid a branch
980 * n = (f->mantissa > bfloat_mantissa())
984 * We need to subtract 1 from f->mantissa for the sign bit trick
985 * to work - that's done in make_bfloat()
987 if (likely(f->exponent != 127))
988 n = j * 2 + (((unsigned int)
990 bfloat_mantissa(search, f))) >> 31);
992 n = (bkey_cmp(tree_to_bkey(t, j), search) > 0)
995 } while (n < t->size);
997 inorder = to_inorder(j, t);
1000 * n would have been the node we recursed to - the low bit tells us if
1001 * we recursed left or recursed right.
1004 l = cacheline_to_bkey(t, inorder, f->m);
1006 if (++inorder != t->size) {
1007 f = &t->tree[inorder_next(j, t->size)];
1008 r = cacheline_to_bkey(t, inorder, f->m);
1010 r = bset_bkey_last(t->data);
1012 r = cacheline_to_bkey(t, inorder, f->m);
1015 f = &t->tree[inorder_prev(j, t->size)];
1016 l = cacheline_to_bkey(t, inorder, f->m);
1021 return (struct bset_search_iter) {l, r};
1024 struct bkey *__bch_bset_search(struct btree_keys *b, struct bset_tree *t,
1025 const struct bkey *search)
1027 struct bset_search_iter i;
1030 * First, we search for a cacheline, then lastly we do a linear search
1031 * within that cacheline.
1033 * To search for the cacheline, there's three different possibilities:
1034 * * The set is too small to have a search tree, so we just do a linear
1035 * search over the whole set.
1036 * * The set is the one we're currently inserting into; keeping a full
1037 * auxiliary search tree up to date would be too expensive, so we
1038 * use a much simpler lookup table to do a binary search -
1039 * bset_search_write_set().
1040 * * Or we use the auxiliary search tree we constructed earlier -
1041 * bset_search_tree()
1044 if (unlikely(!t->size)) {
1045 i.l = t->data->start;
1046 i.r = bset_bkey_last(t->data);
1047 } else if (bset_written(b, t)) {
1049 * Each node in the auxiliary search tree covers a certain range
1050 * of bits, and keys above and below the set it covers might
1051 * differ outside those bits - so we have to special case the
1052 * start and end - handle that here:
1055 if (unlikely(bkey_cmp(search, &t->end) >= 0))
1056 return bset_bkey_last(t->data);
1058 if (unlikely(bkey_cmp(search, t->data->start) < 0))
1059 return t->data->start;
1061 i = bset_search_tree(t, search);
1064 t->size < bkey_to_cacheline(t, bset_bkey_last(t->data)));
1066 i = bset_search_write_set(t, search);
1069 if (btree_keys_expensive_checks(b)) {
1070 BUG_ON(bset_written(b, t) &&
1071 i.l != t->data->start &&
1072 bkey_cmp(tree_to_prev_bkey(t,
1073 inorder_to_tree(bkey_to_cacheline(t, i.l), t)),
1076 BUG_ON(i.r != bset_bkey_last(t->data) &&
1077 bkey_cmp(i.r, search) <= 0);
1080 while (likely(i.l != i.r) &&
1081 bkey_cmp(i.l, search) <= 0)
1082 i.l = bkey_next(i.l);
1086 EXPORT_SYMBOL(__bch_bset_search);
1088 /* Btree iterator */
1090 typedef bool (btree_iter_cmp_fn)(struct btree_iter_set,
1091 struct btree_iter_set);
1093 static inline bool btree_iter_cmp(struct btree_iter_set l,
1094 struct btree_iter_set r)
1096 return bkey_cmp(l.k, r.k) > 0;
1099 static inline bool btree_iter_end(struct btree_iter *iter)
1104 void bch_btree_iter_push(struct btree_iter *iter, struct bkey *k,
1108 BUG_ON(!heap_add(iter,
1109 ((struct btree_iter_set) { k, end }),
1113 static struct bkey *__bch_btree_iter_init(struct btree_keys *b,
1114 struct btree_iter *iter,
1115 struct bkey *search,
1116 struct bset_tree *start)
1118 struct bkey *ret = NULL;
1120 iter->size = ARRAY_SIZE(iter->data);
1123 #ifdef CONFIG_BCACHE_DEBUG
1127 for (; start <= bset_tree_last(b); start++) {
1128 ret = bch_bset_search(b, start, search);
1129 bch_btree_iter_push(iter, ret, bset_bkey_last(start->data));
1135 struct bkey *bch_btree_iter_init(struct btree_keys *b,
1136 struct btree_iter *iter,
1137 struct bkey *search)
1139 return __bch_btree_iter_init(b, iter, search, b->set);
1141 EXPORT_SYMBOL(bch_btree_iter_init);
1143 static inline struct bkey *__bch_btree_iter_next(struct btree_iter *iter,
1144 btree_iter_cmp_fn *cmp)
1146 struct btree_iter_set b __maybe_unused;
1147 struct bkey *ret = NULL;
1149 if (!btree_iter_end(iter)) {
1150 bch_btree_iter_next_check(iter);
1152 ret = iter->data->k;
1153 iter->data->k = bkey_next(iter->data->k);
1155 if (iter->data->k > iter->data->end) {
1156 WARN_ONCE(1, "bset was corrupt!\n");
1157 iter->data->k = iter->data->end;
1160 if (iter->data->k == iter->data->end)
1161 heap_pop(iter, b, cmp);
1163 heap_sift(iter, 0, cmp);
1169 struct bkey *bch_btree_iter_next(struct btree_iter *iter)
1171 return __bch_btree_iter_next(iter, btree_iter_cmp);
1174 EXPORT_SYMBOL(bch_btree_iter_next);
1176 struct bkey *bch_btree_iter_next_filter(struct btree_iter *iter,
1177 struct btree_keys *b, ptr_filter_fn fn)
1182 ret = bch_btree_iter_next(iter);
1183 } while (ret && fn(b, ret));
1190 void bch_bset_sort_state_free(struct bset_sort_state *state)
1192 mempool_exit(&state->pool);
1195 int bch_bset_sort_state_init(struct bset_sort_state *state,
1196 unsigned int page_order)
1198 spin_lock_init(&state->time.lock);
1200 state->page_order = page_order;
1201 state->crit_factor = int_sqrt(1 << page_order);
1203 return mempool_init_page_pool(&state->pool, 1, page_order);
1205 EXPORT_SYMBOL(bch_bset_sort_state_init);
1207 static void btree_mergesort(struct btree_keys *b, struct bset *out,
1208 struct btree_iter *iter,
1209 bool fixup, bool remove_stale)
1212 struct bkey *k, *last = NULL;
1214 bool (*bad)(struct btree_keys *, const struct bkey *) = remove_stale
1218 /* Heapify the iterator, using our comparison function */
1219 for (i = iter->used / 2 - 1; i >= 0; --i)
1220 heap_sift(iter, i, b->ops->sort_cmp);
1222 while (!btree_iter_end(iter)) {
1223 if (b->ops->sort_fixup && fixup)
1224 k = b->ops->sort_fixup(iter, &tmp.k);
1229 k = __bch_btree_iter_next(iter, b->ops->sort_cmp);
1237 } else if (!bch_bkey_try_merge(b, last, k)) {
1238 last = bkey_next(last);
1243 out->keys = last ? (uint64_t *) bkey_next(last) - out->d : 0;
1245 pr_debug("sorted %i keys", out->keys);
1248 static void __btree_sort(struct btree_keys *b, struct btree_iter *iter,
1249 unsigned int start, unsigned int order, bool fixup,
1250 struct bset_sort_state *state)
1252 uint64_t start_time;
1253 bool used_mempool = false;
1254 struct bset *out = (void *) __get_free_pages(__GFP_NOWARN|GFP_NOWAIT,
1259 BUG_ON(order > state->page_order);
1261 outp = mempool_alloc(&state->pool, GFP_NOIO);
1262 out = page_address(outp);
1263 used_mempool = true;
1264 order = state->page_order;
1267 start_time = local_clock();
1269 btree_mergesort(b, out, iter, fixup, false);
1272 if (!start && order == b->page_order) {
1274 * Our temporary buffer is the same size as the btree node's
1275 * buffer, we can just swap buffers instead of doing a big
1279 out->magic = b->set->data->magic;
1280 out->seq = b->set->data->seq;
1281 out->version = b->set->data->version;
1282 swap(out, b->set->data);
1284 b->set[start].data->keys = out->keys;
1285 memcpy(b->set[start].data->start, out->start,
1286 (void *) bset_bkey_last(out) - (void *) out->start);
1290 mempool_free(virt_to_page(out), &state->pool);
1292 free_pages((unsigned long) out, order);
1294 bch_bset_build_written_tree(b);
1297 bch_time_stats_update(&state->time, start_time);
1300 void bch_btree_sort_partial(struct btree_keys *b, unsigned int start,
1301 struct bset_sort_state *state)
1303 size_t order = b->page_order, keys = 0;
1304 struct btree_iter iter;
1305 int oldsize = bch_count_data(b);
1307 __bch_btree_iter_init(b, &iter, NULL, &b->set[start]);
1312 for (i = start; i <= b->nsets; i++)
1313 keys += b->set[i].data->keys;
1315 order = get_order(__set_bytes(b->set->data, keys));
1318 __btree_sort(b, &iter, start, order, false, state);
1320 EBUG_ON(oldsize >= 0 && bch_count_data(b) != oldsize);
1322 EXPORT_SYMBOL(bch_btree_sort_partial);
1324 void bch_btree_sort_and_fix_extents(struct btree_keys *b,
1325 struct btree_iter *iter,
1326 struct bset_sort_state *state)
1328 __btree_sort(b, iter, 0, b->page_order, true, state);
1331 void bch_btree_sort_into(struct btree_keys *b, struct btree_keys *new,
1332 struct bset_sort_state *state)
1334 uint64_t start_time = local_clock();
1335 struct btree_iter iter;
1337 bch_btree_iter_init(b, &iter, NULL);
1339 btree_mergesort(b, new->set->data, &iter, false, true);
1341 bch_time_stats_update(&state->time, start_time);
1343 new->set->size = 0; // XXX: why?
1346 #define SORT_CRIT (4096 / sizeof(uint64_t))
1348 void bch_btree_sort_lazy(struct btree_keys *b, struct bset_sort_state *state)
1350 unsigned int crit = SORT_CRIT;
1353 /* Don't sort if nothing to do */
1357 for (i = b->nsets - 1; i >= 0; --i) {
1358 crit *= state->crit_factor;
1360 if (b->set[i].data->keys < crit) {
1361 bch_btree_sort_partial(b, i, state);
1366 /* Sort if we'd overflow */
1367 if (b->nsets + 1 == MAX_BSETS) {
1368 bch_btree_sort(b, state);
1373 bch_bset_build_written_tree(b);
1375 EXPORT_SYMBOL(bch_btree_sort_lazy);
1377 void bch_btree_keys_stats(struct btree_keys *b, struct bset_stats *stats)
1381 for (i = 0; i <= b->nsets; i++) {
1382 struct bset_tree *t = &b->set[i];
1383 size_t bytes = t->data->keys * sizeof(uint64_t);
1386 if (bset_written(b, t)) {
1387 stats->sets_written++;
1388 stats->bytes_written += bytes;
1390 stats->floats += t->size - 1;
1392 for (j = 1; j < t->size; j++)
1393 if (t->tree[j].exponent == 127)
1396 stats->sets_unwritten++;
1397 stats->bytes_unwritten += bytes;