bset.c 32.0 KB
Newer Older
K
Kent Overstreet 已提交
1 2 3 4 5 6 7 8 9 10 11 12
/*
 * Code for working with individual keys, and sorted sets of keys with in a
 * btree node
 *
 * Copyright 2012 Google, Inc.
 */

#include "bcache.h"
#include "btree.h"
#include "debug.h"

#include <linux/random.h>
13
#include <linux/prefetch.h>
K
Kent Overstreet 已提交
14 15 16

/* Keylists */

17
int __bch_keylist_realloc(struct keylist *l, unsigned u64s)
K
Kent Overstreet 已提交
18
{
K
Kent Overstreet 已提交
19
	size_t oldsize = bch_keylist_nkeys(l);
20
	size_t newsize = oldsize + u64s;
K
Kent Overstreet 已提交
21 22
	uint64_t *old_keys = l->keys_p == l->inline_keys ? NULL : l->keys_p;
	uint64_t *new_keys;
K
Kent Overstreet 已提交
23 24 25 26 27 28 29

	newsize = roundup_pow_of_two(newsize);

	if (newsize <= KEYLIST_INLINE ||
	    roundup_pow_of_two(oldsize) == newsize)
		return 0;

K
Kent Overstreet 已提交
30
	new_keys = krealloc(old_keys, sizeof(uint64_t) * newsize, GFP_NOIO);
K
Kent Overstreet 已提交
31

K
Kent Overstreet 已提交
32
	if (!new_keys)
K
Kent Overstreet 已提交
33 34
		return -ENOMEM;

K
Kent Overstreet 已提交
35 36
	if (!old_keys)
		memcpy(new_keys, l->inline_keys, sizeof(uint64_t) * oldsize);
K
Kent Overstreet 已提交
37

K
Kent Overstreet 已提交
38 39
	l->keys_p = new_keys;
	l->top_p = new_keys + oldsize;
K
Kent Overstreet 已提交
40 41 42 43 44 45

	return 0;
}

struct bkey *bch_keylist_pop(struct keylist *l)
{
K
Kent Overstreet 已提交
46
	struct bkey *k = l->keys;
K
Kent Overstreet 已提交
47 48 49 50 51 52 53 54 55 56

	if (k == l->top)
		return NULL;

	while (bkey_next(k) != l->top)
		k = bkey_next(k);

	return l->top = k;
}

K
Kent Overstreet 已提交
57 58
void bch_keylist_pop_front(struct keylist *l)
{
K
Kent Overstreet 已提交
59
	l->top_p -= bkey_u64s(l->keys);
K
Kent Overstreet 已提交
60

K
Kent Overstreet 已提交
61 62 63
	memmove(l->keys,
		bkey_next(l->keys),
		bch_keylist_bytes(l));
K
Kent Overstreet 已提交
64 65
}

K
Kent Overstreet 已提交
66 67
/* Pointer validation */

68
static bool __ptr_invalid(struct cache_set *c, const struct bkey *k)
K
Kent Overstreet 已提交
69 70 71 72 73 74 75 76 77 78 79 80
{
	unsigned i;

	for (i = 0; i < KEY_PTRS(k); i++)
		if (ptr_available(c, k, i)) {
			struct cache *ca = PTR_CACHE(c, k, i);
			size_t bucket = PTR_BUCKET_NR(c, k, i);
			size_t r = bucket_remainder(c, PTR_OFFSET(k, i));

			if (KEY_SIZE(k) + r > c->sb.bucket_size ||
			    bucket <  ca->sb.first_bucket ||
			    bucket >= ca->sb.nbuckets)
81
				return true;
K
Kent Overstreet 已提交
82 83
		}

84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116
	return false;
}

bool bch_btree_ptr_invalid(struct cache_set *c, const struct bkey *k)
{
	char buf[80];

	if (!KEY_PTRS(k) || !KEY_SIZE(k) || KEY_DIRTY(k))
		goto bad;

	if (__ptr_invalid(c, k))
		goto bad;

	return false;
bad:
	bch_bkey_to_text(buf, sizeof(buf), k);
	cache_bug(c, "spotted btree ptr %s: %s", buf, bch_ptr_status(c, k));
	return true;
}

bool bch_extent_ptr_invalid(struct cache_set *c, const struct bkey *k)
{
	char buf[80];

	if (!KEY_SIZE(k))
		return true;

	if (KEY_SIZE(k) > KEY_OFFSET(k))
		goto bad;

	if (__ptr_invalid(c, k))
		goto bad;

K
Kent Overstreet 已提交
117 118
	return false;
bad:
119
	bch_bkey_to_text(buf, sizeof(buf), k);
120
	cache_bug(c, "spotted extent %s: %s", buf, bch_ptr_status(c, k));
K
Kent Overstreet 已提交
121 122 123
	return true;
}

K
Kent Overstreet 已提交
124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160
static bool ptr_bad_expensive_checks(struct btree *b, const struct bkey *k,
				     unsigned ptr)
{
	struct bucket *g = PTR_BUCKET(b->c, k, ptr);
	char buf[80];

	if (mutex_trylock(&b->c->bucket_lock)) {
		if (b->level) {
			if (KEY_DIRTY(k) ||
			    g->prio != BTREE_PRIO ||
			    (b->c->gc_mark_valid &&
			     GC_MARK(g) != GC_MARK_METADATA))
				goto err;

		} else {
			if (g->prio == BTREE_PRIO)
				goto err;

			if (KEY_DIRTY(k) &&
			    b->c->gc_mark_valid &&
			    GC_MARK(g) != GC_MARK_DIRTY)
				goto err;
		}
		mutex_unlock(&b->c->bucket_lock);
	}

	return false;
err:
	mutex_unlock(&b->c->bucket_lock);
	bch_bkey_to_text(buf, sizeof(buf), k);
	btree_bug(b,
"inconsistent pointer %s: bucket %zu pin %i prio %i gen %i last_gc %i mark %llu gc_gen %i",
		  buf, PTR_BUCKET_NR(b->c, k, ptr), atomic_read(&g->pin),
		  g->prio, g->gen, g->last_gc, GC_MARK(g), g->gc_gen);
	return true;
}

K
Kent Overstreet 已提交
161 162 163 164 165 166 167 168 169 170
bool bch_ptr_bad(struct btree *b, const struct bkey *k)
{
	struct bucket *g;
	unsigned i, stale;

	if (!bkey_cmp(k, &ZERO_KEY) ||
	    !KEY_PTRS(k) ||
	    bch_ptr_invalid(b, k))
		return true;

171
	for (i = 0; i < KEY_PTRS(k); i++)
K
Kent Overstreet 已提交
172 173
		if (!ptr_available(b->c, k, i))
			return true;
K
Kent Overstreet 已提交
174

175 176 177 178
	if (!expensive_debug_checks(b->c) && KEY_DIRTY(k))
		return false;

	for (i = 0; i < KEY_PTRS(k); i++) {
K
Kent Overstreet 已提交
179 180
		g = PTR_BUCKET(b->c, k, i);
		stale = ptr_stale(b->c, k, i);
K
Kent Overstreet 已提交
181

K
Kent Overstreet 已提交
182 183 184
		btree_bug_on(stale > 96, b,
			     "key too stale: %i, need_gc %u",
			     stale, b->c->need_gc);
K
Kent Overstreet 已提交
185

K
Kent Overstreet 已提交
186 187
		btree_bug_on(stale && KEY_DIRTY(k) && KEY_SIZE(k),
			     b, "stale dirty pointer");
K
Kent Overstreet 已提交
188

K
Kent Overstreet 已提交
189 190
		if (stale)
			return true;
K
Kent Overstreet 已提交
191

K
Kent Overstreet 已提交
192 193 194
		if (expensive_debug_checks(b->c) &&
		    ptr_bad_expensive_checks(b, k, i))
			return true;
K
Kent Overstreet 已提交
195
	}
K
Kent Overstreet 已提交
196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304

	return false;
}

/* Key/pointer manipulation */

void bch_bkey_copy_single_ptr(struct bkey *dest, const struct bkey *src,
			      unsigned i)
{
	BUG_ON(i > KEY_PTRS(src));

	/* Only copy the header, key, and one pointer. */
	memcpy(dest, src, 2 * sizeof(uint64_t));
	dest->ptr[0] = src->ptr[i];
	SET_KEY_PTRS(dest, 1);
	/* We didn't copy the checksum so clear that bit. */
	SET_KEY_CSUM(dest, 0);
}

bool __bch_cut_front(const struct bkey *where, struct bkey *k)
{
	unsigned i, len = 0;

	if (bkey_cmp(where, &START_KEY(k)) <= 0)
		return false;

	if (bkey_cmp(where, k) < 0)
		len = KEY_OFFSET(k) - KEY_OFFSET(where);
	else
		bkey_copy_key(k, where);

	for (i = 0; i < KEY_PTRS(k); i++)
		SET_PTR_OFFSET(k, i, PTR_OFFSET(k, i) + KEY_SIZE(k) - len);

	BUG_ON(len > KEY_SIZE(k));
	SET_KEY_SIZE(k, len);
	return true;
}

bool __bch_cut_back(const struct bkey *where, struct bkey *k)
{
	unsigned len = 0;

	if (bkey_cmp(where, k) >= 0)
		return false;

	BUG_ON(KEY_INODE(where) != KEY_INODE(k));

	if (bkey_cmp(where, &START_KEY(k)) > 0)
		len = KEY_OFFSET(where) - KEY_START(k);

	bkey_copy_key(k, where);

	BUG_ON(len > KEY_SIZE(k));
	SET_KEY_SIZE(k, len);
	return true;
}

static uint64_t merge_chksums(struct bkey *l, struct bkey *r)
{
	return (l->ptr[KEY_PTRS(l)] + r->ptr[KEY_PTRS(r)]) &
		~((uint64_t)1 << 63);
}

/* Tries to merge l and r: l should be lower than r
 * Returns true if we were able to merge. If we did merge, l will be the merged
 * key, r will be untouched.
 */
bool bch_bkey_try_merge(struct btree *b, struct bkey *l, struct bkey *r)
{
	unsigned i;

	if (key_merging_disabled(b->c))
		return false;

	if (KEY_PTRS(l) != KEY_PTRS(r) ||
	    KEY_DIRTY(l) != KEY_DIRTY(r) ||
	    bkey_cmp(l, &START_KEY(r)))
		return false;

	for (i = 0; i < KEY_PTRS(l); i++)
		if (l->ptr[i] + PTR(0, KEY_SIZE(l), 0) != r->ptr[i] ||
		    PTR_BUCKET_NR(b->c, l, i) != PTR_BUCKET_NR(b->c, r, i))
			return false;

	/* Keys with no pointers aren't restricted to one bucket and could
	 * overflow KEY_SIZE
	 */
	if (KEY_SIZE(l) + KEY_SIZE(r) > USHRT_MAX) {
		SET_KEY_OFFSET(l, KEY_OFFSET(l) + USHRT_MAX - KEY_SIZE(l));
		SET_KEY_SIZE(l, USHRT_MAX);

		bch_cut_front(l, r);
		return false;
	}

	if (KEY_CSUM(l)) {
		if (KEY_CSUM(r))
			l->ptr[KEY_PTRS(l)] = merge_chksums(l, r);
		else
			SET_KEY_CSUM(l, 0);
	}

	SET_KEY_OFFSET(l, KEY_OFFSET(l) + KEY_SIZE(r));
	SET_KEY_SIZE(l, KEY_SIZE(l) + KEY_SIZE(r));

	return true;
}

305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413
/* Auxiliary search trees */

/* 32 bits total: */
#define BKEY_MID_BITS		3
#define BKEY_EXPONENT_BITS	7
#define BKEY_MANTISSA_BITS	(32 - BKEY_MID_BITS - BKEY_EXPONENT_BITS)
#define BKEY_MANTISSA_MASK	((1 << BKEY_MANTISSA_BITS) - 1)

struct bkey_float {
	unsigned	exponent:BKEY_EXPONENT_BITS;
	unsigned	m:BKEY_MID_BITS;
	unsigned	mantissa:BKEY_MANTISSA_BITS;
} __packed;

/*
 * BSET_CACHELINE was originally intended to match the hardware cacheline size -
 * it used to be 64, but I realized the lookup code would touch slightly less
 * memory if it was 128.
 *
 * It definites the number of bytes (in struct bset) per struct bkey_float in
 * the auxiliar search tree - when we're done searching the bset_float tree we
 * have this many bytes left that we do a linear search over.
 *
 * Since (after level 5) every level of the bset_tree is on a new cacheline,
 * we're touching one fewer cacheline in the bset tree in exchange for one more
 * cacheline in the linear search - but the linear search might stop before it
 * gets to the second cacheline.
 */

#define BSET_CACHELINE		128

/* Space required for the btree node keys */
static inline size_t btree_keys_bytes(struct btree *b)
{
	return PAGE_SIZE << b->page_order;
}

static inline size_t btree_keys_cachelines(struct btree *b)
{
	return btree_keys_bytes(b) / BSET_CACHELINE;
}

/* Space required for the auxiliary search trees */
static inline size_t bset_tree_bytes(struct btree *b)
{
	return btree_keys_cachelines(b) * sizeof(struct bkey_float);
}

/* Space required for the prev pointers */
static inline size_t bset_prev_bytes(struct btree *b)
{
	return btree_keys_cachelines(b) * sizeof(uint8_t);
}

/* Memory allocation */

void bch_btree_keys_free(struct btree *b)
{
	struct bset_tree *t = b->sets;

	if (bset_prev_bytes(b) < PAGE_SIZE)
		kfree(t->prev);
	else
		free_pages((unsigned long) t->prev,
			   get_order(bset_prev_bytes(b)));

	if (bset_tree_bytes(b) < PAGE_SIZE)
		kfree(t->tree);
	else
		free_pages((unsigned long) t->tree,
			   get_order(bset_tree_bytes(b)));

	free_pages((unsigned long) t->data, b->page_order);

	t->prev = NULL;
	t->tree = NULL;
	t->data = NULL;
}

int bch_btree_keys_alloc(struct btree *b, unsigned page_order, gfp_t gfp)
{
	struct bset_tree *t = b->sets;

	BUG_ON(t->data);

	b->page_order = page_order;

	t->data = (void *) __get_free_pages(gfp, b->page_order);
	if (!t->data)
		goto err;

	t->tree = bset_tree_bytes(b) < PAGE_SIZE
		? kmalloc(bset_tree_bytes(b), gfp)
		: (void *) __get_free_pages(gfp, get_order(bset_tree_bytes(b)));
	if (!t->tree)
		goto err;

	t->prev = bset_prev_bytes(b) < PAGE_SIZE
		? kmalloc(bset_prev_bytes(b), gfp)
		: (void *) __get_free_pages(gfp, get_order(bset_prev_bytes(b)));
	if (!t->prev)
		goto err;

	return 0;
err:
	bch_btree_keys_free(b);
	return -ENOMEM;
}

K
Kent Overstreet 已提交
414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533
/* Binary tree stuff for auxiliary search trees */

static unsigned inorder_next(unsigned j, unsigned size)
{
	if (j * 2 + 1 < size) {
		j = j * 2 + 1;

		while (j * 2 < size)
			j *= 2;
	} else
		j >>= ffz(j) + 1;

	return j;
}

static unsigned inorder_prev(unsigned j, unsigned size)
{
	if (j * 2 < size) {
		j = j * 2;

		while (j * 2 + 1 < size)
			j = j * 2 + 1;
	} else
		j >>= ffs(j);

	return j;
}

/* I have no idea why this code works... and I'm the one who wrote it
 *
 * However, I do know what it does:
 * Given a binary tree constructed in an array (i.e. how you normally implement
 * a heap), it converts a node in the tree - referenced by array index - to the
 * index it would have if you did an inorder traversal.
 *
 * Also tested for every j, size up to size somewhere around 6 million.
 *
 * The binary tree starts at array index 1, not 0
 * extra is a function of size:
 *   extra = (size - rounddown_pow_of_two(size - 1)) << 1;
 */
static unsigned __to_inorder(unsigned j, unsigned size, unsigned extra)
{
	unsigned b = fls(j);
	unsigned shift = fls(size - 1) - b;

	j  ^= 1U << (b - 1);
	j <<= 1;
	j  |= 1;
	j <<= shift;

	if (j > extra)
		j -= (j - extra) >> 1;

	return j;
}

static unsigned to_inorder(unsigned j, struct bset_tree *t)
{
	return __to_inorder(j, t->size, t->extra);
}

static unsigned __inorder_to_tree(unsigned j, unsigned size, unsigned extra)
{
	unsigned shift;

	if (j > extra)
		j += j - extra;

	shift = ffs(j);

	j >>= shift;
	j  |= roundup_pow_of_two(size) >> shift;

	return j;
}

static unsigned inorder_to_tree(unsigned j, struct bset_tree *t)
{
	return __inorder_to_tree(j, t->size, t->extra);
}

#if 0
void inorder_test(void)
{
	unsigned long done = 0;
	ktime_t start = ktime_get();

	for (unsigned size = 2;
	     size < 65536000;
	     size++) {
		unsigned extra = (size - rounddown_pow_of_two(size - 1)) << 1;
		unsigned i = 1, j = rounddown_pow_of_two(size - 1);

		if (!(size % 4096))
			printk(KERN_NOTICE "loop %u, %llu per us\n", size,
			       done / ktime_us_delta(ktime_get(), start));

		while (1) {
			if (__inorder_to_tree(i, size, extra) != j)
				panic("size %10u j %10u i %10u", size, j, i);

			if (__to_inorder(j, size, extra) != i)
				panic("size %10u j %10u i %10u", size, j, i);

			if (j == rounddown_pow_of_two(size) - 1)
				break;

			BUG_ON(inorder_prev(inorder_next(j, size), size) != j);

			j = inorder_next(j, size);
			i++;
		}

		done += size - 1;
	}
}
#endif

/*
534
 * Cacheline/offset <-> bkey pointer arithmetic:
K
Kent Overstreet 已提交
535 536 537 538 539 540 541 542
 *
 * t->tree is a binary search tree in an array; each node corresponds to a key
 * in one cacheline in t->set (BSET_CACHELINE bytes).
 *
 * This means we don't have to store the full index of the key that a node in
 * the binary tree points to; to_inorder() gives us the cacheline, and then
 * bkey_float->m gives us the offset within that cacheline, in units of 8 bytes.
 *
543
 * cacheline_to_bkey() and friends abstract out all the pointer arithmetic to
K
Kent Overstreet 已提交
544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611
 * make this work.
 *
 * To construct the bfloat for an arbitrary key we need to know what the key
 * immediately preceding it is: we have to check if the two keys differ in the
 * bits we're going to store in bkey_float->mantissa. t->prev[j] stores the size
 * of the previous key so we can walk backwards to it from t->tree[j]'s key.
 */

static struct bkey *cacheline_to_bkey(struct bset_tree *t, unsigned cacheline,
				      unsigned offset)
{
	return ((void *) t->data) + cacheline * BSET_CACHELINE + offset * 8;
}

static unsigned bkey_to_cacheline(struct bset_tree *t, struct bkey *k)
{
	return ((void *) k - (void *) t->data) / BSET_CACHELINE;
}

static unsigned bkey_to_cacheline_offset(struct bkey *k)
{
	return ((size_t) k & (BSET_CACHELINE - 1)) / sizeof(uint64_t);
}

static struct bkey *tree_to_bkey(struct bset_tree *t, unsigned j)
{
	return cacheline_to_bkey(t, to_inorder(j, t), t->tree[j].m);
}

static struct bkey *tree_to_prev_bkey(struct bset_tree *t, unsigned j)
{
	return (void *) (((uint64_t *) tree_to_bkey(t, j)) - t->prev[j]);
}

/*
 * For the write set - the one we're currently inserting keys into - we don't
 * maintain a full search tree, we just keep a simple lookup table in t->prev.
 */
static struct bkey *table_to_bkey(struct bset_tree *t, unsigned cacheline)
{
	return cacheline_to_bkey(t, cacheline, t->prev[cacheline]);
}

static inline uint64_t shrd128(uint64_t high, uint64_t low, uint8_t shift)
{
	low >>= shift;
	low  |= (high << 1) << (63U - shift);
	return low;
}

static inline unsigned bfloat_mantissa(const struct bkey *k,
				       struct bkey_float *f)
{
	const uint64_t *p = &k->low - (f->exponent >> 6);
	return shrd128(p[-1], p[0], f->exponent & 63) & BKEY_MANTISSA_MASK;
}

static void make_bfloat(struct bset_tree *t, unsigned j)
{
	struct bkey_float *f = &t->tree[j];
	struct bkey *m = tree_to_bkey(t, j);
	struct bkey *p = tree_to_prev_bkey(t, j);

	struct bkey *l = is_power_of_2(j)
		? t->data->start
		: tree_to_prev_bkey(t, j >> ffs(j));

	struct bkey *r = is_power_of_2(j + 1)
K
Kent Overstreet 已提交
612
		? bset_bkey_idx(t->data, t->data->keys - bkey_u64s(&t->end))
K
Kent Overstreet 已提交
613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649
		: tree_to_bkey(t, j >> (ffz(j) + 1));

	BUG_ON(m < l || m > r);
	BUG_ON(bkey_next(p) != m);

	if (KEY_INODE(l) != KEY_INODE(r))
		f->exponent = fls64(KEY_INODE(r) ^ KEY_INODE(l)) + 64;
	else
		f->exponent = fls64(r->low ^ l->low);

	f->exponent = max_t(int, f->exponent - BKEY_MANTISSA_BITS, 0);

	/*
	 * Setting f->exponent = 127 flags this node as failed, and causes the
	 * lookup code to fall back to comparing against the original key.
	 */

	if (bfloat_mantissa(m, f) != bfloat_mantissa(p, f))
		f->mantissa = bfloat_mantissa(m, f) - 1;
	else
		f->exponent = 127;
}

static void bset_alloc_tree(struct btree *b, struct bset_tree *t)
{
	if (t != b->sets) {
		unsigned j = roundup(t[-1].size,
				     64 / sizeof(struct bkey_float));

		t->tree = t[-1].tree + j;
		t->prev = t[-1].prev + j;
	}

	while (t < b->sets + MAX_BSETS)
		t++->size = 0;
}

650
static void bch_bset_build_unwritten_tree(struct btree *b)
K
Kent Overstreet 已提交
651
{
652
	struct bset_tree *t = bset_tree_last(b);
K
Kent Overstreet 已提交
653 654 655

	bset_alloc_tree(b, t);

656
	if (t->tree != b->sets->tree + btree_keys_cachelines(b)) {
K
Kent Overstreet 已提交
657 658 659 660 661
		t->prev[0] = bkey_to_cacheline_offset(t->data->start);
		t->size = 1;
	}
}

662 663 664 665 666 667 668 669 670 671 672 673 674 675 676
void bch_bset_init_next(struct btree *b, struct bset *i, uint64_t magic)
{
	if (i != b->sets->data) {
		b->sets[++b->nsets].data = i;
		i->seq = b->sets->data->seq;
	} else
		get_random_bytes(&i->seq, sizeof(uint64_t));

	i->magic	= magic;
	i->version	= 0;
	i->keys		= 0;

	bch_bset_build_unwritten_tree(b);
}

K
Kent Overstreet 已提交
677 678
static void bset_build_written_tree(struct btree *b)
{
679
	struct bset_tree *t = bset_tree_last(b);
K
Kent Overstreet 已提交
680 681 682 683 684 685
	struct bkey *k = t->data->start;
	unsigned j, cacheline = 1;

	bset_alloc_tree(b, t);

	t->size = min_t(unsigned,
K
Kent Overstreet 已提交
686
			bkey_to_cacheline(t, bset_bkey_last(t->data)),
687
			b->sets->tree + btree_keys_cachelines(b) - t->tree);
K
Kent Overstreet 已提交
688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708

	if (t->size < 2) {
		t->size = 0;
		return;
	}

	t->extra = (t->size - rounddown_pow_of_two(t->size - 1)) << 1;

	/* First we figure out where the first key in each cacheline is */
	for (j = inorder_next(0, t->size);
	     j;
	     j = inorder_next(j, t->size)) {
		while (bkey_to_cacheline(t, k) != cacheline)
			k = bkey_next(k);

		t->prev[j] = bkey_u64s(k);
		k = bkey_next(k);
		cacheline++;
		t->tree[j].m = bkey_to_cacheline_offset(k);
	}

K
Kent Overstreet 已提交
709
	while (bkey_next(k) != bset_bkey_last(t->data))
K
Kent Overstreet 已提交
710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725
		k = bkey_next(k);

	t->end = *k;

	/* Then we build the tree */
	for (j = inorder_next(0, t->size);
	     j;
	     j = inorder_next(j, t->size))
		make_bfloat(t, j);
}

void bch_bset_fix_invalidated_key(struct btree *b, struct bkey *k)
{
	struct bset_tree *t;
	unsigned inorder, j = 1;

726
	for (t = b->sets; t <= bset_tree_last(b); t++)
K
Kent Overstreet 已提交
727
		if (k < bset_bkey_last(t->data))
K
Kent Overstreet 已提交
728 729 730 731 732 733 734 735 736 737 738 739
			goto found_set;

	BUG();
found_set:
	if (!t->size || !bset_written(b, t))
		return;

	inorder = bkey_to_cacheline(t, k);

	if (k == t->data->start)
		goto fix_left;

K
Kent Overstreet 已提交
740
	if (bkey_next(k) == bset_bkey_last(t->data)) {
K
Kent Overstreet 已提交
741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765
		t->end = *k;
		goto fix_right;
	}

	j = inorder_to_tree(inorder, t);

	if (j &&
	    j < t->size &&
	    k == tree_to_bkey(t, j))
fix_left:	do {
			make_bfloat(t, j);
			j = j * 2;
		} while (j < t->size);

	j = inorder_to_tree(inorder + 1, t);

	if (j &&
	    j < t->size &&
	    k == tree_to_prev_bkey(t, j))
fix_right:	do {
			make_bfloat(t, j);
			j = j * 2 + 1;
		} while (j < t->size);
}

766 767 768
static void bch_bset_fix_lookup_table(struct btree *b,
				      struct bset_tree *t,
				      struct bkey *k)
K
Kent Overstreet 已提交
769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800
{
	unsigned shift = bkey_u64s(k);
	unsigned j = bkey_to_cacheline(t, k);

	/* We're getting called from btree_split() or btree_gc, just bail out */
	if (!t->size)
		return;

	/* k is the key we just inserted; we need to find the entry in the
	 * lookup table for the first key that is strictly greater than k:
	 * it's either k's cacheline or the next one
	 */
	if (j < t->size &&
	    table_to_bkey(t, j) <= k)
		j++;

	/* Adjust all the lookup table entries, and find a new key for any that
	 * have gotten too big
	 */
	for (; j < t->size; j++) {
		t->prev[j] += shift;

		if (t->prev[j] > 7) {
			k = table_to_bkey(t, j - 1);

			while (k < cacheline_to_bkey(t, j, 0))
				k = bkey_next(k);

			t->prev[j] = bkey_to_cacheline_offset(k);
		}
	}

801
	if (t->size == b->sets->tree + btree_keys_cachelines(b) - t->tree)
K
Kent Overstreet 已提交
802 803 804 805 806
		return;

	/* Possibly add a new entry to the end of the lookup table */

	for (k = table_to_bkey(t, t->size - 1);
K
Kent Overstreet 已提交
807
	     k != bset_bkey_last(t->data);
K
Kent Overstreet 已提交
808 809 810 811 812 813 814
	     k = bkey_next(k))
		if (t->size == bkey_to_cacheline(t, k)) {
			t->prev[t->size] = bkey_to_cacheline_offset(k);
			t->size++;
		}
}

815 816
void bch_bset_insert(struct btree *b, struct bkey *where,
		     struct bkey *insert)
K
Kent Overstreet 已提交
817
{
818
	struct bset_tree *t = bset_tree_last(b);
K
Kent Overstreet 已提交
819

820 821 822 823
	BUG_ON(t->data != write_block(b));
	BUG_ON(bset_byte_offset(b, t->data) +
	       __set_bytes(t->data, t->data->keys + bkey_u64s(insert)) >
	       PAGE_SIZE << b->page_order);
K
Kent Overstreet 已提交
824

825 826 827
	memmove((uint64_t *) where + bkey_u64s(insert),
		where,
		(void *) bset_bkey_last(t->data) - (void *) where);
K
Kent Overstreet 已提交
828

829 830 831
	t->data->keys += bkey_u64s(insert);
	bkey_copy(where, insert);
	bch_bset_fix_lookup_table(b, t, where);
K
Kent Overstreet 已提交
832 833 834 835 836 837 838 839 840 841 842 843 844
}

struct bset_search_iter {
	struct bkey *l, *r;
};

static struct bset_search_iter bset_search_write_set(struct btree *b,
						     struct bset_tree *t,
						     const struct bkey *search)
{
	unsigned li = 0, ri = t->size;

	BUG_ON(!b->nsets &&
K
Kent Overstreet 已提交
845
	       t->size < bkey_to_cacheline(t, bset_bkey_last(t->data)));
K
Kent Overstreet 已提交
846 847 848 849 850 851 852 853 854 855 856 857

	while (li + 1 != ri) {
		unsigned m = (li + ri) >> 1;

		if (bkey_cmp(table_to_bkey(t, m), search) > 0)
			ri = m;
		else
			li = m;
	}

	return (struct bset_search_iter) {
		table_to_bkey(t, li),
K
Kent Overstreet 已提交
858
		ri < t->size ? table_to_bkey(t, ri) : bset_bkey_last(t->data)
K
Kent Overstreet 已提交
859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909
	};
}

static struct bset_search_iter bset_search_tree(struct btree *b,
						struct bset_tree *t,
						const struct bkey *search)
{
	struct bkey *l, *r;
	struct bkey_float *f;
	unsigned inorder, j, n = 1;

	do {
		unsigned p = n << 4;
		p &= ((int) (p - t->size)) >> 31;

		prefetch(&t->tree[p]);

		j = n;
		f = &t->tree[j];

		/*
		 * n = (f->mantissa > bfloat_mantissa())
		 *	? j * 2
		 *	: j * 2 + 1;
		 *
		 * We need to subtract 1 from f->mantissa for the sign bit trick
		 * to work  - that's done in make_bfloat()
		 */
		if (likely(f->exponent != 127))
			n = j * 2 + (((unsigned)
				      (f->mantissa -
				       bfloat_mantissa(search, f))) >> 31);
		else
			n = (bkey_cmp(tree_to_bkey(t, j), search) > 0)
				? j * 2
				: j * 2 + 1;
	} while (n < t->size);

	inorder = to_inorder(j, t);

	/*
	 * n would have been the node we recursed to - the low bit tells us if
	 * we recursed left or recursed right.
	 */
	if (n & 1) {
		l = cacheline_to_bkey(t, inorder, f->m);

		if (++inorder != t->size) {
			f = &t->tree[inorder_next(j, t->size)];
			r = cacheline_to_bkey(t, inorder, f->m);
		} else
K
Kent Overstreet 已提交
910
			r = bset_bkey_last(t->data);
K
Kent Overstreet 已提交
911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945
	} else {
		r = cacheline_to_bkey(t, inorder, f->m);

		if (--inorder) {
			f = &t->tree[inorder_prev(j, t->size)];
			l = cacheline_to_bkey(t, inorder, f->m);
		} else
			l = t->data->start;
	}

	return (struct bset_search_iter) {l, r};
}

struct bkey *__bch_bset_search(struct btree *b, struct bset_tree *t,
			       const struct bkey *search)
{
	struct bset_search_iter i;

	/*
	 * First, we search for a cacheline, then lastly we do a linear search
	 * within that cacheline.
	 *
	 * To search for the cacheline, there's three different possibilities:
	 *  * The set is too small to have a search tree, so we just do a linear
	 *    search over the whole set.
	 *  * The set is the one we're currently inserting into; keeping a full
	 *    auxiliary search tree up to date would be too expensive, so we
	 *    use a much simpler lookup table to do a binary search -
	 *    bset_search_write_set().
	 *  * Or we use the auxiliary search tree we constructed earlier -
	 *    bset_search_tree()
	 */

	if (unlikely(!t->size)) {
		i.l = t->data->start;
K
Kent Overstreet 已提交
946
		i.r = bset_bkey_last(t->data);
K
Kent Overstreet 已提交
947 948 949 950 951 952 953 954 955
	} else if (bset_written(b, t)) {
		/*
		 * Each node in the auxiliary search tree covers a certain range
		 * of bits, and keys above and below the set it covers might
		 * differ outside those bits - so we have to special case the
		 * start and end - handle that here:
		 */

		if (unlikely(bkey_cmp(search, &t->end) >= 0))
K
Kent Overstreet 已提交
956
			return bset_bkey_last(t->data);
K
Kent Overstreet 已提交
957 958 959 960 961 962 963 964

		if (unlikely(bkey_cmp(search, t->data->start) < 0))
			return t->data->start;

		i = bset_search_tree(b, t, search);
	} else
		i = bset_search_write_set(b, t, search);

K
Kent Overstreet 已提交
965 966 967 968 969 970
	if (expensive_debug_checks(b->c)) {
		BUG_ON(bset_written(b, t) &&
		       i.l != t->data->start &&
		       bkey_cmp(tree_to_prev_bkey(t,
			  inorder_to_tree(bkey_to_cacheline(t, i.l), t)),
				search) > 0);
K
Kent Overstreet 已提交
971

K
Kent Overstreet 已提交
972
		BUG_ON(i.r != bset_bkey_last(t->data) &&
K
Kent Overstreet 已提交
973 974
		       bkey_cmp(i.r, search) <= 0);
	}
K
Kent Overstreet 已提交
975 976 977 978 979 980 981 982 983 984

	while (likely(i.l != i.r) &&
	       bkey_cmp(i.l, search) <= 0)
		i.l = bkey_next(i.l);

	return i.l;
}

/* Btree iterator */

985 986 987
typedef bool (btree_iter_cmp_fn)(struct btree_iter_set,
				 struct btree_iter_set);

K
Kent Overstreet 已提交
988 989 990
static inline bool btree_iter_cmp(struct btree_iter_set l,
				  struct btree_iter_set r)
{
991
	return bkey_cmp(l.k, r.k) > 0;
K
Kent Overstreet 已提交
992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007
}

static inline bool btree_iter_end(struct btree_iter *iter)
{
	return !iter->used;
}

void bch_btree_iter_push(struct btree_iter *iter, struct bkey *k,
			 struct bkey *end)
{
	if (k != end)
		BUG_ON(!heap_add(iter,
				 ((struct btree_iter_set) { k, end }),
				 btree_iter_cmp));
}

1008 1009 1010 1011
static struct bkey *__bch_btree_iter_init(struct btree *b,
					  struct btree_iter *iter,
					  struct bkey *search,
					  struct bset_tree *start)
K
Kent Overstreet 已提交
1012 1013 1014 1015 1016
{
	struct bkey *ret = NULL;
	iter->size = ARRAY_SIZE(iter->data);
	iter->used = 0;

K
Kent Overstreet 已提交
1017 1018 1019 1020
#ifdef CONFIG_BCACHE_DEBUG
	iter->b = b;
#endif

K
Kent Overstreet 已提交
1021 1022
	for (; start <= &b->sets[b->nsets]; start++) {
		ret = bch_bset_search(b, start, search);
K
Kent Overstreet 已提交
1023
		bch_btree_iter_push(iter, ret, bset_bkey_last(start->data));
K
Kent Overstreet 已提交
1024 1025 1026 1027 1028
	}

	return ret;
}

1029 1030 1031 1032 1033 1034 1035 1036 1037
struct bkey *bch_btree_iter_init(struct btree *b,
				 struct btree_iter *iter,
				 struct bkey *search)
{
	return __bch_btree_iter_init(b, iter, search, b->sets);
}

static inline struct bkey *__bch_btree_iter_next(struct btree_iter *iter,
						 btree_iter_cmp_fn *cmp)
K
Kent Overstreet 已提交
1038 1039 1040 1041 1042
{
	struct btree_iter_set unused;
	struct bkey *ret = NULL;

	if (!btree_iter_end(iter)) {
K
Kent Overstreet 已提交
1043 1044
		bch_btree_iter_next_check(iter);

K
Kent Overstreet 已提交
1045 1046 1047 1048
		ret = iter->data->k;
		iter->data->k = bkey_next(iter->data->k);

		if (iter->data->k > iter->data->end) {
1049
			WARN_ONCE(1, "bset was corrupt!\n");
K
Kent Overstreet 已提交
1050 1051 1052 1053
			iter->data->k = iter->data->end;
		}

		if (iter->data->k == iter->data->end)
1054
			heap_pop(iter, unused, cmp);
K
Kent Overstreet 已提交
1055
		else
1056
			heap_sift(iter, 0, cmp);
K
Kent Overstreet 已提交
1057 1058 1059 1060 1061
	}

	return ret;
}

1062 1063 1064 1065 1066 1067
struct bkey *bch_btree_iter_next(struct btree_iter *iter)
{
	return __bch_btree_iter_next(iter, btree_iter_cmp);

}

K
Kent Overstreet 已提交
1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081
struct bkey *bch_btree_iter_next_filter(struct btree_iter *iter,
					struct btree *b, ptr_filter_fn fn)
{
	struct bkey *ret;

	do {
		ret = bch_btree_iter_next(iter);
	} while (ret && fn(b, ret));

	return ret;
}

/* Mergesort */

1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101
void bch_bset_sort_state_free(struct bset_sort_state *state)
{
	if (state->pool)
		mempool_destroy(state->pool);
}

int bch_bset_sort_state_init(struct bset_sort_state *state, unsigned page_order)
{
	spin_lock_init(&state->time.lock);

	state->page_order = page_order;
	state->crit_factor = int_sqrt(1 << page_order);

	state->pool = mempool_create_page_pool(1, page_order);
	if (!state->pool)
		return -ENOMEM;

	return 0;
}

1102 1103 1104 1105 1106 1107 1108 1109 1110
static void sort_key_next(struct btree_iter *iter,
			  struct btree_iter_set *i)
{
	i->k = bkey_next(i->k);

	if (i->k == i->end)
		*i = iter->data[--iter->used];
}

1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135
/*
 * Returns true if l > r - unless l == r, in which case returns true if l is
 * older than r.
 *
 * Necessary for btree_sort_fixup() - if there are multiple keys that compare
 * equal in different sets, we have to process them newest to oldest.
 */
static inline bool sort_extent_cmp(struct btree_iter_set l,
				   struct btree_iter_set r)
{
	int64_t c = bkey_cmp(&START_KEY(l.k), &START_KEY(r.k));

	return c ? c > 0 : l.k < r.k;
}

static inline bool sort_cmp(struct btree_iter_set l,
			    struct btree_iter_set r)
{
	int64_t c = bkey_cmp(l.k, r.k);

	return c ? c > 0 : l.k < r.k;
}

static struct bkey *btree_sort_fixup_extents(struct btree_iter *iter,
					     struct bkey *tmp)
K
Kent Overstreet 已提交
1136 1137 1138 1139 1140
{
	while (iter->used > 1) {
		struct btree_iter_set *top = iter->data, *i = top + 1;

		if (iter->used > 2 &&
1141
		    sort_extent_cmp(i[0], i[1]))
K
Kent Overstreet 已提交
1142 1143
			i++;

1144
		if (bkey_cmp(top->k, &START_KEY(i->k)) <= 0)
K
Kent Overstreet 已提交
1145 1146
			break;

1147 1148
		if (!KEY_SIZE(i->k)) {
			sort_key_next(iter, i);
1149
			heap_sift(iter, i - top, sort_extent_cmp);
1150 1151 1152 1153 1154 1155 1156 1157 1158
			continue;
		}

		if (top->k > i->k) {
			if (bkey_cmp(top->k, i->k) >= 0)
				sort_key_next(iter, i);
			else
				bch_cut_front(top->k, i->k);

1159
			heap_sift(iter, i - top, sort_extent_cmp);
1160 1161 1162
		} else {
			/* can't happen because of comparison func */
			BUG_ON(!bkey_cmp(&START_KEY(top->k), &START_KEY(i->k)));
K
Kent Overstreet 已提交
1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174

			if (bkey_cmp(i->k, top->k) < 0) {
				bkey_copy(tmp, top->k);

				bch_cut_back(&START_KEY(i->k), tmp);
				bch_cut_front(i->k, top->k);
				heap_sift(iter, 0, btree_iter_cmp);

				return tmp;
			} else {
				bch_cut_back(&START_KEY(i->k), top->k);
			}
1175
		}
K
Kent Overstreet 已提交
1176
	}
K
Kent Overstreet 已提交
1177 1178

	return NULL;
K
Kent Overstreet 已提交
1179 1180 1181 1182 1183 1184
}

static void btree_mergesort(struct btree *b, struct bset *out,
			    struct btree_iter *iter,
			    bool fixup, bool remove_stale)
{
1185
	int i;
K
Kent Overstreet 已提交
1186
	struct bkey *k, *last = NULL;
K
Kent Overstreet 已提交
1187
	BKEY_PADDED(k) tmp;
1188 1189 1190
	btree_iter_cmp_fn *cmp = b->level
		? sort_cmp
		: sort_extent_cmp;
K
Kent Overstreet 已提交
1191 1192 1193 1194
	bool (*bad)(struct btree *, const struct bkey *) = remove_stale
		? bch_ptr_bad
		: bch_ptr_invalid;

1195 1196 1197 1198
	/* Heapify the iterator, using our comparison function */
	for (i = iter->used / 2 - 1; i >= 0; --i)
		heap_sift(iter, i, cmp);

K
Kent Overstreet 已提交
1199 1200
	while (!btree_iter_end(iter)) {
		if (fixup && !b->level)
1201
			k = btree_sort_fixup_extents(iter, &tmp.k);
K
Kent Overstreet 已提交
1202 1203 1204 1205
		else
			k = NULL;

		if (!k)
1206
			k = __bch_btree_iter_next(iter, cmp);
K
Kent Overstreet 已提交
1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226

		if (bad(b, k))
			continue;

		if (!last) {
			last = out->start;
			bkey_copy(last, k);
		} else if (b->level ||
			   !bch_bkey_try_merge(b, last, k)) {
			last = bkey_next(last);
			bkey_copy(last, k);
		}
	}

	out->keys = last ? (uint64_t *) bkey_next(last) - out->d : 0;

	pr_debug("sorted %i keys", out->keys);
}

static void __btree_sort(struct btree *b, struct btree_iter *iter,
1227 1228
			 unsigned start, unsigned order, bool fixup,
			 struct bset_sort_state *state)
K
Kent Overstreet 已提交
1229 1230
{
	uint64_t start_time;
1231
	bool used_mempool = false;
K
Kent Overstreet 已提交
1232 1233 1234
	struct bset *out = (void *) __get_free_pages(__GFP_NOWARN|GFP_NOIO,
						     order);
	if (!out) {
1235 1236 1237
		BUG_ON(order > state->page_order);

		out = page_address(mempool_alloc(state->pool, GFP_NOIO));
1238
		used_mempool = true;
K
Kent Overstreet 已提交
1239 1240 1241 1242 1243
		order = ilog2(bucket_pages(b->c));
	}

	start_time = local_clock();

1244
	btree_mergesort(b, out, iter, fixup, false);
K
Kent Overstreet 已提交
1245 1246 1247 1248 1249 1250 1251 1252 1253
	b->nsets = start;

	if (!start && order == b->page_order) {
		/*
		 * Our temporary buffer is the same size as the btree node's
		 * buffer, we can just swap buffers instead of doing a big
		 * memcpy()
		 */

1254
		out->magic	= bset_magic(&b->c->sb);
K
Kent Overstreet 已提交
1255 1256 1257 1258 1259 1260
		out->seq	= b->sets[0].data->seq;
		out->version	= b->sets[0].data->version;
		swap(out, b->sets[0].data);
	} else {
		b->sets[start].data->keys = out->keys;
		memcpy(b->sets[start].data->start, out->start,
K
Kent Overstreet 已提交
1261
		       (void *) bset_bkey_last(out) - (void *) out->start);
K
Kent Overstreet 已提交
1262 1263
	}

1264
	if (used_mempool)
1265
		mempool_free(virt_to_page(out), state->pool);
K
Kent Overstreet 已提交
1266 1267 1268
	else
		free_pages((unsigned long) out, order);

1269
	bset_build_written_tree(b);
K
Kent Overstreet 已提交
1270

1271
	if (!start)
1272
		bch_time_stats_update(&state->time, start_time);
K
Kent Overstreet 已提交
1273 1274
}

1275 1276
void bch_btree_sort_partial(struct btree *b, unsigned start,
			    struct bset_sort_state *state)
K
Kent Overstreet 已提交
1277
{
K
Kent Overstreet 已提交
1278
	size_t order = b->page_order, keys = 0;
K
Kent Overstreet 已提交
1279
	struct btree_iter iter;
K
Kent Overstreet 已提交
1280 1281
	int oldsize = bch_count_data(b);

K
Kent Overstreet 已提交
1282 1283
	__bch_btree_iter_init(b, &iter, NULL, &b->sets[start]);

1284 1285
	BUG_ON(!bset_written(b, bset_tree_last(b)) &&
	       (bset_tree_last(b)->size || b->nsets));
K
Kent Overstreet 已提交
1286 1287 1288 1289 1290 1291 1292

	if (start) {
		unsigned i;

		for (i = start; i <= b->nsets; i++)
			keys += b->sets[i].data->keys;

K
Kent Overstreet 已提交
1293 1294
		order = roundup_pow_of_two(__set_bytes(b->sets->data,
						       keys)) / PAGE_SIZE;
K
Kent Overstreet 已提交
1295 1296 1297 1298
		if (order)
			order = ilog2(order);
	}

1299
	__btree_sort(b, &iter, start, order, false, state);
K
Kent Overstreet 已提交
1300

K
Kent Overstreet 已提交
1301
	EBUG_ON(b->written && oldsize >= 0 && bch_count_data(b) != oldsize);
K
Kent Overstreet 已提交
1302 1303
}

1304 1305
void bch_btree_sort_and_fix_extents(struct btree *b, struct btree_iter *iter,
				    struct bset_sort_state *state)
K
Kent Overstreet 已提交
1306
{
1307
	__btree_sort(b, iter, 0, b->page_order, true, state);
K
Kent Overstreet 已提交
1308 1309
}

1310 1311
void bch_btree_sort_into(struct btree *b, struct btree *new,
			 struct bset_sort_state *state)
K
Kent Overstreet 已提交
1312 1313 1314 1315 1316 1317 1318 1319
{
	uint64_t start_time = local_clock();

	struct btree_iter iter;
	bch_btree_iter_init(b, &iter, NULL);

	btree_mergesort(b, new->sets->data, &iter, false, true);

1320
	bch_time_stats_update(&state->time, start_time);
K
Kent Overstreet 已提交
1321 1322 1323 1324

	new->sets->size = 0;
}

K
Kent Overstreet 已提交
1325 1326
#define SORT_CRIT	(4096 / sizeof(uint64_t))

1327
void bch_btree_sort_lazy(struct btree *b, struct bset_sort_state *state)
K
Kent Overstreet 已提交
1328
{
K
Kent Overstreet 已提交
1329 1330
	unsigned crit = SORT_CRIT;
	int i;
K
Kent Overstreet 已提交
1331

K
Kent Overstreet 已提交
1332 1333 1334
	/* Don't sort if nothing to do */
	if (!b->nsets)
		goto out;
K
Kent Overstreet 已提交
1335

K
Kent Overstreet 已提交
1336
	for (i = b->nsets - 1; i >= 0; --i) {
1337
		crit *= state->crit_factor;
K
Kent Overstreet 已提交
1338

K
Kent Overstreet 已提交
1339
		if (b->sets[i].data->keys < crit) {
1340
			bch_btree_sort_partial(b, i, state);
K
Kent Overstreet 已提交
1341 1342 1343 1344
			return;
		}
	}

K
Kent Overstreet 已提交
1345 1346
	/* Sort if we'd overflow */
	if (b->nsets + 1 == MAX_BSETS) {
1347
		bch_btree_sort(b, state);
K
Kent Overstreet 已提交
1348 1349 1350 1351
		return;
	}

out:
K
Kent Overstreet 已提交
1352 1353 1354 1355 1356 1357
	bset_build_written_tree(b);
}

/* Sysfs stuff */

struct bset_stats {
1358
	struct btree_op op;
K
Kent Overstreet 已提交
1359 1360 1361 1362 1363 1364
	size_t nodes;
	size_t sets_written, sets_unwritten;
	size_t bytes_written, bytes_unwritten;
	size_t floats, failed;
};

1365
static int btree_bset_stats(struct btree_op *op, struct btree *b)
K
Kent Overstreet 已提交
1366
{
1367
	struct bset_stats *stats = container_of(op, struct bset_stats, op);
K
Kent Overstreet 已提交
1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391
	unsigned i;

	stats->nodes++;

	for (i = 0; i <= b->nsets; i++) {
		struct bset_tree *t = &b->sets[i];
		size_t bytes = t->data->keys * sizeof(uint64_t);
		size_t j;

		if (bset_written(b, t)) {
			stats->sets_written++;
			stats->bytes_written += bytes;

			stats->floats += t->size - 1;

			for (j = 1; j < t->size; j++)
				if (t->tree[j].exponent == 127)
					stats->failed++;
		} else {
			stats->sets_unwritten++;
			stats->bytes_unwritten += bytes;
		}
	}

1392
	return MAP_CONTINUE;
K
Kent Overstreet 已提交
1393 1394 1395 1396 1397 1398 1399 1400
}

int bch_bset_print_stats(struct cache_set *c, char *buf)
{
	struct bset_stats t;
	int ret;

	memset(&t, 0, sizeof(struct bset_stats));
K
Kent Overstreet 已提交
1401
	bch_btree_op_init(&t.op, -1);
K
Kent Overstreet 已提交
1402

1403 1404
	ret = bch_btree_map_nodes(&t.op, c, &ZERO_KEY, btree_bset_stats);
	if (ret < 0)
K
Kent Overstreet 已提交
1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419
		return ret;

	return snprintf(buf, PAGE_SIZE,
			"btree nodes:		%zu\n"
			"written sets:		%zu\n"
			"unwritten sets:		%zu\n"
			"written key bytes:	%zu\n"
			"unwritten key bytes:	%zu\n"
			"floats:			%zu\n"
			"failed:			%zu\n",
			t.nodes,
			t.sets_written, t.sets_unwritten,
			t.bytes_written, t.bytes_unwritten,
			t.floats, t.failed);
}