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