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