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