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