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