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