]> git.sesse.net Git - bcachefs-tools-debian/blob - libbcachefs/super.c
Update bcachefs sources to 2a6125decb43 bcachefs: bch_sb_field_downgrade
[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 err:
1044         if (ret)
1045                 bch_err_msg(c, ret, "starting filesystem");
1046         else
1047                 bch_verbose(c, "done starting filesystem");
1048         up_write(&c->state_lock);
1049         return ret;
1050 }
1051
1052 static int bch2_dev_may_add(struct bch_sb *sb, struct bch_fs *c)
1053 {
1054         struct bch_member m = bch2_sb_member_get(sb, sb->dev_idx);
1055
1056         if (le16_to_cpu(sb->block_size) != block_sectors(c))
1057                 return -BCH_ERR_mismatched_block_size;
1058
1059         if (le16_to_cpu(m.bucket_size) <
1060             BCH_SB_BTREE_NODE_SIZE(c->disk_sb.sb))
1061                 return -BCH_ERR_bucket_size_too_small;
1062
1063         return 0;
1064 }
1065
1066 static int bch2_dev_in_fs(struct bch_sb_handle *fs,
1067                           struct bch_sb_handle *sb)
1068 {
1069         if (fs == sb)
1070                 return 0;
1071
1072         if (!uuid_equal(&fs->sb->uuid, &sb->sb->uuid))
1073                 return -BCH_ERR_device_not_a_member_of_filesystem;
1074
1075         if (!bch2_dev_exists(fs->sb, sb->sb->dev_idx))
1076                 return -BCH_ERR_device_has_been_removed;
1077
1078         if (fs->sb->block_size != sb->sb->block_size)
1079                 return -BCH_ERR_mismatched_block_size;
1080
1081         if (le16_to_cpu(fs->sb->version) < bcachefs_metadata_version_member_seq ||
1082             le16_to_cpu(sb->sb->version) < bcachefs_metadata_version_member_seq)
1083                 return 0;
1084
1085         if (fs->sb->seq == sb->sb->seq &&
1086             fs->sb->write_time != sb->sb->write_time) {
1087                 struct printbuf buf = PRINTBUF;
1088
1089                 prt_printf(&buf, "Split brain detected between %pg and %pg:",
1090                            sb->bdev, fs->bdev);
1091                 prt_newline(&buf);
1092                 prt_printf(&buf, "seq=%llu but write_time different, got", le64_to_cpu(sb->sb->seq));
1093                 prt_newline(&buf);
1094
1095                 prt_printf(&buf, "%pg ", fs->bdev);
1096                 bch2_prt_datetime(&buf, le64_to_cpu(fs->sb->write_time));;
1097                 prt_newline(&buf);
1098
1099                 prt_printf(&buf, "%pg ", sb->bdev);
1100                 bch2_prt_datetime(&buf, le64_to_cpu(sb->sb->write_time));;
1101                 prt_newline(&buf);
1102
1103                 prt_printf(&buf, "Not using older sb");
1104
1105                 pr_err("%s", buf.buf);
1106                 printbuf_exit(&buf);
1107                 return -BCH_ERR_device_splitbrain;
1108         }
1109
1110         struct bch_member m = bch2_sb_member_get(fs->sb, sb->sb->dev_idx);
1111         u64 seq_from_fs         = le64_to_cpu(m.seq);
1112         u64 seq_from_member     = le64_to_cpu(sb->sb->seq);
1113
1114         if (seq_from_fs && seq_from_fs < seq_from_member) {
1115                 pr_err("Split brain detected between %pg and %pg:\n"
1116                        "%pg believes seq of %pg to be %llu, but %pg has %llu\n"
1117                        "Not using %pg",
1118                        sb->bdev, fs->bdev,
1119                        fs->bdev, sb->bdev, seq_from_fs,
1120                        sb->bdev, seq_from_member,
1121                        sb->bdev);
1122                 return -BCH_ERR_device_splitbrain;
1123         }
1124
1125         return 0;
1126 }
1127
1128 /* Device startup/shutdown: */
1129
1130 static void bch2_dev_release(struct kobject *kobj)
1131 {
1132         struct bch_dev *ca = container_of(kobj, struct bch_dev, kobj);
1133
1134         kfree(ca);
1135 }
1136
1137 static void bch2_dev_free(struct bch_dev *ca)
1138 {
1139         cancel_work_sync(&ca->io_error_work);
1140
1141         if (ca->kobj.state_in_sysfs &&
1142             ca->disk_sb.bdev)
1143                 sysfs_remove_link(bdev_kobj(ca->disk_sb.bdev), "bcachefs");
1144
1145         if (ca->kobj.state_in_sysfs)
1146                 kobject_del(&ca->kobj);
1147
1148         bch2_free_super(&ca->disk_sb);
1149         bch2_dev_journal_exit(ca);
1150
1151         free_percpu(ca->io_done);
1152         bioset_exit(&ca->replica_set);
1153         bch2_dev_buckets_free(ca);
1154         free_page((unsigned long) ca->sb_read_scratch);
1155
1156         bch2_time_stats_exit(&ca->io_latency[WRITE]);
1157         bch2_time_stats_exit(&ca->io_latency[READ]);
1158
1159         percpu_ref_exit(&ca->io_ref);
1160         percpu_ref_exit(&ca->ref);
1161         kobject_put(&ca->kobj);
1162 }
1163
1164 static void __bch2_dev_offline(struct bch_fs *c, struct bch_dev *ca)
1165 {
1166
1167         lockdep_assert_held(&c->state_lock);
1168
1169         if (percpu_ref_is_zero(&ca->io_ref))
1170                 return;
1171
1172         __bch2_dev_read_only(c, ca);
1173
1174         reinit_completion(&ca->io_ref_completion);
1175         percpu_ref_kill(&ca->io_ref);
1176         wait_for_completion(&ca->io_ref_completion);
1177
1178         if (ca->kobj.state_in_sysfs) {
1179                 sysfs_remove_link(bdev_kobj(ca->disk_sb.bdev), "bcachefs");
1180                 sysfs_remove_link(&ca->kobj, "block");
1181         }
1182
1183         bch2_free_super(&ca->disk_sb);
1184         bch2_dev_journal_exit(ca);
1185 }
1186
1187 static void bch2_dev_ref_complete(struct percpu_ref *ref)
1188 {
1189         struct bch_dev *ca = container_of(ref, struct bch_dev, ref);
1190
1191         complete(&ca->ref_completion);
1192 }
1193
1194 static void bch2_dev_io_ref_complete(struct percpu_ref *ref)
1195 {
1196         struct bch_dev *ca = container_of(ref, struct bch_dev, io_ref);
1197
1198         complete(&ca->io_ref_completion);
1199 }
1200
1201 static int bch2_dev_sysfs_online(struct bch_fs *c, struct bch_dev *ca)
1202 {
1203         int ret;
1204
1205         if (!c->kobj.state_in_sysfs)
1206                 return 0;
1207
1208         if (!ca->kobj.state_in_sysfs) {
1209                 ret = kobject_add(&ca->kobj, &c->kobj,
1210                                   "dev-%u", ca->dev_idx);
1211                 if (ret)
1212                         return ret;
1213         }
1214
1215         if (ca->disk_sb.bdev) {
1216                 struct kobject *block = bdev_kobj(ca->disk_sb.bdev);
1217
1218                 ret = sysfs_create_link(block, &ca->kobj, "bcachefs");
1219                 if (ret)
1220                         return ret;
1221
1222                 ret = sysfs_create_link(&ca->kobj, block, "block");
1223                 if (ret)
1224                         return ret;
1225         }
1226
1227         return 0;
1228 }
1229
1230 static struct bch_dev *__bch2_dev_alloc(struct bch_fs *c,
1231                                         struct bch_member *member)
1232 {
1233         struct bch_dev *ca;
1234         unsigned i;
1235
1236         ca = kzalloc(sizeof(*ca), GFP_KERNEL);
1237         if (!ca)
1238                 return NULL;
1239
1240         kobject_init(&ca->kobj, &bch2_dev_ktype);
1241         init_completion(&ca->ref_completion);
1242         init_completion(&ca->io_ref_completion);
1243
1244         init_rwsem(&ca->bucket_lock);
1245
1246         INIT_WORK(&ca->io_error_work, bch2_io_error_work);
1247
1248         bch2_time_stats_init(&ca->io_latency[READ]);
1249         bch2_time_stats_init(&ca->io_latency[WRITE]);
1250
1251         ca->mi = bch2_mi_to_cpu(member);
1252
1253         for (i = 0; i < ARRAY_SIZE(member->errors); i++)
1254                 atomic64_set(&ca->errors[i], le64_to_cpu(member->errors[i]));
1255
1256         ca->uuid = member->uuid;
1257
1258         ca->nr_btree_reserve = DIV_ROUND_UP(BTREE_NODE_RESERVE,
1259                              ca->mi.bucket_size / btree_sectors(c));
1260
1261         if (percpu_ref_init(&ca->ref, bch2_dev_ref_complete,
1262                             0, GFP_KERNEL) ||
1263             percpu_ref_init(&ca->io_ref, bch2_dev_io_ref_complete,
1264                             PERCPU_REF_INIT_DEAD, GFP_KERNEL) ||
1265             !(ca->sb_read_scratch = (void *) __get_free_page(GFP_KERNEL)) ||
1266             bch2_dev_buckets_alloc(c, ca) ||
1267             bioset_init(&ca->replica_set, 4,
1268                         offsetof(struct bch_write_bio, bio), 0) ||
1269             !(ca->io_done       = alloc_percpu(*ca->io_done)))
1270                 goto err;
1271
1272         return ca;
1273 err:
1274         bch2_dev_free(ca);
1275         return NULL;
1276 }
1277
1278 static void bch2_dev_attach(struct bch_fs *c, struct bch_dev *ca,
1279                             unsigned dev_idx)
1280 {
1281         ca->dev_idx = dev_idx;
1282         __set_bit(ca->dev_idx, ca->self.d);
1283         scnprintf(ca->name, sizeof(ca->name), "dev-%u", dev_idx);
1284
1285         ca->fs = c;
1286         rcu_assign_pointer(c->devs[ca->dev_idx], ca);
1287
1288         if (bch2_dev_sysfs_online(c, ca))
1289                 pr_warn("error creating sysfs objects");
1290 }
1291
1292 static int bch2_dev_alloc(struct bch_fs *c, unsigned dev_idx)
1293 {
1294         struct bch_member member = bch2_sb_member_get(c->disk_sb.sb, dev_idx);
1295         struct bch_dev *ca = NULL;
1296         int ret = 0;
1297
1298         if (bch2_fs_init_fault("dev_alloc"))
1299                 goto err;
1300
1301         ca = __bch2_dev_alloc(c, &member);
1302         if (!ca)
1303                 goto err;
1304
1305         ca->fs = c;
1306
1307         bch2_dev_attach(c, ca, dev_idx);
1308         return ret;
1309 err:
1310         if (ca)
1311                 bch2_dev_free(ca);
1312         return -BCH_ERR_ENOMEM_dev_alloc;
1313 }
1314
1315 static int __bch2_dev_attach_bdev(struct bch_dev *ca, struct bch_sb_handle *sb)
1316 {
1317         unsigned ret;
1318
1319         if (bch2_dev_is_online(ca)) {
1320                 bch_err(ca, "already have device online in slot %u",
1321                         sb->sb->dev_idx);
1322                 return -BCH_ERR_device_already_online;
1323         }
1324
1325         if (get_capacity(sb->bdev->bd_disk) <
1326             ca->mi.bucket_size * ca->mi.nbuckets) {
1327                 bch_err(ca, "cannot online: device too small");
1328                 return -BCH_ERR_device_size_too_small;
1329         }
1330
1331         BUG_ON(!percpu_ref_is_zero(&ca->io_ref));
1332
1333         ret = bch2_dev_journal_init(ca, sb->sb);
1334         if (ret)
1335                 return ret;
1336
1337         /* Commit: */
1338         ca->disk_sb = *sb;
1339         memset(sb, 0, sizeof(*sb));
1340
1341         ca->dev = ca->disk_sb.bdev->bd_dev;
1342
1343         percpu_ref_reinit(&ca->io_ref);
1344
1345         return 0;
1346 }
1347
1348 static int bch2_dev_attach_bdev(struct bch_fs *c, struct bch_sb_handle *sb)
1349 {
1350         struct bch_dev *ca;
1351         int ret;
1352
1353         lockdep_assert_held(&c->state_lock);
1354
1355         if (le64_to_cpu(sb->sb->seq) >
1356             le64_to_cpu(c->disk_sb.sb->seq))
1357                 bch2_sb_to_fs(c, sb->sb);
1358
1359         BUG_ON(sb->sb->dev_idx >= c->sb.nr_devices ||
1360                !c->devs[sb->sb->dev_idx]);
1361
1362         ca = bch_dev_locked(c, sb->sb->dev_idx);
1363
1364         ret = __bch2_dev_attach_bdev(ca, sb);
1365         if (ret)
1366                 return ret;
1367
1368         bch2_dev_sysfs_online(c, ca);
1369
1370         if (c->sb.nr_devices == 1)
1371                 snprintf(c->name, sizeof(c->name), "%pg", ca->disk_sb.bdev);
1372         snprintf(ca->name, sizeof(ca->name), "%pg", ca->disk_sb.bdev);
1373
1374         rebalance_wakeup(c);
1375         return 0;
1376 }
1377
1378 /* Device management: */
1379
1380 /*
1381  * Note: this function is also used by the error paths - when a particular
1382  * device sees an error, we call it to determine whether we can just set the
1383  * device RO, or - if this function returns false - we'll set the whole
1384  * filesystem RO:
1385  *
1386  * XXX: maybe we should be more explicit about whether we're changing state
1387  * because we got an error or what have you?
1388  */
1389 bool bch2_dev_state_allowed(struct bch_fs *c, struct bch_dev *ca,
1390                             enum bch_member_state new_state, int flags)
1391 {
1392         struct bch_devs_mask new_online_devs;
1393         int nr_rw = 0, required;
1394
1395         lockdep_assert_held(&c->state_lock);
1396
1397         switch (new_state) {
1398         case BCH_MEMBER_STATE_rw:
1399                 return true;
1400         case BCH_MEMBER_STATE_ro:
1401                 if (ca->mi.state != BCH_MEMBER_STATE_rw)
1402                         return true;
1403
1404                 /* do we have enough devices to write to?  */
1405                 for_each_member_device(c, ca2)
1406                         if (ca2 != ca)
1407                                 nr_rw += ca2->mi.state == BCH_MEMBER_STATE_rw;
1408
1409                 required = max(!(flags & BCH_FORCE_IF_METADATA_DEGRADED)
1410                                ? c->opts.metadata_replicas
1411                                : c->opts.metadata_replicas_required,
1412                                !(flags & BCH_FORCE_IF_DATA_DEGRADED)
1413                                ? c->opts.data_replicas
1414                                : c->opts.data_replicas_required);
1415
1416                 return nr_rw >= required;
1417         case BCH_MEMBER_STATE_failed:
1418         case BCH_MEMBER_STATE_spare:
1419                 if (ca->mi.state != BCH_MEMBER_STATE_rw &&
1420                     ca->mi.state != BCH_MEMBER_STATE_ro)
1421                         return true;
1422
1423                 /* do we have enough devices to read from?  */
1424                 new_online_devs = bch2_online_devs(c);
1425                 __clear_bit(ca->dev_idx, new_online_devs.d);
1426
1427                 return bch2_have_enough_devs(c, new_online_devs, flags, false);
1428         default:
1429                 BUG();
1430         }
1431 }
1432
1433 static bool bch2_fs_may_start(struct bch_fs *c)
1434 {
1435         struct bch_dev *ca;
1436         unsigned i, flags = 0;
1437
1438         if (c->opts.very_degraded)
1439                 flags |= BCH_FORCE_IF_DEGRADED|BCH_FORCE_IF_LOST;
1440
1441         if (c->opts.degraded)
1442                 flags |= BCH_FORCE_IF_DEGRADED;
1443
1444         if (!c->opts.degraded &&
1445             !c->opts.very_degraded) {
1446                 mutex_lock(&c->sb_lock);
1447
1448                 for (i = 0; i < c->disk_sb.sb->nr_devices; i++) {
1449                         if (!bch2_dev_exists(c->disk_sb.sb, i))
1450                                 continue;
1451
1452                         ca = bch_dev_locked(c, i);
1453
1454                         if (!bch2_dev_is_online(ca) &&
1455                             (ca->mi.state == BCH_MEMBER_STATE_rw ||
1456                              ca->mi.state == BCH_MEMBER_STATE_ro)) {
1457                                 mutex_unlock(&c->sb_lock);
1458                                 return false;
1459                         }
1460                 }
1461                 mutex_unlock(&c->sb_lock);
1462         }
1463
1464         return bch2_have_enough_devs(c, bch2_online_devs(c), flags, true);
1465 }
1466
1467 static void __bch2_dev_read_only(struct bch_fs *c, struct bch_dev *ca)
1468 {
1469         /*
1470          * The allocator thread itself allocates btree nodes, so stop it first:
1471          */
1472         bch2_dev_allocator_remove(c, ca);
1473         bch2_dev_journal_stop(&c->journal, ca);
1474 }
1475
1476 static void __bch2_dev_read_write(struct bch_fs *c, struct bch_dev *ca)
1477 {
1478         lockdep_assert_held(&c->state_lock);
1479
1480         BUG_ON(ca->mi.state != BCH_MEMBER_STATE_rw);
1481
1482         bch2_dev_allocator_add(c, ca);
1483         bch2_recalc_capacity(c);
1484 }
1485
1486 int __bch2_dev_set_state(struct bch_fs *c, struct bch_dev *ca,
1487                          enum bch_member_state new_state, int flags)
1488 {
1489         struct bch_member *m;
1490         int ret = 0;
1491
1492         if (ca->mi.state == new_state)
1493                 return 0;
1494
1495         if (!bch2_dev_state_allowed(c, ca, new_state, flags))
1496                 return -BCH_ERR_device_state_not_allowed;
1497
1498         if (new_state != BCH_MEMBER_STATE_rw)
1499                 __bch2_dev_read_only(c, ca);
1500
1501         bch_notice(ca, "%s", bch2_member_states[new_state]);
1502
1503         mutex_lock(&c->sb_lock);
1504         m = bch2_members_v2_get_mut(c->disk_sb.sb, ca->dev_idx);
1505         SET_BCH_MEMBER_STATE(m, new_state);
1506         bch2_write_super(c);
1507         mutex_unlock(&c->sb_lock);
1508
1509         if (new_state == BCH_MEMBER_STATE_rw)
1510                 __bch2_dev_read_write(c, ca);
1511
1512         rebalance_wakeup(c);
1513
1514         return ret;
1515 }
1516
1517 int bch2_dev_set_state(struct bch_fs *c, struct bch_dev *ca,
1518                        enum bch_member_state new_state, int flags)
1519 {
1520         int ret;
1521
1522         down_write(&c->state_lock);
1523         ret = __bch2_dev_set_state(c, ca, new_state, flags);
1524         up_write(&c->state_lock);
1525
1526         return ret;
1527 }
1528
1529 /* Device add/removal: */
1530
1531 static int bch2_dev_remove_alloc(struct bch_fs *c, struct bch_dev *ca)
1532 {
1533         struct bpos start       = POS(ca->dev_idx, 0);
1534         struct bpos end         = POS(ca->dev_idx, U64_MAX);
1535         int ret;
1536
1537         /*
1538          * We clear the LRU and need_discard btrees first so that we don't race
1539          * with bch2_do_invalidates() and bch2_do_discards()
1540          */
1541         ret =   bch2_btree_delete_range(c, BTREE_ID_lru, start, end,
1542                                         BTREE_TRIGGER_NORUN, NULL) ?:
1543                 bch2_btree_delete_range(c, BTREE_ID_need_discard, start, end,
1544                                         BTREE_TRIGGER_NORUN, NULL) ?:
1545                 bch2_btree_delete_range(c, BTREE_ID_freespace, start, end,
1546                                         BTREE_TRIGGER_NORUN, NULL) ?:
1547                 bch2_btree_delete_range(c, BTREE_ID_backpointers, start, end,
1548                                         BTREE_TRIGGER_NORUN, NULL) ?:
1549                 bch2_btree_delete_range(c, BTREE_ID_alloc, start, end,
1550                                         BTREE_TRIGGER_NORUN, NULL) ?:
1551                 bch2_btree_delete_range(c, BTREE_ID_bucket_gens, start, end,
1552                                         BTREE_TRIGGER_NORUN, NULL);
1553         bch_err_msg(c, ret, "removing dev alloc info");
1554         return ret;
1555 }
1556
1557 int bch2_dev_remove(struct bch_fs *c, struct bch_dev *ca, int flags)
1558 {
1559         struct bch_member *m;
1560         unsigned dev_idx = ca->dev_idx, data;
1561         int ret;
1562
1563         down_write(&c->state_lock);
1564
1565         /*
1566          * We consume a reference to ca->ref, regardless of whether we succeed
1567          * or fail:
1568          */
1569         percpu_ref_put(&ca->ref);
1570
1571         if (!bch2_dev_state_allowed(c, ca, BCH_MEMBER_STATE_failed, flags)) {
1572                 bch_err(ca, "Cannot remove without losing data");
1573                 ret = -BCH_ERR_device_state_not_allowed;
1574                 goto err;
1575         }
1576
1577         __bch2_dev_read_only(c, ca);
1578
1579         ret = bch2_dev_data_drop(c, ca->dev_idx, flags);
1580         bch_err_msg(ca, ret, "dropping data");
1581         if (ret)
1582                 goto err;
1583
1584         ret = bch2_dev_remove_alloc(c, ca);
1585         bch_err_msg(ca, ret, "deleting alloc info");
1586         if (ret)
1587                 goto err;
1588
1589         ret = bch2_journal_flush_device_pins(&c->journal, ca->dev_idx);
1590         bch_err_msg(ca, ret, "flushing journal");
1591         if (ret)
1592                 goto err;
1593
1594         ret = bch2_journal_flush(&c->journal);
1595         bch_err(ca, "journal error");
1596         if (ret)
1597                 goto err;
1598
1599         ret = bch2_replicas_gc2(c);
1600         bch_err_msg(ca, ret, "in replicas_gc2()");
1601         if (ret)
1602                 goto err;
1603
1604         data = bch2_dev_has_data(c, ca);
1605         if (data) {
1606                 struct printbuf data_has = PRINTBUF;
1607
1608                 prt_bitflags(&data_has, bch2_data_types, data);
1609                 bch_err(ca, "Remove failed, still has data (%s)", data_has.buf);
1610                 printbuf_exit(&data_has);
1611                 ret = -EBUSY;
1612                 goto err;
1613         }
1614
1615         __bch2_dev_offline(c, ca);
1616
1617         mutex_lock(&c->sb_lock);
1618         rcu_assign_pointer(c->devs[ca->dev_idx], NULL);
1619         mutex_unlock(&c->sb_lock);
1620
1621         percpu_ref_kill(&ca->ref);
1622         wait_for_completion(&ca->ref_completion);
1623
1624         bch2_dev_free(ca);
1625
1626         /*
1627          * At this point the device object has been removed in-core, but the
1628          * on-disk journal might still refer to the device index via sb device
1629          * usage entries. Recovery fails if it sees usage information for an
1630          * invalid device. Flush journal pins to push the back of the journal
1631          * past now invalid device index references before we update the
1632          * superblock, but after the device object has been removed so any
1633          * further journal writes elide usage info for the device.
1634          */
1635         bch2_journal_flush_all_pins(&c->journal);
1636
1637         /*
1638          * Free this device's slot in the bch_member array - all pointers to
1639          * this device must be gone:
1640          */
1641         mutex_lock(&c->sb_lock);
1642         m = bch2_members_v2_get_mut(c->disk_sb.sb, dev_idx);
1643         memset(&m->uuid, 0, sizeof(m->uuid));
1644
1645         bch2_write_super(c);
1646
1647         mutex_unlock(&c->sb_lock);
1648         up_write(&c->state_lock);
1649
1650         bch2_dev_usage_journal_reserve(c);
1651         return 0;
1652 err:
1653         if (ca->mi.state == BCH_MEMBER_STATE_rw &&
1654             !percpu_ref_is_zero(&ca->io_ref))
1655                 __bch2_dev_read_write(c, ca);
1656         up_write(&c->state_lock);
1657         return ret;
1658 }
1659
1660 /* Add new device to running filesystem: */
1661 int bch2_dev_add(struct bch_fs *c, const char *path)
1662 {
1663         struct bch_opts opts = bch2_opts_empty();
1664         struct bch_sb_handle sb;
1665         struct bch_dev *ca = NULL;
1666         struct bch_sb_field_members_v2 *mi;
1667         struct bch_member dev_mi;
1668         unsigned dev_idx, nr_devices, u64s;
1669         struct printbuf errbuf = PRINTBUF;
1670         struct printbuf label = PRINTBUF;
1671         int ret;
1672
1673         ret = bch2_read_super(path, &opts, &sb);
1674         bch_err_msg(c, ret, "reading super");
1675         if (ret)
1676                 goto err;
1677
1678         dev_mi = bch2_sb_member_get(sb.sb, sb.sb->dev_idx);
1679
1680         if (BCH_MEMBER_GROUP(&dev_mi)) {
1681                 bch2_disk_path_to_text_sb(&label, sb.sb, BCH_MEMBER_GROUP(&dev_mi) - 1);
1682                 if (label.allocation_failure) {
1683                         ret = -ENOMEM;
1684                         goto err;
1685                 }
1686         }
1687
1688         ret = bch2_dev_may_add(sb.sb, c);
1689         if (ret)
1690                 goto err;
1691
1692         ca = __bch2_dev_alloc(c, &dev_mi);
1693         if (!ca) {
1694                 ret = -ENOMEM;
1695                 goto err;
1696         }
1697
1698         bch2_dev_usage_init(ca);
1699
1700         ret = __bch2_dev_attach_bdev(ca, &sb);
1701         if (ret)
1702                 goto err;
1703
1704         ret = bch2_dev_journal_alloc(ca);
1705         bch_err_msg(c, ret, "allocating journal");
1706         if (ret)
1707                 goto err;
1708
1709         down_write(&c->state_lock);
1710         mutex_lock(&c->sb_lock);
1711
1712         ret = bch2_sb_from_fs(c, ca);
1713         bch_err_msg(c, ret, "setting up new superblock");
1714         if (ret)
1715                 goto err_unlock;
1716
1717         if (dynamic_fault("bcachefs:add:no_slot"))
1718                 goto no_slot;
1719
1720         for (dev_idx = 0; dev_idx < BCH_SB_MEMBERS_MAX; dev_idx++)
1721                 if (!bch2_dev_exists(c->disk_sb.sb, dev_idx))
1722                         goto have_slot;
1723 no_slot:
1724         ret = -BCH_ERR_ENOSPC_sb_members;
1725         bch_err_msg(c, ret, "setting up new superblock");
1726         goto err_unlock;
1727
1728 have_slot:
1729         nr_devices = max_t(unsigned, dev_idx + 1, c->sb.nr_devices);
1730
1731         mi = bch2_sb_field_get(c->disk_sb.sb, members_v2);
1732         u64s = DIV_ROUND_UP(sizeof(struct bch_sb_field_members_v2) +
1733                             le16_to_cpu(mi->member_bytes) * nr_devices, sizeof(u64));
1734
1735         mi = bch2_sb_field_resize(&c->disk_sb, members_v2, u64s);
1736         if (!mi) {
1737                 ret = -BCH_ERR_ENOSPC_sb_members;
1738                 bch_err_msg(c, ret, "setting up new superblock");
1739                 goto err_unlock;
1740         }
1741         struct bch_member *m = bch2_members_v2_get_mut(c->disk_sb.sb, dev_idx);
1742
1743         /* success: */
1744
1745         *m = dev_mi;
1746         m->last_mount = cpu_to_le64(ktime_get_real_seconds());
1747         c->disk_sb.sb->nr_devices       = nr_devices;
1748
1749         ca->disk_sb.sb->dev_idx = dev_idx;
1750         bch2_dev_attach(c, ca, dev_idx);
1751
1752         if (BCH_MEMBER_GROUP(&dev_mi)) {
1753                 ret = __bch2_dev_group_set(c, ca, label.buf);
1754                 bch_err_msg(c, ret, "creating new label");
1755                 if (ret)
1756                         goto err_unlock;
1757         }
1758
1759         bch2_write_super(c);
1760         mutex_unlock(&c->sb_lock);
1761
1762         bch2_dev_usage_journal_reserve(c);
1763
1764         ret = bch2_trans_mark_dev_sb(c, ca);
1765         bch_err_msg(ca, ret, "marking new superblock");
1766         if (ret)
1767                 goto err_late;
1768
1769         ret = bch2_fs_freespace_init(c);
1770         bch_err_msg(ca, ret, "initializing free space");
1771         if (ret)
1772                 goto err_late;
1773
1774         ca->new_fs_bucket_idx = 0;
1775
1776         if (ca->mi.state == BCH_MEMBER_STATE_rw)
1777                 __bch2_dev_read_write(c, ca);
1778
1779         up_write(&c->state_lock);
1780         return 0;
1781
1782 err_unlock:
1783         mutex_unlock(&c->sb_lock);
1784         up_write(&c->state_lock);
1785 err:
1786         if (ca)
1787                 bch2_dev_free(ca);
1788         bch2_free_super(&sb);
1789         printbuf_exit(&label);
1790         printbuf_exit(&errbuf);
1791         bch_err_fn(c, ret);
1792         return ret;
1793 err_late:
1794         up_write(&c->state_lock);
1795         ca = NULL;
1796         goto err;
1797 }
1798
1799 /* Hot add existing device to running filesystem: */
1800 int bch2_dev_online(struct bch_fs *c, const char *path)
1801 {
1802         struct bch_opts opts = bch2_opts_empty();
1803         struct bch_sb_handle sb = { NULL };
1804         struct bch_dev *ca;
1805         unsigned dev_idx;
1806         int ret;
1807
1808         down_write(&c->state_lock);
1809
1810         ret = bch2_read_super(path, &opts, &sb);
1811         if (ret) {
1812                 up_write(&c->state_lock);
1813                 return ret;
1814         }
1815
1816         dev_idx = sb.sb->dev_idx;
1817
1818         ret = bch2_dev_in_fs(&c->disk_sb, &sb);
1819         bch_err_msg(c, ret, "bringing %s online", path);
1820         if (ret)
1821                 goto err;
1822
1823         ret = bch2_dev_attach_bdev(c, &sb);
1824         if (ret)
1825                 goto err;
1826
1827         ca = bch_dev_locked(c, dev_idx);
1828
1829         ret = bch2_trans_mark_dev_sb(c, ca);
1830         bch_err_msg(c, ret, "bringing %s online: error from bch2_trans_mark_dev_sb", path);
1831         if (ret)
1832                 goto err;
1833
1834         if (ca->mi.state == BCH_MEMBER_STATE_rw)
1835                 __bch2_dev_read_write(c, ca);
1836
1837         if (!ca->mi.freespace_initialized) {
1838                 ret = bch2_dev_freespace_init(c, ca, 0, ca->mi.nbuckets);
1839                 bch_err_msg(ca, ret, "initializing free space");
1840                 if (ret)
1841                         goto err;
1842         }
1843
1844         if (!ca->journal.nr) {
1845                 ret = bch2_dev_journal_alloc(ca);
1846                 bch_err_msg(ca, ret, "allocating journal");
1847                 if (ret)
1848                         goto err;
1849         }
1850
1851         mutex_lock(&c->sb_lock);
1852         bch2_members_v2_get_mut(c->disk_sb.sb, ca->dev_idx)->last_mount =
1853                 cpu_to_le64(ktime_get_real_seconds());
1854         bch2_write_super(c);
1855         mutex_unlock(&c->sb_lock);
1856
1857         up_write(&c->state_lock);
1858         return 0;
1859 err:
1860         up_write(&c->state_lock);
1861         bch2_free_super(&sb);
1862         return ret;
1863 }
1864
1865 int bch2_dev_offline(struct bch_fs *c, struct bch_dev *ca, int flags)
1866 {
1867         down_write(&c->state_lock);
1868
1869         if (!bch2_dev_is_online(ca)) {
1870                 bch_err(ca, "Already offline");
1871                 up_write(&c->state_lock);
1872                 return 0;
1873         }
1874
1875         if (!bch2_dev_state_allowed(c, ca, BCH_MEMBER_STATE_failed, flags)) {
1876                 bch_err(ca, "Cannot offline required disk");
1877                 up_write(&c->state_lock);
1878                 return -BCH_ERR_device_state_not_allowed;
1879         }
1880
1881         __bch2_dev_offline(c, ca);
1882
1883         up_write(&c->state_lock);
1884         return 0;
1885 }
1886
1887 int bch2_dev_resize(struct bch_fs *c, struct bch_dev *ca, u64 nbuckets)
1888 {
1889         struct bch_member *m;
1890         u64 old_nbuckets;
1891         int ret = 0;
1892
1893         down_write(&c->state_lock);
1894         old_nbuckets = ca->mi.nbuckets;
1895
1896         if (nbuckets < ca->mi.nbuckets) {
1897                 bch_err(ca, "Cannot shrink yet");
1898                 ret = -EINVAL;
1899                 goto err;
1900         }
1901
1902         if (bch2_dev_is_online(ca) &&
1903             get_capacity(ca->disk_sb.bdev->bd_disk) <
1904             ca->mi.bucket_size * nbuckets) {
1905                 bch_err(ca, "New size larger than device");
1906                 ret = -BCH_ERR_device_size_too_small;
1907                 goto err;
1908         }
1909
1910         ret = bch2_dev_buckets_resize(c, ca, nbuckets);
1911         bch_err_msg(ca, ret, "resizing buckets");
1912         if (ret)
1913                 goto err;
1914
1915         ret = bch2_trans_mark_dev_sb(c, ca);
1916         if (ret)
1917                 goto err;
1918
1919         mutex_lock(&c->sb_lock);
1920         m = bch2_members_v2_get_mut(c->disk_sb.sb, ca->dev_idx);
1921         m->nbuckets = cpu_to_le64(nbuckets);
1922
1923         bch2_write_super(c);
1924         mutex_unlock(&c->sb_lock);
1925
1926         if (ca->mi.freespace_initialized) {
1927                 ret = bch2_dev_freespace_init(c, ca, old_nbuckets, nbuckets);
1928                 if (ret)
1929                         goto err;
1930
1931                 /*
1932                  * XXX: this is all wrong transactionally - we'll be able to do
1933                  * this correctly after the disk space accounting rewrite
1934                  */
1935                 ca->usage_base->d[BCH_DATA_free].buckets += nbuckets - old_nbuckets;
1936         }
1937
1938         bch2_recalc_capacity(c);
1939 err:
1940         up_write(&c->state_lock);
1941         return ret;
1942 }
1943
1944 /* return with ref on ca->ref: */
1945 struct bch_dev *bch2_dev_lookup(struct bch_fs *c, const char *name)
1946 {
1947         rcu_read_lock();
1948         for_each_member_device_rcu(c, ca, NULL)
1949                 if (!strcmp(name, ca->name)) {
1950                         rcu_read_unlock();
1951                         return ca;
1952                 }
1953         rcu_read_unlock();
1954         return ERR_PTR(-BCH_ERR_ENOENT_dev_not_found);
1955 }
1956
1957 /* Filesystem open: */
1958
1959 static inline int sb_cmp(struct bch_sb *l, struct bch_sb *r)
1960 {
1961         return  cmp_int(le64_to_cpu(l->seq), le64_to_cpu(r->seq)) ?:
1962                 cmp_int(le64_to_cpu(l->write_time), le64_to_cpu(r->write_time));
1963 }
1964
1965 struct bch_fs *bch2_fs_open(char * const *devices, unsigned nr_devices,
1966                             struct bch_opts opts)
1967 {
1968         DARRAY(struct bch_sb_handle) sbs = { 0 };
1969         struct bch_fs *c = NULL;
1970         struct bch_sb_handle *best = NULL;
1971         struct printbuf errbuf = PRINTBUF;
1972         int ret = 0;
1973
1974         if (!try_module_get(THIS_MODULE))
1975                 return ERR_PTR(-ENODEV);
1976
1977         if (!nr_devices) {
1978                 ret = -EINVAL;
1979                 goto err;
1980         }
1981
1982         ret = darray_make_room(&sbs, nr_devices);
1983         if (ret)
1984                 goto err;
1985
1986         for (unsigned i = 0; i < nr_devices; i++) {
1987                 struct bch_sb_handle sb = { NULL };
1988
1989                 ret = bch2_read_super(devices[i], &opts, &sb);
1990                 if (ret)
1991                         goto err;
1992
1993                 BUG_ON(darray_push(&sbs, sb));
1994         }
1995
1996         if (opts.nochanges && !opts.read_only) {
1997                 ret = -BCH_ERR_erofs_nochanges;
1998                 goto err_print;
1999         }
2000
2001         darray_for_each(sbs, sb)
2002                 if (!best || sb_cmp(sb->sb, best->sb) > 0)
2003                         best = sb;
2004
2005         darray_for_each_reverse(sbs, sb) {
2006                 ret = bch2_dev_in_fs(best, sb);
2007
2008                 if (ret == -BCH_ERR_device_has_been_removed ||
2009                     ret == -BCH_ERR_device_splitbrain) {
2010                         bch2_free_super(sb);
2011                         darray_remove_item(&sbs, sb);
2012                         best -= best > sb;
2013                         ret = 0;
2014                         continue;
2015                 }
2016
2017                 if (ret)
2018                         goto err_print;
2019         }
2020
2021         c = bch2_fs_alloc(best->sb, opts);
2022         ret = PTR_ERR_OR_ZERO(c);
2023         if (ret)
2024                 goto err;
2025
2026         down_write(&c->state_lock);
2027         darray_for_each(sbs, sb) {
2028                 ret = bch2_dev_attach_bdev(c, sb);
2029                 if (ret) {
2030                         up_write(&c->state_lock);
2031                         goto err;
2032                 }
2033         }
2034         up_write(&c->state_lock);
2035
2036         if (!bch2_fs_may_start(c)) {
2037                 ret = -BCH_ERR_insufficient_devices_to_start;
2038                 goto err_print;
2039         }
2040
2041         if (!c->opts.nostart) {
2042                 ret = bch2_fs_start(c);
2043                 if (ret)
2044                         goto err;
2045         }
2046 out:
2047         darray_for_each(sbs, sb)
2048                 bch2_free_super(sb);
2049         darray_exit(&sbs);
2050         printbuf_exit(&errbuf);
2051         module_put(THIS_MODULE);
2052         return c;
2053 err_print:
2054         pr_err("bch_fs_open err opening %s: %s",
2055                devices[0], bch2_err_str(ret));
2056 err:
2057         if (!IS_ERR_OR_NULL(c))
2058                 bch2_fs_stop(c);
2059         c = ERR_PTR(ret);
2060         goto out;
2061 }
2062
2063 /* Global interfaces/init */
2064
2065 static void bcachefs_exit(void)
2066 {
2067         bch2_debug_exit();
2068         bch2_vfs_exit();
2069         bch2_chardev_exit();
2070         bch2_btree_key_cache_exit();
2071         if (bcachefs_kset)
2072                 kset_unregister(bcachefs_kset);
2073 }
2074
2075 static int __init bcachefs_init(void)
2076 {
2077         bch2_bkey_pack_test();
2078
2079         if (!(bcachefs_kset = kset_create_and_add("bcachefs", NULL, fs_kobj)) ||
2080             bch2_btree_key_cache_init() ||
2081             bch2_chardev_init() ||
2082             bch2_vfs_init() ||
2083             bch2_debug_init())
2084                 goto err;
2085
2086         return 0;
2087 err:
2088         bcachefs_exit();
2089         return -ENOMEM;
2090 }
2091
2092 #define BCH_DEBUG_PARAM(name, description)                      \
2093         bool bch2_##name;                                       \
2094         module_param_named(name, bch2_##name, bool, 0644);      \
2095         MODULE_PARM_DESC(name, description);
2096 BCH_DEBUG_PARAMS()
2097 #undef BCH_DEBUG_PARAM
2098
2099 __maybe_unused
2100 static unsigned bch2_metadata_version = bcachefs_metadata_version_current;
2101 module_param_named(version, bch2_metadata_version, uint, 0400);
2102
2103 module_exit(bcachefs_exit);
2104 module_init(bcachefs_init);