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