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