]> git.sesse.net Git - bcachefs-tools-debian/blob - libbcachefs/super.c
bcachefs-in-userspace improvements
[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         bch2_btree_flush(c);
215
216         for_each_member_device(ca, c, i)
217                 bch2_dev_allocator_stop(ca);
218
219         bch2_fs_journal_stop(&c->journal);
220 }
221
222 static void bch2_writes_disabled(struct percpu_ref *writes)
223 {
224         struct bch_fs *c = container_of(writes, struct bch_fs, writes);
225
226         set_bit(BCH_FS_WRITE_DISABLE_COMPLETE, &c->flags);
227         wake_up(&bch_read_only_wait);
228 }
229
230 void bch2_fs_read_only(struct bch_fs *c)
231 {
232         mutex_lock(&c->state_lock);
233         if (c->state != BCH_FS_STARTING &&
234             c->state != BCH_FS_RW)
235                 goto out;
236
237         if (test_bit(BCH_FS_ERROR, &c->flags))
238                 goto out;
239
240         /*
241          * Block new foreground-end write operations from starting - any new
242          * writes will return -EROFS:
243          *
244          * (This is really blocking new _allocations_, writes to previously
245          * allocated space can still happen until stopping the allocator in
246          * bch2_dev_allocator_stop()).
247          */
248         percpu_ref_kill(&c->writes);
249
250         del_timer(&c->foreground_write_wakeup);
251         cancel_delayed_work(&c->pd_controllers_update);
252
253         c->foreground_write_pd.rate.rate = UINT_MAX;
254         bch2_wake_delayed_writes((unsigned long) c);
255
256         /*
257          * If we're not doing an emergency shutdown, we want to wait on
258          * outstanding writes to complete so they don't see spurious errors due
259          * to shutting down the allocator:
260          *
261          * If we are doing an emergency shutdown outstanding writes may
262          * hang until we shutdown the allocator so we don't want to wait
263          * on outstanding writes before shutting everything down - but
264          * we do need to wait on them before returning and signalling
265          * that going RO is complete:
266          */
267         wait_event(bch_read_only_wait,
268                    test_bit(BCH_FS_WRITE_DISABLE_COMPLETE, &c->flags) ||
269                    test_bit(BCH_FS_EMERGENCY_RO, &c->flags));
270
271         __bch2_fs_read_only(c);
272
273         wait_event(bch_read_only_wait,
274                    test_bit(BCH_FS_WRITE_DISABLE_COMPLETE, &c->flags));
275
276         clear_bit(BCH_FS_WRITE_DISABLE_COMPLETE, &c->flags);
277
278         if (!bch2_journal_error(&c->journal) &&
279             !test_bit(BCH_FS_ERROR, &c->flags)) {
280                 mutex_lock(&c->sb_lock);
281                 SET_BCH_SB_CLEAN(c->disk_sb, true);
282                 bch2_write_super(c);
283                 mutex_unlock(&c->sb_lock);
284         }
285
286         c->state = BCH_FS_RO;
287 out:
288         mutex_unlock(&c->state_lock);
289 }
290
291 static void bch2_fs_read_only_work(struct work_struct *work)
292 {
293         struct bch_fs *c =
294                 container_of(work, struct bch_fs, read_only_work);
295
296         bch2_fs_read_only(c);
297 }
298
299 static void bch2_fs_read_only_async(struct bch_fs *c)
300 {
301         queue_work(system_long_wq, &c->read_only_work);
302 }
303
304 bool bch2_fs_emergency_read_only(struct bch_fs *c)
305 {
306         bool ret = !test_and_set_bit(BCH_FS_EMERGENCY_RO, &c->flags);
307
308         bch2_fs_read_only_async(c);
309         bch2_journal_halt(&c->journal);
310
311         wake_up(&bch_read_only_wait);
312         return ret;
313 }
314
315 const char *bch2_fs_read_write(struct bch_fs *c)
316 {
317         struct bch_dev *ca;
318         const char *err = NULL;
319         unsigned i;
320
321         mutex_lock(&c->state_lock);
322         if (c->state != BCH_FS_STARTING &&
323             c->state != BCH_FS_RO)
324                 goto out;
325
326         err = "error starting allocator thread";
327         for_each_rw_member(ca, c, i)
328                 if (bch2_dev_allocator_start(ca)) {
329                         percpu_ref_put(&ca->io_ref);
330                         goto err;
331                 }
332
333         err = "error starting btree GC thread";
334         if (bch2_gc_thread_start(c))
335                 goto err;
336
337         err = "error starting moving GC thread";
338         for_each_rw_member(ca, c, i)
339                 if (bch2_moving_gc_start(ca)) {
340                         percpu_ref_put(&ca->io_ref);
341                         goto err;
342                 }
343
344         err = "error starting tiering thread";
345         if (bch2_tiering_start(c))
346                 goto err;
347
348         schedule_delayed_work(&c->pd_controllers_update, 5 * HZ);
349
350         if (c->state != BCH_FS_STARTING)
351                 percpu_ref_reinit(&c->writes);
352
353         c->state = BCH_FS_RW;
354         err = NULL;
355 out:
356         mutex_unlock(&c->state_lock);
357         return err;
358 err:
359         __bch2_fs_read_only(c);
360         goto out;
361 }
362
363 /* Filesystem startup/shutdown: */
364
365 static void bch2_fs_free(struct bch_fs *c)
366 {
367         bch2_fs_encryption_exit(c);
368         bch2_fs_btree_exit(c);
369         bch2_fs_journal_exit(&c->journal);
370         bch2_io_clock_exit(&c->io_clock[WRITE]);
371         bch2_io_clock_exit(&c->io_clock[READ]);
372         bch2_fs_compress_exit(c);
373         bdi_destroy(&c->bdi);
374         lg_lock_free(&c->usage_lock);
375         free_percpu(c->usage_percpu);
376         mempool_exit(&c->btree_bounce_pool);
377         mempool_exit(&c->bio_bounce_pages);
378         bioset_exit(&c->bio_write);
379         bioset_exit(&c->bio_read_split);
380         bioset_exit(&c->bio_read);
381         bioset_exit(&c->btree_read_bio);
382         mempool_exit(&c->btree_interior_update_pool);
383         mempool_exit(&c->btree_reserve_pool);
384         mempool_exit(&c->fill_iter);
385         percpu_ref_exit(&c->writes);
386
387         if (c->copygc_wq)
388                 destroy_workqueue(c->copygc_wq);
389         if (c->wq)
390                 destroy_workqueue(c->wq);
391
392         free_pages((unsigned long) c->disk_sb, c->disk_sb_order);
393         kfree(c);
394         module_put(THIS_MODULE);
395 }
396
397 static void bch2_fs_exit(struct bch_fs *c)
398 {
399         unsigned i;
400
401         del_timer_sync(&c->foreground_write_wakeup);
402         cancel_delayed_work_sync(&c->pd_controllers_update);
403         cancel_work_sync(&c->read_only_work);
404         cancel_work_sync(&c->read_retry_work);
405
406         for (i = 0; i < c->sb.nr_devices; i++)
407                 if (c->devs[i])
408                         bch2_dev_free(c->devs[i]);
409
410         closure_debug_destroy(&c->cl);
411         kobject_put(&c->kobj);
412 }
413
414 static void bch2_fs_offline(struct bch_fs *c)
415 {
416         struct bch_dev *ca;
417         unsigned i;
418
419         mutex_lock(&bch_fs_list_lock);
420         list_del(&c->list);
421         mutex_unlock(&bch_fs_list_lock);
422
423         for_each_member_device(ca, c, i)
424                 if (ca->kobj.state_in_sysfs &&
425                     ca->disk_sb.bdev)
426                         sysfs_remove_link(&part_to_dev(ca->disk_sb.bdev->bd_part)->kobj,
427                                           "bcachefs");
428
429         if (c->kobj.state_in_sysfs)
430                 kobject_del(&c->kobj);
431
432         bch2_fs_debug_exit(c);
433         bch2_fs_chardev_exit(c);
434
435         kobject_put(&c->time_stats);
436         kobject_put(&c->opts_dir);
437         kobject_put(&c->internal);
438
439         __bch2_fs_read_only(c);
440 }
441
442 static void bch2_fs_release(struct kobject *kobj)
443 {
444         struct bch_fs *c = container_of(kobj, struct bch_fs, kobj);
445
446         bch2_fs_free(c);
447 }
448
449 void bch2_fs_stop(struct bch_fs *c)
450 {
451         mutex_lock(&c->state_lock);
452         BUG_ON(c->state == BCH_FS_STOPPING);
453         c->state = BCH_FS_STOPPING;
454         mutex_unlock(&c->state_lock);
455
456         bch2_fs_offline(c);
457
458         closure_sync(&c->cl);
459
460         bch2_fs_exit(c);
461 }
462
463 #define alloc_bucket_pages(gfp, ca)                     \
464         ((void *) __get_free_pages(__GFP_ZERO|gfp, ilog2(bucket_pages(ca))))
465
466 static struct bch_fs *bch2_fs_alloc(struct bch_sb *sb, struct bch_opts opts)
467 {
468         struct bch_sb_field_members *mi;
469         struct bch_fs *c;
470         unsigned i, iter_size, journal_entry_bytes;
471
472         c = kzalloc(sizeof(struct bch_fs), GFP_KERNEL);
473         if (!c)
474                 return NULL;
475
476         __module_get(THIS_MODULE);
477
478         c->minor                = -1;
479
480         mutex_init(&c->state_lock);
481         mutex_init(&c->sb_lock);
482         mutex_init(&c->btree_cache_lock);
483         mutex_init(&c->bucket_lock);
484         mutex_init(&c->btree_root_lock);
485         INIT_WORK(&c->read_only_work, bch2_fs_read_only_work);
486
487         init_rwsem(&c->gc_lock);
488
489 #define BCH_TIME_STAT(name, frequency_units, duration_units)            \
490         spin_lock_init(&c->name##_time.lock);
491         BCH_TIME_STATS()
492 #undef BCH_TIME_STAT
493
494         bch2_fs_allocator_init(c);
495         bch2_fs_tiering_init(c);
496
497         INIT_LIST_HEAD(&c->list);
498         INIT_LIST_HEAD(&c->btree_cache);
499         INIT_LIST_HEAD(&c->btree_cache_freeable);
500         INIT_LIST_HEAD(&c->btree_cache_freed);
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         bio_list_init(&c->read_retry_list);
508         spin_lock_init(&c->read_retry_lock);
509         INIT_WORK(&c->read_retry_work, bch2_read_retry_work);
510         mutex_init(&c->zlib_workspace_lock);
511
512         seqcount_init(&c->gc_pos_lock);
513
514         c->prio_clock[READ].hand = 1;
515         c->prio_clock[READ].min_prio = 0;
516         c->prio_clock[WRITE].hand = 1;
517         c->prio_clock[WRITE].min_prio = 0;
518
519         init_waitqueue_head(&c->writeback_wait);
520         c->writeback_pages_max = (256 << 10) / PAGE_SIZE;
521
522         c->copy_gc_enabled = 1;
523         c->tiering_enabled = 1;
524         c->tiering_percent = 10;
525
526         c->foreground_target_percent = 20;
527
528         c->journal.write_time   = &c->journal_write_time;
529         c->journal.delay_time   = &c->journal_delay_time;
530         c->journal.blocked_time = &c->journal_blocked_time;
531         c->journal.flush_seq_time = &c->journal_flush_seq_time;
532
533         mutex_lock(&c->sb_lock);
534
535         if (bch2_sb_to_fs(c, sb)) {
536                 mutex_unlock(&c->sb_lock);
537                 goto err;
538         }
539
540         mutex_unlock(&c->sb_lock);
541
542         scnprintf(c->name, sizeof(c->name), "%pU", &c->sb.user_uuid);
543
544         bch2_opts_apply(&c->opts, bch2_sb_opts(sb));
545         bch2_opts_apply(&c->opts, opts);
546
547         c->opts.nochanges       |= c->opts.noreplay;
548         c->opts.read_only       |= c->opts.nochanges;
549
550         c->block_bits           = ilog2(c->sb.block_size);
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         journal_entry_bytes = 512U << BCH_SB_JOURNAL_ENTRY_SIZE(sb);
559
560         if (!(c->wq = alloc_workqueue("bcachefs",
561                                 WQ_FREEZABLE|WQ_MEM_RECLAIM|WQ_HIGHPRI, 1)) ||
562             !(c->copygc_wq = alloc_workqueue("bcache_copygc",
563                                 WQ_FREEZABLE|WQ_MEM_RECLAIM|WQ_HIGHPRI, 1)) ||
564             percpu_ref_init(&c->writes, bch2_writes_disabled, 0, GFP_KERNEL) ||
565             mempool_init_kmalloc_pool(&c->btree_reserve_pool, 1,
566                                       sizeof(struct btree_reserve)) ||
567             mempool_init_kmalloc_pool(&c->btree_interior_update_pool, 1,
568                                       sizeof(struct btree_interior_update)) ||
569             mempool_init_kmalloc_pool(&c->fill_iter, 1, iter_size) ||
570             bioset_init(&c->btree_read_bio, 1, 0) ||
571             bioset_init(&c->bio_read, 1, offsetof(struct bch_read_bio, bio)) ||
572             bioset_init(&c->bio_read_split, 1, offsetof(struct bch_read_bio, bio)) ||
573             bioset_init(&c->bio_write, 1, offsetof(struct bch_write_bio, bio)) ||
574             mempool_init_page_pool(&c->bio_bounce_pages,
575                                    max_t(unsigned,
576                                          c->sb.btree_node_size,
577                                          BCH_ENCODED_EXTENT_MAX) /
578                                    PAGE_SECTORS, 0) ||
579             !(c->usage_percpu = alloc_percpu(struct bch_fs_usage)) ||
580             lg_lock_init(&c->usage_lock) ||
581             mempool_init_page_pool(&c->btree_bounce_pool, 1,
582                                    ilog2(btree_pages(c))) ||
583             bdi_setup_and_register(&c->bdi, "bcachefs") ||
584             bch2_io_clock_init(&c->io_clock[READ]) ||
585             bch2_io_clock_init(&c->io_clock[WRITE]) ||
586             bch2_fs_journal_init(&c->journal, journal_entry_bytes) ||
587             bch2_fs_btree_init(c) ||
588             bch2_fs_encryption_init(c) ||
589             bch2_fs_compress_init(c) ||
590             bch2_check_set_has_compressed_data(c, c->opts.compression))
591                 goto err;
592
593         c->bdi.ra_pages         = VM_MAX_READAHEAD * 1024 / PAGE_SIZE;
594         c->bdi.congested_fn     = bch2_congested_fn;
595         c->bdi.congested_data   = c;
596
597         mi = bch2_sb_get_members(c->disk_sb);
598         for (i = 0; i < c->sb.nr_devices; i++)
599                 if (!bch2_is_zero(mi->members[i].uuid.b, sizeof(uuid_le)) &&
600                     bch2_dev_alloc(c, i))
601                         goto err;
602
603         /*
604          * Now that all allocations have succeeded, init various refcounty
605          * things that let us shutdown:
606          */
607         closure_init(&c->cl, NULL);
608
609         c->kobj.kset = bcachefs_kset;
610         kobject_init(&c->kobj, &bch2_fs_ktype);
611         kobject_init(&c->internal, &bch2_fs_internal_ktype);
612         kobject_init(&c->opts_dir, &bch2_fs_opts_dir_ktype);
613         kobject_init(&c->time_stats, &bch2_fs_time_stats_ktype);
614         return c;
615 err:
616         bch2_fs_free(c);
617         return NULL;
618 }
619
620 static const char *__bch2_fs_online(struct bch_fs *c)
621 {
622         struct bch_dev *ca;
623         const char *err = NULL;
624         unsigned i;
625         int ret;
626
627         lockdep_assert_held(&bch_fs_list_lock);
628
629         if (!list_empty(&c->list))
630                 return NULL;
631
632         if (__bch2_uuid_to_fs(c->sb.uuid))
633                 return "filesystem UUID already open";
634
635         ret = bch2_fs_chardev_init(c);
636         if (ret)
637                 return "error creating character device";
638
639         bch2_fs_debug_init(c);
640
641         if (kobject_add(&c->kobj, NULL, "%pU", c->sb.user_uuid.b) ||
642             kobject_add(&c->internal, &c->kobj, "internal") ||
643             kobject_add(&c->opts_dir, &c->kobj, "options") ||
644             kobject_add(&c->time_stats, &c->kobj, "time_stats"))
645                 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)
651                 if (bch2_dev_sysfs_online(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         unsigned i, id;
678         time64_t now;
679         LIST_HEAD(journal);
680         struct jset *j;
681         int ret = -EINVAL;
682
683         BUG_ON(c->state != BCH_FS_STARTING);
684
685         mutex_lock(&c->sb_lock);
686         for_each_online_member(ca, c, i)
687                 bch2_sb_from_fs(c, ca);
688         mutex_unlock(&c->sb_lock);
689
690         if (BCH_SB_INITIALIZED(c->disk_sb)) {
691                 ret = bch2_journal_read(c, &journal);
692                 if (ret)
693                         goto err;
694
695                 j = &list_entry(journal.prev, struct journal_replay, list)->j;
696
697                 c->prio_clock[READ].hand = le16_to_cpu(j->read_clock);
698                 c->prio_clock[WRITE].hand = le16_to_cpu(j->write_clock);
699
700                 err = "error reading priorities";
701                 for_each_readable_member(ca, c, i) {
702                         ret = bch2_prio_read(ca);
703                         if (ret) {
704                                 percpu_ref_put(&ca->io_ref);
705                                 goto err;
706                         }
707                 }
708
709                 for (id = 0; id < BTREE_ID_NR; id++) {
710                         unsigned level;
711                         struct bkey_i *k;
712
713                         err = "bad btree root";
714                         k = bch2_journal_find_btree_root(c, j, id, &level);
715                         if (!k && id == BTREE_ID_EXTENTS)
716                                 goto err;
717                         if (!k) {
718                                 pr_debug("missing btree root: %d", id);
719                                 continue;
720                         }
721
722                         err = "error reading btree root";
723                         if (bch2_btree_root_read(c, id, k, level))
724                                 goto err;
725                 }
726
727                 bch_verbose(c, "starting mark and sweep:");
728
729                 err = "error in recovery";
730                 if (bch2_initial_gc(c, &journal))
731                         goto err;
732
733                 if (c->opts.noreplay)
734                         goto recovery_done;
735
736                 bch_verbose(c, "mark and sweep done");
737
738                 /*
739                  * bch2_journal_start() can't happen sooner, or btree_gc_finish()
740                  * will give spurious errors about oldest_gen > bucket_gen -
741                  * this is a hack but oh well.
742                  */
743                 bch2_journal_start(c);
744
745                 err = "error starting allocator thread";
746                 for_each_rw_member(ca, c, i)
747                         if (bch2_dev_allocator_start(ca)) {
748                                 percpu_ref_put(&ca->io_ref);
749                                 goto err;
750                         }
751
752                 bch_verbose(c, "starting journal replay:");
753
754                 err = "journal replay failed";
755                 ret = bch2_journal_replay(c, &journal);
756                 if (ret)
757                         goto err;
758
759                 bch_verbose(c, "journal replay done");
760
761                 if (c->opts.norecovery)
762                         goto recovery_done;
763
764                 bch_verbose(c, "starting fsck:");
765                 err = "error in fsck";
766                 ret = bch2_fsck(c, !c->opts.nofsck);
767                 if (ret)
768                         goto err;
769
770                 bch_verbose(c, "fsck done");
771         } else {
772                 struct bch_inode_unpacked inode;
773                 struct bkey_inode_buf packed_inode;
774                 struct closure cl;
775
776                 closure_init_stack(&cl);
777
778                 bch_notice(c, "initializing new filesystem");
779
780                 bch2_initial_gc(c, NULL);
781
782                 err = "unable to allocate journal buckets";
783                 for_each_rw_member(ca, c, i)
784                         if (bch2_dev_journal_alloc(ca)) {
785                                 percpu_ref_put(&ca->io_ref);
786                                 goto err;
787                         }
788
789                 /*
790                  * journal_res_get() will crash if called before this has
791                  * set up the journal.pin FIFO and journal.cur pointer:
792                  */
793                 bch2_journal_start(c);
794                 bch2_journal_set_replay_done(&c->journal);
795
796                 err = "error starting allocator thread";
797                 for_each_rw_member(ca, c, i)
798                         if (bch2_dev_allocator_start(ca)) {
799                                 percpu_ref_put(&ca->io_ref);
800                                 goto err;
801                         }
802
803                 err = "cannot allocate new btree root";
804                 for (id = 0; id < BTREE_ID_NR; id++)
805                         if (bch2_btree_root_alloc(c, id, &cl)) {
806                                 closure_sync(&cl);
807                                 goto err;
808                         }
809
810                 /* Wait for new btree roots to be written: */
811                 closure_sync(&cl);
812
813                 bch2_inode_init(c, &inode, 0, 0,
814                                S_IFDIR|S_IRWXU|S_IRUGO|S_IXUGO, 0);
815                 inode.inum = BCACHE_ROOT_INO;
816
817                 bch2_inode_pack(&packed_inode, &inode);
818
819                 err = "error creating root directory";
820                 if (bch2_btree_insert(c, BTREE_ID_INODES,
821                                      &packed_inode.inode.k_i,
822                                      NULL, NULL, NULL, 0))
823                         goto err;
824
825                 err = "error writing first journal entry";
826                 if (bch2_journal_meta(&c->journal))
827                         goto err;
828         }
829 recovery_done:
830         err = "dynamic fault";
831         if (bch2_fs_init_fault("fs_start"))
832                 goto err;
833
834         if (c->opts.read_only) {
835                 bch2_fs_read_only(c);
836         } else {
837                 err = bch2_fs_read_write(c);
838                 if (err)
839                         goto err;
840         }
841
842         mutex_lock(&c->sb_lock);
843         mi = bch2_sb_get_members(c->disk_sb);
844         now = ktime_get_seconds();
845
846         for_each_member_device(ca, c, i)
847                 mi->members[ca->dev_idx].last_mount = cpu_to_le64(now);
848
849         SET_BCH_SB_INITIALIZED(c->disk_sb, true);
850         SET_BCH_SB_CLEAN(c->disk_sb, false);
851         c->disk_sb->version = BCACHE_SB_VERSION_CDEV;
852
853         bch2_write_super(c);
854         mutex_unlock(&c->sb_lock);
855
856         err = NULL;
857 out:
858         bch2_journal_entries_free(&journal);
859         return err;
860 err:
861         switch (ret) {
862         case BCH_FSCK_ERRORS_NOT_FIXED:
863                 bch_err(c, "filesystem contains errors: please report this to the developers");
864                 pr_cont("mount with -o fix_errors to repair");
865                 err = "fsck error";
866                 break;
867         case BCH_FSCK_REPAIR_UNIMPLEMENTED:
868                 bch_err(c, "filesystem contains errors: please report this to the developers");
869                 pr_cont("repair unimplemented: inform the developers so that it can be added");
870                 err = "fsck error";
871                 break;
872         case BCH_FSCK_REPAIR_IMPOSSIBLE:
873                 bch_err(c, "filesystem contains errors, but repair impossible");
874                 err = "fsck error";
875                 break;
876         case BCH_FSCK_UNKNOWN_VERSION:
877                 err = "unknown metadata version";;
878                 break;
879         case -ENOMEM:
880                 err = "cannot allocate memory";
881                 break;
882         case -EIO:
883                 err = "IO error";
884                 break;
885         }
886
887         BUG_ON(!err);
888         set_bit(BCH_FS_ERROR, &c->flags);
889         goto out;
890 }
891
892 const char *bch2_fs_start(struct bch_fs *c)
893 {
894         return __bch2_fs_start(c) ?: bch2_fs_online(c);
895 }
896
897 static const char *bch2_dev_may_add(struct bch_sb *sb, struct bch_fs *c)
898 {
899         struct bch_sb_field_members *sb_mi;
900
901         sb_mi = bch2_sb_get_members(sb);
902         if (!sb_mi)
903                 return "Invalid superblock: member info area missing";
904
905         if (le16_to_cpu(sb->block_size) != c->sb.block_size)
906                 return "mismatched block size";
907
908         if (le16_to_cpu(sb_mi->members[sb->dev_idx].bucket_size) <
909             BCH_SB_BTREE_NODE_SIZE(c->disk_sb))
910                 return "new cache bucket size is too small";
911
912         return NULL;
913 }
914
915 static const char *bch2_dev_in_fs(struct bch_sb *fs, struct bch_sb *sb)
916 {
917         struct bch_sb *newest =
918                 le64_to_cpu(fs->seq) > le64_to_cpu(sb->seq) ? fs : sb;
919         struct bch_sb_field_members *mi = bch2_sb_get_members(newest);
920
921         if (uuid_le_cmp(fs->uuid, sb->uuid))
922                 return "device not a member of filesystem";
923
924         if (sb->dev_idx >= newest->nr_devices)
925                 return "device has invalid dev_idx";
926
927         if (bch2_is_zero(mi->members[sb->dev_idx].uuid.b, sizeof(uuid_le)))
928                 return "device has been removed";
929
930         if (fs->block_size != sb->block_size)
931                 return "mismatched block size";
932
933         return NULL;
934 }
935
936 /* Device startup/shutdown: */
937
938 static void bch2_dev_release(struct kobject *kobj)
939 {
940         struct bch_dev *ca = container_of(kobj, struct bch_dev, kobj);
941
942         kfree(ca);
943 }
944
945 static void bch2_dev_free(struct bch_dev *ca)
946 {
947         unsigned i;
948
949         cancel_work_sync(&ca->io_error_work);
950
951         if (ca->kobj.state_in_sysfs &&
952             ca->disk_sb.bdev)
953                 sysfs_remove_link(&part_to_dev(ca->disk_sb.bdev->bd_part)->kobj,
954                                   "bcachefs");
955
956         if (ca->kobj.state_in_sysfs)
957                 kobject_del(&ca->kobj);
958
959         bch2_free_super(&ca->disk_sb);
960         bch2_dev_journal_exit(ca);
961
962         free_percpu(ca->sectors_written);
963         bioset_exit(&ca->replica_set);
964         free_percpu(ca->usage_percpu);
965         free_pages((unsigned long) ca->disk_buckets, ilog2(bucket_pages(ca)));
966         kfree(ca->prio_buckets);
967         kfree(ca->bio_prio);
968         vfree(ca->buckets);
969         vfree(ca->oldest_gens);
970         free_heap(&ca->heap);
971         free_fifo(&ca->free_inc);
972
973         for (i = 0; i < RESERVE_NR; i++)
974                 free_fifo(&ca->free[i]);
975
976         percpu_ref_exit(&ca->io_ref);
977         percpu_ref_exit(&ca->ref);
978         kobject_put(&ca->kobj);
979 }
980
981 static void bch2_dev_io_ref_release(struct percpu_ref *ref)
982 {
983         struct bch_dev *ca = container_of(ref, struct bch_dev, io_ref);
984
985         complete(&ca->offline_complete);
986 }
987
988 static void __bch2_dev_offline(struct bch_dev *ca)
989 {
990         struct bch_fs *c = ca->fs;
991
992         lockdep_assert_held(&c->state_lock);
993
994         __bch2_dev_read_only(ca->fs, ca);
995
996         reinit_completion(&ca->offline_complete);
997         percpu_ref_kill(&ca->io_ref);
998         wait_for_completion(&ca->offline_complete);
999
1000         if (ca->kobj.state_in_sysfs) {
1001                 struct kobject *block =
1002                         &part_to_dev(ca->disk_sb.bdev->bd_part)->kobj;
1003
1004                 sysfs_remove_link(block, "bcachefs");
1005                 sysfs_remove_link(&ca->kobj, "block");
1006         }
1007
1008         bch2_free_super(&ca->disk_sb);
1009         bch2_dev_journal_exit(ca);
1010 }
1011
1012 static void bch2_dev_ref_release(struct percpu_ref *ref)
1013 {
1014         struct bch_dev *ca = container_of(ref, struct bch_dev, ref);
1015
1016         complete(&ca->stop_complete);
1017 }
1018
1019 static void bch2_dev_stop(struct bch_dev *ca)
1020 {
1021         struct bch_fs *c = ca->fs;
1022
1023         lockdep_assert_held(&c->state_lock);
1024
1025         BUG_ON(rcu_access_pointer(c->devs[ca->dev_idx]) != ca);
1026         rcu_assign_pointer(c->devs[ca->dev_idx], NULL);
1027
1028         synchronize_rcu();
1029
1030         reinit_completion(&ca->stop_complete);
1031         percpu_ref_kill(&ca->ref);
1032         wait_for_completion(&ca->stop_complete);
1033 }
1034
1035 static int bch2_dev_sysfs_online(struct bch_dev *ca)
1036 {
1037         struct bch_fs *c = ca->fs;
1038         int ret;
1039
1040         if (!c->kobj.state_in_sysfs)
1041                 return 0;
1042
1043         if (!ca->kobj.state_in_sysfs) {
1044                 ret = kobject_add(&ca->kobj, &ca->fs->kobj,
1045                                   "dev-%u", ca->dev_idx);
1046                 if (ret)
1047                         return ret;
1048         }
1049
1050         if (ca->disk_sb.bdev) {
1051                 struct kobject *block =
1052                         &part_to_dev(ca->disk_sb.bdev->bd_part)->kobj;
1053
1054                 ret = sysfs_create_link(block, &ca->kobj, "bcachefs");
1055                 if (ret)
1056                         return ret;
1057                 ret = sysfs_create_link(&ca->kobj, block, "block");
1058                 if (ret)
1059                         return ret;
1060         }
1061
1062         return 0;
1063 }
1064
1065 static int bch2_dev_alloc(struct bch_fs *c, unsigned dev_idx)
1066 {
1067         struct bch_member *member;
1068         size_t reserve_none, movinggc_reserve, free_inc_reserve, total_reserve;
1069         size_t heap_size;
1070         unsigned i;
1071         struct bch_dev *ca;
1072
1073         if (bch2_fs_init_fault("dev_alloc"))
1074                 return -ENOMEM;
1075
1076         ca = kzalloc(sizeof(*ca), GFP_KERNEL);
1077         if (!ca)
1078                 return -ENOMEM;
1079
1080         kobject_init(&ca->kobj, &bch2_dev_ktype);
1081         init_completion(&ca->stop_complete);
1082         init_completion(&ca->offline_complete);
1083
1084         spin_lock_init(&ca->self.lock);
1085         ca->self.nr = 1;
1086         rcu_assign_pointer(ca->self.d[0].dev, ca);
1087         ca->dev_idx = dev_idx;
1088
1089         spin_lock_init(&ca->freelist_lock);
1090         spin_lock_init(&ca->prio_buckets_lock);
1091         mutex_init(&ca->heap_lock);
1092         bch2_dev_moving_gc_init(ca);
1093
1094         INIT_WORK(&ca->io_error_work, bch2_nonfatal_io_error_work);
1095
1096         if (bch2_fs_init_fault("dev_alloc"))
1097                 goto err;
1098
1099         member = bch2_sb_get_members(c->disk_sb)->members + dev_idx;
1100
1101         ca->mi = bch2_mi_to_cpu(member);
1102         ca->uuid = member->uuid;
1103         ca->bucket_bits = ilog2(ca->mi.bucket_size);
1104         scnprintf(ca->name, sizeof(ca->name), "dev-%u", dev_idx);
1105
1106         /* XXX: tune these */
1107         movinggc_reserve = max_t(size_t, 16, ca->mi.nbuckets >> 7);
1108         reserve_none = max_t(size_t, 4, ca->mi.nbuckets >> 9);
1109         /*
1110          * free_inc must be smaller than the copygc reserve: if it was bigger,
1111          * one copygc iteration might not make enough buckets available to fill
1112          * up free_inc and allow the allocator to make forward progress
1113          */
1114         free_inc_reserve = movinggc_reserve / 2;
1115         heap_size = movinggc_reserve * 8;
1116
1117         if (percpu_ref_init(&ca->ref, bch2_dev_ref_release,
1118                             0, GFP_KERNEL) ||
1119             percpu_ref_init(&ca->io_ref, bch2_dev_io_ref_release,
1120                             PERCPU_REF_INIT_DEAD, GFP_KERNEL) ||
1121             !init_fifo(&ca->free[RESERVE_PRIO], prio_buckets(ca), GFP_KERNEL) ||
1122             !init_fifo(&ca->free[RESERVE_BTREE], BTREE_NODE_RESERVE, GFP_KERNEL) ||
1123             !init_fifo(&ca->free[RESERVE_MOVINGGC],
1124                        movinggc_reserve, GFP_KERNEL) ||
1125             !init_fifo(&ca->free[RESERVE_NONE], reserve_none, GFP_KERNEL) ||
1126             !init_fifo(&ca->free_inc,   free_inc_reserve, GFP_KERNEL) ||
1127             !init_heap(&ca->heap,       heap_size, GFP_KERNEL) ||
1128             !(ca->oldest_gens   = vzalloc(sizeof(u8) *
1129                                           ca->mi.nbuckets)) ||
1130             !(ca->buckets       = vzalloc(sizeof(struct bucket) *
1131                                           ca->mi.nbuckets)) ||
1132             !(ca->prio_buckets  = kzalloc(sizeof(u64) * prio_buckets(ca) *
1133                                           2, GFP_KERNEL)) ||
1134             !(ca->disk_buckets  = alloc_bucket_pages(GFP_KERNEL, ca)) ||
1135             !(ca->usage_percpu = alloc_percpu(struct bch_dev_usage)) ||
1136             !(ca->bio_prio = bio_kmalloc(GFP_NOIO, bucket_pages(ca))) ||
1137             bioset_init(&ca->replica_set, 4,
1138                         offsetof(struct bch_write_bio, bio)) ||
1139             !(ca->sectors_written = alloc_percpu(*ca->sectors_written)))
1140                 goto err;
1141
1142         ca->prio_last_buckets = ca->prio_buckets + prio_buckets(ca);
1143
1144         total_reserve = ca->free_inc.size;
1145         for (i = 0; i < RESERVE_NR; i++)
1146                 total_reserve += ca->free[i].size;
1147
1148         ca->copygc_write_point.group = &ca->self;
1149         ca->tiering_write_point.group = &ca->self;
1150
1151         ca->fs = c;
1152         rcu_assign_pointer(c->devs[ca->dev_idx], ca);
1153
1154         if (bch2_dev_sysfs_online(ca))
1155                 pr_warn("error creating sysfs objects");
1156
1157         return 0;
1158 err:
1159         bch2_dev_free(ca);
1160         return -ENOMEM;
1161 }
1162
1163 static int __bch2_dev_online(struct bch_fs *c, struct bcache_superblock *sb)
1164 {
1165         struct bch_dev *ca;
1166         int ret;
1167
1168         lockdep_assert_held(&c->sb_lock);
1169
1170         if (le64_to_cpu(sb->sb->seq) >
1171             le64_to_cpu(c->disk_sb->seq))
1172                 bch2_sb_to_fs(c, sb->sb);
1173
1174         BUG_ON(sb->sb->dev_idx >= c->sb.nr_devices ||
1175                !c->devs[sb->sb->dev_idx]);
1176
1177         ca = c->devs[sb->sb->dev_idx];
1178         if (ca->disk_sb.bdev) {
1179                 bch_err(c, "already have device online in slot %u",
1180                         sb->sb->dev_idx);
1181                 return -EINVAL;
1182         }
1183
1184         ret = bch2_dev_journal_init(ca, sb->sb);
1185         if (ret)
1186                 return ret;
1187
1188         /*
1189          * Increase journal write timeout if flushes to this device are
1190          * expensive:
1191          */
1192         if (!blk_queue_nonrot(bdev_get_queue(sb->bdev)) &&
1193             journal_flushes_device(ca))
1194                 c->journal.write_delay_ms =
1195                         max(c->journal.write_delay_ms, 1000U);
1196
1197         /* Commit: */
1198         ca->disk_sb = *sb;
1199         if (sb->mode & FMODE_EXCL)
1200                 ca->disk_sb.bdev->bd_holder = ca;
1201         memset(sb, 0, sizeof(*sb));
1202
1203         if (c->sb.nr_devices == 1)
1204                 bdevname(ca->disk_sb.bdev, c->name);
1205         bdevname(ca->disk_sb.bdev, ca->name);
1206
1207         if (bch2_dev_sysfs_online(ca))
1208                 pr_warn("error creating sysfs objects");
1209
1210         lg_local_lock(&c->usage_lock);
1211         if (!gc_will_visit(c, gc_phase(GC_PHASE_SB_METADATA)))
1212                 bch2_mark_dev_metadata(ca->fs, ca);
1213         lg_local_unlock(&c->usage_lock);
1214
1215         percpu_ref_reinit(&ca->io_ref);
1216         return 0;
1217 }
1218
1219 /* Device management: */
1220
1221 bool bch2_fs_may_start(struct bch_fs *c, int flags)
1222 {
1223         struct bch_sb_field_members *mi;
1224         unsigned meta_missing = 0;
1225         unsigned data_missing = 0;
1226         bool degraded = false;
1227         unsigned i;
1228
1229         mutex_lock(&c->sb_lock);
1230         mi = bch2_sb_get_members(c->disk_sb);
1231
1232         for (i = 0; i < c->disk_sb->nr_devices; i++)
1233                 if (!c->devs[i] &&
1234                     !bch2_is_zero(mi->members[i].uuid.b, sizeof(uuid_le))) {
1235                         degraded = true;
1236                         if (BCH_MEMBER_HAS_METADATA(&mi->members[i]))
1237                                 meta_missing++;
1238                         if (BCH_MEMBER_HAS_DATA(&mi->members[i]))
1239                                 data_missing++;
1240                 }
1241         mutex_unlock(&c->sb_lock);
1242
1243         if (degraded &&
1244             !(flags & BCH_FORCE_IF_DEGRADED))
1245                 return false;
1246
1247         if (meta_missing &&
1248             !(flags & BCH_FORCE_IF_METADATA_DEGRADED))
1249                 return false;
1250
1251         if (meta_missing >= BCH_SB_META_REPLICAS_HAVE(c->disk_sb) &&
1252             !(flags & BCH_FORCE_IF_METADATA_LOST))
1253                 return false;
1254
1255         if (data_missing && !(flags & BCH_FORCE_IF_DATA_DEGRADED))
1256                 return false;
1257
1258         if (data_missing >= BCH_SB_DATA_REPLICAS_HAVE(c->disk_sb) &&
1259             !(flags & BCH_FORCE_IF_DATA_LOST))
1260                 return false;
1261
1262         return true;
1263 }
1264
1265 bool bch2_dev_state_allowed(struct bch_fs *c, struct bch_dev *ca,
1266                             enum bch_member_state new_state, int flags)
1267 {
1268         lockdep_assert_held(&c->state_lock);
1269
1270         if (new_state == BCH_MEMBER_STATE_RW)
1271                 return true;
1272
1273         if (ca->mi.has_data &&
1274             !(flags & BCH_FORCE_IF_DATA_DEGRADED))
1275                 return false;
1276
1277         if (ca->mi.has_data &&
1278             c->sb.data_replicas_have <= 1 &&
1279             !(flags & BCH_FORCE_IF_DATA_LOST))
1280                 return false;
1281
1282         if (ca->mi.has_metadata &&
1283             !(flags & BCH_FORCE_IF_METADATA_DEGRADED))
1284                 return false;
1285
1286         if (ca->mi.has_metadata &&
1287             c->sb.meta_replicas_have <= 1 &&
1288             !(flags & BCH_FORCE_IF_METADATA_LOST))
1289                 return false;
1290
1291         return true;
1292 }
1293
1294 static void __bch2_dev_read_only(struct bch_fs *c, struct bch_dev *ca)
1295 {
1296         bch2_moving_gc_stop(ca);
1297
1298         /*
1299          * This stops new data writes (e.g. to existing open data
1300          * buckets) and then waits for all existing writes to
1301          * complete.
1302          */
1303         bch2_dev_allocator_stop(ca);
1304
1305         bch2_dev_group_remove(&c->journal.devs, ca);
1306 }
1307
1308 static const char *__bch2_dev_read_write(struct bch_fs *c, struct bch_dev *ca)
1309 {
1310         lockdep_assert_held(&c->state_lock);
1311
1312         BUG_ON(ca->mi.state != BCH_MEMBER_STATE_RW);
1313
1314         if (bch2_dev_allocator_start(ca))
1315                 return "error starting allocator thread";
1316
1317         if (bch2_moving_gc_start(ca))
1318                 return "error starting moving GC thread";
1319
1320         if (bch2_tiering_start(c))
1321                 return "error starting tiering thread";
1322
1323         return NULL;
1324 }
1325
1326 int __bch2_dev_set_state(struct bch_fs *c, struct bch_dev *ca,
1327                          enum bch_member_state new_state, int flags)
1328 {
1329         struct bch_sb_field_members *mi;
1330
1331         if (ca->mi.state == new_state)
1332                 return 0;
1333
1334         if (!bch2_dev_state_allowed(c, ca, new_state, flags))
1335                 return -EINVAL;
1336
1337         if (new_state == BCH_MEMBER_STATE_RW) {
1338                 if (__bch2_dev_read_write(c, ca))
1339                         return -ENOMEM;
1340         } else {
1341                 __bch2_dev_read_only(c, ca);
1342         }
1343
1344         bch_notice(ca, "%s", bch2_dev_state[new_state]);
1345
1346         mutex_lock(&c->sb_lock);
1347         mi = bch2_sb_get_members(c->disk_sb);
1348         SET_BCH_MEMBER_STATE(&mi->members[ca->dev_idx], new_state);
1349         bch2_write_super(c);
1350         mutex_unlock(&c->sb_lock);
1351
1352         return 0;
1353 }
1354
1355 int bch2_dev_set_state(struct bch_fs *c, struct bch_dev *ca,
1356                        enum bch_member_state new_state, int flags)
1357 {
1358         int ret;
1359
1360         mutex_lock(&c->state_lock);
1361         ret = __bch2_dev_set_state(c, ca, new_state, flags);
1362         mutex_unlock(&c->state_lock);
1363
1364         return ret;
1365 }
1366
1367 /* Device add/removal: */
1368
1369 int bch2_dev_remove(struct bch_fs *c, struct bch_dev *ca, int flags)
1370 {
1371         struct bch_sb_field_members *mi;
1372         unsigned dev_idx = ca->dev_idx;
1373         int ret = -EINVAL;
1374
1375         mutex_lock(&c->state_lock);
1376
1377         percpu_ref_put(&ca->ref); /* XXX */
1378
1379         if (ca->mi.state == BCH_MEMBER_STATE_RW) {
1380                 bch_err(ca, "Cannot remove RW device");
1381                 goto err;
1382         }
1383
1384         if (!bch2_dev_state_allowed(c, ca, BCH_MEMBER_STATE_FAILED, flags)) {
1385                 bch_err(ca, "Cannot remove without losing data");
1386                 goto err;
1387         }
1388
1389         /*
1390          * XXX: verify that dev_idx is really not in use anymore, anywhere
1391          *
1392          * flag_data_bad() does not check btree pointers
1393          */
1394         ret = bch2_flag_data_bad(ca);
1395         if (ret) {
1396                 bch_err(ca, "Remove failed");
1397                 goto err;
1398         }
1399
1400         if (ca->mi.has_data || ca->mi.has_metadata) {
1401                 bch_err(ca, "Remove failed, still has data");
1402                 goto err;
1403         }
1404
1405         /*
1406          * Ok, really doing the remove:
1407          * Drop device's prio pointer before removing it from superblock:
1408          */
1409         spin_lock(&c->journal.lock);
1410         c->journal.prio_buckets[dev_idx] = 0;
1411         spin_unlock(&c->journal.lock);
1412
1413         bch2_journal_meta(&c->journal);
1414
1415         __bch2_dev_offline(ca);
1416         bch2_dev_stop(ca);
1417         bch2_dev_free(ca);
1418
1419         /*
1420          * Free this device's slot in the bch_member array - all pointers to
1421          * this device must be gone:
1422          */
1423         mutex_lock(&c->sb_lock);
1424         mi = bch2_sb_get_members(c->disk_sb);
1425         memset(&mi->members[dev_idx].uuid, 0, sizeof(mi->members[dev_idx].uuid));
1426
1427         bch2_write_super(c);
1428
1429         mutex_unlock(&c->sb_lock);
1430         mutex_unlock(&c->state_lock);
1431         return 0;
1432 err:
1433         mutex_unlock(&c->state_lock);
1434         return ret;
1435 }
1436
1437 int bch2_dev_add(struct bch_fs *c, const char *path)
1438 {
1439         struct bcache_superblock sb;
1440         const char *err;
1441         struct bch_dev *ca = NULL;
1442         struct bch_sb_field_members *mi, *dev_mi;
1443         struct bch_member saved_mi;
1444         unsigned dev_idx, nr_devices, u64s;
1445         int ret = -EINVAL;
1446
1447         err = bch2_read_super(&sb, bch2_opts_empty(), path);
1448         if (err)
1449                 return -EINVAL;
1450
1451         err = bch2_validate_cache_super(&sb);
1452         if (err)
1453                 return -EINVAL;
1454
1455         err = bch2_dev_may_add(sb.sb, c);
1456         if (err)
1457                 return -EINVAL;
1458
1459         mutex_lock(&c->state_lock);
1460         mutex_lock(&c->sb_lock);
1461
1462         /*
1463          * Preserve the old cache member information (esp. tier)
1464          * before we start bashing the disk stuff.
1465          */
1466         dev_mi = bch2_sb_get_members(sb.sb);
1467         saved_mi = dev_mi->members[sb.sb->dev_idx];
1468         saved_mi.last_mount = cpu_to_le64(ktime_get_seconds());
1469
1470         if (dynamic_fault("bcachefs:add:no_slot"))
1471                 goto no_slot;
1472
1473         mi = bch2_sb_get_members(c->disk_sb);
1474         for (dev_idx = 0; dev_idx < BCH_SB_MEMBERS_MAX; dev_idx++)
1475                 if (dev_idx >= c->sb.nr_devices ||
1476                     bch2_is_zero(mi->members[dev_idx].uuid.b,
1477                                  sizeof(uuid_le)))
1478                         goto have_slot;
1479 no_slot:
1480         err = "no slots available in superblock";
1481         ret = -ENOSPC;
1482         goto err_unlock;
1483
1484 have_slot:
1485         nr_devices = max_t(unsigned, dev_idx + 1, c->sb.nr_devices);
1486         u64s = (sizeof(struct bch_sb_field_members) +
1487                 sizeof(struct bch_member) * nr_devices) / sizeof(u64);
1488         err = "no space in superblock for member info";
1489
1490         mi = bch2_fs_sb_resize_members(c, u64s);
1491         if (!mi)
1492                 goto err_unlock;
1493
1494         dev_mi = bch2_sb_resize_members(&sb, u64s);
1495         if (!dev_mi)
1496                 goto err_unlock;
1497
1498         memcpy(dev_mi, mi, u64s * sizeof(u64));
1499         dev_mi->members[dev_idx] = saved_mi;
1500
1501         sb.sb->uuid             = c->disk_sb->uuid;
1502         sb.sb->dev_idx          = dev_idx;
1503         sb.sb->nr_devices       = nr_devices;
1504
1505         /* commit new member info */
1506         memcpy(mi, dev_mi, u64s * sizeof(u64));
1507         c->disk_sb->nr_devices  = nr_devices;
1508         c->sb.nr_devices        = nr_devices;
1509
1510         if (bch2_dev_alloc(c, dev_idx)) {
1511                 err = "cannot allocate memory";
1512                 ret = -ENOMEM;
1513                 goto err_unlock;
1514         }
1515
1516         if (__bch2_dev_online(c, &sb)) {
1517                 err = "bch2_dev_online() error";
1518                 ret = -ENOMEM;
1519                 goto err_unlock;
1520         }
1521
1522         bch2_write_super(c);
1523         mutex_unlock(&c->sb_lock);
1524
1525         ca = c->devs[dev_idx];
1526         if (ca->mi.state == BCH_MEMBER_STATE_RW) {
1527                 err = "journal alloc failed";
1528                 if (bch2_dev_journal_alloc(ca))
1529                         goto err;
1530
1531                 err = __bch2_dev_read_write(c, ca);
1532                 if (err)
1533                         goto err;
1534         }
1535
1536         mutex_unlock(&c->state_lock);
1537         return 0;
1538 err_unlock:
1539         mutex_unlock(&c->sb_lock);
1540 err:
1541         mutex_unlock(&c->state_lock);
1542         bch2_free_super(&sb);
1543
1544         bch_err(c, "Unable to add device: %s", err);
1545         return ret ?: -EINVAL;
1546 }
1547
1548 int bch2_dev_online(struct bch_fs *c, const char *path)
1549 {
1550         struct bcache_superblock sb = { 0 };
1551         struct bch_dev *ca;
1552         unsigned dev_idx;
1553         const char *err;
1554
1555         mutex_lock(&c->state_lock);
1556
1557         err = bch2_read_super(&sb, bch2_opts_empty(), path);
1558         if (err)
1559                 goto err;
1560
1561         dev_idx = sb.sb->dev_idx;
1562
1563         err = bch2_dev_in_fs(c->disk_sb, sb.sb);
1564         if (err)
1565                 goto err;
1566
1567         mutex_lock(&c->sb_lock);
1568         if (__bch2_dev_online(c, &sb)) {
1569                 err = "__bch2_dev_online() error";
1570                 mutex_unlock(&c->sb_lock);
1571                 goto err;
1572         }
1573         mutex_unlock(&c->sb_lock);
1574
1575         ca = c->devs[dev_idx];
1576         if (ca->mi.state == BCH_MEMBER_STATE_RW) {
1577                 err = __bch2_dev_read_write(c, ca);
1578                 if (err)
1579                         goto err;
1580         }
1581
1582         mutex_unlock(&c->state_lock);
1583         return 0;
1584 err:
1585         mutex_unlock(&c->state_lock);
1586         bch2_free_super(&sb);
1587         bch_err(c, "error bringing %s online: %s", path, err);
1588         return -EINVAL;
1589 }
1590
1591 int bch2_dev_offline(struct bch_fs *c, struct bch_dev *ca, int flags)
1592 {
1593         mutex_lock(&c->state_lock);
1594
1595         if (!bch2_dev_state_allowed(c, ca, BCH_MEMBER_STATE_FAILED, flags)) {
1596                 bch_err(ca, "Cannot offline required disk");
1597                 mutex_unlock(&c->state_lock);
1598                 return -EINVAL;
1599         }
1600
1601         __bch2_dev_read_only(c, ca);
1602         __bch2_dev_offline(ca);
1603
1604         mutex_unlock(&c->state_lock);
1605         return 0;
1606 }
1607
1608 int bch2_dev_evacuate(struct bch_fs *c, struct bch_dev *ca)
1609 {
1610         int ret;
1611
1612         mutex_lock(&c->state_lock);
1613
1614         if (ca->mi.state == BCH_MEMBER_STATE_RW) {
1615                 bch_err(ca, "Cannot migrate data off RW device");
1616                 mutex_unlock(&c->state_lock);
1617                 return -EINVAL;
1618         }
1619
1620         mutex_unlock(&c->state_lock);
1621
1622         ret = bch2_move_data_off_device(ca);
1623         if (ret) {
1624                 bch_err(ca, "Error migrating data: %i", ret);
1625                 return ret;
1626         }
1627
1628         ret = bch2_move_metadata_off_device(ca);
1629         if (ret) {
1630                 bch_err(ca, "Error migrating metadata: %i", ret);
1631                 return ret;
1632         }
1633
1634         if (ca->mi.has_data || ca->mi.has_metadata) {
1635                 bch_err(ca, "Migrate error: data still present");
1636                 return -EINVAL;
1637         }
1638
1639         return 0;
1640 }
1641
1642 /* Filesystem open: */
1643
1644 const char *bch2_fs_open(char * const *devices, unsigned nr_devices,
1645                          struct bch_opts opts, struct bch_fs **ret)
1646 {
1647         const char *err;
1648         struct bch_fs *c = NULL;
1649         struct bcache_superblock *sb;
1650         unsigned i, best_sb = 0;
1651
1652         if (!nr_devices)
1653                 return "need at least one device";
1654
1655         if (!try_module_get(THIS_MODULE))
1656                 return "module unloading";
1657
1658         err = "cannot allocate memory";
1659         sb = kcalloc(nr_devices, sizeof(*sb), GFP_KERNEL);
1660         if (!sb)
1661                 goto err;
1662
1663         for (i = 0; i < nr_devices; i++) {
1664                 err = bch2_read_super(&sb[i], opts, devices[i]);
1665                 if (err)
1666                         goto err;
1667
1668                 err = "attempting to register backing device";
1669                 if (__SB_IS_BDEV(le64_to_cpu(sb[i].sb->version)))
1670                         goto err;
1671
1672                 err = bch2_validate_cache_super(&sb[i]);
1673                 if (err)
1674                         goto err;
1675         }
1676
1677         for (i = 1; i < nr_devices; i++)
1678                 if (le64_to_cpu(sb[i].sb->seq) >
1679                     le64_to_cpu(sb[best_sb].sb->seq))
1680                         best_sb = i;
1681
1682         for (i = 0; i < nr_devices; i++) {
1683                 err = bch2_dev_in_fs(sb[best_sb].sb, sb[i].sb);
1684                 if (err)
1685                         goto err;
1686         }
1687
1688         err = "cannot allocate memory";
1689         c = bch2_fs_alloc(sb[best_sb].sb, opts);
1690         if (!c)
1691                 goto err;
1692
1693         err = "bch2_dev_online() error";
1694         mutex_lock(&c->sb_lock);
1695         for (i = 0; i < nr_devices; i++)
1696                 if (__bch2_dev_online(c, &sb[i])) {
1697                         mutex_unlock(&c->sb_lock);
1698                         goto err;
1699                 }
1700         mutex_unlock(&c->sb_lock);
1701
1702         err = "insufficient devices";
1703         if (!bch2_fs_may_start(c, 0))
1704                 goto err;
1705
1706         if (!c->opts.nostart) {
1707                 err = __bch2_fs_start(c);
1708                 if (err)
1709                         goto err;
1710         }
1711
1712         err = bch2_fs_online(c);
1713         if (err)
1714                 goto err;
1715
1716         if (ret)
1717                 *ret = c;
1718         else
1719                 closure_put(&c->cl);
1720
1721         err = NULL;
1722 out:
1723         kfree(sb);
1724         module_put(THIS_MODULE);
1725         if (err)
1726                 c = NULL;
1727         return err;
1728 err:
1729         if (c)
1730                 bch2_fs_stop(c);
1731
1732         for (i = 0; i < nr_devices; i++)
1733                 bch2_free_super(&sb[i]);
1734         goto out;
1735 }
1736
1737 static const char *__bch2_fs_open_incremental(struct bcache_superblock *sb,
1738                                               struct bch_opts opts)
1739 {
1740         const char *err;
1741         struct bch_fs *c;
1742         bool allocated_fs = false;
1743
1744         err = bch2_validate_cache_super(sb);
1745         if (err)
1746                 return err;
1747
1748         mutex_lock(&bch_fs_list_lock);
1749         c = __bch2_uuid_to_fs(sb->sb->uuid);
1750         if (c) {
1751                 closure_get(&c->cl);
1752
1753                 err = bch2_dev_in_fs(c->disk_sb, sb->sb);
1754                 if (err)
1755                         goto err;
1756         } else {
1757                 c = bch2_fs_alloc(sb->sb, opts);
1758                 err = "cannot allocate memory";
1759                 if (!c)
1760                         goto err;
1761
1762                 allocated_fs = true;
1763         }
1764
1765         err = "bch2_dev_online() error";
1766
1767         mutex_lock(&c->sb_lock);
1768         if (__bch2_dev_online(c, sb)) {
1769                 mutex_unlock(&c->sb_lock);
1770                 goto err;
1771         }
1772         mutex_unlock(&c->sb_lock);
1773
1774         if (!c->opts.nostart && bch2_fs_may_start(c, 0)) {
1775                 err = __bch2_fs_start(c);
1776                 if (err)
1777                         goto err;
1778         }
1779
1780         err = __bch2_fs_online(c);
1781         if (err)
1782                 goto err;
1783
1784         closure_put(&c->cl);
1785         mutex_unlock(&bch_fs_list_lock);
1786
1787         return NULL;
1788 err:
1789         mutex_unlock(&bch_fs_list_lock);
1790
1791         if (allocated_fs)
1792                 bch2_fs_stop(c);
1793         else if (c)
1794                 closure_put(&c->cl);
1795
1796         return err;
1797 }
1798
1799 const char *bch2_fs_open_incremental(const char *path)
1800 {
1801         struct bcache_superblock sb;
1802         struct bch_opts opts = bch2_opts_empty();
1803         const char *err;
1804
1805         err = bch2_read_super(&sb, opts, path);
1806         if (err)
1807                 return err;
1808
1809         if (!__SB_IS_BDEV(le64_to_cpu(sb.sb->version)))
1810                 err = __bch2_fs_open_incremental(&sb, opts);
1811         else
1812                 err = "not a bcachefs superblock";
1813
1814         bch2_free_super(&sb);
1815
1816         return err;
1817 }
1818
1819 /* Global interfaces/init */
1820
1821 static void bcachefs_exit(void)
1822 {
1823         bch2_debug_exit();
1824         bch2_vfs_exit();
1825         bch2_chardev_exit();
1826         if (bcachefs_kset)
1827                 kset_unregister(bcachefs_kset);
1828 }
1829
1830 static int __init bcachefs_init(void)
1831 {
1832         bch2_bkey_pack_test();
1833
1834         if (!(bcachefs_kset = kset_create_and_add("bcachefs", NULL, fs_kobj)) ||
1835             bch2_chardev_init() ||
1836             bch2_vfs_init() ||
1837             bch2_debug_init())
1838                 goto err;
1839
1840         return 0;
1841 err:
1842         bcachefs_exit();
1843         return -ENOMEM;
1844 }
1845
1846 #define BCH_DEBUG_PARAM(name, description)                      \
1847         bool bch2_##name;                                       \
1848         module_param_named(name, bch2_##name, bool, 0644);      \
1849         MODULE_PARM_DESC(name, description);
1850 BCH_DEBUG_PARAMS()
1851 #undef BCH_DEBUG_PARAM
1852
1853 module_exit(bcachefs_exit);
1854 module_init(bcachefs_init);