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