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