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