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