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