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