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