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