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