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