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