]> git.sesse.net Git - bcachefs-tools-debian/blob - libbcachefs/fs.c
Update bcachefs sources to c9b4a210f9 fixup! bcachefs: Fixes for going RO
[bcachefs-tools-debian] / libbcachefs / fs.c
1 // SPDX-License-Identifier: GPL-2.0
2 #ifndef NO_BCACHEFS_FS
3
4 #include "bcachefs.h"
5 #include "acl.h"
6 #include "bkey_on_stack.h"
7 #include "btree_update.h"
8 #include "buckets.h"
9 #include "chardev.h"
10 #include "dirent.h"
11 #include "extents.h"
12 #include "fs.h"
13 #include "fs-common.h"
14 #include "fs-io.h"
15 #include "fs-ioctl.h"
16 #include "fsck.h"
17 #include "inode.h"
18 #include "io.h"
19 #include "journal.h"
20 #include "keylist.h"
21 #include "quota.h"
22 #include "super.h"
23 #include "xattr.h"
24
25 #include <linux/aio.h>
26 #include <linux/backing-dev.h>
27 #include <linux/exportfs.h>
28 #include <linux/module.h>
29 #include <linux/posix_acl.h>
30 #include <linux/random.h>
31 #include <linux/statfs.h>
32 #include <linux/xattr.h>
33
34 static struct kmem_cache *bch2_inode_cache;
35
36 static void bch2_vfs_inode_init(struct bch_fs *,
37                                 struct bch_inode_info *,
38                                 struct bch_inode_unpacked *);
39
40 static void journal_seq_copy(struct bch_inode_info *dst,
41                              u64 journal_seq)
42 {
43         u64 old, v = READ_ONCE(dst->ei_journal_seq);
44
45         do {
46                 old = v;
47
48                 if (old >= journal_seq)
49                         break;
50         } while ((v = cmpxchg(&dst->ei_journal_seq, old, journal_seq)) != old);
51 }
52
53 static void __pagecache_lock_put(struct pagecache_lock *lock, long i)
54 {
55         BUG_ON(atomic_long_read(&lock->v) == 0);
56
57         if (atomic_long_sub_return_release(i, &lock->v) == 0)
58                 wake_up_all(&lock->wait);
59 }
60
61 static bool __pagecache_lock_tryget(struct pagecache_lock *lock, long i)
62 {
63         long v = atomic_long_read(&lock->v), old;
64
65         do {
66                 old = v;
67
68                 if (i > 0 ? v < 0 : v > 0)
69                         return false;
70         } while ((v = atomic_long_cmpxchg_acquire(&lock->v,
71                                         old, old + i)) != old);
72         return true;
73 }
74
75 static void __pagecache_lock_get(struct pagecache_lock *lock, long i)
76 {
77         wait_event(lock->wait, __pagecache_lock_tryget(lock, i));
78 }
79
80 void bch2_pagecache_add_put(struct pagecache_lock *lock)
81 {
82         __pagecache_lock_put(lock, 1);
83 }
84
85 void bch2_pagecache_add_get(struct pagecache_lock *lock)
86 {
87         __pagecache_lock_get(lock, 1);
88 }
89
90 void bch2_pagecache_block_put(struct pagecache_lock *lock)
91 {
92         __pagecache_lock_put(lock, -1);
93 }
94
95 void bch2_pagecache_block_get(struct pagecache_lock *lock)
96 {
97         __pagecache_lock_get(lock, -1);
98 }
99
100 void bch2_inode_update_after_write(struct bch_fs *c,
101                                    struct bch_inode_info *inode,
102                                    struct bch_inode_unpacked *bi,
103                                    unsigned fields)
104 {
105         set_nlink(&inode->v, bch2_inode_nlink_get(bi));
106         i_uid_write(&inode->v, bi->bi_uid);
107         i_gid_write(&inode->v, bi->bi_gid);
108         inode->v.i_mode = bi->bi_mode;
109
110         if (fields & ATTR_ATIME)
111                 inode->v.i_atime = bch2_time_to_timespec(c, bi->bi_atime);
112         if (fields & ATTR_MTIME)
113                 inode->v.i_mtime = bch2_time_to_timespec(c, bi->bi_mtime);
114         if (fields & ATTR_CTIME)
115                 inode->v.i_ctime = bch2_time_to_timespec(c, bi->bi_ctime);
116
117         inode->ei_inode         = *bi;
118
119         bch2_inode_flags_to_vfs(inode);
120 }
121
122 int __must_check bch2_write_inode(struct bch_fs *c,
123                                   struct bch_inode_info *inode,
124                                   inode_set_fn set,
125                                   void *p, unsigned fields)
126 {
127         struct btree_trans trans;
128         struct btree_iter *iter;
129         struct bch_inode_unpacked inode_u;
130         int ret;
131
132         bch2_trans_init(&trans, c, 0, 0);
133 retry:
134         bch2_trans_begin(&trans);
135
136         iter = bch2_inode_peek(&trans, &inode_u, inode->v.i_ino,
137                                BTREE_ITER_INTENT);
138         ret   = PTR_ERR_OR_ZERO(iter) ?:
139                 (set ? set(inode, &inode_u, p) : 0) ?:
140                 bch2_inode_write(&trans, iter, &inode_u) ?:
141                 bch2_trans_commit(&trans, NULL,
142                                   &inode->ei_journal_seq,
143                                   BTREE_INSERT_NOUNLOCK|
144                                   BTREE_INSERT_NOFAIL);
145
146         /*
147          * the btree node lock protects inode->ei_inode, not ei_update_lock;
148          * this is important for inode updates via bchfs_write_index_update
149          */
150         if (!ret)
151                 bch2_inode_update_after_write(c, inode, &inode_u, fields);
152
153         bch2_trans_iter_put(&trans, iter);
154
155         if (ret == -EINTR)
156                 goto retry;
157
158         bch2_trans_exit(&trans);
159         return ret < 0 ? ret : 0;
160 }
161
162 int bch2_fs_quota_transfer(struct bch_fs *c,
163                            struct bch_inode_info *inode,
164                            struct bch_qid new_qid,
165                            unsigned qtypes,
166                            enum quota_acct_mode mode)
167 {
168         unsigned i;
169         int ret;
170
171         qtypes &= enabled_qtypes(c);
172
173         for (i = 0; i < QTYP_NR; i++)
174                 if (new_qid.q[i] == inode->ei_qid.q[i])
175                         qtypes &= ~(1U << i);
176
177         if (!qtypes)
178                 return 0;
179
180         mutex_lock(&inode->ei_quota_lock);
181
182         ret = bch2_quota_transfer(c, qtypes, new_qid,
183                                   inode->ei_qid,
184                                   inode->v.i_blocks +
185                                   inode->ei_quota_reserved,
186                                   mode);
187         if (!ret)
188                 for (i = 0; i < QTYP_NR; i++)
189                         if (qtypes & (1 << i))
190                                 inode->ei_qid.q[i] = new_qid.q[i];
191
192         mutex_unlock(&inode->ei_quota_lock);
193
194         return ret;
195 }
196
197 struct inode *bch2_vfs_inode_get(struct bch_fs *c, u64 inum)
198 {
199         struct bch_inode_unpacked inode_u;
200         struct bch_inode_info *inode;
201         int ret;
202
203         inode = to_bch_ei(iget_locked(c->vfs_sb, inum));
204         if (unlikely(!inode))
205                 return ERR_PTR(-ENOMEM);
206         if (!(inode->v.i_state & I_NEW))
207                 return &inode->v;
208
209         ret = bch2_inode_find_by_inum(c, inum, &inode_u);
210         if (ret) {
211                 iget_failed(&inode->v);
212                 return ERR_PTR(ret);
213         }
214
215         bch2_vfs_inode_init(c, inode, &inode_u);
216
217         inode->ei_journal_seq = bch2_inode_journal_seq(&c->journal, inum);
218
219         unlock_new_inode(&inode->v);
220
221         return &inode->v;
222 }
223
224 static struct bch_inode_info *
225 __bch2_create(struct bch_inode_info *dir, struct dentry *dentry,
226               umode_t mode, dev_t rdev, bool tmpfile)
227 {
228         struct bch_fs *c = dir->v.i_sb->s_fs_info;
229         struct user_namespace *ns = dir->v.i_sb->s_user_ns;
230         struct btree_trans trans;
231         struct bch_inode_unpacked dir_u;
232         struct bch_inode_info *inode, *old;
233         struct bch_inode_unpacked inode_u;
234         struct posix_acl *default_acl = NULL, *acl = NULL;
235         u64 journal_seq = 0;
236         int ret;
237
238         /*
239          * preallocate acls + vfs inode before btree transaction, so that
240          * nothing can fail after the transaction succeeds:
241          */
242 #ifdef CONFIG_BCACHEFS_POSIX_ACL
243         ret = posix_acl_create(&dir->v, &mode, &default_acl, &acl);
244         if (ret)
245                 return ERR_PTR(ret);
246 #endif
247         inode = to_bch_ei(new_inode(c->vfs_sb));
248         if (unlikely(!inode)) {
249                 inode = ERR_PTR(-ENOMEM);
250                 goto err;
251         }
252
253         bch2_inode_init_early(c, &inode_u);
254
255         if (!tmpfile)
256                 mutex_lock(&dir->ei_update_lock);
257
258         bch2_trans_init(&trans, c, 8, 1024);
259 retry:
260         bch2_trans_begin(&trans);
261
262         ret   = bch2_create_trans(&trans, dir->v.i_ino, &dir_u, &inode_u,
263                                   !tmpfile ? &dentry->d_name : NULL,
264                                   from_kuid(ns, current_fsuid()),
265                                   from_kgid(ns, current_fsgid()),
266                                   mode, rdev,
267                                   default_acl, acl) ?:
268                 bch2_quota_acct(c, bch_qid(&inode_u), Q_INO, 1,
269                                 KEY_TYPE_QUOTA_PREALLOC);
270         if (unlikely(ret))
271                 goto err_before_quota;
272
273         ret   = bch2_trans_commit(&trans, NULL, &journal_seq,
274                                   BTREE_INSERT_NOUNLOCK);
275         if (unlikely(ret)) {
276                 bch2_quota_acct(c, bch_qid(&inode_u), Q_INO, -1,
277                                 KEY_TYPE_QUOTA_WARN);
278 err_before_quota:
279                 if (ret == -EINTR)
280                         goto retry;
281                 goto err_trans;
282         }
283
284         if (!tmpfile) {
285                 bch2_inode_update_after_write(c, dir, &dir_u,
286                                               ATTR_MTIME|ATTR_CTIME);
287                 journal_seq_copy(dir, journal_seq);
288                 mutex_unlock(&dir->ei_update_lock);
289         }
290
291         bch2_vfs_inode_init(c, inode, &inode_u);
292         journal_seq_copy(inode, journal_seq);
293
294         set_cached_acl(&inode->v, ACL_TYPE_ACCESS, acl);
295         set_cached_acl(&inode->v, ACL_TYPE_DEFAULT, default_acl);
296
297         /*
298          * we must insert the new inode into the inode cache before calling
299          * bch2_trans_exit() and dropping locks, else we could race with another
300          * thread pulling the inode in and modifying it:
301          */
302
303         old = to_bch_ei(insert_inode_locked2(&inode->v));
304         if (unlikely(old)) {
305                 /*
306                  * We raced, another process pulled the new inode into cache
307                  * before us:
308                  */
309                 journal_seq_copy(old, journal_seq);
310                 make_bad_inode(&inode->v);
311                 iput(&inode->v);
312
313                 inode = old;
314         } else {
315                 /*
316                  * we really don't want insert_inode_locked2() to be setting
317                  * I_NEW...
318                  */
319                 unlock_new_inode(&inode->v);
320         }
321
322         bch2_trans_exit(&trans);
323 err:
324         posix_acl_release(default_acl);
325         posix_acl_release(acl);
326         return inode;
327 err_trans:
328         if (!tmpfile)
329                 mutex_unlock(&dir->ei_update_lock);
330
331         bch2_trans_exit(&trans);
332         make_bad_inode(&inode->v);
333         iput(&inode->v);
334         inode = ERR_PTR(ret);
335         goto err;
336 }
337
338 /* methods */
339
340 static struct dentry *bch2_lookup(struct inode *vdir, struct dentry *dentry,
341                                   unsigned int flags)
342 {
343         struct bch_fs *c = vdir->i_sb->s_fs_info;
344         struct bch_inode_info *dir = to_bch_ei(vdir);
345         struct inode *vinode = NULL;
346         u64 inum;
347
348         inum = bch2_dirent_lookup(c, dir->v.i_ino,
349                                   &dir->ei_str_hash,
350                                   &dentry->d_name);
351
352         if (inum)
353                 vinode = bch2_vfs_inode_get(c, inum);
354
355         return d_splice_alias(vinode, dentry);
356 }
357
358 static int bch2_mknod(struct inode *vdir, struct dentry *dentry,
359                       umode_t mode, dev_t rdev)
360 {
361         struct bch_inode_info *inode =
362                 __bch2_create(to_bch_ei(vdir), dentry, mode, rdev, false);
363
364         if (IS_ERR(inode))
365                 return PTR_ERR(inode);
366
367         d_instantiate(dentry, &inode->v);
368         return 0;
369 }
370
371 static int bch2_create(struct inode *vdir, struct dentry *dentry,
372                        umode_t mode, bool excl)
373 {
374         return bch2_mknod(vdir, dentry, mode|S_IFREG, 0);
375 }
376
377 static int __bch2_link(struct bch_fs *c,
378                        struct bch_inode_info *inode,
379                        struct bch_inode_info *dir,
380                        struct dentry *dentry)
381 {
382         struct btree_trans trans;
383         struct bch_inode_unpacked dir_u, inode_u;
384         int ret;
385
386         mutex_lock(&inode->ei_update_lock);
387         bch2_trans_init(&trans, c, 4, 1024);
388
389         do {
390                 bch2_trans_begin(&trans);
391                 ret   = bch2_link_trans(&trans,
392                                         dir->v.i_ino,
393                                         inode->v.i_ino, &dir_u, &inode_u,
394                                         &dentry->d_name) ?:
395                         bch2_trans_commit(&trans, NULL,
396                                         &inode->ei_journal_seq,
397                                         BTREE_INSERT_NOUNLOCK);
398         } while (ret == -EINTR);
399
400         if (likely(!ret)) {
401                 BUG_ON(inode_u.bi_inum != inode->v.i_ino);
402
403                 journal_seq_copy(inode, dir->ei_journal_seq);
404                 bch2_inode_update_after_write(c, dir, &dir_u,
405                                               ATTR_MTIME|ATTR_CTIME);
406                 bch2_inode_update_after_write(c, inode, &inode_u, ATTR_CTIME);
407         }
408
409         bch2_trans_exit(&trans);
410         mutex_unlock(&inode->ei_update_lock);
411         return ret;
412 }
413
414 static int bch2_link(struct dentry *old_dentry, struct inode *vdir,
415                      struct dentry *dentry)
416 {
417         struct bch_fs *c = vdir->i_sb->s_fs_info;
418         struct bch_inode_info *dir = to_bch_ei(vdir);
419         struct bch_inode_info *inode = to_bch_ei(old_dentry->d_inode);
420         int ret;
421
422         lockdep_assert_held(&inode->v.i_rwsem);
423
424         ret = __bch2_link(c, inode, dir, dentry);
425         if (unlikely(ret))
426                 return ret;
427
428         ihold(&inode->v);
429         d_instantiate(dentry, &inode->v);
430         return 0;
431 }
432
433 static int bch2_unlink(struct inode *vdir, struct dentry *dentry)
434 {
435         struct bch_fs *c = vdir->i_sb->s_fs_info;
436         struct bch_inode_info *dir = to_bch_ei(vdir);
437         struct bch_inode_info *inode = to_bch_ei(dentry->d_inode);
438         struct bch_inode_unpacked dir_u, inode_u;
439         struct btree_trans trans;
440         int ret;
441
442         bch2_lock_inodes(INODE_UPDATE_LOCK, dir, inode);
443         bch2_trans_init(&trans, c, 4, 1024);
444
445         do {
446                 bch2_trans_begin(&trans);
447
448                 ret   = bch2_unlink_trans(&trans,
449                                           dir->v.i_ino, &dir_u,
450                                           &inode_u, &dentry->d_name) ?:
451                         bch2_trans_commit(&trans, NULL,
452                                           &dir->ei_journal_seq,
453                                           BTREE_INSERT_NOUNLOCK|
454                                           BTREE_INSERT_NOFAIL);
455         } while (ret == -EINTR);
456
457         if (likely(!ret)) {
458                 BUG_ON(inode_u.bi_inum != inode->v.i_ino);
459
460                 journal_seq_copy(inode, dir->ei_journal_seq);
461                 bch2_inode_update_after_write(c, dir, &dir_u,
462                                               ATTR_MTIME|ATTR_CTIME);
463                 bch2_inode_update_after_write(c, inode, &inode_u,
464                                               ATTR_MTIME);
465         }
466
467         bch2_trans_exit(&trans);
468         bch2_unlock_inodes(INODE_UPDATE_LOCK, dir, inode);
469
470         return ret;
471 }
472
473 static int bch2_symlink(struct inode *vdir, struct dentry *dentry,
474                         const char *symname)
475 {
476         struct bch_fs *c = vdir->i_sb->s_fs_info;
477         struct bch_inode_info *dir = to_bch_ei(vdir), *inode;
478         int ret;
479
480         inode = __bch2_create(dir, dentry, S_IFLNK|S_IRWXUGO, 0, true);
481         if (unlikely(IS_ERR(inode)))
482                 return PTR_ERR(inode);
483
484         inode_lock(&inode->v);
485         ret = page_symlink(&inode->v, symname, strlen(symname) + 1);
486         inode_unlock(&inode->v);
487
488         if (unlikely(ret))
489                 goto err;
490
491         ret = filemap_write_and_wait_range(inode->v.i_mapping, 0, LLONG_MAX);
492         if (unlikely(ret))
493                 goto err;
494
495         journal_seq_copy(dir, inode->ei_journal_seq);
496
497         ret = __bch2_link(c, inode, dir, dentry);
498         if (unlikely(ret))
499                 goto err;
500
501         d_instantiate(dentry, &inode->v);
502         return 0;
503 err:
504         iput(&inode->v);
505         return ret;
506 }
507
508 static int bch2_mkdir(struct inode *vdir, struct dentry *dentry, umode_t mode)
509 {
510         return bch2_mknod(vdir, dentry, mode|S_IFDIR, 0);
511 }
512
513 static int bch2_rename2(struct inode *src_vdir, struct dentry *src_dentry,
514                         struct inode *dst_vdir, struct dentry *dst_dentry,
515                         unsigned flags)
516 {
517         struct bch_fs *c = src_vdir->i_sb->s_fs_info;
518         struct bch_inode_info *src_dir = to_bch_ei(src_vdir);
519         struct bch_inode_info *dst_dir = to_bch_ei(dst_vdir);
520         struct bch_inode_info *src_inode = to_bch_ei(src_dentry->d_inode);
521         struct bch_inode_info *dst_inode = to_bch_ei(dst_dentry->d_inode);
522         struct bch_inode_unpacked dst_dir_u, src_dir_u;
523         struct bch_inode_unpacked src_inode_u, dst_inode_u;
524         struct btree_trans trans;
525         enum bch_rename_mode mode = flags & RENAME_EXCHANGE
526                 ? BCH_RENAME_EXCHANGE
527                 : dst_dentry->d_inode
528                 ? BCH_RENAME_OVERWRITE : BCH_RENAME;
529         u64 journal_seq = 0;
530         int ret;
531
532         if (flags & ~(RENAME_NOREPLACE|RENAME_EXCHANGE))
533                 return -EINVAL;
534
535         if (mode == BCH_RENAME_OVERWRITE) {
536                 ret = filemap_write_and_wait_range(src_inode->v.i_mapping,
537                                                    0, LLONG_MAX);
538                 if (ret)
539                         return ret;
540         }
541
542         bch2_trans_init(&trans, c, 8, 2048);
543
544         bch2_lock_inodes(INODE_UPDATE_LOCK,
545                          src_dir,
546                          dst_dir,
547                          src_inode,
548                          dst_inode);
549
550         if (inode_attr_changing(dst_dir, src_inode, Inode_opt_project)) {
551                 ret = bch2_fs_quota_transfer(c, src_inode,
552                                              dst_dir->ei_qid,
553                                              1 << QTYP_PRJ,
554                                              KEY_TYPE_QUOTA_PREALLOC);
555                 if (ret)
556                         goto err;
557         }
558
559         if (mode == BCH_RENAME_EXCHANGE &&
560             inode_attr_changing(src_dir, dst_inode, Inode_opt_project)) {
561                 ret = bch2_fs_quota_transfer(c, dst_inode,
562                                              src_dir->ei_qid,
563                                              1 << QTYP_PRJ,
564                                              KEY_TYPE_QUOTA_PREALLOC);
565                 if (ret)
566                         goto err;
567         }
568
569 retry:
570         bch2_trans_begin(&trans);
571         ret   = bch2_rename_trans(&trans,
572                                   src_dir->v.i_ino, &src_dir_u,
573                                   dst_dir->v.i_ino, &dst_dir_u,
574                                   &src_inode_u,
575                                   &dst_inode_u,
576                                   &src_dentry->d_name,
577                                   &dst_dentry->d_name,
578                                   mode) ?:
579                 bch2_trans_commit(&trans, NULL,
580                                   &journal_seq,
581                                   BTREE_INSERT_NOUNLOCK);
582         if (ret == -EINTR)
583                 goto retry;
584         if (unlikely(ret))
585                 goto err;
586
587         BUG_ON(src_inode->v.i_ino != src_inode_u.bi_inum);
588         BUG_ON(dst_inode &&
589                dst_inode->v.i_ino != dst_inode_u.bi_inum);
590
591         bch2_inode_update_after_write(c, src_dir, &src_dir_u,
592                                       ATTR_MTIME|ATTR_CTIME);
593         journal_seq_copy(src_dir, journal_seq);
594
595         if (src_dir != dst_dir) {
596                 bch2_inode_update_after_write(c, dst_dir, &dst_dir_u,
597                                               ATTR_MTIME|ATTR_CTIME);
598                 journal_seq_copy(dst_dir, journal_seq);
599         }
600
601         bch2_inode_update_after_write(c, src_inode, &src_inode_u,
602                                       ATTR_CTIME);
603         journal_seq_copy(src_inode, journal_seq);
604
605         if (dst_inode) {
606                 bch2_inode_update_after_write(c, dst_inode, &dst_inode_u,
607                                               ATTR_CTIME);
608                 journal_seq_copy(dst_inode, journal_seq);
609         }
610 err:
611         bch2_trans_exit(&trans);
612
613         bch2_fs_quota_transfer(c, src_inode,
614                                bch_qid(&src_inode->ei_inode),
615                                1 << QTYP_PRJ,
616                                KEY_TYPE_QUOTA_NOCHECK);
617         if (dst_inode)
618                 bch2_fs_quota_transfer(c, dst_inode,
619                                        bch_qid(&dst_inode->ei_inode),
620                                        1 << QTYP_PRJ,
621                                        KEY_TYPE_QUOTA_NOCHECK);
622
623         bch2_unlock_inodes(INODE_UPDATE_LOCK,
624                            src_dir,
625                            dst_dir,
626                            src_inode,
627                            dst_inode);
628
629         return ret;
630 }
631
632 void bch2_setattr_copy(struct bch_inode_info *inode,
633                        struct bch_inode_unpacked *bi,
634                        struct iattr *attr)
635 {
636         struct bch_fs *c = inode->v.i_sb->s_fs_info;
637         unsigned int ia_valid = attr->ia_valid;
638
639         if (ia_valid & ATTR_UID)
640                 bi->bi_uid = from_kuid(c->vfs_sb->s_user_ns, attr->ia_uid);
641         if (ia_valid & ATTR_GID)
642                 bi->bi_gid = from_kgid(c->vfs_sb->s_user_ns, attr->ia_gid);
643
644         if (ia_valid & ATTR_ATIME)
645                 bi->bi_atime = timespec_to_bch2_time(c, attr->ia_atime);
646         if (ia_valid & ATTR_MTIME)
647                 bi->bi_mtime = timespec_to_bch2_time(c, attr->ia_mtime);
648         if (ia_valid & ATTR_CTIME)
649                 bi->bi_ctime = timespec_to_bch2_time(c, attr->ia_ctime);
650
651         if (ia_valid & ATTR_MODE) {
652                 umode_t mode = attr->ia_mode;
653                 kgid_t gid = ia_valid & ATTR_GID
654                         ? attr->ia_gid
655                         : inode->v.i_gid;
656
657                 if (!in_group_p(gid) &&
658                     !capable_wrt_inode_uidgid(&inode->v, CAP_FSETID))
659                         mode &= ~S_ISGID;
660                 bi->bi_mode = mode;
661         }
662 }
663
664 static int bch2_setattr_nonsize(struct bch_inode_info *inode,
665                                 struct iattr *attr)
666 {
667         struct bch_fs *c = inode->v.i_sb->s_fs_info;
668         struct bch_qid qid;
669         struct btree_trans trans;
670         struct btree_iter *inode_iter;
671         struct bch_inode_unpacked inode_u;
672         struct posix_acl *acl = NULL;
673         int ret;
674
675         mutex_lock(&inode->ei_update_lock);
676
677         qid = inode->ei_qid;
678
679         if (attr->ia_valid & ATTR_UID)
680                 qid.q[QTYP_USR] = from_kuid(&init_user_ns, attr->ia_uid);
681
682         if (attr->ia_valid & ATTR_GID)
683                 qid.q[QTYP_GRP] = from_kgid(&init_user_ns, attr->ia_gid);
684
685         ret = bch2_fs_quota_transfer(c, inode, qid, ~0,
686                                      KEY_TYPE_QUOTA_PREALLOC);
687         if (ret)
688                 goto err;
689
690         bch2_trans_init(&trans, c, 0, 0);
691 retry:
692         bch2_trans_begin(&trans);
693         kfree(acl);
694         acl = NULL;
695
696         inode_iter = bch2_inode_peek(&trans, &inode_u, inode->v.i_ino,
697                                      BTREE_ITER_INTENT);
698         ret = PTR_ERR_OR_ZERO(inode_iter);
699         if (ret)
700                 goto btree_err;
701
702         bch2_setattr_copy(inode, &inode_u, attr);
703
704         if (attr->ia_valid & ATTR_MODE) {
705                 ret = bch2_acl_chmod(&trans, inode, inode_u.bi_mode, &acl);
706                 if (ret)
707                         goto btree_err;
708         }
709
710         ret =   bch2_inode_write(&trans, inode_iter, &inode_u) ?:
711                 bch2_trans_commit(&trans, NULL,
712                                   &inode->ei_journal_seq,
713                                   BTREE_INSERT_NOUNLOCK|
714                                   BTREE_INSERT_NOFAIL);
715 btree_err:
716         if (ret == -EINTR)
717                 goto retry;
718         if (unlikely(ret))
719                 goto err_trans;
720
721         bch2_inode_update_after_write(c, inode, &inode_u, attr->ia_valid);
722
723         if (acl)
724                 set_cached_acl(&inode->v, ACL_TYPE_ACCESS, acl);
725 err_trans:
726         bch2_trans_exit(&trans);
727 err:
728         mutex_unlock(&inode->ei_update_lock);
729
730         return ret;
731 }
732
733 static int bch2_getattr(const struct path *path, struct kstat *stat,
734                         u32 request_mask, unsigned query_flags)
735 {
736         struct bch_inode_info *inode = to_bch_ei(d_inode(path->dentry));
737         struct bch_fs *c = inode->v.i_sb->s_fs_info;
738
739         stat->dev       = inode->v.i_sb->s_dev;
740         stat->ino       = inode->v.i_ino;
741         stat->mode      = inode->v.i_mode;
742         stat->nlink     = inode->v.i_nlink;
743         stat->uid       = inode->v.i_uid;
744         stat->gid       = inode->v.i_gid;
745         stat->rdev      = inode->v.i_rdev;
746         stat->size      = i_size_read(&inode->v);
747         stat->atime     = inode->v.i_atime;
748         stat->mtime     = inode->v.i_mtime;
749         stat->ctime     = inode->v.i_ctime;
750         stat->blksize   = block_bytes(c);
751         stat->blocks    = inode->v.i_blocks;
752
753         if (request_mask & STATX_BTIME) {
754                 stat->result_mask |= STATX_BTIME;
755                 stat->btime = bch2_time_to_timespec(c, inode->ei_inode.bi_otime);
756         }
757
758         if (inode->ei_inode.bi_flags & BCH_INODE_IMMUTABLE)
759                 stat->attributes |= STATX_ATTR_IMMUTABLE;
760         stat->attributes_mask    |= STATX_ATTR_IMMUTABLE;
761
762         if (inode->ei_inode.bi_flags & BCH_INODE_APPEND)
763                 stat->attributes |= STATX_ATTR_APPEND;
764         stat->attributes_mask    |= STATX_ATTR_APPEND;
765
766         if (inode->ei_inode.bi_flags & BCH_INODE_NODUMP)
767                 stat->attributes |= STATX_ATTR_NODUMP;
768         stat->attributes_mask    |= STATX_ATTR_NODUMP;
769
770         return 0;
771 }
772
773 static int bch2_setattr(struct dentry *dentry, struct iattr *iattr)
774 {
775         struct bch_inode_info *inode = to_bch_ei(dentry->d_inode);
776         int ret;
777
778         lockdep_assert_held(&inode->v.i_rwsem);
779
780         ret = setattr_prepare(dentry, iattr);
781         if (ret)
782                 return ret;
783
784         return iattr->ia_valid & ATTR_SIZE
785                 ? bch2_truncate(inode, iattr)
786                 : bch2_setattr_nonsize(inode, iattr);
787 }
788
789 static int bch2_tmpfile(struct inode *vdir, struct dentry *dentry, umode_t mode)
790 {
791         struct bch_inode_info *inode =
792                 __bch2_create(to_bch_ei(vdir), dentry, mode, 0, true);
793
794         if (IS_ERR(inode))
795                 return PTR_ERR(inode);
796
797         d_mark_tmpfile(dentry, &inode->v);
798         d_instantiate(dentry, &inode->v);
799         return 0;
800 }
801
802 static int bch2_fill_extent(struct bch_fs *c,
803                             struct fiemap_extent_info *info,
804                             struct bkey_s_c k, unsigned flags)
805 {
806         if (bkey_extent_is_data(k.k)) {
807                 struct bkey_ptrs_c ptrs = bch2_bkey_ptrs_c(k);
808                 const union bch_extent_entry *entry;
809                 struct extent_ptr_decoded p;
810                 int ret;
811
812                 if (k.k->type == KEY_TYPE_reflink_v)
813                         flags |= FIEMAP_EXTENT_SHARED;
814
815                 bkey_for_each_ptr_decode(k.k, ptrs, p, entry) {
816                         int flags2 = 0;
817                         u64 offset = p.ptr.offset;
818
819                         if (p.crc.compression_type)
820                                 flags2 |= FIEMAP_EXTENT_ENCODED;
821                         else
822                                 offset += p.crc.offset;
823
824                         if ((offset & (c->opts.block_size - 1)) ||
825                             (k.k->size & (c->opts.block_size - 1)))
826                                 flags2 |= FIEMAP_EXTENT_NOT_ALIGNED;
827
828                         ret = fiemap_fill_next_extent(info,
829                                                 bkey_start_offset(k.k) << 9,
830                                                 offset << 9,
831                                                 k.k->size << 9, flags|flags2);
832                         if (ret)
833                                 return ret;
834                 }
835
836                 return 0;
837         } else if (k.k->type == KEY_TYPE_reservation) {
838                 return fiemap_fill_next_extent(info,
839                                                bkey_start_offset(k.k) << 9,
840                                                0, k.k->size << 9,
841                                                flags|
842                                                FIEMAP_EXTENT_DELALLOC|
843                                                FIEMAP_EXTENT_UNWRITTEN);
844         } else {
845                 BUG();
846         }
847 }
848
849 static int bch2_fiemap(struct inode *vinode, struct fiemap_extent_info *info,
850                        u64 start, u64 len)
851 {
852         struct bch_fs *c = vinode->i_sb->s_fs_info;
853         struct bch_inode_info *ei = to_bch_ei(vinode);
854         struct btree_trans trans;
855         struct btree_iter *iter;
856         struct bkey_s_c k;
857         struct bkey_on_stack cur, prev;
858         struct bpos end = POS(ei->v.i_ino, (start + len) >> 9);
859         unsigned offset_into_extent, sectors;
860         bool have_extent = false;
861         int ret = 0;
862
863         if (start + len < start)
864                 return -EINVAL;
865
866         bkey_on_stack_init(&cur);
867         bkey_on_stack_init(&prev);
868         bch2_trans_init(&trans, c, 0, 0);
869
870         iter = bch2_trans_get_iter(&trans, BTREE_ID_EXTENTS,
871                                    POS(ei->v.i_ino, start >> 9), 0);
872 retry:
873         while ((k = bch2_btree_iter_peek(iter)).k &&
874                !(ret = bkey_err(k)) &&
875                bkey_cmp(iter->pos, end) < 0) {
876                 if (!bkey_extent_is_data(k.k) &&
877                     k.k->type != KEY_TYPE_reservation) {
878                         bch2_btree_iter_next(iter);
879                         continue;
880                 }
881
882                 bkey_on_stack_realloc(&cur, c, k.k->u64s);
883                 bkey_on_stack_realloc(&prev, c, k.k->u64s);
884                 bkey_reassemble(cur.k, k);
885                 k = bkey_i_to_s_c(cur.k);
886
887                 offset_into_extent      = iter->pos.offset -
888                         bkey_start_offset(k.k);
889                 sectors                 = k.k->size - offset_into_extent;
890
891                 ret = bch2_read_indirect_extent(&trans,
892                                         &offset_into_extent, &cur);
893                 if (ret)
894                         break;
895
896                 sectors = min(sectors, k.k->size - offset_into_extent);
897
898                 if (offset_into_extent)
899                         bch2_cut_front(POS(k.k->p.inode,
900                                            bkey_start_offset(k.k) +
901                                            offset_into_extent),
902                                        cur.k);
903                 bch2_key_resize(&cur.k->k, sectors);
904                 cur.k->k.p = iter->pos;
905                 cur.k->k.p.offset += cur.k->k.size;
906
907                 if (have_extent) {
908                         ret = bch2_fill_extent(c, info,
909                                         bkey_i_to_s_c(prev.k), 0);
910                         if (ret)
911                                 break;
912                 }
913
914                 bkey_copy(prev.k, cur.k);
915                 have_extent = true;
916
917                 if (k.k->type == KEY_TYPE_reflink_v)
918                         bch2_btree_iter_set_pos(iter, k.k->p);
919                 else
920                         bch2_btree_iter_next(iter);
921         }
922
923         if (ret == -EINTR)
924                 goto retry;
925
926         if (!ret && have_extent)
927                 ret = bch2_fill_extent(c, info, bkey_i_to_s_c(prev.k),
928                                        FIEMAP_EXTENT_LAST);
929
930         ret = bch2_trans_exit(&trans) ?: ret;
931         bkey_on_stack_exit(&cur, c);
932         bkey_on_stack_exit(&prev, c);
933         return ret < 0 ? ret : 0;
934 }
935
936 static const struct vm_operations_struct bch_vm_ops = {
937         .fault          = bch2_page_fault,
938         .map_pages      = filemap_map_pages,
939         .page_mkwrite   = bch2_page_mkwrite,
940 };
941
942 static int bch2_mmap(struct file *file, struct vm_area_struct *vma)
943 {
944         file_accessed(file);
945
946         vma->vm_ops = &bch_vm_ops;
947         return 0;
948 }
949
950 /* Directories: */
951
952 static loff_t bch2_dir_llseek(struct file *file, loff_t offset, int whence)
953 {
954         return generic_file_llseek_size(file, offset, whence,
955                                         S64_MAX, S64_MAX);
956 }
957
958 static int bch2_vfs_readdir(struct file *file, struct dir_context *ctx)
959 {
960         struct bch_inode_info *inode = file_bch_inode(file);
961         struct bch_fs *c = inode->v.i_sb->s_fs_info;
962
963         if (!dir_emit_dots(file, ctx))
964                 return 0;
965
966         return bch2_readdir(c, inode->v.i_ino, ctx);
967 }
968
969 static const struct file_operations bch_file_operations = {
970         .llseek         = bch2_llseek,
971         .read_iter      = bch2_read_iter,
972         .write_iter     = bch2_write_iter,
973         .mmap           = bch2_mmap,
974         .open           = generic_file_open,
975         .fsync          = bch2_fsync,
976         .splice_read    = generic_file_splice_read,
977         /*
978          * Broken, on v5.3:
979         .splice_write   = iter_file_splice_write,
980         */
981         .fallocate      = bch2_fallocate_dispatch,
982         .unlocked_ioctl = bch2_fs_file_ioctl,
983 #ifdef CONFIG_COMPAT
984         .compat_ioctl   = bch2_compat_fs_ioctl,
985 #endif
986         .remap_file_range = bch2_remap_file_range,
987 };
988
989 static const struct inode_operations bch_file_inode_operations = {
990         .getattr        = bch2_getattr,
991         .setattr        = bch2_setattr,
992         .fiemap         = bch2_fiemap,
993         .listxattr      = bch2_xattr_list,
994 #ifdef CONFIG_BCACHEFS_POSIX_ACL
995         .get_acl        = bch2_get_acl,
996         .set_acl        = bch2_set_acl,
997 #endif
998 };
999
1000 static const struct inode_operations bch_dir_inode_operations = {
1001         .lookup         = bch2_lookup,
1002         .create         = bch2_create,
1003         .link           = bch2_link,
1004         .unlink         = bch2_unlink,
1005         .symlink        = bch2_symlink,
1006         .mkdir          = bch2_mkdir,
1007         .rmdir          = bch2_unlink,
1008         .mknod          = bch2_mknod,
1009         .rename         = bch2_rename2,
1010         .getattr        = bch2_getattr,
1011         .setattr        = bch2_setattr,
1012         .tmpfile        = bch2_tmpfile,
1013         .listxattr      = bch2_xattr_list,
1014 #ifdef CONFIG_BCACHEFS_POSIX_ACL
1015         .get_acl        = bch2_get_acl,
1016         .set_acl        = bch2_set_acl,
1017 #endif
1018 };
1019
1020 static const struct file_operations bch_dir_file_operations = {
1021         .llseek         = bch2_dir_llseek,
1022         .read           = generic_read_dir,
1023         .iterate_shared = bch2_vfs_readdir,
1024         .fsync          = bch2_fsync,
1025         .unlocked_ioctl = bch2_fs_file_ioctl,
1026 #ifdef CONFIG_COMPAT
1027         .compat_ioctl   = bch2_compat_fs_ioctl,
1028 #endif
1029 };
1030
1031 static const struct inode_operations bch_symlink_inode_operations = {
1032         .get_link       = page_get_link,
1033         .getattr        = bch2_getattr,
1034         .setattr        = bch2_setattr,
1035         .listxattr      = bch2_xattr_list,
1036 #ifdef CONFIG_BCACHEFS_POSIX_ACL
1037         .get_acl        = bch2_get_acl,
1038         .set_acl        = bch2_set_acl,
1039 #endif
1040 };
1041
1042 static const struct inode_operations bch_special_inode_operations = {
1043         .getattr        = bch2_getattr,
1044         .setattr        = bch2_setattr,
1045         .listxattr      = bch2_xattr_list,
1046 #ifdef CONFIG_BCACHEFS_POSIX_ACL
1047         .get_acl        = bch2_get_acl,
1048         .set_acl        = bch2_set_acl,
1049 #endif
1050 };
1051
1052 static const struct address_space_operations bch_address_space_operations = {
1053         .writepage      = bch2_writepage,
1054         .readpage       = bch2_readpage,
1055         .writepages     = bch2_writepages,
1056         .readpages      = bch2_readpages,
1057         .set_page_dirty = __set_page_dirty_nobuffers,
1058         .write_begin    = bch2_write_begin,
1059         .write_end      = bch2_write_end,
1060         .invalidatepage = bch2_invalidatepage,
1061         .releasepage    = bch2_releasepage,
1062         .direct_IO      = noop_direct_IO,
1063 #ifdef CONFIG_MIGRATION
1064         .migratepage    = bch2_migrate_page,
1065 #endif
1066         .error_remove_page = generic_error_remove_page,
1067 };
1068
1069 static struct inode *bch2_nfs_get_inode(struct super_block *sb,
1070                 u64 ino, u32 generation)
1071 {
1072         struct bch_fs *c = sb->s_fs_info;
1073         struct inode *vinode;
1074
1075         if (ino < BCACHEFS_ROOT_INO)
1076                 return ERR_PTR(-ESTALE);
1077
1078         vinode = bch2_vfs_inode_get(c, ino);
1079         if (IS_ERR(vinode))
1080                 return ERR_CAST(vinode);
1081         if (generation && vinode->i_generation != generation) {
1082                 /* we didn't find the right inode.. */
1083                 iput(vinode);
1084                 return ERR_PTR(-ESTALE);
1085         }
1086         return vinode;
1087 }
1088
1089 static struct dentry *bch2_fh_to_dentry(struct super_block *sb, struct fid *fid,
1090                 int fh_len, int fh_type)
1091 {
1092         return generic_fh_to_dentry(sb, fid, fh_len, fh_type,
1093                                     bch2_nfs_get_inode);
1094 }
1095
1096 static struct dentry *bch2_fh_to_parent(struct super_block *sb, struct fid *fid,
1097                 int fh_len, int fh_type)
1098 {
1099         return generic_fh_to_parent(sb, fid, fh_len, fh_type,
1100                                     bch2_nfs_get_inode);
1101 }
1102
1103 static const struct export_operations bch_export_ops = {
1104         .fh_to_dentry   = bch2_fh_to_dentry,
1105         .fh_to_parent   = bch2_fh_to_parent,
1106         //.get_parent   = bch2_get_parent,
1107 };
1108
1109 static void bch2_vfs_inode_init(struct bch_fs *c,
1110                                 struct bch_inode_info *inode,
1111                                 struct bch_inode_unpacked *bi)
1112 {
1113         bch2_inode_update_after_write(c, inode, bi, ~0);
1114
1115         inode->v.i_blocks       = bi->bi_sectors;
1116         inode->v.i_ino          = bi->bi_inum;
1117         inode->v.i_rdev         = bi->bi_dev;
1118         inode->v.i_generation   = bi->bi_generation;
1119         inode->v.i_size         = bi->bi_size;
1120
1121         inode->ei_journal_seq   = 0;
1122         inode->ei_quota_reserved = 0;
1123         inode->ei_str_hash      = bch2_hash_info_init(c, bi);
1124         inode->ei_qid           = bch_qid(bi);
1125
1126         inode->v.i_mapping->a_ops = &bch_address_space_operations;
1127
1128         switch (inode->v.i_mode & S_IFMT) {
1129         case S_IFREG:
1130                 inode->v.i_op   = &bch_file_inode_operations;
1131                 inode->v.i_fop  = &bch_file_operations;
1132                 break;
1133         case S_IFDIR:
1134                 inode->v.i_op   = &bch_dir_inode_operations;
1135                 inode->v.i_fop  = &bch_dir_file_operations;
1136                 break;
1137         case S_IFLNK:
1138                 inode_nohighmem(&inode->v);
1139                 inode->v.i_op   = &bch_symlink_inode_operations;
1140                 break;
1141         default:
1142                 init_special_inode(&inode->v, inode->v.i_mode, inode->v.i_rdev);
1143                 inode->v.i_op   = &bch_special_inode_operations;
1144                 break;
1145         }
1146 }
1147
1148 static struct inode *bch2_alloc_inode(struct super_block *sb)
1149 {
1150         struct bch_inode_info *inode;
1151
1152         inode = kmem_cache_alloc(bch2_inode_cache, GFP_NOFS);
1153         if (!inode)
1154                 return NULL;
1155
1156         inode_init_once(&inode->v);
1157         mutex_init(&inode->ei_update_lock);
1158         pagecache_lock_init(&inode->ei_pagecache_lock);
1159         mutex_init(&inode->ei_quota_lock);
1160         inode->ei_journal_seq = 0;
1161
1162         return &inode->v;
1163 }
1164
1165 static void bch2_i_callback(struct rcu_head *head)
1166 {
1167         struct inode *vinode = container_of(head, struct inode, i_rcu);
1168         struct bch_inode_info *inode = to_bch_ei(vinode);
1169
1170         kmem_cache_free(bch2_inode_cache, inode);
1171 }
1172
1173 static void bch2_destroy_inode(struct inode *vinode)
1174 {
1175         call_rcu(&vinode->i_rcu, bch2_i_callback);
1176 }
1177
1178 static int inode_update_times_fn(struct bch_inode_info *inode,
1179                                  struct bch_inode_unpacked *bi,
1180                                  void *p)
1181 {
1182         struct bch_fs *c = inode->v.i_sb->s_fs_info;
1183
1184         bi->bi_atime    = timespec_to_bch2_time(c, inode->v.i_atime);
1185         bi->bi_mtime    = timespec_to_bch2_time(c, inode->v.i_mtime);
1186         bi->bi_ctime    = timespec_to_bch2_time(c, inode->v.i_ctime);
1187
1188         return 0;
1189 }
1190
1191 static int bch2_vfs_write_inode(struct inode *vinode,
1192                                 struct writeback_control *wbc)
1193 {
1194         struct bch_fs *c = vinode->i_sb->s_fs_info;
1195         struct bch_inode_info *inode = to_bch_ei(vinode);
1196         int ret;
1197
1198         mutex_lock(&inode->ei_update_lock);
1199         ret = bch2_write_inode(c, inode, inode_update_times_fn, NULL,
1200                                ATTR_ATIME|ATTR_MTIME|ATTR_CTIME);
1201         mutex_unlock(&inode->ei_update_lock);
1202
1203         return ret;
1204 }
1205
1206 static void bch2_evict_inode(struct inode *vinode)
1207 {
1208         struct bch_fs *c = vinode->i_sb->s_fs_info;
1209         struct bch_inode_info *inode = to_bch_ei(vinode);
1210
1211         truncate_inode_pages_final(&inode->v.i_data);
1212
1213         clear_inode(&inode->v);
1214
1215         BUG_ON(!is_bad_inode(&inode->v) && inode->ei_quota_reserved);
1216
1217         if (!inode->v.i_nlink && !is_bad_inode(&inode->v)) {
1218                 bch2_quota_acct(c, inode->ei_qid, Q_SPC, -((s64) inode->v.i_blocks),
1219                                 KEY_TYPE_QUOTA_WARN);
1220                 bch2_quota_acct(c, inode->ei_qid, Q_INO, -1,
1221                                 KEY_TYPE_QUOTA_WARN);
1222                 bch2_inode_rm(c, inode->v.i_ino);
1223         }
1224 }
1225
1226 static int bch2_statfs(struct dentry *dentry, struct kstatfs *buf)
1227 {
1228         struct super_block *sb = dentry->d_sb;
1229         struct bch_fs *c = sb->s_fs_info;
1230         struct bch_fs_usage_short usage = bch2_fs_usage_read_short(c);
1231         unsigned shift = sb->s_blocksize_bits - 9;
1232         u64 fsid;
1233
1234         buf->f_type     = BCACHEFS_STATFS_MAGIC;
1235         buf->f_bsize    = sb->s_blocksize;
1236         buf->f_blocks   = usage.capacity >> shift;
1237         buf->f_bfree    = (usage.capacity - usage.used) >> shift;
1238         buf->f_bavail   = buf->f_bfree;
1239         buf->f_files    = usage.nr_inodes;
1240         buf->f_ffree    = U64_MAX;
1241
1242         fsid = le64_to_cpup((void *) c->sb.user_uuid.b) ^
1243                le64_to_cpup((void *) c->sb.user_uuid.b + sizeof(u64));
1244         buf->f_fsid.val[0] = fsid & 0xFFFFFFFFUL;
1245         buf->f_fsid.val[1] = (fsid >> 32) & 0xFFFFFFFFUL;
1246         buf->f_namelen  = BCH_NAME_MAX;
1247
1248         return 0;
1249 }
1250
1251 static int bch2_sync_fs(struct super_block *sb, int wait)
1252 {
1253         struct bch_fs *c = sb->s_fs_info;
1254
1255         if (c->opts.journal_flush_disabled)
1256                 return 0;
1257
1258         if (!wait) {
1259                 bch2_journal_flush_async(&c->journal, NULL);
1260                 return 0;
1261         }
1262
1263         return bch2_journal_flush(&c->journal);
1264 }
1265
1266 static struct bch_fs *bch2_path_to_fs(const char *dev)
1267 {
1268         struct bch_fs *c;
1269         struct block_device *bdev = lookup_bdev(dev);
1270
1271         if (IS_ERR(bdev))
1272                 return ERR_CAST(bdev);
1273
1274         c = bch2_bdev_to_fs(bdev);
1275         bdput(bdev);
1276         return c ?: ERR_PTR(-ENOENT);
1277 }
1278
1279 static struct bch_fs *__bch2_open_as_blockdevs(const char *dev_name, char * const *devs,
1280                                                unsigned nr_devs, struct bch_opts opts)
1281 {
1282         struct bch_fs *c, *c1, *c2;
1283         size_t i;
1284
1285         if (!nr_devs)
1286                 return ERR_PTR(-EINVAL);
1287
1288         c = bch2_fs_open(devs, nr_devs, opts);
1289
1290         if (IS_ERR(c) && PTR_ERR(c) == -EBUSY) {
1291                 /*
1292                  * Already open?
1293                  * Look up each block device, make sure they all belong to a
1294                  * filesystem and they all belong to the _same_ filesystem
1295                  */
1296
1297                 c1 = bch2_path_to_fs(devs[0]);
1298                 if (IS_ERR(c1))
1299                         return c;
1300
1301                 for (i = 1; i < nr_devs; i++) {
1302                         c2 = bch2_path_to_fs(devs[i]);
1303                         if (!IS_ERR(c2))
1304                                 closure_put(&c2->cl);
1305
1306                         if (c1 != c2) {
1307                                 closure_put(&c1->cl);
1308                                 return c;
1309                         }
1310                 }
1311
1312                 c = c1;
1313         }
1314
1315         if (IS_ERR(c))
1316                 return c;
1317
1318         mutex_lock(&c->state_lock);
1319
1320         if (!test_bit(BCH_FS_STARTED, &c->flags)) {
1321                 mutex_unlock(&c->state_lock);
1322                 closure_put(&c->cl);
1323                 pr_err("err mounting %s: incomplete filesystem", dev_name);
1324                 return ERR_PTR(-EINVAL);
1325         }
1326
1327         mutex_unlock(&c->state_lock);
1328
1329         set_bit(BCH_FS_BDEV_MOUNTED, &c->flags);
1330         return c;
1331 }
1332
1333 static struct bch_fs *bch2_open_as_blockdevs(const char *_dev_name,
1334                                              struct bch_opts opts)
1335 {
1336         char *dev_name = NULL, **devs = NULL, *s;
1337         struct bch_fs *c = ERR_PTR(-ENOMEM);
1338         size_t i, nr_devs = 0;
1339
1340         dev_name = kstrdup(_dev_name, GFP_KERNEL);
1341         if (!dev_name)
1342                 goto err;
1343
1344         for (s = dev_name; s; s = strchr(s + 1, ':'))
1345                 nr_devs++;
1346
1347         devs = kcalloc(nr_devs, sizeof(const char *), GFP_KERNEL);
1348         if (!devs)
1349                 goto err;
1350
1351         for (i = 0, s = dev_name;
1352              s;
1353              (s = strchr(s, ':')) && (*s++ = '\0'))
1354                 devs[i++] = s;
1355
1356         c = __bch2_open_as_blockdevs(_dev_name, devs, nr_devs, opts);
1357 err:
1358         kfree(devs);
1359         kfree(dev_name);
1360         return c;
1361 }
1362
1363 static int bch2_remount(struct super_block *sb, int *flags, char *data)
1364 {
1365         struct bch_fs *c = sb->s_fs_info;
1366         struct bch_opts opts = bch2_opts_empty();
1367         int ret;
1368
1369         opt_set(opts, read_only, (*flags & SB_RDONLY) != 0);
1370
1371         ret = bch2_parse_mount_opts(&opts, data);
1372         if (ret)
1373                 return ret;
1374
1375         if (opts.read_only != c->opts.read_only) {
1376                 mutex_lock(&c->state_lock);
1377
1378                 if (opts.read_only) {
1379                         bch2_fs_read_only(c);
1380
1381                         sb->s_flags |= SB_RDONLY;
1382                 } else {
1383                         ret = bch2_fs_read_write(c);
1384                         if (ret) {
1385                                 bch_err(c, "error going rw: %i", ret);
1386                                 mutex_unlock(&c->state_lock);
1387                                 return -EINVAL;
1388                         }
1389
1390                         sb->s_flags &= ~SB_RDONLY;
1391                 }
1392
1393                 c->opts.read_only = opts.read_only;
1394
1395                 mutex_unlock(&c->state_lock);
1396         }
1397
1398         if (opts.errors >= 0)
1399                 c->opts.errors = opts.errors;
1400
1401         return ret;
1402 }
1403
1404 static int bch2_show_options(struct seq_file *seq, struct dentry *root)
1405 {
1406         struct bch_fs *c = root->d_sb->s_fs_info;
1407         enum bch_opt_id i;
1408         char buf[512];
1409
1410         for (i = 0; i < bch2_opts_nr; i++) {
1411                 const struct bch_option *opt = &bch2_opt_table[i];
1412                 u64 v = bch2_opt_get_by_id(&c->opts, i);
1413
1414                 if (!(opt->mode & OPT_MOUNT))
1415                         continue;
1416
1417                 if (v == bch2_opt_get_by_id(&bch2_opts_default, i))
1418                         continue;
1419
1420                 bch2_opt_to_text(&PBUF(buf), c, opt, v,
1421                                  OPT_SHOW_MOUNT_STYLE);
1422                 seq_putc(seq, ',');
1423                 seq_puts(seq, buf);
1424         }
1425
1426         return 0;
1427
1428 }
1429
1430 static const struct super_operations bch_super_operations = {
1431         .alloc_inode    = bch2_alloc_inode,
1432         .destroy_inode  = bch2_destroy_inode,
1433         .write_inode    = bch2_vfs_write_inode,
1434         .evict_inode    = bch2_evict_inode,
1435         .sync_fs        = bch2_sync_fs,
1436         .statfs         = bch2_statfs,
1437         .show_options   = bch2_show_options,
1438         .remount_fs     = bch2_remount,
1439 #if 0
1440         .put_super      = bch2_put_super,
1441         .freeze_fs      = bch2_freeze,
1442         .unfreeze_fs    = bch2_unfreeze,
1443 #endif
1444 };
1445
1446 static int bch2_test_super(struct super_block *s, void *data)
1447 {
1448         return s->s_fs_info == data;
1449 }
1450
1451 static int bch2_set_super(struct super_block *s, void *data)
1452 {
1453         s->s_fs_info = data;
1454         return 0;
1455 }
1456
1457 static struct dentry *bch2_mount(struct file_system_type *fs_type,
1458                                  int flags, const char *dev_name, void *data)
1459 {
1460         struct bch_fs *c;
1461         struct bch_dev *ca;
1462         struct super_block *sb;
1463         struct inode *vinode;
1464         struct bch_opts opts = bch2_opts_empty();
1465         unsigned i;
1466         int ret;
1467
1468         opt_set(opts, read_only, (flags & SB_RDONLY) != 0);
1469
1470         ret = bch2_parse_mount_opts(&opts, data);
1471         if (ret)
1472                 return ERR_PTR(ret);
1473
1474         c = bch2_open_as_blockdevs(dev_name, opts);
1475         if (IS_ERR(c))
1476                 return ERR_CAST(c);
1477
1478         sb = sget(fs_type, bch2_test_super, bch2_set_super, flags|SB_NOSEC, c);
1479         if (IS_ERR(sb)) {
1480                 closure_put(&c->cl);
1481                 return ERR_CAST(sb);
1482         }
1483
1484         BUG_ON(sb->s_fs_info != c);
1485
1486         if (sb->s_root) {
1487                 closure_put(&c->cl);
1488
1489                 if ((flags ^ sb->s_flags) & SB_RDONLY) {
1490                         ret = -EBUSY;
1491                         goto err_put_super;
1492                 }
1493                 goto out;
1494         }
1495
1496         sb->s_blocksize         = block_bytes(c);
1497         sb->s_blocksize_bits    = ilog2(block_bytes(c));
1498         sb->s_maxbytes          = MAX_LFS_FILESIZE;
1499         sb->s_op                = &bch_super_operations;
1500         sb->s_export_op         = &bch_export_ops;
1501 #ifdef CONFIG_BCACHEFS_QUOTA
1502         sb->s_qcop              = &bch2_quotactl_operations;
1503         sb->s_quota_types       = QTYPE_MASK_USR|QTYPE_MASK_GRP|QTYPE_MASK_PRJ;
1504 #endif
1505         sb->s_xattr             = bch2_xattr_handlers;
1506         sb->s_magic             = BCACHEFS_STATFS_MAGIC;
1507         sb->s_time_gran         = c->sb.time_precision;
1508         c->vfs_sb               = sb;
1509         strlcpy(sb->s_id, c->name, sizeof(sb->s_id));
1510
1511         ret = super_setup_bdi(sb);
1512         if (ret)
1513                 goto err_put_super;
1514
1515         sb->s_bdi->congested_fn         = bch2_congested;
1516         sb->s_bdi->congested_data       = c;
1517         sb->s_bdi->ra_pages             = VM_READAHEAD_PAGES;
1518
1519         for_each_online_member(ca, c, i) {
1520                 struct block_device *bdev = ca->disk_sb.bdev;
1521
1522                 /* XXX: create an anonymous device for multi device filesystems */
1523                 sb->s_bdev      = bdev;
1524                 sb->s_dev       = bdev->bd_dev;
1525                 percpu_ref_put(&ca->io_ref);
1526                 break;
1527         }
1528
1529 #ifdef CONFIG_BCACHEFS_POSIX_ACL
1530         if (c->opts.acl)
1531                 sb->s_flags     |= SB_POSIXACL;
1532 #endif
1533
1534         vinode = bch2_vfs_inode_get(c, BCACHEFS_ROOT_INO);
1535         if (IS_ERR(vinode)) {
1536                 bch_err(c, "error mounting: error getting root inode %i",
1537                         (int) PTR_ERR(vinode));
1538                 ret = PTR_ERR(vinode);
1539                 goto err_put_super;
1540         }
1541
1542         sb->s_root = d_make_root(vinode);
1543         if (!sb->s_root) {
1544                 bch_err(c, "error mounting: error allocating root dentry");
1545                 ret = -ENOMEM;
1546                 goto err_put_super;
1547         }
1548
1549         sb->s_flags |= SB_ACTIVE;
1550 out:
1551         return dget(sb->s_root);
1552
1553 err_put_super:
1554         deactivate_locked_super(sb);
1555         return ERR_PTR(ret);
1556 }
1557
1558 static void bch2_kill_sb(struct super_block *sb)
1559 {
1560         struct bch_fs *c = sb->s_fs_info;
1561
1562         generic_shutdown_super(sb);
1563
1564         if (test_bit(BCH_FS_BDEV_MOUNTED, &c->flags))
1565                 bch2_fs_stop(c);
1566         else
1567                 closure_put(&c->cl);
1568 }
1569
1570 static struct file_system_type bcache_fs_type = {
1571         .owner          = THIS_MODULE,
1572         .name           = "bcachefs",
1573         .mount          = bch2_mount,
1574         .kill_sb        = bch2_kill_sb,
1575         .fs_flags       = FS_REQUIRES_DEV,
1576 };
1577
1578 MODULE_ALIAS_FS("bcachefs");
1579
1580 void bch2_vfs_exit(void)
1581 {
1582         unregister_filesystem(&bcache_fs_type);
1583         if (bch2_inode_cache)
1584                 kmem_cache_destroy(bch2_inode_cache);
1585 }
1586
1587 int __init bch2_vfs_init(void)
1588 {
1589         int ret = -ENOMEM;
1590
1591         bch2_inode_cache = KMEM_CACHE(bch_inode_info, 0);
1592         if (!bch2_inode_cache)
1593                 goto err;
1594
1595         ret = register_filesystem(&bcache_fs_type);
1596         if (ret)
1597                 goto err;
1598
1599         return 0;
1600 err:
1601         bch2_vfs_exit();
1602         return ret;
1603 }
1604
1605 #endif /* NO_BCACHEFS_FS */