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