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