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