]> git.proxmox.com Git - mirror_ubuntu-focal-kernel.git/blame - drivers/md/bcache/bset.c
bcache: Make bch_keylist_realloc() take u64s, not nptrs
[mirror_ubuntu-focal-kernel.git] / drivers / md / bcache / bset.c
CommitLineData
cafe5635
KO
1/*
2 * Code for working with individual keys, and sorted sets of keys with in a
3 * btree node
4 *
5 * Copyright 2012 Google, Inc.
6 */
7
8#include "bcache.h"
9#include "btree.h"
10#include "debug.h"
11
12#include <linux/random.h>
cd953ed0 13#include <linux/prefetch.h>
cafe5635
KO
14
15/* Keylists */
16
085d2a3d 17int __bch_keylist_realloc(struct keylist *l, unsigned u64s)
cafe5635 18{
c2f95ae2 19 size_t oldsize = bch_keylist_nkeys(l);
085d2a3d 20 size_t newsize = oldsize + u64s;
c2f95ae2
KO
21 uint64_t *old_keys = l->keys_p == l->inline_keys ? NULL : l->keys_p;
22 uint64_t *new_keys;
cafe5635 23
cafe5635
KO
24 newsize = roundup_pow_of_two(newsize);
25
26 if (newsize <= KEYLIST_INLINE ||
27 roundup_pow_of_two(oldsize) == newsize)
28 return 0;
29
c2f95ae2 30 new_keys = krealloc(old_keys, sizeof(uint64_t) * newsize, GFP_NOIO);
cafe5635 31
c2f95ae2 32 if (!new_keys)
cafe5635
KO
33 return -ENOMEM;
34
c2f95ae2
KO
35 if (!old_keys)
36 memcpy(new_keys, l->inline_keys, sizeof(uint64_t) * oldsize);
cafe5635 37
c2f95ae2
KO
38 l->keys_p = new_keys;
39 l->top_p = new_keys + oldsize;
cafe5635
KO
40
41 return 0;
42}
43
44struct bkey *bch_keylist_pop(struct keylist *l)
45{
c2f95ae2 46 struct bkey *k = l->keys;
cafe5635
KO
47
48 if (k == l->top)
49 return NULL;
50
51 while (bkey_next(k) != l->top)
52 k = bkey_next(k);
53
54 return l->top = k;
55}
56
26c949f8
KO
57void bch_keylist_pop_front(struct keylist *l)
58{
c2f95ae2 59 l->top_p -= bkey_u64s(l->keys);
26c949f8 60
c2f95ae2
KO
61 memmove(l->keys,
62 bkey_next(l->keys),
63 bch_keylist_bytes(l));
26c949f8
KO
64}
65
cafe5635
KO
66/* Pointer validation */
67
d5cc66e9 68static bool __ptr_invalid(struct cache_set *c, const struct bkey *k)
cafe5635
KO
69{
70 unsigned i;
cafe5635
KO
71
72 for (i = 0; i < KEY_PTRS(k); i++)
73 if (ptr_available(c, k, i)) {
74 struct cache *ca = PTR_CACHE(c, k, i);
75 size_t bucket = PTR_BUCKET_NR(c, k, i);
76 size_t r = bucket_remainder(c, PTR_OFFSET(k, i));
77
78 if (KEY_SIZE(k) + r > c->sb.bucket_size ||
79 bucket < ca->sb.first_bucket ||
80 bucket >= ca->sb.nbuckets)
d5cc66e9 81 return true;
cafe5635
KO
82 }
83
d5cc66e9
KO
84 return false;
85}
86
87bool bch_btree_ptr_invalid(struct cache_set *c, const struct bkey *k)
88{
89 char buf[80];
90
91 if (!KEY_PTRS(k) || !KEY_SIZE(k) || KEY_DIRTY(k))
92 goto bad;
93
94 if (__ptr_invalid(c, k))
95 goto bad;
96
97 return false;
98bad:
99 bch_bkey_to_text(buf, sizeof(buf), k);
100 cache_bug(c, "spotted btree ptr %s: %s", buf, bch_ptr_status(c, k));
101 return true;
102}
103
104bool bch_extent_ptr_invalid(struct cache_set *c, const struct bkey *k)
105{
106 char buf[80];
107
108 if (!KEY_SIZE(k))
109 return true;
110
111 if (KEY_SIZE(k) > KEY_OFFSET(k))
112 goto bad;
113
114 if (__ptr_invalid(c, k))
115 goto bad;
116
cafe5635
KO
117 return false;
118bad:
85b1492e 119 bch_bkey_to_text(buf, sizeof(buf), k);
d5cc66e9 120 cache_bug(c, "spotted extent %s: %s", buf, bch_ptr_status(c, k));
cafe5635
KO
121 return true;
122}
123
280481d0
KO
124static bool ptr_bad_expensive_checks(struct btree *b, const struct bkey *k,
125 unsigned ptr)
126{
127 struct bucket *g = PTR_BUCKET(b->c, k, ptr);
128 char buf[80];
129
130 if (mutex_trylock(&b->c->bucket_lock)) {
131 if (b->level) {
132 if (KEY_DIRTY(k) ||
133 g->prio != BTREE_PRIO ||
134 (b->c->gc_mark_valid &&
135 GC_MARK(g) != GC_MARK_METADATA))
136 goto err;
137
138 } else {
139 if (g->prio == BTREE_PRIO)
140 goto err;
141
142 if (KEY_DIRTY(k) &&
143 b->c->gc_mark_valid &&
144 GC_MARK(g) != GC_MARK_DIRTY)
145 goto err;
146 }
147 mutex_unlock(&b->c->bucket_lock);
148 }
149
150 return false;
151err:
152 mutex_unlock(&b->c->bucket_lock);
153 bch_bkey_to_text(buf, sizeof(buf), k);
154 btree_bug(b,
155"inconsistent pointer %s: bucket %zu pin %i prio %i gen %i last_gc %i mark %llu gc_gen %i",
156 buf, PTR_BUCKET_NR(b->c, k, ptr), atomic_read(&g->pin),
157 g->prio, g->gen, g->last_gc, GC_MARK(g), g->gc_gen);
158 return true;
159}
160
cafe5635
KO
161bool bch_ptr_bad(struct btree *b, const struct bkey *k)
162{
163 struct bucket *g;
164 unsigned i, stale;
165
166 if (!bkey_cmp(k, &ZERO_KEY) ||
167 !KEY_PTRS(k) ||
168 bch_ptr_invalid(b, k))
169 return true;
170
d56d000a 171 for (i = 0; i < KEY_PTRS(k); i++)
e58ff155
KO
172 if (!ptr_available(b->c, k, i))
173 return true;
cafe5635 174
d56d000a
KO
175 if (!expensive_debug_checks(b->c) && KEY_DIRTY(k))
176 return false;
177
178 for (i = 0; i < KEY_PTRS(k); i++) {
e58ff155
KO
179 g = PTR_BUCKET(b->c, k, i);
180 stale = ptr_stale(b->c, k, i);
cafe5635 181
e58ff155
KO
182 btree_bug_on(stale > 96, b,
183 "key too stale: %i, need_gc %u",
184 stale, b->c->need_gc);
cafe5635 185
e58ff155
KO
186 btree_bug_on(stale && KEY_DIRTY(k) && KEY_SIZE(k),
187 b, "stale dirty pointer");
cafe5635 188
e58ff155
KO
189 if (stale)
190 return true;
cafe5635 191
280481d0
KO
192 if (expensive_debug_checks(b->c) &&
193 ptr_bad_expensive_checks(b, k, i))
194 return true;
e58ff155 195 }
cafe5635
KO
196
197 return false;
cafe5635
KO
198}
199
200/* Key/pointer manipulation */
201
202void bch_bkey_copy_single_ptr(struct bkey *dest, const struct bkey *src,
203 unsigned i)
204{
205 BUG_ON(i > KEY_PTRS(src));
206
207 /* Only copy the header, key, and one pointer. */
208 memcpy(dest, src, 2 * sizeof(uint64_t));
209 dest->ptr[0] = src->ptr[i];
210 SET_KEY_PTRS(dest, 1);
211 /* We didn't copy the checksum so clear that bit. */
212 SET_KEY_CSUM(dest, 0);
213}
214
215bool __bch_cut_front(const struct bkey *where, struct bkey *k)
216{
217 unsigned i, len = 0;
218
219 if (bkey_cmp(where, &START_KEY(k)) <= 0)
220 return false;
221
222 if (bkey_cmp(where, k) < 0)
223 len = KEY_OFFSET(k) - KEY_OFFSET(where);
224 else
225 bkey_copy_key(k, where);
226
227 for (i = 0; i < KEY_PTRS(k); i++)
228 SET_PTR_OFFSET(k, i, PTR_OFFSET(k, i) + KEY_SIZE(k) - len);
229
230 BUG_ON(len > KEY_SIZE(k));
231 SET_KEY_SIZE(k, len);
232 return true;
233}
234
235bool __bch_cut_back(const struct bkey *where, struct bkey *k)
236{
237 unsigned len = 0;
238
239 if (bkey_cmp(where, k) >= 0)
240 return false;
241
242 BUG_ON(KEY_INODE(where) != KEY_INODE(k));
243
244 if (bkey_cmp(where, &START_KEY(k)) > 0)
245 len = KEY_OFFSET(where) - KEY_START(k);
246
247 bkey_copy_key(k, where);
248
249 BUG_ON(len > KEY_SIZE(k));
250 SET_KEY_SIZE(k, len);
251 return true;
252}
253
254static uint64_t merge_chksums(struct bkey *l, struct bkey *r)
255{
256 return (l->ptr[KEY_PTRS(l)] + r->ptr[KEY_PTRS(r)]) &
257 ~((uint64_t)1 << 63);
258}
259
260/* Tries to merge l and r: l should be lower than r
261 * Returns true if we were able to merge. If we did merge, l will be the merged
262 * key, r will be untouched.
263 */
264bool bch_bkey_try_merge(struct btree *b, struct bkey *l, struct bkey *r)
265{
266 unsigned i;
267
268 if (key_merging_disabled(b->c))
269 return false;
270
271 if (KEY_PTRS(l) != KEY_PTRS(r) ||
272 KEY_DIRTY(l) != KEY_DIRTY(r) ||
273 bkey_cmp(l, &START_KEY(r)))
274 return false;
275
276 for (i = 0; i < KEY_PTRS(l); i++)
277 if (l->ptr[i] + PTR(0, KEY_SIZE(l), 0) != r->ptr[i] ||
278 PTR_BUCKET_NR(b->c, l, i) != PTR_BUCKET_NR(b->c, r, i))
279 return false;
280
281 /* Keys with no pointers aren't restricted to one bucket and could
282 * overflow KEY_SIZE
283 */
284 if (KEY_SIZE(l) + KEY_SIZE(r) > USHRT_MAX) {
285 SET_KEY_OFFSET(l, KEY_OFFSET(l) + USHRT_MAX - KEY_SIZE(l));
286 SET_KEY_SIZE(l, USHRT_MAX);
287
288 bch_cut_front(l, r);
289 return false;
290 }
291
292 if (KEY_CSUM(l)) {
293 if (KEY_CSUM(r))
294 l->ptr[KEY_PTRS(l)] = merge_chksums(l, r);
295 else
296 SET_KEY_CSUM(l, 0);
297 }
298
299 SET_KEY_OFFSET(l, KEY_OFFSET(l) + KEY_SIZE(r));
300 SET_KEY_SIZE(l, KEY_SIZE(l) + KEY_SIZE(r));
301
302 return true;
303}
304
305/* Binary tree stuff for auxiliary search trees */
306
307static unsigned inorder_next(unsigned j, unsigned size)
308{
309 if (j * 2 + 1 < size) {
310 j = j * 2 + 1;
311
312 while (j * 2 < size)
313 j *= 2;
314 } else
315 j >>= ffz(j) + 1;
316
317 return j;
318}
319
320static unsigned inorder_prev(unsigned j, unsigned size)
321{
322 if (j * 2 < size) {
323 j = j * 2;
324
325 while (j * 2 + 1 < size)
326 j = j * 2 + 1;
327 } else
328 j >>= ffs(j);
329
330 return j;
331}
332
333/* I have no idea why this code works... and I'm the one who wrote it
334 *
335 * However, I do know what it does:
336 * Given a binary tree constructed in an array (i.e. how you normally implement
337 * a heap), it converts a node in the tree - referenced by array index - to the
338 * index it would have if you did an inorder traversal.
339 *
340 * Also tested for every j, size up to size somewhere around 6 million.
341 *
342 * The binary tree starts at array index 1, not 0
343 * extra is a function of size:
344 * extra = (size - rounddown_pow_of_two(size - 1)) << 1;
345 */
346static unsigned __to_inorder(unsigned j, unsigned size, unsigned extra)
347{
348 unsigned b = fls(j);
349 unsigned shift = fls(size - 1) - b;
350
351 j ^= 1U << (b - 1);
352 j <<= 1;
353 j |= 1;
354 j <<= shift;
355
356 if (j > extra)
357 j -= (j - extra) >> 1;
358
359 return j;
360}
361
362static unsigned to_inorder(unsigned j, struct bset_tree *t)
363{
364 return __to_inorder(j, t->size, t->extra);
365}
366
367static unsigned __inorder_to_tree(unsigned j, unsigned size, unsigned extra)
368{
369 unsigned shift;
370
371 if (j > extra)
372 j += j - extra;
373
374 shift = ffs(j);
375
376 j >>= shift;
377 j |= roundup_pow_of_two(size) >> shift;
378
379 return j;
380}
381
382static unsigned inorder_to_tree(unsigned j, struct bset_tree *t)
383{
384 return __inorder_to_tree(j, t->size, t->extra);
385}
386
387#if 0
388void inorder_test(void)
389{
390 unsigned long done = 0;
391 ktime_t start = ktime_get();
392
393 for (unsigned size = 2;
394 size < 65536000;
395 size++) {
396 unsigned extra = (size - rounddown_pow_of_two(size - 1)) << 1;
397 unsigned i = 1, j = rounddown_pow_of_two(size - 1);
398
399 if (!(size % 4096))
400 printk(KERN_NOTICE "loop %u, %llu per us\n", size,
401 done / ktime_us_delta(ktime_get(), start));
402
403 while (1) {
404 if (__inorder_to_tree(i, size, extra) != j)
405 panic("size %10u j %10u i %10u", size, j, i);
406
407 if (__to_inorder(j, size, extra) != i)
408 panic("size %10u j %10u i %10u", size, j, i);
409
410 if (j == rounddown_pow_of_two(size) - 1)
411 break;
412
413 BUG_ON(inorder_prev(inorder_next(j, size), size) != j);
414
415 j = inorder_next(j, size);
416 i++;
417 }
418
419 done += size - 1;
420 }
421}
422#endif
423
424/*
48a73025 425 * Cacheline/offset <-> bkey pointer arithmetic:
cafe5635
KO
426 *
427 * t->tree is a binary search tree in an array; each node corresponds to a key
428 * in one cacheline in t->set (BSET_CACHELINE bytes).
429 *
430 * This means we don't have to store the full index of the key that a node in
431 * the binary tree points to; to_inorder() gives us the cacheline, and then
432 * bkey_float->m gives us the offset within that cacheline, in units of 8 bytes.
433 *
48a73025 434 * cacheline_to_bkey() and friends abstract out all the pointer arithmetic to
cafe5635
KO
435 * make this work.
436 *
437 * To construct the bfloat for an arbitrary key we need to know what the key
438 * immediately preceding it is: we have to check if the two keys differ in the
439 * bits we're going to store in bkey_float->mantissa. t->prev[j] stores the size
440 * of the previous key so we can walk backwards to it from t->tree[j]'s key.
441 */
442
443static struct bkey *cacheline_to_bkey(struct bset_tree *t, unsigned cacheline,
444 unsigned offset)
445{
446 return ((void *) t->data) + cacheline * BSET_CACHELINE + offset * 8;
447}
448
449static unsigned bkey_to_cacheline(struct bset_tree *t, struct bkey *k)
450{
451 return ((void *) k - (void *) t->data) / BSET_CACHELINE;
452}
453
454static unsigned bkey_to_cacheline_offset(struct bkey *k)
455{
456 return ((size_t) k & (BSET_CACHELINE - 1)) / sizeof(uint64_t);
457}
458
459static struct bkey *tree_to_bkey(struct bset_tree *t, unsigned j)
460{
461 return cacheline_to_bkey(t, to_inorder(j, t), t->tree[j].m);
462}
463
464static struct bkey *tree_to_prev_bkey(struct bset_tree *t, unsigned j)
465{
466 return (void *) (((uint64_t *) tree_to_bkey(t, j)) - t->prev[j]);
467}
468
469/*
470 * For the write set - the one we're currently inserting keys into - we don't
471 * maintain a full search tree, we just keep a simple lookup table in t->prev.
472 */
473static struct bkey *table_to_bkey(struct bset_tree *t, unsigned cacheline)
474{
475 return cacheline_to_bkey(t, cacheline, t->prev[cacheline]);
476}
477
478static inline uint64_t shrd128(uint64_t high, uint64_t low, uint8_t shift)
479{
cafe5635
KO
480 low >>= shift;
481 low |= (high << 1) << (63U - shift);
cafe5635
KO
482 return low;
483}
484
485static inline unsigned bfloat_mantissa(const struct bkey *k,
486 struct bkey_float *f)
487{
488 const uint64_t *p = &k->low - (f->exponent >> 6);
489 return shrd128(p[-1], p[0], f->exponent & 63) & BKEY_MANTISSA_MASK;
490}
491
492static void make_bfloat(struct bset_tree *t, unsigned j)
493{
494 struct bkey_float *f = &t->tree[j];
495 struct bkey *m = tree_to_bkey(t, j);
496 struct bkey *p = tree_to_prev_bkey(t, j);
497
498 struct bkey *l = is_power_of_2(j)
499 ? t->data->start
500 : tree_to_prev_bkey(t, j >> ffs(j));
501
502 struct bkey *r = is_power_of_2(j + 1)
503 ? node(t->data, t->data->keys - bkey_u64s(&t->end))
504 : tree_to_bkey(t, j >> (ffz(j) + 1));
505
506 BUG_ON(m < l || m > r);
507 BUG_ON(bkey_next(p) != m);
508
509 if (KEY_INODE(l) != KEY_INODE(r))
510 f->exponent = fls64(KEY_INODE(r) ^ KEY_INODE(l)) + 64;
511 else
512 f->exponent = fls64(r->low ^ l->low);
513
514 f->exponent = max_t(int, f->exponent - BKEY_MANTISSA_BITS, 0);
515
516 /*
517 * Setting f->exponent = 127 flags this node as failed, and causes the
518 * lookup code to fall back to comparing against the original key.
519 */
520
521 if (bfloat_mantissa(m, f) != bfloat_mantissa(p, f))
522 f->mantissa = bfloat_mantissa(m, f) - 1;
523 else
524 f->exponent = 127;
525}
526
527static void bset_alloc_tree(struct btree *b, struct bset_tree *t)
528{
529 if (t != b->sets) {
530 unsigned j = roundup(t[-1].size,
531 64 / sizeof(struct bkey_float));
532
533 t->tree = t[-1].tree + j;
534 t->prev = t[-1].prev + j;
535 }
536
537 while (t < b->sets + MAX_BSETS)
538 t++->size = 0;
539}
540
541static void bset_build_unwritten_tree(struct btree *b)
542{
543 struct bset_tree *t = b->sets + b->nsets;
544
545 bset_alloc_tree(b, t);
546
547 if (t->tree != b->sets->tree + bset_tree_space(b)) {
548 t->prev[0] = bkey_to_cacheline_offset(t->data->start);
549 t->size = 1;
550 }
551}
552
553static void bset_build_written_tree(struct btree *b)
554{
555 struct bset_tree *t = b->sets + b->nsets;
556 struct bkey *k = t->data->start;
557 unsigned j, cacheline = 1;
558
559 bset_alloc_tree(b, t);
560
561 t->size = min_t(unsigned,
562 bkey_to_cacheline(t, end(t->data)),
563 b->sets->tree + bset_tree_space(b) - t->tree);
564
565 if (t->size < 2) {
566 t->size = 0;
567 return;
568 }
569
570 t->extra = (t->size - rounddown_pow_of_two(t->size - 1)) << 1;
571
572 /* First we figure out where the first key in each cacheline is */
573 for (j = inorder_next(0, t->size);
574 j;
575 j = inorder_next(j, t->size)) {
576 while (bkey_to_cacheline(t, k) != cacheline)
577 k = bkey_next(k);
578
579 t->prev[j] = bkey_u64s(k);
580 k = bkey_next(k);
581 cacheline++;
582 t->tree[j].m = bkey_to_cacheline_offset(k);
583 }
584
585 while (bkey_next(k) != end(t->data))
586 k = bkey_next(k);
587
588 t->end = *k;
589
590 /* Then we build the tree */
591 for (j = inorder_next(0, t->size);
592 j;
593 j = inorder_next(j, t->size))
594 make_bfloat(t, j);
595}
596
597void bch_bset_fix_invalidated_key(struct btree *b, struct bkey *k)
598{
599 struct bset_tree *t;
600 unsigned inorder, j = 1;
601
602 for (t = b->sets; t <= &b->sets[b->nsets]; t++)
603 if (k < end(t->data))
604 goto found_set;
605
606 BUG();
607found_set:
608 if (!t->size || !bset_written(b, t))
609 return;
610
611 inorder = bkey_to_cacheline(t, k);
612
613 if (k == t->data->start)
614 goto fix_left;
615
616 if (bkey_next(k) == end(t->data)) {
617 t->end = *k;
618 goto fix_right;
619 }
620
621 j = inorder_to_tree(inorder, t);
622
623 if (j &&
624 j < t->size &&
625 k == tree_to_bkey(t, j))
626fix_left: do {
627 make_bfloat(t, j);
628 j = j * 2;
629 } while (j < t->size);
630
631 j = inorder_to_tree(inorder + 1, t);
632
633 if (j &&
634 j < t->size &&
635 k == tree_to_prev_bkey(t, j))
636fix_right: do {
637 make_bfloat(t, j);
638 j = j * 2 + 1;
639 } while (j < t->size);
640}
641
642void bch_bset_fix_lookup_table(struct btree *b, struct bkey *k)
643{
644 struct bset_tree *t = &b->sets[b->nsets];
645 unsigned shift = bkey_u64s(k);
646 unsigned j = bkey_to_cacheline(t, k);
647
648 /* We're getting called from btree_split() or btree_gc, just bail out */
649 if (!t->size)
650 return;
651
652 /* k is the key we just inserted; we need to find the entry in the
653 * lookup table for the first key that is strictly greater than k:
654 * it's either k's cacheline or the next one
655 */
656 if (j < t->size &&
657 table_to_bkey(t, j) <= k)
658 j++;
659
660 /* Adjust all the lookup table entries, and find a new key for any that
661 * have gotten too big
662 */
663 for (; j < t->size; j++) {
664 t->prev[j] += shift;
665
666 if (t->prev[j] > 7) {
667 k = table_to_bkey(t, j - 1);
668
669 while (k < cacheline_to_bkey(t, j, 0))
670 k = bkey_next(k);
671
672 t->prev[j] = bkey_to_cacheline_offset(k);
673 }
674 }
675
676 if (t->size == b->sets->tree + bset_tree_space(b) - t->tree)
677 return;
678
679 /* Possibly add a new entry to the end of the lookup table */
680
681 for (k = table_to_bkey(t, t->size - 1);
682 k != end(t->data);
683 k = bkey_next(k))
684 if (t->size == bkey_to_cacheline(t, k)) {
685 t->prev[t->size] = bkey_to_cacheline_offset(k);
686 t->size++;
687 }
688}
689
690void bch_bset_init_next(struct btree *b)
691{
692 struct bset *i = write_block(b);
693
694 if (i != b->sets[0].data) {
695 b->sets[++b->nsets].data = i;
696 i->seq = b->sets[0].data->seq;
697 } else
698 get_random_bytes(&i->seq, sizeof(uint64_t));
699
81ab4190 700 i->magic = bset_magic(&b->c->sb);
cafe5635
KO
701 i->version = 0;
702 i->keys = 0;
703
704 bset_build_unwritten_tree(b);
705}
706
707struct bset_search_iter {
708 struct bkey *l, *r;
709};
710
711static struct bset_search_iter bset_search_write_set(struct btree *b,
712 struct bset_tree *t,
713 const struct bkey *search)
714{
715 unsigned li = 0, ri = t->size;
716
717 BUG_ON(!b->nsets &&
718 t->size < bkey_to_cacheline(t, end(t->data)));
719
720 while (li + 1 != ri) {
721 unsigned m = (li + ri) >> 1;
722
723 if (bkey_cmp(table_to_bkey(t, m), search) > 0)
724 ri = m;
725 else
726 li = m;
727 }
728
729 return (struct bset_search_iter) {
730 table_to_bkey(t, li),
731 ri < t->size ? table_to_bkey(t, ri) : end(t->data)
732 };
733}
734
735static struct bset_search_iter bset_search_tree(struct btree *b,
736 struct bset_tree *t,
737 const struct bkey *search)
738{
739 struct bkey *l, *r;
740 struct bkey_float *f;
741 unsigned inorder, j, n = 1;
742
743 do {
744 unsigned p = n << 4;
745 p &= ((int) (p - t->size)) >> 31;
746
747 prefetch(&t->tree[p]);
748
749 j = n;
750 f = &t->tree[j];
751
752 /*
753 * n = (f->mantissa > bfloat_mantissa())
754 * ? j * 2
755 * : j * 2 + 1;
756 *
757 * We need to subtract 1 from f->mantissa for the sign bit trick
758 * to work - that's done in make_bfloat()
759 */
760 if (likely(f->exponent != 127))
761 n = j * 2 + (((unsigned)
762 (f->mantissa -
763 bfloat_mantissa(search, f))) >> 31);
764 else
765 n = (bkey_cmp(tree_to_bkey(t, j), search) > 0)
766 ? j * 2
767 : j * 2 + 1;
768 } while (n < t->size);
769
770 inorder = to_inorder(j, t);
771
772 /*
773 * n would have been the node we recursed to - the low bit tells us if
774 * we recursed left or recursed right.
775 */
776 if (n & 1) {
777 l = cacheline_to_bkey(t, inorder, f->m);
778
779 if (++inorder != t->size) {
780 f = &t->tree[inorder_next(j, t->size)];
781 r = cacheline_to_bkey(t, inorder, f->m);
782 } else
783 r = end(t->data);
784 } else {
785 r = cacheline_to_bkey(t, inorder, f->m);
786
787 if (--inorder) {
788 f = &t->tree[inorder_prev(j, t->size)];
789 l = cacheline_to_bkey(t, inorder, f->m);
790 } else
791 l = t->data->start;
792 }
793
794 return (struct bset_search_iter) {l, r};
795}
796
797struct bkey *__bch_bset_search(struct btree *b, struct bset_tree *t,
798 const struct bkey *search)
799{
800 struct bset_search_iter i;
801
802 /*
803 * First, we search for a cacheline, then lastly we do a linear search
804 * within that cacheline.
805 *
806 * To search for the cacheline, there's three different possibilities:
807 * * The set is too small to have a search tree, so we just do a linear
808 * search over the whole set.
809 * * The set is the one we're currently inserting into; keeping a full
810 * auxiliary search tree up to date would be too expensive, so we
811 * use a much simpler lookup table to do a binary search -
812 * bset_search_write_set().
813 * * Or we use the auxiliary search tree we constructed earlier -
814 * bset_search_tree()
815 */
816
817 if (unlikely(!t->size)) {
818 i.l = t->data->start;
819 i.r = end(t->data);
820 } else if (bset_written(b, t)) {
821 /*
822 * Each node in the auxiliary search tree covers a certain range
823 * of bits, and keys above and below the set it covers might
824 * differ outside those bits - so we have to special case the
825 * start and end - handle that here:
826 */
827
828 if (unlikely(bkey_cmp(search, &t->end) >= 0))
829 return end(t->data);
830
831 if (unlikely(bkey_cmp(search, t->data->start) < 0))
832 return t->data->start;
833
834 i = bset_search_tree(b, t, search);
835 } else
836 i = bset_search_write_set(b, t, search);
837
280481d0
KO
838 if (expensive_debug_checks(b->c)) {
839 BUG_ON(bset_written(b, t) &&
840 i.l != t->data->start &&
841 bkey_cmp(tree_to_prev_bkey(t,
842 inorder_to_tree(bkey_to_cacheline(t, i.l), t)),
843 search) > 0);
cafe5635 844
280481d0
KO
845 BUG_ON(i.r != end(t->data) &&
846 bkey_cmp(i.r, search) <= 0);
847 }
cafe5635
KO
848
849 while (likely(i.l != i.r) &&
850 bkey_cmp(i.l, search) <= 0)
851 i.l = bkey_next(i.l);
852
853 return i.l;
854}
855
856/* Btree iterator */
857
48dad8ba
KO
858/*
859 * Returns true if l > r - unless l == r, in which case returns true if l is
860 * older than r.
861 *
862 * Necessary for btree_sort_fixup() - if there are multiple keys that compare
863 * equal in different sets, we have to process them newest to oldest.
864 */
cafe5635
KO
865static inline bool btree_iter_cmp(struct btree_iter_set l,
866 struct btree_iter_set r)
867{
868 int64_t c = bkey_cmp(&START_KEY(l.k), &START_KEY(r.k));
869
870 return c ? c > 0 : l.k < r.k;
871}
872
873static inline bool btree_iter_end(struct btree_iter *iter)
874{
875 return !iter->used;
876}
877
878void bch_btree_iter_push(struct btree_iter *iter, struct bkey *k,
879 struct bkey *end)
880{
881 if (k != end)
882 BUG_ON(!heap_add(iter,
883 ((struct btree_iter_set) { k, end }),
884 btree_iter_cmp));
885}
886
887struct bkey *__bch_btree_iter_init(struct btree *b, struct btree_iter *iter,
280481d0 888 struct bkey *search, struct bset_tree *start)
cafe5635
KO
889{
890 struct bkey *ret = NULL;
891 iter->size = ARRAY_SIZE(iter->data);
892 iter->used = 0;
893
280481d0
KO
894#ifdef CONFIG_BCACHE_DEBUG
895 iter->b = b;
896#endif
897
cafe5635
KO
898 for (; start <= &b->sets[b->nsets]; start++) {
899 ret = bch_bset_search(b, start, search);
900 bch_btree_iter_push(iter, ret, end(start->data));
901 }
902
903 return ret;
904}
905
906struct bkey *bch_btree_iter_next(struct btree_iter *iter)
907{
908 struct btree_iter_set unused;
909 struct bkey *ret = NULL;
910
911 if (!btree_iter_end(iter)) {
280481d0
KO
912 bch_btree_iter_next_check(iter);
913
cafe5635
KO
914 ret = iter->data->k;
915 iter->data->k = bkey_next(iter->data->k);
916
917 if (iter->data->k > iter->data->end) {
cc0f4eaa 918 WARN_ONCE(1, "bset was corrupt!\n");
cafe5635
KO
919 iter->data->k = iter->data->end;
920 }
921
922 if (iter->data->k == iter->data->end)
923 heap_pop(iter, unused, btree_iter_cmp);
924 else
925 heap_sift(iter, 0, btree_iter_cmp);
926 }
927
928 return ret;
929}
930
931struct bkey *bch_btree_iter_next_filter(struct btree_iter *iter,
932 struct btree *b, ptr_filter_fn fn)
933{
934 struct bkey *ret;
935
936 do {
937 ret = bch_btree_iter_next(iter);
938 } while (ret && fn(b, ret));
939
940 return ret;
941}
942
cafe5635
KO
943/* Mergesort */
944
84786438
KO
945static void sort_key_next(struct btree_iter *iter,
946 struct btree_iter_set *i)
947{
948 i->k = bkey_next(i->k);
949
950 if (i->k == i->end)
951 *i = iter->data[--iter->used];
952}
953
ef71ec00 954static struct bkey *btree_sort_fixup(struct btree_iter *iter, struct bkey *tmp)
cafe5635
KO
955{
956 while (iter->used > 1) {
957 struct btree_iter_set *top = iter->data, *i = top + 1;
cafe5635
KO
958
959 if (iter->used > 2 &&
960 btree_iter_cmp(i[0], i[1]))
961 i++;
962
84786438 963 if (bkey_cmp(top->k, &START_KEY(i->k)) <= 0)
cafe5635
KO
964 break;
965
84786438
KO
966 if (!KEY_SIZE(i->k)) {
967 sort_key_next(iter, i);
968 heap_sift(iter, i - top, btree_iter_cmp);
969 continue;
970 }
971
972 if (top->k > i->k) {
973 if (bkey_cmp(top->k, i->k) >= 0)
974 sort_key_next(iter, i);
975 else
976 bch_cut_front(top->k, i->k);
977
978 heap_sift(iter, i - top, btree_iter_cmp);
979 } else {
980 /* can't happen because of comparison func */
981 BUG_ON(!bkey_cmp(&START_KEY(top->k), &START_KEY(i->k)));
ef71ec00
KO
982
983 if (bkey_cmp(i->k, top->k) < 0) {
984 bkey_copy(tmp, top->k);
985
986 bch_cut_back(&START_KEY(i->k), tmp);
987 bch_cut_front(i->k, top->k);
988 heap_sift(iter, 0, btree_iter_cmp);
989
990 return tmp;
991 } else {
992 bch_cut_back(&START_KEY(i->k), top->k);
993 }
84786438 994 }
cafe5635 995 }
ef71ec00
KO
996
997 return NULL;
cafe5635
KO
998}
999
1000static void btree_mergesort(struct btree *b, struct bset *out,
1001 struct btree_iter *iter,
1002 bool fixup, bool remove_stale)
1003{
1004 struct bkey *k, *last = NULL;
ef71ec00 1005 BKEY_PADDED(k) tmp;
cafe5635
KO
1006 bool (*bad)(struct btree *, const struct bkey *) = remove_stale
1007 ? bch_ptr_bad
1008 : bch_ptr_invalid;
1009
1010 while (!btree_iter_end(iter)) {
1011 if (fixup && !b->level)
ef71ec00
KO
1012 k = btree_sort_fixup(iter, &tmp.k);
1013 else
1014 k = NULL;
1015
1016 if (!k)
1017 k = bch_btree_iter_next(iter);
cafe5635 1018
cafe5635
KO
1019 if (bad(b, k))
1020 continue;
1021
1022 if (!last) {
1023 last = out->start;
1024 bkey_copy(last, k);
1025 } else if (b->level ||
1026 !bch_bkey_try_merge(b, last, k)) {
1027 last = bkey_next(last);
1028 bkey_copy(last, k);
1029 }
1030 }
1031
1032 out->keys = last ? (uint64_t *) bkey_next(last) - out->d : 0;
1033
1034 pr_debug("sorted %i keys", out->keys);
cafe5635
KO
1035}
1036
1037static void __btree_sort(struct btree *b, struct btree_iter *iter,
1038 unsigned start, unsigned order, bool fixup)
1039{
1040 uint64_t start_time;
1041 bool remove_stale = !b->written;
0a451145 1042 bool used_mempool = false;
cafe5635
KO
1043 struct bset *out = (void *) __get_free_pages(__GFP_NOWARN|GFP_NOIO,
1044 order);
1045 if (!out) {
0a451145
KO
1046 out = page_address(mempool_alloc(b->c->sort_pool, GFP_NOIO));
1047 used_mempool = true;
cafe5635
KO
1048 order = ilog2(bucket_pages(b->c));
1049 }
1050
1051 start_time = local_clock();
1052
1053 btree_mergesort(b, out, iter, fixup, remove_stale);
1054 b->nsets = start;
1055
cafe5635
KO
1056 if (!start && order == b->page_order) {
1057 /*
1058 * Our temporary buffer is the same size as the btree node's
1059 * buffer, we can just swap buffers instead of doing a big
1060 * memcpy()
1061 */
1062
81ab4190 1063 out->magic = bset_magic(&b->c->sb);
cafe5635
KO
1064 out->seq = b->sets[0].data->seq;
1065 out->version = b->sets[0].data->version;
1066 swap(out, b->sets[0].data);
cafe5635
KO
1067 } else {
1068 b->sets[start].data->keys = out->keys;
1069 memcpy(b->sets[start].data->start, out->start,
1070 (void *) end(out) - (void *) out->start);
1071 }
1072
0a451145
KO
1073 if (used_mempool)
1074 mempool_free(virt_to_page(out), b->c->sort_pool);
cafe5635
KO
1075 else
1076 free_pages((unsigned long) out, order);
1077
1078 if (b->written)
1079 bset_build_written_tree(b);
1080
65d22e91 1081 if (!start)
169ef1cf 1082 bch_time_stats_update(&b->c->sort_time, start_time);
cafe5635
KO
1083}
1084
1085void bch_btree_sort_partial(struct btree *b, unsigned start)
1086{
280481d0 1087 size_t order = b->page_order, keys = 0;
cafe5635 1088 struct btree_iter iter;
280481d0
KO
1089 int oldsize = bch_count_data(b);
1090
cafe5635
KO
1091 __bch_btree_iter_init(b, &iter, NULL, &b->sets[start]);
1092
1093 BUG_ON(b->sets[b->nsets].data == write_block(b) &&
1094 (b->sets[b->nsets].size || b->nsets));
1095
cafe5635
KO
1096
1097 if (start) {
1098 unsigned i;
1099
1100 for (i = start; i <= b->nsets; i++)
1101 keys += b->sets[i].data->keys;
1102
b1a67b0f
KO
1103 order = roundup_pow_of_two(__set_bytes(b->sets->data,
1104 keys)) / PAGE_SIZE;
cafe5635
KO
1105 if (order)
1106 order = ilog2(order);
1107 }
1108
1109 __btree_sort(b, &iter, start, order, false);
1110
280481d0 1111 EBUG_ON(b->written && oldsize >= 0 && bch_count_data(b) != oldsize);
cafe5635
KO
1112}
1113
1114void bch_btree_sort_and_fix_extents(struct btree *b, struct btree_iter *iter)
1115{
1116 BUG_ON(!b->written);
1117 __btree_sort(b, iter, 0, b->page_order, true);
1118}
1119
1120void bch_btree_sort_into(struct btree *b, struct btree *new)
1121{
1122 uint64_t start_time = local_clock();
1123
1124 struct btree_iter iter;
1125 bch_btree_iter_init(b, &iter, NULL);
1126
1127 btree_mergesort(b, new->sets->data, &iter, false, true);
1128
169ef1cf 1129 bch_time_stats_update(&b->c->sort_time, start_time);
cafe5635
KO
1130
1131 bkey_copy_key(&new->key, &b->key);
1132 new->sets->size = 0;
1133}
1134
6ded34d1
KO
1135#define SORT_CRIT (4096 / sizeof(uint64_t))
1136
cafe5635
KO
1137void bch_btree_sort_lazy(struct btree *b)
1138{
6ded34d1
KO
1139 unsigned crit = SORT_CRIT;
1140 int i;
cafe5635 1141
6ded34d1
KO
1142 /* Don't sort if nothing to do */
1143 if (!b->nsets)
1144 goto out;
cafe5635 1145
6ded34d1
KO
1146 /* If not a leaf node, always sort */
1147 if (b->level) {
1148 bch_btree_sort(b);
1149 return;
1150 }
cafe5635 1151
6ded34d1
KO
1152 for (i = b->nsets - 1; i >= 0; --i) {
1153 crit *= b->c->sort_crit_factor;
cafe5635 1154
6ded34d1
KO
1155 if (b->sets[i].data->keys < crit) {
1156 bch_btree_sort_partial(b, i);
cafe5635
KO
1157 return;
1158 }
1159 }
1160
6ded34d1
KO
1161 /* Sort if we'd overflow */
1162 if (b->nsets + 1 == MAX_BSETS) {
1163 bch_btree_sort(b);
1164 return;
1165 }
1166
1167out:
cafe5635
KO
1168 bset_build_written_tree(b);
1169}
1170
1171/* Sysfs stuff */
1172
1173struct bset_stats {
48dad8ba 1174 struct btree_op op;
cafe5635
KO
1175 size_t nodes;
1176 size_t sets_written, sets_unwritten;
1177 size_t bytes_written, bytes_unwritten;
1178 size_t floats, failed;
1179};
1180
48dad8ba 1181static int btree_bset_stats(struct btree_op *op, struct btree *b)
cafe5635 1182{
48dad8ba 1183 struct bset_stats *stats = container_of(op, struct bset_stats, op);
cafe5635
KO
1184 unsigned i;
1185
1186 stats->nodes++;
1187
1188 for (i = 0; i <= b->nsets; i++) {
1189 struct bset_tree *t = &b->sets[i];
1190 size_t bytes = t->data->keys * sizeof(uint64_t);
1191 size_t j;
1192
1193 if (bset_written(b, t)) {
1194 stats->sets_written++;
1195 stats->bytes_written += bytes;
1196
1197 stats->floats += t->size - 1;
1198
1199 for (j = 1; j < t->size; j++)
1200 if (t->tree[j].exponent == 127)
1201 stats->failed++;
1202 } else {
1203 stats->sets_unwritten++;
1204 stats->bytes_unwritten += bytes;
1205 }
1206 }
1207
48dad8ba 1208 return MAP_CONTINUE;
cafe5635
KO
1209}
1210
1211int bch_bset_print_stats(struct cache_set *c, char *buf)
1212{
cafe5635
KO
1213 struct bset_stats t;
1214 int ret;
1215
cafe5635 1216 memset(&t, 0, sizeof(struct bset_stats));
b54d6934 1217 bch_btree_op_init(&t.op, -1);
cafe5635 1218
48dad8ba
KO
1219 ret = bch_btree_map_nodes(&t.op, c, &ZERO_KEY, btree_bset_stats);
1220 if (ret < 0)
cafe5635
KO
1221 return ret;
1222
1223 return snprintf(buf, PAGE_SIZE,
1224 "btree nodes: %zu\n"
1225 "written sets: %zu\n"
1226 "unwritten sets: %zu\n"
1227 "written key bytes: %zu\n"
1228 "unwritten key bytes: %zu\n"
1229 "floats: %zu\n"
1230 "failed: %zu\n",
1231 t.nodes,
1232 t.sets_written, t.sets_unwritten,
1233 t.bytes_written, t.bytes_unwritten,
1234 t.floats, t.failed);
1235}