OSDN Git Service

f37a429f093dc3e95b3f772376ace1c5c307bf26
[tomoyo/tomoyo-test1.git] / drivers / md / bcache / bset.c
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Code for working with individual keys, and sorted sets of keys with in a
4  * btree node
5  *
6  * Copyright 2012 Google, Inc.
7  */
8
9 #define pr_fmt(fmt) "bcache: %s() " fmt "\n", __func__
10
11 #include "util.h"
12 #include "bset.h"
13
14 #include <linux/console.h>
15 #include <linux/sched/clock.h>
16 #include <linux/random.h>
17 #include <linux/prefetch.h>
18
19 #ifdef CONFIG_BCACHE_DEBUG
20
21 void bch_dump_bset(struct btree_keys *b, struct bset *i, unsigned int set)
22 {
23         struct bkey *k, *next;
24
25         for (k = i->start; k < bset_bkey_last(i); k = next) {
26                 next = bkey_next(k);
27
28                 pr_err("block %u key %u/%u: ", set,
29                        (unsigned int) ((u64 *) k - i->d), i->keys);
30
31                 if (b->ops->key_dump)
32                         b->ops->key_dump(b, k);
33                 else
34                         pr_err("%llu:%llu\n", KEY_INODE(k), KEY_OFFSET(k));
35
36                 if (next < bset_bkey_last(i) &&
37                     bkey_cmp(k, b->ops->is_extents ?
38                              &START_KEY(next) : next) > 0)
39                         pr_err("Key skipped backwards\n");
40         }
41 }
42
43 void bch_dump_bucket(struct btree_keys *b)
44 {
45         unsigned int i;
46
47         console_lock();
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));
51         console_unlock();
52 }
53
54 int __bch_count_data(struct btree_keys *b)
55 {
56         unsigned int ret = 0;
57         struct btree_iter iter;
58         struct bkey *k;
59
60         if (b->ops->is_extents)
61                 for_each_key(b, k, &iter)
62                         ret += KEY_SIZE(k);
63         return ret;
64 }
65
66 void __bch_check_keys(struct btree_keys *b, const char *fmt, ...)
67 {
68         va_list args;
69         struct bkey *k, *p = NULL;
70         struct btree_iter iter;
71         const char *err;
72
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)
77                                 goto bug;
78
79                         if (bch_ptr_invalid(b, k))
80                                 continue;
81
82                         err =  "Overlapping keys";
83                         if (p && bkey_cmp(p, &START_KEY(k)) > 0)
84                                 goto bug;
85                 } else {
86                         if (bch_ptr_bad(b, k))
87                                 continue;
88
89                         err = "Duplicate keys";
90                         if (p && !bkey_cmp(p, k))
91                                 goto bug;
92                 }
93                 p = k;
94         }
95 #if 0
96         err = "Key larger than btree node key";
97         if (p && bkey_cmp(p, &b->key) > 0)
98                 goto bug;
99 #endif
100         return;
101 bug:
102         bch_dump_bucket(b);
103
104         va_start(args, fmt);
105         vprintk(fmt, args);
106         va_end(args);
107
108         panic("bch_check_keys error:  %s:\n", err);
109 }
110
111 static void bch_btree_iter_next_check(struct btree_iter *iter)
112 {
113         struct bkey *k = iter->data->k, *next = bkey_next(k);
114
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");
120         }
121 }
122
123 #else
124
125 static inline void bch_btree_iter_next_check(struct btree_iter *iter) {}
126
127 #endif
128
129 /* Keylists */
130
131 int __bch_keylist_realloc(struct keylist *l, unsigned int u64s)
132 {
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;
136         uint64_t *new_keys;
137
138         newsize = roundup_pow_of_two(newsize);
139
140         if (newsize <= KEYLIST_INLINE ||
141             roundup_pow_of_two(oldsize) == newsize)
142                 return 0;
143
144         new_keys = krealloc(old_keys, sizeof(uint64_t) * newsize, GFP_NOIO);
145
146         if (!new_keys)
147                 return -ENOMEM;
148
149         if (!old_keys)
150                 memcpy(new_keys, l->inline_keys, sizeof(uint64_t) * oldsize);
151
152         l->keys_p = new_keys;
153         l->top_p = new_keys + oldsize;
154
155         return 0;
156 }
157
158 /* Pop the top key of keylist by pointing l->top to its previous key */
159 struct bkey *bch_keylist_pop(struct keylist *l)
160 {
161         struct bkey *k = l->keys;
162
163         if (k == l->top)
164                 return NULL;
165
166         while (bkey_next(k) != l->top)
167                 k = bkey_next(k);
168
169         return l->top = k;
170 }
171
172 /* Pop the bottom key of keylist and update l->top_p */
173 void bch_keylist_pop_front(struct keylist *l)
174 {
175         l->top_p -= bkey_u64s(l->keys);
176
177         memmove(l->keys,
178                 bkey_next(l->keys),
179                 bch_keylist_bytes(l));
180 }
181
182 /* Key/pointer manipulation */
183
184 void bch_bkey_copy_single_ptr(struct bkey *dest, const struct bkey *src,
185                               unsigned int i)
186 {
187         BUG_ON(i > KEY_PTRS(src));
188
189         /* Only copy the header, key, and one pointer. */
190         memcpy(dest, src, 2 * sizeof(uint64_t));
191         dest->ptr[0] = src->ptr[i];
192         SET_KEY_PTRS(dest, 1);
193         /* We didn't copy the checksum so clear that bit. */
194         SET_KEY_CSUM(dest, 0);
195 }
196
197 bool __bch_cut_front(const struct bkey *where, struct bkey *k)
198 {
199         unsigned int i, len = 0;
200
201         if (bkey_cmp(where, &START_KEY(k)) <= 0)
202                 return false;
203
204         if (bkey_cmp(where, k) < 0)
205                 len = KEY_OFFSET(k) - KEY_OFFSET(where);
206         else
207                 bkey_copy_key(k, where);
208
209         for (i = 0; i < KEY_PTRS(k); i++)
210                 SET_PTR_OFFSET(k, i, PTR_OFFSET(k, i) + KEY_SIZE(k) - len);
211
212         BUG_ON(len > KEY_SIZE(k));
213         SET_KEY_SIZE(k, len);
214         return true;
215 }
216
217 bool __bch_cut_back(const struct bkey *where, struct bkey *k)
218 {
219         unsigned int len = 0;
220
221         if (bkey_cmp(where, k) >= 0)
222                 return false;
223
224         BUG_ON(KEY_INODE(where) != KEY_INODE(k));
225
226         if (bkey_cmp(where, &START_KEY(k)) > 0)
227                 len = KEY_OFFSET(where) - KEY_START(k);
228
229         bkey_copy_key(k, where);
230
231         BUG_ON(len > KEY_SIZE(k));
232         SET_KEY_SIZE(k, len);
233         return true;
234 }
235
236 /* Auxiliary search trees */
237
238 /* 32 bits total: */
239 #define BKEY_MID_BITS           3
240 #define BKEY_EXPONENT_BITS      7
241 #define BKEY_MANTISSA_BITS      (32 - BKEY_MID_BITS - BKEY_EXPONENT_BITS)
242 #define BKEY_MANTISSA_MASK      ((1 << BKEY_MANTISSA_BITS) - 1)
243
244 struct bkey_float {
245         unsigned int    exponent:BKEY_EXPONENT_BITS;
246         unsigned int    m:BKEY_MID_BITS;
247         unsigned int    mantissa:BKEY_MANTISSA_BITS;
248 } __packed;
249
250 /*
251  * BSET_CACHELINE was originally intended to match the hardware cacheline size -
252  * it used to be 64, but I realized the lookup code would touch slightly less
253  * memory if it was 128.
254  *
255  * It definites the number of bytes (in struct bset) per struct bkey_float in
256  * the auxiliar search tree - when we're done searching the bset_float tree we
257  * have this many bytes left that we do a linear search over.
258  *
259  * Since (after level 5) every level of the bset_tree is on a new cacheline,
260  * we're touching one fewer cacheline in the bset tree in exchange for one more
261  * cacheline in the linear search - but the linear search might stop before it
262  * gets to the second cacheline.
263  */
264
265 #define BSET_CACHELINE          128
266
267 /* Space required for the btree node keys */
268 static inline size_t btree_keys_bytes(struct btree_keys *b)
269 {
270         return PAGE_SIZE << b->page_order;
271 }
272
273 static inline size_t btree_keys_cachelines(struct btree_keys *b)
274 {
275         return btree_keys_bytes(b) / BSET_CACHELINE;
276 }
277
278 /* Space required for the auxiliary search trees */
279 static inline size_t bset_tree_bytes(struct btree_keys *b)
280 {
281         return btree_keys_cachelines(b) * sizeof(struct bkey_float);
282 }
283
284 /* Space required for the prev pointers */
285 static inline size_t bset_prev_bytes(struct btree_keys *b)
286 {
287         return btree_keys_cachelines(b) * sizeof(uint8_t);
288 }
289
290 /* Memory allocation */
291
292 void bch_btree_keys_free(struct btree_keys *b)
293 {
294         struct bset_tree *t = b->set;
295
296         if (bset_prev_bytes(b) < PAGE_SIZE)
297                 kfree(t->prev);
298         else
299                 free_pages((unsigned long) t->prev,
300                            get_order(bset_prev_bytes(b)));
301
302         if (bset_tree_bytes(b) < PAGE_SIZE)
303                 kfree(t->tree);
304         else
305                 free_pages((unsigned long) t->tree,
306                            get_order(bset_tree_bytes(b)));
307
308         free_pages((unsigned long) t->data, b->page_order);
309
310         t->prev = NULL;
311         t->tree = NULL;
312         t->data = NULL;
313 }
314 EXPORT_SYMBOL(bch_btree_keys_free);
315
316 int bch_btree_keys_alloc(struct btree_keys *b,
317                          unsigned int page_order,
318                          gfp_t gfp)
319 {
320         struct bset_tree *t = b->set;
321
322         BUG_ON(t->data);
323
324         b->page_order = page_order;
325
326         t->data = (void *) __get_free_pages(gfp, b->page_order);
327         if (!t->data)
328                 goto err;
329
330         t->tree = bset_tree_bytes(b) < PAGE_SIZE
331                 ? kmalloc(bset_tree_bytes(b), gfp)
332                 : (void *) __get_free_pages(gfp, get_order(bset_tree_bytes(b)));
333         if (!t->tree)
334                 goto err;
335
336         t->prev = bset_prev_bytes(b) < PAGE_SIZE
337                 ? kmalloc(bset_prev_bytes(b), gfp)
338                 : (void *) __get_free_pages(gfp, get_order(bset_prev_bytes(b)));
339         if (!t->prev)
340                 goto err;
341
342         return 0;
343 err:
344         bch_btree_keys_free(b);
345         return -ENOMEM;
346 }
347 EXPORT_SYMBOL(bch_btree_keys_alloc);
348
349 void bch_btree_keys_init(struct btree_keys *b, const struct btree_keys_ops *ops,
350                          bool *expensive_debug_checks)
351 {
352         b->ops = ops;
353         b->expensive_debug_checks = expensive_debug_checks;
354         b->nsets = 0;
355         b->last_set_unwritten = 0;
356
357         /*
358          * struct btree_keys in embedded in struct btree, and struct
359          * bset_tree is embedded into struct btree_keys. They are all
360          * initialized as 0 by kzalloc() in mca_bucket_alloc(), and
361          * b->set[0].data is allocated in bch_btree_keys_alloc(), so we
362          * don't have to initiate b->set[].size and b->set[].data here
363          * any more.
364          */
365 }
366 EXPORT_SYMBOL(bch_btree_keys_init);
367
368 /* Binary tree stuff for auxiliary search trees */
369
370 /*
371  * return array index next to j when does in-order traverse
372  * of a binary tree which is stored in a linear array
373  */
374 static unsigned int inorder_next(unsigned int j, unsigned int size)
375 {
376         if (j * 2 + 1 < size) {
377                 j = j * 2 + 1;
378
379                 while (j * 2 < size)
380                         j *= 2;
381         } else
382                 j >>= ffz(j) + 1;
383
384         return j;
385 }
386
387 /*
388  * return array index previous to j when does in-order traverse
389  * of a binary tree which is stored in a linear array
390  */
391 static unsigned int inorder_prev(unsigned int j, unsigned int size)
392 {
393         if (j * 2 < size) {
394                 j = j * 2;
395
396                 while (j * 2 + 1 < size)
397                         j = j * 2 + 1;
398         } else
399                 j >>= ffs(j);
400
401         return j;
402 }
403
404 /*
405  * I have no idea why this code works... and I'm the one who wrote it
406  *
407  * However, I do know what it does:
408  * Given a binary tree constructed in an array (i.e. how you normally implement
409  * a heap), it converts a node in the tree - referenced by array index - to the
410  * index it would have if you did an inorder traversal.
411  *
412  * Also tested for every j, size up to size somewhere around 6 million.
413  *
414  * The binary tree starts at array index 1, not 0
415  * extra is a function of size:
416  *   extra = (size - rounddown_pow_of_two(size - 1)) << 1;
417  */
418 static unsigned int __to_inorder(unsigned int j,
419                                   unsigned int size,
420                                   unsigned int extra)
421 {
422         unsigned int b = fls(j);
423         unsigned int shift = fls(size - 1) - b;
424
425         j  ^= 1U << (b - 1);
426         j <<= 1;
427         j  |= 1;
428         j <<= shift;
429
430         if (j > extra)
431                 j -= (j - extra) >> 1;
432
433         return j;
434 }
435
436 /*
437  * Return the cacheline index in bset_tree->data, where j is index
438  * from a linear array which stores the auxiliar binary tree
439  */
440 static unsigned int to_inorder(unsigned int j, struct bset_tree *t)
441 {
442         return __to_inorder(j, t->size, t->extra);
443 }
444
445 static unsigned int __inorder_to_tree(unsigned int j,
446                                       unsigned int size,
447                                       unsigned int extra)
448 {
449         unsigned int shift;
450
451         if (j > extra)
452                 j += j - extra;
453
454         shift = ffs(j);
455
456         j >>= shift;
457         j  |= roundup_pow_of_two(size) >> shift;
458
459         return j;
460 }
461
462 /*
463  * Return an index from a linear array which stores the auxiliar binary
464  * tree, j is the cacheline index of t->data.
465  */
466 static unsigned int inorder_to_tree(unsigned int j, struct bset_tree *t)
467 {
468         return __inorder_to_tree(j, t->size, t->extra);
469 }
470
471 #if 0
472 void inorder_test(void)
473 {
474         unsigned long done = 0;
475         ktime_t start = ktime_get();
476
477         for (unsigned int size = 2;
478              size < 65536000;
479              size++) {
480                 unsigned int extra =
481                         (size - rounddown_pow_of_two(size - 1)) << 1;
482                 unsigned int i = 1, j = rounddown_pow_of_two(size - 1);
483
484                 if (!(size % 4096))
485                         pr_notice("loop %u, %llu per us\n", size,
486                                done / ktime_us_delta(ktime_get(), start));
487
488                 while (1) {
489                         if (__inorder_to_tree(i, size, extra) != j)
490                                 panic("size %10u j %10u i %10u", size, j, i);
491
492                         if (__to_inorder(j, size, extra) != i)
493                                 panic("size %10u j %10u i %10u", size, j, i);
494
495                         if (j == rounddown_pow_of_two(size) - 1)
496                                 break;
497
498                         BUG_ON(inorder_prev(inorder_next(j, size), size) != j);
499
500                         j = inorder_next(j, size);
501                         i++;
502                 }
503
504                 done += size - 1;
505         }
506 }
507 #endif
508
509 /*
510  * Cacheline/offset <-> bkey pointer arithmetic:
511  *
512  * t->tree is a binary search tree in an array; each node corresponds to a key
513  * in one cacheline in t->set (BSET_CACHELINE bytes).
514  *
515  * This means we don't have to store the full index of the key that a node in
516  * the binary tree points to; to_inorder() gives us the cacheline, and then
517  * bkey_float->m gives us the offset within that cacheline, in units of 8 bytes.
518  *
519  * cacheline_to_bkey() and friends abstract out all the pointer arithmetic to
520  * make this work.
521  *
522  * To construct the bfloat for an arbitrary key we need to know what the key
523  * immediately preceding it is: we have to check if the two keys differ in the
524  * bits we're going to store in bkey_float->mantissa. t->prev[j] stores the size
525  * of the previous key so we can walk backwards to it from t->tree[j]'s key.
526  */
527
528 static struct bkey *cacheline_to_bkey(struct bset_tree *t,
529                                       unsigned int cacheline,
530                                       unsigned int offset)
531 {
532         return ((void *) t->data) + cacheline * BSET_CACHELINE + offset * 8;
533 }
534
535 static unsigned int bkey_to_cacheline(struct bset_tree *t, struct bkey *k)
536 {
537         return ((void *) k - (void *) t->data) / BSET_CACHELINE;
538 }
539
540 static unsigned int bkey_to_cacheline_offset(struct bset_tree *t,
541                                          unsigned int cacheline,
542                                          struct bkey *k)
543 {
544         return (u64 *) k - (u64 *) cacheline_to_bkey(t, cacheline, 0);
545 }
546
547 static struct bkey *tree_to_bkey(struct bset_tree *t, unsigned int j)
548 {
549         return cacheline_to_bkey(t, to_inorder(j, t), t->tree[j].m);
550 }
551
552 static struct bkey *tree_to_prev_bkey(struct bset_tree *t, unsigned int j)
553 {
554         return (void *) (((uint64_t *) tree_to_bkey(t, j)) - t->prev[j]);
555 }
556
557 /*
558  * For the write set - the one we're currently inserting keys into - we don't
559  * maintain a full search tree, we just keep a simple lookup table in t->prev.
560  */
561 static struct bkey *table_to_bkey(struct bset_tree *t, unsigned int cacheline)
562 {
563         return cacheline_to_bkey(t, cacheline, t->prev[cacheline]);
564 }
565
566 static inline uint64_t shrd128(uint64_t high, uint64_t low, uint8_t shift)
567 {
568         low >>= shift;
569         low  |= (high << 1) << (63U - shift);
570         return low;
571 }
572
573 /*
574  * Calculate mantissa value for struct bkey_float.
575  * If most significant bit of f->exponent is not set, then
576  *  - f->exponent >> 6 is 0
577  *  - p[0] points to bkey->low
578  *  - p[-1] borrows bits from KEY_INODE() of bkey->high
579  * if most isgnificant bits of f->exponent is set, then
580  *  - f->exponent >> 6 is 1
581  *  - p[0] points to bits from KEY_INODE() of bkey->high
582  *  - p[-1] points to other bits from KEY_INODE() of
583  *    bkey->high too.
584  * See make_bfloat() to check when most significant bit of f->exponent
585  * is set or not.
586  */
587 static inline unsigned int bfloat_mantissa(const struct bkey *k,
588                                        struct bkey_float *f)
589 {
590         const uint64_t *p = &k->low - (f->exponent >> 6);
591
592         return shrd128(p[-1], p[0], f->exponent & 63) & BKEY_MANTISSA_MASK;
593 }
594
595 static void make_bfloat(struct bset_tree *t, unsigned int j)
596 {
597         struct bkey_float *f = &t->tree[j];
598         struct bkey *m = tree_to_bkey(t, j);
599         struct bkey *p = tree_to_prev_bkey(t, j);
600
601         struct bkey *l = is_power_of_2(j)
602                 ? t->data->start
603                 : tree_to_prev_bkey(t, j >> ffs(j));
604
605         struct bkey *r = is_power_of_2(j + 1)
606                 ? bset_bkey_idx(t->data, t->data->keys - bkey_u64s(&t->end))
607                 : tree_to_bkey(t, j >> (ffz(j) + 1));
608
609         BUG_ON(m < l || m > r);
610         BUG_ON(bkey_next(p) != m);
611
612         /*
613          * If l and r have different KEY_INODE values (different backing
614          * device), f->exponent records how many least significant bits
615          * are different in KEY_INODE values and sets most significant
616          * bits to 1 (by +64).
617          * If l and r have same KEY_INODE value, f->exponent records
618          * how many different bits in least significant bits of bkey->low.
619          * See bfloat_mantiss() how the most significant bit of
620          * f->exponent is used to calculate bfloat mantissa value.
621          */
622         if (KEY_INODE(l) != KEY_INODE(r))
623                 f->exponent = fls64(KEY_INODE(r) ^ KEY_INODE(l)) + 64;
624         else
625                 f->exponent = fls64(r->low ^ l->low);
626
627         f->exponent = max_t(int, f->exponent - BKEY_MANTISSA_BITS, 0);
628
629         /*
630          * Setting f->exponent = 127 flags this node as failed, and causes the
631          * lookup code to fall back to comparing against the original key.
632          */
633
634         if (bfloat_mantissa(m, f) != bfloat_mantissa(p, f))
635                 f->mantissa = bfloat_mantissa(m, f) - 1;
636         else
637                 f->exponent = 127;
638 }
639
640 static void bset_alloc_tree(struct btree_keys *b, struct bset_tree *t)
641 {
642         if (t != b->set) {
643                 unsigned int j = roundup(t[-1].size,
644                                      64 / sizeof(struct bkey_float));
645
646                 t->tree = t[-1].tree + j;
647                 t->prev = t[-1].prev + j;
648         }
649
650         while (t < b->set + MAX_BSETS)
651                 t++->size = 0;
652 }
653
654 static void bch_bset_build_unwritten_tree(struct btree_keys *b)
655 {
656         struct bset_tree *t = bset_tree_last(b);
657
658         BUG_ON(b->last_set_unwritten);
659         b->last_set_unwritten = 1;
660
661         bset_alloc_tree(b, t);
662
663         if (t->tree != b->set->tree + btree_keys_cachelines(b)) {
664                 t->prev[0] = bkey_to_cacheline_offset(t, 0, t->data->start);
665                 t->size = 1;
666         }
667 }
668
669 void bch_bset_init_next(struct btree_keys *b, struct bset *i, uint64_t magic)
670 {
671         if (i != b->set->data) {
672                 b->set[++b->nsets].data = i;
673                 i->seq = b->set->data->seq;
674         } else
675                 get_random_bytes(&i->seq, sizeof(uint64_t));
676
677         i->magic        = magic;
678         i->version      = 0;
679         i->keys         = 0;
680
681         bch_bset_build_unwritten_tree(b);
682 }
683 EXPORT_SYMBOL(bch_bset_init_next);
684
685 /*
686  * Build auxiliary binary tree 'struct bset_tree *t', this tree is used to
687  * accelerate bkey search in a btree node (pointed by bset_tree->data in
688  * memory). After search in the auxiliar tree by calling bset_search_tree(),
689  * a struct bset_search_iter is returned which indicates range [l, r] from
690  * bset_tree->data where the searching bkey might be inside. Then a followed
691  * linear comparison does the exact search, see __bch_bset_search() for how
692  * the auxiliary tree is used.
693  */
694 void bch_bset_build_written_tree(struct btree_keys *b)
695 {
696         struct bset_tree *t = bset_tree_last(b);
697         struct bkey *prev = NULL, *k = t->data->start;
698         unsigned int j, cacheline = 1;
699
700         b->last_set_unwritten = 0;
701
702         bset_alloc_tree(b, t);
703
704         t->size = min_t(unsigned int,
705                         bkey_to_cacheline(t, bset_bkey_last(t->data)),
706                         b->set->tree + btree_keys_cachelines(b) - t->tree);
707
708         if (t->size < 2) {
709                 t->size = 0;
710                 return;
711         }
712
713         t->extra = (t->size - rounddown_pow_of_two(t->size - 1)) << 1;
714
715         /* First we figure out where the first key in each cacheline is */
716         for (j = inorder_next(0, t->size);
717              j;
718              j = inorder_next(j, t->size)) {
719                 while (bkey_to_cacheline(t, k) < cacheline)
720                         prev = k, k = bkey_next(k);
721
722                 t->prev[j] = bkey_u64s(prev);
723                 t->tree[j].m = bkey_to_cacheline_offset(t, cacheline++, k);
724         }
725
726         while (bkey_next(k) != bset_bkey_last(t->data))
727                 k = bkey_next(k);
728
729         t->end = *k;
730
731         /* Then we build the tree */
732         for (j = inorder_next(0, t->size);
733              j;
734              j = inorder_next(j, t->size))
735                 make_bfloat(t, j);
736 }
737 EXPORT_SYMBOL(bch_bset_build_written_tree);
738
739 /* Insert */
740
741 void bch_bset_fix_invalidated_key(struct btree_keys *b, struct bkey *k)
742 {
743         struct bset_tree *t;
744         unsigned int inorder, j = 1;
745
746         for (t = b->set; t <= bset_tree_last(b); t++)
747                 if (k < bset_bkey_last(t->data))
748                         goto found_set;
749
750         BUG();
751 found_set:
752         if (!t->size || !bset_written(b, t))
753                 return;
754
755         inorder = bkey_to_cacheline(t, k);
756
757         if (k == t->data->start)
758                 goto fix_left;
759
760         if (bkey_next(k) == bset_bkey_last(t->data)) {
761                 t->end = *k;
762                 goto fix_right;
763         }
764
765         j = inorder_to_tree(inorder, t);
766
767         if (j &&
768             j < t->size &&
769             k == tree_to_bkey(t, j))
770 fix_left:       do {
771                         make_bfloat(t, j);
772                         j = j * 2;
773                 } while (j < t->size);
774
775         j = inorder_to_tree(inorder + 1, t);
776
777         if (j &&
778             j < t->size &&
779             k == tree_to_prev_bkey(t, j))
780 fix_right:      do {
781                         make_bfloat(t, j);
782                         j = j * 2 + 1;
783                 } while (j < t->size);
784 }
785 EXPORT_SYMBOL(bch_bset_fix_invalidated_key);
786
787 static void bch_bset_fix_lookup_table(struct btree_keys *b,
788                                       struct bset_tree *t,
789                                       struct bkey *k)
790 {
791         unsigned int shift = bkey_u64s(k);
792         unsigned int j = bkey_to_cacheline(t, k);
793
794         /* We're getting called from btree_split() or btree_gc, just bail out */
795         if (!t->size)
796                 return;
797
798         /*
799          * k is the key we just inserted; we need to find the entry in the
800          * lookup table for the first key that is strictly greater than k:
801          * it's either k's cacheline or the next one
802          */
803         while (j < t->size &&
804                table_to_bkey(t, j) <= k)
805                 j++;
806
807         /*
808          * Adjust all the lookup table entries, and find a new key for any that
809          * have gotten too big
810          */
811         for (; j < t->size; j++) {
812                 t->prev[j] += shift;
813
814                 if (t->prev[j] > 7) {
815                         k = table_to_bkey(t, j - 1);
816
817                         while (k < cacheline_to_bkey(t, j, 0))
818                                 k = bkey_next(k);
819
820                         t->prev[j] = bkey_to_cacheline_offset(t, j, k);
821                 }
822         }
823
824         if (t->size == b->set->tree + btree_keys_cachelines(b) - t->tree)
825                 return;
826
827         /* Possibly add a new entry to the end of the lookup table */
828
829         for (k = table_to_bkey(t, t->size - 1);
830              k != bset_bkey_last(t->data);
831              k = bkey_next(k))
832                 if (t->size == bkey_to_cacheline(t, k)) {
833                         t->prev[t->size] =
834                                 bkey_to_cacheline_offset(t, t->size, k);
835                         t->size++;
836                 }
837 }
838
839 /*
840  * Tries to merge l and r: l should be lower than r
841  * Returns true if we were able to merge. If we did merge, l will be the merged
842  * key, r will be untouched.
843  */
844 bool bch_bkey_try_merge(struct btree_keys *b, struct bkey *l, struct bkey *r)
845 {
846         if (!b->ops->key_merge)
847                 return false;
848
849         /*
850          * Generic header checks
851          * Assumes left and right are in order
852          * Left and right must be exactly aligned
853          */
854         if (!bch_bkey_equal_header(l, r) ||
855              bkey_cmp(l, &START_KEY(r)))
856                 return false;
857
858         return b->ops->key_merge(b, l, r);
859 }
860 EXPORT_SYMBOL(bch_bkey_try_merge);
861
862 void bch_bset_insert(struct btree_keys *b, struct bkey *where,
863                      struct bkey *insert)
864 {
865         struct bset_tree *t = bset_tree_last(b);
866
867         BUG_ON(!b->last_set_unwritten);
868         BUG_ON(bset_byte_offset(b, t->data) +
869                __set_bytes(t->data, t->data->keys + bkey_u64s(insert)) >
870                PAGE_SIZE << b->page_order);
871
872         memmove((uint64_t *) where + bkey_u64s(insert),
873                 where,
874                 (void *) bset_bkey_last(t->data) - (void *) where);
875
876         t->data->keys += bkey_u64s(insert);
877         bkey_copy(where, insert);
878         bch_bset_fix_lookup_table(b, t, where);
879 }
880 EXPORT_SYMBOL(bch_bset_insert);
881
882 unsigned int bch_btree_insert_key(struct btree_keys *b, struct bkey *k,
883                               struct bkey *replace_key)
884 {
885         unsigned int status = BTREE_INSERT_STATUS_NO_INSERT;
886         struct bset *i = bset_tree_last(b)->data;
887         struct bkey *m, *prev = NULL;
888         struct btree_iter iter;
889         struct bkey preceding_key_on_stack = ZERO_KEY;
890         struct bkey *preceding_key_p = &preceding_key_on_stack;
891
892         BUG_ON(b->ops->is_extents && !KEY_SIZE(k));
893
894         /*
895          * If k has preceding key, preceding_key_p will be set to address
896          *  of k's preceding key; otherwise preceding_key_p will be set
897          * to NULL inside preceding_key().
898          */
899         if (b->ops->is_extents)
900                 preceding_key(&START_KEY(k), &preceding_key_p);
901         else
902                 preceding_key(k, &preceding_key_p);
903
904         m = bch_btree_iter_init(b, &iter, preceding_key_p);
905
906         if (b->ops->insert_fixup(b, k, &iter, replace_key))
907                 return status;
908
909         status = BTREE_INSERT_STATUS_INSERT;
910
911         while (m != bset_bkey_last(i) &&
912                bkey_cmp(k, b->ops->is_extents ? &START_KEY(m) : m) > 0)
913                 prev = m, m = bkey_next(m);
914
915         /* prev is in the tree, if we merge we're done */
916         status = BTREE_INSERT_STATUS_BACK_MERGE;
917         if (prev &&
918             bch_bkey_try_merge(b, prev, k))
919                 goto merged;
920 #if 0
921         status = BTREE_INSERT_STATUS_OVERWROTE;
922         if (m != bset_bkey_last(i) &&
923             KEY_PTRS(m) == KEY_PTRS(k) && !KEY_SIZE(m))
924                 goto copy;
925 #endif
926         status = BTREE_INSERT_STATUS_FRONT_MERGE;
927         if (m != bset_bkey_last(i) &&
928             bch_bkey_try_merge(b, k, m))
929                 goto copy;
930
931         bch_bset_insert(b, m, k);
932 copy:   bkey_copy(m, k);
933 merged:
934         return status;
935 }
936 EXPORT_SYMBOL(bch_btree_insert_key);
937
938 /* Lookup */
939
940 struct bset_search_iter {
941         struct bkey *l, *r;
942 };
943
944 static struct bset_search_iter bset_search_write_set(struct bset_tree *t,
945                                                      const struct bkey *search)
946 {
947         unsigned int li = 0, ri = t->size;
948
949         while (li + 1 != ri) {
950                 unsigned int m = (li + ri) >> 1;
951
952                 if (bkey_cmp(table_to_bkey(t, m), search) > 0)
953                         ri = m;
954                 else
955                         li = m;
956         }
957
958         return (struct bset_search_iter) {
959                 table_to_bkey(t, li),
960                 ri < t->size ? table_to_bkey(t, ri) : bset_bkey_last(t->data)
961         };
962 }
963
964 static struct bset_search_iter bset_search_tree(struct bset_tree *t,
965                                                 const struct bkey *search)
966 {
967         struct bkey *l, *r;
968         struct bkey_float *f;
969         unsigned int inorder, j, n = 1;
970
971         do {
972                 unsigned int p = n << 4;
973
974                 if (p < t->size)
975                         prefetch(&t->tree[p]);
976
977                 j = n;
978                 f = &t->tree[j];
979
980                 if (likely(f->exponent != 127)) {
981                         if (f->mantissa >= bfloat_mantissa(search, f))
982                                 n = j * 2;
983                         else
984                                 n = j * 2 + 1;
985                 } else {
986                         if (bkey_cmp(tree_to_bkey(t, j), search) > 0)
987                                 n = j * 2;
988                         else
989                                 n = j * 2 + 1;
990                 }
991         } while (n < t->size);
992
993         inorder = to_inorder(j, t);
994
995         /*
996          * n would have been the node we recursed to - the low bit tells us if
997          * we recursed left or recursed right.
998          */
999         if (n & 1) {
1000                 l = cacheline_to_bkey(t, inorder, f->m);
1001
1002                 if (++inorder != t->size) {
1003                         f = &t->tree[inorder_next(j, t->size)];
1004                         r = cacheline_to_bkey(t, inorder, f->m);
1005                 } else
1006                         r = bset_bkey_last(t->data);
1007         } else {
1008                 r = cacheline_to_bkey(t, inorder, f->m);
1009
1010                 if (--inorder) {
1011                         f = &t->tree[inorder_prev(j, t->size)];
1012                         l = cacheline_to_bkey(t, inorder, f->m);
1013                 } else
1014                         l = t->data->start;
1015         }
1016
1017         return (struct bset_search_iter) {l, r};
1018 }
1019
1020 struct bkey *__bch_bset_search(struct btree_keys *b, struct bset_tree *t,
1021                                const struct bkey *search)
1022 {
1023         struct bset_search_iter i;
1024
1025         /*
1026          * First, we search for a cacheline, then lastly we do a linear search
1027          * within that cacheline.
1028          *
1029          * To search for the cacheline, there's three different possibilities:
1030          *  * The set is too small to have a search tree, so we just do a linear
1031          *    search over the whole set.
1032          *  * The set is the one we're currently inserting into; keeping a full
1033          *    auxiliary search tree up to date would be too expensive, so we
1034          *    use a much simpler lookup table to do a binary search -
1035          *    bset_search_write_set().
1036          *  * Or we use the auxiliary search tree we constructed earlier -
1037          *    bset_search_tree()
1038          */
1039
1040         if (unlikely(!t->size)) {
1041                 i.l = t->data->start;
1042                 i.r = bset_bkey_last(t->data);
1043         } else if (bset_written(b, t)) {
1044                 /*
1045                  * Each node in the auxiliary search tree covers a certain range
1046                  * of bits, and keys above and below the set it covers might
1047                  * differ outside those bits - so we have to special case the
1048                  * start and end - handle that here:
1049                  */
1050
1051                 if (unlikely(bkey_cmp(search, &t->end) >= 0))
1052                         return bset_bkey_last(t->data);
1053
1054                 if (unlikely(bkey_cmp(search, t->data->start) < 0))
1055                         return t->data->start;
1056
1057                 i = bset_search_tree(t, search);
1058         } else {
1059                 BUG_ON(!b->nsets &&
1060                        t->size < bkey_to_cacheline(t, bset_bkey_last(t->data)));
1061
1062                 i = bset_search_write_set(t, search);
1063         }
1064
1065         if (btree_keys_expensive_checks(b)) {
1066                 BUG_ON(bset_written(b, t) &&
1067                        i.l != t->data->start &&
1068                        bkey_cmp(tree_to_prev_bkey(t,
1069                           inorder_to_tree(bkey_to_cacheline(t, i.l), t)),
1070                                 search) > 0);
1071
1072                 BUG_ON(i.r != bset_bkey_last(t->data) &&
1073                        bkey_cmp(i.r, search) <= 0);
1074         }
1075
1076         while (likely(i.l != i.r) &&
1077                bkey_cmp(i.l, search) <= 0)
1078                 i.l = bkey_next(i.l);
1079
1080         return i.l;
1081 }
1082 EXPORT_SYMBOL(__bch_bset_search);
1083
1084 /* Btree iterator */
1085
1086 typedef bool (btree_iter_cmp_fn)(struct btree_iter_set,
1087                                  struct btree_iter_set);
1088
1089 static inline bool btree_iter_cmp(struct btree_iter_set l,
1090                                   struct btree_iter_set r)
1091 {
1092         return bkey_cmp(l.k, r.k) > 0;
1093 }
1094
1095 static inline bool btree_iter_end(struct btree_iter *iter)
1096 {
1097         return !iter->used;
1098 }
1099
1100 void bch_btree_iter_push(struct btree_iter *iter, struct bkey *k,
1101                          struct bkey *end)
1102 {
1103         if (k != end)
1104                 BUG_ON(!heap_add(iter,
1105                                  ((struct btree_iter_set) { k, end }),
1106                                  btree_iter_cmp));
1107 }
1108
1109 static struct bkey *__bch_btree_iter_init(struct btree_keys *b,
1110                                           struct btree_iter *iter,
1111                                           struct bkey *search,
1112                                           struct bset_tree *start)
1113 {
1114         struct bkey *ret = NULL;
1115
1116         iter->size = ARRAY_SIZE(iter->data);
1117         iter->used = 0;
1118
1119 #ifdef CONFIG_BCACHE_DEBUG
1120         iter->b = b;
1121 #endif
1122
1123         for (; start <= bset_tree_last(b); start++) {
1124                 ret = bch_bset_search(b, start, search);
1125                 bch_btree_iter_push(iter, ret, bset_bkey_last(start->data));
1126         }
1127
1128         return ret;
1129 }
1130
1131 struct bkey *bch_btree_iter_init(struct btree_keys *b,
1132                                  struct btree_iter *iter,
1133                                  struct bkey *search)
1134 {
1135         return __bch_btree_iter_init(b, iter, search, b->set);
1136 }
1137 EXPORT_SYMBOL(bch_btree_iter_init);
1138
1139 static inline struct bkey *__bch_btree_iter_next(struct btree_iter *iter,
1140                                                  btree_iter_cmp_fn *cmp)
1141 {
1142         struct btree_iter_set b __maybe_unused;
1143         struct bkey *ret = NULL;
1144
1145         if (!btree_iter_end(iter)) {
1146                 bch_btree_iter_next_check(iter);
1147
1148                 ret = iter->data->k;
1149                 iter->data->k = bkey_next(iter->data->k);
1150
1151                 if (iter->data->k > iter->data->end) {
1152                         WARN_ONCE(1, "bset was corrupt!\n");
1153                         iter->data->k = iter->data->end;
1154                 }
1155
1156                 if (iter->data->k == iter->data->end)
1157                         heap_pop(iter, b, cmp);
1158                 else
1159                         heap_sift(iter, 0, cmp);
1160         }
1161
1162         return ret;
1163 }
1164
1165 struct bkey *bch_btree_iter_next(struct btree_iter *iter)
1166 {
1167         return __bch_btree_iter_next(iter, btree_iter_cmp);
1168
1169 }
1170 EXPORT_SYMBOL(bch_btree_iter_next);
1171
1172 struct bkey *bch_btree_iter_next_filter(struct btree_iter *iter,
1173                                         struct btree_keys *b, ptr_filter_fn fn)
1174 {
1175         struct bkey *ret;
1176
1177         do {
1178                 ret = bch_btree_iter_next(iter);
1179         } while (ret && fn(b, ret));
1180
1181         return ret;
1182 }
1183
1184 /* Mergesort */
1185
1186 void bch_bset_sort_state_free(struct bset_sort_state *state)
1187 {
1188         mempool_exit(&state->pool);
1189 }
1190
1191 int bch_bset_sort_state_init(struct bset_sort_state *state,
1192                              unsigned int page_order)
1193 {
1194         spin_lock_init(&state->time.lock);
1195
1196         state->page_order = page_order;
1197         state->crit_factor = int_sqrt(1 << page_order);
1198
1199         return mempool_init_page_pool(&state->pool, 1, page_order);
1200 }
1201 EXPORT_SYMBOL(bch_bset_sort_state_init);
1202
1203 static void btree_mergesort(struct btree_keys *b, struct bset *out,
1204                             struct btree_iter *iter,
1205                             bool fixup, bool remove_stale)
1206 {
1207         int i;
1208         struct bkey *k, *last = NULL;
1209         BKEY_PADDED(k) tmp;
1210         bool (*bad)(struct btree_keys *, const struct bkey *) = remove_stale
1211                 ? bch_ptr_bad
1212                 : bch_ptr_invalid;
1213
1214         /* Heapify the iterator, using our comparison function */
1215         for (i = iter->used / 2 - 1; i >= 0; --i)
1216                 heap_sift(iter, i, b->ops->sort_cmp);
1217
1218         while (!btree_iter_end(iter)) {
1219                 if (b->ops->sort_fixup && fixup)
1220                         k = b->ops->sort_fixup(iter, &tmp.k);
1221                 else
1222                         k = NULL;
1223
1224                 if (!k)
1225                         k = __bch_btree_iter_next(iter, b->ops->sort_cmp);
1226
1227                 if (bad(b, k))
1228                         continue;
1229
1230                 if (!last) {
1231                         last = out->start;
1232                         bkey_copy(last, k);
1233                 } else if (!bch_bkey_try_merge(b, last, k)) {
1234                         last = bkey_next(last);
1235                         bkey_copy(last, k);
1236                 }
1237         }
1238
1239         out->keys = last ? (uint64_t *) bkey_next(last) - out->d : 0;
1240
1241         pr_debug("sorted %i keys", out->keys);
1242 }
1243
1244 static void __btree_sort(struct btree_keys *b, struct btree_iter *iter,
1245                          unsigned int start, unsigned int order, bool fixup,
1246                          struct bset_sort_state *state)
1247 {
1248         uint64_t start_time;
1249         bool used_mempool = false;
1250         struct bset *out = (void *) __get_free_pages(__GFP_NOWARN|GFP_NOWAIT,
1251                                                      order);
1252         if (!out) {
1253                 struct page *outp;
1254
1255                 BUG_ON(order > state->page_order);
1256
1257                 outp = mempool_alloc(&state->pool, GFP_NOIO);
1258                 out = page_address(outp);
1259                 used_mempool = true;
1260                 order = state->page_order;
1261         }
1262
1263         start_time = local_clock();
1264
1265         btree_mergesort(b, out, iter, fixup, false);
1266         b->nsets = start;
1267
1268         if (!start && order == b->page_order) {
1269                 /*
1270                  * Our temporary buffer is the same size as the btree node's
1271                  * buffer, we can just swap buffers instead of doing a big
1272                  * memcpy()
1273                  */
1274
1275                 out->magic      = b->set->data->magic;
1276                 out->seq        = b->set->data->seq;
1277                 out->version    = b->set->data->version;
1278                 swap(out, b->set->data);
1279         } else {
1280                 b->set[start].data->keys = out->keys;
1281                 memcpy(b->set[start].data->start, out->start,
1282                        (void *) bset_bkey_last(out) - (void *) out->start);
1283         }
1284
1285         if (used_mempool)
1286                 mempool_free(virt_to_page(out), &state->pool);
1287         else
1288                 free_pages((unsigned long) out, order);
1289
1290         bch_bset_build_written_tree(b);
1291
1292         if (!start)
1293                 bch_time_stats_update(&state->time, start_time);
1294 }
1295
1296 void bch_btree_sort_partial(struct btree_keys *b, unsigned int start,
1297                             struct bset_sort_state *state)
1298 {
1299         size_t order = b->page_order, keys = 0;
1300         struct btree_iter iter;
1301         int oldsize = bch_count_data(b);
1302
1303         __bch_btree_iter_init(b, &iter, NULL, &b->set[start]);
1304
1305         if (start) {
1306                 unsigned int i;
1307
1308                 for (i = start; i <= b->nsets; i++)
1309                         keys += b->set[i].data->keys;
1310
1311                 order = get_order(__set_bytes(b->set->data, keys));
1312         }
1313
1314         __btree_sort(b, &iter, start, order, false, state);
1315
1316         EBUG_ON(oldsize >= 0 && bch_count_data(b) != oldsize);
1317 }
1318 EXPORT_SYMBOL(bch_btree_sort_partial);
1319
1320 void bch_btree_sort_and_fix_extents(struct btree_keys *b,
1321                                     struct btree_iter *iter,
1322                                     struct bset_sort_state *state)
1323 {
1324         __btree_sort(b, iter, 0, b->page_order, true, state);
1325 }
1326
1327 void bch_btree_sort_into(struct btree_keys *b, struct btree_keys *new,
1328                          struct bset_sort_state *state)
1329 {
1330         uint64_t start_time = local_clock();
1331         struct btree_iter iter;
1332
1333         bch_btree_iter_init(b, &iter, NULL);
1334
1335         btree_mergesort(b, new->set->data, &iter, false, true);
1336
1337         bch_time_stats_update(&state->time, start_time);
1338
1339         new->set->size = 0; // XXX: why?
1340 }
1341
1342 #define SORT_CRIT       (4096 / sizeof(uint64_t))
1343
1344 void bch_btree_sort_lazy(struct btree_keys *b, struct bset_sort_state *state)
1345 {
1346         unsigned int crit = SORT_CRIT;
1347         int i;
1348
1349         /* Don't sort if nothing to do */
1350         if (!b->nsets)
1351                 goto out;
1352
1353         for (i = b->nsets - 1; i >= 0; --i) {
1354                 crit *= state->crit_factor;
1355
1356                 if (b->set[i].data->keys < crit) {
1357                         bch_btree_sort_partial(b, i, state);
1358                         return;
1359                 }
1360         }
1361
1362         /* Sort if we'd overflow */
1363         if (b->nsets + 1 == MAX_BSETS) {
1364                 bch_btree_sort(b, state);
1365                 return;
1366         }
1367
1368 out:
1369         bch_bset_build_written_tree(b);
1370 }
1371 EXPORT_SYMBOL(bch_btree_sort_lazy);
1372
1373 void bch_btree_keys_stats(struct btree_keys *b, struct bset_stats *stats)
1374 {
1375         unsigned int i;
1376
1377         for (i = 0; i <= b->nsets; i++) {
1378                 struct bset_tree *t = &b->set[i];
1379                 size_t bytes = t->data->keys * sizeof(uint64_t);
1380                 size_t j;
1381
1382                 if (bset_written(b, t)) {
1383                         stats->sets_written++;
1384                         stats->bytes_written += bytes;
1385
1386                         stats->floats += t->size - 1;
1387
1388                         for (j = 1; j < t->size; j++)
1389                                 if (t->tree[j].exponent == 127)
1390                                         stats->failed++;
1391                 } else {
1392                         stats->sets_unwritten++;
1393                         stats->bytes_unwritten += bytes;
1394                 }
1395         }
1396 }