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