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