1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * bcachefs setup/teardown code, and some metadata io - read a superblock and
4  * figure out what to do with it.
5  *
6  * Copyright 2010, 2011 Kent Overstreet <kent.overstreet@gmail.com>
7  * Copyright 2012 Google, Inc.
8  */
9 
10 #include "bcachefs.h"
11 #include "alloc_background.h"
12 #include "alloc_foreground.h"
13 #include "bkey_sort.h"
14 #include "btree_cache.h"
15 #include "btree_gc.h"
16 #include "btree_journal_iter.h"
17 #include "btree_key_cache.h"
18 #include "btree_node_scan.h"
19 #include "btree_update_interior.h"
20 #include "btree_io.h"
21 #include "btree_write_buffer.h"
22 #include "buckets_waiting_for_journal.h"
23 #include "chardev.h"
24 #include "checksum.h"
25 #include "clock.h"
26 #include "compress.h"
27 #include "debug.h"
28 #include "disk_accounting.h"
29 #include "disk_groups.h"
30 #include "ec.h"
31 #include "errcode.h"
32 #include "error.h"
33 #include "fs.h"
34 #include "fs-io.h"
35 #include "fs-io-buffered.h"
36 #include "fs-io-direct.h"
37 #include "fsck.h"
38 #include "inode.h"
39 #include "io_read.h"
40 #include "io_write.h"
41 #include "journal.h"
42 #include "journal_reclaim.h"
43 #include "journal_seq_blacklist.h"
44 #include "move.h"
45 #include "migrate.h"
46 #include "movinggc.h"
47 #include "nocow_locking.h"
48 #include "quota.h"
49 #include "rebalance.h"
50 #include "recovery.h"
51 #include "replicas.h"
52 #include "sb-clean.h"
53 #include "sb-counters.h"
54 #include "sb-errors.h"
55 #include "sb-members.h"
56 #include "snapshot.h"
57 #include "subvolume.h"
58 #include "super.h"
59 #include "super-io.h"
60 #include "sysfs.h"
61 #include "thread_with_file.h"
62 #include "trace.h"
63 
64 #include <linux/backing-dev.h>
65 #include <linux/blkdev.h>
66 #include <linux/debugfs.h>
67 #include <linux/device.h>
68 #include <linux/idr.h>
69 #include <linux/module.h>
70 #include <linux/percpu.h>
71 #include <linux/random.h>
72 #include <linux/sysfs.h>
73 
74 MODULE_LICENSE("GPL");
75 MODULE_AUTHOR("Kent Overstreet <kent.overstreet@gmail.com>");
76 MODULE_DESCRIPTION("bcachefs filesystem");
77 
78 const char * const bch2_fs_flag_strs[] = {
79 #define x(n)		#n,
80 	BCH_FS_FLAGS()
81 #undef x
82 	NULL
83 };
84 
bch2_print_str(struct bch_fs * c,const char * str)85 void bch2_print_str(struct bch_fs *c, const char *str)
86 {
87 #ifdef __KERNEL__
88 	struct stdio_redirect *stdio = bch2_fs_stdio_redirect(c);
89 
90 	if (unlikely(stdio)) {
91 		bch2_stdio_redirect_printf(stdio, true, "%s", str);
92 		return;
93 	}
94 #endif
95 	bch2_print_string_as_lines(KERN_ERR, str);
96 }
97 
98 __printf(2, 0)
bch2_print_maybe_redirect(struct stdio_redirect * stdio,const char * fmt,va_list args)99 static void bch2_print_maybe_redirect(struct stdio_redirect *stdio, const char *fmt, va_list args)
100 {
101 #ifdef __KERNEL__
102 	if (unlikely(stdio)) {
103 		if (fmt[0] == KERN_SOH[0])
104 			fmt += 2;
105 
106 		bch2_stdio_redirect_vprintf(stdio, true, fmt, args);
107 		return;
108 	}
109 #endif
110 	vprintk(fmt, args);
111 }
112 
bch2_print_opts(struct bch_opts * opts,const char * fmt,...)113 void bch2_print_opts(struct bch_opts *opts, const char *fmt, ...)
114 {
115 	struct stdio_redirect *stdio = (void *)(unsigned long)opts->stdio;
116 
117 	va_list args;
118 	va_start(args, fmt);
119 	bch2_print_maybe_redirect(stdio, fmt, args);
120 	va_end(args);
121 }
122 
__bch2_print(struct bch_fs * c,const char * fmt,...)123 void __bch2_print(struct bch_fs *c, const char *fmt, ...)
124 {
125 	struct stdio_redirect *stdio = bch2_fs_stdio_redirect(c);
126 
127 	va_list args;
128 	va_start(args, fmt);
129 	bch2_print_maybe_redirect(stdio, fmt, args);
130 	va_end(args);
131 }
132 
133 #define KTYPE(type)							\
134 static const struct attribute_group type ## _group = {			\
135 	.attrs = type ## _files						\
136 };									\
137 									\
138 static const struct attribute_group *type ## _groups[] = {		\
139 	&type ## _group,						\
140 	NULL								\
141 };									\
142 									\
143 static const struct kobj_type type ## _ktype = {			\
144 	.release	= type ## _release,				\
145 	.sysfs_ops	= &type ## _sysfs_ops,				\
146 	.default_groups = type ## _groups				\
147 }
148 
149 static void bch2_fs_release(struct kobject *);
150 static void bch2_dev_release(struct kobject *);
bch2_fs_counters_release(struct kobject * k)151 static void bch2_fs_counters_release(struct kobject *k)
152 {
153 }
154 
bch2_fs_internal_release(struct kobject * k)155 static void bch2_fs_internal_release(struct kobject *k)
156 {
157 }
158 
bch2_fs_opts_dir_release(struct kobject * k)159 static void bch2_fs_opts_dir_release(struct kobject *k)
160 {
161 }
162 
bch2_fs_time_stats_release(struct kobject * k)163 static void bch2_fs_time_stats_release(struct kobject *k)
164 {
165 }
166 
167 KTYPE(bch2_fs);
168 KTYPE(bch2_fs_counters);
169 KTYPE(bch2_fs_internal);
170 KTYPE(bch2_fs_opts_dir);
171 KTYPE(bch2_fs_time_stats);
172 KTYPE(bch2_dev);
173 
174 static struct kset *bcachefs_kset;
175 static LIST_HEAD(bch_fs_list);
176 static DEFINE_MUTEX(bch_fs_list_lock);
177 
178 DECLARE_WAIT_QUEUE_HEAD(bch2_read_only_wait);
179 
180 static void bch2_dev_unlink(struct bch_dev *);
181 static void bch2_dev_free(struct bch_dev *);
182 static int bch2_dev_alloc(struct bch_fs *, unsigned);
183 static int bch2_dev_sysfs_online(struct bch_fs *, struct bch_dev *);
184 static void bch2_dev_io_ref_stop(struct bch_dev *, int);
185 static void __bch2_dev_read_only(struct bch_fs *, struct bch_dev *);
186 
bch2_dev_to_fs(dev_t dev)187 struct bch_fs *bch2_dev_to_fs(dev_t dev)
188 {
189 	struct bch_fs *c;
190 
191 	mutex_lock(&bch_fs_list_lock);
192 	rcu_read_lock();
193 
194 	list_for_each_entry(c, &bch_fs_list, list)
195 		for_each_member_device_rcu(c, ca, NULL)
196 			if (ca->disk_sb.bdev && ca->disk_sb.bdev->bd_dev == dev) {
197 				closure_get(&c->cl);
198 				goto found;
199 			}
200 	c = NULL;
201 found:
202 	rcu_read_unlock();
203 	mutex_unlock(&bch_fs_list_lock);
204 
205 	return c;
206 }
207 
__bch2_uuid_to_fs(__uuid_t uuid)208 static struct bch_fs *__bch2_uuid_to_fs(__uuid_t uuid)
209 {
210 	struct bch_fs *c;
211 
212 	lockdep_assert_held(&bch_fs_list_lock);
213 
214 	list_for_each_entry(c, &bch_fs_list, list)
215 		if (!memcmp(&c->disk_sb.sb->uuid, &uuid, sizeof(uuid)))
216 			return c;
217 
218 	return NULL;
219 }
220 
bch2_uuid_to_fs(__uuid_t uuid)221 struct bch_fs *bch2_uuid_to_fs(__uuid_t uuid)
222 {
223 	struct bch_fs *c;
224 
225 	mutex_lock(&bch_fs_list_lock);
226 	c = __bch2_uuid_to_fs(uuid);
227 	if (c)
228 		closure_get(&c->cl);
229 	mutex_unlock(&bch_fs_list_lock);
230 
231 	return c;
232 }
233 
234 /* Filesystem RO/RW: */
235 
236 /*
237  * For startup/shutdown of RW stuff, the dependencies are:
238  *
239  * - foreground writes depend on copygc and rebalance (to free up space)
240  *
241  * - copygc and rebalance depend on mark and sweep gc (they actually probably
242  *   don't because they either reserve ahead of time or don't block if
243  *   allocations fail, but allocations can require mark and sweep gc to run
244  *   because of generation number wraparound)
245  *
246  * - all of the above depends on the allocator threads
247  *
248  * - allocator depends on the journal (when it rewrites prios and gens)
249  */
250 
__bch2_fs_read_only(struct bch_fs * c)251 static void __bch2_fs_read_only(struct bch_fs *c)
252 {
253 	unsigned clean_passes = 0;
254 	u64 seq = 0;
255 
256 	bch2_fs_ec_stop(c);
257 	bch2_open_buckets_stop(c, NULL, true);
258 	bch2_rebalance_stop(c);
259 	bch2_copygc_stop(c);
260 	bch2_fs_ec_flush(c);
261 
262 	bch_verbose(c, "flushing journal and stopping allocators, journal seq %llu",
263 		    journal_cur_seq(&c->journal));
264 
265 	do {
266 		clean_passes++;
267 
268 		if (bch2_btree_interior_updates_flush(c) ||
269 		    bch2_btree_write_buffer_flush_going_ro(c) ||
270 		    bch2_journal_flush_all_pins(&c->journal) ||
271 		    bch2_btree_flush_all_writes(c) ||
272 		    seq != atomic64_read(&c->journal.seq)) {
273 			seq = atomic64_read(&c->journal.seq);
274 			clean_passes = 0;
275 		}
276 	} while (clean_passes < 2);
277 
278 	bch_verbose(c, "flushing journal and stopping allocators complete, journal seq %llu",
279 		    journal_cur_seq(&c->journal));
280 
281 	if (test_bit(JOURNAL_replay_done, &c->journal.flags) &&
282 	    !test_bit(BCH_FS_emergency_ro, &c->flags))
283 		set_bit(BCH_FS_clean_shutdown, &c->flags);
284 
285 	bch2_fs_journal_stop(&c->journal);
286 
287 	bch_info(c, "%sclean shutdown complete, journal seq %llu",
288 		 test_bit(BCH_FS_clean_shutdown, &c->flags) ? "" : "un",
289 		 c->journal.seq_ondisk);
290 
291 	/*
292 	 * After stopping journal:
293 	 */
294 	for_each_member_device(c, ca) {
295 		bch2_dev_io_ref_stop(ca, WRITE);
296 		bch2_dev_allocator_remove(c, ca);
297 	}
298 }
299 
300 #ifndef BCH_WRITE_REF_DEBUG
bch2_writes_disabled(struct percpu_ref * writes)301 static void bch2_writes_disabled(struct percpu_ref *writes)
302 {
303 	struct bch_fs *c = container_of(writes, struct bch_fs, writes);
304 
305 	set_bit(BCH_FS_write_disable_complete, &c->flags);
306 	wake_up(&bch2_read_only_wait);
307 }
308 #endif
309 
bch2_fs_read_only(struct bch_fs * c)310 void bch2_fs_read_only(struct bch_fs *c)
311 {
312 	if (!test_bit(BCH_FS_rw, &c->flags)) {
313 		bch2_journal_reclaim_stop(&c->journal);
314 		return;
315 	}
316 
317 	BUG_ON(test_bit(BCH_FS_write_disable_complete, &c->flags));
318 
319 	bch_verbose(c, "going read-only");
320 
321 	/*
322 	 * Block new foreground-end write operations from starting - any new
323 	 * writes will return -EROFS:
324 	 */
325 	set_bit(BCH_FS_going_ro, &c->flags);
326 #ifndef BCH_WRITE_REF_DEBUG
327 	percpu_ref_kill(&c->writes);
328 #else
329 	for (unsigned i = 0; i < BCH_WRITE_REF_NR; i++)
330 		bch2_write_ref_put(c, i);
331 #endif
332 
333 	/*
334 	 * If we're not doing an emergency shutdown, we want to wait on
335 	 * outstanding writes to complete so they don't see spurious errors due
336 	 * to shutting down the allocator:
337 	 *
338 	 * If we are doing an emergency shutdown outstanding writes may
339 	 * hang until we shutdown the allocator so we don't want to wait
340 	 * on outstanding writes before shutting everything down - but
341 	 * we do need to wait on them before returning and signalling
342 	 * that going RO is complete:
343 	 */
344 	wait_event(bch2_read_only_wait,
345 		   test_bit(BCH_FS_write_disable_complete, &c->flags) ||
346 		   test_bit(BCH_FS_emergency_ro, &c->flags));
347 
348 	bool writes_disabled = test_bit(BCH_FS_write_disable_complete, &c->flags);
349 	if (writes_disabled)
350 		bch_verbose(c, "finished waiting for writes to stop");
351 
352 	__bch2_fs_read_only(c);
353 
354 	wait_event(bch2_read_only_wait,
355 		   test_bit(BCH_FS_write_disable_complete, &c->flags));
356 
357 	if (!writes_disabled)
358 		bch_verbose(c, "finished waiting for writes to stop");
359 
360 	clear_bit(BCH_FS_write_disable_complete, &c->flags);
361 	clear_bit(BCH_FS_going_ro, &c->flags);
362 	clear_bit(BCH_FS_rw, &c->flags);
363 
364 	if (!bch2_journal_error(&c->journal) &&
365 	    !test_bit(BCH_FS_error, &c->flags) &&
366 	    !test_bit(BCH_FS_emergency_ro, &c->flags) &&
367 	    test_bit(BCH_FS_started, &c->flags) &&
368 	    test_bit(BCH_FS_clean_shutdown, &c->flags) &&
369 	    c->recovery_pass_done >= BCH_RECOVERY_PASS_journal_replay) {
370 		BUG_ON(c->journal.last_empty_seq != journal_cur_seq(&c->journal));
371 		BUG_ON(atomic_long_read(&c->btree_cache.nr_dirty));
372 		BUG_ON(atomic_long_read(&c->btree_key_cache.nr_dirty));
373 		BUG_ON(c->btree_write_buffer.inc.keys.nr);
374 		BUG_ON(c->btree_write_buffer.flushing.keys.nr);
375 		bch2_verify_accounting_clean(c);
376 
377 		bch_verbose(c, "marking filesystem clean");
378 		bch2_fs_mark_clean(c);
379 	} else {
380 		/* Make sure error counts/counters are persisted */
381 		mutex_lock(&c->sb_lock);
382 		bch2_write_super(c);
383 		mutex_unlock(&c->sb_lock);
384 
385 		bch_verbose(c, "done going read-only, filesystem not clean");
386 	}
387 }
388 
bch2_fs_read_only_work(struct work_struct * work)389 static void bch2_fs_read_only_work(struct work_struct *work)
390 {
391 	struct bch_fs *c =
392 		container_of(work, struct bch_fs, read_only_work);
393 
394 	down_write(&c->state_lock);
395 	bch2_fs_read_only(c);
396 	up_write(&c->state_lock);
397 }
398 
bch2_fs_read_only_async(struct bch_fs * c)399 static void bch2_fs_read_only_async(struct bch_fs *c)
400 {
401 	queue_work(system_long_wq, &c->read_only_work);
402 }
403 
bch2_fs_emergency_read_only(struct bch_fs * c)404 bool bch2_fs_emergency_read_only(struct bch_fs *c)
405 {
406 	bool ret = !test_and_set_bit(BCH_FS_emergency_ro, &c->flags);
407 
408 	bch2_journal_halt(&c->journal);
409 	bch2_fs_read_only_async(c);
410 
411 	wake_up(&bch2_read_only_wait);
412 	return ret;
413 }
414 
bch2_fs_emergency_read_only_locked(struct bch_fs * c)415 bool bch2_fs_emergency_read_only_locked(struct bch_fs *c)
416 {
417 	bool ret = !test_and_set_bit(BCH_FS_emergency_ro, &c->flags);
418 
419 	bch2_journal_halt_locked(&c->journal);
420 	bch2_fs_read_only_async(c);
421 
422 	wake_up(&bch2_read_only_wait);
423 	return ret;
424 }
425 
__bch2_fs_read_write(struct bch_fs * c,bool early)426 static int __bch2_fs_read_write(struct bch_fs *c, bool early)
427 {
428 	int ret;
429 
430 	BUG_ON(!test_bit(BCH_FS_may_go_rw, &c->flags));
431 
432 	if (test_bit(BCH_FS_initial_gc_unfixed, &c->flags)) {
433 		bch_err(c, "cannot go rw, unfixed btree errors");
434 		return -BCH_ERR_erofs_unfixed_errors;
435 	}
436 
437 	if (test_bit(BCH_FS_rw, &c->flags))
438 		return 0;
439 
440 	bch_info(c, "going read-write");
441 
442 	ret = bch2_sb_members_v2_init(c);
443 	if (ret)
444 		goto err;
445 
446 	clear_bit(BCH_FS_clean_shutdown, &c->flags);
447 
448 	__for_each_online_member(c, ca, BIT(BCH_MEMBER_STATE_rw), READ) {
449 		bch2_dev_allocator_add(c, ca);
450 		percpu_ref_reinit(&ca->io_ref[WRITE]);
451 	}
452 	bch2_recalc_capacity(c);
453 
454 	/*
455 	 * First journal write must be a flush write: after a clean shutdown we
456 	 * don't read the journal, so the first journal write may end up
457 	 * overwriting whatever was there previously, and there must always be
458 	 * at least one non-flush write in the journal or recovery will fail:
459 	 */
460 	spin_lock(&c->journal.lock);
461 	set_bit(JOURNAL_need_flush_write, &c->journal.flags);
462 	set_bit(JOURNAL_running, &c->journal.flags);
463 	bch2_journal_space_available(&c->journal);
464 	spin_unlock(&c->journal.lock);
465 
466 	ret = bch2_fs_mark_dirty(c);
467 	if (ret)
468 		goto err;
469 
470 	ret = bch2_journal_reclaim_start(&c->journal);
471 	if (ret)
472 		goto err;
473 
474 	set_bit(BCH_FS_rw, &c->flags);
475 	set_bit(BCH_FS_was_rw, &c->flags);
476 
477 #ifndef BCH_WRITE_REF_DEBUG
478 	percpu_ref_reinit(&c->writes);
479 #else
480 	for (unsigned i = 0; i < BCH_WRITE_REF_NR; i++) {
481 		BUG_ON(atomic_long_read(&c->writes[i]));
482 		atomic_long_inc(&c->writes[i]);
483 	}
484 #endif
485 
486 	ret = bch2_copygc_start(c);
487 	if (ret) {
488 		bch_err_msg(c, ret, "error starting copygc thread");
489 		goto err;
490 	}
491 
492 	ret = bch2_rebalance_start(c);
493 	if (ret) {
494 		bch_err_msg(c, ret, "error starting rebalance thread");
495 		goto err;
496 	}
497 
498 	bch2_do_discards(c);
499 	bch2_do_invalidates(c);
500 	bch2_do_stripe_deletes(c);
501 	bch2_do_pending_node_rewrites(c);
502 	return 0;
503 err:
504 	if (test_bit(BCH_FS_rw, &c->flags))
505 		bch2_fs_read_only(c);
506 	else
507 		__bch2_fs_read_only(c);
508 	return ret;
509 }
510 
bch2_fs_read_write(struct bch_fs * c)511 int bch2_fs_read_write(struct bch_fs *c)
512 {
513 	if (c->opts.recovery_pass_last &&
514 	    c->opts.recovery_pass_last < BCH_RECOVERY_PASS_journal_replay)
515 		return -BCH_ERR_erofs_norecovery;
516 
517 	if (c->opts.nochanges)
518 		return -BCH_ERR_erofs_nochanges;
519 
520 	return __bch2_fs_read_write(c, false);
521 }
522 
bch2_fs_read_write_early(struct bch_fs * c)523 int bch2_fs_read_write_early(struct bch_fs *c)
524 {
525 	down_write(&c->state_lock);
526 	int ret = __bch2_fs_read_write(c, true);
527 	up_write(&c->state_lock);
528 
529 	return ret;
530 }
531 
532 /* Filesystem startup/shutdown: */
533 
__bch2_fs_free(struct bch_fs * c)534 static void __bch2_fs_free(struct bch_fs *c)
535 {
536 	for (unsigned i = 0; i < BCH_TIME_STAT_NR; i++)
537 		bch2_time_stats_exit(&c->times[i]);
538 
539 #ifdef CONFIG_UNICODE
540 	utf8_unload(c->cf_encoding);
541 #endif
542 
543 	bch2_find_btree_nodes_exit(&c->found_btree_nodes);
544 	bch2_free_pending_node_rewrites(c);
545 	bch2_free_fsck_errs(c);
546 	bch2_fs_accounting_exit(c);
547 	bch2_fs_sb_errors_exit(c);
548 	bch2_fs_counters_exit(c);
549 	bch2_fs_snapshots_exit(c);
550 	bch2_fs_quota_exit(c);
551 	bch2_fs_fs_io_direct_exit(c);
552 	bch2_fs_fs_io_buffered_exit(c);
553 	bch2_fs_fsio_exit(c);
554 	bch2_fs_vfs_exit(c);
555 	bch2_fs_ec_exit(c);
556 	bch2_fs_encryption_exit(c);
557 	bch2_fs_nocow_locking_exit(c);
558 	bch2_fs_io_write_exit(c);
559 	bch2_fs_io_read_exit(c);
560 	bch2_fs_buckets_waiting_for_journal_exit(c);
561 	bch2_fs_btree_interior_update_exit(c);
562 	bch2_fs_btree_key_cache_exit(&c->btree_key_cache);
563 	bch2_fs_btree_cache_exit(c);
564 	bch2_fs_btree_iter_exit(c);
565 	bch2_fs_replicas_exit(c);
566 	bch2_fs_journal_exit(&c->journal);
567 	bch2_io_clock_exit(&c->io_clock[WRITE]);
568 	bch2_io_clock_exit(&c->io_clock[READ]);
569 	bch2_fs_compress_exit(c);
570 	bch2_fs_btree_gc_exit(c);
571 	bch2_journal_keys_put_initial(c);
572 	bch2_find_btree_nodes_exit(&c->found_btree_nodes);
573 	BUG_ON(atomic_read(&c->journal_keys.ref));
574 	bch2_fs_btree_write_buffer_exit(c);
575 	percpu_free_rwsem(&c->mark_lock);
576 	if (c->online_reserved) {
577 		u64 v = percpu_u64_get(c->online_reserved);
578 		WARN(v, "online_reserved not 0 at shutdown: %lli", v);
579 		free_percpu(c->online_reserved);
580 	}
581 
582 	darray_exit(&c->incompat_versions_requested);
583 	darray_exit(&c->btree_roots_extra);
584 	free_percpu(c->pcpu);
585 	free_percpu(c->usage);
586 	mempool_exit(&c->large_bkey_pool);
587 	mempool_exit(&c->btree_bounce_pool);
588 	bioset_exit(&c->btree_bio);
589 	mempool_exit(&c->fill_iter);
590 #ifndef BCH_WRITE_REF_DEBUG
591 	percpu_ref_exit(&c->writes);
592 #endif
593 	kfree(rcu_dereference_protected(c->disk_groups, 1));
594 	kfree(c->journal_seq_blacklist_table);
595 
596 	if (c->write_ref_wq)
597 		destroy_workqueue(c->write_ref_wq);
598 	if (c->btree_write_submit_wq)
599 		destroy_workqueue(c->btree_write_submit_wq);
600 	if (c->btree_read_complete_wq)
601 		destroy_workqueue(c->btree_read_complete_wq);
602 	if (c->copygc_wq)
603 		destroy_workqueue(c->copygc_wq);
604 	if (c->btree_io_complete_wq)
605 		destroy_workqueue(c->btree_io_complete_wq);
606 	if (c->btree_update_wq)
607 		destroy_workqueue(c->btree_update_wq);
608 
609 	bch2_free_super(&c->disk_sb);
610 	kvfree(c);
611 	module_put(THIS_MODULE);
612 }
613 
bch2_fs_release(struct kobject * kobj)614 static void bch2_fs_release(struct kobject *kobj)
615 {
616 	struct bch_fs *c = container_of(kobj, struct bch_fs, kobj);
617 
618 	__bch2_fs_free(c);
619 }
620 
__bch2_fs_stop(struct bch_fs * c)621 void __bch2_fs_stop(struct bch_fs *c)
622 {
623 	bch_verbose(c, "shutting down");
624 
625 	set_bit(BCH_FS_stopping, &c->flags);
626 
627 	down_write(&c->state_lock);
628 	bch2_fs_read_only(c);
629 	up_write(&c->state_lock);
630 
631 	for_each_member_device(c, ca)
632 		bch2_dev_unlink(ca);
633 
634 	if (c->kobj.state_in_sysfs)
635 		kobject_del(&c->kobj);
636 
637 	bch2_fs_debug_exit(c);
638 	bch2_fs_chardev_exit(c);
639 
640 	bch2_ro_ref_put(c);
641 	wait_event(c->ro_ref_wait, !refcount_read(&c->ro_ref));
642 
643 	kobject_put(&c->counters_kobj);
644 	kobject_put(&c->time_stats);
645 	kobject_put(&c->opts_dir);
646 	kobject_put(&c->internal);
647 
648 	/* btree prefetch might have kicked off reads in the background: */
649 	bch2_btree_flush_all_reads(c);
650 
651 	for_each_member_device(c, ca)
652 		cancel_work_sync(&ca->io_error_work);
653 
654 	cancel_work_sync(&c->read_only_work);
655 }
656 
bch2_fs_free(struct bch_fs * c)657 void bch2_fs_free(struct bch_fs *c)
658 {
659 	unsigned i;
660 
661 	mutex_lock(&bch_fs_list_lock);
662 	list_del(&c->list);
663 	mutex_unlock(&bch_fs_list_lock);
664 
665 	closure_sync(&c->cl);
666 	closure_debug_destroy(&c->cl);
667 
668 	for (i = 0; i < c->sb.nr_devices; i++) {
669 		struct bch_dev *ca = rcu_dereference_protected(c->devs[i], true);
670 
671 		if (ca) {
672 			EBUG_ON(atomic_long_read(&ca->ref) != 1);
673 			bch2_dev_io_ref_stop(ca, READ);
674 			bch2_free_super(&ca->disk_sb);
675 			bch2_dev_free(ca);
676 		}
677 	}
678 
679 	bch_verbose(c, "shutdown complete");
680 
681 	kobject_put(&c->kobj);
682 }
683 
bch2_fs_stop(struct bch_fs * c)684 void bch2_fs_stop(struct bch_fs *c)
685 {
686 	__bch2_fs_stop(c);
687 	bch2_fs_free(c);
688 }
689 
bch2_fs_online(struct bch_fs * c)690 static int bch2_fs_online(struct bch_fs *c)
691 {
692 	int ret = 0;
693 
694 	lockdep_assert_held(&bch_fs_list_lock);
695 
696 	if (__bch2_uuid_to_fs(c->sb.uuid)) {
697 		bch_err(c, "filesystem UUID already open");
698 		return -EINVAL;
699 	}
700 
701 	ret = bch2_fs_chardev_init(c);
702 	if (ret) {
703 		bch_err(c, "error creating character device");
704 		return ret;
705 	}
706 
707 	bch2_fs_debug_init(c);
708 
709 	ret = kobject_add(&c->kobj, NULL, "%pU", c->sb.user_uuid.b) ?:
710 	    kobject_add(&c->internal, &c->kobj, "internal") ?:
711 	    kobject_add(&c->opts_dir, &c->kobj, "options") ?:
712 #ifndef CONFIG_BCACHEFS_NO_LATENCY_ACCT
713 	    kobject_add(&c->time_stats, &c->kobj, "time_stats") ?:
714 #endif
715 	    kobject_add(&c->counters_kobj, &c->kobj, "counters") ?:
716 	    bch2_opts_create_sysfs_files(&c->opts_dir, OPT_FS);
717 	if (ret) {
718 		bch_err(c, "error creating sysfs objects");
719 		return ret;
720 	}
721 
722 	down_write(&c->state_lock);
723 
724 	for_each_member_device(c, ca) {
725 		ret = bch2_dev_sysfs_online(c, ca);
726 		if (ret) {
727 			bch_err(c, "error creating sysfs objects");
728 			bch2_dev_put(ca);
729 			goto err;
730 		}
731 	}
732 
733 	BUG_ON(!list_empty(&c->list));
734 	list_add(&c->list, &bch_fs_list);
735 err:
736 	up_write(&c->state_lock);
737 	return ret;
738 }
739 
bch2_fs_alloc(struct bch_sb * sb,struct bch_opts opts)740 static struct bch_fs *bch2_fs_alloc(struct bch_sb *sb, struct bch_opts opts)
741 {
742 	struct bch_fs *c;
743 	struct printbuf name = PRINTBUF;
744 	unsigned i, iter_size;
745 	int ret = 0;
746 
747 	c = kvmalloc(sizeof(struct bch_fs), GFP_KERNEL|__GFP_ZERO);
748 	if (!c) {
749 		c = ERR_PTR(-BCH_ERR_ENOMEM_fs_alloc);
750 		goto out;
751 	}
752 
753 	c->stdio = (void *)(unsigned long) opts.stdio;
754 
755 	__module_get(THIS_MODULE);
756 
757 	closure_init(&c->cl, NULL);
758 
759 	c->kobj.kset = bcachefs_kset;
760 	kobject_init(&c->kobj, &bch2_fs_ktype);
761 	kobject_init(&c->internal, &bch2_fs_internal_ktype);
762 	kobject_init(&c->opts_dir, &bch2_fs_opts_dir_ktype);
763 	kobject_init(&c->time_stats, &bch2_fs_time_stats_ktype);
764 	kobject_init(&c->counters_kobj, &bch2_fs_counters_ktype);
765 
766 	c->minor		= -1;
767 	c->disk_sb.fs_sb	= true;
768 
769 	init_rwsem(&c->state_lock);
770 	mutex_init(&c->sb_lock);
771 	mutex_init(&c->replicas_gc_lock);
772 	mutex_init(&c->btree_root_lock);
773 	INIT_WORK(&c->read_only_work, bch2_fs_read_only_work);
774 
775 	refcount_set(&c->ro_ref, 1);
776 	init_waitqueue_head(&c->ro_ref_wait);
777 	spin_lock_init(&c->recovery_pass_lock);
778 	sema_init(&c->online_fsck_mutex, 1);
779 
780 	for (i = 0; i < BCH_TIME_STAT_NR; i++)
781 		bch2_time_stats_init(&c->times[i]);
782 
783 	bch2_fs_copygc_init(c);
784 	bch2_fs_btree_key_cache_init_early(&c->btree_key_cache);
785 	bch2_fs_btree_iter_init_early(c);
786 	bch2_fs_btree_interior_update_init_early(c);
787 	bch2_fs_journal_keys_init(c);
788 	bch2_fs_allocator_background_init(c);
789 	bch2_fs_allocator_foreground_init(c);
790 	bch2_fs_rebalance_init(c);
791 	bch2_fs_quota_init(c);
792 	bch2_fs_ec_init_early(c);
793 	bch2_fs_move_init(c);
794 	bch2_fs_sb_errors_init_early(c);
795 
796 	INIT_LIST_HEAD(&c->list);
797 
798 	mutex_init(&c->bio_bounce_pages_lock);
799 	mutex_init(&c->snapshot_table_lock);
800 	init_rwsem(&c->snapshot_create_lock);
801 
802 	spin_lock_init(&c->btree_write_error_lock);
803 
804 	INIT_LIST_HEAD(&c->journal_iters);
805 
806 	INIT_LIST_HEAD(&c->fsck_error_msgs);
807 	mutex_init(&c->fsck_error_msgs_lock);
808 
809 	seqcount_init(&c->usage_lock);
810 
811 	sema_init(&c->io_in_flight, 128);
812 
813 	INIT_LIST_HEAD(&c->vfs_inodes_list);
814 	mutex_init(&c->vfs_inodes_lock);
815 
816 	c->journal.flush_write_time	= &c->times[BCH_TIME_journal_flush_write];
817 	c->journal.noflush_write_time	= &c->times[BCH_TIME_journal_noflush_write];
818 	c->journal.flush_seq_time	= &c->times[BCH_TIME_journal_flush_seq];
819 
820 	bch2_fs_btree_cache_init_early(&c->btree_cache);
821 
822 	mutex_init(&c->sectors_available_lock);
823 
824 	ret = percpu_init_rwsem(&c->mark_lock);
825 	if (ret)
826 		goto err;
827 
828 	mutex_lock(&c->sb_lock);
829 	ret = bch2_sb_to_fs(c, sb);
830 	mutex_unlock(&c->sb_lock);
831 
832 	if (ret)
833 		goto err;
834 
835 	pr_uuid(&name, c->sb.user_uuid.b);
836 	ret = name.allocation_failure ? -BCH_ERR_ENOMEM_fs_name_alloc : 0;
837 	if (ret)
838 		goto err;
839 
840 	strscpy(c->name, name.buf, sizeof(c->name));
841 	printbuf_exit(&name);
842 
843 	/* Compat: */
844 	if (le16_to_cpu(sb->version) <= bcachefs_metadata_version_inode_v2 &&
845 	    !BCH_SB_JOURNAL_FLUSH_DELAY(sb))
846 		SET_BCH_SB_JOURNAL_FLUSH_DELAY(sb, 1000);
847 
848 	if (le16_to_cpu(sb->version) <= bcachefs_metadata_version_inode_v2 &&
849 	    !BCH_SB_JOURNAL_RECLAIM_DELAY(sb))
850 		SET_BCH_SB_JOURNAL_RECLAIM_DELAY(sb, 100);
851 
852 	c->opts = bch2_opts_default;
853 	ret = bch2_opts_from_sb(&c->opts, sb);
854 	if (ret)
855 		goto err;
856 
857 	bch2_opts_apply(&c->opts, opts);
858 
859 	c->btree_key_cache_btrees |= 1U << BTREE_ID_alloc;
860 	if (c->opts.inodes_use_key_cache)
861 		c->btree_key_cache_btrees |= 1U << BTREE_ID_inodes;
862 	c->btree_key_cache_btrees |= 1U << BTREE_ID_logged_ops;
863 
864 	c->block_bits		= ilog2(block_sectors(c));
865 	c->btree_foreground_merge_threshold = BTREE_FOREGROUND_MERGE_THRESHOLD(c);
866 
867 	if (bch2_fs_init_fault("fs_alloc")) {
868 		bch_err(c, "fs_alloc fault injected");
869 		ret = -EFAULT;
870 		goto err;
871 	}
872 
873 	iter_size = sizeof(struct sort_iter) +
874 		(btree_blocks(c) + 1) * 2 *
875 		sizeof(struct sort_iter_set);
876 
877 	if (!(c->btree_update_wq = alloc_workqueue("bcachefs",
878 				WQ_HIGHPRI|WQ_FREEZABLE|WQ_MEM_RECLAIM|WQ_UNBOUND, 512)) ||
879 	    !(c->btree_io_complete_wq = alloc_workqueue("bcachefs_btree_io",
880 				WQ_HIGHPRI|WQ_FREEZABLE|WQ_MEM_RECLAIM, 1)) ||
881 	    !(c->copygc_wq = alloc_workqueue("bcachefs_copygc",
882 				WQ_HIGHPRI|WQ_FREEZABLE|WQ_MEM_RECLAIM|WQ_CPU_INTENSIVE, 1)) ||
883 	    !(c->btree_read_complete_wq = alloc_workqueue("bcachefs_btree_read_complete",
884 				WQ_HIGHPRI|WQ_FREEZABLE|WQ_MEM_RECLAIM, 512)) ||
885 	    !(c->btree_write_submit_wq = alloc_workqueue("bcachefs_btree_write_sumit",
886 				WQ_HIGHPRI|WQ_FREEZABLE|WQ_MEM_RECLAIM, 1)) ||
887 	    !(c->write_ref_wq = alloc_workqueue("bcachefs_write_ref",
888 				WQ_FREEZABLE, 0)) ||
889 #ifndef BCH_WRITE_REF_DEBUG
890 	    percpu_ref_init(&c->writes, bch2_writes_disabled,
891 			    PERCPU_REF_INIT_DEAD, GFP_KERNEL) ||
892 #endif
893 	    mempool_init_kmalloc_pool(&c->fill_iter, 1, iter_size) ||
894 	    bioset_init(&c->btree_bio, 1,
895 			max(offsetof(struct btree_read_bio, bio),
896 			    offsetof(struct btree_write_bio, wbio.bio)),
897 			BIOSET_NEED_BVECS) ||
898 	    !(c->pcpu = alloc_percpu(struct bch_fs_pcpu)) ||
899 	    !(c->usage = alloc_percpu(struct bch_fs_usage_base)) ||
900 	    !(c->online_reserved = alloc_percpu(u64)) ||
901 	    mempool_init_kvmalloc_pool(&c->btree_bounce_pool, 1,
902 				       c->opts.btree_node_size) ||
903 	    mempool_init_kmalloc_pool(&c->large_bkey_pool, 1, 2048)) {
904 		ret = -BCH_ERR_ENOMEM_fs_other_alloc;
905 		goto err;
906 	}
907 
908 	ret = bch2_fs_counters_init(c) ?:
909 	    bch2_fs_sb_errors_init(c) ?:
910 	    bch2_io_clock_init(&c->io_clock[READ]) ?:
911 	    bch2_io_clock_init(&c->io_clock[WRITE]) ?:
912 	    bch2_fs_journal_init(&c->journal) ?:
913 	    bch2_fs_btree_iter_init(c) ?:
914 	    bch2_fs_btree_cache_init(c) ?:
915 	    bch2_fs_btree_key_cache_init(&c->btree_key_cache) ?:
916 	    bch2_fs_btree_interior_update_init(c) ?:
917 	    bch2_fs_btree_gc_init(c) ?:
918 	    bch2_fs_buckets_waiting_for_journal_init(c) ?:
919 	    bch2_fs_btree_write_buffer_init(c) ?:
920 	    bch2_fs_subvolumes_init(c) ?:
921 	    bch2_fs_io_read_init(c) ?:
922 	    bch2_fs_io_write_init(c) ?:
923 	    bch2_fs_nocow_locking_init(c) ?:
924 	    bch2_fs_encryption_init(c) ?:
925 	    bch2_fs_compress_init(c) ?:
926 	    bch2_fs_ec_init(c) ?:
927 	    bch2_fs_vfs_init(c) ?:
928 	    bch2_fs_fsio_init(c) ?:
929 	    bch2_fs_fs_io_buffered_init(c) ?:
930 	    bch2_fs_fs_io_direct_init(c);
931 	if (ret)
932 		goto err;
933 
934 #ifdef CONFIG_UNICODE
935 	/* Default encoding until we can potentially have more as an option. */
936 	c->cf_encoding = utf8_load(BCH_FS_DEFAULT_UTF8_ENCODING);
937 	if (IS_ERR(c->cf_encoding)) {
938 		printk(KERN_ERR "Cannot load UTF-8 encoding for filesystem. Version: %u.%u.%u",
939 			unicode_major(BCH_FS_DEFAULT_UTF8_ENCODING),
940 			unicode_minor(BCH_FS_DEFAULT_UTF8_ENCODING),
941 			unicode_rev(BCH_FS_DEFAULT_UTF8_ENCODING));
942 		ret = -EINVAL;
943 		goto err;
944 	}
945 	bch_info(c, "Using encoding defined by superblock: utf8-%u.%u.%u",
946 		 unicode_major(BCH_FS_DEFAULT_UTF8_ENCODING),
947 		 unicode_minor(BCH_FS_DEFAULT_UTF8_ENCODING),
948 		 unicode_rev(BCH_FS_DEFAULT_UTF8_ENCODING));
949 #else
950 	if (c->sb.features & BIT_ULL(BCH_FEATURE_casefolding)) {
951 		printk(KERN_ERR "Cannot mount a filesystem with casefolding on a kernel without CONFIG_UNICODE\n");
952 		ret = -EINVAL;
953 		goto err;
954 	}
955 #endif
956 
957 	for (i = 0; i < c->sb.nr_devices; i++) {
958 		if (!bch2_member_exists(c->disk_sb.sb, i))
959 			continue;
960 		ret = bch2_dev_alloc(c, i);
961 		if (ret)
962 			goto err;
963 	}
964 
965 	bch2_journal_entry_res_resize(&c->journal,
966 			&c->btree_root_journal_res,
967 			BTREE_ID_NR * (JSET_KEYS_U64s + BKEY_BTREE_PTR_U64s_MAX));
968 	bch2_journal_entry_res_resize(&c->journal,
969 			&c->clock_journal_res,
970 			(sizeof(struct jset_entry_clock) / sizeof(u64)) * 2);
971 
972 	mutex_lock(&bch_fs_list_lock);
973 	ret = bch2_fs_online(c);
974 	mutex_unlock(&bch_fs_list_lock);
975 
976 	if (ret)
977 		goto err;
978 out:
979 	return c;
980 err:
981 	bch2_fs_free(c);
982 	c = ERR_PTR(ret);
983 	goto out;
984 }
985 
986 noinline_for_stack
print_mount_opts(struct bch_fs * c)987 static void print_mount_opts(struct bch_fs *c)
988 {
989 	enum bch_opt_id i;
990 	struct printbuf p = PRINTBUF;
991 	bool first = true;
992 
993 	prt_str(&p, "starting version ");
994 	bch2_version_to_text(&p, c->sb.version);
995 
996 	for (i = 0; i < bch2_opts_nr; i++) {
997 		const struct bch_option *opt = &bch2_opt_table[i];
998 		u64 v = bch2_opt_get_by_id(&c->opts, i);
999 
1000 		if (!(opt->flags & OPT_MOUNT))
1001 			continue;
1002 
1003 		if (v == bch2_opt_get_by_id(&bch2_opts_default, i))
1004 			continue;
1005 
1006 		prt_str(&p, first ? " opts=" : ",");
1007 		first = false;
1008 		bch2_opt_to_text(&p, c, c->disk_sb.sb, opt, v, OPT_SHOW_MOUNT_STYLE);
1009 	}
1010 
1011 	if (c->sb.version_incompat_allowed != c->sb.version) {
1012 		prt_printf(&p, "\n  allowing incompatible features above ");
1013 		bch2_version_to_text(&p, c->sb.version_incompat_allowed);
1014 	}
1015 
1016 	bch_info(c, "%s", p.buf);
1017 	printbuf_exit(&p);
1018 }
1019 
bch2_fs_may_start(struct bch_fs * c)1020 static bool bch2_fs_may_start(struct bch_fs *c)
1021 {
1022 	struct bch_dev *ca;
1023 	unsigned i, flags = 0;
1024 
1025 	if (c->opts.very_degraded)
1026 		flags |= BCH_FORCE_IF_DEGRADED|BCH_FORCE_IF_LOST;
1027 
1028 	if (c->opts.degraded)
1029 		flags |= BCH_FORCE_IF_DEGRADED;
1030 
1031 	if (!c->opts.degraded &&
1032 	    !c->opts.very_degraded) {
1033 		mutex_lock(&c->sb_lock);
1034 
1035 		for (i = 0; i < c->disk_sb.sb->nr_devices; i++) {
1036 			if (!bch2_member_exists(c->disk_sb.sb, i))
1037 				continue;
1038 
1039 			ca = bch2_dev_locked(c, i);
1040 
1041 			if (!bch2_dev_is_online(ca) &&
1042 			    (ca->mi.state == BCH_MEMBER_STATE_rw ||
1043 			     ca->mi.state == BCH_MEMBER_STATE_ro)) {
1044 				mutex_unlock(&c->sb_lock);
1045 				return false;
1046 			}
1047 		}
1048 		mutex_unlock(&c->sb_lock);
1049 	}
1050 
1051 	return bch2_have_enough_devs(c, bch2_online_devs(c), flags, true);
1052 }
1053 
bch2_fs_start(struct bch_fs * c)1054 int bch2_fs_start(struct bch_fs *c)
1055 {
1056 	time64_t now = ktime_get_real_seconds();
1057 	int ret = 0;
1058 
1059 	print_mount_opts(c);
1060 
1061 	if (!bch2_fs_may_start(c))
1062 		return -BCH_ERR_insufficient_devices_to_start;
1063 
1064 	down_write(&c->state_lock);
1065 	mutex_lock(&c->sb_lock);
1066 
1067 	BUG_ON(test_bit(BCH_FS_started, &c->flags));
1068 
1069 	if (!bch2_sb_field_get_minsize(&c->disk_sb, ext,
1070 			sizeof(struct bch_sb_field_ext) / sizeof(u64))) {
1071 		mutex_unlock(&c->sb_lock);
1072 		up_write(&c->state_lock);
1073 		ret = -BCH_ERR_ENOSPC_sb;
1074 		goto err;
1075 	}
1076 
1077 	ret = bch2_sb_members_v2_init(c);
1078 	if (ret) {
1079 		mutex_unlock(&c->sb_lock);
1080 		up_write(&c->state_lock);
1081 		goto err;
1082 	}
1083 
1084 	for_each_online_member(c, ca)
1085 		bch2_members_v2_get_mut(c->disk_sb.sb, ca->dev_idx)->last_mount = cpu_to_le64(now);
1086 
1087 	mutex_unlock(&c->sb_lock);
1088 
1089 	for_each_rw_member(c, ca)
1090 		bch2_dev_allocator_add(c, ca);
1091 	bch2_recalc_capacity(c);
1092 	up_write(&c->state_lock);
1093 
1094 	c->recovery_task = current;
1095 	ret = BCH_SB_INITIALIZED(c->disk_sb.sb)
1096 		? bch2_fs_recovery(c)
1097 		: bch2_fs_initialize(c);
1098 	c->recovery_task = NULL;
1099 
1100 	if (ret)
1101 		goto err;
1102 
1103 	ret = bch2_opts_check_may_set(c);
1104 	if (ret)
1105 		goto err;
1106 
1107 	if (bch2_fs_init_fault("fs_start")) {
1108 		ret = -BCH_ERR_injected_fs_start;
1109 		goto err;
1110 	}
1111 
1112 	set_bit(BCH_FS_started, &c->flags);
1113 	wake_up(&c->ro_ref_wait);
1114 
1115 	down_write(&c->state_lock);
1116 	if (c->opts.read_only)
1117 		bch2_fs_read_only(c);
1118 	else if (!test_bit(BCH_FS_rw, &c->flags))
1119 		ret = bch2_fs_read_write(c);
1120 	up_write(&c->state_lock);
1121 
1122 err:
1123 	if (ret)
1124 		bch_err_msg(c, ret, "starting filesystem");
1125 	else
1126 		bch_verbose(c, "done starting filesystem");
1127 	return ret;
1128 }
1129 
bch2_dev_may_add(struct bch_sb * sb,struct bch_fs * c)1130 static int bch2_dev_may_add(struct bch_sb *sb, struct bch_fs *c)
1131 {
1132 	struct bch_member m = bch2_sb_member_get(sb, sb->dev_idx);
1133 
1134 	if (le16_to_cpu(sb->block_size) != block_sectors(c))
1135 		return -BCH_ERR_mismatched_block_size;
1136 
1137 	if (le16_to_cpu(m.bucket_size) <
1138 	    BCH_SB_BTREE_NODE_SIZE(c->disk_sb.sb))
1139 		return -BCH_ERR_bucket_size_too_small;
1140 
1141 	return 0;
1142 }
1143 
bch2_dev_in_fs(struct bch_sb_handle * fs,struct bch_sb_handle * sb,struct bch_opts * opts)1144 static int bch2_dev_in_fs(struct bch_sb_handle *fs,
1145 			  struct bch_sb_handle *sb,
1146 			  struct bch_opts *opts)
1147 {
1148 	if (fs == sb)
1149 		return 0;
1150 
1151 	if (!uuid_equal(&fs->sb->uuid, &sb->sb->uuid))
1152 		return -BCH_ERR_device_not_a_member_of_filesystem;
1153 
1154 	if (!bch2_member_exists(fs->sb, sb->sb->dev_idx))
1155 		return -BCH_ERR_device_has_been_removed;
1156 
1157 	if (fs->sb->block_size != sb->sb->block_size)
1158 		return -BCH_ERR_mismatched_block_size;
1159 
1160 	if (le16_to_cpu(fs->sb->version) < bcachefs_metadata_version_member_seq ||
1161 	    le16_to_cpu(sb->sb->version) < bcachefs_metadata_version_member_seq)
1162 		return 0;
1163 
1164 	if (fs->sb->seq == sb->sb->seq &&
1165 	    fs->sb->write_time != sb->sb->write_time) {
1166 		struct printbuf buf = PRINTBUF;
1167 
1168 		prt_str(&buf, "Split brain detected between ");
1169 		prt_bdevname(&buf, sb->bdev);
1170 		prt_str(&buf, " and ");
1171 		prt_bdevname(&buf, fs->bdev);
1172 		prt_char(&buf, ':');
1173 		prt_newline(&buf);
1174 		prt_printf(&buf, "seq=%llu but write_time different, got", le64_to_cpu(sb->sb->seq));
1175 		prt_newline(&buf);
1176 
1177 		prt_bdevname(&buf, fs->bdev);
1178 		prt_char(&buf, ' ');
1179 		bch2_prt_datetime(&buf, le64_to_cpu(fs->sb->write_time));
1180 		prt_newline(&buf);
1181 
1182 		prt_bdevname(&buf, sb->bdev);
1183 		prt_char(&buf, ' ');
1184 		bch2_prt_datetime(&buf, le64_to_cpu(sb->sb->write_time));
1185 		prt_newline(&buf);
1186 
1187 		if (!opts->no_splitbrain_check)
1188 			prt_printf(&buf, "Not using older sb");
1189 
1190 		pr_err("%s", buf.buf);
1191 		printbuf_exit(&buf);
1192 
1193 		if (!opts->no_splitbrain_check)
1194 			return -BCH_ERR_device_splitbrain;
1195 	}
1196 
1197 	struct bch_member m = bch2_sb_member_get(fs->sb, sb->sb->dev_idx);
1198 	u64 seq_from_fs		= le64_to_cpu(m.seq);
1199 	u64 seq_from_member	= le64_to_cpu(sb->sb->seq);
1200 
1201 	if (seq_from_fs && seq_from_fs < seq_from_member) {
1202 		struct printbuf buf = PRINTBUF;
1203 
1204 		prt_str(&buf, "Split brain detected between ");
1205 		prt_bdevname(&buf, sb->bdev);
1206 		prt_str(&buf, " and ");
1207 		prt_bdevname(&buf, fs->bdev);
1208 		prt_char(&buf, ':');
1209 		prt_newline(&buf);
1210 
1211 		prt_bdevname(&buf, fs->bdev);
1212 		prt_str(&buf, " believes seq of ");
1213 		prt_bdevname(&buf, sb->bdev);
1214 		prt_printf(&buf, " to be %llu, but ", seq_from_fs);
1215 		prt_bdevname(&buf, sb->bdev);
1216 		prt_printf(&buf, " has %llu\n", seq_from_member);
1217 
1218 		if (!opts->no_splitbrain_check) {
1219 			prt_str(&buf, "Not using ");
1220 			prt_bdevname(&buf, sb->bdev);
1221 		}
1222 
1223 		pr_err("%s", buf.buf);
1224 		printbuf_exit(&buf);
1225 
1226 		if (!opts->no_splitbrain_check)
1227 			return -BCH_ERR_device_splitbrain;
1228 	}
1229 
1230 	return 0;
1231 }
1232 
1233 /* Device startup/shutdown: */
1234 
bch2_dev_io_ref_stop(struct bch_dev * ca,int rw)1235 static void bch2_dev_io_ref_stop(struct bch_dev *ca, int rw)
1236 {
1237 	if (!percpu_ref_is_zero(&ca->io_ref[rw])) {
1238 		reinit_completion(&ca->io_ref_completion[rw]);
1239 		percpu_ref_kill(&ca->io_ref[rw]);
1240 		wait_for_completion(&ca->io_ref_completion[rw]);
1241 	}
1242 }
1243 
bch2_dev_release(struct kobject * kobj)1244 static void bch2_dev_release(struct kobject *kobj)
1245 {
1246 	struct bch_dev *ca = container_of(kobj, struct bch_dev, kobj);
1247 
1248 	kfree(ca);
1249 }
1250 
bch2_dev_free(struct bch_dev * ca)1251 static void bch2_dev_free(struct bch_dev *ca)
1252 {
1253 	WARN_ON(!percpu_ref_is_zero(&ca->io_ref[WRITE]));
1254 	WARN_ON(!percpu_ref_is_zero(&ca->io_ref[READ]));
1255 
1256 	cancel_work_sync(&ca->io_error_work);
1257 
1258 	bch2_dev_unlink(ca);
1259 
1260 	if (ca->kobj.state_in_sysfs)
1261 		kobject_del(&ca->kobj);
1262 
1263 	bch2_free_super(&ca->disk_sb);
1264 	bch2_dev_allocator_background_exit(ca);
1265 	bch2_dev_journal_exit(ca);
1266 
1267 	free_percpu(ca->io_done);
1268 	bch2_dev_buckets_free(ca);
1269 	kfree(ca->sb_read_scratch);
1270 
1271 	bch2_time_stats_quantiles_exit(&ca->io_latency[WRITE]);
1272 	bch2_time_stats_quantiles_exit(&ca->io_latency[READ]);
1273 
1274 	percpu_ref_exit(&ca->io_ref[WRITE]);
1275 	percpu_ref_exit(&ca->io_ref[READ]);
1276 #ifndef CONFIG_BCACHEFS_DEBUG
1277 	percpu_ref_exit(&ca->ref);
1278 #endif
1279 	kobject_put(&ca->kobj);
1280 }
1281 
__bch2_dev_offline(struct bch_fs * c,struct bch_dev * ca)1282 static void __bch2_dev_offline(struct bch_fs *c, struct bch_dev *ca)
1283 {
1284 
1285 	lockdep_assert_held(&c->state_lock);
1286 
1287 	if (percpu_ref_is_zero(&ca->io_ref[READ]))
1288 		return;
1289 
1290 	__bch2_dev_read_only(c, ca);
1291 
1292 	bch2_dev_io_ref_stop(ca, READ);
1293 
1294 	bch2_dev_unlink(ca);
1295 
1296 	bch2_free_super(&ca->disk_sb);
1297 	bch2_dev_journal_exit(ca);
1298 }
1299 
1300 #ifndef CONFIG_BCACHEFS_DEBUG
bch2_dev_ref_complete(struct percpu_ref * ref)1301 static void bch2_dev_ref_complete(struct percpu_ref *ref)
1302 {
1303 	struct bch_dev *ca = container_of(ref, struct bch_dev, ref);
1304 
1305 	complete(&ca->ref_completion);
1306 }
1307 #endif
1308 
bch2_dev_io_ref_read_complete(struct percpu_ref * ref)1309 static void bch2_dev_io_ref_read_complete(struct percpu_ref *ref)
1310 {
1311 	struct bch_dev *ca = container_of(ref, struct bch_dev, io_ref[READ]);
1312 
1313 	complete(&ca->io_ref_completion[READ]);
1314 }
1315 
bch2_dev_io_ref_write_complete(struct percpu_ref * ref)1316 static void bch2_dev_io_ref_write_complete(struct percpu_ref *ref)
1317 {
1318 	struct bch_dev *ca = container_of(ref, struct bch_dev, io_ref[WRITE]);
1319 
1320 	complete(&ca->io_ref_completion[WRITE]);
1321 }
1322 
bch2_dev_unlink(struct bch_dev * ca)1323 static void bch2_dev_unlink(struct bch_dev *ca)
1324 {
1325 	struct kobject *b;
1326 
1327 	/*
1328 	 * This is racy w.r.t. the underlying block device being hot-removed,
1329 	 * which removes it from sysfs.
1330 	 *
1331 	 * It'd be lovely if we had a way to handle this race, but the sysfs
1332 	 * code doesn't appear to provide a good method and block/holder.c is
1333 	 * susceptible as well:
1334 	 */
1335 	if (ca->kobj.state_in_sysfs &&
1336 	    ca->disk_sb.bdev &&
1337 	    (b = bdev_kobj(ca->disk_sb.bdev))->state_in_sysfs) {
1338 		sysfs_remove_link(b, "bcachefs");
1339 		sysfs_remove_link(&ca->kobj, "block");
1340 	}
1341 }
1342 
bch2_dev_sysfs_online(struct bch_fs * c,struct bch_dev * ca)1343 static int bch2_dev_sysfs_online(struct bch_fs *c, struct bch_dev *ca)
1344 {
1345 	int ret;
1346 
1347 	if (!c->kobj.state_in_sysfs)
1348 		return 0;
1349 
1350 	if (!ca->kobj.state_in_sysfs) {
1351 		ret =   kobject_add(&ca->kobj, &c->kobj, "dev-%u", ca->dev_idx) ?:
1352 			bch2_opts_create_sysfs_files(&ca->kobj, OPT_DEVICE);
1353 		if (ret)
1354 			return ret;
1355 	}
1356 
1357 	if (ca->disk_sb.bdev) {
1358 		struct kobject *block = bdev_kobj(ca->disk_sb.bdev);
1359 
1360 		ret = sysfs_create_link(block, &ca->kobj, "bcachefs");
1361 		if (ret)
1362 			return ret;
1363 
1364 		ret = sysfs_create_link(&ca->kobj, block, "block");
1365 		if (ret)
1366 			return ret;
1367 	}
1368 
1369 	return 0;
1370 }
1371 
__bch2_dev_alloc(struct bch_fs * c,struct bch_member * member)1372 static struct bch_dev *__bch2_dev_alloc(struct bch_fs *c,
1373 					struct bch_member *member)
1374 {
1375 	struct bch_dev *ca;
1376 	unsigned i;
1377 
1378 	ca = kzalloc(sizeof(*ca), GFP_KERNEL);
1379 	if (!ca)
1380 		return NULL;
1381 
1382 	kobject_init(&ca->kobj, &bch2_dev_ktype);
1383 	init_completion(&ca->ref_completion);
1384 	init_completion(&ca->io_ref_completion[READ]);
1385 	init_completion(&ca->io_ref_completion[WRITE]);
1386 
1387 	INIT_WORK(&ca->io_error_work, bch2_io_error_work);
1388 
1389 	bch2_time_stats_quantiles_init(&ca->io_latency[READ]);
1390 	bch2_time_stats_quantiles_init(&ca->io_latency[WRITE]);
1391 
1392 	ca->mi = bch2_mi_to_cpu(member);
1393 
1394 	for (i = 0; i < ARRAY_SIZE(member->errors); i++)
1395 		atomic64_set(&ca->errors[i], le64_to_cpu(member->errors[i]));
1396 
1397 	ca->uuid = member->uuid;
1398 
1399 	ca->nr_btree_reserve = DIV_ROUND_UP(BTREE_NODE_RESERVE,
1400 			     ca->mi.bucket_size / btree_sectors(c));
1401 
1402 #ifndef CONFIG_BCACHEFS_DEBUG
1403 	if (percpu_ref_init(&ca->ref, bch2_dev_ref_complete, 0, GFP_KERNEL))
1404 		goto err;
1405 #else
1406 	atomic_long_set(&ca->ref, 1);
1407 #endif
1408 
1409 	bch2_dev_allocator_background_init(ca);
1410 
1411 	if (percpu_ref_init(&ca->io_ref[READ], bch2_dev_io_ref_read_complete,
1412 			    PERCPU_REF_INIT_DEAD, GFP_KERNEL) ||
1413 	    percpu_ref_init(&ca->io_ref[WRITE], bch2_dev_io_ref_write_complete,
1414 			    PERCPU_REF_INIT_DEAD, GFP_KERNEL) ||
1415 	    !(ca->sb_read_scratch = kmalloc(BCH_SB_READ_SCRATCH_BUF_SIZE, GFP_KERNEL)) ||
1416 	    bch2_dev_buckets_alloc(c, ca) ||
1417 	    !(ca->io_done	= alloc_percpu(*ca->io_done)))
1418 		goto err;
1419 
1420 	return ca;
1421 err:
1422 	bch2_dev_free(ca);
1423 	return NULL;
1424 }
1425 
bch2_dev_attach(struct bch_fs * c,struct bch_dev * ca,unsigned dev_idx)1426 static void bch2_dev_attach(struct bch_fs *c, struct bch_dev *ca,
1427 			    unsigned dev_idx)
1428 {
1429 	ca->dev_idx = dev_idx;
1430 	__set_bit(ca->dev_idx, ca->self.d);
1431 	scnprintf(ca->name, sizeof(ca->name), "dev-%u", dev_idx);
1432 
1433 	ca->fs = c;
1434 	rcu_assign_pointer(c->devs[ca->dev_idx], ca);
1435 
1436 	if (bch2_dev_sysfs_online(c, ca))
1437 		pr_warn("error creating sysfs objects");
1438 }
1439 
bch2_dev_alloc(struct bch_fs * c,unsigned dev_idx)1440 static int bch2_dev_alloc(struct bch_fs *c, unsigned dev_idx)
1441 {
1442 	struct bch_member member = bch2_sb_member_get(c->disk_sb.sb, dev_idx);
1443 	struct bch_dev *ca = NULL;
1444 
1445 	if (bch2_fs_init_fault("dev_alloc"))
1446 		goto err;
1447 
1448 	ca = __bch2_dev_alloc(c, &member);
1449 	if (!ca)
1450 		goto err;
1451 
1452 	ca->fs = c;
1453 
1454 	bch2_dev_attach(c, ca, dev_idx);
1455 	return 0;
1456 err:
1457 	return -BCH_ERR_ENOMEM_dev_alloc;
1458 }
1459 
__bch2_dev_attach_bdev(struct bch_dev * ca,struct bch_sb_handle * sb)1460 static int __bch2_dev_attach_bdev(struct bch_dev *ca, struct bch_sb_handle *sb)
1461 {
1462 	unsigned ret;
1463 
1464 	if (bch2_dev_is_online(ca)) {
1465 		bch_err(ca, "already have device online in slot %u",
1466 			sb->sb->dev_idx);
1467 		return -BCH_ERR_device_already_online;
1468 	}
1469 
1470 	if (get_capacity(sb->bdev->bd_disk) <
1471 	    ca->mi.bucket_size * ca->mi.nbuckets) {
1472 		bch_err(ca, "cannot online: device too small");
1473 		return -BCH_ERR_device_size_too_small;
1474 	}
1475 
1476 	BUG_ON(!percpu_ref_is_zero(&ca->io_ref[READ]));
1477 	BUG_ON(!percpu_ref_is_zero(&ca->io_ref[WRITE]));
1478 
1479 	ret = bch2_dev_journal_init(ca, sb->sb);
1480 	if (ret)
1481 		return ret;
1482 
1483 	/* Commit: */
1484 	ca->disk_sb = *sb;
1485 	memset(sb, 0, sizeof(*sb));
1486 
1487 	/*
1488 	 * Stash pointer to the filesystem for blk_holder_ops - note that once
1489 	 * attached to a filesystem, we will always close the block device
1490 	 * before tearing down the filesystem object.
1491 	 */
1492 	ca->disk_sb.holder->c = ca->fs;
1493 
1494 	ca->dev = ca->disk_sb.bdev->bd_dev;
1495 
1496 	percpu_ref_reinit(&ca->io_ref[READ]);
1497 
1498 	return 0;
1499 }
1500 
bch2_dev_attach_bdev(struct bch_fs * c,struct bch_sb_handle * sb)1501 static int bch2_dev_attach_bdev(struct bch_fs *c, struct bch_sb_handle *sb)
1502 {
1503 	struct bch_dev *ca;
1504 	int ret;
1505 
1506 	lockdep_assert_held(&c->state_lock);
1507 
1508 	if (le64_to_cpu(sb->sb->seq) >
1509 	    le64_to_cpu(c->disk_sb.sb->seq))
1510 		bch2_sb_to_fs(c, sb->sb);
1511 
1512 	BUG_ON(!bch2_dev_exists(c, sb->sb->dev_idx));
1513 
1514 	ca = bch2_dev_locked(c, sb->sb->dev_idx);
1515 
1516 	ret = __bch2_dev_attach_bdev(ca, sb);
1517 	if (ret)
1518 		return ret;
1519 
1520 	bch2_dev_sysfs_online(c, ca);
1521 
1522 	struct printbuf name = PRINTBUF;
1523 	prt_bdevname(&name, ca->disk_sb.bdev);
1524 
1525 	if (c->sb.nr_devices == 1)
1526 		strscpy(c->name, name.buf, sizeof(c->name));
1527 	strscpy(ca->name, name.buf, sizeof(ca->name));
1528 
1529 	printbuf_exit(&name);
1530 
1531 	bch2_rebalance_wakeup(c);
1532 	return 0;
1533 }
1534 
1535 /* Device management: */
1536 
1537 /*
1538  * Note: this function is also used by the error paths - when a particular
1539  * device sees an error, we call it to determine whether we can just set the
1540  * device RO, or - if this function returns false - we'll set the whole
1541  * filesystem RO:
1542  *
1543  * XXX: maybe we should be more explicit about whether we're changing state
1544  * because we got an error or what have you?
1545  */
bch2_dev_state_allowed(struct bch_fs * c,struct bch_dev * ca,enum bch_member_state new_state,int flags)1546 bool bch2_dev_state_allowed(struct bch_fs *c, struct bch_dev *ca,
1547 			    enum bch_member_state new_state, int flags)
1548 {
1549 	struct bch_devs_mask new_online_devs;
1550 	int nr_rw = 0, required;
1551 
1552 	lockdep_assert_held(&c->state_lock);
1553 
1554 	switch (new_state) {
1555 	case BCH_MEMBER_STATE_rw:
1556 		return true;
1557 	case BCH_MEMBER_STATE_ro:
1558 		if (ca->mi.state != BCH_MEMBER_STATE_rw)
1559 			return true;
1560 
1561 		/* do we have enough devices to write to?  */
1562 		for_each_member_device(c, ca2)
1563 			if (ca2 != ca)
1564 				nr_rw += ca2->mi.state == BCH_MEMBER_STATE_rw;
1565 
1566 		required = max(!(flags & BCH_FORCE_IF_METADATA_DEGRADED)
1567 			       ? c->opts.metadata_replicas
1568 			       : metadata_replicas_required(c),
1569 			       !(flags & BCH_FORCE_IF_DATA_DEGRADED)
1570 			       ? c->opts.data_replicas
1571 			       : data_replicas_required(c));
1572 
1573 		return nr_rw >= required;
1574 	case BCH_MEMBER_STATE_failed:
1575 	case BCH_MEMBER_STATE_spare:
1576 		if (ca->mi.state != BCH_MEMBER_STATE_rw &&
1577 		    ca->mi.state != BCH_MEMBER_STATE_ro)
1578 			return true;
1579 
1580 		/* do we have enough devices to read from?  */
1581 		new_online_devs = bch2_online_devs(c);
1582 		__clear_bit(ca->dev_idx, new_online_devs.d);
1583 
1584 		return bch2_have_enough_devs(c, new_online_devs, flags, false);
1585 	default:
1586 		BUG();
1587 	}
1588 }
1589 
__bch2_dev_read_only(struct bch_fs * c,struct bch_dev * ca)1590 static void __bch2_dev_read_only(struct bch_fs *c, struct bch_dev *ca)
1591 {
1592 	bch2_dev_io_ref_stop(ca, WRITE);
1593 
1594 	/*
1595 	 * The allocator thread itself allocates btree nodes, so stop it first:
1596 	 */
1597 	bch2_dev_allocator_remove(c, ca);
1598 	bch2_recalc_capacity(c);
1599 	bch2_dev_journal_stop(&c->journal, ca);
1600 }
1601 
__bch2_dev_read_write(struct bch_fs * c,struct bch_dev * ca)1602 static void __bch2_dev_read_write(struct bch_fs *c, struct bch_dev *ca)
1603 {
1604 	lockdep_assert_held(&c->state_lock);
1605 
1606 	BUG_ON(ca->mi.state != BCH_MEMBER_STATE_rw);
1607 
1608 	bch2_dev_allocator_add(c, ca);
1609 	bch2_recalc_capacity(c);
1610 
1611 	if (percpu_ref_is_zero(&ca->io_ref[WRITE]))
1612 		percpu_ref_reinit(&ca->io_ref[WRITE]);
1613 
1614 	bch2_dev_do_discards(ca);
1615 }
1616 
__bch2_dev_set_state(struct bch_fs * c,struct bch_dev * ca,enum bch_member_state new_state,int flags)1617 int __bch2_dev_set_state(struct bch_fs *c, struct bch_dev *ca,
1618 			 enum bch_member_state new_state, int flags)
1619 {
1620 	struct bch_member *m;
1621 	int ret = 0;
1622 
1623 	if (ca->mi.state == new_state)
1624 		return 0;
1625 
1626 	if (!bch2_dev_state_allowed(c, ca, new_state, flags))
1627 		return -BCH_ERR_device_state_not_allowed;
1628 
1629 	if (new_state != BCH_MEMBER_STATE_rw)
1630 		__bch2_dev_read_only(c, ca);
1631 
1632 	bch_notice(ca, "%s", bch2_member_states[new_state]);
1633 
1634 	mutex_lock(&c->sb_lock);
1635 	m = bch2_members_v2_get_mut(c->disk_sb.sb, ca->dev_idx);
1636 	SET_BCH_MEMBER_STATE(m, new_state);
1637 	bch2_write_super(c);
1638 	mutex_unlock(&c->sb_lock);
1639 
1640 	if (new_state == BCH_MEMBER_STATE_rw)
1641 		__bch2_dev_read_write(c, ca);
1642 
1643 	bch2_rebalance_wakeup(c);
1644 
1645 	return ret;
1646 }
1647 
bch2_dev_set_state(struct bch_fs * c,struct bch_dev * ca,enum bch_member_state new_state,int flags)1648 int bch2_dev_set_state(struct bch_fs *c, struct bch_dev *ca,
1649 		       enum bch_member_state new_state, int flags)
1650 {
1651 	int ret;
1652 
1653 	down_write(&c->state_lock);
1654 	ret = __bch2_dev_set_state(c, ca, new_state, flags);
1655 	up_write(&c->state_lock);
1656 
1657 	return ret;
1658 }
1659 
1660 /* Device add/removal: */
1661 
bch2_dev_remove(struct bch_fs * c,struct bch_dev * ca,int flags)1662 int bch2_dev_remove(struct bch_fs *c, struct bch_dev *ca, int flags)
1663 {
1664 	struct bch_member *m;
1665 	unsigned dev_idx = ca->dev_idx, data;
1666 	int ret;
1667 
1668 	down_write(&c->state_lock);
1669 
1670 	/*
1671 	 * We consume a reference to ca->ref, regardless of whether we succeed
1672 	 * or fail:
1673 	 */
1674 	bch2_dev_put(ca);
1675 
1676 	if (!bch2_dev_state_allowed(c, ca, BCH_MEMBER_STATE_failed, flags)) {
1677 		bch_err(ca, "Cannot remove without losing data");
1678 		ret = -BCH_ERR_device_state_not_allowed;
1679 		goto err;
1680 	}
1681 
1682 	__bch2_dev_read_only(c, ca);
1683 
1684 	ret = bch2_dev_data_drop(c, ca->dev_idx, flags);
1685 	bch_err_msg(ca, ret, "bch2_dev_data_drop()");
1686 	if (ret)
1687 		goto err;
1688 
1689 	ret = bch2_dev_remove_alloc(c, ca);
1690 	bch_err_msg(ca, ret, "bch2_dev_remove_alloc()");
1691 	if (ret)
1692 		goto err;
1693 
1694 	/*
1695 	 * We need to flush the entire journal to get rid of keys that reference
1696 	 * the device being removed before removing the superblock entry
1697 	 */
1698 	bch2_journal_flush_all_pins(&c->journal);
1699 
1700 	/*
1701 	 * this is really just needed for the bch2_replicas_gc_(start|end)
1702 	 * calls, and could be cleaned up:
1703 	 */
1704 	ret = bch2_journal_flush_device_pins(&c->journal, ca->dev_idx);
1705 	bch_err_msg(ca, ret, "bch2_journal_flush_device_pins()");
1706 	if (ret)
1707 		goto err;
1708 
1709 	ret = bch2_journal_flush(&c->journal);
1710 	bch_err_msg(ca, ret, "bch2_journal_flush()");
1711 	if (ret)
1712 		goto err;
1713 
1714 	ret = bch2_replicas_gc2(c);
1715 	bch_err_msg(ca, ret, "bch2_replicas_gc2()");
1716 	if (ret)
1717 		goto err;
1718 
1719 	data = bch2_dev_has_data(c, ca);
1720 	if (data) {
1721 		struct printbuf data_has = PRINTBUF;
1722 
1723 		prt_bitflags(&data_has, __bch2_data_types, data);
1724 		bch_err(ca, "Remove failed, still has data (%s)", data_has.buf);
1725 		printbuf_exit(&data_has);
1726 		ret = -EBUSY;
1727 		goto err;
1728 	}
1729 
1730 	__bch2_dev_offline(c, ca);
1731 
1732 	mutex_lock(&c->sb_lock);
1733 	rcu_assign_pointer(c->devs[ca->dev_idx], NULL);
1734 	mutex_unlock(&c->sb_lock);
1735 
1736 #ifndef CONFIG_BCACHEFS_DEBUG
1737 	percpu_ref_kill(&ca->ref);
1738 #else
1739 	ca->dying = true;
1740 	bch2_dev_put(ca);
1741 #endif
1742 	wait_for_completion(&ca->ref_completion);
1743 
1744 	bch2_dev_free(ca);
1745 
1746 	/*
1747 	 * Free this device's slot in the bch_member array - all pointers to
1748 	 * this device must be gone:
1749 	 */
1750 	mutex_lock(&c->sb_lock);
1751 	m = bch2_members_v2_get_mut(c->disk_sb.sb, dev_idx);
1752 	memset(&m->uuid, 0, sizeof(m->uuid));
1753 
1754 	bch2_write_super(c);
1755 
1756 	mutex_unlock(&c->sb_lock);
1757 	up_write(&c->state_lock);
1758 	return 0;
1759 err:
1760 	if (test_bit(BCH_FS_rw, &c->flags) &&
1761 	    ca->mi.state == BCH_MEMBER_STATE_rw &&
1762 	    !percpu_ref_is_zero(&ca->io_ref[READ]))
1763 		__bch2_dev_read_write(c, ca);
1764 	up_write(&c->state_lock);
1765 	return ret;
1766 }
1767 
1768 /* Add new device to running filesystem: */
bch2_dev_add(struct bch_fs * c,const char * path)1769 int bch2_dev_add(struct bch_fs *c, const char *path)
1770 {
1771 	struct bch_opts opts = bch2_opts_empty();
1772 	struct bch_sb_handle sb;
1773 	struct bch_dev *ca = NULL;
1774 	struct printbuf errbuf = PRINTBUF;
1775 	struct printbuf label = PRINTBUF;
1776 	int ret;
1777 
1778 	ret = bch2_read_super(path, &opts, &sb);
1779 	bch_err_msg(c, ret, "reading super");
1780 	if (ret)
1781 		goto err;
1782 
1783 	struct bch_member dev_mi = bch2_sb_member_get(sb.sb, sb.sb->dev_idx);
1784 
1785 	if (BCH_MEMBER_GROUP(&dev_mi)) {
1786 		bch2_disk_path_to_text_sb(&label, sb.sb, BCH_MEMBER_GROUP(&dev_mi) - 1);
1787 		if (label.allocation_failure) {
1788 			ret = -ENOMEM;
1789 			goto err;
1790 		}
1791 	}
1792 
1793 	ret = bch2_dev_may_add(sb.sb, c);
1794 	if (ret)
1795 		goto err;
1796 
1797 	ca = __bch2_dev_alloc(c, &dev_mi);
1798 	if (!ca) {
1799 		ret = -ENOMEM;
1800 		goto err;
1801 	}
1802 
1803 	ret = __bch2_dev_attach_bdev(ca, &sb);
1804 	if (ret)
1805 		goto err;
1806 
1807 	down_write(&c->state_lock);
1808 	mutex_lock(&c->sb_lock);
1809 
1810 	ret = bch2_sb_from_fs(c, ca);
1811 	bch_err_msg(c, ret, "setting up new superblock");
1812 	if (ret)
1813 		goto err_unlock;
1814 
1815 	if (dynamic_fault("bcachefs:add:no_slot"))
1816 		goto err_unlock;
1817 
1818 	ret = bch2_sb_member_alloc(c);
1819 	if (ret < 0) {
1820 		bch_err_msg(c, ret, "setting up new superblock");
1821 		goto err_unlock;
1822 	}
1823 	unsigned dev_idx = ret;
1824 
1825 	/* success: */
1826 
1827 	dev_mi.last_mount = cpu_to_le64(ktime_get_real_seconds());
1828 	*bch2_members_v2_get_mut(c->disk_sb.sb, dev_idx) = dev_mi;
1829 
1830 	ca->disk_sb.sb->dev_idx	= dev_idx;
1831 	bch2_dev_attach(c, ca, dev_idx);
1832 
1833 	if (BCH_MEMBER_GROUP(&dev_mi)) {
1834 		ret = __bch2_dev_group_set(c, ca, label.buf);
1835 		bch_err_msg(c, ret, "creating new label");
1836 		if (ret)
1837 			goto err_unlock;
1838 	}
1839 
1840 	bch2_write_super(c);
1841 	mutex_unlock(&c->sb_lock);
1842 
1843 	ret = bch2_dev_usage_init(ca, false);
1844 	if (ret)
1845 		goto err_late;
1846 
1847 	ret = bch2_trans_mark_dev_sb(c, ca, BTREE_TRIGGER_transactional);
1848 	bch_err_msg(ca, ret, "marking new superblock");
1849 	if (ret)
1850 		goto err_late;
1851 
1852 	ret = bch2_fs_freespace_init(c);
1853 	bch_err_msg(ca, ret, "initializing free space");
1854 	if (ret)
1855 		goto err_late;
1856 
1857 	if (ca->mi.state == BCH_MEMBER_STATE_rw)
1858 		__bch2_dev_read_write(c, ca);
1859 
1860 	ret = bch2_dev_journal_alloc(ca, false);
1861 	bch_err_msg(c, ret, "allocating journal");
1862 	if (ret)
1863 		goto err_late;
1864 
1865 	up_write(&c->state_lock);
1866 out:
1867 	printbuf_exit(&label);
1868 	printbuf_exit(&errbuf);
1869 	bch_err_fn(c, ret);
1870 	return ret;
1871 
1872 err_unlock:
1873 	mutex_unlock(&c->sb_lock);
1874 	up_write(&c->state_lock);
1875 err:
1876 	if (ca)
1877 		bch2_dev_free(ca);
1878 	bch2_free_super(&sb);
1879 	goto out;
1880 err_late:
1881 	up_write(&c->state_lock);
1882 	ca = NULL;
1883 	goto err;
1884 }
1885 
1886 /* Hot add existing device to running filesystem: */
bch2_dev_online(struct bch_fs * c,const char * path)1887 int bch2_dev_online(struct bch_fs *c, const char *path)
1888 {
1889 	struct bch_opts opts = bch2_opts_empty();
1890 	struct bch_sb_handle sb = { NULL };
1891 	struct bch_dev *ca;
1892 	unsigned dev_idx;
1893 	int ret;
1894 
1895 	down_write(&c->state_lock);
1896 
1897 	ret = bch2_read_super(path, &opts, &sb);
1898 	if (ret) {
1899 		up_write(&c->state_lock);
1900 		return ret;
1901 	}
1902 
1903 	dev_idx = sb.sb->dev_idx;
1904 
1905 	ret = bch2_dev_in_fs(&c->disk_sb, &sb, &c->opts);
1906 	bch_err_msg(c, ret, "bringing %s online", path);
1907 	if (ret)
1908 		goto err;
1909 
1910 	ret = bch2_dev_attach_bdev(c, &sb);
1911 	if (ret)
1912 		goto err;
1913 
1914 	ca = bch2_dev_locked(c, dev_idx);
1915 
1916 	ret = bch2_trans_mark_dev_sb(c, ca, BTREE_TRIGGER_transactional);
1917 	bch_err_msg(c, ret, "bringing %s online: error from bch2_trans_mark_dev_sb", path);
1918 	if (ret)
1919 		goto err;
1920 
1921 	if (ca->mi.state == BCH_MEMBER_STATE_rw)
1922 		__bch2_dev_read_write(c, ca);
1923 
1924 	if (!ca->mi.freespace_initialized) {
1925 		ret = bch2_dev_freespace_init(c, ca, 0, ca->mi.nbuckets);
1926 		bch_err_msg(ca, ret, "initializing free space");
1927 		if (ret)
1928 			goto err;
1929 	}
1930 
1931 	if (!ca->journal.nr) {
1932 		ret = bch2_dev_journal_alloc(ca, false);
1933 		bch_err_msg(ca, ret, "allocating journal");
1934 		if (ret)
1935 			goto err;
1936 	}
1937 
1938 	mutex_lock(&c->sb_lock);
1939 	bch2_members_v2_get_mut(c->disk_sb.sb, ca->dev_idx)->last_mount =
1940 		cpu_to_le64(ktime_get_real_seconds());
1941 	bch2_write_super(c);
1942 	mutex_unlock(&c->sb_lock);
1943 
1944 	up_write(&c->state_lock);
1945 	return 0;
1946 err:
1947 	up_write(&c->state_lock);
1948 	bch2_free_super(&sb);
1949 	return ret;
1950 }
1951 
bch2_dev_offline(struct bch_fs * c,struct bch_dev * ca,int flags)1952 int bch2_dev_offline(struct bch_fs *c, struct bch_dev *ca, int flags)
1953 {
1954 	down_write(&c->state_lock);
1955 
1956 	if (!bch2_dev_is_online(ca)) {
1957 		bch_err(ca, "Already offline");
1958 		up_write(&c->state_lock);
1959 		return 0;
1960 	}
1961 
1962 	if (!bch2_dev_state_allowed(c, ca, BCH_MEMBER_STATE_failed, flags)) {
1963 		bch_err(ca, "Cannot offline required disk");
1964 		up_write(&c->state_lock);
1965 		return -BCH_ERR_device_state_not_allowed;
1966 	}
1967 
1968 	__bch2_dev_offline(c, ca);
1969 
1970 	up_write(&c->state_lock);
1971 	return 0;
1972 }
1973 
bch2_dev_resize(struct bch_fs * c,struct bch_dev * ca,u64 nbuckets)1974 int bch2_dev_resize(struct bch_fs *c, struct bch_dev *ca, u64 nbuckets)
1975 {
1976 	struct bch_member *m;
1977 	u64 old_nbuckets;
1978 	int ret = 0;
1979 
1980 	down_write(&c->state_lock);
1981 	old_nbuckets = ca->mi.nbuckets;
1982 
1983 	if (nbuckets < ca->mi.nbuckets) {
1984 		bch_err(ca, "Cannot shrink yet");
1985 		ret = -EINVAL;
1986 		goto err;
1987 	}
1988 
1989 	if (nbuckets > BCH_MEMBER_NBUCKETS_MAX) {
1990 		bch_err(ca, "New device size too big (%llu greater than max %u)",
1991 			nbuckets, BCH_MEMBER_NBUCKETS_MAX);
1992 		ret = -BCH_ERR_device_size_too_big;
1993 		goto err;
1994 	}
1995 
1996 	if (bch2_dev_is_online(ca) &&
1997 	    get_capacity(ca->disk_sb.bdev->bd_disk) <
1998 	    ca->mi.bucket_size * nbuckets) {
1999 		bch_err(ca, "New size larger than device");
2000 		ret = -BCH_ERR_device_size_too_small;
2001 		goto err;
2002 	}
2003 
2004 	ret = bch2_dev_buckets_resize(c, ca, nbuckets);
2005 	bch_err_msg(ca, ret, "resizing buckets");
2006 	if (ret)
2007 		goto err;
2008 
2009 	ret = bch2_trans_mark_dev_sb(c, ca, BTREE_TRIGGER_transactional);
2010 	if (ret)
2011 		goto err;
2012 
2013 	mutex_lock(&c->sb_lock);
2014 	m = bch2_members_v2_get_mut(c->disk_sb.sb, ca->dev_idx);
2015 	m->nbuckets = cpu_to_le64(nbuckets);
2016 
2017 	bch2_write_super(c);
2018 	mutex_unlock(&c->sb_lock);
2019 
2020 	if (ca->mi.freespace_initialized) {
2021 		u64 v[3] = { nbuckets - old_nbuckets, 0, 0 };
2022 
2023 		ret   = bch2_trans_commit_do(ca->fs, NULL, NULL, 0,
2024 				bch2_disk_accounting_mod2(trans, false, v, dev_data_type,
2025 							  .dev = ca->dev_idx,
2026 							  .data_type = BCH_DATA_free)) ?:
2027 			bch2_dev_freespace_init(c, ca, old_nbuckets, nbuckets);
2028 		if (ret)
2029 			goto err;
2030 	}
2031 
2032 	bch2_recalc_capacity(c);
2033 err:
2034 	up_write(&c->state_lock);
2035 	return ret;
2036 }
2037 
2038 /* return with ref on ca->ref: */
bch2_dev_lookup(struct bch_fs * c,const char * name)2039 struct bch_dev *bch2_dev_lookup(struct bch_fs *c, const char *name)
2040 {
2041 	if (!strncmp(name, "/dev/", strlen("/dev/")))
2042 		name += strlen("/dev/");
2043 
2044 	for_each_member_device(c, ca)
2045 		if (!strcmp(name, ca->name))
2046 			return ca;
2047 	return ERR_PTR(-BCH_ERR_ENOENT_dev_not_found);
2048 }
2049 
2050 /* blk_holder_ops: */
2051 
bdev_get_fs(struct block_device * bdev)2052 static struct bch_fs *bdev_get_fs(struct block_device *bdev)
2053 	__releases(&bdev->bd_holder_lock)
2054 {
2055 	struct bch_sb_handle_holder *holder = bdev->bd_holder;
2056 	struct bch_fs *c = holder->c;
2057 
2058 	if (c && !bch2_ro_ref_tryget(c))
2059 		c = NULL;
2060 
2061 	mutex_unlock(&bdev->bd_holder_lock);
2062 
2063 	if (c)
2064 		wait_event(c->ro_ref_wait, test_bit(BCH_FS_started, &c->flags));
2065 	return c;
2066 }
2067 
2068 /* returns with ref on ca->ref */
bdev_to_bch_dev(struct bch_fs * c,struct block_device * bdev)2069 static struct bch_dev *bdev_to_bch_dev(struct bch_fs *c, struct block_device *bdev)
2070 {
2071 	for_each_member_device(c, ca)
2072 		if (ca->disk_sb.bdev == bdev)
2073 			return ca;
2074 	return NULL;
2075 }
2076 
bch2_fs_bdev_mark_dead(struct block_device * bdev,bool surprise)2077 static void bch2_fs_bdev_mark_dead(struct block_device *bdev, bool surprise)
2078 {
2079 	struct bch_fs *c = bdev_get_fs(bdev);
2080 	if (!c)
2081 		return;
2082 
2083 	struct super_block *sb = c->vfs_sb;
2084 	if (sb) {
2085 		/*
2086 		 * Not necessary, c->ro_ref guards against the filesystem being
2087 		 * unmounted - we only take this to avoid a warning in
2088 		 * sync_filesystem:
2089 		 */
2090 		down_read(&sb->s_umount);
2091 	}
2092 
2093 	down_write(&c->state_lock);
2094 	struct bch_dev *ca = bdev_to_bch_dev(c, bdev);
2095 	if (!ca)
2096 		goto unlock;
2097 
2098 	if (bch2_dev_state_allowed(c, ca, BCH_MEMBER_STATE_failed, BCH_FORCE_IF_DEGRADED)) {
2099 		__bch2_dev_offline(c, ca);
2100 	} else {
2101 		if (sb) {
2102 			if (!surprise)
2103 				sync_filesystem(sb);
2104 			shrink_dcache_sb(sb);
2105 			evict_inodes(sb);
2106 		}
2107 
2108 		bch2_journal_flush(&c->journal);
2109 		bch2_fs_emergency_read_only(c);
2110 	}
2111 
2112 	bch2_dev_put(ca);
2113 unlock:
2114 	if (sb)
2115 		up_read(&sb->s_umount);
2116 	up_write(&c->state_lock);
2117 	bch2_ro_ref_put(c);
2118 }
2119 
bch2_fs_bdev_sync(struct block_device * bdev)2120 static void bch2_fs_bdev_sync(struct block_device *bdev)
2121 {
2122 	struct bch_fs *c = bdev_get_fs(bdev);
2123 	if (!c)
2124 		return;
2125 
2126 	struct super_block *sb = c->vfs_sb;
2127 	if (sb) {
2128 		/*
2129 		 * Not necessary, c->ro_ref guards against the filesystem being
2130 		 * unmounted - we only take this to avoid a warning in
2131 		 * sync_filesystem:
2132 		 */
2133 		down_read(&sb->s_umount);
2134 		sync_filesystem(sb);
2135 		up_read(&sb->s_umount);
2136 	}
2137 
2138 	bch2_ro_ref_put(c);
2139 }
2140 
2141 const struct blk_holder_ops bch2_sb_handle_bdev_ops = {
2142 	.mark_dead		= bch2_fs_bdev_mark_dead,
2143 	.sync			= bch2_fs_bdev_sync,
2144 };
2145 
2146 /* Filesystem open: */
2147 
sb_cmp(struct bch_sb * l,struct bch_sb * r)2148 static inline int sb_cmp(struct bch_sb *l, struct bch_sb *r)
2149 {
2150 	return  cmp_int(le64_to_cpu(l->seq), le64_to_cpu(r->seq)) ?:
2151 		cmp_int(le64_to_cpu(l->write_time), le64_to_cpu(r->write_time));
2152 }
2153 
bch2_fs_open(char * const * devices,unsigned nr_devices,struct bch_opts opts)2154 struct bch_fs *bch2_fs_open(char * const *devices, unsigned nr_devices,
2155 			    struct bch_opts opts)
2156 {
2157 	DARRAY(struct bch_sb_handle) sbs = { 0 };
2158 	struct bch_fs *c = NULL;
2159 	struct bch_sb_handle *best = NULL;
2160 	struct printbuf errbuf = PRINTBUF;
2161 	int ret = 0;
2162 
2163 	if (!try_module_get(THIS_MODULE))
2164 		return ERR_PTR(-ENODEV);
2165 
2166 	if (!nr_devices) {
2167 		ret = -EINVAL;
2168 		goto err;
2169 	}
2170 
2171 	ret = darray_make_room(&sbs, nr_devices);
2172 	if (ret)
2173 		goto err;
2174 
2175 	for (unsigned i = 0; i < nr_devices; i++) {
2176 		struct bch_sb_handle sb = { NULL };
2177 
2178 		ret = bch2_read_super(devices[i], &opts, &sb);
2179 		if (ret)
2180 			goto err;
2181 
2182 		BUG_ON(darray_push(&sbs, sb));
2183 	}
2184 
2185 	if (opts.nochanges && !opts.read_only) {
2186 		ret = -BCH_ERR_erofs_nochanges;
2187 		goto err_print;
2188 	}
2189 
2190 	darray_for_each(sbs, sb)
2191 		if (!best || sb_cmp(sb->sb, best->sb) > 0)
2192 			best = sb;
2193 
2194 	darray_for_each_reverse(sbs, sb) {
2195 		ret = bch2_dev_in_fs(best, sb, &opts);
2196 
2197 		if (ret == -BCH_ERR_device_has_been_removed ||
2198 		    ret == -BCH_ERR_device_splitbrain) {
2199 			bch2_free_super(sb);
2200 			darray_remove_item(&sbs, sb);
2201 			best -= best > sb;
2202 			ret = 0;
2203 			continue;
2204 		}
2205 
2206 		if (ret)
2207 			goto err_print;
2208 	}
2209 
2210 	c = bch2_fs_alloc(best->sb, opts);
2211 	ret = PTR_ERR_OR_ZERO(c);
2212 	if (ret)
2213 		goto err;
2214 
2215 	down_write(&c->state_lock);
2216 	darray_for_each(sbs, sb) {
2217 		ret = bch2_dev_attach_bdev(c, sb);
2218 		if (ret) {
2219 			up_write(&c->state_lock);
2220 			goto err;
2221 		}
2222 	}
2223 	up_write(&c->state_lock);
2224 
2225 	if (!c->opts.nostart) {
2226 		ret = bch2_fs_start(c);
2227 		if (ret)
2228 			goto err;
2229 	}
2230 out:
2231 	darray_for_each(sbs, sb)
2232 		bch2_free_super(sb);
2233 	darray_exit(&sbs);
2234 	printbuf_exit(&errbuf);
2235 	module_put(THIS_MODULE);
2236 	return c;
2237 err_print:
2238 	pr_err("bch_fs_open err opening %s: %s",
2239 	       devices[0], bch2_err_str(ret));
2240 err:
2241 	if (!IS_ERR_OR_NULL(c))
2242 		bch2_fs_stop(c);
2243 	c = ERR_PTR(ret);
2244 	goto out;
2245 }
2246 
2247 /* Global interfaces/init */
2248 
bcachefs_exit(void)2249 static void bcachefs_exit(void)
2250 {
2251 	bch2_debug_exit();
2252 	bch2_vfs_exit();
2253 	bch2_chardev_exit();
2254 	bch2_btree_key_cache_exit();
2255 	if (bcachefs_kset)
2256 		kset_unregister(bcachefs_kset);
2257 }
2258 
bcachefs_init(void)2259 static int __init bcachefs_init(void)
2260 {
2261 	bch2_bkey_pack_test();
2262 
2263 	if (!(bcachefs_kset = kset_create_and_add("bcachefs", NULL, fs_kobj)) ||
2264 	    bch2_btree_key_cache_init() ||
2265 	    bch2_chardev_init() ||
2266 	    bch2_vfs_init() ||
2267 	    bch2_debug_init())
2268 		goto err;
2269 
2270 	return 0;
2271 err:
2272 	bcachefs_exit();
2273 	return -ENOMEM;
2274 }
2275 
2276 #define BCH_DEBUG_PARAM(name, description)			\
2277 	bool bch2_##name;					\
2278 	module_param_named(name, bch2_##name, bool, 0644);	\
2279 	MODULE_PARM_DESC(name, description);
2280 BCH_DEBUG_PARAMS()
2281 #undef BCH_DEBUG_PARAM
2282 
2283 __maybe_unused
2284 static unsigned bch2_metadata_version = bcachefs_metadata_version_current;
2285 module_param_named(version, bch2_metadata_version, uint, 0444);
2286 
2287 module_exit(bcachefs_exit);
2288 module_init(bcachefs_init);
2289