alloc_background.c 34.5 KB
Newer Older
1
// SPDX-License-Identifier: GPL-2.0
2
#include "bcachefs.h"
3 4
#include "alloc_background.h"
#include "alloc_foreground.h"
5 6
#include "btree_cache.h"
#include "btree_io.h"
7
#include "btree_key_cache.h"
8 9 10 11
#include "btree_update.h"
#include "btree_update_interior.h"
#include "btree_gc.h"
#include "buckets.h"
12
#include "buckets_waiting_for_journal.h"
13 14
#include "clock.h"
#include "debug.h"
15
#include "ec.h"
16
#include "error.h"
17
#include "lru.h"
18
#include "recovery.h"
19
#include "trace.h"
20
#include "varint.h"
21 22 23 24 25 26 27 28 29

#include <linux/kthread.h>
#include <linux/math64.h>
#include <linux/random.h>
#include <linux/rculist.h>
#include <linux/rcupdate.h>
#include <linux/sched/task.h>
#include <linux/sort.h>

30 31
/* Persistent alloc info: */

32 33 34
static const unsigned BCH_ALLOC_V1_FIELD_BYTES[] = {
#define x(name, bits) [BCH_ALLOC_FIELD_V1_##name] = bits / 8,
	BCH_ALLOC_FIELDS_V1()
35 36 37
#undef x
};

38 39 40 41 42 43 44 45 46 47 48 49 50
struct bkey_alloc_unpacked {
	u64		journal_seq;
	u64		bucket;
	u8		dev;
	u8		gen;
	u8		oldest_gen;
	u8		data_type;
	bool		need_discard:1;
	bool		need_inc_gen:1;
#define x(_name, _bits)	u##_bits _name;
	BCH_ALLOC_FIELDS_V2()
#undef  x
};
51

52 53
static inline u64 alloc_field_v1_get(const struct bch_alloc *a,
				     const void **p, unsigned field)
54
{
55
	unsigned bytes = BCH_ALLOC_V1_FIELD_BYTES[field];
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
	u64 v;

	if (!(a->fields & (1 << field)))
		return 0;

	switch (bytes) {
	case 1:
		v = *((const u8 *) *p);
		break;
	case 2:
		v = le16_to_cpup(*p);
		break;
	case 4:
		v = le32_to_cpup(*p);
		break;
	case 8:
		v = le64_to_cpup(*p);
		break;
	default:
		BUG();
	}

	*p += bytes;
	return v;
}

82 83
static inline void alloc_field_v1_put(struct bkey_i_alloc *a, void **p,
				      unsigned field, u64 v)
84
{
85
	unsigned bytes = BCH_ALLOC_V1_FIELD_BYTES[field];
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

	if (!v)
		return;

	a->v.fields |= 1 << field;

	switch (bytes) {
	case 1:
		*((u8 *) *p) = v;
		break;
	case 2:
		*((__le16 *) *p) = cpu_to_le16(v);
		break;
	case 4:
		*((__le32 *) *p) = cpu_to_le32(v);
		break;
	case 8:
		*((__le64 *) *p) = cpu_to_le64(v);
		break;
	default:
		BUG();
	}

	*p += bytes;
}

112 113
static void bch2_alloc_unpack_v1(struct bkey_alloc_unpacked *out,
				 struct bkey_s_c k)
114
{
115 116 117
	const struct bch_alloc *in = bkey_s_c_to_alloc(k).v;
	const void *d = in->data;
	unsigned idx = 0;
118

119 120 121 122 123 124 125 126 127
	out->gen = in->gen;

#define x(_name, _bits) out->_name = alloc_field_v1_get(in, &d, idx++);
	BCH_ALLOC_FIELDS_V1()
#undef  x
}

static int bch2_alloc_unpack_v2(struct bkey_alloc_unpacked *out,
				struct bkey_s_c k)
128
{
129 130 131 132 133 134 135 136 137 138 139 140 141
	struct bkey_s_c_alloc_v2 a = bkey_s_c_to_alloc_v2(k);
	const u8 *in = a.v->data;
	const u8 *end = bkey_val_end(a);
	unsigned fieldnr = 0;
	int ret;
	u64 v;

	out->gen	= a.v->gen;
	out->oldest_gen	= a.v->oldest_gen;
	out->data_type	= a.v->data_type;

#define x(_name, _bits)							\
	if (fieldnr < a.v->nr_fields) {					\
142
		ret = bch2_varint_decode_fast(in, end, &v);		\
143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158
		if (ret < 0)						\
			return ret;					\
		in += ret;						\
	} else {							\
		v = 0;							\
	}								\
	out->_name = v;							\
	if (v != out->_name)						\
		return -1;						\
	fieldnr++;

	BCH_ALLOC_FIELDS_V2()
#undef  x
	return 0;
}

159 160 161 162 163 164 165 166 167 168 169 170 171
static int bch2_alloc_unpack_v3(struct bkey_alloc_unpacked *out,
				struct bkey_s_c k)
{
	struct bkey_s_c_alloc_v3 a = bkey_s_c_to_alloc_v3(k);
	const u8 *in = a.v->data;
	const u8 *end = bkey_val_end(a);
	unsigned fieldnr = 0;
	int ret;
	u64 v;

	out->gen	= a.v->gen;
	out->oldest_gen	= a.v->oldest_gen;
	out->data_type	= a.v->data_type;
172 173
	out->need_discard = BCH_ALLOC_V3_NEED_DISCARD(a.v);
	out->need_inc_gen = BCH_ALLOC_V3_NEED_INC_GEN(a.v);
174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194
	out->journal_seq = le64_to_cpu(a.v->journal_seq);

#define x(_name, _bits)							\
	if (fieldnr < a.v->nr_fields) {					\
		ret = bch2_varint_decode_fast(in, end, &v);		\
		if (ret < 0)						\
			return ret;					\
		in += ret;						\
	} else {							\
		v = 0;							\
	}								\
	out->_name = v;							\
	if (v != out->_name)						\
		return -1;						\
	fieldnr++;

	BCH_ALLOC_FIELDS_V2()
#undef  x
	return 0;
}

195
static struct bkey_alloc_unpacked bch2_alloc_unpack(struct bkey_s_c k)
196 197 198 199 200 201
{
	struct bkey_alloc_unpacked ret = {
		.dev	= k.k->p.inode,
		.bucket	= k.k->p.offset,
		.gen	= 0,
	};
202

203 204
	switch (k.k->type) {
	case KEY_TYPE_alloc:
205
		bch2_alloc_unpack_v1(&ret, k);
206 207 208 209 210 211 212 213
		break;
	case KEY_TYPE_alloc_v2:
		bch2_alloc_unpack_v2(&ret, k);
		break;
	case KEY_TYPE_alloc_v3:
		bch2_alloc_unpack_v3(&ret, k);
		break;
	}
214 215 216 217

	return ret;
}

218
void bch2_alloc_to_v4(struct bkey_s_c k, struct bch_alloc_v4 *out)
219
{
220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239
	if (k.k->type == KEY_TYPE_alloc_v4) {
		*out = *bkey_s_c_to_alloc_v4(k).v;
	} else {
		struct bkey_alloc_unpacked u = bch2_alloc_unpack(k);

		*out = (struct bch_alloc_v4) {
			.journal_seq		= u.journal_seq,
			.flags			= u.need_discard,
			.gen			= u.gen,
			.oldest_gen		= u.oldest_gen,
			.data_type		= u.data_type,
			.stripe_redundancy	= u.stripe_redundancy,
			.dirty_sectors		= u.dirty_sectors,
			.cached_sectors		= u.cached_sectors,
			.io_time[READ]		= u.read_time,
			.io_time[WRITE]		= u.write_time,
			.stripe			= u.stripe,
		};
	}
}
240

241 242 243
struct bkey_i_alloc_v4 *bch2_alloc_to_v4_mut(struct btree_trans *trans, struct bkey_s_c k)
{
	struct bkey_i_alloc_v4 *ret;
244

245 246 247 248 249 250 251 252 253 254 255 256 257
	if (k.k->type == KEY_TYPE_alloc_v4) {
		ret = bch2_trans_kmalloc(trans, bkey_bytes(k.k));
		if (!IS_ERR(ret))
			bkey_reassemble(&ret->k_i, k);
	} else {
		ret = bch2_trans_kmalloc(trans, sizeof(*ret));
		if (!IS_ERR(ret)) {
			bkey_alloc_v4_init(&ret->k_i);
			ret->k.p = k.k->p;
			bch2_alloc_to_v4(k, &ret->v);
		}
	}
	return ret;
258 259
}

260 261 262
struct bkey_i_alloc_v4 *
bch2_trans_start_alloc_update(struct btree_trans *trans, struct btree_iter *iter,
			      struct bpos pos)
263
{
264 265 266
	struct bkey_s_c k;
	struct bkey_i_alloc_v4 *a;
	int ret;
267

268 269 270 271 272 273 274 275 276 277 278 279 280 281 282
	bch2_trans_iter_init(trans, iter, BTREE_ID_alloc, pos,
			     BTREE_ITER_WITH_UPDATES|
			     BTREE_ITER_CACHED|
			     BTREE_ITER_INTENT);
	k = bch2_btree_iter_peek_slot(iter);
	ret = bkey_err(k);
	if (ret) {
		bch2_trans_iter_exit(trans, iter);
		return ERR_PTR(ret);
	}

	a = bch2_alloc_to_v4_mut(trans, k);
	if (IS_ERR(a))
		bch2_trans_iter_exit(trans, iter);
	return a;
283 284
}

285
static unsigned bch_alloc_v1_val_u64s(const struct bch_alloc *a)
286
{
287
	unsigned i, bytes = offsetof(struct bch_alloc, data);
288

289
	for (i = 0; i < ARRAY_SIZE(BCH_ALLOC_V1_FIELD_BYTES); i++)
290
		if (a->fields & (1 << i))
291
			bytes += BCH_ALLOC_V1_FIELD_BYTES[i];
292 293 294 295

	return DIV_ROUND_UP(bytes, sizeof(u64));
}

296 297
int bch2_alloc_v1_invalid(const struct bch_fs *c, struct bkey_s_c k,
			  int rw, struct printbuf *err)
298
{
299 300 301
	struct bkey_s_c_alloc a = bkey_s_c_to_alloc(k);

	/* allow for unknown fields */
302 303 304 305 306
	if (bkey_val_u64s(a.k) < bch_alloc_v1_val_u64s(a.v)) {
		pr_buf(err, "incorrect value size (%zu < %u)",
		       bkey_val_u64s(a.k), bch_alloc_v1_val_u64s(a.v));
		return -EINVAL;
	}
307

308
	return 0;
309 310
}

311 312
int bch2_alloc_v2_invalid(const struct bch_fs *c, struct bkey_s_c k,
			  int rw, struct printbuf *err)
313
{
314 315
	struct bkey_alloc_unpacked u;

316 317 318 319
	if (bch2_alloc_unpack_v2(&u, k)) {
		pr_buf(err, "unpack error");
		return -EINVAL;
	}
320

321
	return 0;
322 323
}

324 325
int bch2_alloc_v3_invalid(const struct bch_fs *c, struct bkey_s_c k,
			  int rw, struct printbuf *err)
326 327
{
	struct bkey_alloc_unpacked u;
328

329 330 331 332
	if (bch2_alloc_unpack_v3(&u, k)) {
		pr_buf(err, "unpack error");
		return -EINVAL;
	}
333

334
	return 0;
335 336
}

337 338
int bch2_alloc_v4_invalid(const struct bch_fs *c, struct bkey_s_c k,
			  int rw, struct printbuf *err)
339
{
340 341
	struct bkey_s_c_alloc_v4 a = bkey_s_c_to_alloc_v4(k);

342 343 344
	if (bkey_val_bytes(k.k) != sizeof(struct bch_alloc_v4)) {
		pr_buf(err, "bad val size (%zu != %zu)",
		       bkey_val_bytes(k.k), sizeof(struct bch_alloc_v4));
345 346
		return -EINVAL;
	}
347

348
	if (rw == WRITE) {
349 350 351
		if (alloc_data_type(*a.v, a.v->data_type) != a.v->data_type) {
			pr_buf(err, "invalid data type (got %u should be %u)",
			       a.v->data_type, alloc_data_type(*a.v, a.v->data_type));
352 353
			return -EINVAL;
		}
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
		switch (a.v->data_type) {
		case BCH_DATA_free:
		case BCH_DATA_need_gc_gens:
		case BCH_DATA_need_discard:
			if (a.v->dirty_sectors ||
			    a.v->cached_sectors ||
			    a.v->stripe) {
				pr_buf(err, "empty data type free but have data");
				return -EINVAL;
			}
			break;
		case BCH_DATA_sb:
		case BCH_DATA_journal:
		case BCH_DATA_btree:
		case BCH_DATA_user:
		case BCH_DATA_parity:
			if (!a.v->dirty_sectors) {
				pr_buf(err, "data_type %s but dirty_sectors==0",
				       bch2_data_types[a.v->data_type]);
				return -EINVAL;
			}
			break;
		case BCH_DATA_cached:
			if (!a.v->cached_sectors ||
			    a.v->dirty_sectors ||
			    a.v->stripe) {
				pr_buf(err, "data type inconsistency");
				return -EINVAL;
			}

			if (!a.v->io_time[READ]) {
				pr_buf(err, "cached bucket with read_time == 0");
				return -EINVAL;
			}
			break;
		case BCH_DATA_stripe:
			if (!a.v->stripe) {
				pr_buf(err, "data_type %s but stripe==0",
				       bch2_data_types[a.v->data_type]);
				return -EINVAL;
			}
			break;
397
		}
398 399
	}

400
	return 0;
401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422
}

void bch2_alloc_v4_swab(struct bkey_s k)
{
	struct bch_alloc_v4 *a = bkey_s_to_alloc_v4(k).v;

	a->journal_seq		= swab64(a->journal_seq);
	a->flags		= swab32(a->flags);
	a->dirty_sectors	= swab32(a->dirty_sectors);
	a->cached_sectors	= swab32(a->cached_sectors);
	a->io_time[0]		= swab64(a->io_time[0]);
	a->io_time[1]		= swab64(a->io_time[1]);
	a->stripe		= swab32(a->stripe);
	a->nr_external_backpointers = swab32(a->nr_external_backpointers);
}

void bch2_alloc_to_text(struct printbuf *out, struct bch_fs *c, struct bkey_s_c k)
{
	struct bch_alloc_v4 a;

	bch2_alloc_to_v4(k, &a);

423
	pr_buf(out, "gen %u oldest_gen %u data_type %s journal_seq %llu need_discard %llu need_inc_gen %llu",
424
	       a.gen, a.oldest_gen, bch2_data_types[a.data_type],
425 426 427
	       a.journal_seq,
	       BCH_ALLOC_V4_NEED_DISCARD(&a),
	       BCH_ALLOC_V4_NEED_INC_GEN(&a));
428 429 430 431 432 433
	pr_buf(out, " dirty_sectors %u",	a.dirty_sectors);
	pr_buf(out, " cached_sectors %u",	a.cached_sectors);
	pr_buf(out, " stripe %u",		a.stripe);
	pr_buf(out, " stripe_redundancy %u",	a.stripe_redundancy);
	pr_buf(out, " read_time %llu",		a.io_time[READ]);
	pr_buf(out, " write_time %llu",		a.io_time[WRITE]);
434 435
}

436
int bch2_alloc_read(struct bch_fs *c)
437
{
438 439 440
	struct btree_trans trans;
	struct btree_iter iter;
	struct bkey_s_c k;
441
	struct bch_alloc_v4 a;
442
	struct bch_dev *ca;
443
	int ret;
444

445
	bch2_trans_init(&trans, c, 0, 0);
446 447 448

	for_each_btree_key(&trans, iter, BTREE_ID_alloc, POS_MIN,
			   BTREE_ITER_PREFETCH, k, ret) {
449 450 451 452 453 454 455
		/*
		 * Not a fsck error because this is checked/repaired by
		 * bch2_check_alloc_key() which runs later:
		 */
		if (!bch2_dev_bucket_exists(c, k.k->p))
			continue;

456
		ca = bch_dev_bkey_exists(c, k.k->p.inode);
457
		bch2_alloc_to_v4(k, &a);
458

459
		*bucket_gen(ca, k.k->p.offset) = a.gen;
460
	}
461
	bch2_trans_iter_exit(&trans, &iter);
462

463
	bch2_trans_exit(&trans);
464

465
	if (ret)
466
		bch_err(c, "error reading alloc info: %i", ret);
467

468
	return ret;
469 470
}

471 472 473 474
/* Free space/discard btree: */

static int bch2_bucket_do_index(struct btree_trans *trans,
				struct bkey_s_c alloc_k,
475
				const struct bch_alloc_v4 *a,
476 477 478 479 480 481 482 483 484 485 486 487 488
				bool set)
{
	struct bch_fs *c = trans->c;
	struct bch_dev *ca = bch_dev_bkey_exists(c, alloc_k.k->p.inode);
	struct btree_iter iter;
	struct bkey_s_c old;
	struct bkey_i *k;
	enum btree_id btree;
	enum bch_bkey_type old_type = !set ? KEY_TYPE_set : KEY_TYPE_deleted;
	enum bch_bkey_type new_type =  set ? KEY_TYPE_set : KEY_TYPE_deleted;
	struct printbuf buf = PRINTBUF;
	int ret;

489 490
	if (a->data_type != BCH_DATA_free &&
	    a->data_type != BCH_DATA_need_discard)
491 492 493 494 495 496 497 498 499
		return 0;

	k = bch2_trans_kmalloc(trans, sizeof(*k));
	if (IS_ERR(k))
		return PTR_ERR(k);

	bkey_init(&k->k);
	k->k.type = new_type;

500 501
	switch (a->data_type) {
	case BCH_DATA_free:
502
		btree = BTREE_ID_freespace;
503
		k->k.p = alloc_freespace_pos(alloc_k.k->p, *a);
504 505
		bch2_key_resize(&k->k, 1);
		break;
506
	case BCH_DATA_need_discard:
507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522
		btree = BTREE_ID_need_discard;
		k->k.p = alloc_k.k->p;
		break;
	default:
		return 0;
	}

	bch2_trans_iter_init(trans, &iter, btree,
			     bkey_start_pos(&k->k),
			     BTREE_ITER_INTENT);
	old = bch2_btree_iter_peek_slot(&iter);
	ret = bkey_err(old);
	if (ret)
		goto err;

	if (ca->mi.freespace_initialized &&
523
	    bch2_trans_inconsistent_on(old.k->type != old_type, trans,
524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542
			"incorrect key when %s %s btree (got %s should be %s)\n"
			"  for %s",
			set ? "setting" : "clearing",
			bch2_btree_ids[btree],
			bch2_bkey_types[old.k->type],
			bch2_bkey_types[old_type],
			(bch2_bkey_val_to_text(&buf, c, alloc_k), buf.buf))) {
		ret = -EIO;
		goto err;
	}

	ret = bch2_trans_update(trans, &iter, k, 0);
err:
	bch2_trans_iter_exit(trans, &iter);
	printbuf_exit(&buf);
	return ret;
}

int bch2_trans_mark_alloc(struct btree_trans *trans,
543
			  enum btree_id btree_id, unsigned level,
544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560
			  struct bkey_s_c old, struct bkey_i *new,
			  unsigned flags)
{
	struct bch_fs *c = trans->c;
	struct bch_alloc_v4 old_a, *new_a;
	u64 old_lru, new_lru;
	int ret = 0;

	/*
	 * Deletion only happens in the device removal path, with
	 * BTREE_TRIGGER_NORUN:
	 */
	BUG_ON(new->k.type != KEY_TYPE_alloc_v4);

	bch2_alloc_to_v4(old, &old_a);
	new_a = &bkey_i_to_alloc_v4(new)->v;

561 562
	new_a->data_type = alloc_data_type(*new_a, new_a->data_type);

563 564 565 566 567
	if (new_a->dirty_sectors > old_a.dirty_sectors ||
	    new_a->cached_sectors > old_a.cached_sectors) {
		new_a->io_time[READ] = max_t(u64, 1, atomic64_read(&c->io_clock[READ].now));
		new_a->io_time[WRITE]= max_t(u64, 1, atomic64_read(&c->io_clock[WRITE].now));
		SET_BCH_ALLOC_V4_NEED_INC_GEN(new_a, true);
568
		SET_BCH_ALLOC_V4_NEED_DISCARD(new_a, true);
569 570
	}

571 572
	if (data_type_is_empty(new_a->data_type) &&
	    BCH_ALLOC_V4_NEED_INC_GEN(new_a) &&
573 574 575 576 577
	    !bch2_bucket_is_open_safe(c, new->k.p.inode, new->k.p.offset)) {
		new_a->gen++;
		SET_BCH_ALLOC_V4_NEED_INC_GEN(new_a, false);
	}

578 579
	if (old_a.data_type != new_a->data_type ||
	    (new_a->data_type == BCH_DATA_free &&
580
	     alloc_freespace_genbits(old_a) != alloc_freespace_genbits(*new_a))) {
581 582
		ret =   bch2_bucket_do_index(trans, old, &old_a, false) ?:
			bch2_bucket_do_index(trans, bkey_i_to_s_c(new), new_a, true);
583 584 585 586
		if (ret)
			return ret;
	}

587 588 589 590 591
	if (new_a->data_type == BCH_DATA_cached &&
	    !new_a->io_time[READ])
		new_a->io_time[READ] = max_t(u64, 1, atomic64_read(&c->io_clock[READ].now));


592 593 594 595 596
	old_lru = alloc_lru_idx(old_a);
	new_lru = alloc_lru_idx(*new_a);

	if (old_lru != new_lru) {
		ret = bch2_lru_change(trans, new->k.p.inode, new->k.p.offset,
597
				      old_lru, &new_lru, old);
598 599 600
		if (ret)
			return ret;

601
		if (new_a->data_type == BCH_DATA_cached)
602 603 604 605 606 607
			new_a->io_time[READ] = new_lru;
	}

	return 0;
}

608 609 610 611
static int bch2_check_alloc_key(struct btree_trans *trans,
				struct btree_iter *alloc_iter)
{
	struct bch_fs *c = trans->c;
612
	struct bch_dev *ca;
613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628
	struct btree_iter discard_iter, freespace_iter;
	struct bch_alloc_v4 a;
	unsigned discard_key_type, freespace_key_type;
	struct bkey_s_c alloc_k, k;
	struct printbuf buf = PRINTBUF;
	struct printbuf buf2 = PRINTBUF;
	int ret;

	alloc_k = bch2_btree_iter_peek(alloc_iter);
	if (!alloc_k.k)
		return 0;

	ret = bkey_err(alloc_k);
	if (ret)
		return ret;

629
	if (fsck_err_on(!bch2_dev_bucket_exists(c, alloc_k.k->p), c,
630 631
			"alloc key for invalid device:bucket %llu:%llu",
			alloc_k.k->p.inode, alloc_k.k->p.offset))
632 633 634 635 636 637
		return bch2_btree_delete_at(trans, alloc_iter, 0);

	ca = bch_dev_bkey_exists(c, alloc_k.k->p.inode);
	if (!ca->mi.freespace_initialized)
		return 0;

638
	bch2_alloc_to_v4(alloc_k, &a);
639

640
	discard_key_type = a.data_type == BCH_DATA_need_discard
641
		? KEY_TYPE_set : 0;
642
	freespace_key_type = a.data_type == BCH_DATA_free
643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713
		? KEY_TYPE_set : 0;

	bch2_trans_iter_init(trans, &discard_iter, BTREE_ID_need_discard,
			     alloc_k.k->p, 0);
	bch2_trans_iter_init(trans, &freespace_iter, BTREE_ID_freespace,
			     alloc_freespace_pos(alloc_k.k->p, a), 0);

	k = bch2_btree_iter_peek_slot(&discard_iter);
	ret = bkey_err(k);
	if (ret)
		goto err;

	if (fsck_err_on(k.k->type != discard_key_type, c,
			"incorrect key in need_discard btree (got %s should be %s)\n"
			"  %s",
			bch2_bkey_types[k.k->type],
			bch2_bkey_types[discard_key_type],
			(bch2_bkey_val_to_text(&buf, c, alloc_k), buf.buf))) {
		struct bkey_i *update =
			bch2_trans_kmalloc(trans, sizeof(*update));

		ret = PTR_ERR_OR_ZERO(update);
		if (ret)
			goto err;

		bkey_init(&update->k);
		update->k.type	= discard_key_type;
		update->k.p	= discard_iter.pos;

		ret = bch2_trans_update(trans, &discard_iter, update, 0);
		if (ret)
			goto err;
	}

	k = bch2_btree_iter_peek_slot(&freespace_iter);
	ret = bkey_err(k);
	if (ret)
		goto err;

	if (fsck_err_on(k.k->type != freespace_key_type, c,
			"incorrect key in freespace btree (got %s should be %s)\n"
			"  %s",
			bch2_bkey_types[k.k->type],
			bch2_bkey_types[freespace_key_type],
			(printbuf_reset(&buf),
			 bch2_bkey_val_to_text(&buf, c, alloc_k), buf.buf))) {
		struct bkey_i *update =
			bch2_trans_kmalloc(trans, sizeof(*update));

		ret = PTR_ERR_OR_ZERO(update);
		if (ret)
			goto err;

		bkey_init(&update->k);
		update->k.type	= freespace_key_type;
		update->k.p	= freespace_iter.pos;
		bch2_key_resize(&update->k, 1);

		ret = bch2_trans_update(trans, &freespace_iter, update, 0);
		if (ret)
			goto err;
	}
err:
fsck_err:
	bch2_trans_iter_exit(trans, &freespace_iter);
	bch2_trans_iter_exit(trans, &discard_iter);
	printbuf_exit(&buf2);
	printbuf_exit(&buf);
	return ret;
}

714 715
static int bch2_check_discard_freespace_key(struct btree_trans *trans,
					    struct btree_iter *iter)
716 717 718 719 720 721 722
{
	struct bch_fs *c = trans->c;
	struct btree_iter alloc_iter;
	struct bkey_s_c k, freespace_k;
	struct bch_alloc_v4 a;
	u64 genbits;
	struct bpos pos;
723 724 725
	enum bch_data_type state = iter->btree_id == BTREE_ID_need_discard
		? BCH_DATA_need_discard
		: BCH_DATA_free;
726 727 728
	struct printbuf buf = PRINTBUF;
	int ret;

729
	freespace_k = bch2_btree_iter_peek(iter);
730 731 732 733 734 735 736
	if (!freespace_k.k)
		return 1;

	ret = bkey_err(freespace_k);
	if (ret)
		return ret;

737
	pos = iter->pos;
738
	pos.offset &= ~(~0ULL << 56);
739
	genbits = iter->pos.offset & (~0ULL << 56);
740 741 742 743

	bch2_trans_iter_init(trans, &alloc_iter, BTREE_ID_alloc, pos, 0);

	if (fsck_err_on(!bch2_dev_bucket_exists(c, pos), c,
744 745
			"entry in %s btree for nonexistant dev:bucket %llu:%llu",
			bch2_btree_ids[iter->btree_id], pos.inode, pos.offset))
746 747 748 749 750 751 752 753 754
		goto delete;

	k = bch2_btree_iter_peek_slot(&alloc_iter);
	ret = bkey_err(k);
	if (ret)
		goto err;

	bch2_alloc_to_v4(k, &a);

755 756
	if (fsck_err_on(a.data_type != state ||
			(state == BCH_DATA_free &&
757 758
			 genbits != alloc_freespace_genbits(a)), c,
			"%s\n  incorrectly set in %s index (free %u, genbits %llu should be %llu)",
759
			(bch2_bkey_val_to_text(&buf, c, k), buf.buf),
760
			bch2_btree_ids[iter->btree_id],
761
			a.data_type == state,
762 763 764 765 766 767 768 769 770
			genbits >> 56, alloc_freespace_genbits(a) >> 56))
		goto delete;
out:
err:
fsck_err:
	bch2_trans_iter_exit(trans, &alloc_iter);
	printbuf_exit(&buf);
	return ret;
delete:
771 772
	ret = bch2_btree_delete_extent_at(trans, iter,
			iter->btree_id == BTREE_ID_freespace ? 1 : 0, 0);
773 774 775
	goto out;
}

776
int bch2_check_alloc_info(struct bch_fs *c)
777 778 779 780
{
	struct btree_trans trans;
	struct btree_iter iter;
	struct bkey_s_c k;
781
	int ret = 0;
782 783 784 785 786

	bch2_trans_init(&trans, c, 0, 0);

	for_each_btree_key(&trans, iter, BTREE_ID_alloc, POS_MIN,
			   BTREE_ITER_PREFETCH, k, ret) {
787 788 789 790 791 792
		ret = __bch2_trans_do(&trans, NULL, NULL, 0,
			bch2_check_alloc_key(&trans, &iter));
		if (ret)
			break;
	}
	bch2_trans_iter_exit(&trans, &iter);
793

794 795
	if (ret)
		goto err;
796

797 798 799
	bch2_trans_iter_init(&trans, &iter, BTREE_ID_need_discard, POS_MIN,
			     BTREE_ITER_PREFETCH);
	while (1) {
800
		ret = __bch2_trans_do(&trans, NULL, NULL, 0,
801
			bch2_check_discard_freespace_key(&trans, &iter));
802 803
		if (ret)
			break;
804 805

		bch2_btree_iter_set_pos(&iter, bpos_nosnap_successor(iter.pos));
806 807 808 809 810 811 812 813 814 815
	}
	bch2_trans_iter_exit(&trans, &iter);

	if (ret)
		goto err;

	bch2_trans_iter_init(&trans, &iter, BTREE_ID_freespace, POS_MIN,
			     BTREE_ITER_PREFETCH);
	while (1) {
		ret = __bch2_trans_do(&trans, NULL, NULL, 0,
816
			bch2_check_discard_freespace_key(&trans, &iter));
817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848
		if (ret)
			break;

		bch2_btree_iter_set_pos(&iter, bpos_nosnap_successor(iter.pos));
	}
	bch2_trans_iter_exit(&trans, &iter);
err:
	bch2_trans_exit(&trans);
	return ret < 0 ? ret : 0;
}

static int bch2_check_alloc_to_lru_ref(struct btree_trans *trans,
				       struct btree_iter *alloc_iter)
{
	struct bch_fs *c = trans->c;
	struct btree_iter lru_iter;
	struct bch_alloc_v4 a;
	struct bkey_s_c alloc_k, k;
	struct printbuf buf = PRINTBUF;
	struct printbuf buf2 = PRINTBUF;
	int ret;

	alloc_k = bch2_btree_iter_peek(alloc_iter);
	if (!alloc_k.k)
		return 0;

	ret = bkey_err(alloc_k);
	if (ret)
		return ret;

	bch2_alloc_to_v4(alloc_k, &a);

849
	if (a.data_type != BCH_DATA_cached)
850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877
		return 0;

	bch2_trans_iter_init(trans, &lru_iter, BTREE_ID_lru,
			     POS(alloc_k.k->p.inode, a.io_time[READ]), 0);

	k = bch2_btree_iter_peek_slot(&lru_iter);
	ret = bkey_err(k);
	if (ret)
		goto err;

	if (fsck_err_on(!a.io_time[READ], c,
			"cached bucket with read_time 0\n"
			"  %s",
		(printbuf_reset(&buf),
		 bch2_bkey_val_to_text(&buf, c, alloc_k), buf.buf)) ||
	    fsck_err_on(k.k->type != KEY_TYPE_lru ||
			le64_to_cpu(bkey_s_c_to_lru(k).v->idx) != alloc_k.k->p.offset, c,
			"incorrect/missing lru entry\n"
			"  %s\n"
			"  %s",
			(printbuf_reset(&buf),
			 bch2_bkey_val_to_text(&buf, c, alloc_k), buf.buf),
			(bch2_bkey_val_to_text(&buf2, c, k), buf2.buf))) {
		u64 read_time = a.io_time[READ];

		if (!a.io_time[READ])
			a.io_time[READ] = atomic64_read(&c->io_clock[READ].now);

878 879 880 881
		ret = bch2_lru_set(trans,
				   alloc_k.k->p.inode,
				   alloc_k.k->p.offset,
				   &a.io_time[READ]);
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 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930
		if (ret)
			goto err;

		if (a.io_time[READ] != read_time) {
			struct bkey_i_alloc_v4 *a_mut =
				bch2_alloc_to_v4_mut(trans, alloc_k);
			ret = PTR_ERR_OR_ZERO(a_mut);
			if (ret)
				goto err;

			a_mut->v.io_time[READ] = a.io_time[READ];
			ret = bch2_trans_update(trans, alloc_iter,
						&a_mut->k_i, BTREE_TRIGGER_NORUN);
			if (ret)
				goto err;
		}
	}
err:
fsck_err:
	bch2_trans_iter_exit(trans, &lru_iter);
	printbuf_exit(&buf2);
	printbuf_exit(&buf);
	return ret;
}

int bch2_check_alloc_to_lru_refs(struct bch_fs *c)
{
	struct btree_trans trans;
	struct btree_iter iter;
	struct bkey_s_c k;
	int ret = 0;

	bch2_trans_init(&trans, c, 0, 0);

	for_each_btree_key(&trans, iter, BTREE_ID_alloc, POS_MIN,
			   BTREE_ITER_PREFETCH, k, ret) {
		ret = __bch2_trans_do(&trans, NULL, NULL,
				      BTREE_INSERT_NOFAIL|
				      BTREE_INSERT_LAZY_RW,
			bch2_check_alloc_to_lru_ref(&trans, &iter));
		if (ret)
			break;
	}
	bch2_trans_iter_exit(&trans, &iter);

	bch2_trans_exit(&trans);
	return ret < 0 ? ret : 0;
}

931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958
static int bch2_clear_need_discard(struct btree_trans *trans, struct bpos pos,
				   struct bch_dev *ca, bool *discard_done)
{
	struct bch_fs *c = trans->c;
	struct btree_iter iter;
	struct bkey_s_c k;
	struct bkey_i_alloc_v4 *a;
	struct printbuf buf = PRINTBUF;
	int ret;

	bch2_trans_iter_init(trans, &iter, BTREE_ID_alloc, pos,
			     BTREE_ITER_CACHED);
	k = bch2_btree_iter_peek_slot(&iter);
	ret = bkey_err(k);
	if (ret)
		goto out;

	a = bch2_alloc_to_v4_mut(trans, k);
	ret = PTR_ERR_OR_ZERO(a);
	if (ret)
		goto out;

	if (BCH_ALLOC_V4_NEED_INC_GEN(&a->v)) {
		a->v.gen++;
		SET_BCH_ALLOC_V4_NEED_INC_GEN(&a->v, false);
		goto write;
	}

959
	if (bch2_trans_inconsistent_on(a->v.journal_seq > c->journal.flushed_seq_ondisk, trans,
960 961 962 963 964 965 966 967
			"clearing need_discard but journal_seq %llu > flushed_seq %llu\n"
			"%s",
			a->v.journal_seq,
			c->journal.flushed_seq_ondisk,
			(bch2_bkey_val_to_text(&buf, c, k), buf.buf))) {
		ret = -EIO;
		goto out;
	}
968

969
	if (bch2_trans_inconsistent_on(a->v.data_type != BCH_DATA_need_discard, trans,
970 971
			"bucket incorrectly set in need_discard btree\n"
			"%s",
972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994
			(bch2_bkey_val_to_text(&buf, c, k), buf.buf))) {
		ret = -EIO;
		goto out;
	}

	if (!*discard_done && ca->mi.discard && !c->opts.nochanges) {
		/*
		 * This works without any other locks because this is the only
		 * thread that removes items from the need_discard tree
		 */
		bch2_trans_unlock(trans);
		blkdev_issue_discard(ca->disk_sb.bdev,
				     k.k->p.offset * ca->mi.bucket_size,
				     ca->mi.bucket_size,
				     GFP_KERNEL);
		*discard_done = true;

		ret = bch2_trans_relock(trans) ? 0 : -EINTR;
		if (ret)
			goto out;
	}

	SET_BCH_ALLOC_V4_NEED_DISCARD(&a->v, false);
995
	a->v.data_type = alloc_data_type(a->v, a->v.data_type);
996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068
write:
	ret = bch2_trans_update(trans, &iter, &a->k_i, 0);
out:
	bch2_trans_iter_exit(trans, &iter);
	printbuf_exit(&buf);
	return ret;
}

static void bch2_do_discards_work(struct work_struct *work)
{
	struct bch_fs *c = container_of(work, struct bch_fs, discard_work);
	struct bch_dev *ca = NULL;
	struct btree_trans trans;
	struct btree_iter iter;
	struct bkey_s_c k;
	u64 seen = 0, open = 0, need_journal_commit = 0, discarded = 0;
	int ret;

	bch2_trans_init(&trans, c, 0, 0);

	for_each_btree_key(&trans, iter, BTREE_ID_need_discard,
			   POS_MIN, 0, k, ret) {
		bool discard_done = false;

		if (ca && k.k->p.inode != ca->dev_idx) {
			percpu_ref_put(&ca->io_ref);
			ca = NULL;
		}

		if (!ca) {
			ca = bch_dev_bkey_exists(c, k.k->p.inode);
			if (!percpu_ref_tryget(&ca->io_ref)) {
				ca = NULL;
				bch2_btree_iter_set_pos(&iter, POS(k.k->p.inode + 1, 0));
				continue;
			}
		}

		seen++;

		if (bch2_bucket_is_open_safe(c, k.k->p.inode, k.k->p.offset)) {
			open++;
			continue;
		}

		if (bch2_bucket_needs_journal_commit(&c->buckets_waiting_for_journal,
				c->journal.flushed_seq_ondisk,
				k.k->p.inode, k.k->p.offset)) {
			need_journal_commit++;
			continue;
		}

		ret = __bch2_trans_do(&trans, NULL, NULL,
				      BTREE_INSERT_USE_RESERVE|
				      BTREE_INSERT_NOFAIL,
				bch2_clear_need_discard(&trans, k.k->p, ca, &discard_done));
		if (ret)
			break;

		discarded++;
	}
	bch2_trans_iter_exit(&trans, &iter);

	if (ca)
		percpu_ref_put(&ca->io_ref);

	bch2_trans_exit(&trans);

	if (need_journal_commit * 2 > seen)
		bch2_journal_flush_async(&c->journal, NULL);

	percpu_ref_put(&c->writes);

1069
	trace_discard_buckets(c, seen, open, need_journal_commit, discarded, ret);
1070 1071 1072 1073 1074 1075 1076 1077 1078
}

void bch2_do_discards(struct bch_fs *c)
{
	if (percpu_ref_tryget(&c->writes) &&
	    !queue_work(system_long_wq, &c->discard_work))
		percpu_ref_put(&c->writes);
}

1079 1080 1081 1082 1083 1084 1085
static int invalidate_one_bucket(struct btree_trans *trans, struct bch_dev *ca)
{
	struct bch_fs *c = trans->c;
	struct btree_iter lru_iter, alloc_iter = { NULL };
	struct bkey_s_c k;
	struct bkey_i_alloc_v4 *a;
	u64 bucket, idx;
1086
	struct printbuf buf = PRINTBUF;
1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098
	int ret;

	bch2_trans_iter_init(trans, &lru_iter, BTREE_ID_lru,
			     POS(ca->dev_idx, 0), 0);
	k = bch2_btree_iter_peek(&lru_iter);
	ret = bkey_err(k);
	if (ret)
		goto out;

	if (!k.k || k.k->p.inode != ca->dev_idx)
		goto out;

1099 1100
	if (bch2_trans_inconsistent_on(k.k->type != KEY_TYPE_lru, trans,
				       "non lru key in lru btree"))
1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111
		goto out;

	idx	= k.k->p.offset;
	bucket	= le64_to_cpu(bkey_s_c_to_lru(k).v->idx);

	a = bch2_trans_start_alloc_update(trans, &alloc_iter,
					  POS(ca->dev_idx, bucket));
	ret = PTR_ERR_OR_ZERO(a);
	if (ret)
		goto out;

1112 1113 1114 1115 1116 1117 1118 1119
	if (idx != alloc_lru_idx(a->v)) {
		pr_buf(&buf, "alloc key does not point back to lru entry when invalidating bucket:\n  ");

		bch2_bkey_val_to_text(&buf, c, bkey_i_to_s_c(&a->k_i));
		pr_buf(&buf, "\n  ");
		bch2_bkey_val_to_text(&buf, c, k);
		bch2_trans_inconsistent(trans, "%s", buf.buf);
		ret = -EINVAL;
1120
		goto out;
1121
	}
1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132

	SET_BCH_ALLOC_V4_NEED_INC_GEN(&a->v, false);
	a->v.gen++;
	a->v.data_type		= 0;
	a->v.dirty_sectors	= 0;
	a->v.cached_sectors	= 0;
	a->v.io_time[READ]	= atomic64_read(&c->io_clock[READ].now);
	a->v.io_time[WRITE]	= atomic64_read(&c->io_clock[WRITE].now);

	ret = bch2_trans_update(trans, &alloc_iter, &a->k_i,
				BTREE_TRIGGER_BUCKET_INVALIDATE);
1133 1134 1135 1136
	if (ret)
		goto out;

	trace_invalidate_bucket(c, a->k.p.inode, a->k.p.offset);
1137 1138 1139
out:
	bch2_trans_iter_exit(trans, &alloc_iter);
	bch2_trans_iter_exit(trans, &lru_iter);
1140
	printbuf_exit(&buf);
1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153
	return ret;
}

static void bch2_do_invalidates_work(struct work_struct *work)
{
	struct bch_fs *c = container_of(work, struct bch_fs, invalidate_work);
	struct bch_dev *ca;
	struct btree_trans trans;
	unsigned i;
	int ret = 0;

	bch2_trans_init(&trans, c, 0, 0);

1154 1155 1156 1157 1158
	for_each_member_device(ca, c, i) {
		s64 nr_to_invalidate =
			should_invalidate_buckets(ca, bch2_dev_usage_read(ca));

		while (!ret && nr_to_invalidate-- >= 0)
1159 1160 1161 1162
			ret = __bch2_trans_do(&trans, NULL, NULL,
					      BTREE_INSERT_USE_RESERVE|
					      BTREE_INSERT_NOFAIL,
					invalidate_one_bucket(&trans, ca));
1163
	}
1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174

	bch2_trans_exit(&trans);
	percpu_ref_put(&c->writes);
}

void bch2_do_invalidates(struct bch_fs *c)
{
	if (percpu_ref_tryget(&c->writes))
		queue_work(system_long_wq, &c->invalidate_work);
}

1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195
static int bch2_dev_freespace_init(struct bch_fs *c, struct bch_dev *ca)
{
	struct btree_trans trans;
	struct btree_iter iter;
	struct bkey_s_c k;
	struct bch_alloc_v4 a;
	struct bch_member *m;
	int ret;

	bch2_trans_init(&trans, c, 0, 0);

	for_each_btree_key(&trans, iter, BTREE_ID_alloc,
			   POS(ca->dev_idx, ca->mi.first_bucket),
			   BTREE_ITER_SLOTS|
			   BTREE_ITER_PREFETCH, k, ret) {
		if (iter.pos.offset >= ca->mi.nbuckets)
			break;

		bch2_alloc_to_v4(k, &a);
		ret = __bch2_trans_do(&trans, NULL, NULL,
				      BTREE_INSERT_LAZY_RW,
1196
				 bch2_bucket_do_index(&trans, k, &a, true));
1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255
		if (ret)
			break;
	}
	bch2_trans_iter_exit(&trans, &iter);

	bch2_trans_exit(&trans);

	if (ret) {
		bch_err(ca, "error initializing free space: %i", ret);
		return ret;
	}

	mutex_lock(&c->sb_lock);
	m = bch2_sb_get_members(c->disk_sb.sb)->members + ca->dev_idx;
	SET_BCH_MEMBER_FREESPACE_INITIALIZED(m, true);
	mutex_unlock(&c->sb_lock);

	return ret;
}

int bch2_fs_freespace_init(struct bch_fs *c)
{
	struct bch_dev *ca;
	unsigned i;
	int ret = 0;
	bool doing_init = false;

	/*
	 * We can crash during the device add path, so we need to check this on
	 * every mount:
	 */

	for_each_member_device(ca, c, i) {
		if (ca->mi.freespace_initialized)
			continue;

		if (!doing_init) {
			bch_info(c, "initializing freespace");
			doing_init = true;
		}

		ret = bch2_dev_freespace_init(c, ca);
		if (ret) {
			percpu_ref_put(&ca->ref);
			return ret;
		}
	}

	if (doing_init) {
		mutex_lock(&c->sb_lock);
		bch2_write_super(c);
		mutex_unlock(&c->sb_lock);

		bch_verbose(c, "done initializing freespace");
	}

	return ret;
}

1256 1257
/* Bucket IO clocks: */

1258 1259 1260 1261
int bch2_bucket_io_time_reset(struct btree_trans *trans, unsigned dev,
			      size_t bucket_nr, int rw)
{
	struct bch_fs *c = trans->c;
Kent Overstreet's avatar
Kent Overstreet committed
1262
	struct btree_iter iter;
1263 1264
	struct bkey_i_alloc_v4 *a;
	u64 now;
1265 1266
	int ret = 0;

1267 1268
	a = bch2_trans_start_alloc_update(trans, &iter,  POS(dev, bucket_nr));
	ret = PTR_ERR_OR_ZERO(a);
1269
	if (ret)
1270
		return ret;
1271

1272
	now = atomic64_read(&c->io_clock[rw].now);
1273
	if (a->v.io_time[rw] == now)
1274 1275
		goto out;

1276
	a->v.io_time[rw] = now;
1277

1278
	ret   = bch2_trans_update(trans, &iter, &a->k_i, 0) ?:
1279 1280
		bch2_trans_commit(trans, NULL, NULL, 0);
out:
Kent Overstreet's avatar
Kent Overstreet committed
1281
	bch2_trans_iter_exit(trans, &iter);
1282 1283 1284
	return ret;
}

1285 1286 1287 1288 1289
/* Startup/shutdown (ro/rw): */

void bch2_recalc_capacity(struct bch_fs *c)
{
	struct bch_dev *ca;
1290
	u64 capacity = 0, reserved_sectors = 0, gc_reserve;
1291
	unsigned bucket_size_max = 0;
1292
	unsigned long ra_pages = 0;
1293
	unsigned i;
1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305

	lockdep_assert_held(&c->state_lock);

	for_each_online_member(ca, c, i) {
		struct backing_dev_info *bdi = ca->disk_sb.bdev->bd_disk->bdi;

		ra_pages += bdi->ra_pages;
	}

	bch2_set_ra_pages(c, ra_pages);

	for_each_rw_member(ca, c, i) {
1306
		u64 dev_reserve = 0;
1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323

		/*
		 * We need to reserve buckets (from the number
		 * of currently available buckets) against
		 * foreground writes so that mainly copygc can
		 * make forward progress.
		 *
		 * We need enough to refill the various reserves
		 * from scratch - copygc will use its entire
		 * reserve all at once, then run against when
		 * its reserve is refilled (from the formerly
		 * available buckets).
		 *
		 * This reserve is just used when considering if
		 * allocations for foreground writes must wait -
		 * not -ENOSPC calculations.
		 */
1324 1325 1326

		dev_reserve += ca->nr_btree_reserve * 2;
		dev_reserve += ca->mi.nbuckets >> 6; /* copygc reserve */
1327

1328 1329 1330
		dev_reserve += 1;	/* btree write point */
		dev_reserve += 1;	/* copygc write point */
		dev_reserve += 1;	/* rebalance write point */
1331

1332
		dev_reserve *= ca->mi.bucket_size;
1333

1334 1335
		capacity += bucket_to_sector(ca, ca->mi.nbuckets -
					     ca->mi.first_bucket);
1336

1337
		reserved_sectors += dev_reserve * 2;
1338 1339 1340

		bucket_size_max = max_t(unsigned, bucket_size_max,
					ca->mi.bucket_size);
1341
	}
1342

1343 1344 1345 1346 1347
	gc_reserve = c->opts.gc_reserve_bytes
		? c->opts.gc_reserve_bytes >> 9
		: div64_u64(capacity * c->opts.gc_reserve_percent, 100);

	reserved_sectors = max(gc_reserve, reserved_sectors);
1348

1349
	reserved_sectors = min(reserved_sectors, capacity);
1350

1351
	c->capacity = capacity - reserved_sectors;
1352

1353 1354
	c->bucket_size_max = bucket_size_max;

1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368
	/* Wake up case someone was waiting for buckets */
	closure_wake_up(&c->freelist_wait);
}

static bool bch2_dev_has_open_write_point(struct bch_fs *c, struct bch_dev *ca)
{
	struct open_bucket *ob;
	bool ret = false;

	for (ob = c->open_buckets;
	     ob < c->open_buckets + ARRAY_SIZE(c->open_buckets);
	     ob++) {
		spin_lock(&ob->lock);
		if (ob->valid && !ob->on_partial_list &&
1369
		    ob->dev == ca->dev_idx)
1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393
			ret = true;
		spin_unlock(&ob->lock);
	}

	return ret;
}

/* device goes ro: */
void bch2_dev_allocator_remove(struct bch_fs *c, struct bch_dev *ca)
{
	unsigned i;

	/* First, remove device from allocation groups: */

	for (i = 0; i < ARRAY_SIZE(c->rw_devs); i++)
		clear_bit(ca->dev_idx, c->rw_devs[i].d);

	/*
	 * Capacity is calculated based off of devices in allocation groups:
	 */
	bch2_recalc_capacity(c);

	/* Next, close write points that point to this device... */
	for (i = 0; i < ARRAY_SIZE(c->write_points); i++)
1394
		bch2_writepoint_stop(c, ca, &c->write_points[i]);
1395

1396
	bch2_writepoint_stop(c, ca, &c->copygc_write_point);
1397 1398
	bch2_writepoint_stop(c, ca, &c->rebalance_write_point);
	bch2_writepoint_stop(c, ca, &c->btree_write_point);
1399 1400 1401 1402 1403 1404

	mutex_lock(&c->btree_reserve_cache_lock);
	while (c->btree_reserve_cache_nr) {
		struct btree_alloc *a =
			&c->btree_reserve_cache[--c->btree_reserve_cache_nr];

1405
		bch2_open_buckets_put(c, &a->ob);
1406 1407 1408
	}
	mutex_unlock(&c->btree_reserve_cache_lock);

1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426
	while (1) {
		struct open_bucket *ob;

		spin_lock(&c->freelist_lock);
		if (!ca->open_buckets_partial_nr) {
			spin_unlock(&c->freelist_lock);
			break;
		}
		ob = c->open_buckets +
			ca->open_buckets_partial[--ca->open_buckets_partial_nr];
		ob->on_partial_list = false;
		spin_unlock(&c->freelist_lock);

		bch2_open_bucket_put(c, ob);
	}

	bch2_ec_stop_dev(c, ca);

1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454
	/*
	 * Wake up threads that were blocked on allocation, so they can notice
	 * the device can no longer be removed and the capacity has changed:
	 */
	closure_wake_up(&c->freelist_wait);

	/*
	 * journal_res_get() can block waiting for free space in the journal -
	 * it needs to notice there may not be devices to allocate from anymore:
	 */
	wake_up(&c->journal.wait);

	/* Now wait for any in flight writes: */

	closure_wait_event(&c->open_buckets_wait,
			   !bch2_dev_has_open_write_point(c, ca));
}

/* device goes rw: */
void bch2_dev_allocator_add(struct bch_fs *c, struct bch_dev *ca)
{
	unsigned i;

	for (i = 0; i < ARRAY_SIZE(c->rw_devs); i++)
		if (ca->mi.data_allowed & (1 << i))
			set_bit(ca->dev_idx, c->rw_devs[i].d);
}

1455
void bch2_fs_allocator_background_init(struct bch_fs *c)
1456 1457
{
	spin_lock_init(&c->freelist_lock);
1458
	INIT_WORK(&c->discard_work, bch2_do_discards_work);
1459
	INIT_WORK(&c->invalidate_work, bch2_do_invalidates_work);
1460
}