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