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