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