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