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