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