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