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