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