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