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