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