]> git.sesse.net Git - bcachefs-tools-debian/blob - libbcachefs/super.c
Update bcachefs sources to e7f4678827 bcachefs: fix variable shadowing in macro call
[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         rcu_read_lock();
153         if (bdi_bits & (1 << WB_sync_congested)) {
154                 /* Reads - check all devices: */
155                 for_each_readable_member(ca, c, i) {
156                         bdi = ca->disk_sb.bdev->bd_bdi;
157
158                         if (bdi_congested(bdi, bdi_bits)) {
159                                 ret = 1;
160                                 break;
161                         }
162                 }
163         } else {
164                 unsigned target = READ_ONCE(c->opts.foreground_target);
165                 const struct bch_devs_mask *devs = target
166                         ? bch2_target_to_mask(c, target)
167                         : &c->rw_devs[BCH_DATA_USER];
168
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         }
178         rcu_read_unlock();
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 rebalance (to free up space)
189  *
190  * - copygc and rebalance 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_rebalance_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 rebalance thread";
389         if (bch2_rebalance_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_rebalance_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         c->copy_gc_enabled = 1;
555         c->rebalance_enabled = 1;
556         c->rebalance_percent = 10;
557
558         c->journal.write_time   = &c->journal_write_time;
559         c->journal.delay_time   = &c->journal_delay_time;
560         c->journal.blocked_time = &c->journal_blocked_time;
561         c->journal.flush_seq_time = &c->journal_flush_seq_time;
562
563         bch2_fs_btree_cache_init_early(&c->btree_cache);
564
565         mutex_lock(&c->sb_lock);
566
567         if (bch2_sb_to_fs(c, sb)) {
568                 mutex_unlock(&c->sb_lock);
569                 goto err;
570         }
571
572         mutex_unlock(&c->sb_lock);
573
574         scnprintf(c->name, sizeof(c->name), "%pU", &c->sb.user_uuid);
575
576         c->opts = bch2_opts_default;
577         bch2_opts_apply(&c->opts, bch2_opts_from_sb(sb));
578         bch2_opts_apply(&c->opts, opts);
579
580         c->block_bits           = ilog2(c->opts.block_size);
581         c->btree_foreground_merge_threshold = BTREE_FOREGROUND_MERGE_THRESHOLD(c);
582
583         c->opts.nochanges       |= c->opts.noreplay;
584         c->opts.read_only       |= c->opts.nochanges;
585
586         if (bch2_fs_init_fault("fs_alloc"))
587                 goto err;
588
589         iter_size = sizeof(struct btree_node_iter_large) +
590                 (btree_blocks(c) + 1) * 2 *
591                 sizeof(struct btree_node_iter_set);
592
593         if (!(c->wq = alloc_workqueue("bcachefs",
594                                 WQ_FREEZABLE|WQ_MEM_RECLAIM|WQ_HIGHPRI, 1)) ||
595             !(c->copygc_wq = alloc_workqueue("bcache_copygc",
596                                 WQ_FREEZABLE|WQ_MEM_RECLAIM|WQ_HIGHPRI, 1)) ||
597             percpu_ref_init(&c->writes, bch2_writes_disabled, 0, GFP_KERNEL) ||
598             mempool_init_kmalloc_pool(&c->btree_reserve_pool, 1,
599                                       sizeof(struct btree_reserve)) ||
600             mempool_init_kmalloc_pool(&c->btree_interior_update_pool, 1,
601                                       sizeof(struct btree_update)) ||
602             mempool_init_kmalloc_pool(&c->fill_iter, 1, iter_size) ||
603             bioset_init(&c->btree_bio, 1,
604                         max(offsetof(struct btree_read_bio, bio),
605                             offsetof(struct btree_write_bio, wbio.bio)),
606                         BIOSET_NEED_BVECS) ||
607             bioset_init(&c->bio_read, 1, offsetof(struct bch_read_bio, bio),
608                         BIOSET_NEED_BVECS) ||
609             bioset_init(&c->bio_read_split, 1, offsetof(struct bch_read_bio, bio),
610                         BIOSET_NEED_BVECS) ||
611             bioset_init(&c->bio_write, 1, offsetof(struct bch_write_bio, bio),
612                         BIOSET_NEED_BVECS) ||
613             mempool_init_page_pool(&c->bio_bounce_pages,
614                                    max_t(unsigned,
615                                          c->opts.btree_node_size,
616                                          c->sb.encoded_extent_max) /
617                                    PAGE_SECTORS, 0) ||
618             !(c->usage_percpu = alloc_percpu(struct bch_fs_usage)) ||
619             lg_lock_init(&c->usage_lock) ||
620             mempool_init_vp_pool(&c->btree_bounce_pool, 1, btree_bytes(c)) ||
621             bch2_io_clock_init(&c->io_clock[READ]) ||
622             bch2_io_clock_init(&c->io_clock[WRITE]) ||
623             bch2_fs_journal_init(&c->journal) ||
624             bch2_fs_btree_cache_init(c) ||
625             bch2_fs_encryption_init(c) ||
626             bch2_fs_compress_init(c) ||
627             bch2_fs_fsio_init(c))
628                 goto err;
629
630         mi = bch2_sb_get_members(c->disk_sb);
631         for (i = 0; i < c->sb.nr_devices; i++)
632                 if (bch2_dev_exists(c->disk_sb, mi, i) &&
633                     bch2_dev_alloc(c, i))
634                         goto err;
635
636         /*
637          * Now that all allocations have succeeded, init various refcounty
638          * things that let us shutdown:
639          */
640         closure_init(&c->cl, NULL);
641
642         c->kobj.kset = bcachefs_kset;
643         kobject_init(&c->kobj, &bch2_fs_ktype);
644         kobject_init(&c->internal, &bch2_fs_internal_ktype);
645         kobject_init(&c->opts_dir, &bch2_fs_opts_dir_ktype);
646         kobject_init(&c->time_stats, &bch2_fs_time_stats_ktype);
647 out:
648         pr_verbose_init(opts, "ret %i", c ? 0 : -ENOMEM);
649         return c;
650 err:
651         bch2_fs_free(c);
652         c = NULL;
653         goto out;
654 }
655
656 static const char *__bch2_fs_online(struct bch_fs *c)
657 {
658         struct bch_dev *ca;
659         const char *err = NULL;
660         unsigned i;
661         int ret;
662
663         lockdep_assert_held(&bch_fs_list_lock);
664
665         if (!list_empty(&c->list))
666                 return NULL;
667
668         if (__bch2_uuid_to_fs(c->sb.uuid))
669                 return "filesystem UUID already open";
670
671         ret = bch2_fs_chardev_init(c);
672         if (ret)
673                 return "error creating character device";
674
675         bch2_fs_debug_init(c);
676
677         if (kobject_add(&c->kobj, NULL, "%pU", c->sb.user_uuid.b) ||
678             kobject_add(&c->internal, &c->kobj, "internal") ||
679             kobject_add(&c->opts_dir, &c->kobj, "options") ||
680             kobject_add(&c->time_stats, &c->kobj, "time_stats") ||
681             bch2_opts_create_sysfs_files(&c->opts_dir))
682                 return "error creating sysfs objects";
683
684         mutex_lock(&c->state_lock);
685
686         err = "error creating sysfs objects";
687         __for_each_member_device(ca, c, i, NULL)
688                 if (bch2_dev_sysfs_online(c, ca))
689                         goto err;
690
691         list_add(&c->list, &bch_fs_list);
692         err = NULL;
693 err:
694         mutex_unlock(&c->state_lock);
695         return err;
696 }
697
698 static const char *bch2_fs_online(struct bch_fs *c)
699 {
700         const char *err;
701
702         mutex_lock(&bch_fs_list_lock);
703         err = __bch2_fs_online(c);
704         mutex_unlock(&bch_fs_list_lock);
705
706         return err;
707 }
708
709 static const char *__bch2_fs_start(struct bch_fs *c)
710 {
711         const char *err = "cannot allocate memory";
712         struct bch_sb_field_members *mi;
713         struct bch_dev *ca;
714         LIST_HEAD(journal);
715         struct jset *j;
716         time64_t now;
717         unsigned i;
718         int ret = -EINVAL;
719
720         mutex_lock(&c->state_lock);
721
722         BUG_ON(c->state != BCH_FS_STARTING);
723
724         mutex_lock(&c->sb_lock);
725         for_each_online_member(ca, c, i)
726                 bch2_sb_from_fs(c, ca);
727         mutex_unlock(&c->sb_lock);
728
729         for_each_rw_member(ca, c, i)
730                 bch2_dev_allocator_add(c, ca);
731         bch2_recalc_capacity(c);
732
733         if (BCH_SB_INITIALIZED(c->disk_sb)) {
734                 ret = bch2_journal_read(c, &journal);
735                 if (ret)
736                         goto err;
737
738                 j = &list_entry(journal.prev, struct journal_replay, list)->j;
739
740                 c->prio_clock[READ].hand = le16_to_cpu(j->read_clock);
741                 c->prio_clock[WRITE].hand = le16_to_cpu(j->write_clock);
742
743                 for (i = 0; i < BTREE_ID_NR; i++) {
744                         unsigned level;
745                         struct bkey_i *k;
746
747                         k = bch2_journal_find_btree_root(c, j, i, &level);
748                         if (!k)
749                                 continue;
750
751                         err = "invalid btree root pointer";
752                         if (IS_ERR(k))
753                                 goto err;
754
755                         err = "error reading btree root";
756                         if (bch2_btree_root_read(c, i, k, level)) {
757                                 if (i != BTREE_ID_ALLOC)
758                                         goto err;
759
760                                 mustfix_fsck_err(c, "error reading btree root");
761                         }
762                 }
763
764                 for (i = 0; i < BTREE_ID_NR; i++)
765                         if (!c->btree_roots[i].b)
766                                 bch2_btree_root_alloc(c, i);
767
768                 err = "error reading allocation information";
769                 ret = bch2_alloc_read(c, &journal);
770                 if (ret)
771                         goto err;
772
773                 set_bit(BCH_FS_ALLOC_READ_DONE, &c->flags);
774
775                 bch_verbose(c, "starting mark and sweep:");
776                 err = "error in recovery";
777                 ret = bch2_initial_gc(c, &journal);
778                 if (ret)
779                         goto err;
780                 bch_verbose(c, "mark and sweep done");
781
782                 if (c->opts.noreplay)
783                         goto recovery_done;
784
785                 /*
786                  * bch2_journal_start() can't happen sooner, or btree_gc_finish()
787                  * will give spurious errors about oldest_gen > bucket_gen -
788                  * this is a hack but oh well.
789                  */
790                 bch2_journal_start(c);
791
792                 err = "error starting allocator";
793                 if (bch2_fs_allocator_start(c))
794                         goto err;
795
796                 bch_verbose(c, "starting journal replay:");
797                 err = "journal replay failed";
798                 ret = bch2_journal_replay(c, &journal);
799                 if (ret)
800                         goto err;
801                 bch_verbose(c, "journal replay done");
802
803                 if (c->opts.norecovery)
804                         goto recovery_done;
805
806                 bch_verbose(c, "starting fsck:");
807                 err = "error in fsck";
808                 ret = bch2_fsck(c, !c->opts.nofsck);
809                 if (ret)
810                         goto err;
811                 bch_verbose(c, "fsck done");
812
813                 if (enabled_qtypes(c)) {
814                         bch_verbose(c, "reading quotas:");
815                         ret = bch2_fs_quota_read(c);
816                         if (ret)
817                                 goto err;
818                         bch_verbose(c, "quotas done");
819                 }
820         } else {
821                 struct bch_inode_unpacked inode;
822                 struct bkey_inode_buf packed_inode;
823
824                 bch_notice(c, "initializing new filesystem");
825
826                 set_bit(BCH_FS_ALLOC_READ_DONE, &c->flags);
827                 set_bit(BCH_FS_BRAND_NEW_FS, &c->flags);
828
829                 ret = bch2_initial_gc(c, &journal);
830                 if (ret)
831                         goto err;
832
833                 err = "unable to allocate journal buckets";
834                 for_each_rw_member(ca, c, i)
835                         if (bch2_dev_journal_alloc(c, ca)) {
836                                 percpu_ref_put(&ca->io_ref);
837                                 goto err;
838                         }
839
840                 clear_bit(BCH_FS_BRAND_NEW_FS, &c->flags);
841
842                 for (i = 0; i < BTREE_ID_NR; i++)
843                         bch2_btree_root_alloc(c, i);
844
845                 /*
846                  * journal_res_get() will crash if called before this has
847                  * set up the journal.pin FIFO and journal.cur pointer:
848                  */
849                 bch2_journal_start(c);
850                 bch2_journal_set_replay_done(&c->journal);
851
852                 err = "error starting allocator";
853                 if (bch2_fs_allocator_start(c))
854                         goto err;
855
856                 bch2_inode_init(c, &inode, 0, 0,
857                                S_IFDIR|S_IRWXU|S_IRUGO|S_IXUGO, 0, NULL);
858                 inode.bi_inum = BCACHEFS_ROOT_INO;
859
860                 bch2_inode_pack(&packed_inode, &inode);
861
862                 err = "error creating root directory";
863                 if (bch2_btree_insert(c, BTREE_ID_INODES,
864                                      &packed_inode.inode.k_i,
865                                      NULL, NULL, NULL, 0))
866                         goto err;
867
868                 if (enabled_qtypes(c)) {
869                         ret = bch2_fs_quota_read(c);
870                         if (ret)
871                                 goto err;
872                 }
873
874                 err = "error writing first journal entry";
875                 if (bch2_journal_meta(&c->journal))
876                         goto err;
877         }
878 recovery_done:
879         err = "dynamic fault";
880         if (bch2_fs_init_fault("fs_start"))
881                 goto err;
882
883         if (c->opts.read_only) {
884                 bch2_fs_read_only(c);
885         } else {
886                 err = bch2_fs_read_write(c);
887                 if (err)
888                         goto err;
889         }
890
891         mutex_lock(&c->sb_lock);
892         mi = bch2_sb_get_members(c->disk_sb);
893         now = ktime_get_seconds();
894
895         for_each_member_device(ca, c, i)
896                 mi->members[ca->dev_idx].last_mount = cpu_to_le64(now);
897
898         SET_BCH_SB_INITIALIZED(c->disk_sb, true);
899         SET_BCH_SB_CLEAN(c->disk_sb, false);
900
901         bch2_write_super(c);
902         mutex_unlock(&c->sb_lock);
903
904         err = NULL;
905 out:
906         mutex_unlock(&c->state_lock);
907         bch2_journal_entries_free(&journal);
908         return err;
909 err:
910 fsck_err:
911         switch (ret) {
912         case BCH_FSCK_ERRORS_NOT_FIXED:
913                 bch_err(c, "filesystem contains errors: please report this to the developers");
914                 pr_cont("mount with -o fix_errors to repair\n");
915                 err = "fsck error";
916                 break;
917         case BCH_FSCK_REPAIR_UNIMPLEMENTED:
918                 bch_err(c, "filesystem contains errors: please report this to the developers");
919                 pr_cont("repair unimplemented: inform the developers so that it can be added\n");
920                 err = "fsck error";
921                 break;
922         case BCH_FSCK_REPAIR_IMPOSSIBLE:
923                 bch_err(c, "filesystem contains errors, but repair impossible");
924                 err = "fsck error";
925                 break;
926         case BCH_FSCK_UNKNOWN_VERSION:
927                 err = "unknown metadata version";;
928                 break;
929         case -ENOMEM:
930                 err = "cannot allocate memory";
931                 break;
932         case -EIO:
933                 err = "IO error";
934                 break;
935         }
936
937         BUG_ON(!err);
938         set_bit(BCH_FS_ERROR, &c->flags);
939         goto out;
940 }
941
942 const char *bch2_fs_start(struct bch_fs *c)
943 {
944         return __bch2_fs_start(c) ?: bch2_fs_online(c);
945 }
946
947 static const char *bch2_dev_may_add(struct bch_sb *sb, struct bch_fs *c)
948 {
949         struct bch_sb_field_members *sb_mi;
950
951         sb_mi = bch2_sb_get_members(sb);
952         if (!sb_mi)
953                 return "Invalid superblock: member info area missing";
954
955         if (le16_to_cpu(sb->block_size) != c->opts.block_size)
956                 return "mismatched block size";
957
958         if (le16_to_cpu(sb_mi->members[sb->dev_idx].bucket_size) <
959             BCH_SB_BTREE_NODE_SIZE(c->disk_sb))
960                 return "new cache bucket size is too small";
961
962         return NULL;
963 }
964
965 static const char *bch2_dev_in_fs(struct bch_sb *fs, struct bch_sb *sb)
966 {
967         struct bch_sb *newest =
968                 le64_to_cpu(fs->seq) > le64_to_cpu(sb->seq) ? fs : sb;
969         struct bch_sb_field_members *mi = bch2_sb_get_members(newest);
970
971         if (uuid_le_cmp(fs->uuid, sb->uuid))
972                 return "device not a member of filesystem";
973
974         if (!bch2_dev_exists(newest, mi, sb->dev_idx))
975                 return "device has been removed";
976
977         if (fs->block_size != sb->block_size)
978                 return "mismatched block size";
979
980         return NULL;
981 }
982
983 /* Device startup/shutdown: */
984
985 static void bch2_dev_release(struct kobject *kobj)
986 {
987         struct bch_dev *ca = container_of(kobj, struct bch_dev, kobj);
988
989         kfree(ca);
990 }
991
992 static void bch2_dev_free(struct bch_dev *ca)
993 {
994         cancel_work_sync(&ca->io_error_work);
995
996         if (ca->kobj.state_in_sysfs &&
997             ca->disk_sb.bdev)
998                 sysfs_remove_link(&part_to_dev(ca->disk_sb.bdev->bd_part)->kobj,
999                                   "bcachefs");
1000
1001         if (ca->kobj.state_in_sysfs)
1002                 kobject_del(&ca->kobj);
1003
1004         bch2_free_super(&ca->disk_sb);
1005         bch2_dev_journal_exit(ca);
1006
1007         free_percpu(ca->io_done);
1008         bioset_exit(&ca->replica_set);
1009         bch2_dev_buckets_free(ca);
1010
1011         percpu_ref_exit(&ca->io_ref);
1012         percpu_ref_exit(&ca->ref);
1013         kobject_put(&ca->kobj);
1014 }
1015
1016 static void __bch2_dev_offline(struct bch_fs *c, struct bch_dev *ca)
1017 {
1018
1019         lockdep_assert_held(&c->state_lock);
1020
1021         if (percpu_ref_is_zero(&ca->io_ref))
1022                 return;
1023
1024         __bch2_dev_read_only(c, ca);
1025
1026         reinit_completion(&ca->io_ref_completion);
1027         percpu_ref_kill(&ca->io_ref);
1028         wait_for_completion(&ca->io_ref_completion);
1029
1030         if (ca->kobj.state_in_sysfs) {
1031                 struct kobject *block =
1032                         &part_to_dev(ca->disk_sb.bdev->bd_part)->kobj;
1033
1034                 sysfs_remove_link(block, "bcachefs");
1035                 sysfs_remove_link(&ca->kobj, "block");
1036         }
1037
1038         bch2_free_super(&ca->disk_sb);
1039         bch2_dev_journal_exit(ca);
1040 }
1041
1042 static void bch2_dev_ref_complete(struct percpu_ref *ref)
1043 {
1044         struct bch_dev *ca = container_of(ref, struct bch_dev, ref);
1045
1046         complete(&ca->ref_completion);
1047 }
1048
1049 static void bch2_dev_io_ref_complete(struct percpu_ref *ref)
1050 {
1051         struct bch_dev *ca = container_of(ref, struct bch_dev, io_ref);
1052
1053         complete(&ca->io_ref_completion);
1054 }
1055
1056 static int bch2_dev_sysfs_online(struct bch_fs *c, struct bch_dev *ca)
1057 {
1058         int ret;
1059
1060         if (!c->kobj.state_in_sysfs)
1061                 return 0;
1062
1063         if (!ca->kobj.state_in_sysfs) {
1064                 ret = kobject_add(&ca->kobj, &c->kobj,
1065                                   "dev-%u", ca->dev_idx);
1066                 if (ret)
1067                         return ret;
1068         }
1069
1070         if (ca->disk_sb.bdev) {
1071                 struct kobject *block =
1072                         &part_to_dev(ca->disk_sb.bdev->bd_part)->kobj;
1073
1074                 ret = sysfs_create_link(block, &ca->kobj, "bcachefs");
1075                 if (ret)
1076                         return ret;
1077                 ret = sysfs_create_link(&ca->kobj, block, "block");
1078                 if (ret)
1079                         return ret;
1080         }
1081
1082         return 0;
1083 }
1084
1085 static int bch2_dev_alloc(struct bch_fs *c, unsigned dev_idx)
1086 {
1087         struct bch_member *member;
1088         struct bch_dev *ca = NULL;
1089         int ret = 0;
1090
1091         pr_verbose_init(c->opts, "");
1092
1093         if (bch2_fs_init_fault("dev_alloc"))
1094                 goto err;
1095
1096         ca = kzalloc(sizeof(*ca), GFP_KERNEL);
1097         if (!ca)
1098                 goto err;
1099
1100         kobject_init(&ca->kobj, &bch2_dev_ktype);
1101         init_completion(&ca->ref_completion);
1102         init_completion(&ca->io_ref_completion);
1103
1104         ca->dev_idx = dev_idx;
1105         __set_bit(ca->dev_idx, ca->self.d);
1106
1107         init_rwsem(&ca->bucket_lock);
1108
1109         writepoint_init(&ca->copygc_write_point, BCH_DATA_USER);
1110
1111         spin_lock_init(&ca->freelist_lock);
1112         bch2_dev_copygc_init(ca);
1113
1114         INIT_WORK(&ca->io_error_work, bch2_io_error_work);
1115
1116         if (bch2_fs_init_fault("dev_alloc"))
1117                 goto err;
1118
1119         member = bch2_sb_get_members(c->disk_sb)->members + dev_idx;
1120
1121         ca->mi = bch2_mi_to_cpu(member);
1122         ca->uuid = member->uuid;
1123         scnprintf(ca->name, sizeof(ca->name), "dev-%u", dev_idx);
1124
1125         if (percpu_ref_init(&ca->ref, bch2_dev_ref_complete,
1126                             0, GFP_KERNEL) ||
1127             percpu_ref_init(&ca->io_ref, bch2_dev_io_ref_complete,
1128                             PERCPU_REF_INIT_DEAD, GFP_KERNEL) ||
1129             bch2_dev_buckets_alloc(c, ca) ||
1130             bioset_init(&ca->replica_set, 4,
1131                         offsetof(struct bch_write_bio, bio), 0) ||
1132             !(ca->io_done       = alloc_percpu(*ca->io_done)))
1133                 goto err;
1134
1135         ca->fs = c;
1136         rcu_assign_pointer(c->devs[ca->dev_idx], ca);
1137
1138         if (bch2_dev_sysfs_online(c, ca))
1139                 pr_warn("error creating sysfs objects");
1140 out:
1141         pr_verbose_init(c->opts, "ret %i", ret);
1142         return ret;
1143 err:
1144         if (ca)
1145                 bch2_dev_free(ca);
1146         ret = -ENOMEM;
1147         goto out;
1148 }
1149
1150 static int __bch2_dev_online(struct bch_fs *c, struct bch_sb_handle *sb)
1151 {
1152         struct bch_dev *ca;
1153         int ret;
1154
1155         lockdep_assert_held(&c->state_lock);
1156
1157         if (le64_to_cpu(sb->sb->seq) >
1158             le64_to_cpu(c->disk_sb->seq))
1159                 bch2_sb_to_fs(c, sb->sb);
1160
1161         BUG_ON(sb->sb->dev_idx >= c->sb.nr_devices ||
1162                !c->devs[sb->sb->dev_idx]);
1163
1164         ca = bch_dev_locked(c, sb->sb->dev_idx);
1165
1166         if (bch2_dev_is_online(ca)) {
1167                 bch_err(ca, "already have device online in slot %u",
1168                         sb->sb->dev_idx);
1169                 return -EINVAL;
1170         }
1171
1172         if (get_capacity(sb->bdev->bd_disk) <
1173             ca->mi.bucket_size * ca->mi.nbuckets) {
1174                 bch_err(ca, "cannot online: device too small");
1175                 return -EINVAL;
1176         }
1177
1178         BUG_ON(!percpu_ref_is_zero(&ca->io_ref));
1179
1180         if (get_capacity(sb->bdev->bd_disk) <
1181             ca->mi.bucket_size * ca->mi.nbuckets) {
1182                 bch_err(c, "device too small");
1183                 return -EINVAL;
1184         }
1185
1186         ret = bch2_dev_journal_init(ca, sb->sb);
1187         if (ret)
1188                 return ret;
1189
1190         /*
1191          * Increase journal write timeout if flushes to this device are
1192          * expensive:
1193          */
1194         if (!blk_queue_nonrot(bdev_get_queue(sb->bdev)) &&
1195             journal_flushes_device(ca))
1196                 c->journal.write_delay_ms =
1197                         max(c->journal.write_delay_ms, 1000U);
1198
1199         /* Commit: */
1200         ca->disk_sb = *sb;
1201         if (sb->mode & FMODE_EXCL)
1202                 ca->disk_sb.bdev->bd_holder = ca;
1203         memset(sb, 0, sizeof(*sb));
1204
1205         if (c->sb.nr_devices == 1)
1206                 bdevname(ca->disk_sb.bdev, c->name);
1207         bdevname(ca->disk_sb.bdev, ca->name);
1208
1209         mutex_lock(&c->sb_lock);
1210         bch2_mark_dev_superblock(c, ca, BCH_BUCKET_MARK_MAY_MAKE_UNAVAILABLE);
1211         mutex_unlock(&c->sb_lock);
1212
1213         if (ca->mi.state == BCH_MEMBER_STATE_RW)
1214                 bch2_dev_allocator_add(c, ca);
1215
1216         rebalance_wakeup(c);
1217
1218         percpu_ref_reinit(&ca->io_ref);
1219         return 0;
1220 }
1221
1222 /* Device management: */
1223
1224 /*
1225  * Note: this function is also used by the error paths - when a particular
1226  * device sees an error, we call it to determine whether we can just set the
1227  * device RO, or - if this function returns false - we'll set the whole
1228  * filesystem RO:
1229  *
1230  * XXX: maybe we should be more explicit about whether we're changing state
1231  * because we got an error or what have you?
1232  */
1233 bool bch2_dev_state_allowed(struct bch_fs *c, struct bch_dev *ca,
1234                             enum bch_member_state new_state, int flags)
1235 {
1236         struct bch_devs_mask new_online_devs;
1237         struct replicas_status s;
1238         struct bch_dev *ca2;
1239         int i, nr_rw = 0, required;
1240
1241         lockdep_assert_held(&c->state_lock);
1242
1243         switch (new_state) {
1244         case BCH_MEMBER_STATE_RW:
1245                 return true;
1246         case BCH_MEMBER_STATE_RO:
1247                 if (ca->mi.state != BCH_MEMBER_STATE_RW)
1248                         return true;
1249
1250                 /* do we have enough devices to write to?  */
1251                 for_each_member_device(ca2, c, i)
1252                         if (ca2 != ca)
1253                                 nr_rw += ca2->mi.state == BCH_MEMBER_STATE_RW;
1254
1255                 required = max(!(flags & BCH_FORCE_IF_METADATA_DEGRADED)
1256                                ? c->opts.metadata_replicas
1257                                : c->opts.metadata_replicas_required,
1258                                !(flags & BCH_FORCE_IF_DATA_DEGRADED)
1259                                ? c->opts.data_replicas
1260                                : c->opts.data_replicas_required);
1261
1262                 return nr_rw >= required;
1263         case BCH_MEMBER_STATE_FAILED:
1264         case BCH_MEMBER_STATE_SPARE:
1265                 if (ca->mi.state != BCH_MEMBER_STATE_RW &&
1266                     ca->mi.state != BCH_MEMBER_STATE_RO)
1267                         return true;
1268
1269                 /* do we have enough devices to read from?  */
1270                 new_online_devs = bch2_online_devs(c);
1271                 __clear_bit(ca->dev_idx, new_online_devs.d);
1272
1273                 s = __bch2_replicas_status(c, new_online_devs);
1274
1275                 return bch2_have_enough_devs(s, flags);
1276         default:
1277                 BUG();
1278         }
1279 }
1280
1281 static bool bch2_fs_may_start(struct bch_fs *c)
1282 {
1283         struct replicas_status s;
1284         struct bch_sb_field_members *mi;
1285         struct bch_dev *ca;
1286         unsigned i, flags = c->opts.degraded
1287                 ? BCH_FORCE_IF_DEGRADED
1288                 : 0;
1289
1290         if (!c->opts.degraded) {
1291                 mutex_lock(&c->sb_lock);
1292                 mi = bch2_sb_get_members(c->disk_sb);
1293
1294                 for (i = 0; i < c->disk_sb->nr_devices; i++) {
1295                         if (!bch2_dev_exists(c->disk_sb, mi, i))
1296                                 continue;
1297
1298                         ca = bch_dev_locked(c, i);
1299
1300                         if (!bch2_dev_is_online(ca) &&
1301                             (ca->mi.state == BCH_MEMBER_STATE_RW ||
1302                              ca->mi.state == BCH_MEMBER_STATE_RO)) {
1303                                 mutex_unlock(&c->sb_lock);
1304                                 return false;
1305                         }
1306                 }
1307                 mutex_unlock(&c->sb_lock);
1308         }
1309
1310         s = bch2_replicas_status(c);
1311
1312         return bch2_have_enough_devs(s, flags);
1313 }
1314
1315 static void __bch2_dev_read_only(struct bch_fs *c, struct bch_dev *ca)
1316 {
1317         bch2_copygc_stop(ca);
1318
1319         /*
1320          * The allocator thread itself allocates btree nodes, so stop it first:
1321          */
1322         bch2_dev_allocator_stop(ca);
1323         bch2_dev_allocator_remove(c, ca);
1324         bch2_dev_journal_stop(&c->journal, ca);
1325 }
1326
1327 static const char *__bch2_dev_read_write(struct bch_fs *c, struct bch_dev *ca)
1328 {
1329         lockdep_assert_held(&c->state_lock);
1330
1331         BUG_ON(ca->mi.state != BCH_MEMBER_STATE_RW);
1332
1333         bch2_dev_allocator_add(c, ca);
1334         bch2_recalc_capacity(c);
1335
1336         if (bch2_dev_allocator_start(ca))
1337                 return "error starting allocator thread";
1338
1339         if (bch2_copygc_start(c, ca))
1340                 return "error starting copygc thread";
1341
1342         return NULL;
1343 }
1344
1345 int __bch2_dev_set_state(struct bch_fs *c, struct bch_dev *ca,
1346                          enum bch_member_state new_state, int flags)
1347 {
1348         struct bch_sb_field_members *mi;
1349         int ret = 0;
1350
1351         if (ca->mi.state == new_state)
1352                 return 0;
1353
1354         if (!bch2_dev_state_allowed(c, ca, new_state, flags))
1355                 return -EINVAL;
1356
1357         if (new_state != BCH_MEMBER_STATE_RW)
1358                 __bch2_dev_read_only(c, ca);
1359
1360         bch_notice(ca, "%s", bch2_dev_state[new_state]);
1361
1362         mutex_lock(&c->sb_lock);
1363         mi = bch2_sb_get_members(c->disk_sb);
1364         SET_BCH_MEMBER_STATE(&mi->members[ca->dev_idx], new_state);
1365         bch2_write_super(c);
1366         mutex_unlock(&c->sb_lock);
1367
1368         if (new_state == BCH_MEMBER_STATE_RW &&
1369             __bch2_dev_read_write(c, ca))
1370                 ret = -ENOMEM;
1371
1372         rebalance_wakeup(c);
1373
1374         return ret;
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 /* return with ref on ca->ref: */
1704 struct bch_dev *bch2_dev_lookup(struct bch_fs *c, const char *path)
1705 {
1706
1707         struct block_device *bdev = lookup_bdev(path);
1708         struct bch_dev *ca;
1709         unsigned i;
1710
1711         if (IS_ERR(bdev))
1712                 return ERR_CAST(bdev);
1713
1714         for_each_member_device(ca, c, i)
1715                 if (ca->disk_sb.bdev == bdev)
1716                         goto found;
1717
1718         ca = ERR_PTR(-ENOENT);
1719 found:
1720         bdput(bdev);
1721         return ca;
1722 }
1723
1724 int bch2_dev_group_set(struct bch_fs *c, struct bch_dev *ca, const char *label)
1725 {
1726         struct bch_sb_field_disk_groups *groups;
1727         struct bch_disk_group *g;
1728         struct bch_member *mi;
1729         unsigned i, v, nr_groups;
1730         int ret;
1731
1732         if (strlen(label) > BCH_SB_LABEL_SIZE)
1733                 return -EINVAL;
1734
1735         mutex_lock(&c->sb_lock);
1736         groups          = bch2_sb_get_disk_groups(c->disk_sb);
1737         nr_groups       = disk_groups_nr(groups);
1738
1739         if (!strcmp(label, "none")) {
1740                 v = 0;
1741                 goto write_sb;
1742         }
1743
1744         ret = __bch2_disk_group_find(groups, label);
1745         if (ret >= 0) {
1746                 v = ret + 1;
1747                 goto write_sb;
1748         }
1749
1750         /* not found - create a new disk group: */
1751
1752         for (i = 0;
1753              i < nr_groups && !BCH_GROUP_DELETED(&groups->entries[i]);
1754              i++)
1755                 ;
1756
1757         if (i == nr_groups) {
1758                 unsigned u64s =
1759                         (sizeof(struct bch_sb_field_disk_groups) +
1760                          sizeof(struct bch_disk_group) * (nr_groups + 1)) /
1761                         sizeof(u64);
1762
1763                 groups = bch2_fs_sb_resize_disk_groups(c, u64s);
1764                 if (!groups) {
1765                         mutex_unlock(&c->sb_lock);
1766                         return -ENOSPC;
1767                 }
1768
1769                 nr_groups = disk_groups_nr(groups);
1770         }
1771
1772         BUG_ON(i >= nr_groups);
1773
1774         g = &groups->entries[i];
1775         v = i + 1;
1776
1777         memcpy(g->label, label, strlen(label));
1778         if (strlen(label) < sizeof(g->label))
1779                 g->label[strlen(label)] = '\0';
1780         SET_BCH_GROUP_DELETED(g, 0);
1781         SET_BCH_GROUP_DATA_ALLOWED(g, ~0);
1782 write_sb:
1783         mi = &bch2_sb_get_members(c->disk_sb)->members[ca->dev_idx];
1784         SET_BCH_MEMBER_GROUP(mi, v);
1785
1786         bch2_write_super(c);
1787         mutex_unlock(&c->sb_lock);
1788
1789         return 0;
1790 }
1791
1792 /* Filesystem open: */
1793
1794 struct bch_fs *bch2_fs_open(char * const *devices, unsigned nr_devices,
1795                             struct bch_opts opts)
1796 {
1797         struct bch_sb_handle *sb = NULL;
1798         struct bch_fs *c = NULL;
1799         unsigned i, best_sb = 0;
1800         const char *err;
1801         int ret = -ENOMEM;
1802
1803         pr_verbose_init(opts, "");
1804
1805         if (!nr_devices) {
1806                 c = ERR_PTR(-EINVAL);
1807                 goto out2;
1808         }
1809
1810         if (!try_module_get(THIS_MODULE)) {
1811                 c = ERR_PTR(-ENODEV);
1812                 goto out2;
1813         }
1814
1815         sb = kcalloc(nr_devices, sizeof(*sb), GFP_KERNEL);
1816         if (!sb)
1817                 goto err;
1818
1819         for (i = 0; i < nr_devices; i++) {
1820                 ret = bch2_read_super(devices[i], &opts, &sb[i]);
1821                 if (ret)
1822                         goto err;
1823
1824                 err = bch2_sb_validate(&sb[i]);
1825                 if (err)
1826                         goto err_print;
1827         }
1828
1829         for (i = 1; i < nr_devices; i++)
1830                 if (le64_to_cpu(sb[i].sb->seq) >
1831                     le64_to_cpu(sb[best_sb].sb->seq))
1832                         best_sb = i;
1833
1834         for (i = 0; i < nr_devices; i++) {
1835                 err = bch2_dev_in_fs(sb[best_sb].sb, sb[i].sb);
1836                 if (err)
1837                         goto err_print;
1838         }
1839
1840         ret = -ENOMEM;
1841         c = bch2_fs_alloc(sb[best_sb].sb, opts);
1842         if (!c)
1843                 goto err;
1844
1845         err = "bch2_dev_online() error";
1846         mutex_lock(&c->state_lock);
1847         for (i = 0; i < nr_devices; i++)
1848                 if (__bch2_dev_online(c, &sb[i])) {
1849                         mutex_unlock(&c->state_lock);
1850                         goto err_print;
1851                 }
1852         mutex_unlock(&c->state_lock);
1853
1854         err = "insufficient devices";
1855         if (!bch2_fs_may_start(c))
1856                 goto err_print;
1857
1858         if (!c->opts.nostart) {
1859                 err = __bch2_fs_start(c);
1860                 if (err)
1861                         goto err_print;
1862         }
1863
1864         err = bch2_fs_online(c);
1865         if (err)
1866                 goto err_print;
1867
1868 out:
1869         kfree(sb);
1870         module_put(THIS_MODULE);
1871 out2:
1872         pr_verbose_init(opts, "ret %i", PTR_ERR_OR_ZERO(c));
1873         return c;
1874 err_print:
1875         pr_err("bch_fs_open err opening %s: %s",
1876                devices[0], err);
1877         ret = -EINVAL;
1878 err:
1879         if (c)
1880                 bch2_fs_stop(c);
1881         for (i = 0; i < nr_devices; i++)
1882                 bch2_free_super(&sb[i]);
1883         c = ERR_PTR(ret);
1884         goto out;
1885 }
1886
1887 static const char *__bch2_fs_open_incremental(struct bch_sb_handle *sb,
1888                                               struct bch_opts opts)
1889 {
1890         const char *err;
1891         struct bch_fs *c;
1892         bool allocated_fs = false;
1893
1894         err = bch2_sb_validate(sb);
1895         if (err)
1896                 return err;
1897
1898         mutex_lock(&bch_fs_list_lock);
1899         c = __bch2_uuid_to_fs(sb->sb->uuid);
1900         if (c) {
1901                 closure_get(&c->cl);
1902
1903                 err = bch2_dev_in_fs(c->disk_sb, sb->sb);
1904                 if (err)
1905                         goto err;
1906         } else {
1907                 c = bch2_fs_alloc(sb->sb, opts);
1908                 err = "cannot allocate memory";
1909                 if (!c)
1910                         goto err;
1911
1912                 allocated_fs = true;
1913         }
1914
1915         err = "bch2_dev_online() error";
1916
1917         mutex_lock(&c->sb_lock);
1918         if (__bch2_dev_online(c, sb)) {
1919                 mutex_unlock(&c->sb_lock);
1920                 goto err;
1921         }
1922         mutex_unlock(&c->sb_lock);
1923
1924         if (!c->opts.nostart && bch2_fs_may_start(c)) {
1925                 err = __bch2_fs_start(c);
1926                 if (err)
1927                         goto err;
1928         }
1929
1930         err = __bch2_fs_online(c);
1931         if (err)
1932                 goto err;
1933
1934         closure_put(&c->cl);
1935         mutex_unlock(&bch_fs_list_lock);
1936
1937         return NULL;
1938 err:
1939         mutex_unlock(&bch_fs_list_lock);
1940
1941         if (allocated_fs)
1942                 bch2_fs_stop(c);
1943         else if (c)
1944                 closure_put(&c->cl);
1945
1946         return err;
1947 }
1948
1949 const char *bch2_fs_open_incremental(const char *path)
1950 {
1951         struct bch_sb_handle sb;
1952         struct bch_opts opts = bch2_opts_empty();
1953         const char *err;
1954
1955         if (bch2_read_super(path, &opts, &sb))
1956                 return "error reading superblock";
1957
1958         err = __bch2_fs_open_incremental(&sb, opts);
1959         bch2_free_super(&sb);
1960
1961         return err;
1962 }
1963
1964 /* Global interfaces/init */
1965
1966 static void bcachefs_exit(void)
1967 {
1968         bch2_debug_exit();
1969         bch2_vfs_exit();
1970         bch2_chardev_exit();
1971         if (bcachefs_kset)
1972                 kset_unregister(bcachefs_kset);
1973 }
1974
1975 static int __init bcachefs_init(void)
1976 {
1977         bch2_bkey_pack_test();
1978         bch2_inode_pack_test();
1979
1980         if (!(bcachefs_kset = kset_create_and_add("bcachefs", NULL, fs_kobj)) ||
1981             bch2_chardev_init() ||
1982             bch2_vfs_init() ||
1983             bch2_debug_init())
1984                 goto err;
1985
1986         return 0;
1987 err:
1988         bcachefs_exit();
1989         return -ENOMEM;
1990 }
1991
1992 #define BCH_DEBUG_PARAM(name, description)                      \
1993         bool bch2_##name;                                       \
1994         module_param_named(name, bch2_##name, bool, 0644);      \
1995         MODULE_PARM_DESC(name, description);
1996 BCH_DEBUG_PARAMS()
1997 #undef BCH_DEBUG_PARAM
1998
1999 module_exit(bcachefs_exit);
2000 module_init(bcachefs_init);