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