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