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