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