]> git.sesse.net Git - bcachefs-tools-debian/blob - libbcachefs/fs.c
4445fa2f53d02b341add2899e7df044150abcee8
[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_buf.h"
7 #include "btree_update.h"
8 #include "buckets.h"
9 #include "chardev.h"
10 #include "dirent.h"
11 #include "errcode.h"
12 #include "extents.h"
13 #include "fs.h"
14 #include "fs-common.h"
15 #include "fs-io.h"
16 #include "fs-ioctl.h"
17 #include "fs-io-buffered.h"
18 #include "fs-io-direct.h"
19 #include "fs-io-pagecache.h"
20 #include "fsck.h"
21 #include "inode.h"
22 #include "io_read.h"
23 #include "journal.h"
24 #include "keylist.h"
25 #include "quota.h"
26 #include "snapshot.h"
27 #include "super.h"
28 #include "xattr.h"
29
30 #include <linux/aio.h>
31 #include <linux/backing-dev.h>
32 #include <linux/exportfs.h>
33 #include <linux/fiemap.h>
34 #include <linux/module.h>
35 #include <linux/pagemap.h>
36 #include <linux/posix_acl.h>
37 #include <linux/random.h>
38 #include <linux/seq_file.h>
39 #include <linux/statfs.h>
40 #include <linux/string.h>
41 #include <linux/xattr.h>
42
43 static struct kmem_cache *bch2_inode_cache;
44
45 static void bch2_vfs_inode_init(struct btree_trans *, subvol_inum,
46                                 struct bch_inode_info *,
47                                 struct bch_inode_unpacked *,
48                                 struct bch_subvolume *);
49
50 void bch2_inode_update_after_write(struct btree_trans *trans,
51                                    struct bch_inode_info *inode,
52                                    struct bch_inode_unpacked *bi,
53                                    unsigned fields)
54 {
55         struct bch_fs *c = trans->c;
56
57         BUG_ON(bi->bi_inum != inode->v.i_ino);
58
59         bch2_assert_pos_locked(trans, BTREE_ID_inodes,
60                                POS(0, bi->bi_inum),
61                                c->opts.inodes_use_key_cache);
62
63         set_nlink(&inode->v, bch2_inode_nlink_get(bi));
64         i_uid_write(&inode->v, bi->bi_uid);
65         i_gid_write(&inode->v, bi->bi_gid);
66         inode->v.i_mode = bi->bi_mode;
67
68         if (fields & ATTR_ATIME)
69                 inode_set_atime_to_ts(&inode->v, bch2_time_to_timespec(c, bi->bi_atime));
70         if (fields & ATTR_MTIME)
71                 inode_set_mtime_to_ts(&inode->v, bch2_time_to_timespec(c, bi->bi_mtime));
72         if (fields & ATTR_CTIME)
73                 inode_set_ctime_to_ts(&inode->v, bch2_time_to_timespec(c, bi->bi_ctime));
74
75         inode->ei_inode         = *bi;
76
77         bch2_inode_flags_to_vfs(inode);
78 }
79
80 int __must_check bch2_write_inode(struct bch_fs *c,
81                                   struct bch_inode_info *inode,
82                                   inode_set_fn set,
83                                   void *p, unsigned fields)
84 {
85         struct btree_trans *trans = bch2_trans_get(c);
86         struct btree_iter iter = { NULL };
87         struct bch_inode_unpacked inode_u;
88         int ret;
89 retry:
90         bch2_trans_begin(trans);
91
92         ret   = bch2_inode_peek(trans, &iter, &inode_u, inode_inum(inode),
93                                 BTREE_ITER_INTENT) ?:
94                 (set ? set(trans, inode, &inode_u, p) : 0) ?:
95                 bch2_inode_write(trans, &iter, &inode_u) ?:
96                 bch2_trans_commit(trans, NULL, NULL, BCH_TRANS_COMMIT_no_enospc);
97
98         /*
99          * the btree node lock protects inode->ei_inode, not ei_update_lock;
100          * this is important for inode updates via bchfs_write_index_update
101          */
102         if (!ret)
103                 bch2_inode_update_after_write(trans, inode, &inode_u, fields);
104
105         bch2_trans_iter_exit(trans, &iter);
106
107         if (bch2_err_matches(ret, BCH_ERR_transaction_restart))
108                 goto retry;
109
110         bch2_fs_fatal_err_on(bch2_err_matches(ret, ENOENT), c,
111                              "inode %u:%llu not found when updating",
112                              inode_inum(inode).subvol,
113                              inode_inum(inode).inum);
114
115         bch2_trans_put(trans);
116         return ret < 0 ? ret : 0;
117 }
118
119 int bch2_fs_quota_transfer(struct bch_fs *c,
120                            struct bch_inode_info *inode,
121                            struct bch_qid new_qid,
122                            unsigned qtypes,
123                            enum quota_acct_mode mode)
124 {
125         unsigned i;
126         int ret;
127
128         qtypes &= enabled_qtypes(c);
129
130         for (i = 0; i < QTYP_NR; i++)
131                 if (new_qid.q[i] == inode->ei_qid.q[i])
132                         qtypes &= ~(1U << i);
133
134         if (!qtypes)
135                 return 0;
136
137         mutex_lock(&inode->ei_quota_lock);
138
139         ret = bch2_quota_transfer(c, qtypes, new_qid,
140                                   inode->ei_qid,
141                                   inode->v.i_blocks +
142                                   inode->ei_quota_reserved,
143                                   mode);
144         if (!ret)
145                 for (i = 0; i < QTYP_NR; i++)
146                         if (qtypes & (1 << i))
147                                 inode->ei_qid.q[i] = new_qid.q[i];
148
149         mutex_unlock(&inode->ei_quota_lock);
150
151         return ret;
152 }
153
154 static int bch2_iget5_test(struct inode *vinode, void *p)
155 {
156         struct bch_inode_info *inode = to_bch_ei(vinode);
157         subvol_inum *inum = p;
158
159         return inode->ei_subvol == inum->subvol &&
160                 inode->ei_inode.bi_inum == inum->inum;
161 }
162
163 static int bch2_iget5_set(struct inode *vinode, void *p)
164 {
165         struct bch_inode_info *inode = to_bch_ei(vinode);
166         subvol_inum *inum = p;
167
168         inode->v.i_ino          = inum->inum;
169         inode->ei_subvol        = inum->subvol;
170         inode->ei_inode.bi_inum = inum->inum;
171         return 0;
172 }
173
174 static unsigned bch2_inode_hash(subvol_inum inum)
175 {
176         return jhash_3words(inum.subvol, inum.inum >> 32, inum.inum, JHASH_INITVAL);
177 }
178
179 static struct bch_inode_info *bch2_inode_insert(struct bch_fs *c, struct bch_inode_info *inode)
180 {
181         subvol_inum inum = inode_inum(inode);
182         struct bch_inode_info *old = to_bch_ei(inode_insert5(&inode->v,
183                                       bch2_inode_hash(inum),
184                                       bch2_iget5_test,
185                                       bch2_iget5_set,
186                                       &inum));
187         BUG_ON(!old);
188
189         if (unlikely(old != inode)) {
190                 discard_new_inode(&inode->v);
191                 inode = old;
192         } else {
193                 mutex_lock(&c->vfs_inodes_lock);
194                 list_add(&inode->ei_vfs_inode_list, &c->vfs_inodes_list);
195                 mutex_unlock(&c->vfs_inodes_lock);
196                 /*
197                  * we really don't want insert_inode_locked2() to be setting
198                  * I_NEW...
199                  */
200                 unlock_new_inode(&inode->v);
201         }
202
203         return inode;
204 }
205
206 #define memalloc_flags_do(_flags, _do)                                          \
207 ({                                                                              \
208         unsigned _saved_flags = memalloc_flags_save(_flags);                    \
209         typeof(_do) _ret = _do;                                                 \
210         memalloc_noreclaim_restore(_saved_flags);                               \
211         _ret;                                                                   \
212 })
213
214 /*
215  * Allocate a new inode, dropping/retaking btree locks if necessary:
216  */
217 static struct bch_inode_info *bch2_new_inode(struct btree_trans *trans)
218 {
219         struct bch_fs *c = trans->c;
220
221         struct bch_inode_info *inode =
222                 memalloc_flags_do(PF_MEMALLOC_NORECLAIM|PF_MEMALLOC_NOWARN,
223                                   to_bch_ei(new_inode(c->vfs_sb)));
224
225         if (unlikely(!inode)) {
226                 int ret = drop_locks_do(trans, (inode = to_bch_ei(new_inode(c->vfs_sb))) ? 0 : -ENOMEM);
227                 if (ret && inode)
228                         discard_new_inode(&inode->v);
229                 if (ret)
230                         return ERR_PTR(ret);
231         }
232
233         return inode;
234 }
235
236 struct inode *bch2_vfs_inode_get(struct bch_fs *c, subvol_inum inum)
237 {
238         struct bch_inode_info *inode =
239                 to_bch_ei(ilookup5_nowait(c->vfs_sb,
240                                           bch2_inode_hash(inum),
241                                           bch2_iget5_test,
242                                           &inum));
243         if (inode)
244                 return &inode->v;
245
246         struct btree_trans *trans = bch2_trans_get(c);
247
248         struct bch_inode_unpacked inode_u;
249         struct bch_subvolume subvol;
250         int ret = lockrestart_do(trans,
251                 bch2_subvolume_get(trans, inum.subvol, true, 0, &subvol) ?:
252                 bch2_inode_find_by_inum_trans(trans, inum, &inode_u)) ?:
253                 PTR_ERR_OR_ZERO(inode = bch2_new_inode(trans));
254         if (!ret) {
255                 bch2_vfs_inode_init(trans, inum, inode, &inode_u, &subvol);
256                 inode = bch2_inode_insert(c, inode);
257         }
258         bch2_trans_put(trans);
259
260         return ret ? ERR_PTR(ret) : &inode->v;
261 }
262
263 struct bch_inode_info *
264 __bch2_create(struct mnt_idmap *idmap,
265               struct bch_inode_info *dir, struct dentry *dentry,
266               umode_t mode, dev_t rdev, subvol_inum snapshot_src,
267               unsigned flags)
268 {
269         struct bch_fs *c = dir->v.i_sb->s_fs_info;
270         struct btree_trans *trans;
271         struct bch_inode_unpacked dir_u;
272         struct bch_inode_info *inode;
273         struct bch_inode_unpacked inode_u;
274         struct posix_acl *default_acl = NULL, *acl = NULL;
275         subvol_inum inum;
276         struct bch_subvolume subvol;
277         u64 journal_seq = 0;
278         int ret;
279
280         /*
281          * preallocate acls + vfs inode before btree transaction, so that
282          * nothing can fail after the transaction succeeds:
283          */
284 #ifdef CONFIG_BCACHEFS_POSIX_ACL
285         ret = posix_acl_create(&dir->v, &mode, &default_acl, &acl);
286         if (ret)
287                 return ERR_PTR(ret);
288 #endif
289         inode = to_bch_ei(new_inode(c->vfs_sb));
290         if (unlikely(!inode)) {
291                 inode = ERR_PTR(-ENOMEM);
292                 goto err;
293         }
294
295         bch2_inode_init_early(c, &inode_u);
296
297         if (!(flags & BCH_CREATE_TMPFILE))
298                 mutex_lock(&dir->ei_update_lock);
299
300         trans = bch2_trans_get(c);
301 retry:
302         bch2_trans_begin(trans);
303
304         ret   = bch2_subvol_is_ro_trans(trans, dir->ei_subvol) ?:
305                 bch2_create_trans(trans,
306                                   inode_inum(dir), &dir_u, &inode_u,
307                                   !(flags & BCH_CREATE_TMPFILE)
308                                   ? &dentry->d_name : NULL,
309                                   from_kuid(i_user_ns(&dir->v), current_fsuid()),
310                                   from_kgid(i_user_ns(&dir->v), current_fsgid()),
311                                   mode, rdev,
312                                   default_acl, acl, snapshot_src, flags) ?:
313                 bch2_quota_acct(c, bch_qid(&inode_u), Q_INO, 1,
314                                 KEY_TYPE_QUOTA_PREALLOC);
315         if (unlikely(ret))
316                 goto err_before_quota;
317
318         inum.subvol = inode_u.bi_subvol ?: dir->ei_subvol;
319         inum.inum = inode_u.bi_inum;
320
321         ret   = bch2_subvolume_get(trans, inum.subvol, true,
322                                    BTREE_ITER_WITH_UPDATES, &subvol) ?:
323                 bch2_trans_commit(trans, NULL, &journal_seq, 0);
324         if (unlikely(ret)) {
325                 bch2_quota_acct(c, bch_qid(&inode_u), Q_INO, -1,
326                                 KEY_TYPE_QUOTA_WARN);
327 err_before_quota:
328                 if (bch2_err_matches(ret, BCH_ERR_transaction_restart))
329                         goto retry;
330                 goto err_trans;
331         }
332
333         if (!(flags & BCH_CREATE_TMPFILE)) {
334                 bch2_inode_update_after_write(trans, dir, &dir_u,
335                                               ATTR_MTIME|ATTR_CTIME);
336                 mutex_unlock(&dir->ei_update_lock);
337         }
338
339         bch2_vfs_inode_init(trans, inum, inode, &inode_u, &subvol);
340
341         set_cached_acl(&inode->v, ACL_TYPE_ACCESS, acl);
342         set_cached_acl(&inode->v, ACL_TYPE_DEFAULT, default_acl);
343
344         /*
345          * we must insert the new inode into the inode cache before calling
346          * bch2_trans_exit() and dropping locks, else we could race with another
347          * thread pulling the inode in and modifying it:
348          */
349         inode = bch2_inode_insert(c, inode);
350         bch2_trans_put(trans);
351 err:
352         posix_acl_release(default_acl);
353         posix_acl_release(acl);
354         return inode;
355 err_trans:
356         if (!(flags & BCH_CREATE_TMPFILE))
357                 mutex_unlock(&dir->ei_update_lock);
358
359         bch2_trans_put(trans);
360         make_bad_inode(&inode->v);
361         iput(&inode->v);
362         inode = ERR_PTR(ret);
363         goto err;
364 }
365
366 /* methods */
367
368 static struct bch_inode_info *bch2_lookup_trans(struct btree_trans *trans,
369                         subvol_inum dir, struct bch_hash_info *dir_hash_info,
370                         const struct qstr *name)
371 {
372         struct bch_fs *c = trans->c;
373         struct btree_iter dirent_iter = {};
374         subvol_inum inum = {};
375
376         int ret = bch2_hash_lookup(trans, &dirent_iter, bch2_dirent_hash_desc,
377                                    dir_hash_info, dir, name, 0);
378         if (ret)
379                 return ERR_PTR(ret);
380
381         struct bkey_s_c k = bch2_btree_iter_peek_slot(&dirent_iter);
382         ret = bkey_err(k);
383         if (ret)
384                 goto err;
385
386         ret = bch2_dirent_read_target(trans, dir, bkey_s_c_to_dirent(k), &inum);
387         if (ret > 0)
388                 ret = -ENOENT;
389         if (ret)
390                 goto err;
391
392         struct bch_inode_info *inode =
393                 to_bch_ei(ilookup5_nowait(c->vfs_sb,
394                                           bch2_inode_hash(inum),
395                                           bch2_iget5_test,
396                                           &inum));
397         if (inode)
398                 goto out;
399
400         struct bch_subvolume subvol;
401         struct bch_inode_unpacked inode_u;
402         ret =   bch2_subvolume_get(trans, inum.subvol, true, 0, &subvol) ?:
403                 bch2_inode_find_by_inum_nowarn_trans(trans, inum, &inode_u) ?:
404                 PTR_ERR_OR_ZERO(inode = bch2_new_inode(trans));
405         if (bch2_err_matches(ret, ENOENT)) {
406                 struct printbuf buf = PRINTBUF;
407
408                 bch2_bkey_val_to_text(&buf, c, k);
409                 bch_err(c, "%s points to missing inode", buf.buf);
410                 printbuf_exit(&buf);
411         }
412         if (ret)
413                 goto err;
414
415         bch2_vfs_inode_init(trans, inum, inode, &inode_u, &subvol);
416         inode = bch2_inode_insert(c, inode);
417 out:
418         bch2_trans_iter_exit(trans, &dirent_iter);
419         return inode;
420 err:
421         inode = ERR_PTR(ret);
422         goto out;
423 }
424
425 static struct dentry *bch2_lookup(struct inode *vdir, struct dentry *dentry,
426                                   unsigned int flags)
427 {
428         struct bch_fs *c = vdir->i_sb->s_fs_info;
429         struct bch_inode_info *dir = to_bch_ei(vdir);
430         struct bch_hash_info hash = bch2_hash_info_init(c, &dir->ei_inode);
431
432         struct bch_inode_info *inode;
433         bch2_trans_do(c, NULL, NULL, 0,
434                 PTR_ERR_OR_ZERO(inode = bch2_lookup_trans(trans, inode_inum(dir),
435                                                           &hash, &dentry->d_name)));
436         if (IS_ERR(inode))
437                 inode = NULL;
438
439         return d_splice_alias(&inode->v, dentry);
440 }
441
442 static int bch2_mknod(struct mnt_idmap *idmap,
443                       struct inode *vdir, struct dentry *dentry,
444                       umode_t mode, dev_t rdev)
445 {
446         struct bch_inode_info *inode =
447                 __bch2_create(idmap, to_bch_ei(vdir), dentry, mode, rdev,
448                               (subvol_inum) { 0 }, 0);
449
450         if (IS_ERR(inode))
451                 return bch2_err_class(PTR_ERR(inode));
452
453         d_instantiate(dentry, &inode->v);
454         return 0;
455 }
456
457 static int bch2_create(struct mnt_idmap *idmap,
458                        struct inode *vdir, struct dentry *dentry,
459                        umode_t mode, bool excl)
460 {
461         return bch2_mknod(idmap, vdir, dentry, mode|S_IFREG, 0);
462 }
463
464 static int __bch2_link(struct bch_fs *c,
465                        struct bch_inode_info *inode,
466                        struct bch_inode_info *dir,
467                        struct dentry *dentry)
468 {
469         struct btree_trans *trans = bch2_trans_get(c);
470         struct bch_inode_unpacked dir_u, inode_u;
471         int ret;
472
473         mutex_lock(&inode->ei_update_lock);
474
475         ret = commit_do(trans, NULL, NULL, 0,
476                         bch2_link_trans(trans,
477                                         inode_inum(dir),   &dir_u,
478                                         inode_inum(inode), &inode_u,
479                                         &dentry->d_name));
480
481         if (likely(!ret)) {
482                 bch2_inode_update_after_write(trans, dir, &dir_u,
483                                               ATTR_MTIME|ATTR_CTIME);
484                 bch2_inode_update_after_write(trans, inode, &inode_u, ATTR_CTIME);
485         }
486
487         bch2_trans_put(trans);
488         mutex_unlock(&inode->ei_update_lock);
489         return ret;
490 }
491
492 static int bch2_link(struct dentry *old_dentry, struct inode *vdir,
493                      struct dentry *dentry)
494 {
495         struct bch_fs *c = vdir->i_sb->s_fs_info;
496         struct bch_inode_info *dir = to_bch_ei(vdir);
497         struct bch_inode_info *inode = to_bch_ei(old_dentry->d_inode);
498         int ret;
499
500         lockdep_assert_held(&inode->v.i_rwsem);
501
502         ret   = bch2_subvol_is_ro(c, dir->ei_subvol) ?:
503                 bch2_subvol_is_ro(c, inode->ei_subvol) ?:
504                 __bch2_link(c, inode, dir, dentry);
505         if (unlikely(ret))
506                 return bch2_err_class(ret);
507
508         ihold(&inode->v);
509         d_instantiate(dentry, &inode->v);
510         return 0;
511 }
512
513 int __bch2_unlink(struct inode *vdir, struct dentry *dentry,
514                   bool deleting_snapshot)
515 {
516         struct bch_fs *c = vdir->i_sb->s_fs_info;
517         struct bch_inode_info *dir = to_bch_ei(vdir);
518         struct bch_inode_info *inode = to_bch_ei(dentry->d_inode);
519         struct bch_inode_unpacked dir_u, inode_u;
520         struct btree_trans *trans = bch2_trans_get(c);
521         int ret;
522
523         bch2_lock_inodes(INODE_UPDATE_LOCK, dir, inode);
524
525         ret = commit_do(trans, NULL, NULL,
526                         BCH_TRANS_COMMIT_no_enospc,
527                 bch2_unlink_trans(trans,
528                                   inode_inum(dir), &dir_u,
529                                   &inode_u, &dentry->d_name,
530                                   deleting_snapshot));
531         if (unlikely(ret))
532                 goto err;
533
534         bch2_inode_update_after_write(trans, dir, &dir_u,
535                                       ATTR_MTIME|ATTR_CTIME);
536         bch2_inode_update_after_write(trans, inode, &inode_u,
537                                       ATTR_MTIME);
538
539         if (inode_u.bi_subvol) {
540                 /*
541                  * Subvolume deletion is asynchronous, but we still want to tell
542                  * the VFS that it's been deleted here:
543                  */
544                 set_nlink(&inode->v, 0);
545         }
546 err:
547         bch2_unlock_inodes(INODE_UPDATE_LOCK, dir, inode);
548         bch2_trans_put(trans);
549
550         return ret;
551 }
552
553 static int bch2_unlink(struct inode *vdir, struct dentry *dentry)
554 {
555         struct bch_inode_info *dir= to_bch_ei(vdir);
556         struct bch_fs *c = dir->v.i_sb->s_fs_info;
557
558         int ret = bch2_subvol_is_ro(c, dir->ei_subvol) ?:
559                 __bch2_unlink(vdir, dentry, false);
560         return bch2_err_class(ret);
561 }
562
563 static int bch2_symlink(struct mnt_idmap *idmap,
564                         struct inode *vdir, struct dentry *dentry,
565                         const char *symname)
566 {
567         struct bch_fs *c = vdir->i_sb->s_fs_info;
568         struct bch_inode_info *dir = to_bch_ei(vdir), *inode;
569         int ret;
570
571         inode = __bch2_create(idmap, dir, dentry, S_IFLNK|S_IRWXUGO, 0,
572                               (subvol_inum) { 0 }, BCH_CREATE_TMPFILE);
573         if (IS_ERR(inode))
574                 return bch2_err_class(PTR_ERR(inode));
575
576         inode_lock(&inode->v);
577         ret = page_symlink(&inode->v, symname, strlen(symname) + 1);
578         inode_unlock(&inode->v);
579
580         if (unlikely(ret))
581                 goto err;
582
583         ret = filemap_write_and_wait_range(inode->v.i_mapping, 0, LLONG_MAX);
584         if (unlikely(ret))
585                 goto err;
586
587         ret = __bch2_link(c, inode, dir, dentry);
588         if (unlikely(ret))
589                 goto err;
590
591         d_instantiate(dentry, &inode->v);
592         return 0;
593 err:
594         iput(&inode->v);
595         return bch2_err_class(ret);
596 }
597
598 static int bch2_mkdir(struct mnt_idmap *idmap,
599                       struct inode *vdir, struct dentry *dentry, umode_t mode)
600 {
601         return bch2_mknod(idmap, vdir, dentry, mode|S_IFDIR, 0);
602 }
603
604 static int bch2_rename2(struct mnt_idmap *idmap,
605                         struct inode *src_vdir, struct dentry *src_dentry,
606                         struct inode *dst_vdir, struct dentry *dst_dentry,
607                         unsigned flags)
608 {
609         struct bch_fs *c = src_vdir->i_sb->s_fs_info;
610         struct bch_inode_info *src_dir = to_bch_ei(src_vdir);
611         struct bch_inode_info *dst_dir = to_bch_ei(dst_vdir);
612         struct bch_inode_info *src_inode = to_bch_ei(src_dentry->d_inode);
613         struct bch_inode_info *dst_inode = to_bch_ei(dst_dentry->d_inode);
614         struct bch_inode_unpacked dst_dir_u, src_dir_u;
615         struct bch_inode_unpacked src_inode_u, dst_inode_u;
616         struct btree_trans *trans;
617         enum bch_rename_mode mode = flags & RENAME_EXCHANGE
618                 ? BCH_RENAME_EXCHANGE
619                 : dst_dentry->d_inode
620                 ? BCH_RENAME_OVERWRITE : BCH_RENAME;
621         int ret;
622
623         if (flags & ~(RENAME_NOREPLACE|RENAME_EXCHANGE))
624                 return -EINVAL;
625
626         if (mode == BCH_RENAME_OVERWRITE) {
627                 ret = filemap_write_and_wait_range(src_inode->v.i_mapping,
628                                                    0, LLONG_MAX);
629                 if (ret)
630                         return ret;
631         }
632
633         trans = bch2_trans_get(c);
634
635         bch2_lock_inodes(INODE_UPDATE_LOCK,
636                          src_dir,
637                          dst_dir,
638                          src_inode,
639                          dst_inode);
640
641         ret   = bch2_subvol_is_ro_trans(trans, src_dir->ei_subvol) ?:
642                 bch2_subvol_is_ro_trans(trans, dst_dir->ei_subvol);
643         if (ret)
644                 goto err;
645
646         if (inode_attr_changing(dst_dir, src_inode, Inode_opt_project)) {
647                 ret = bch2_fs_quota_transfer(c, src_inode,
648                                              dst_dir->ei_qid,
649                                              1 << QTYP_PRJ,
650                                              KEY_TYPE_QUOTA_PREALLOC);
651                 if (ret)
652                         goto err;
653         }
654
655         if (mode == BCH_RENAME_EXCHANGE &&
656             inode_attr_changing(src_dir, dst_inode, Inode_opt_project)) {
657                 ret = bch2_fs_quota_transfer(c, dst_inode,
658                                              src_dir->ei_qid,
659                                              1 << QTYP_PRJ,
660                                              KEY_TYPE_QUOTA_PREALLOC);
661                 if (ret)
662                         goto err;
663         }
664
665         ret = commit_do(trans, NULL, NULL, 0,
666                         bch2_rename_trans(trans,
667                                           inode_inum(src_dir), &src_dir_u,
668                                           inode_inum(dst_dir), &dst_dir_u,
669                                           &src_inode_u,
670                                           &dst_inode_u,
671                                           &src_dentry->d_name,
672                                           &dst_dentry->d_name,
673                                           mode));
674         if (unlikely(ret))
675                 goto err;
676
677         BUG_ON(src_inode->v.i_ino != src_inode_u.bi_inum);
678         BUG_ON(dst_inode &&
679                dst_inode->v.i_ino != dst_inode_u.bi_inum);
680
681         bch2_inode_update_after_write(trans, src_dir, &src_dir_u,
682                                       ATTR_MTIME|ATTR_CTIME);
683
684         if (src_dir != dst_dir)
685                 bch2_inode_update_after_write(trans, dst_dir, &dst_dir_u,
686                                               ATTR_MTIME|ATTR_CTIME);
687
688         bch2_inode_update_after_write(trans, src_inode, &src_inode_u,
689                                       ATTR_CTIME);
690
691         if (dst_inode)
692                 bch2_inode_update_after_write(trans, dst_inode, &dst_inode_u,
693                                               ATTR_CTIME);
694 err:
695         bch2_trans_put(trans);
696
697         bch2_fs_quota_transfer(c, src_inode,
698                                bch_qid(&src_inode->ei_inode),
699                                1 << QTYP_PRJ,
700                                KEY_TYPE_QUOTA_NOCHECK);
701         if (dst_inode)
702                 bch2_fs_quota_transfer(c, dst_inode,
703                                        bch_qid(&dst_inode->ei_inode),
704                                        1 << QTYP_PRJ,
705                                        KEY_TYPE_QUOTA_NOCHECK);
706
707         bch2_unlock_inodes(INODE_UPDATE_LOCK,
708                            src_dir,
709                            dst_dir,
710                            src_inode,
711                            dst_inode);
712
713         return ret;
714 }
715
716 static void bch2_setattr_copy(struct mnt_idmap *idmap,
717                               struct bch_inode_info *inode,
718                               struct bch_inode_unpacked *bi,
719                               struct iattr *attr)
720 {
721         struct bch_fs *c = inode->v.i_sb->s_fs_info;
722         unsigned int ia_valid = attr->ia_valid;
723
724         if (ia_valid & ATTR_UID)
725                 bi->bi_uid = from_kuid(i_user_ns(&inode->v), attr->ia_uid);
726         if (ia_valid & ATTR_GID)
727                 bi->bi_gid = from_kgid(i_user_ns(&inode->v), attr->ia_gid);
728
729         if (ia_valid & ATTR_SIZE)
730                 bi->bi_size = attr->ia_size;
731
732         if (ia_valid & ATTR_ATIME)
733                 bi->bi_atime = timespec_to_bch2_time(c, attr->ia_atime);
734         if (ia_valid & ATTR_MTIME)
735                 bi->bi_mtime = timespec_to_bch2_time(c, attr->ia_mtime);
736         if (ia_valid & ATTR_CTIME)
737                 bi->bi_ctime = timespec_to_bch2_time(c, attr->ia_ctime);
738
739         if (ia_valid & ATTR_MODE) {
740                 umode_t mode = attr->ia_mode;
741                 kgid_t gid = ia_valid & ATTR_GID
742                         ? attr->ia_gid
743                         : inode->v.i_gid;
744
745                 if (!in_group_p(gid) &&
746                     !capable_wrt_inode_uidgid(idmap, &inode->v, CAP_FSETID))
747                         mode &= ~S_ISGID;
748                 bi->bi_mode = mode;
749         }
750 }
751
752 int bch2_setattr_nonsize(struct mnt_idmap *idmap,
753                          struct bch_inode_info *inode,
754                          struct iattr *attr)
755 {
756         struct bch_fs *c = inode->v.i_sb->s_fs_info;
757         struct bch_qid qid;
758         struct btree_trans *trans;
759         struct btree_iter inode_iter = { NULL };
760         struct bch_inode_unpacked inode_u;
761         struct posix_acl *acl = NULL;
762         int ret;
763
764         mutex_lock(&inode->ei_update_lock);
765
766         qid = inode->ei_qid;
767
768         if (attr->ia_valid & ATTR_UID)
769                 qid.q[QTYP_USR] = from_kuid(i_user_ns(&inode->v), attr->ia_uid);
770
771         if (attr->ia_valid & ATTR_GID)
772                 qid.q[QTYP_GRP] = from_kgid(i_user_ns(&inode->v), attr->ia_gid);
773
774         ret = bch2_fs_quota_transfer(c, inode, qid, ~0,
775                                      KEY_TYPE_QUOTA_PREALLOC);
776         if (ret)
777                 goto err;
778
779         trans = bch2_trans_get(c);
780 retry:
781         bch2_trans_begin(trans);
782         kfree(acl);
783         acl = NULL;
784
785         ret = bch2_inode_peek(trans, &inode_iter, &inode_u, inode_inum(inode),
786                               BTREE_ITER_INTENT);
787         if (ret)
788                 goto btree_err;
789
790         bch2_setattr_copy(idmap, inode, &inode_u, attr);
791
792         if (attr->ia_valid & ATTR_MODE) {
793                 ret = bch2_acl_chmod(trans, inode_inum(inode), &inode_u,
794                                      inode_u.bi_mode, &acl);
795                 if (ret)
796                         goto btree_err;
797         }
798
799         ret =   bch2_inode_write(trans, &inode_iter, &inode_u) ?:
800                 bch2_trans_commit(trans, NULL, NULL,
801                                   BCH_TRANS_COMMIT_no_enospc);
802 btree_err:
803         bch2_trans_iter_exit(trans, &inode_iter);
804
805         if (bch2_err_matches(ret, BCH_ERR_transaction_restart))
806                 goto retry;
807         if (unlikely(ret))
808                 goto err_trans;
809
810         bch2_inode_update_after_write(trans, inode, &inode_u, attr->ia_valid);
811
812         if (acl)
813                 set_cached_acl(&inode->v, ACL_TYPE_ACCESS, acl);
814 err_trans:
815         bch2_trans_put(trans);
816 err:
817         mutex_unlock(&inode->ei_update_lock);
818
819         return bch2_err_class(ret);
820 }
821
822 static int bch2_getattr(struct mnt_idmap *idmap,
823                         const struct path *path, struct kstat *stat,
824                         u32 request_mask, unsigned query_flags)
825 {
826         struct bch_inode_info *inode = to_bch_ei(d_inode(path->dentry));
827         struct bch_fs *c = inode->v.i_sb->s_fs_info;
828
829         stat->dev       = inode->v.i_sb->s_dev;
830         stat->ino       = inode->v.i_ino;
831         stat->mode      = inode->v.i_mode;
832         stat->nlink     = inode->v.i_nlink;
833         stat->uid       = inode->v.i_uid;
834         stat->gid       = inode->v.i_gid;
835         stat->rdev      = inode->v.i_rdev;
836         stat->size      = i_size_read(&inode->v);
837         stat->atime     = inode_get_atime(&inode->v);
838         stat->mtime     = inode_get_mtime(&inode->v);
839         stat->ctime     = inode_get_ctime(&inode->v);
840         stat->blksize   = block_bytes(c);
841         stat->blocks    = inode->v.i_blocks;
842
843         if (request_mask & STATX_BTIME) {
844                 stat->result_mask |= STATX_BTIME;
845                 stat->btime = bch2_time_to_timespec(c, inode->ei_inode.bi_otime);
846         }
847
848         if (inode->ei_inode.bi_flags & BCH_INODE_immutable)
849                 stat->attributes |= STATX_ATTR_IMMUTABLE;
850         stat->attributes_mask    |= STATX_ATTR_IMMUTABLE;
851
852         if (inode->ei_inode.bi_flags & BCH_INODE_append)
853                 stat->attributes |= STATX_ATTR_APPEND;
854         stat->attributes_mask    |= STATX_ATTR_APPEND;
855
856         if (inode->ei_inode.bi_flags & BCH_INODE_nodump)
857                 stat->attributes |= STATX_ATTR_NODUMP;
858         stat->attributes_mask    |= STATX_ATTR_NODUMP;
859
860         return 0;
861 }
862
863 static int bch2_setattr(struct mnt_idmap *idmap,
864                         struct dentry *dentry, struct iattr *iattr)
865 {
866         struct bch_inode_info *inode = to_bch_ei(dentry->d_inode);
867         struct bch_fs *c = inode->v.i_sb->s_fs_info;
868         int ret;
869
870         lockdep_assert_held(&inode->v.i_rwsem);
871
872         ret   = bch2_subvol_is_ro(c, inode->ei_subvol) ?:
873                 setattr_prepare(idmap, dentry, iattr);
874         if (ret)
875                 return ret;
876
877         return iattr->ia_valid & ATTR_SIZE
878                 ? bchfs_truncate(idmap, inode, iattr)
879                 : bch2_setattr_nonsize(idmap, inode, iattr);
880 }
881
882 static int bch2_tmpfile(struct mnt_idmap *idmap,
883                         struct inode *vdir, struct file *file, umode_t mode)
884 {
885         struct bch_inode_info *inode =
886                 __bch2_create(idmap, to_bch_ei(vdir),
887                               file->f_path.dentry, mode, 0,
888                               (subvol_inum) { 0 }, BCH_CREATE_TMPFILE);
889
890         if (IS_ERR(inode))
891                 return bch2_err_class(PTR_ERR(inode));
892
893         d_mark_tmpfile(file, &inode->v);
894         d_instantiate(file->f_path.dentry, &inode->v);
895         return finish_open_simple(file, 0);
896 }
897
898 static int bch2_fill_extent(struct bch_fs *c,
899                             struct fiemap_extent_info *info,
900                             struct bkey_s_c k, unsigned flags)
901 {
902         if (bkey_extent_is_direct_data(k.k)) {
903                 struct bkey_ptrs_c ptrs = bch2_bkey_ptrs_c(k);
904                 const union bch_extent_entry *entry;
905                 struct extent_ptr_decoded p;
906                 int ret;
907
908                 if (k.k->type == KEY_TYPE_reflink_v)
909                         flags |= FIEMAP_EXTENT_SHARED;
910
911                 bkey_for_each_ptr_decode(k.k, ptrs, p, entry) {
912                         int flags2 = 0;
913                         u64 offset = p.ptr.offset;
914
915                         if (p.ptr.unwritten)
916                                 flags2 |= FIEMAP_EXTENT_UNWRITTEN;
917
918                         if (p.crc.compression_type)
919                                 flags2 |= FIEMAP_EXTENT_ENCODED;
920                         else
921                                 offset += p.crc.offset;
922
923                         if ((offset & (block_sectors(c) - 1)) ||
924                             (k.k->size & (block_sectors(c) - 1)))
925                                 flags2 |= FIEMAP_EXTENT_NOT_ALIGNED;
926
927                         ret = fiemap_fill_next_extent(info,
928                                                 bkey_start_offset(k.k) << 9,
929                                                 offset << 9,
930                                                 k.k->size << 9, flags|flags2);
931                         if (ret)
932                                 return ret;
933                 }
934
935                 return 0;
936         } else if (bkey_extent_is_inline_data(k.k)) {
937                 return fiemap_fill_next_extent(info,
938                                                bkey_start_offset(k.k) << 9,
939                                                0, k.k->size << 9,
940                                                flags|
941                                                FIEMAP_EXTENT_DATA_INLINE);
942         } else if (k.k->type == KEY_TYPE_reservation) {
943                 return fiemap_fill_next_extent(info,
944                                                bkey_start_offset(k.k) << 9,
945                                                0, k.k->size << 9,
946                                                flags|
947                                                FIEMAP_EXTENT_DELALLOC|
948                                                FIEMAP_EXTENT_UNWRITTEN);
949         } else {
950                 BUG();
951         }
952 }
953
954 static int bch2_fiemap(struct inode *vinode, struct fiemap_extent_info *info,
955                        u64 start, u64 len)
956 {
957         struct bch_fs *c = vinode->i_sb->s_fs_info;
958         struct bch_inode_info *ei = to_bch_ei(vinode);
959         struct btree_trans *trans;
960         struct btree_iter iter;
961         struct bkey_s_c k;
962         struct bkey_buf cur, prev;
963         struct bpos end = POS(ei->v.i_ino, (start + len) >> 9);
964         unsigned offset_into_extent, sectors;
965         bool have_extent = false;
966         u32 snapshot;
967         int ret = 0;
968
969         ret = fiemap_prep(&ei->v, info, start, &len, FIEMAP_FLAG_SYNC);
970         if (ret)
971                 return ret;
972
973         if (start + len < start)
974                 return -EINVAL;
975
976         start >>= 9;
977
978         bch2_bkey_buf_init(&cur);
979         bch2_bkey_buf_init(&prev);
980         trans = bch2_trans_get(c);
981 retry:
982         bch2_trans_begin(trans);
983
984         ret = bch2_subvolume_get_snapshot(trans, ei->ei_subvol, &snapshot);
985         if (ret)
986                 goto err;
987
988         bch2_trans_iter_init(trans, &iter, BTREE_ID_extents,
989                              SPOS(ei->v.i_ino, start, snapshot), 0);
990
991         while (!(ret = btree_trans_too_many_iters(trans)) &&
992                (k = bch2_btree_iter_peek_upto(&iter, end)).k &&
993                !(ret = bkey_err(k))) {
994                 enum btree_id data_btree = BTREE_ID_extents;
995
996                 if (!bkey_extent_is_data(k.k) &&
997                     k.k->type != KEY_TYPE_reservation) {
998                         bch2_btree_iter_advance(&iter);
999                         continue;
1000                 }
1001
1002                 offset_into_extent      = iter.pos.offset -
1003                         bkey_start_offset(k.k);
1004                 sectors                 = k.k->size - offset_into_extent;
1005
1006                 bch2_bkey_buf_reassemble(&cur, c, k);
1007
1008                 ret = bch2_read_indirect_extent(trans, &data_btree,
1009                                         &offset_into_extent, &cur);
1010                 if (ret)
1011                         break;
1012
1013                 k = bkey_i_to_s_c(cur.k);
1014                 bch2_bkey_buf_realloc(&prev, c, k.k->u64s);
1015
1016                 sectors = min(sectors, k.k->size - offset_into_extent);
1017
1018                 bch2_cut_front(POS(k.k->p.inode,
1019                                    bkey_start_offset(k.k) +
1020                                    offset_into_extent),
1021                                cur.k);
1022                 bch2_key_resize(&cur.k->k, sectors);
1023                 cur.k->k.p = iter.pos;
1024                 cur.k->k.p.offset += cur.k->k.size;
1025
1026                 if (have_extent) {
1027                         bch2_trans_unlock(trans);
1028                         ret = bch2_fill_extent(c, info,
1029                                         bkey_i_to_s_c(prev.k), 0);
1030                         if (ret)
1031                                 break;
1032                 }
1033
1034                 bkey_copy(prev.k, cur.k);
1035                 have_extent = true;
1036
1037                 bch2_btree_iter_set_pos(&iter,
1038                         POS(iter.pos.inode, iter.pos.offset + sectors));
1039         }
1040         start = iter.pos.offset;
1041         bch2_trans_iter_exit(trans, &iter);
1042 err:
1043         if (bch2_err_matches(ret, BCH_ERR_transaction_restart))
1044                 goto retry;
1045
1046         if (!ret && have_extent) {
1047                 bch2_trans_unlock(trans);
1048                 ret = bch2_fill_extent(c, info, bkey_i_to_s_c(prev.k),
1049                                        FIEMAP_EXTENT_LAST);
1050         }
1051
1052         bch2_trans_put(trans);
1053         bch2_bkey_buf_exit(&cur, c);
1054         bch2_bkey_buf_exit(&prev, c);
1055         return ret < 0 ? ret : 0;
1056 }
1057
1058 static const struct vm_operations_struct bch_vm_ops = {
1059         .fault          = bch2_page_fault,
1060         .map_pages      = filemap_map_pages,
1061         .page_mkwrite   = bch2_page_mkwrite,
1062 };
1063
1064 static int bch2_mmap(struct file *file, struct vm_area_struct *vma)
1065 {
1066         file_accessed(file);
1067
1068         vma->vm_ops = &bch_vm_ops;
1069         return 0;
1070 }
1071
1072 /* Directories: */
1073
1074 static loff_t bch2_dir_llseek(struct file *file, loff_t offset, int whence)
1075 {
1076         return generic_file_llseek_size(file, offset, whence,
1077                                         S64_MAX, S64_MAX);
1078 }
1079
1080 static int bch2_vfs_readdir(struct file *file, struct dir_context *ctx)
1081 {
1082         struct bch_inode_info *inode = file_bch_inode(file);
1083         struct bch_fs *c = inode->v.i_sb->s_fs_info;
1084
1085         if (!dir_emit_dots(file, ctx))
1086                 return 0;
1087
1088         int ret = bch2_readdir(c, inode_inum(inode), ctx);
1089
1090         bch_err_fn(c, ret);
1091         return bch2_err_class(ret);
1092 }
1093
1094 static int bch2_open(struct inode *vinode, struct file *file)
1095 {
1096         if (file->f_flags & (O_WRONLY|O_RDWR)) {
1097                 struct bch_inode_info *inode = to_bch_ei(vinode);
1098                 struct bch_fs *c = inode->v.i_sb->s_fs_info;
1099
1100                 int ret = bch2_subvol_is_ro(c, inode->ei_subvol);
1101                 if (ret)
1102                         return ret;
1103         }
1104
1105         return generic_file_open(vinode, file);
1106 }
1107
1108 static const struct file_operations bch_file_operations = {
1109         .open           = bch2_open,
1110         .llseek         = bch2_llseek,
1111         .read_iter      = bch2_read_iter,
1112         .write_iter     = bch2_write_iter,
1113         .mmap           = bch2_mmap,
1114         .fsync          = bch2_fsync,
1115         .splice_read    = filemap_splice_read,
1116         .splice_write   = iter_file_splice_write,
1117         .fallocate      = bch2_fallocate_dispatch,
1118         .unlocked_ioctl = bch2_fs_file_ioctl,
1119 #ifdef CONFIG_COMPAT
1120         .compat_ioctl   = bch2_compat_fs_ioctl,
1121 #endif
1122         .remap_file_range = bch2_remap_file_range,
1123 };
1124
1125 static const struct inode_operations bch_file_inode_operations = {
1126         .getattr        = bch2_getattr,
1127         .setattr        = bch2_setattr,
1128         .fiemap         = bch2_fiemap,
1129         .listxattr      = bch2_xattr_list,
1130 #ifdef CONFIG_BCACHEFS_POSIX_ACL
1131         .get_acl        = bch2_get_acl,
1132         .set_acl        = bch2_set_acl,
1133 #endif
1134 };
1135
1136 static const struct inode_operations bch_dir_inode_operations = {
1137         .lookup         = bch2_lookup,
1138         .create         = bch2_create,
1139         .link           = bch2_link,
1140         .unlink         = bch2_unlink,
1141         .symlink        = bch2_symlink,
1142         .mkdir          = bch2_mkdir,
1143         .rmdir          = bch2_unlink,
1144         .mknod          = bch2_mknod,
1145         .rename         = bch2_rename2,
1146         .getattr        = bch2_getattr,
1147         .setattr        = bch2_setattr,
1148         .tmpfile        = bch2_tmpfile,
1149         .listxattr      = bch2_xattr_list,
1150 #ifdef CONFIG_BCACHEFS_POSIX_ACL
1151         .get_acl        = bch2_get_acl,
1152         .set_acl        = bch2_set_acl,
1153 #endif
1154 };
1155
1156 static const struct file_operations bch_dir_file_operations = {
1157         .llseek         = bch2_dir_llseek,
1158         .read           = generic_read_dir,
1159         .iterate_shared = bch2_vfs_readdir,
1160         .fsync          = bch2_fsync,
1161         .unlocked_ioctl = bch2_fs_file_ioctl,
1162 #ifdef CONFIG_COMPAT
1163         .compat_ioctl   = bch2_compat_fs_ioctl,
1164 #endif
1165 };
1166
1167 static const struct inode_operations bch_symlink_inode_operations = {
1168         .get_link       = page_get_link,
1169         .getattr        = bch2_getattr,
1170         .setattr        = bch2_setattr,
1171         .listxattr      = bch2_xattr_list,
1172 #ifdef CONFIG_BCACHEFS_POSIX_ACL
1173         .get_acl        = bch2_get_acl,
1174         .set_acl        = bch2_set_acl,
1175 #endif
1176 };
1177
1178 static const struct inode_operations bch_special_inode_operations = {
1179         .getattr        = bch2_getattr,
1180         .setattr        = bch2_setattr,
1181         .listxattr      = bch2_xattr_list,
1182 #ifdef CONFIG_BCACHEFS_POSIX_ACL
1183         .get_acl        = bch2_get_acl,
1184         .set_acl        = bch2_set_acl,
1185 #endif
1186 };
1187
1188 static const struct address_space_operations bch_address_space_operations = {
1189         .read_folio     = bch2_read_folio,
1190         .writepages     = bch2_writepages,
1191         .readahead      = bch2_readahead,
1192         .dirty_folio    = filemap_dirty_folio,
1193         .write_begin    = bch2_write_begin,
1194         .write_end      = bch2_write_end,
1195         .invalidate_folio = bch2_invalidate_folio,
1196         .release_folio  = bch2_release_folio,
1197         .direct_IO      = noop_direct_IO,
1198 #ifdef CONFIG_MIGRATION
1199         .migrate_folio  = filemap_migrate_folio,
1200 #endif
1201         .error_remove_folio = generic_error_remove_folio,
1202 };
1203
1204 struct bcachefs_fid {
1205         u64             inum;
1206         u32             subvol;
1207         u32             gen;
1208 } __packed;
1209
1210 struct bcachefs_fid_with_parent {
1211         struct bcachefs_fid     fid;
1212         struct bcachefs_fid     dir;
1213 } __packed;
1214
1215 static int bcachefs_fid_valid(int fh_len, int fh_type)
1216 {
1217         switch (fh_type) {
1218         case FILEID_BCACHEFS_WITHOUT_PARENT:
1219                 return fh_len == sizeof(struct bcachefs_fid) / sizeof(u32);
1220         case FILEID_BCACHEFS_WITH_PARENT:
1221                 return fh_len == sizeof(struct bcachefs_fid_with_parent) / sizeof(u32);
1222         default:
1223                 return false;
1224         }
1225 }
1226
1227 static struct bcachefs_fid bch2_inode_to_fid(struct bch_inode_info *inode)
1228 {
1229         return (struct bcachefs_fid) {
1230                 .inum   = inode->ei_inode.bi_inum,
1231                 .subvol = inode->ei_subvol,
1232                 .gen    = inode->ei_inode.bi_generation,
1233         };
1234 }
1235
1236 static int bch2_encode_fh(struct inode *vinode, u32 *fh, int *len,
1237                           struct inode *vdir)
1238 {
1239         struct bch_inode_info *inode    = to_bch_ei(vinode);
1240         struct bch_inode_info *dir      = to_bch_ei(vdir);
1241         int min_len;
1242
1243         if (!S_ISDIR(inode->v.i_mode) && dir) {
1244                 struct bcachefs_fid_with_parent *fid = (void *) fh;
1245
1246                 min_len = sizeof(*fid) / sizeof(u32);
1247                 if (*len < min_len) {
1248                         *len = min_len;
1249                         return FILEID_INVALID;
1250                 }
1251
1252                 fid->fid = bch2_inode_to_fid(inode);
1253                 fid->dir = bch2_inode_to_fid(dir);
1254
1255                 *len = min_len;
1256                 return FILEID_BCACHEFS_WITH_PARENT;
1257         } else {
1258                 struct bcachefs_fid *fid = (void *) fh;
1259
1260                 min_len = sizeof(*fid) / sizeof(u32);
1261                 if (*len < min_len) {
1262                         *len = min_len;
1263                         return FILEID_INVALID;
1264                 }
1265                 *fid = bch2_inode_to_fid(inode);
1266
1267                 *len = min_len;
1268                 return FILEID_BCACHEFS_WITHOUT_PARENT;
1269         }
1270 }
1271
1272 static struct inode *bch2_nfs_get_inode(struct super_block *sb,
1273                                         struct bcachefs_fid fid)
1274 {
1275         struct bch_fs *c = sb->s_fs_info;
1276         struct inode *vinode = bch2_vfs_inode_get(c, (subvol_inum) {
1277                                     .subvol = fid.subvol,
1278                                     .inum = fid.inum,
1279         });
1280         if (!IS_ERR(vinode) && vinode->i_generation != fid.gen) {
1281                 iput(vinode);
1282                 vinode = ERR_PTR(-ESTALE);
1283         }
1284         return vinode;
1285 }
1286
1287 static struct dentry *bch2_fh_to_dentry(struct super_block *sb, struct fid *_fid,
1288                 int fh_len, int fh_type)
1289 {
1290         struct bcachefs_fid *fid = (void *) _fid;
1291
1292         if (!bcachefs_fid_valid(fh_len, fh_type))
1293                 return NULL;
1294
1295         return d_obtain_alias(bch2_nfs_get_inode(sb, *fid));
1296 }
1297
1298 static struct dentry *bch2_fh_to_parent(struct super_block *sb, struct fid *_fid,
1299                 int fh_len, int fh_type)
1300 {
1301         struct bcachefs_fid_with_parent *fid = (void *) _fid;
1302
1303         if (!bcachefs_fid_valid(fh_len, fh_type) ||
1304             fh_type != FILEID_BCACHEFS_WITH_PARENT)
1305                 return NULL;
1306
1307         return d_obtain_alias(bch2_nfs_get_inode(sb, fid->dir));
1308 }
1309
1310 static struct dentry *bch2_get_parent(struct dentry *child)
1311 {
1312         struct bch_inode_info *inode = to_bch_ei(child->d_inode);
1313         struct bch_fs *c = inode->v.i_sb->s_fs_info;
1314         subvol_inum parent_inum = {
1315                 .subvol = inode->ei_inode.bi_parent_subvol ?:
1316                         inode->ei_subvol,
1317                 .inum = inode->ei_inode.bi_dir,
1318         };
1319
1320         return d_obtain_alias(bch2_vfs_inode_get(c, parent_inum));
1321 }
1322
1323 static int bch2_get_name(struct dentry *parent, char *name, struct dentry *child)
1324 {
1325         struct bch_inode_info *inode    = to_bch_ei(child->d_inode);
1326         struct bch_inode_info *dir      = to_bch_ei(parent->d_inode);
1327         struct bch_fs *c = inode->v.i_sb->s_fs_info;
1328         struct btree_trans *trans;
1329         struct btree_iter iter1;
1330         struct btree_iter iter2;
1331         struct bkey_s_c k;
1332         struct bkey_s_c_dirent d;
1333         struct bch_inode_unpacked inode_u;
1334         subvol_inum target;
1335         u32 snapshot;
1336         struct qstr dirent_name;
1337         unsigned name_len = 0;
1338         int ret;
1339
1340         if (!S_ISDIR(dir->v.i_mode))
1341                 return -EINVAL;
1342
1343         trans = bch2_trans_get(c);
1344
1345         bch2_trans_iter_init(trans, &iter1, BTREE_ID_dirents,
1346                              POS(dir->ei_inode.bi_inum, 0), 0);
1347         bch2_trans_iter_init(trans, &iter2, BTREE_ID_dirents,
1348                              POS(dir->ei_inode.bi_inum, 0), 0);
1349 retry:
1350         bch2_trans_begin(trans);
1351
1352         ret = bch2_subvolume_get_snapshot(trans, dir->ei_subvol, &snapshot);
1353         if (ret)
1354                 goto err;
1355
1356         bch2_btree_iter_set_snapshot(&iter1, snapshot);
1357         bch2_btree_iter_set_snapshot(&iter2, snapshot);
1358
1359         ret = bch2_inode_find_by_inum_trans(trans, inode_inum(inode), &inode_u);
1360         if (ret)
1361                 goto err;
1362
1363         if (inode_u.bi_dir == dir->ei_inode.bi_inum) {
1364                 bch2_btree_iter_set_pos(&iter1, POS(inode_u.bi_dir, inode_u.bi_dir_offset));
1365
1366                 k = bch2_btree_iter_peek_slot(&iter1);
1367                 ret = bkey_err(k);
1368                 if (ret)
1369                         goto err;
1370
1371                 if (k.k->type != KEY_TYPE_dirent) {
1372                         ret = -BCH_ERR_ENOENT_dirent_doesnt_match_inode;
1373                         goto err;
1374                 }
1375
1376                 d = bkey_s_c_to_dirent(k);
1377                 ret = bch2_dirent_read_target(trans, inode_inum(dir), d, &target);
1378                 if (ret > 0)
1379                         ret = -BCH_ERR_ENOENT_dirent_doesnt_match_inode;
1380                 if (ret)
1381                         goto err;
1382
1383                 if (target.subvol       == inode->ei_subvol &&
1384                     target.inum         == inode->ei_inode.bi_inum)
1385                         goto found;
1386         } else {
1387                 /*
1388                  * File with multiple hardlinks and our backref is to the wrong
1389                  * directory - linear search:
1390                  */
1391                 for_each_btree_key_continue_norestart(iter2, 0, k, ret) {
1392                         if (k.k->p.inode > dir->ei_inode.bi_inum)
1393                                 break;
1394
1395                         if (k.k->type != KEY_TYPE_dirent)
1396                                 continue;
1397
1398                         d = bkey_s_c_to_dirent(k);
1399                         ret = bch2_dirent_read_target(trans, inode_inum(dir), d, &target);
1400                         if (ret < 0)
1401                                 break;
1402                         if (ret)
1403                                 continue;
1404
1405                         if (target.subvol       == inode->ei_subvol &&
1406                             target.inum         == inode->ei_inode.bi_inum)
1407                                 goto found;
1408                 }
1409         }
1410
1411         ret = -ENOENT;
1412         goto err;
1413 found:
1414         dirent_name = bch2_dirent_get_name(d);
1415
1416         name_len = min_t(unsigned, dirent_name.len, NAME_MAX);
1417         memcpy(name, dirent_name.name, name_len);
1418         name[name_len] = '\0';
1419 err:
1420         if (bch2_err_matches(ret, BCH_ERR_transaction_restart))
1421                 goto retry;
1422
1423         bch2_trans_iter_exit(trans, &iter1);
1424         bch2_trans_iter_exit(trans, &iter2);
1425         bch2_trans_put(trans);
1426
1427         return ret;
1428 }
1429
1430 static const struct export_operations bch_export_ops = {
1431         .encode_fh      = bch2_encode_fh,
1432         .fh_to_dentry   = bch2_fh_to_dentry,
1433         .fh_to_parent   = bch2_fh_to_parent,
1434         .get_parent     = bch2_get_parent,
1435         .get_name       = bch2_get_name,
1436 };
1437
1438 static void bch2_vfs_inode_init(struct btree_trans *trans, subvol_inum inum,
1439                                 struct bch_inode_info *inode,
1440                                 struct bch_inode_unpacked *bi,
1441                                 struct bch_subvolume *subvol)
1442 {
1443         bch2_iget5_set(&inode->v, &inum);
1444         bch2_inode_update_after_write(trans, inode, bi, ~0);
1445
1446         if (BCH_SUBVOLUME_SNAP(subvol))
1447                 set_bit(EI_INODE_SNAPSHOT, &inode->ei_flags);
1448         else
1449                 clear_bit(EI_INODE_SNAPSHOT, &inode->ei_flags);
1450
1451         inode->v.i_blocks       = bi->bi_sectors;
1452         inode->v.i_ino          = bi->bi_inum;
1453         inode->v.i_rdev         = bi->bi_dev;
1454         inode->v.i_generation   = bi->bi_generation;
1455         inode->v.i_size         = bi->bi_size;
1456
1457         inode->ei_flags         = 0;
1458         inode->ei_quota_reserved = 0;
1459         inode->ei_qid           = bch_qid(bi);
1460         inode->ei_subvol        = inum.subvol;
1461
1462         inode->v.i_mapping->a_ops = &bch_address_space_operations;
1463
1464         switch (inode->v.i_mode & S_IFMT) {
1465         case S_IFREG:
1466                 inode->v.i_op   = &bch_file_inode_operations;
1467                 inode->v.i_fop  = &bch_file_operations;
1468                 break;
1469         case S_IFDIR:
1470                 inode->v.i_op   = &bch_dir_inode_operations;
1471                 inode->v.i_fop  = &bch_dir_file_operations;
1472                 break;
1473         case S_IFLNK:
1474                 inode_nohighmem(&inode->v);
1475                 inode->v.i_op   = &bch_symlink_inode_operations;
1476                 break;
1477         default:
1478                 init_special_inode(&inode->v, inode->v.i_mode, inode->v.i_rdev);
1479                 inode->v.i_op   = &bch_special_inode_operations;
1480                 break;
1481         }
1482
1483         mapping_set_large_folios(inode->v.i_mapping);
1484 }
1485
1486 static struct inode *bch2_alloc_inode(struct super_block *sb)
1487 {
1488         struct bch_inode_info *inode;
1489
1490         inode = kmem_cache_alloc(bch2_inode_cache, GFP_NOFS);
1491         if (!inode)
1492                 return NULL;
1493
1494         inode_init_once(&inode->v);
1495         mutex_init(&inode->ei_update_lock);
1496         two_state_lock_init(&inode->ei_pagecache_lock);
1497         INIT_LIST_HEAD(&inode->ei_vfs_inode_list);
1498         mutex_init(&inode->ei_quota_lock);
1499
1500         return &inode->v;
1501 }
1502
1503 static void bch2_i_callback(struct rcu_head *head)
1504 {
1505         struct inode *vinode = container_of(head, struct inode, i_rcu);
1506         struct bch_inode_info *inode = to_bch_ei(vinode);
1507
1508         kmem_cache_free(bch2_inode_cache, inode);
1509 }
1510
1511 static void bch2_destroy_inode(struct inode *vinode)
1512 {
1513         call_rcu(&vinode->i_rcu, bch2_i_callback);
1514 }
1515
1516 static int inode_update_times_fn(struct btree_trans *trans,
1517                                  struct bch_inode_info *inode,
1518                                  struct bch_inode_unpacked *bi,
1519                                  void *p)
1520 {
1521         struct bch_fs *c = inode->v.i_sb->s_fs_info;
1522
1523         bi->bi_atime    = timespec_to_bch2_time(c, inode_get_atime(&inode->v));
1524         bi->bi_mtime    = timespec_to_bch2_time(c, inode_get_mtime(&inode->v));
1525         bi->bi_ctime    = timespec_to_bch2_time(c, inode_get_ctime(&inode->v));
1526
1527         return 0;
1528 }
1529
1530 static int bch2_vfs_write_inode(struct inode *vinode,
1531                                 struct writeback_control *wbc)
1532 {
1533         struct bch_fs *c = vinode->i_sb->s_fs_info;
1534         struct bch_inode_info *inode = to_bch_ei(vinode);
1535         int ret;
1536
1537         mutex_lock(&inode->ei_update_lock);
1538         ret = bch2_write_inode(c, inode, inode_update_times_fn, NULL,
1539                                ATTR_ATIME|ATTR_MTIME|ATTR_CTIME);
1540         mutex_unlock(&inode->ei_update_lock);
1541
1542         return bch2_err_class(ret);
1543 }
1544
1545 static void bch2_evict_inode(struct inode *vinode)
1546 {
1547         struct bch_fs *c = vinode->i_sb->s_fs_info;
1548         struct bch_inode_info *inode = to_bch_ei(vinode);
1549
1550         truncate_inode_pages_final(&inode->v.i_data);
1551
1552         clear_inode(&inode->v);
1553
1554         BUG_ON(!is_bad_inode(&inode->v) && inode->ei_quota_reserved);
1555
1556         if (!inode->v.i_nlink && !is_bad_inode(&inode->v)) {
1557                 bch2_quota_acct(c, inode->ei_qid, Q_SPC, -((s64) inode->v.i_blocks),
1558                                 KEY_TYPE_QUOTA_WARN);
1559                 bch2_quota_acct(c, inode->ei_qid, Q_INO, -1,
1560                                 KEY_TYPE_QUOTA_WARN);
1561                 bch2_inode_rm(c, inode_inum(inode));
1562         }
1563
1564         mutex_lock(&c->vfs_inodes_lock);
1565         list_del_init(&inode->ei_vfs_inode_list);
1566         mutex_unlock(&c->vfs_inodes_lock);
1567 }
1568
1569 void bch2_evict_subvolume_inodes(struct bch_fs *c, snapshot_id_list *s)
1570 {
1571         struct bch_inode_info *inode;
1572         DARRAY(struct bch_inode_info *) grabbed;
1573         bool clean_pass = false, this_pass_clean;
1574
1575         /*
1576          * Initially, we scan for inodes without I_DONTCACHE, then mark them to
1577          * be pruned with d_mark_dontcache().
1578          *
1579          * Once we've had a clean pass where we didn't find any inodes without
1580          * I_DONTCACHE, we wait for them to be freed:
1581          */
1582
1583         darray_init(&grabbed);
1584         darray_make_room(&grabbed, 1024);
1585 again:
1586         cond_resched();
1587         this_pass_clean = true;
1588
1589         mutex_lock(&c->vfs_inodes_lock);
1590         list_for_each_entry(inode, &c->vfs_inodes_list, ei_vfs_inode_list) {
1591                 if (!snapshot_list_has_id(s, inode->ei_subvol))
1592                         continue;
1593
1594                 if (!(inode->v.i_state & I_DONTCACHE) &&
1595                     !(inode->v.i_state & I_FREEING) &&
1596                     igrab(&inode->v)) {
1597                         this_pass_clean = false;
1598
1599                         if (darray_push_gfp(&grabbed, inode, GFP_ATOMIC|__GFP_NOWARN)) {
1600                                 iput(&inode->v);
1601                                 break;
1602                         }
1603                 } else if (clean_pass && this_pass_clean) {
1604                         wait_queue_head_t *wq = bit_waitqueue(&inode->v.i_state, __I_NEW);
1605                         DEFINE_WAIT_BIT(wait, &inode->v.i_state, __I_NEW);
1606
1607                         prepare_to_wait(wq, &wait.wq_entry, TASK_UNINTERRUPTIBLE);
1608                         mutex_unlock(&c->vfs_inodes_lock);
1609
1610                         schedule();
1611                         finish_wait(wq, &wait.wq_entry);
1612                         goto again;
1613                 }
1614         }
1615         mutex_unlock(&c->vfs_inodes_lock);
1616
1617         darray_for_each(grabbed, i) {
1618                 inode = *i;
1619                 d_mark_dontcache(&inode->v);
1620                 d_prune_aliases(&inode->v);
1621                 iput(&inode->v);
1622         }
1623         grabbed.nr = 0;
1624
1625         if (!clean_pass || !this_pass_clean) {
1626                 clean_pass = this_pass_clean;
1627                 goto again;
1628         }
1629
1630         darray_exit(&grabbed);
1631 }
1632
1633 static int bch2_statfs(struct dentry *dentry, struct kstatfs *buf)
1634 {
1635         struct super_block *sb = dentry->d_sb;
1636         struct bch_fs *c = sb->s_fs_info;
1637         struct bch_fs_usage_short usage = bch2_fs_usage_read_short(c);
1638         unsigned shift = sb->s_blocksize_bits - 9;
1639         /*
1640          * this assumes inodes take up 64 bytes, which is a decent average
1641          * number:
1642          */
1643         u64 avail_inodes = ((usage.capacity - usage.used) << 3);
1644
1645         buf->f_type     = BCACHEFS_STATFS_MAGIC;
1646         buf->f_bsize    = sb->s_blocksize;
1647         buf->f_blocks   = usage.capacity >> shift;
1648         buf->f_bfree    = usage.free >> shift;
1649         buf->f_bavail   = avail_factor(usage.free) >> shift;
1650
1651         buf->f_files    = usage.nr_inodes + avail_inodes;
1652         buf->f_ffree    = avail_inodes;
1653
1654         buf->f_fsid     = uuid_to_fsid(c->sb.user_uuid.b);
1655         buf->f_namelen  = BCH_NAME_MAX;
1656
1657         return 0;
1658 }
1659
1660 static int bch2_sync_fs(struct super_block *sb, int wait)
1661 {
1662         struct bch_fs *c = sb->s_fs_info;
1663         int ret;
1664
1665         if (c->opts.journal_flush_disabled)
1666                 return 0;
1667
1668         if (!wait) {
1669                 bch2_journal_flush_async(&c->journal, NULL);
1670                 return 0;
1671         }
1672
1673         ret = bch2_journal_flush(&c->journal);
1674         return bch2_err_class(ret);
1675 }
1676
1677 static struct bch_fs *bch2_path_to_fs(const char *path)
1678 {
1679         struct bch_fs *c;
1680         dev_t dev;
1681         int ret;
1682
1683         ret = lookup_bdev(path, &dev);
1684         if (ret)
1685                 return ERR_PTR(ret);
1686
1687         c = bch2_dev_to_fs(dev);
1688         if (c)
1689                 closure_put(&c->cl);
1690         return c ?: ERR_PTR(-ENOENT);
1691 }
1692
1693 static int bch2_remount(struct super_block *sb, int *flags, char *data)
1694 {
1695         struct bch_fs *c = sb->s_fs_info;
1696         struct bch_opts opts = bch2_opts_empty();
1697         int ret;
1698
1699         ret = bch2_parse_mount_opts(c, &opts, data);
1700         if (ret)
1701                 goto err;
1702
1703         opt_set(opts, read_only, (*flags & SB_RDONLY) != 0);
1704
1705         if (opts.read_only != c->opts.read_only) {
1706                 down_write(&c->state_lock);
1707
1708                 if (opts.read_only) {
1709                         bch2_fs_read_only(c);
1710
1711                         sb->s_flags |= SB_RDONLY;
1712                 } else {
1713                         ret = bch2_fs_read_write(c);
1714                         if (ret) {
1715                                 bch_err(c, "error going rw: %i", ret);
1716                                 up_write(&c->state_lock);
1717                                 ret = -EINVAL;
1718                                 goto err;
1719                         }
1720
1721                         sb->s_flags &= ~SB_RDONLY;
1722                 }
1723
1724                 c->opts.read_only = opts.read_only;
1725
1726                 up_write(&c->state_lock);
1727         }
1728
1729         if (opt_defined(opts, errors))
1730                 c->opts.errors = opts.errors;
1731 err:
1732         return bch2_err_class(ret);
1733 }
1734
1735 static int bch2_show_devname(struct seq_file *seq, struct dentry *root)
1736 {
1737         struct bch_fs *c = root->d_sb->s_fs_info;
1738         bool first = true;
1739
1740         for_each_online_member(c, ca) {
1741                 if (!first)
1742                         seq_putc(seq, ':');
1743                 first = false;
1744                 seq_puts(seq, ca->disk_sb.sb_name);
1745         }
1746
1747         return 0;
1748 }
1749
1750 static int bch2_show_options(struct seq_file *seq, struct dentry *root)
1751 {
1752         struct bch_fs *c = root->d_sb->s_fs_info;
1753         enum bch_opt_id i;
1754         struct printbuf buf = PRINTBUF;
1755         int ret = 0;
1756
1757         for (i = 0; i < bch2_opts_nr; i++) {
1758                 const struct bch_option *opt = &bch2_opt_table[i];
1759                 u64 v = bch2_opt_get_by_id(&c->opts, i);
1760
1761                 if (!(opt->flags & OPT_MOUNT))
1762                         continue;
1763
1764                 if (v == bch2_opt_get_by_id(&bch2_opts_default, i))
1765                         continue;
1766
1767                 printbuf_reset(&buf);
1768                 bch2_opt_to_text(&buf, c, c->disk_sb.sb, opt, v,
1769                                  OPT_SHOW_MOUNT_STYLE);
1770                 seq_putc(seq, ',');
1771                 seq_puts(seq, buf.buf);
1772         }
1773
1774         if (buf.allocation_failure)
1775                 ret = -ENOMEM;
1776         printbuf_exit(&buf);
1777         return ret;
1778 }
1779
1780 static void bch2_put_super(struct super_block *sb)
1781 {
1782         struct bch_fs *c = sb->s_fs_info;
1783
1784         __bch2_fs_stop(c);
1785 }
1786
1787 /*
1788  * bcachefs doesn't currently integrate intwrite freeze protection but the
1789  * internal write references serve the same purpose. Therefore reuse the
1790  * read-only transition code to perform the quiesce. The caveat is that we don't
1791  * currently have the ability to block tasks that want a write reference while
1792  * the superblock is frozen. This is fine for now, but we should either add
1793  * blocking support or find a way to integrate sb_start_intwrite() and friends.
1794  */
1795 static int bch2_freeze(struct super_block *sb)
1796 {
1797         struct bch_fs *c = sb->s_fs_info;
1798
1799         down_write(&c->state_lock);
1800         bch2_fs_read_only(c);
1801         up_write(&c->state_lock);
1802         return 0;
1803 }
1804
1805 static int bch2_unfreeze(struct super_block *sb)
1806 {
1807         struct bch_fs *c = sb->s_fs_info;
1808         int ret;
1809
1810         if (test_bit(BCH_FS_emergency_ro, &c->flags))
1811                 return 0;
1812
1813         down_write(&c->state_lock);
1814         ret = bch2_fs_read_write(c);
1815         up_write(&c->state_lock);
1816         return ret;
1817 }
1818
1819 static const struct super_operations bch_super_operations = {
1820         .alloc_inode    = bch2_alloc_inode,
1821         .destroy_inode  = bch2_destroy_inode,
1822         .write_inode    = bch2_vfs_write_inode,
1823         .evict_inode    = bch2_evict_inode,
1824         .sync_fs        = bch2_sync_fs,
1825         .statfs         = bch2_statfs,
1826         .show_devname   = bch2_show_devname,
1827         .show_options   = bch2_show_options,
1828         .remount_fs     = bch2_remount,
1829         .put_super      = bch2_put_super,
1830         .freeze_fs      = bch2_freeze,
1831         .unfreeze_fs    = bch2_unfreeze,
1832 };
1833
1834 static int bch2_set_super(struct super_block *s, void *data)
1835 {
1836         s->s_fs_info = data;
1837         return 0;
1838 }
1839
1840 static int bch2_noset_super(struct super_block *s, void *data)
1841 {
1842         return -EBUSY;
1843 }
1844
1845 typedef DARRAY(struct bch_fs *) darray_fs;
1846
1847 static int bch2_test_super(struct super_block *s, void *data)
1848 {
1849         struct bch_fs *c = s->s_fs_info;
1850         darray_fs *d = data;
1851
1852         if (!c)
1853                 return false;
1854
1855         darray_for_each(*d, i)
1856                 if (c != *i)
1857                         return false;
1858         return true;
1859 }
1860
1861 static struct dentry *bch2_mount(struct file_system_type *fs_type,
1862                                  int flags, const char *dev_name, void *data)
1863 {
1864         struct bch_fs *c;
1865         struct super_block *sb;
1866         struct inode *vinode;
1867         struct bch_opts opts = bch2_opts_empty();
1868         int ret;
1869
1870         opt_set(opts, read_only, (flags & SB_RDONLY) != 0);
1871
1872         ret = bch2_parse_mount_opts(NULL, &opts, data);
1873         if (ret)
1874                 return ERR_PTR(ret);
1875
1876         if (!dev_name || strlen(dev_name) == 0)
1877                 return ERR_PTR(-EINVAL);
1878
1879         darray_str devs;
1880         ret = bch2_split_devs(dev_name, &devs);
1881         if (ret)
1882                 return ERR_PTR(ret);
1883
1884         darray_fs devs_to_fs = {};
1885         darray_for_each(devs, i) {
1886                 ret = darray_push(&devs_to_fs, bch2_path_to_fs(*i));
1887                 if (ret) {
1888                         sb = ERR_PTR(ret);
1889                         goto got_sb;
1890                 }
1891         }
1892
1893         sb = sget(fs_type, bch2_test_super, bch2_noset_super, flags|SB_NOSEC, &devs_to_fs);
1894         if (!IS_ERR(sb))
1895                 goto got_sb;
1896
1897         c = bch2_fs_open(devs.data, devs.nr, opts);
1898         if (IS_ERR(c)) {
1899                 sb = ERR_CAST(c);
1900                 goto got_sb;
1901         }
1902
1903         /* Some options can't be parsed until after the fs is started: */
1904         ret = bch2_parse_mount_opts(c, &opts, data);
1905         if (ret) {
1906                 bch2_fs_stop(c);
1907                 sb = ERR_PTR(ret);
1908                 goto got_sb;
1909         }
1910
1911         bch2_opts_apply(&c->opts, opts);
1912
1913         sb = sget(fs_type, NULL, bch2_set_super, flags|SB_NOSEC, c);
1914         if (IS_ERR(sb))
1915                 bch2_fs_stop(c);
1916 got_sb:
1917         darray_exit(&devs_to_fs);
1918         bch2_darray_str_exit(&devs);
1919
1920         if (IS_ERR(sb)) {
1921                 ret = PTR_ERR(sb);
1922                 ret = bch2_err_class(ret);
1923                 return ERR_PTR(ret);
1924         }
1925
1926         c = sb->s_fs_info;
1927
1928         if (sb->s_root) {
1929                 if ((flags ^ sb->s_flags) & SB_RDONLY) {
1930                         ret = -EBUSY;
1931                         goto err_put_super;
1932                 }
1933                 goto out;
1934         }
1935
1936         sb->s_blocksize         = block_bytes(c);
1937         sb->s_blocksize_bits    = ilog2(block_bytes(c));
1938         sb->s_maxbytes          = MAX_LFS_FILESIZE;
1939         sb->s_op                = &bch_super_operations;
1940         sb->s_export_op         = &bch_export_ops;
1941 #ifdef CONFIG_BCACHEFS_QUOTA
1942         sb->s_qcop              = &bch2_quotactl_operations;
1943         sb->s_quota_types       = QTYPE_MASK_USR|QTYPE_MASK_GRP|QTYPE_MASK_PRJ;
1944 #endif
1945         sb->s_xattr             = bch2_xattr_handlers;
1946         sb->s_magic             = BCACHEFS_STATFS_MAGIC;
1947         sb->s_time_gran         = c->sb.nsec_per_time_unit;
1948         sb->s_time_min          = div_s64(S64_MIN, c->sb.time_units_per_sec) + 1;
1949         sb->s_time_max          = div_s64(S64_MAX, c->sb.time_units_per_sec);
1950         sb->s_uuid              = c->sb.user_uuid;
1951         c->vfs_sb               = sb;
1952         strscpy(sb->s_id, c->name, sizeof(sb->s_id));
1953
1954         ret = super_setup_bdi(sb);
1955         if (ret)
1956                 goto err_put_super;
1957
1958         sb->s_bdi->ra_pages             = VM_READAHEAD_PAGES;
1959
1960         for_each_online_member(c, ca) {
1961                 struct block_device *bdev = ca->disk_sb.bdev;
1962
1963                 /* XXX: create an anonymous device for multi device filesystems */
1964                 sb->s_bdev      = bdev;
1965                 sb->s_dev       = bdev->bd_dev;
1966                 percpu_ref_put(&ca->io_ref);
1967                 break;
1968         }
1969
1970         c->dev = sb->s_dev;
1971
1972 #ifdef CONFIG_BCACHEFS_POSIX_ACL
1973         if (c->opts.acl)
1974                 sb->s_flags     |= SB_POSIXACL;
1975 #endif
1976
1977         sb->s_shrink->seeks = 0;
1978
1979         vinode = bch2_vfs_inode_get(c, BCACHEFS_ROOT_SUBVOL_INUM);
1980         ret = PTR_ERR_OR_ZERO(vinode);
1981         bch_err_msg(c, ret, "mounting: error getting root inode");
1982         if (ret)
1983                 goto err_put_super;
1984
1985         sb->s_root = d_make_root(vinode);
1986         if (!sb->s_root) {
1987                 bch_err(c, "error mounting: error allocating root dentry");
1988                 ret = -ENOMEM;
1989                 goto err_put_super;
1990         }
1991
1992         sb->s_flags |= SB_ACTIVE;
1993 out:
1994         return dget(sb->s_root);
1995
1996 err_put_super:
1997         deactivate_locked_super(sb);
1998         return ERR_PTR(bch2_err_class(ret));
1999 }
2000
2001 static void bch2_kill_sb(struct super_block *sb)
2002 {
2003         struct bch_fs *c = sb->s_fs_info;
2004
2005         generic_shutdown_super(sb);
2006         bch2_fs_free(c);
2007 }
2008
2009 static struct file_system_type bcache_fs_type = {
2010         .owner          = THIS_MODULE,
2011         .name           = "bcachefs",
2012         .mount          = bch2_mount,
2013         .kill_sb        = bch2_kill_sb,
2014         .fs_flags       = FS_REQUIRES_DEV,
2015 };
2016
2017 MODULE_ALIAS_FS("bcachefs");
2018
2019 void bch2_vfs_exit(void)
2020 {
2021         unregister_filesystem(&bcache_fs_type);
2022         kmem_cache_destroy(bch2_inode_cache);
2023 }
2024
2025 int __init bch2_vfs_init(void)
2026 {
2027         int ret = -ENOMEM;
2028
2029         bch2_inode_cache = KMEM_CACHE(bch_inode_info, SLAB_RECLAIM_ACCOUNT);
2030         if (!bch2_inode_cache)
2031                 goto err;
2032
2033         ret = register_filesystem(&bcache_fs_type);
2034         if (ret)
2035                 goto err;
2036
2037         return 0;
2038 err:
2039         bch2_vfs_exit();
2040         return ret;
2041 }
2042
2043 #endif /* NO_BCACHEFS_FS */