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