]> git.sesse.net Git - bcachefs-tools-debian/blob - libbcachefs/super.c
f836c199e06b38292ecd0dd044782cde23d8f684
[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         c = kvpmalloc(sizeof(struct bch_fs), GFP_KERNEL|__GFP_ZERO);
511         if (!c)
512                 return NULL;
513
514         __module_get(THIS_MODULE);
515
516         c->minor                = -1;
517
518         mutex_init(&c->state_lock);
519         mutex_init(&c->sb_lock);
520         mutex_init(&c->replicas_gc_lock);
521         mutex_init(&c->btree_root_lock);
522         INIT_WORK(&c->read_only_work, bch2_fs_read_only_work);
523
524         init_rwsem(&c->gc_lock);
525
526 #define BCH_TIME_STAT(name, frequency_units, duration_units)            \
527         spin_lock_init(&c->name##_time.lock);
528         BCH_TIME_STATS()
529 #undef BCH_TIME_STAT
530
531         bch2_fs_allocator_init(c);
532         bch2_fs_tiering_init(c);
533         bch2_fs_quota_init(c);
534
535         INIT_LIST_HEAD(&c->list);
536
537         INIT_LIST_HEAD(&c->btree_interior_update_list);
538         mutex_init(&c->btree_reserve_cache_lock);
539         mutex_init(&c->btree_interior_update_lock);
540
541         mutex_init(&c->bio_bounce_pages_lock);
542         mutex_init(&c->zlib_workspace_lock);
543
544         bio_list_init(&c->btree_write_error_list);
545         spin_lock_init(&c->btree_write_error_lock);
546         INIT_WORK(&c->btree_write_error_work, bch2_btree_write_error_work);
547
548         INIT_LIST_HEAD(&c->fsck_errors);
549         mutex_init(&c->fsck_error_lock);
550
551         seqcount_init(&c->gc_pos_lock);
552
553         init_waitqueue_head(&c->writeback_wait);
554         c->writeback_pages_max = (256 << 10) / PAGE_SIZE;
555
556         c->copy_gc_enabled = 1;
557         c->tiering_enabled = 1;
558         c->tiering_percent = 10;
559
560         c->journal.write_time   = &c->journal_write_time;
561         c->journal.delay_time   = &c->journal_delay_time;
562         c->journal.blocked_time = &c->journal_blocked_time;
563         c->journal.flush_seq_time = &c->journal_flush_seq_time;
564
565         bch2_fs_btree_cache_init_early(&c->btree_cache);
566
567         mutex_lock(&c->sb_lock);
568
569         if (bch2_sb_to_fs(c, sb)) {
570                 mutex_unlock(&c->sb_lock);
571                 goto err;
572         }
573
574         mutex_unlock(&c->sb_lock);
575
576         scnprintf(c->name, sizeof(c->name), "%pU", &c->sb.user_uuid);
577
578         c->opts = bch2_opts_default;
579         bch2_opts_apply(&c->opts, bch2_opts_from_sb(sb));
580         bch2_opts_apply(&c->opts, opts);
581
582         c->block_bits           = ilog2(c->opts.block_size);
583         c->btree_foreground_merge_threshold = BTREE_FOREGROUND_MERGE_THRESHOLD(c);
584
585         c->opts.nochanges       |= c->opts.noreplay;
586         c->opts.read_only       |= c->opts.nochanges;
587
588         if (bch2_fs_init_fault("fs_alloc"))
589                 goto err;
590
591         iter_size = (btree_blocks(c) + 1) * 2 *
592                 sizeof(struct btree_node_iter_set);
593
594         if (!(c->wq = alloc_workqueue("bcachefs",
595                                 WQ_FREEZABLE|WQ_MEM_RECLAIM|WQ_HIGHPRI, 1)) ||
596             !(c->copygc_wq = alloc_workqueue("bcache_copygc",
597                                 WQ_FREEZABLE|WQ_MEM_RECLAIM|WQ_HIGHPRI, 1)) ||
598             percpu_ref_init(&c->writes, bch2_writes_disabled, 0, GFP_KERNEL) ||
599             mempool_init_kmalloc_pool(&c->btree_reserve_pool, 1,
600                                       sizeof(struct btree_reserve)) ||
601             mempool_init_kmalloc_pool(&c->btree_interior_update_pool, 1,
602                                       sizeof(struct btree_update)) ||
603             mempool_init_kmalloc_pool(&c->fill_iter, 1, iter_size) ||
604             bioset_init(&c->btree_bio, 1,
605                         max(offsetof(struct btree_read_bio, bio),
606                             offsetof(struct btree_write_bio, wbio.bio)),
607                         BIOSET_NEED_BVECS) ||
608             bioset_init(&c->bio_read, 1, offsetof(struct bch_read_bio, bio),
609                         BIOSET_NEED_BVECS) ||
610             bioset_init(&c->bio_read_split, 1, offsetof(struct bch_read_bio, bio),
611                         BIOSET_NEED_BVECS) ||
612             bioset_init(&c->bio_write, 1, offsetof(struct bch_write_bio, bio),
613                         BIOSET_NEED_BVECS) ||
614             mempool_init_page_pool(&c->bio_bounce_pages,
615                                    max_t(unsigned,
616                                          c->opts.btree_node_size,
617                                          c->sb.encoded_extent_max) /
618                                    PAGE_SECTORS, 0) ||
619             !(c->usage_percpu = alloc_percpu(struct bch_fs_usage)) ||
620             lg_lock_init(&c->usage_lock) ||
621             mempool_init_vp_pool(&c->btree_bounce_pool, 1, btree_bytes(c)) ||
622             bch2_io_clock_init(&c->io_clock[READ]) ||
623             bch2_io_clock_init(&c->io_clock[WRITE]) ||
624             bch2_fs_journal_init(&c->journal) ||
625             bch2_fs_btree_cache_init(c) ||
626             bch2_fs_encryption_init(c) ||
627             bch2_fs_compress_init(c) ||
628             bch2_check_set_has_compressed_data(c, c->opts.compression) ||
629             bch2_fs_fsio_init(c))
630                 goto err;
631
632         mi = bch2_sb_get_members(c->disk_sb);
633         for (i = 0; i < c->sb.nr_devices; i++)
634                 if (bch2_dev_exists(c->disk_sb, mi, i) &&
635                     bch2_dev_alloc(c, i))
636                         goto err;
637
638         /*
639          * Now that all allocations have succeeded, init various refcounty
640          * things that let us shutdown:
641          */
642         closure_init(&c->cl, NULL);
643
644         c->kobj.kset = bcachefs_kset;
645         kobject_init(&c->kobj, &bch2_fs_ktype);
646         kobject_init(&c->internal, &bch2_fs_internal_ktype);
647         kobject_init(&c->opts_dir, &bch2_fs_opts_dir_ktype);
648         kobject_init(&c->time_stats, &bch2_fs_time_stats_ktype);
649         return c;
650 err:
651         bch2_fs_free(c);
652         return NULL;
653 }
654
655 static const char *__bch2_fs_online(struct bch_fs *c)
656 {
657         struct bch_dev *ca;
658         const char *err = NULL;
659         unsigned i;
660         int ret;
661
662         lockdep_assert_held(&bch_fs_list_lock);
663
664         if (!list_empty(&c->list))
665                 return NULL;
666
667         if (__bch2_uuid_to_fs(c->sb.uuid))
668                 return "filesystem UUID already open";
669
670         ret = bch2_fs_chardev_init(c);
671         if (ret)
672                 return "error creating character device";
673
674         bch2_fs_debug_init(c);
675
676         if (kobject_add(&c->kobj, NULL, "%pU", c->sb.user_uuid.b) ||
677             kobject_add(&c->internal, &c->kobj, "internal") ||
678             kobject_add(&c->opts_dir, &c->kobj, "options") ||
679             kobject_add(&c->time_stats, &c->kobj, "time_stats") ||
680             bch2_opts_create_sysfs_files(&c->opts_dir))
681                 return "error creating sysfs objects";
682
683         mutex_lock(&c->state_lock);
684
685         err = "error creating sysfs objects";
686         __for_each_member_device(ca, c, i, NULL)
687                 if (bch2_dev_sysfs_online(c, ca))
688                         goto err;
689
690         list_add(&c->list, &bch_fs_list);
691         err = NULL;
692 err:
693         mutex_unlock(&c->state_lock);
694         return err;
695 }
696
697 static const char *bch2_fs_online(struct bch_fs *c)
698 {
699         const char *err;
700
701         mutex_lock(&bch_fs_list_lock);
702         err = __bch2_fs_online(c);
703         mutex_unlock(&bch_fs_list_lock);
704
705         return err;
706 }
707
708 static const char *__bch2_fs_start(struct bch_fs *c)
709 {
710         const char *err = "cannot allocate memory";
711         struct bch_sb_field_members *mi;
712         struct bch_dev *ca;
713         LIST_HEAD(journal);
714         struct jset *j;
715         time64_t now;
716         unsigned i;
717         int ret = -EINVAL;
718
719         mutex_lock(&c->state_lock);
720
721         BUG_ON(c->state != BCH_FS_STARTING);
722
723         mutex_lock(&c->sb_lock);
724         for_each_online_member(ca, c, i)
725                 bch2_sb_from_fs(c, ca);
726         mutex_unlock(&c->sb_lock);
727
728         for_each_rw_member(ca, c, i)
729                 bch2_dev_allocator_add(c, ca);
730         bch2_recalc_capacity(c);
731
732         if (BCH_SB_INITIALIZED(c->disk_sb)) {
733                 ret = bch2_journal_read(c, &journal);
734                 if (ret)
735                         goto err;
736
737                 j = &list_entry(journal.prev, struct journal_replay, list)->j;
738
739                 c->prio_clock[READ].hand = le16_to_cpu(j->read_clock);
740                 c->prio_clock[WRITE].hand = le16_to_cpu(j->write_clock);
741
742                 for (i = 0; i < BTREE_ID_NR; i++) {
743                         unsigned level;
744                         struct bkey_i *k;
745
746                         k = bch2_journal_find_btree_root(c, j, i, &level);
747                         if (!k)
748                                 continue;
749
750                         err = "invalid btree root pointer";
751                         if (IS_ERR(k))
752                                 goto err;
753
754                         err = "error reading btree root";
755                         if (bch2_btree_root_read(c, i, k, level)) {
756                                 if (i != BTREE_ID_ALLOC)
757                                         goto err;
758
759                                 mustfix_fsck_err(c, "error reading btree root");
760                         }
761                 }
762
763                 for (i = 0; i < BTREE_ID_NR; i++)
764                         if (!c->btree_roots[i].b)
765                                 bch2_btree_root_alloc(c, i);
766
767                 err = "error reading allocation information";
768                 ret = bch2_alloc_read(c, &journal);
769                 if (ret)
770                         goto err;
771
772                 set_bit(BCH_FS_ALLOC_READ_DONE, &c->flags);
773
774                 bch_verbose(c, "starting mark and sweep:");
775                 err = "error in recovery";
776                 ret = bch2_initial_gc(c, &journal);
777                 if (ret)
778                         goto err;
779                 bch_verbose(c, "mark and sweep done");
780
781                 if (c->opts.noreplay)
782                         goto recovery_done;
783
784                 /*
785                  * bch2_journal_start() can't happen sooner, or btree_gc_finish()
786                  * will give spurious errors about oldest_gen > bucket_gen -
787                  * this is a hack but oh well.
788                  */
789                 bch2_journal_start(c);
790
791                 err = "error starting allocator";
792                 if (bch2_fs_allocator_start(c))
793                         goto err;
794
795                 bch_verbose(c, "starting journal replay:");
796                 err = "journal replay failed";
797                 ret = bch2_journal_replay(c, &journal);
798                 if (ret)
799                         goto err;
800                 bch_verbose(c, "journal replay done");
801
802                 if (c->opts.norecovery)
803                         goto recovery_done;
804
805                 bch_verbose(c, "starting fsck:");
806                 err = "error in fsck";
807                 ret = bch2_fsck(c, !c->opts.nofsck);
808                 if (ret)
809                         goto err;
810                 bch_verbose(c, "fsck done");
811
812                 if (c->opts.usrquota || c->opts.grpquota) {
813                         bch_verbose(c, "reading quotas:");
814                         ret = bch2_fs_quota_read(c);
815                         if (ret)
816                                 goto err;
817                         bch_verbose(c, "quotas done");
818                 }
819         } else {
820                 struct bch_inode_unpacked inode;
821                 struct bkey_inode_buf packed_inode;
822
823                 bch_notice(c, "initializing new filesystem");
824
825                 set_bit(BCH_FS_ALLOC_READ_DONE, &c->flags);
826                 set_bit(BCH_FS_BRAND_NEW_FS, &c->flags);
827
828                 ret = bch2_initial_gc(c, &journal);
829                 if (ret)
830                         goto err;
831
832                 err = "unable to allocate journal buckets";
833                 for_each_rw_member(ca, c, i)
834                         if (bch2_dev_journal_alloc(c, ca)) {
835                                 percpu_ref_put(&ca->io_ref);
836                                 goto err;
837                         }
838
839                 clear_bit(BCH_FS_BRAND_NEW_FS, &c->flags);
840
841                 for (i = 0; i < BTREE_ID_NR; i++)
842                         bch2_btree_root_alloc(c, i);
843
844                 /*
845                  * journal_res_get() will crash if called before this has
846                  * set up the journal.pin FIFO and journal.cur pointer:
847                  */
848                 bch2_journal_start(c);
849                 bch2_journal_set_replay_done(&c->journal);
850
851                 err = "error starting allocator";
852                 if (bch2_fs_allocator_start(c))
853                         goto err;
854
855                 bch2_inode_init(c, &inode, 0, 0,
856                                S_IFDIR|S_IRWXU|S_IRUGO|S_IXUGO, 0, NULL);
857                 inode.bi_inum = BCACHEFS_ROOT_INO;
858
859                 bch2_inode_pack(&packed_inode, &inode);
860
861                 err = "error creating root directory";
862                 if (bch2_btree_insert(c, BTREE_ID_INODES,
863                                      &packed_inode.inode.k_i,
864                                      NULL, NULL, NULL, 0))
865                         goto err;
866
867                 if (c->opts.usrquota || c->opts.grpquota) {
868                         ret = bch2_fs_quota_read(c);
869                         if (ret)
870                                 goto err;
871                 }
872
873                 err = "error writing first journal entry";
874                 if (bch2_journal_meta(&c->journal))
875                         goto err;
876         }
877 recovery_done:
878         err = "dynamic fault";
879         if (bch2_fs_init_fault("fs_start"))
880                 goto err;
881
882         if (c->opts.read_only) {
883                 bch2_fs_read_only(c);
884         } else {
885                 err = bch2_fs_read_write(c);
886                 if (err)
887                         goto err;
888         }
889
890         mutex_lock(&c->sb_lock);
891         mi = bch2_sb_get_members(c->disk_sb);
892         now = ktime_get_seconds();
893
894         for_each_member_device(ca, c, i)
895                 mi->members[ca->dev_idx].last_mount = cpu_to_le64(now);
896
897         SET_BCH_SB_INITIALIZED(c->disk_sb, true);
898         SET_BCH_SB_CLEAN(c->disk_sb, false);
899
900         bch2_write_super(c);
901         mutex_unlock(&c->sb_lock);
902
903         err = NULL;
904 out:
905         mutex_unlock(&c->state_lock);
906         bch2_journal_entries_free(&journal);
907         return err;
908 err:
909 fsck_err:
910         switch (ret) {
911         case BCH_FSCK_ERRORS_NOT_FIXED:
912                 bch_err(c, "filesystem contains errors: please report this to the developers");
913                 pr_cont("mount with -o fix_errors to repair\n");
914                 err = "fsck error";
915                 break;
916         case BCH_FSCK_REPAIR_UNIMPLEMENTED:
917                 bch_err(c, "filesystem contains errors: please report this to the developers");
918                 pr_cont("repair unimplemented: inform the developers so that it can be added\n");
919                 err = "fsck error";
920                 break;
921         case BCH_FSCK_REPAIR_IMPOSSIBLE:
922                 bch_err(c, "filesystem contains errors, but repair impossible");
923                 err = "fsck error";
924                 break;
925         case BCH_FSCK_UNKNOWN_VERSION:
926                 err = "unknown metadata version";;
927                 break;
928         case -ENOMEM:
929                 err = "cannot allocate memory";
930                 break;
931         case -EIO:
932                 err = "IO error";
933                 break;
934         }
935
936         BUG_ON(!err);
937         set_bit(BCH_FS_ERROR, &c->flags);
938         goto out;
939 }
940
941 const char *bch2_fs_start(struct bch_fs *c)
942 {
943         return __bch2_fs_start(c) ?: bch2_fs_online(c);
944 }
945
946 static const char *bch2_dev_may_add(struct bch_sb *sb, struct bch_fs *c)
947 {
948         struct bch_sb_field_members *sb_mi;
949
950         sb_mi = bch2_sb_get_members(sb);
951         if (!sb_mi)
952                 return "Invalid superblock: member info area missing";
953
954         if (le16_to_cpu(sb->block_size) != c->opts.block_size)
955                 return "mismatched block size";
956
957         if (le16_to_cpu(sb_mi->members[sb->dev_idx].bucket_size) <
958             BCH_SB_BTREE_NODE_SIZE(c->disk_sb))
959                 return "new cache bucket size is too small";
960
961         return NULL;
962 }
963
964 static const char *bch2_dev_in_fs(struct bch_sb *fs, struct bch_sb *sb)
965 {
966         struct bch_sb *newest =
967                 le64_to_cpu(fs->seq) > le64_to_cpu(sb->seq) ? fs : sb;
968         struct bch_sb_field_members *mi = bch2_sb_get_members(newest);
969
970         if (uuid_le_cmp(fs->uuid, sb->uuid))
971                 return "device not a member of filesystem";
972
973         if (!bch2_dev_exists(newest, mi, sb->dev_idx))
974                 return "device has been removed";
975
976         if (fs->block_size != sb->block_size)
977                 return "mismatched block size";
978
979         return NULL;
980 }
981
982 /* Device startup/shutdown: */
983
984 static void bch2_dev_release(struct kobject *kobj)
985 {
986         struct bch_dev *ca = container_of(kobj, struct bch_dev, kobj);
987
988         kfree(ca);
989 }
990
991 static void bch2_dev_free(struct bch_dev *ca)
992 {
993         cancel_work_sync(&ca->io_error_work);
994
995         if (ca->kobj.state_in_sysfs &&
996             ca->disk_sb.bdev)
997                 sysfs_remove_link(&part_to_dev(ca->disk_sb.bdev->bd_part)->kobj,
998                                   "bcachefs");
999
1000         if (ca->kobj.state_in_sysfs)
1001                 kobject_del(&ca->kobj);
1002
1003         bch2_free_super(&ca->disk_sb);
1004         bch2_dev_journal_exit(ca);
1005
1006         free_percpu(ca->io_done);
1007         bioset_exit(&ca->replica_set);
1008         bch2_dev_buckets_free(ca);
1009
1010         percpu_ref_exit(&ca->io_ref);
1011         percpu_ref_exit(&ca->ref);
1012         kobject_put(&ca->kobj);
1013 }
1014
1015 static void __bch2_dev_offline(struct bch_fs *c, struct bch_dev *ca)
1016 {
1017
1018         lockdep_assert_held(&c->state_lock);
1019
1020         if (percpu_ref_is_zero(&ca->io_ref))
1021                 return;
1022
1023         __bch2_dev_read_only(c, ca);
1024
1025         reinit_completion(&ca->io_ref_completion);
1026         percpu_ref_kill(&ca->io_ref);
1027         wait_for_completion(&ca->io_ref_completion);
1028
1029         if (ca->kobj.state_in_sysfs) {
1030                 struct kobject *block =
1031                         &part_to_dev(ca->disk_sb.bdev->bd_part)->kobj;
1032
1033                 sysfs_remove_link(block, "bcachefs");
1034                 sysfs_remove_link(&ca->kobj, "block");
1035         }
1036
1037         bch2_free_super(&ca->disk_sb);
1038         bch2_dev_journal_exit(ca);
1039 }
1040
1041 static void bch2_dev_ref_complete(struct percpu_ref *ref)
1042 {
1043         struct bch_dev *ca = container_of(ref, struct bch_dev, ref);
1044
1045         complete(&ca->ref_completion);
1046 }
1047
1048 static void bch2_dev_io_ref_complete(struct percpu_ref *ref)
1049 {
1050         struct bch_dev *ca = container_of(ref, struct bch_dev, io_ref);
1051
1052         complete(&ca->io_ref_completion);
1053 }
1054
1055 static int bch2_dev_sysfs_online(struct bch_fs *c, struct bch_dev *ca)
1056 {
1057         int ret;
1058
1059         if (!c->kobj.state_in_sysfs)
1060                 return 0;
1061
1062         if (!ca->kobj.state_in_sysfs) {
1063                 ret = kobject_add(&ca->kobj, &c->kobj,
1064                                   "dev-%u", ca->dev_idx);
1065                 if (ret)
1066                         return ret;
1067         }
1068
1069         if (ca->disk_sb.bdev) {
1070                 struct kobject *block =
1071                         &part_to_dev(ca->disk_sb.bdev->bd_part)->kobj;
1072
1073                 ret = sysfs_create_link(block, &ca->kobj, "bcachefs");
1074                 if (ret)
1075                         return ret;
1076                 ret = sysfs_create_link(&ca->kobj, block, "block");
1077                 if (ret)
1078                         return ret;
1079         }
1080
1081         return 0;
1082 }
1083
1084 static int bch2_dev_alloc(struct bch_fs *c, unsigned dev_idx)
1085 {
1086         struct bch_member *member;
1087         struct bch_dev *ca;
1088
1089         if (bch2_fs_init_fault("dev_alloc"))
1090                 return -ENOMEM;
1091
1092         ca = kzalloc(sizeof(*ca), GFP_KERNEL);
1093         if (!ca)
1094                 return -ENOMEM;
1095
1096         kobject_init(&ca->kobj, &bch2_dev_ktype);
1097         init_completion(&ca->ref_completion);
1098         init_completion(&ca->io_ref_completion);
1099
1100         ca->dev_idx = dev_idx;
1101         __set_bit(ca->dev_idx, ca->self.d);
1102
1103         init_rwsem(&ca->bucket_lock);
1104
1105         writepoint_init(&ca->copygc_write_point, BCH_DATA_USER);
1106
1107         spin_lock_init(&ca->freelist_lock);
1108         bch2_dev_copygc_init(ca);
1109
1110         INIT_WORK(&ca->io_error_work, bch2_io_error_work);
1111
1112         if (bch2_fs_init_fault("dev_alloc"))
1113                 goto err;
1114
1115         member = bch2_sb_get_members(c->disk_sb)->members + dev_idx;
1116
1117         ca->mi = bch2_mi_to_cpu(member);
1118         ca->uuid = member->uuid;
1119         scnprintf(ca->name, sizeof(ca->name), "dev-%u", dev_idx);
1120
1121         if (percpu_ref_init(&ca->ref, bch2_dev_ref_complete,
1122                             0, GFP_KERNEL) ||
1123             percpu_ref_init(&ca->io_ref, bch2_dev_io_ref_complete,
1124                             PERCPU_REF_INIT_DEAD, GFP_KERNEL) ||
1125             bch2_dev_buckets_alloc(c, ca) ||
1126             bioset_init(&ca->replica_set, 4,
1127                         offsetof(struct bch_write_bio, bio), 0) ||
1128             !(ca->io_done       = alloc_percpu(*ca->io_done)))
1129                 goto err;
1130
1131         ca->fs = c;
1132         rcu_assign_pointer(c->devs[ca->dev_idx], ca);
1133
1134         if (bch2_dev_sysfs_online(c, ca))
1135                 pr_warn("error creating sysfs objects");
1136
1137         return 0;
1138 err:
1139         bch2_dev_free(ca);
1140         return -ENOMEM;
1141 }
1142
1143 static int __bch2_dev_online(struct bch_fs *c, struct bch_sb_handle *sb)
1144 {
1145         struct bch_dev *ca;
1146         int ret;
1147
1148         lockdep_assert_held(&c->state_lock);
1149
1150         if (le64_to_cpu(sb->sb->seq) >
1151             le64_to_cpu(c->disk_sb->seq))
1152                 bch2_sb_to_fs(c, sb->sb);
1153
1154         BUG_ON(sb->sb->dev_idx >= c->sb.nr_devices ||
1155                !c->devs[sb->sb->dev_idx]);
1156
1157         ca = bch_dev_locked(c, sb->sb->dev_idx);
1158
1159         if (bch2_dev_is_online(ca)) {
1160                 bch_err(ca, "already have device online in slot %u",
1161                         sb->sb->dev_idx);
1162                 return -EINVAL;
1163         }
1164
1165         if (get_capacity(sb->bdev->bd_disk) <
1166             ca->mi.bucket_size * ca->mi.nbuckets) {
1167                 bch_err(ca, "cannot online: device too small");
1168                 return -EINVAL;
1169         }
1170
1171         BUG_ON(!percpu_ref_is_zero(&ca->io_ref));
1172
1173         if (get_capacity(sb->bdev->bd_disk) <
1174             ca->mi.bucket_size * ca->mi.nbuckets) {
1175                 bch_err(c, "device too small");
1176                 return -EINVAL;
1177         }
1178
1179         ret = bch2_dev_journal_init(ca, sb->sb);
1180         if (ret)
1181                 return ret;
1182
1183         /*
1184          * Increase journal write timeout if flushes to this device are
1185          * expensive:
1186          */
1187         if (!blk_queue_nonrot(bdev_get_queue(sb->bdev)) &&
1188             journal_flushes_device(ca))
1189                 c->journal.write_delay_ms =
1190                         max(c->journal.write_delay_ms, 1000U);
1191
1192         /* Commit: */
1193         ca->disk_sb = *sb;
1194         if (sb->mode & FMODE_EXCL)
1195                 ca->disk_sb.bdev->bd_holder = ca;
1196         memset(sb, 0, sizeof(*sb));
1197
1198         if (c->sb.nr_devices == 1)
1199                 bdevname(ca->disk_sb.bdev, c->name);
1200         bdevname(ca->disk_sb.bdev, ca->name);
1201
1202         mutex_lock(&c->sb_lock);
1203         bch2_mark_dev_superblock(c, ca, BCH_BUCKET_MARK_MAY_MAKE_UNAVAILABLE);
1204         mutex_unlock(&c->sb_lock);
1205
1206         if (ca->mi.state == BCH_MEMBER_STATE_RW)
1207                 bch2_dev_allocator_add(c, ca);
1208
1209         percpu_ref_reinit(&ca->io_ref);
1210         return 0;
1211 }
1212
1213 /* Device management: */
1214
1215 /*
1216  * Note: this function is also used by the error paths - when a particular
1217  * device sees an error, we call it to determine whether we can just set the
1218  * device RO, or - if this function returns false - we'll set the whole
1219  * filesystem RO:
1220  *
1221  * XXX: maybe we should be more explicit about whether we're changing state
1222  * because we got an error or what have you?
1223  */
1224 bool bch2_dev_state_allowed(struct bch_fs *c, struct bch_dev *ca,
1225                             enum bch_member_state new_state, int flags)
1226 {
1227         struct bch_devs_mask new_online_devs;
1228         struct replicas_status s;
1229         struct bch_dev *ca2;
1230         int i, nr_rw = 0, required;
1231
1232         lockdep_assert_held(&c->state_lock);
1233
1234         switch (new_state) {
1235         case BCH_MEMBER_STATE_RW:
1236                 return true;
1237         case BCH_MEMBER_STATE_RO:
1238                 if (ca->mi.state != BCH_MEMBER_STATE_RW)
1239                         return true;
1240
1241                 /* do we have enough devices to write to?  */
1242                 for_each_member_device(ca2, c, i)
1243                         nr_rw += ca2->mi.state == BCH_MEMBER_STATE_RW;
1244
1245                 required = max(!(flags & BCH_FORCE_IF_METADATA_DEGRADED)
1246                                ? c->opts.metadata_replicas
1247                                : c->opts.metadata_replicas_required,
1248                                !(flags & BCH_FORCE_IF_DATA_DEGRADED)
1249                                ? c->opts.data_replicas
1250                                : c->opts.data_replicas_required);
1251
1252                 return nr_rw - 1 <= required;
1253         case BCH_MEMBER_STATE_FAILED:
1254         case BCH_MEMBER_STATE_SPARE:
1255                 if (ca->mi.state != BCH_MEMBER_STATE_RW &&
1256                     ca->mi.state != BCH_MEMBER_STATE_RO)
1257                         return true;
1258
1259                 /* do we have enough devices to read from?  */
1260                 new_online_devs = bch2_online_devs(c);
1261                 __clear_bit(ca->dev_idx, new_online_devs.d);
1262
1263                 s = __bch2_replicas_status(c, new_online_devs);
1264
1265                 return bch2_have_enough_devs(c, s, flags);
1266         default:
1267                 BUG();
1268         }
1269 }
1270
1271 static bool bch2_fs_may_start(struct bch_fs *c)
1272 {
1273         struct replicas_status s;
1274         struct bch_sb_field_members *mi;
1275         struct bch_dev *ca;
1276         unsigned i, flags = c->opts.degraded
1277                 ? BCH_FORCE_IF_DEGRADED
1278                 : 0;
1279
1280         if (!c->opts.degraded) {
1281                 mutex_lock(&c->sb_lock);
1282                 mi = bch2_sb_get_members(c->disk_sb);
1283
1284                 for (i = 0; i < c->disk_sb->nr_devices; i++) {
1285                         if (!bch2_dev_exists(c->disk_sb, mi, i))
1286                                 continue;
1287
1288                         ca = bch_dev_locked(c, i);
1289
1290                         if (!bch2_dev_is_online(ca) &&
1291                             (ca->mi.state == BCH_MEMBER_STATE_RW ||
1292                              ca->mi.state == BCH_MEMBER_STATE_RO)) {
1293                                 mutex_unlock(&c->sb_lock);
1294                                 return false;
1295                         }
1296                 }
1297                 mutex_unlock(&c->sb_lock);
1298         }
1299
1300         s = bch2_replicas_status(c);
1301
1302         return bch2_have_enough_devs(c, s, flags);
1303 }
1304
1305 static void __bch2_dev_read_only(struct bch_fs *c, struct bch_dev *ca)
1306 {
1307         bch2_copygc_stop(ca);
1308
1309         /*
1310          * The allocator thread itself allocates btree nodes, so stop it first:
1311          */
1312         bch2_dev_allocator_stop(ca);
1313         bch2_dev_allocator_remove(c, ca);
1314         bch2_dev_journal_stop(&c->journal, ca);
1315 }
1316
1317 static const char *__bch2_dev_read_write(struct bch_fs *c, struct bch_dev *ca)
1318 {
1319         lockdep_assert_held(&c->state_lock);
1320
1321         BUG_ON(ca->mi.state != BCH_MEMBER_STATE_RW);
1322
1323         bch2_dev_allocator_add(c, ca);
1324         bch2_recalc_capacity(c);
1325
1326         if (bch2_dev_allocator_start(ca))
1327                 return "error starting allocator thread";
1328
1329         if (bch2_copygc_start(c, ca))
1330                 return "error starting copygc thread";
1331
1332         if (bch2_tiering_start(c))
1333                 return "error starting tiering thread";
1334
1335         return NULL;
1336 }
1337
1338 int __bch2_dev_set_state(struct bch_fs *c, struct bch_dev *ca,
1339                          enum bch_member_state new_state, int flags)
1340 {
1341         struct bch_sb_field_members *mi;
1342
1343         if (ca->mi.state == new_state)
1344                 return 0;
1345
1346         if (!bch2_dev_state_allowed(c, ca, new_state, flags))
1347                 return -EINVAL;
1348
1349         if (new_state == BCH_MEMBER_STATE_RW) {
1350                 if (__bch2_dev_read_write(c, ca))
1351                         return -ENOMEM;
1352         } else {
1353                 __bch2_dev_read_only(c, ca);
1354         }
1355
1356         bch_notice(ca, "%s", bch2_dev_state[new_state]);
1357
1358         mutex_lock(&c->sb_lock);
1359         mi = bch2_sb_get_members(c->disk_sb);
1360         SET_BCH_MEMBER_STATE(&mi->members[ca->dev_idx], new_state);
1361         bch2_write_super(c);
1362         mutex_unlock(&c->sb_lock);
1363
1364         return 0;
1365 }
1366
1367 int bch2_dev_set_state(struct bch_fs *c, struct bch_dev *ca,
1368                        enum bch_member_state new_state, int flags)
1369 {
1370         int ret;
1371
1372         mutex_lock(&c->state_lock);
1373         ret = __bch2_dev_set_state(c, ca, new_state, flags);
1374         mutex_unlock(&c->state_lock);
1375
1376         return ret;
1377 }
1378
1379 /* Device add/removal: */
1380
1381 int bch2_dev_remove(struct bch_fs *c, struct bch_dev *ca, int flags)
1382 {
1383         struct bch_sb_field_members *mi;
1384         unsigned dev_idx = ca->dev_idx, data;
1385         int ret = -EINVAL;
1386
1387         mutex_lock(&c->state_lock);
1388
1389         percpu_ref_put(&ca->ref); /* XXX */
1390
1391         if (!bch2_dev_state_allowed(c, ca, BCH_MEMBER_STATE_FAILED, flags)) {
1392                 bch_err(ca, "Cannot remove without losing data");
1393                 goto err;
1394         }
1395
1396         __bch2_dev_read_only(c, ca);
1397
1398         /*
1399          * XXX: verify that dev_idx is really not in use anymore, anywhere
1400          *
1401          * flag_data_bad() does not check btree pointers
1402          */
1403         ret = bch2_dev_data_drop(c, ca->dev_idx, flags);
1404         if (ret) {
1405                 bch_err(ca, "Remove failed: error %i dropping data", ret);
1406                 goto err;
1407         }
1408
1409         ret = bch2_journal_flush_device(&c->journal, ca->dev_idx);
1410         if (ret) {
1411                 bch_err(ca, "Remove failed: error %i flushing journal", ret);
1412                 goto err;
1413         }
1414
1415         data = bch2_dev_has_data(c, ca);
1416         if (data) {
1417                 char data_has_str[100];
1418                 bch2_scnprint_flag_list(data_has_str,
1419                                         sizeof(data_has_str),
1420                                         bch2_data_types,
1421                                         data);
1422                 bch_err(ca, "Remove failed, still has data (%s)", data_has_str);
1423                 ret = -EBUSY;
1424                 goto err;
1425         }
1426
1427         ret = bch2_btree_delete_range(c, BTREE_ID_ALLOC,
1428                                       POS(ca->dev_idx, 0),
1429                                       POS(ca->dev_idx + 1, 0),
1430                                       ZERO_VERSION,
1431                                       NULL, NULL, NULL);
1432         if (ret) {
1433                 bch_err(ca, "Remove failed, error deleting alloc info");
1434                 goto err;
1435         }
1436
1437         /*
1438          * must flush all existing journal entries, they might have
1439          * (overwritten) keys that point to the device we're removing:
1440          */
1441         ret = bch2_journal_flush_all_pins(&c->journal);
1442         if (ret) {
1443                 bch_err(ca, "Remove failed, journal error");
1444                 goto err;
1445         }
1446
1447         __bch2_dev_offline(c, ca);
1448
1449         mutex_lock(&c->sb_lock);
1450         rcu_assign_pointer(c->devs[ca->dev_idx], NULL);
1451         mutex_unlock(&c->sb_lock);
1452
1453         percpu_ref_kill(&ca->ref);
1454         wait_for_completion(&ca->ref_completion);
1455
1456         bch2_dev_free(ca);
1457
1458         /*
1459          * Free this device's slot in the bch_member array - all pointers to
1460          * this device must be gone:
1461          */
1462         mutex_lock(&c->sb_lock);
1463         mi = bch2_sb_get_members(c->disk_sb);
1464         memset(&mi->members[dev_idx].uuid, 0, sizeof(mi->members[dev_idx].uuid));
1465
1466         bch2_write_super(c);
1467
1468         mutex_unlock(&c->sb_lock);
1469         mutex_unlock(&c->state_lock);
1470         return 0;
1471 err:
1472         if (ca->mi.state == BCH_MEMBER_STATE_RW)
1473                 __bch2_dev_read_write(c, ca);
1474         mutex_unlock(&c->state_lock);
1475         return ret;
1476 }
1477
1478 /* Add new device to running filesystem: */
1479 int bch2_dev_add(struct bch_fs *c, const char *path)
1480 {
1481         struct bch_opts opts = bch2_opts_empty();
1482         struct bch_sb_handle sb;
1483         const char *err;
1484         struct bch_dev *ca = NULL;
1485         struct bch_sb_field_members *mi, *dev_mi;
1486         struct bch_member saved_mi;
1487         unsigned dev_idx, nr_devices, u64s;
1488         int ret;
1489
1490         ret = bch2_read_super(path, &opts, &sb);
1491         if (ret)
1492                 return ret;
1493
1494         err = bch2_sb_validate(&sb);
1495         if (err)
1496                 return -EINVAL;
1497
1498         err = bch2_dev_may_add(sb.sb, c);
1499         if (err)
1500                 return -EINVAL;
1501
1502         mutex_lock(&c->state_lock);
1503         mutex_lock(&c->sb_lock);
1504
1505         /* Grab member info for new disk: */
1506         dev_mi = bch2_sb_get_members(sb.sb);
1507         saved_mi = dev_mi->members[sb.sb->dev_idx];
1508         saved_mi.last_mount = cpu_to_le64(ktime_get_seconds());
1509
1510         if (dynamic_fault("bcachefs:add:no_slot"))
1511                 goto no_slot;
1512
1513         mi = bch2_sb_get_members(c->disk_sb);
1514         for (dev_idx = 0; dev_idx < BCH_SB_MEMBERS_MAX; dev_idx++)
1515                 if (!bch2_dev_exists(c->disk_sb, mi, dev_idx))
1516                         goto have_slot;
1517 no_slot:
1518         err = "no slots available in superblock";
1519         ret = -ENOSPC;
1520         goto err_unlock;
1521
1522 have_slot:
1523         nr_devices = max_t(unsigned, dev_idx + 1, c->sb.nr_devices);
1524         u64s = (sizeof(struct bch_sb_field_members) +
1525                 sizeof(struct bch_member) * nr_devices) / sizeof(u64);
1526         err = "no space in superblock for member info";
1527
1528         dev_mi = bch2_sb_resize_members(&sb, u64s);
1529         if (!dev_mi)
1530                 goto err_unlock;
1531
1532         mi = bch2_fs_sb_resize_members(c, u64s);
1533         if (!mi)
1534                 goto err_unlock;
1535
1536         memcpy(dev_mi, mi, u64s * sizeof(u64));
1537         dev_mi->members[dev_idx] = saved_mi;
1538
1539         sb.sb->uuid             = c->disk_sb->uuid;
1540         sb.sb->dev_idx          = dev_idx;
1541         sb.sb->nr_devices       = nr_devices;
1542
1543         /* commit new member info */
1544         memcpy(mi, dev_mi, u64s * sizeof(u64));
1545         c->disk_sb->nr_devices  = nr_devices;
1546         c->sb.nr_devices        = nr_devices;
1547
1548         bch2_write_super(c);
1549         mutex_unlock(&c->sb_lock);
1550
1551         if (bch2_dev_alloc(c, dev_idx)) {
1552                 err = "cannot allocate memory";
1553                 ret = -ENOMEM;
1554                 goto err;
1555         }
1556
1557         if (__bch2_dev_online(c, &sb)) {
1558                 err = "bch2_dev_online() error";
1559                 ret = -ENOMEM;
1560                 goto err;
1561         }
1562
1563         ca = bch_dev_locked(c, dev_idx);
1564         if (ca->mi.state == BCH_MEMBER_STATE_RW) {
1565                 err = __bch2_dev_read_write(c, ca);
1566                 if (err)
1567                         goto err;
1568
1569                 err = "journal alloc failed";
1570                 if (bch2_dev_journal_alloc(c, ca))
1571                         goto err;
1572         }
1573
1574         mutex_unlock(&c->state_lock);
1575         return 0;
1576 err_unlock:
1577         mutex_unlock(&c->sb_lock);
1578 err:
1579         mutex_unlock(&c->state_lock);
1580         bch2_free_super(&sb);
1581
1582         bch_err(c, "Unable to add device: %s", err);
1583         return ret ?: -EINVAL;
1584 }
1585
1586 /* Hot add existing device to running filesystem: */
1587 int bch2_dev_online(struct bch_fs *c, const char *path)
1588 {
1589         struct bch_opts opts = bch2_opts_empty();
1590         struct bch_sb_handle sb = { NULL };
1591         struct bch_dev *ca;
1592         unsigned dev_idx;
1593         const char *err;
1594         int ret;
1595
1596         mutex_lock(&c->state_lock);
1597
1598         ret = bch2_read_super(path, &opts, &sb);
1599         if (ret) {
1600                 mutex_unlock(&c->state_lock);
1601                 return ret;
1602         }
1603
1604         dev_idx = sb.sb->dev_idx;
1605
1606         err = bch2_dev_in_fs(c->disk_sb, sb.sb);
1607         if (err)
1608                 goto err;
1609
1610         if (__bch2_dev_online(c, &sb)) {
1611                 err = "__bch2_dev_online() error";
1612                 goto err;
1613         }
1614
1615         ca = bch_dev_locked(c, dev_idx);
1616         if (ca->mi.state == BCH_MEMBER_STATE_RW) {
1617                 err = __bch2_dev_read_write(c, ca);
1618                 if (err)
1619                         goto err;
1620         }
1621
1622         mutex_unlock(&c->state_lock);
1623         return 0;
1624 err:
1625         mutex_unlock(&c->state_lock);
1626         bch2_free_super(&sb);
1627         bch_err(c, "error bringing %s online: %s", path, err);
1628         return -EINVAL;
1629 }
1630
1631 int bch2_dev_offline(struct bch_fs *c, struct bch_dev *ca, int flags)
1632 {
1633         mutex_lock(&c->state_lock);
1634
1635         if (!bch2_dev_is_online(ca)) {
1636                 bch_err(ca, "Already offline");
1637                 mutex_unlock(&c->state_lock);
1638                 return 0;
1639         }
1640
1641         if (!bch2_dev_state_allowed(c, ca, BCH_MEMBER_STATE_FAILED, flags)) {
1642                 bch_err(ca, "Cannot offline required disk");
1643                 mutex_unlock(&c->state_lock);
1644                 return -EINVAL;
1645         }
1646
1647         __bch2_dev_offline(c, ca);
1648
1649         mutex_unlock(&c->state_lock);
1650         return 0;
1651 }
1652
1653 int bch2_dev_resize(struct bch_fs *c, struct bch_dev *ca, u64 nbuckets)
1654 {
1655         struct bch_member *mi;
1656         int ret = 0;
1657
1658         mutex_lock(&c->state_lock);
1659
1660         if (nbuckets < ca->mi.nbuckets) {
1661                 bch_err(ca, "Cannot shrink yet");
1662                 ret = -EINVAL;
1663                 goto err;
1664         }
1665
1666         if (bch2_dev_is_online(ca) &&
1667             get_capacity(ca->disk_sb.bdev->bd_disk) <
1668             ca->mi.bucket_size * nbuckets) {
1669                 bch_err(ca, "New size larger than device");
1670                 ret = -EINVAL;
1671                 goto err;
1672         }
1673
1674         ret = bch2_dev_buckets_resize(c, ca, nbuckets);
1675         if (ret) {
1676                 bch_err(ca, "Resize error: %i", ret);
1677                 goto err;
1678         }
1679
1680         mutex_lock(&c->sb_lock);
1681         mi = &bch2_sb_get_members(c->disk_sb)->members[ca->dev_idx];
1682         mi->nbuckets = cpu_to_le64(nbuckets);
1683
1684         bch2_write_super(c);
1685         mutex_unlock(&c->sb_lock);
1686
1687         bch2_recalc_capacity(c);
1688 err:
1689         mutex_unlock(&c->state_lock);
1690         return ret;
1691 }
1692
1693 /* Filesystem open: */
1694
1695 struct bch_fs *bch2_fs_open(char * const *devices, unsigned nr_devices,
1696                             struct bch_opts opts)
1697 {
1698         struct bch_sb_handle *sb = NULL;
1699         struct bch_fs *c = NULL;
1700         unsigned i, best_sb = 0;
1701         const char *err;
1702         int ret = -ENOMEM;
1703
1704         if (!nr_devices)
1705                 return ERR_PTR(-EINVAL);
1706
1707         if (!try_module_get(THIS_MODULE))
1708                 return ERR_PTR(-ENODEV);
1709
1710         sb = kcalloc(nr_devices, sizeof(*sb), GFP_KERNEL);
1711         if (!sb)
1712                 goto err;
1713
1714         for (i = 0; i < nr_devices; i++) {
1715                 ret = bch2_read_super(devices[i], &opts, &sb[i]);
1716                 if (ret)
1717                         goto err;
1718
1719                 err = bch2_sb_validate(&sb[i]);
1720                 if (err)
1721                         goto err_print;
1722         }
1723
1724         for (i = 1; i < nr_devices; i++)
1725                 if (le64_to_cpu(sb[i].sb->seq) >
1726                     le64_to_cpu(sb[best_sb].sb->seq))
1727                         best_sb = i;
1728
1729         for (i = 0; i < nr_devices; i++) {
1730                 err = bch2_dev_in_fs(sb[best_sb].sb, sb[i].sb);
1731                 if (err)
1732                         goto err_print;
1733         }
1734
1735         ret = -ENOMEM;
1736         c = bch2_fs_alloc(sb[best_sb].sb, opts);
1737         if (!c)
1738                 goto err;
1739
1740         err = "bch2_dev_online() error";
1741         mutex_lock(&c->state_lock);
1742         for (i = 0; i < nr_devices; i++)
1743                 if (__bch2_dev_online(c, &sb[i])) {
1744                         mutex_unlock(&c->state_lock);
1745                         goto err_print;
1746                 }
1747         mutex_unlock(&c->state_lock);
1748
1749         err = "insufficient devices";
1750         if (!bch2_fs_may_start(c))
1751                 goto err_print;
1752
1753         if (!c->opts.nostart) {
1754                 err = __bch2_fs_start(c);
1755                 if (err)
1756                         goto err_print;
1757         }
1758
1759         err = bch2_fs_online(c);
1760         if (err)
1761                 goto err_print;
1762
1763         kfree(sb);
1764         module_put(THIS_MODULE);
1765         return c;
1766 err_print:
1767         pr_err("bch_fs_open err opening %s: %s",
1768                devices[0], err);
1769         ret = -EINVAL;
1770 err:
1771         if (c)
1772                 bch2_fs_stop(c);
1773
1774         for (i = 0; i < nr_devices; i++)
1775                 bch2_free_super(&sb[i]);
1776         kfree(sb);
1777         module_put(THIS_MODULE);
1778         return ERR_PTR(ret);
1779 }
1780
1781 static const char *__bch2_fs_open_incremental(struct bch_sb_handle *sb,
1782                                               struct bch_opts opts)
1783 {
1784         const char *err;
1785         struct bch_fs *c;
1786         bool allocated_fs = false;
1787
1788         err = bch2_sb_validate(sb);
1789         if (err)
1790                 return err;
1791
1792         mutex_lock(&bch_fs_list_lock);
1793         c = __bch2_uuid_to_fs(sb->sb->uuid);
1794         if (c) {
1795                 closure_get(&c->cl);
1796
1797                 err = bch2_dev_in_fs(c->disk_sb, sb->sb);
1798                 if (err)
1799                         goto err;
1800         } else {
1801                 c = bch2_fs_alloc(sb->sb, opts);
1802                 err = "cannot allocate memory";
1803                 if (!c)
1804                         goto err;
1805
1806                 allocated_fs = true;
1807         }
1808
1809         err = "bch2_dev_online() error";
1810
1811         mutex_lock(&c->sb_lock);
1812         if (__bch2_dev_online(c, sb)) {
1813                 mutex_unlock(&c->sb_lock);
1814                 goto err;
1815         }
1816         mutex_unlock(&c->sb_lock);
1817
1818         if (!c->opts.nostart && bch2_fs_may_start(c)) {
1819                 err = __bch2_fs_start(c);
1820                 if (err)
1821                         goto err;
1822         }
1823
1824         err = __bch2_fs_online(c);
1825         if (err)
1826                 goto err;
1827
1828         closure_put(&c->cl);
1829         mutex_unlock(&bch_fs_list_lock);
1830
1831         return NULL;
1832 err:
1833         mutex_unlock(&bch_fs_list_lock);
1834
1835         if (allocated_fs)
1836                 bch2_fs_stop(c);
1837         else if (c)
1838                 closure_put(&c->cl);
1839
1840         return err;
1841 }
1842
1843 const char *bch2_fs_open_incremental(const char *path)
1844 {
1845         struct bch_sb_handle sb;
1846         struct bch_opts opts = bch2_opts_empty();
1847         const char *err;
1848
1849         if (bch2_read_super(path, &opts, &sb))
1850                 return "error reading superblock";
1851
1852         err = __bch2_fs_open_incremental(&sb, opts);
1853         bch2_free_super(&sb);
1854
1855         return err;
1856 }
1857
1858 /* Global interfaces/init */
1859
1860 static void bcachefs_exit(void)
1861 {
1862         bch2_debug_exit();
1863         bch2_vfs_exit();
1864         bch2_chardev_exit();
1865         if (bcachefs_kset)
1866                 kset_unregister(bcachefs_kset);
1867 }
1868
1869 static int __init bcachefs_init(void)
1870 {
1871         bch2_bkey_pack_test();
1872         bch2_inode_pack_test();
1873
1874         if (!(bcachefs_kset = kset_create_and_add("bcachefs", NULL, fs_kobj)) ||
1875             bch2_chardev_init() ||
1876             bch2_vfs_init() ||
1877             bch2_debug_init())
1878                 goto err;
1879
1880         return 0;
1881 err:
1882         bcachefs_exit();
1883         return -ENOMEM;
1884 }
1885
1886 #define BCH_DEBUG_PARAM(name, description)                      \
1887         bool bch2_##name;                                       \
1888         module_param_named(name, bch2_##name, bool, 0644);      \
1889         MODULE_PARM_DESC(name, description);
1890 BCH_DEBUG_PARAMS()
1891 #undef BCH_DEBUG_PARAM
1892
1893 module_exit(bcachefs_exit);
1894 module_init(bcachefs_init);