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