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