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