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