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