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