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