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