]> git.sesse.net Git - bcachefs-tools-debian/blob - libbcachefs/fs.c
Update bcachefs sources to ea47add37d bcachefs: More errcode cleanup
[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(&init_user_ns, attr->ia_uid);
671
672         if (attr->ia_valid & ATTR_GID)
673                 qid.q[QTYP_GRP] = from_kgid(&init_user_ns, 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 dentry *dentry, umode_t mode)
783 {
784         struct bch_inode_info *inode =
785                 __bch2_create(mnt_userns, to_bch_ei(vdir), dentry, mode, 0,
786                               (subvol_inum) { 0 }, BCH_CREATE_TMPFILE);
787
788         if (IS_ERR(inode))
789                 return bch2_err_class(PTR_ERR(inode));
790
791         d_mark_tmpfile(dentry, &inode->v);
792         d_instantiate(dentry, &inode->v);
793         return 0;
794 }
795
796 static int bch2_fill_extent(struct bch_fs *c,
797                             struct fiemap_extent_info *info,
798                             struct bkey_s_c k, unsigned flags)
799 {
800         if (bkey_extent_is_direct_data(k.k)) {
801                 struct bkey_ptrs_c ptrs = bch2_bkey_ptrs_c(k);
802                 const union bch_extent_entry *entry;
803                 struct extent_ptr_decoded p;
804                 int ret;
805
806                 if (k.k->type == KEY_TYPE_reflink_v)
807                         flags |= FIEMAP_EXTENT_SHARED;
808
809                 bkey_for_each_ptr_decode(k.k, ptrs, p, entry) {
810                         int flags2 = 0;
811                         u64 offset = p.ptr.offset;
812
813                         if (p.ptr.unwritten)
814                                 flags2 |= FIEMAP_EXTENT_UNWRITTEN;
815
816                         if (p.crc.compression_type)
817                                 flags2 |= FIEMAP_EXTENT_ENCODED;
818                         else
819                                 offset += p.crc.offset;
820
821                         if ((offset & (block_sectors(c) - 1)) ||
822                             (k.k->size & (block_sectors(c) - 1)))
823                                 flags2 |= FIEMAP_EXTENT_NOT_ALIGNED;
824
825                         ret = fiemap_fill_next_extent(info,
826                                                 bkey_start_offset(k.k) << 9,
827                                                 offset << 9,
828                                                 k.k->size << 9, flags|flags2);
829                         if (ret)
830                                 return ret;
831                 }
832
833                 return 0;
834         } else if (bkey_extent_is_inline_data(k.k)) {
835                 return fiemap_fill_next_extent(info,
836                                                bkey_start_offset(k.k) << 9,
837                                                0, k.k->size << 9,
838                                                flags|
839                                                FIEMAP_EXTENT_DATA_INLINE);
840         } else if (k.k->type == KEY_TYPE_reservation) {
841                 return fiemap_fill_next_extent(info,
842                                                bkey_start_offset(k.k) << 9,
843                                                0, k.k->size << 9,
844                                                flags|
845                                                FIEMAP_EXTENT_DELALLOC|
846                                                FIEMAP_EXTENT_UNWRITTEN);
847         } else {
848                 BUG();
849         }
850 }
851
852 static int bch2_fiemap(struct inode *vinode, struct fiemap_extent_info *info,
853                        u64 start, u64 len)
854 {
855         struct bch_fs *c = vinode->i_sb->s_fs_info;
856         struct bch_inode_info *ei = to_bch_ei(vinode);
857         struct btree_trans trans;
858         struct btree_iter iter;
859         struct bkey_s_c k;
860         struct bkey_buf cur, prev;
861         struct bpos end = POS(ei->v.i_ino, (start + len) >> 9);
862         unsigned offset_into_extent, sectors;
863         bool have_extent = false;
864         u32 snapshot;
865         int ret = 0;
866
867         ret = fiemap_prep(&ei->v, info, start, &len, FIEMAP_FLAG_SYNC);
868         if (ret)
869                 return ret;
870
871         if (start + len < start)
872                 return -EINVAL;
873
874         start >>= 9;
875
876         bch2_bkey_buf_init(&cur);
877         bch2_bkey_buf_init(&prev);
878         bch2_trans_init(&trans, c, 0, 0);
879 retry:
880         bch2_trans_begin(&trans);
881
882         ret = bch2_subvolume_get_snapshot(&trans, ei->ei_subvol, &snapshot);
883         if (ret)
884                 goto err;
885
886         bch2_trans_iter_init(&trans, &iter, BTREE_ID_extents,
887                              SPOS(ei->v.i_ino, start, snapshot), 0);
888
889         while (!(ret = btree_trans_too_many_iters(&trans)) &&
890                (k = bch2_btree_iter_peek_upto(&iter, end)).k &&
891                !(ret = bkey_err(k))) {
892                 enum btree_id data_btree = BTREE_ID_extents;
893
894                 if (!bkey_extent_is_data(k.k) &&
895                     k.k->type != KEY_TYPE_reservation) {
896                         bch2_btree_iter_advance(&iter);
897                         continue;
898                 }
899
900                 offset_into_extent      = iter.pos.offset -
901                         bkey_start_offset(k.k);
902                 sectors                 = k.k->size - offset_into_extent;
903
904                 bch2_bkey_buf_reassemble(&cur, c, k);
905
906                 ret = bch2_read_indirect_extent(&trans, &data_btree,
907                                         &offset_into_extent, &cur);
908                 if (ret)
909                         break;
910
911                 k = bkey_i_to_s_c(cur.k);
912                 bch2_bkey_buf_realloc(&prev, c, k.k->u64s);
913
914                 sectors = min(sectors, k.k->size - offset_into_extent);
915
916                 bch2_cut_front(POS(k.k->p.inode,
917                                    bkey_start_offset(k.k) +
918                                    offset_into_extent),
919                                cur.k);
920                 bch2_key_resize(&cur.k->k, sectors);
921                 cur.k->k.p = iter.pos;
922                 cur.k->k.p.offset += cur.k->k.size;
923
924                 if (have_extent) {
925                         ret = bch2_fill_extent(c, info,
926                                         bkey_i_to_s_c(prev.k), 0);
927                         if (ret)
928                                 break;
929                 }
930
931                 bkey_copy(prev.k, cur.k);
932                 have_extent = true;
933
934                 bch2_btree_iter_set_pos(&iter,
935                         POS(iter.pos.inode, iter.pos.offset + sectors));
936         }
937         start = iter.pos.offset;
938         bch2_trans_iter_exit(&trans, &iter);
939 err:
940         if (bch2_err_matches(ret, BCH_ERR_transaction_restart))
941                 goto retry;
942
943         if (!ret && have_extent)
944                 ret = bch2_fill_extent(c, info, bkey_i_to_s_c(prev.k),
945                                        FIEMAP_EXTENT_LAST);
946
947         bch2_trans_exit(&trans);
948         bch2_bkey_buf_exit(&cur, c);
949         bch2_bkey_buf_exit(&prev, c);
950         return ret < 0 ? ret : 0;
951 }
952
953 static const struct vm_operations_struct bch_vm_ops = {
954         .fault          = bch2_page_fault,
955         .map_pages      = filemap_map_pages,
956         .page_mkwrite   = bch2_page_mkwrite,
957 };
958
959 static int bch2_mmap(struct file *file, struct vm_area_struct *vma)
960 {
961         file_accessed(file);
962
963         vma->vm_ops = &bch_vm_ops;
964         return 0;
965 }
966
967 /* Directories: */
968
969 static loff_t bch2_dir_llseek(struct file *file, loff_t offset, int whence)
970 {
971         return generic_file_llseek_size(file, offset, whence,
972                                         S64_MAX, S64_MAX);
973 }
974
975 static int bch2_vfs_readdir(struct file *file, struct dir_context *ctx)
976 {
977         struct bch_inode_info *inode = file_bch_inode(file);
978         struct bch_fs *c = inode->v.i_sb->s_fs_info;
979
980         if (!dir_emit_dots(file, ctx))
981                 return 0;
982
983         return bch2_readdir(c, inode_inum(inode), ctx);
984 }
985
986 static const struct file_operations bch_file_operations = {
987         .llseek         = bch2_llseek,
988         .read_iter      = bch2_read_iter,
989         .write_iter     = bch2_write_iter,
990         .mmap           = bch2_mmap,
991         .open           = generic_file_open,
992         .fsync          = bch2_fsync,
993         .splice_read    = generic_file_splice_read,
994         .splice_write   = iter_file_splice_write,
995         .fallocate      = bch2_fallocate_dispatch,
996         .unlocked_ioctl = bch2_fs_file_ioctl,
997 #ifdef CONFIG_COMPAT
998         .compat_ioctl   = bch2_compat_fs_ioctl,
999 #endif
1000         .remap_file_range = bch2_remap_file_range,
1001 };
1002
1003 static const struct inode_operations bch_file_inode_operations = {
1004         .getattr        = bch2_getattr,
1005         .setattr        = bch2_setattr,
1006         .fiemap         = bch2_fiemap,
1007         .listxattr      = bch2_xattr_list,
1008 #ifdef CONFIG_BCACHEFS_POSIX_ACL
1009         .get_acl        = bch2_get_acl,
1010         .set_acl        = bch2_set_acl,
1011 #endif
1012 };
1013
1014 static const struct inode_operations bch_dir_inode_operations = {
1015         .lookup         = bch2_lookup,
1016         .create         = bch2_create,
1017         .link           = bch2_link,
1018         .unlink         = bch2_unlink,
1019         .symlink        = bch2_symlink,
1020         .mkdir          = bch2_mkdir,
1021         .rmdir          = bch2_unlink,
1022         .mknod          = bch2_mknod,
1023         .rename         = bch2_rename2,
1024         .getattr        = bch2_getattr,
1025         .setattr        = bch2_setattr,
1026         .tmpfile        = bch2_tmpfile,
1027         .listxattr      = bch2_xattr_list,
1028 #ifdef CONFIG_BCACHEFS_POSIX_ACL
1029         .get_acl        = bch2_get_acl,
1030         .set_acl        = bch2_set_acl,
1031 #endif
1032 };
1033
1034 static const struct file_operations bch_dir_file_operations = {
1035         .llseek         = bch2_dir_llseek,
1036         .read           = generic_read_dir,
1037         .iterate_shared = bch2_vfs_readdir,
1038         .fsync          = bch2_fsync,
1039         .unlocked_ioctl = bch2_fs_file_ioctl,
1040 #ifdef CONFIG_COMPAT
1041         .compat_ioctl   = bch2_compat_fs_ioctl,
1042 #endif
1043 };
1044
1045 static const struct inode_operations bch_symlink_inode_operations = {
1046         .get_link       = page_get_link,
1047         .getattr        = bch2_getattr,
1048         .setattr        = bch2_setattr,
1049         .listxattr      = bch2_xattr_list,
1050 #ifdef CONFIG_BCACHEFS_POSIX_ACL
1051         .get_acl        = bch2_get_acl,
1052         .set_acl        = bch2_set_acl,
1053 #endif
1054 };
1055
1056 static const struct inode_operations bch_special_inode_operations = {
1057         .getattr        = bch2_getattr,
1058         .setattr        = bch2_setattr,
1059         .listxattr      = bch2_xattr_list,
1060 #ifdef CONFIG_BCACHEFS_POSIX_ACL
1061         .get_acl        = bch2_get_acl,
1062         .set_acl        = bch2_set_acl,
1063 #endif
1064 };
1065
1066 static const struct address_space_operations bch_address_space_operations = {
1067         .read_folio     = bch2_read_folio,
1068         .writepages     = bch2_writepages,
1069         .readahead      = bch2_readahead,
1070         .dirty_folio    = filemap_dirty_folio,
1071         .write_begin    = bch2_write_begin,
1072         .write_end      = bch2_write_end,
1073         .invalidate_folio = bch2_invalidate_folio,
1074         .release_folio  = bch2_release_folio,
1075         .direct_IO      = noop_direct_IO,
1076 #ifdef CONFIG_MIGRATION
1077         .migrate_folio  = filemap_migrate_folio,
1078 #endif
1079         .error_remove_page = generic_error_remove_page,
1080 };
1081
1082 struct bcachefs_fid {
1083         u64             inum;
1084         u32             subvol;
1085         u32             gen;
1086 } __packed;
1087
1088 struct bcachefs_fid_with_parent {
1089         struct bcachefs_fid     fid;
1090         struct bcachefs_fid     dir;
1091 } __packed;
1092
1093 static int bcachefs_fid_valid(int fh_len, int fh_type)
1094 {
1095         switch (fh_type) {
1096         case FILEID_BCACHEFS_WITHOUT_PARENT:
1097                 return fh_len == sizeof(struct bcachefs_fid) / sizeof(u32);
1098         case FILEID_BCACHEFS_WITH_PARENT:
1099                 return fh_len == sizeof(struct bcachefs_fid_with_parent) / sizeof(u32);
1100         default:
1101                 return false;
1102         }
1103 }
1104
1105 static struct bcachefs_fid bch2_inode_to_fid(struct bch_inode_info *inode)
1106 {
1107         return (struct bcachefs_fid) {
1108                 .inum   = inode->ei_inode.bi_inum,
1109                 .subvol = inode->ei_subvol,
1110                 .gen    = inode->ei_inode.bi_generation,
1111         };
1112 }
1113
1114 static int bch2_encode_fh(struct inode *vinode, u32 *fh, int *len,
1115                           struct inode *vdir)
1116 {
1117         struct bch_inode_info *inode    = to_bch_ei(vinode);
1118         struct bch_inode_info *dir      = to_bch_ei(vdir);
1119
1120         if (*len < sizeof(struct bcachefs_fid_with_parent) / sizeof(u32))
1121                 return FILEID_INVALID;
1122
1123         if (!S_ISDIR(inode->v.i_mode) && dir) {
1124                 struct bcachefs_fid_with_parent *fid = (void *) fh;
1125
1126                 fid->fid = bch2_inode_to_fid(inode);
1127                 fid->dir = bch2_inode_to_fid(dir);
1128
1129                 *len = sizeof(*fid) / sizeof(u32);
1130                 return FILEID_BCACHEFS_WITH_PARENT;
1131         } else {
1132                 struct bcachefs_fid *fid = (void *) fh;
1133
1134                 *fid = bch2_inode_to_fid(inode);
1135
1136                 *len = sizeof(*fid) / sizeof(u32);
1137                 return FILEID_BCACHEFS_WITHOUT_PARENT;
1138         }
1139 }
1140
1141 static struct inode *bch2_nfs_get_inode(struct super_block *sb,
1142                                         struct bcachefs_fid fid)
1143 {
1144         struct bch_fs *c = sb->s_fs_info;
1145         struct inode *vinode = bch2_vfs_inode_get(c, (subvol_inum) {
1146                                     .subvol = fid.subvol,
1147                                     .inum = fid.inum,
1148         });
1149         if (!IS_ERR(vinode) && vinode->i_generation != fid.gen) {
1150                 iput(vinode);
1151                 vinode = ERR_PTR(-ESTALE);
1152         }
1153         return vinode;
1154 }
1155
1156 static struct dentry *bch2_fh_to_dentry(struct super_block *sb, struct fid *_fid,
1157                 int fh_len, int fh_type)
1158 {
1159         struct bcachefs_fid *fid = (void *) _fid;
1160
1161         if (!bcachefs_fid_valid(fh_len, fh_type))
1162                 return NULL;
1163
1164         return d_obtain_alias(bch2_nfs_get_inode(sb, *fid));
1165 }
1166
1167 static struct dentry *bch2_fh_to_parent(struct super_block *sb, struct fid *_fid,
1168                 int fh_len, int fh_type)
1169 {
1170         struct bcachefs_fid_with_parent *fid = (void *) _fid;
1171
1172         if (!bcachefs_fid_valid(fh_len, fh_type) ||
1173             fh_type != FILEID_BCACHEFS_WITH_PARENT)
1174                 return NULL;
1175
1176         return d_obtain_alias(bch2_nfs_get_inode(sb, fid->dir));
1177 }
1178
1179 static struct dentry *bch2_get_parent(struct dentry *child)
1180 {
1181         struct bch_inode_info *inode = to_bch_ei(child->d_inode);
1182         struct bch_fs *c = inode->v.i_sb->s_fs_info;
1183         subvol_inum parent_inum = {
1184                 .subvol = inode->ei_inode.bi_parent_subvol ?:
1185                         inode->ei_subvol,
1186                 .inum = inode->ei_inode.bi_dir,
1187         };
1188
1189         if (!parent_inum.inum)
1190                 return NULL;
1191
1192         return d_obtain_alias(bch2_vfs_inode_get(c, parent_inum));
1193 }
1194
1195 static int bch2_get_name(struct dentry *parent, char *name, struct dentry *child)
1196 {
1197         struct bch_inode_info *inode    = to_bch_ei(child->d_inode);
1198         struct bch_inode_info *dir      = to_bch_ei(parent->d_inode);
1199         struct bch_fs *c = inode->v.i_sb->s_fs_info;
1200         struct btree_trans trans;
1201         struct btree_iter iter1;
1202         struct btree_iter iter2;
1203         struct bkey_s_c k;
1204         struct bkey_s_c_dirent d;
1205         struct bch_inode_unpacked inode_u;
1206         subvol_inum target;
1207         u32 snapshot;
1208         unsigned name_len;
1209         int ret;
1210
1211         if (!S_ISDIR(dir->v.i_mode))
1212                 return -EINVAL;
1213
1214         bch2_trans_init(&trans, c, 0, 0);
1215
1216         bch2_trans_iter_init(&trans, &iter1, BTREE_ID_dirents,
1217                              POS(dir->ei_inode.bi_inum, 0), 0);
1218         bch2_trans_iter_init(&trans, &iter2, BTREE_ID_dirents,
1219                              POS(dir->ei_inode.bi_inum, 0), 0);
1220 retry:
1221         bch2_trans_begin(&trans);
1222
1223         ret = bch2_subvolume_get_snapshot(&trans, dir->ei_subvol, &snapshot);
1224         if (ret)
1225                 goto err;
1226
1227         bch2_btree_iter_set_snapshot(&iter1, snapshot);
1228         bch2_btree_iter_set_snapshot(&iter2, snapshot);
1229
1230         ret = bch2_inode_find_by_inum_trans(&trans, inode_inum(inode), &inode_u);
1231         if (ret)
1232                 goto err;
1233
1234         if (inode_u.bi_dir == dir->ei_inode.bi_inum) {
1235                 bch2_btree_iter_set_pos(&iter1, POS(inode_u.bi_dir, inode_u.bi_dir_offset));
1236
1237                 k = bch2_btree_iter_peek_slot(&iter1);
1238                 ret = bkey_err(k);
1239                 if (ret)
1240                         goto err;
1241
1242                 if (k.k->type != KEY_TYPE_dirent) {
1243                         ret = -ENOENT;
1244                         goto err;
1245                 }
1246
1247                 d = bkey_s_c_to_dirent(k);
1248                 ret = bch2_dirent_read_target(&trans, inode_inum(dir), d, &target);
1249                 if (ret > 0)
1250                         ret = -ENOENT;
1251                 if (ret)
1252                         goto err;
1253
1254                 if (target.subvol       == inode->ei_subvol &&
1255                     target.inum         == inode->ei_inode.bi_inum)
1256                         goto found;
1257         } else {
1258                 /*
1259                  * File with multiple hardlinks and our backref is to the wrong
1260                  * directory - linear search:
1261                  */
1262                 for_each_btree_key_continue_norestart(iter2, 0, k, ret) {
1263                         if (k.k->p.inode > dir->ei_inode.bi_inum)
1264                                 break;
1265
1266                         if (k.k->type != KEY_TYPE_dirent)
1267                                 continue;
1268
1269                         d = bkey_s_c_to_dirent(k);
1270                         ret = bch2_dirent_read_target(&trans, inode_inum(dir), d, &target);
1271                         if (ret < 0)
1272                                 break;
1273                         if (ret)
1274                                 continue;
1275
1276                         if (target.subvol       == inode->ei_subvol &&
1277                             target.inum         == inode->ei_inode.bi_inum)
1278                                 goto found;
1279                 }
1280         }
1281
1282         ret = -ENOENT;
1283         goto err;
1284 found:
1285         name_len = min_t(unsigned, bch2_dirent_name_bytes(d), NAME_MAX);
1286
1287         memcpy(name, d.v->d_name, name_len);
1288         name[name_len] = '\0';
1289 err:
1290         if (bch2_err_matches(ret, BCH_ERR_transaction_restart))
1291                 goto retry;
1292
1293         bch2_trans_iter_exit(&trans, &iter1);
1294         bch2_trans_iter_exit(&trans, &iter2);
1295         bch2_trans_exit(&trans);
1296
1297         return ret;
1298 }
1299
1300 static const struct export_operations bch_export_ops = {
1301         .encode_fh      = bch2_encode_fh,
1302         .fh_to_dentry   = bch2_fh_to_dentry,
1303         .fh_to_parent   = bch2_fh_to_parent,
1304         .get_parent     = bch2_get_parent,
1305         .get_name       = bch2_get_name,
1306 };
1307
1308 static void bch2_vfs_inode_init(struct btree_trans *trans, subvol_inum inum,
1309                                 struct bch_inode_info *inode,
1310                                 struct bch_inode_unpacked *bi,
1311                                 struct bch_subvolume *subvol)
1312 {
1313         bch2_inode_update_after_write(trans, inode, bi, ~0);
1314
1315         if (BCH_SUBVOLUME_SNAP(subvol))
1316                 set_bit(EI_INODE_SNAPSHOT, &inode->ei_flags);
1317         else
1318                 clear_bit(EI_INODE_SNAPSHOT, &inode->ei_flags);
1319
1320         inode->v.i_blocks       = bi->bi_sectors;
1321         inode->v.i_ino          = bi->bi_inum;
1322         inode->v.i_rdev         = bi->bi_dev;
1323         inode->v.i_generation   = bi->bi_generation;
1324         inode->v.i_size         = bi->bi_size;
1325
1326         inode->ei_flags         = 0;
1327         inode->ei_quota_reserved = 0;
1328         inode->ei_qid           = bch_qid(bi);
1329         inode->ei_subvol        = inum.subvol;
1330
1331         inode->v.i_mapping->a_ops = &bch_address_space_operations;
1332
1333         switch (inode->v.i_mode & S_IFMT) {
1334         case S_IFREG:
1335                 inode->v.i_op   = &bch_file_inode_operations;
1336                 inode->v.i_fop  = &bch_file_operations;
1337                 break;
1338         case S_IFDIR:
1339                 inode->v.i_op   = &bch_dir_inode_operations;
1340                 inode->v.i_fop  = &bch_dir_file_operations;
1341                 break;
1342         case S_IFLNK:
1343                 inode_nohighmem(&inode->v);
1344                 inode->v.i_op   = &bch_symlink_inode_operations;
1345                 break;
1346         default:
1347                 init_special_inode(&inode->v, inode->v.i_mode, inode->v.i_rdev);
1348                 inode->v.i_op   = &bch_special_inode_operations;
1349                 break;
1350         }
1351 }
1352
1353 static struct inode *bch2_alloc_inode(struct super_block *sb)
1354 {
1355         struct bch_inode_info *inode;
1356
1357         inode = kmem_cache_alloc(bch2_inode_cache, GFP_NOFS);
1358         if (!inode)
1359                 return NULL;
1360
1361         inode_init_once(&inode->v);
1362         mutex_init(&inode->ei_update_lock);
1363         two_state_lock_init(&inode->ei_pagecache_lock);
1364         mutex_init(&inode->ei_quota_lock);
1365
1366         return &inode->v;
1367 }
1368
1369 static void bch2_i_callback(struct rcu_head *head)
1370 {
1371         struct inode *vinode = container_of(head, struct inode, i_rcu);
1372         struct bch_inode_info *inode = to_bch_ei(vinode);
1373
1374         kmem_cache_free(bch2_inode_cache, inode);
1375 }
1376
1377 static void bch2_destroy_inode(struct inode *vinode)
1378 {
1379         call_rcu(&vinode->i_rcu, bch2_i_callback);
1380 }
1381
1382 static int inode_update_times_fn(struct bch_inode_info *inode,
1383                                  struct bch_inode_unpacked *bi,
1384                                  void *p)
1385 {
1386         struct bch_fs *c = inode->v.i_sb->s_fs_info;
1387
1388         bi->bi_atime    = timespec_to_bch2_time(c, inode->v.i_atime);
1389         bi->bi_mtime    = timespec_to_bch2_time(c, inode->v.i_mtime);
1390         bi->bi_ctime    = timespec_to_bch2_time(c, inode->v.i_ctime);
1391
1392         return 0;
1393 }
1394
1395 static int bch2_vfs_write_inode(struct inode *vinode,
1396                                 struct writeback_control *wbc)
1397 {
1398         struct bch_fs *c = vinode->i_sb->s_fs_info;
1399         struct bch_inode_info *inode = to_bch_ei(vinode);
1400         int ret;
1401
1402         mutex_lock(&inode->ei_update_lock);
1403         ret = bch2_write_inode(c, inode, inode_update_times_fn, NULL,
1404                                ATTR_ATIME|ATTR_MTIME|ATTR_CTIME);
1405         mutex_unlock(&inode->ei_update_lock);
1406
1407         return bch2_err_class(ret);
1408 }
1409
1410 static void bch2_evict_inode(struct inode *vinode)
1411 {
1412         struct bch_fs *c = vinode->i_sb->s_fs_info;
1413         struct bch_inode_info *inode = to_bch_ei(vinode);
1414
1415         truncate_inode_pages_final(&inode->v.i_data);
1416
1417         clear_inode(&inode->v);
1418
1419         BUG_ON(!is_bad_inode(&inode->v) && inode->ei_quota_reserved);
1420
1421         if (!inode->v.i_nlink && !is_bad_inode(&inode->v)) {
1422                 bch2_quota_acct(c, inode->ei_qid, Q_SPC, -((s64) inode->v.i_blocks),
1423                                 KEY_TYPE_QUOTA_WARN);
1424                 bch2_quota_acct(c, inode->ei_qid, Q_INO, -1,
1425                                 KEY_TYPE_QUOTA_WARN);
1426                 bch2_inode_rm(c, inode_inum(inode));
1427         }
1428 }
1429
1430 void bch2_evict_subvolume_inodes(struct bch_fs *c,
1431                                  snapshot_id_list *s)
1432 {
1433         struct super_block *sb = c->vfs_sb;
1434         struct inode *inode;
1435
1436         spin_lock(&sb->s_inode_list_lock);
1437         list_for_each_entry(inode, &sb->s_inodes, i_sb_list) {
1438                 if (!snapshot_list_has_id(s, to_bch_ei(inode)->ei_subvol) ||
1439                     (inode->i_state & I_FREEING))
1440                         continue;
1441
1442                 d_mark_dontcache(inode);
1443                 d_prune_aliases(inode);
1444         }
1445         spin_unlock(&sb->s_inode_list_lock);
1446 again:
1447         cond_resched();
1448         spin_lock(&sb->s_inode_list_lock);
1449         list_for_each_entry(inode, &sb->s_inodes, i_sb_list) {
1450                 if (!snapshot_list_has_id(s, to_bch_ei(inode)->ei_subvol) ||
1451                     (inode->i_state & I_FREEING))
1452                         continue;
1453
1454                 if (!(inode->i_state & I_DONTCACHE)) {
1455                         d_mark_dontcache(inode);
1456                         d_prune_aliases(inode);
1457                 }
1458
1459                 spin_lock(&inode->i_lock);
1460                 if (snapshot_list_has_id(s, to_bch_ei(inode)->ei_subvol) &&
1461                     !(inode->i_state & I_FREEING)) {
1462                         wait_queue_head_t *wq = bit_waitqueue(&inode->i_state, __I_NEW);
1463                         DEFINE_WAIT_BIT(wait, &inode->i_state, __I_NEW);
1464                         prepare_to_wait(wq, &wait.wq_entry, TASK_UNINTERRUPTIBLE);
1465                         spin_unlock(&inode->i_lock);
1466                         spin_unlock(&sb->s_inode_list_lock);
1467                         schedule();
1468                         finish_wait(wq, &wait.wq_entry);
1469                         goto again;
1470                 }
1471
1472                 spin_unlock(&inode->i_lock);
1473         }
1474         spin_unlock(&sb->s_inode_list_lock);
1475 }
1476
1477 static int bch2_statfs(struct dentry *dentry, struct kstatfs *buf)
1478 {
1479         struct super_block *sb = dentry->d_sb;
1480         struct bch_fs *c = sb->s_fs_info;
1481         struct bch_fs_usage_short usage = bch2_fs_usage_read_short(c);
1482         unsigned shift = sb->s_blocksize_bits - 9;
1483         /*
1484          * this assumes inodes take up 64 bytes, which is a decent average
1485          * number:
1486          */
1487         u64 avail_inodes = ((usage.capacity - usage.used) << 3);
1488         u64 fsid;
1489
1490         buf->f_type     = BCACHEFS_STATFS_MAGIC;
1491         buf->f_bsize    = sb->s_blocksize;
1492         buf->f_blocks   = usage.capacity >> shift;
1493         buf->f_bfree    = usage.free >> shift;
1494         buf->f_bavail   = avail_factor(usage.free) >> shift;
1495
1496         buf->f_files    = usage.nr_inodes + avail_inodes;
1497         buf->f_ffree    = avail_inodes;
1498
1499         fsid = le64_to_cpup((void *) c->sb.user_uuid.b) ^
1500                le64_to_cpup((void *) c->sb.user_uuid.b + sizeof(u64));
1501         buf->f_fsid.val[0] = fsid & 0xFFFFFFFFUL;
1502         buf->f_fsid.val[1] = (fsid >> 32) & 0xFFFFFFFFUL;
1503         buf->f_namelen  = BCH_NAME_MAX;
1504
1505         return 0;
1506 }
1507
1508 static int bch2_sync_fs(struct super_block *sb, int wait)
1509 {
1510         struct bch_fs *c = sb->s_fs_info;
1511         int ret;
1512
1513         if (c->opts.journal_flush_disabled)
1514                 return 0;
1515
1516         if (!wait) {
1517                 bch2_journal_flush_async(&c->journal, NULL);
1518                 return 0;
1519         }
1520
1521         ret = bch2_journal_flush(&c->journal);
1522         return bch2_err_class(ret);
1523 }
1524
1525 static struct bch_fs *bch2_path_to_fs(const char *path)
1526 {
1527         struct bch_fs *c;
1528         dev_t dev;
1529         int ret;
1530
1531         ret = lookup_bdev(path, &dev);
1532         if (ret)
1533                 return ERR_PTR(ret);
1534
1535         c = bch2_dev_to_fs(dev);
1536         if (c)
1537                 closure_put(&c->cl);
1538         return c ?: ERR_PTR(-ENOENT);
1539 }
1540
1541 static char **split_devs(const char *_dev_name, unsigned *nr)
1542 {
1543         char *dev_name = NULL, **devs = NULL, *s;
1544         size_t i, nr_devs = 0;
1545
1546         dev_name = kstrdup(_dev_name, GFP_KERNEL);
1547         if (!dev_name)
1548                 return NULL;
1549
1550         for (s = dev_name; s; s = strchr(s + 1, ':'))
1551                 nr_devs++;
1552
1553         devs = kcalloc(nr_devs + 1, sizeof(const char *), GFP_KERNEL);
1554         if (!devs) {
1555                 kfree(dev_name);
1556                 return NULL;
1557         }
1558
1559         for (i = 0, s = dev_name;
1560              s;
1561              (s = strchr(s, ':')) && (*s++ = '\0'))
1562                 devs[i++] = s;
1563
1564         *nr = nr_devs;
1565         return devs;
1566 }
1567
1568 static int bch2_remount(struct super_block *sb, int *flags, char *data)
1569 {
1570         struct bch_fs *c = sb->s_fs_info;
1571         struct bch_opts opts = bch2_opts_empty();
1572         int ret;
1573
1574         opt_set(opts, read_only, (*flags & SB_RDONLY) != 0);
1575
1576         ret = bch2_parse_mount_opts(c, &opts, data);
1577         if (ret)
1578                 goto err;
1579
1580         if (opts.read_only != c->opts.read_only) {
1581                 down_write(&c->state_lock);
1582
1583                 if (opts.read_only) {
1584                         bch2_fs_read_only(c);
1585
1586                         sb->s_flags |= SB_RDONLY;
1587                 } else {
1588                         ret = bch2_fs_read_write(c);
1589                         if (ret) {
1590                                 bch_err(c, "error going rw: %i", ret);
1591                                 up_write(&c->state_lock);
1592                                 ret = -EINVAL;
1593                                 goto err;
1594                         }
1595
1596                         sb->s_flags &= ~SB_RDONLY;
1597                 }
1598
1599                 c->opts.read_only = opts.read_only;
1600
1601                 up_write(&c->state_lock);
1602         }
1603
1604         if (opts.errors >= 0)
1605                 c->opts.errors = opts.errors;
1606 err:
1607         return bch2_err_class(ret);
1608 }
1609
1610 static int bch2_show_devname(struct seq_file *seq, struct dentry *root)
1611 {
1612         struct bch_fs *c = root->d_sb->s_fs_info;
1613         struct bch_dev *ca;
1614         unsigned i;
1615         bool first = true;
1616
1617         for_each_online_member(ca, c, i) {
1618                 if (!first)
1619                         seq_putc(seq, ':');
1620                 first = false;
1621                 seq_puts(seq, "/dev/");
1622                 seq_puts(seq, ca->name);
1623         }
1624
1625         return 0;
1626 }
1627
1628 static int bch2_show_options(struct seq_file *seq, struct dentry *root)
1629 {
1630         struct bch_fs *c = root->d_sb->s_fs_info;
1631         enum bch_opt_id i;
1632         struct printbuf buf = PRINTBUF;
1633         int ret = 0;
1634
1635         for (i = 0; i < bch2_opts_nr; i++) {
1636                 const struct bch_option *opt = &bch2_opt_table[i];
1637                 u64 v = bch2_opt_get_by_id(&c->opts, i);
1638
1639                 if (!(opt->flags & OPT_MOUNT))
1640                         continue;
1641
1642                 if (v == bch2_opt_get_by_id(&bch2_opts_default, i))
1643                         continue;
1644
1645                 printbuf_reset(&buf);
1646                 bch2_opt_to_text(&buf, c, c->disk_sb.sb, opt, v,
1647                                  OPT_SHOW_MOUNT_STYLE);
1648                 seq_putc(seq, ',');
1649                 seq_puts(seq, buf.buf);
1650         }
1651
1652         if (buf.allocation_failure)
1653                 ret = -ENOMEM;
1654         printbuf_exit(&buf);
1655         return ret;
1656 }
1657
1658 static void bch2_put_super(struct super_block *sb)
1659 {
1660         struct bch_fs *c = sb->s_fs_info;
1661
1662         __bch2_fs_stop(c);
1663 }
1664
1665 static const struct super_operations bch_super_operations = {
1666         .alloc_inode    = bch2_alloc_inode,
1667         .destroy_inode  = bch2_destroy_inode,
1668         .write_inode    = bch2_vfs_write_inode,
1669         .evict_inode    = bch2_evict_inode,
1670         .sync_fs        = bch2_sync_fs,
1671         .statfs         = bch2_statfs,
1672         .show_devname   = bch2_show_devname,
1673         .show_options   = bch2_show_options,
1674         .remount_fs     = bch2_remount,
1675         .put_super      = bch2_put_super,
1676 #if 0
1677         .freeze_fs      = bch2_freeze,
1678         .unfreeze_fs    = bch2_unfreeze,
1679 #endif
1680 };
1681
1682 static int bch2_set_super(struct super_block *s, void *data)
1683 {
1684         s->s_fs_info = data;
1685         return 0;
1686 }
1687
1688 static int bch2_noset_super(struct super_block *s, void *data)
1689 {
1690         return -EBUSY;
1691 }
1692
1693 static int bch2_test_super(struct super_block *s, void *data)
1694 {
1695         struct bch_fs *c = s->s_fs_info;
1696         struct bch_fs **devs = data;
1697         unsigned i;
1698
1699         if (!c)
1700                 return false;
1701
1702         for (i = 0; devs[i]; i++)
1703                 if (c != devs[i])
1704                         return false;
1705         return true;
1706 }
1707
1708 static struct dentry *bch2_mount(struct file_system_type *fs_type,
1709                                  int flags, const char *dev_name, void *data)
1710 {
1711         struct bch_fs *c;
1712         struct bch_dev *ca;
1713         struct super_block *sb;
1714         struct inode *vinode;
1715         struct bch_opts opts = bch2_opts_empty();
1716         char **devs;
1717         struct bch_fs **devs_to_fs = NULL;
1718         unsigned i, nr_devs;
1719         int ret;
1720
1721         opt_set(opts, read_only, (flags & SB_RDONLY) != 0);
1722
1723         ret = bch2_parse_mount_opts(NULL, &opts, data);
1724         if (ret)
1725                 return ERR_PTR(ret);
1726
1727         if (!dev_name || strlen(dev_name) == 0)
1728                 return ERR_PTR(-EINVAL);
1729
1730         devs = split_devs(dev_name, &nr_devs);
1731         if (!devs)
1732                 return ERR_PTR(-ENOMEM);
1733
1734         devs_to_fs = kcalloc(nr_devs + 1, sizeof(void *), GFP_KERNEL);
1735         if (!devs_to_fs) {
1736                 sb = ERR_PTR(-ENOMEM);
1737                 goto got_sb;
1738         }
1739
1740         for (i = 0; i < nr_devs; i++)
1741                 devs_to_fs[i] = bch2_path_to_fs(devs[i]);
1742
1743         sb = sget(fs_type, bch2_test_super, bch2_noset_super,
1744                   flags|SB_NOSEC, devs_to_fs);
1745         if (!IS_ERR(sb))
1746                 goto got_sb;
1747
1748         c = bch2_fs_open(devs, nr_devs, opts);
1749         if (IS_ERR(c)) {
1750                 sb = ERR_CAST(c);
1751                 goto got_sb;
1752         }
1753
1754         /* Some options can't be parsed until after the fs is started: */
1755         ret = bch2_parse_mount_opts(c, &opts, data);
1756         if (ret) {
1757                 bch2_fs_stop(c);
1758                 sb = ERR_PTR(ret);
1759                 goto got_sb;
1760         }
1761
1762         bch2_opts_apply(&c->opts, opts);
1763
1764         sb = sget(fs_type, NULL, bch2_set_super, flags|SB_NOSEC, c);
1765         if (IS_ERR(sb))
1766                 bch2_fs_stop(c);
1767 got_sb:
1768         kfree(devs_to_fs);
1769         kfree(devs[0]);
1770         kfree(devs);
1771
1772         if (IS_ERR(sb)) {
1773                 ret = PTR_ERR(sb);
1774                 ret = bch2_err_class(ret);
1775                 return ERR_PTR(ret);
1776         }
1777
1778         c = sb->s_fs_info;
1779
1780         if (sb->s_root) {
1781                 if ((flags ^ sb->s_flags) & SB_RDONLY) {
1782                         ret = -EBUSY;
1783                         goto err_put_super;
1784                 }
1785                 goto out;
1786         }
1787
1788         sb->s_blocksize         = block_bytes(c);
1789         sb->s_blocksize_bits    = ilog2(block_bytes(c));
1790         sb->s_maxbytes          = MAX_LFS_FILESIZE;
1791         sb->s_op                = &bch_super_operations;
1792         sb->s_export_op         = &bch_export_ops;
1793 #ifdef CONFIG_BCACHEFS_QUOTA
1794         sb->s_qcop              = &bch2_quotactl_operations;
1795         sb->s_quota_types       = QTYPE_MASK_USR|QTYPE_MASK_GRP|QTYPE_MASK_PRJ;
1796 #endif
1797         sb->s_xattr             = bch2_xattr_handlers;
1798         sb->s_magic             = BCACHEFS_STATFS_MAGIC;
1799         sb->s_time_gran         = c->sb.nsec_per_time_unit;
1800         sb->s_time_min          = div_s64(S64_MIN, c->sb.time_units_per_sec) + 1;
1801         sb->s_time_max          = div_s64(S64_MAX, c->sb.time_units_per_sec);
1802         c->vfs_sb               = sb;
1803         strscpy(sb->s_id, c->name, sizeof(sb->s_id));
1804
1805         ret = super_setup_bdi(sb);
1806         if (ret)
1807                 goto err_put_super;
1808
1809         sb->s_bdi->ra_pages             = VM_READAHEAD_PAGES;
1810
1811         for_each_online_member(ca, c, i) {
1812                 struct block_device *bdev = ca->disk_sb.bdev;
1813
1814                 /* XXX: create an anonymous device for multi device filesystems */
1815                 sb->s_bdev      = bdev;
1816                 sb->s_dev       = bdev->bd_dev;
1817                 percpu_ref_put(&ca->io_ref);
1818                 break;
1819         }
1820
1821         c->dev = sb->s_dev;
1822
1823 #ifdef CONFIG_BCACHEFS_POSIX_ACL
1824         if (c->opts.acl)
1825                 sb->s_flags     |= SB_POSIXACL;
1826 #endif
1827
1828         sb->s_shrink.seeks = 0;
1829
1830         vinode = bch2_vfs_inode_get(c, BCACHEFS_ROOT_SUBVOL_INUM);
1831         ret = PTR_ERR_OR_ZERO(vinode);
1832         if (ret) {
1833                 bch_err(c, "error mounting: error getting root inode: %s", bch2_err_str(ret));
1834                 goto err_put_super;
1835         }
1836
1837         sb->s_root = d_make_root(vinode);
1838         if (!sb->s_root) {
1839                 bch_err(c, "error mounting: error allocating root dentry");
1840                 ret = -ENOMEM;
1841                 goto err_put_super;
1842         }
1843
1844         sb->s_flags |= SB_ACTIVE;
1845 out:
1846         return dget(sb->s_root);
1847
1848 err_put_super:
1849         deactivate_locked_super(sb);
1850         return ERR_PTR(ret);
1851 }
1852
1853 static void bch2_kill_sb(struct super_block *sb)
1854 {
1855         struct bch_fs *c = sb->s_fs_info;
1856
1857         generic_shutdown_super(sb);
1858         bch2_fs_free(c);
1859 }
1860
1861 static struct file_system_type bcache_fs_type = {
1862         .owner          = THIS_MODULE,
1863         .name           = "bcachefs",
1864         .mount          = bch2_mount,
1865         .kill_sb        = bch2_kill_sb,
1866         .fs_flags       = FS_REQUIRES_DEV,
1867 };
1868
1869 MODULE_ALIAS_FS("bcachefs");
1870
1871 void bch2_vfs_exit(void)
1872 {
1873         unregister_filesystem(&bcache_fs_type);
1874         kmem_cache_destroy(bch2_inode_cache);
1875 }
1876
1877 int __init bch2_vfs_init(void)
1878 {
1879         int ret = -ENOMEM;
1880
1881         bch2_inode_cache = KMEM_CACHE(bch_inode_info, 0);
1882         if (!bch2_inode_cache)
1883                 goto err;
1884
1885         ret = register_filesystem(&bcache_fs_type);
1886         if (ret)
1887                 goto err;
1888
1889         return 0;
1890 err:
1891         bch2_vfs_exit();
1892         return ret;
1893 }
1894
1895 #endif /* NO_BCACHEFS_FS */