]> git.sesse.net Git - bcachefs-tools-debian/blob - libbcachefs/fs.c
Update bcachefs sources to 242d37cbd0 bcachefs: Kill btree_iter_pos_changed()
[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 bch_hash_info hash = bch2_hash_info_init(c, &dir->ei_inode);
372         struct inode *vinode = NULL;
373         u64 inum;
374
375         inum = bch2_dirent_lookup(c, dir->v.i_ino, &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         ret = __bch2_trans_do(&trans, NULL, &inode->ei_journal_seq,
416                               BTREE_INSERT_NOUNLOCK,
417                         bch2_link_trans(&trans,
418                                         dir->v.i_ino,
419                                         inode->v.i_ino, &dir_u, &inode_u,
420                                         &dentry->d_name));
421
422         if (likely(!ret)) {
423                 BUG_ON(inode_u.bi_inum != inode->v.i_ino);
424
425                 journal_seq_copy(c, inode, dir->ei_journal_seq);
426                 bch2_inode_update_after_write(c, dir, &dir_u,
427                                               ATTR_MTIME|ATTR_CTIME);
428                 bch2_inode_update_after_write(c, inode, &inode_u, ATTR_CTIME);
429         }
430
431         bch2_trans_exit(&trans);
432         mutex_unlock(&inode->ei_update_lock);
433         return ret;
434 }
435
436 static int bch2_link(struct dentry *old_dentry, struct inode *vdir,
437                      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(old_dentry->d_inode);
442         int ret;
443
444         lockdep_assert_held(&inode->v.i_rwsem);
445
446         ret = __bch2_link(c, inode, dir, dentry);
447         if (unlikely(ret))
448                 return ret;
449
450         ihold(&inode->v);
451         d_instantiate(dentry, &inode->v);
452         return 0;
453 }
454
455 static int bch2_unlink(struct inode *vdir, struct dentry *dentry)
456 {
457         struct bch_fs *c = vdir->i_sb->s_fs_info;
458         struct bch_inode_info *dir = to_bch_ei(vdir);
459         struct bch_inode_info *inode = to_bch_ei(dentry->d_inode);
460         struct bch_inode_unpacked dir_u, inode_u;
461         struct btree_trans trans;
462         int ret;
463
464         bch2_lock_inodes(INODE_UPDATE_LOCK, dir, inode);
465         bch2_trans_init(&trans, c, 4, 1024);
466
467         ret = __bch2_trans_do(&trans, NULL, &dir->ei_journal_seq,
468                               BTREE_INSERT_NOUNLOCK|
469                               BTREE_INSERT_NOFAIL,
470                         bch2_unlink_trans(&trans,
471                                           dir->v.i_ino, &dir_u,
472                                           &inode_u, &dentry->d_name));
473
474         if (likely(!ret)) {
475                 BUG_ON(inode_u.bi_inum != inode->v.i_ino);
476
477                 journal_seq_copy(c, inode, dir->ei_journal_seq);
478                 bch2_inode_update_after_write(c, dir, &dir_u,
479                                               ATTR_MTIME|ATTR_CTIME);
480                 bch2_inode_update_after_write(c, inode, &inode_u,
481                                               ATTR_MTIME);
482         }
483
484         bch2_trans_exit(&trans);
485         bch2_unlock_inodes(INODE_UPDATE_LOCK, dir, inode);
486
487         return ret;
488 }
489
490 static int bch2_symlink(struct inode *vdir, struct dentry *dentry,
491                         const char *symname)
492 {
493         struct bch_fs *c = vdir->i_sb->s_fs_info;
494         struct bch_inode_info *dir = to_bch_ei(vdir), *inode;
495         int ret;
496
497         inode = __bch2_create(dir, dentry, S_IFLNK|S_IRWXUGO, 0, true);
498         if (unlikely(IS_ERR(inode)))
499                 return PTR_ERR(inode);
500
501         inode_lock(&inode->v);
502         ret = page_symlink(&inode->v, symname, strlen(symname) + 1);
503         inode_unlock(&inode->v);
504
505         if (unlikely(ret))
506                 goto err;
507
508         ret = filemap_write_and_wait_range(inode->v.i_mapping, 0, LLONG_MAX);
509         if (unlikely(ret))
510                 goto err;
511
512         journal_seq_copy(c, dir, inode->ei_journal_seq);
513
514         ret = __bch2_link(c, inode, dir, dentry);
515         if (unlikely(ret))
516                 goto err;
517
518         d_instantiate(dentry, &inode->v);
519         return 0;
520 err:
521         iput(&inode->v);
522         return ret;
523 }
524
525 static int bch2_mkdir(struct inode *vdir, struct dentry *dentry, umode_t mode)
526 {
527         return bch2_mknod(vdir, dentry, mode|S_IFDIR, 0);
528 }
529
530 static int bch2_rename2(struct inode *src_vdir, struct dentry *src_dentry,
531                         struct inode *dst_vdir, struct dentry *dst_dentry,
532                         unsigned flags)
533 {
534         struct bch_fs *c = src_vdir->i_sb->s_fs_info;
535         struct bch_inode_info *src_dir = to_bch_ei(src_vdir);
536         struct bch_inode_info *dst_dir = to_bch_ei(dst_vdir);
537         struct bch_inode_info *src_inode = to_bch_ei(src_dentry->d_inode);
538         struct bch_inode_info *dst_inode = to_bch_ei(dst_dentry->d_inode);
539         struct bch_inode_unpacked dst_dir_u, src_dir_u;
540         struct bch_inode_unpacked src_inode_u, dst_inode_u;
541         struct btree_trans trans;
542         enum bch_rename_mode mode = flags & RENAME_EXCHANGE
543                 ? BCH_RENAME_EXCHANGE
544                 : dst_dentry->d_inode
545                 ? BCH_RENAME_OVERWRITE : BCH_RENAME;
546         u64 journal_seq = 0;
547         int ret;
548
549         if (flags & ~(RENAME_NOREPLACE|RENAME_EXCHANGE))
550                 return -EINVAL;
551
552         if (mode == BCH_RENAME_OVERWRITE) {
553                 ret = filemap_write_and_wait_range(src_inode->v.i_mapping,
554                                                    0, LLONG_MAX);
555                 if (ret)
556                         return ret;
557         }
558
559         bch2_trans_init(&trans, c, 8, 2048);
560
561         bch2_lock_inodes(INODE_UPDATE_LOCK,
562                          src_dir,
563                          dst_dir,
564                          src_inode,
565                          dst_inode);
566
567         if (inode_attr_changing(dst_dir, src_inode, Inode_opt_project)) {
568                 ret = bch2_fs_quota_transfer(c, src_inode,
569                                              dst_dir->ei_qid,
570                                              1 << QTYP_PRJ,
571                                              KEY_TYPE_QUOTA_PREALLOC);
572                 if (ret)
573                         goto err;
574         }
575
576         if (mode == BCH_RENAME_EXCHANGE &&
577             inode_attr_changing(src_dir, dst_inode, Inode_opt_project)) {
578                 ret = bch2_fs_quota_transfer(c, dst_inode,
579                                              src_dir->ei_qid,
580                                              1 << QTYP_PRJ,
581                                              KEY_TYPE_QUOTA_PREALLOC);
582                 if (ret)
583                         goto err;
584         }
585
586         ret = __bch2_trans_do(&trans, NULL, &journal_seq,
587                               BTREE_INSERT_NOUNLOCK,
588                         bch2_rename_trans(&trans,
589                                           src_dir->v.i_ino, &src_dir_u,
590                                           dst_dir->v.i_ino, &dst_dir_u,
591                                           &src_inode_u,
592                                           &dst_inode_u,
593                                           &src_dentry->d_name,
594                                           &dst_dentry->d_name,
595                                           mode));
596         if (unlikely(ret))
597                 goto err;
598
599         BUG_ON(src_inode->v.i_ino != src_inode_u.bi_inum);
600         BUG_ON(dst_inode &&
601                dst_inode->v.i_ino != dst_inode_u.bi_inum);
602
603         bch2_inode_update_after_write(c, src_dir, &src_dir_u,
604                                       ATTR_MTIME|ATTR_CTIME);
605         journal_seq_copy(c, src_dir, journal_seq);
606
607         if (src_dir != dst_dir) {
608                 bch2_inode_update_after_write(c, dst_dir, &dst_dir_u,
609                                               ATTR_MTIME|ATTR_CTIME);
610                 journal_seq_copy(c, dst_dir, journal_seq);
611         }
612
613         bch2_inode_update_after_write(c, src_inode, &src_inode_u,
614                                       ATTR_CTIME);
615         journal_seq_copy(c, src_inode, journal_seq);
616
617         if (dst_inode) {
618                 bch2_inode_update_after_write(c, dst_inode, &dst_inode_u,
619                                               ATTR_CTIME);
620                 journal_seq_copy(c, dst_inode, journal_seq);
621         }
622 err:
623         bch2_trans_exit(&trans);
624
625         bch2_fs_quota_transfer(c, src_inode,
626                                bch_qid(&src_inode->ei_inode),
627                                1 << QTYP_PRJ,
628                                KEY_TYPE_QUOTA_NOCHECK);
629         if (dst_inode)
630                 bch2_fs_quota_transfer(c, dst_inode,
631                                        bch_qid(&dst_inode->ei_inode),
632                                        1 << QTYP_PRJ,
633                                        KEY_TYPE_QUOTA_NOCHECK);
634
635         bch2_unlock_inodes(INODE_UPDATE_LOCK,
636                            src_dir,
637                            dst_dir,
638                            src_inode,
639                            dst_inode);
640
641         return ret;
642 }
643
644 void bch2_setattr_copy(struct bch_inode_info *inode,
645                        struct bch_inode_unpacked *bi,
646                        struct iattr *attr)
647 {
648         struct bch_fs *c = inode->v.i_sb->s_fs_info;
649         unsigned int ia_valid = attr->ia_valid;
650
651         if (ia_valid & ATTR_UID)
652                 bi->bi_uid = from_kuid(c->vfs_sb->s_user_ns, attr->ia_uid);
653         if (ia_valid & ATTR_GID)
654                 bi->bi_gid = from_kgid(c->vfs_sb->s_user_ns, attr->ia_gid);
655
656         if (ia_valid & ATTR_ATIME)
657                 bi->bi_atime = timespec_to_bch2_time(c, attr->ia_atime);
658         if (ia_valid & ATTR_MTIME)
659                 bi->bi_mtime = timespec_to_bch2_time(c, attr->ia_mtime);
660         if (ia_valid & ATTR_CTIME)
661                 bi->bi_ctime = timespec_to_bch2_time(c, attr->ia_ctime);
662
663         if (ia_valid & ATTR_MODE) {
664                 umode_t mode = attr->ia_mode;
665                 kgid_t gid = ia_valid & ATTR_GID
666                         ? attr->ia_gid
667                         : inode->v.i_gid;
668
669                 if (!in_group_p(gid) &&
670                     !capable_wrt_inode_uidgid(&inode->v, CAP_FSETID))
671                         mode &= ~S_ISGID;
672                 bi->bi_mode = mode;
673         }
674 }
675
676 static int bch2_setattr_nonsize(struct bch_inode_info *inode,
677                                 struct iattr *attr)
678 {
679         struct bch_fs *c = inode->v.i_sb->s_fs_info;
680         struct bch_qid qid;
681         struct btree_trans trans;
682         struct btree_iter *inode_iter;
683         struct bch_inode_unpacked inode_u;
684         struct posix_acl *acl = NULL;
685         int ret;
686
687         mutex_lock(&inode->ei_update_lock);
688
689         qid = inode->ei_qid;
690
691         if (attr->ia_valid & ATTR_UID)
692                 qid.q[QTYP_USR] = from_kuid(&init_user_ns, attr->ia_uid);
693
694         if (attr->ia_valid & ATTR_GID)
695                 qid.q[QTYP_GRP] = from_kgid(&init_user_ns, attr->ia_gid);
696
697         ret = bch2_fs_quota_transfer(c, inode, qid, ~0,
698                                      KEY_TYPE_QUOTA_PREALLOC);
699         if (ret)
700                 goto err;
701
702         bch2_trans_init(&trans, c, 0, 0);
703 retry:
704         bch2_trans_begin(&trans);
705         kfree(acl);
706         acl = NULL;
707
708         inode_iter = bch2_inode_peek(&trans, &inode_u, inode->v.i_ino,
709                                      BTREE_ITER_INTENT);
710         ret = PTR_ERR_OR_ZERO(inode_iter);
711         if (ret)
712                 goto btree_err;
713
714         bch2_setattr_copy(inode, &inode_u, attr);
715
716         if (attr->ia_valid & ATTR_MODE) {
717                 ret = bch2_acl_chmod(&trans, &inode_u, inode_u.bi_mode, &acl);
718                 if (ret)
719                         goto btree_err;
720         }
721
722         ret =   bch2_inode_write(&trans, inode_iter, &inode_u) ?:
723                 bch2_trans_commit(&trans, NULL,
724                                   &inode->ei_journal_seq,
725                                   BTREE_INSERT_NOUNLOCK|
726                                   BTREE_INSERT_NOFAIL);
727 btree_err:
728         if (ret == -EINTR)
729                 goto retry;
730         if (unlikely(ret))
731                 goto err_trans;
732
733         bch2_inode_update_after_write(c, inode, &inode_u, attr->ia_valid);
734
735         if (acl)
736                 set_cached_acl(&inode->v, ACL_TYPE_ACCESS, acl);
737 err_trans:
738         bch2_trans_exit(&trans);
739 err:
740         mutex_unlock(&inode->ei_update_lock);
741
742         return ret;
743 }
744
745 static int bch2_getattr(const struct path *path, struct kstat *stat,
746                         u32 request_mask, unsigned query_flags)
747 {
748         struct bch_inode_info *inode = to_bch_ei(d_inode(path->dentry));
749         struct bch_fs *c = inode->v.i_sb->s_fs_info;
750
751         stat->dev       = inode->v.i_sb->s_dev;
752         stat->ino       = inode->v.i_ino;
753         stat->mode      = inode->v.i_mode;
754         stat->nlink     = inode->v.i_nlink;
755         stat->uid       = inode->v.i_uid;
756         stat->gid       = inode->v.i_gid;
757         stat->rdev      = inode->v.i_rdev;
758         stat->size      = i_size_read(&inode->v);
759         stat->atime     = inode->v.i_atime;
760         stat->mtime     = inode->v.i_mtime;
761         stat->ctime     = inode->v.i_ctime;
762         stat->blksize   = block_bytes(c);
763         stat->blocks    = inode->v.i_blocks;
764
765         if (request_mask & STATX_BTIME) {
766                 stat->result_mask |= STATX_BTIME;
767                 stat->btime = bch2_time_to_timespec(c, inode->ei_inode.bi_otime);
768         }
769
770         if (inode->ei_inode.bi_flags & BCH_INODE_IMMUTABLE)
771                 stat->attributes |= STATX_ATTR_IMMUTABLE;
772         stat->attributes_mask    |= STATX_ATTR_IMMUTABLE;
773
774         if (inode->ei_inode.bi_flags & BCH_INODE_APPEND)
775                 stat->attributes |= STATX_ATTR_APPEND;
776         stat->attributes_mask    |= STATX_ATTR_APPEND;
777
778         if (inode->ei_inode.bi_flags & BCH_INODE_NODUMP)
779                 stat->attributes |= STATX_ATTR_NODUMP;
780         stat->attributes_mask    |= STATX_ATTR_NODUMP;
781
782         return 0;
783 }
784
785 static int bch2_setattr(struct dentry *dentry, struct iattr *iattr)
786 {
787         struct bch_inode_info *inode = to_bch_ei(dentry->d_inode);
788         int ret;
789
790         lockdep_assert_held(&inode->v.i_rwsem);
791
792         ret = setattr_prepare(dentry, iattr);
793         if (ret)
794                 return ret;
795
796         return iattr->ia_valid & ATTR_SIZE
797                 ? bch2_truncate(inode, iattr)
798                 : bch2_setattr_nonsize(inode, iattr);
799 }
800
801 static int bch2_tmpfile(struct inode *vdir, struct dentry *dentry, umode_t mode)
802 {
803         struct bch_inode_info *inode =
804                 __bch2_create(to_bch_ei(vdir), dentry, mode, 0, true);
805
806         if (IS_ERR(inode))
807                 return PTR_ERR(inode);
808
809         d_mark_tmpfile(dentry, &inode->v);
810         d_instantiate(dentry, &inode->v);
811         return 0;
812 }
813
814 static int bch2_fill_extent(struct bch_fs *c,
815                             struct fiemap_extent_info *info,
816                             struct bkey_s_c k, unsigned flags)
817 {
818         if (bkey_extent_is_direct_data(k.k)) {
819                 struct bkey_ptrs_c ptrs = bch2_bkey_ptrs_c(k);
820                 const union bch_extent_entry *entry;
821                 struct extent_ptr_decoded p;
822                 int ret;
823
824                 if (k.k->type == KEY_TYPE_reflink_v)
825                         flags |= FIEMAP_EXTENT_SHARED;
826
827                 bkey_for_each_ptr_decode(k.k, ptrs, p, entry) {
828                         int flags2 = 0;
829                         u64 offset = p.ptr.offset;
830
831                         if (p.crc.compression_type)
832                                 flags2 |= FIEMAP_EXTENT_ENCODED;
833                         else
834                                 offset += p.crc.offset;
835
836                         if ((offset & (c->opts.block_size - 1)) ||
837                             (k.k->size & (c->opts.block_size - 1)))
838                                 flags2 |= FIEMAP_EXTENT_NOT_ALIGNED;
839
840                         ret = fiemap_fill_next_extent(info,
841                                                 bkey_start_offset(k.k) << 9,
842                                                 offset << 9,
843                                                 k.k->size << 9, flags|flags2);
844                         if (ret)
845                                 return ret;
846                 }
847
848                 return 0;
849         } else if (bkey_extent_is_inline_data(k.k)) {
850                 return fiemap_fill_next_extent(info,
851                                                bkey_start_offset(k.k) << 9,
852                                                0, k.k->size << 9,
853                                                flags|
854                                                FIEMAP_EXTENT_DATA_INLINE);
855         } else if (k.k->type == KEY_TYPE_reservation) {
856                 return fiemap_fill_next_extent(info,
857                                                bkey_start_offset(k.k) << 9,
858                                                0, k.k->size << 9,
859                                                flags|
860                                                FIEMAP_EXTENT_DELALLOC|
861                                                FIEMAP_EXTENT_UNWRITTEN);
862         } else {
863                 BUG();
864         }
865 }
866
867 static int bch2_fiemap(struct inode *vinode, struct fiemap_extent_info *info,
868                        u64 start, u64 len)
869 {
870         struct bch_fs *c = vinode->i_sb->s_fs_info;
871         struct bch_inode_info *ei = to_bch_ei(vinode);
872         struct btree_trans trans;
873         struct btree_iter *iter;
874         struct bkey_s_c k;
875         struct bkey_buf cur, prev;
876         struct bpos end = POS(ei->v.i_ino, (start + len) >> 9);
877         unsigned offset_into_extent, sectors;
878         bool have_extent = false;
879         int ret = 0;
880
881         ret = fiemap_prep(&ei->v, info, start, &len, FIEMAP_FLAG_SYNC);
882         if (ret)
883                 return ret;
884
885         if (start + len < start)
886                 return -EINVAL;
887
888         bch2_bkey_buf_init(&cur);
889         bch2_bkey_buf_init(&prev);
890         bch2_trans_init(&trans, c, 0, 0);
891
892         iter = bch2_trans_get_iter(&trans, BTREE_ID_extents,
893                                    POS(ei->v.i_ino, start >> 9), 0);
894 retry:
895         while ((k = bch2_btree_iter_peek(iter)).k &&
896                !(ret = bkey_err(k)) &&
897                bkey_cmp(iter->pos, end) < 0) {
898                 enum btree_id data_btree = BTREE_ID_extents;
899
900                 if (!bkey_extent_is_data(k.k) &&
901                     k.k->type != KEY_TYPE_reservation) {
902                         bch2_btree_iter_next(iter);
903                         continue;
904                 }
905
906                 offset_into_extent      = iter->pos.offset -
907                         bkey_start_offset(k.k);
908                 sectors                 = k.k->size - offset_into_extent;
909
910                 bch2_bkey_buf_reassemble(&cur, c, k);
911
912                 ret = bch2_read_indirect_extent(&trans, &data_btree,
913                                         &offset_into_extent, &cur);
914                 if (ret)
915                         break;
916
917                 k = bkey_i_to_s_c(cur.k);
918                 bch2_bkey_buf_realloc(&prev, c, k.k->u64s);
919
920                 sectors = min(sectors, k.k->size - offset_into_extent);
921
922                 bch2_cut_front(POS(k.k->p.inode,
923                                    bkey_start_offset(k.k) +
924                                    offset_into_extent),
925                                cur.k);
926                 bch2_key_resize(&cur.k->k, sectors);
927                 cur.k->k.p = iter->pos;
928                 cur.k->k.p.offset += cur.k->k.size;
929
930                 if (have_extent) {
931                         ret = bch2_fill_extent(c, info,
932                                         bkey_i_to_s_c(prev.k), 0);
933                         if (ret)
934                                 break;
935                 }
936
937                 bkey_copy(prev.k, cur.k);
938                 have_extent = true;
939
940                 bch2_btree_iter_set_pos(iter,
941                         POS(iter->pos.inode, iter->pos.offset + sectors));
942         }
943
944         if (ret == -EINTR)
945                 goto retry;
946
947         if (!ret && have_extent)
948                 ret = bch2_fill_extent(c, info, bkey_i_to_s_c(prev.k),
949                                        FIEMAP_EXTENT_LAST);
950
951         ret = bch2_trans_exit(&trans) ?: ret;
952         bch2_bkey_buf_exit(&cur, c);
953         bch2_bkey_buf_exit(&prev, c);
954         return ret < 0 ? ret : 0;
955 }
956
957 static const struct vm_operations_struct bch_vm_ops = {
958         .fault          = bch2_page_fault,
959         .map_pages      = filemap_map_pages,
960         .page_mkwrite   = bch2_page_mkwrite,
961 };
962
963 static int bch2_mmap(struct file *file, struct vm_area_struct *vma)
964 {
965         file_accessed(file);
966
967         vma->vm_ops = &bch_vm_ops;
968         return 0;
969 }
970
971 /* Directories: */
972
973 static loff_t bch2_dir_llseek(struct file *file, loff_t offset, int whence)
974 {
975         return generic_file_llseek_size(file, offset, whence,
976                                         S64_MAX, S64_MAX);
977 }
978
979 static int bch2_vfs_readdir(struct file *file, struct dir_context *ctx)
980 {
981         struct bch_inode_info *inode = file_bch_inode(file);
982         struct bch_fs *c = inode->v.i_sb->s_fs_info;
983
984         if (!dir_emit_dots(file, ctx))
985                 return 0;
986
987         return bch2_readdir(c, inode->v.i_ino, ctx);
988 }
989
990 static const struct file_operations bch_file_operations = {
991         .llseek         = bch2_llseek,
992         .read_iter      = bch2_read_iter,
993         .write_iter     = bch2_write_iter,
994         .mmap           = bch2_mmap,
995         .open           = generic_file_open,
996         .fsync          = bch2_fsync,
997         .splice_read    = generic_file_splice_read,
998 #if 0
999         /* Busted: */
1000         .splice_write   = iter_file_splice_write,
1001 #endif
1002         .fallocate      = bch2_fallocate_dispatch,
1003         .unlocked_ioctl = bch2_fs_file_ioctl,
1004 #ifdef CONFIG_COMPAT
1005         .compat_ioctl   = bch2_compat_fs_ioctl,
1006 #endif
1007         .remap_file_range = bch2_remap_file_range,
1008 };
1009
1010 static const struct inode_operations bch_file_inode_operations = {
1011         .getattr        = bch2_getattr,
1012         .setattr        = bch2_setattr,
1013         .fiemap         = bch2_fiemap,
1014         .listxattr      = bch2_xattr_list,
1015 #ifdef CONFIG_BCACHEFS_POSIX_ACL
1016         .get_acl        = bch2_get_acl,
1017         .set_acl        = bch2_set_acl,
1018 #endif
1019 };
1020
1021 static const struct inode_operations bch_dir_inode_operations = {
1022         .lookup         = bch2_lookup,
1023         .create         = bch2_create,
1024         .link           = bch2_link,
1025         .unlink         = bch2_unlink,
1026         .symlink        = bch2_symlink,
1027         .mkdir          = bch2_mkdir,
1028         .rmdir          = bch2_unlink,
1029         .mknod          = bch2_mknod,
1030         .rename         = bch2_rename2,
1031         .getattr        = bch2_getattr,
1032         .setattr        = bch2_setattr,
1033         .tmpfile        = bch2_tmpfile,
1034         .listxattr      = bch2_xattr_list,
1035 #ifdef CONFIG_BCACHEFS_POSIX_ACL
1036         .get_acl        = bch2_get_acl,
1037         .set_acl        = bch2_set_acl,
1038 #endif
1039 };
1040
1041 static const struct file_operations bch_dir_file_operations = {
1042         .llseek         = bch2_dir_llseek,
1043         .read           = generic_read_dir,
1044         .iterate_shared = bch2_vfs_readdir,
1045         .fsync          = bch2_fsync,
1046         .unlocked_ioctl = bch2_fs_file_ioctl,
1047 #ifdef CONFIG_COMPAT
1048         .compat_ioctl   = bch2_compat_fs_ioctl,
1049 #endif
1050 };
1051
1052 static const struct inode_operations bch_symlink_inode_operations = {
1053         .get_link       = page_get_link,
1054         .getattr        = bch2_getattr,
1055         .setattr        = bch2_setattr,
1056         .listxattr      = bch2_xattr_list,
1057 #ifdef CONFIG_BCACHEFS_POSIX_ACL
1058         .get_acl        = bch2_get_acl,
1059         .set_acl        = bch2_set_acl,
1060 #endif
1061 };
1062
1063 static const struct inode_operations bch_special_inode_operations = {
1064         .getattr        = bch2_getattr,
1065         .setattr        = bch2_setattr,
1066         .listxattr      = bch2_xattr_list,
1067 #ifdef CONFIG_BCACHEFS_POSIX_ACL
1068         .get_acl        = bch2_get_acl,
1069         .set_acl        = bch2_set_acl,
1070 #endif
1071 };
1072
1073 static const struct address_space_operations bch_address_space_operations = {
1074         .writepage      = bch2_writepage,
1075         .readpage       = bch2_readpage,
1076         .writepages     = bch2_writepages,
1077         .readahead      = bch2_readahead,
1078         .set_page_dirty = __set_page_dirty_nobuffers,
1079         .write_begin    = bch2_write_begin,
1080         .write_end      = bch2_write_end,
1081         .invalidatepage = bch2_invalidatepage,
1082         .releasepage    = bch2_releasepage,
1083         .direct_IO      = noop_direct_IO,
1084 #ifdef CONFIG_MIGRATION
1085         .migratepage    = bch2_migrate_page,
1086 #endif
1087         .error_remove_page = generic_error_remove_page,
1088 };
1089
1090 static struct inode *bch2_nfs_get_inode(struct super_block *sb,
1091                 u64 ino, u32 generation)
1092 {
1093         struct bch_fs *c = sb->s_fs_info;
1094         struct inode *vinode;
1095
1096         if (ino < BCACHEFS_ROOT_INO)
1097                 return ERR_PTR(-ESTALE);
1098
1099         vinode = bch2_vfs_inode_get(c, ino);
1100         if (IS_ERR(vinode))
1101                 return ERR_CAST(vinode);
1102         if (generation && vinode->i_generation != generation) {
1103                 /* we didn't find the right inode.. */
1104                 iput(vinode);
1105                 return ERR_PTR(-ESTALE);
1106         }
1107         return vinode;
1108 }
1109
1110 static struct dentry *bch2_fh_to_dentry(struct super_block *sb, struct fid *fid,
1111                 int fh_len, int fh_type)
1112 {
1113         return generic_fh_to_dentry(sb, fid, fh_len, fh_type,
1114                                     bch2_nfs_get_inode);
1115 }
1116
1117 static struct dentry *bch2_fh_to_parent(struct super_block *sb, struct fid *fid,
1118                 int fh_len, int fh_type)
1119 {
1120         return generic_fh_to_parent(sb, fid, fh_len, fh_type,
1121                                     bch2_nfs_get_inode);
1122 }
1123
1124 static const struct export_operations bch_export_ops = {
1125         .fh_to_dentry   = bch2_fh_to_dentry,
1126         .fh_to_parent   = bch2_fh_to_parent,
1127         //.get_parent   = bch2_get_parent,
1128 };
1129
1130 static void bch2_vfs_inode_init(struct bch_fs *c,
1131                                 struct bch_inode_info *inode,
1132                                 struct bch_inode_unpacked *bi)
1133 {
1134         bch2_inode_update_after_write(c, inode, bi, ~0);
1135
1136         inode->v.i_blocks       = bi->bi_sectors;
1137         inode->v.i_ino          = bi->bi_inum;
1138         inode->v.i_rdev         = bi->bi_dev;
1139         inode->v.i_generation   = bi->bi_generation;
1140         inode->v.i_size         = bi->bi_size;
1141
1142         inode->ei_flags         = 0;
1143         inode->ei_journal_seq   = 0;
1144         inode->ei_quota_reserved = 0;
1145         inode->ei_qid           = bch_qid(bi);
1146
1147         inode->v.i_mapping->a_ops = &bch_address_space_operations;
1148
1149         switch (inode->v.i_mode & S_IFMT) {
1150         case S_IFREG:
1151                 inode->v.i_op   = &bch_file_inode_operations;
1152                 inode->v.i_fop  = &bch_file_operations;
1153                 break;
1154         case S_IFDIR:
1155                 inode->v.i_op   = &bch_dir_inode_operations;
1156                 inode->v.i_fop  = &bch_dir_file_operations;
1157                 break;
1158         case S_IFLNK:
1159                 inode_nohighmem(&inode->v);
1160                 inode->v.i_op   = &bch_symlink_inode_operations;
1161                 break;
1162         default:
1163                 init_special_inode(&inode->v, inode->v.i_mode, inode->v.i_rdev);
1164                 inode->v.i_op   = &bch_special_inode_operations;
1165                 break;
1166         }
1167 }
1168
1169 static struct inode *bch2_alloc_inode(struct super_block *sb)
1170 {
1171         struct bch_inode_info *inode;
1172
1173         inode = kmem_cache_alloc(bch2_inode_cache, GFP_NOFS);
1174         if (!inode)
1175                 return NULL;
1176
1177         inode_init_once(&inode->v);
1178         mutex_init(&inode->ei_update_lock);
1179         pagecache_lock_init(&inode->ei_pagecache_lock);
1180         mutex_init(&inode->ei_quota_lock);
1181         inode->ei_journal_seq = 0;
1182
1183         return &inode->v;
1184 }
1185
1186 static void bch2_i_callback(struct rcu_head *head)
1187 {
1188         struct inode *vinode = container_of(head, struct inode, i_rcu);
1189         struct bch_inode_info *inode = to_bch_ei(vinode);
1190
1191         kmem_cache_free(bch2_inode_cache, inode);
1192 }
1193
1194 static void bch2_destroy_inode(struct inode *vinode)
1195 {
1196         call_rcu(&vinode->i_rcu, bch2_i_callback);
1197 }
1198
1199 static int inode_update_times_fn(struct bch_inode_info *inode,
1200                                  struct bch_inode_unpacked *bi,
1201                                  void *p)
1202 {
1203         struct bch_fs *c = inode->v.i_sb->s_fs_info;
1204
1205         bi->bi_atime    = timespec_to_bch2_time(c, inode->v.i_atime);
1206         bi->bi_mtime    = timespec_to_bch2_time(c, inode->v.i_mtime);
1207         bi->bi_ctime    = timespec_to_bch2_time(c, inode->v.i_ctime);
1208
1209         return 0;
1210 }
1211
1212 static int bch2_vfs_write_inode(struct inode *vinode,
1213                                 struct writeback_control *wbc)
1214 {
1215         struct bch_fs *c = vinode->i_sb->s_fs_info;
1216         struct bch_inode_info *inode = to_bch_ei(vinode);
1217         int ret;
1218
1219         mutex_lock(&inode->ei_update_lock);
1220         ret = bch2_write_inode(c, inode, inode_update_times_fn, NULL,
1221                                ATTR_ATIME|ATTR_MTIME|ATTR_CTIME);
1222         mutex_unlock(&inode->ei_update_lock);
1223
1224         return ret;
1225 }
1226
1227 static void bch2_evict_inode(struct inode *vinode)
1228 {
1229         struct bch_fs *c = vinode->i_sb->s_fs_info;
1230         struct bch_inode_info *inode = to_bch_ei(vinode);
1231
1232         truncate_inode_pages_final(&inode->v.i_data);
1233
1234         clear_inode(&inode->v);
1235
1236         BUG_ON(!is_bad_inode(&inode->v) && inode->ei_quota_reserved);
1237
1238         if (!inode->v.i_nlink && !is_bad_inode(&inode->v)) {
1239                 bch2_quota_acct(c, inode->ei_qid, Q_SPC, -((s64) inode->v.i_blocks),
1240                                 KEY_TYPE_QUOTA_WARN);
1241                 bch2_quota_acct(c, inode->ei_qid, Q_INO, -1,
1242                                 KEY_TYPE_QUOTA_WARN);
1243                 bch2_inode_rm(c, inode->v.i_ino, true);
1244         }
1245 }
1246
1247 static int bch2_statfs(struct dentry *dentry, struct kstatfs *buf)
1248 {
1249         struct super_block *sb = dentry->d_sb;
1250         struct bch_fs *c = sb->s_fs_info;
1251         struct bch_fs_usage_short usage = bch2_fs_usage_read_short(c);
1252         unsigned shift = sb->s_blocksize_bits - 9;
1253         /*
1254          * this assumes inodes take up 64 bytes, which is a decent average
1255          * number:
1256          */
1257         u64 avail_inodes = ((usage.capacity - usage.used) << 3);
1258         u64 fsid;
1259
1260         buf->f_type     = BCACHEFS_STATFS_MAGIC;
1261         buf->f_bsize    = sb->s_blocksize;
1262         buf->f_blocks   = usage.capacity >> shift;
1263         buf->f_bfree    = (usage.capacity - usage.used) >> shift;
1264         buf->f_bavail   = buf->f_bfree;
1265
1266         buf->f_files    = usage.nr_inodes + avail_inodes;
1267         buf->f_ffree    = avail_inodes;
1268
1269         fsid = le64_to_cpup((void *) c->sb.user_uuid.b) ^
1270                le64_to_cpup((void *) c->sb.user_uuid.b + sizeof(u64));
1271         buf->f_fsid.val[0] = fsid & 0xFFFFFFFFUL;
1272         buf->f_fsid.val[1] = (fsid >> 32) & 0xFFFFFFFFUL;
1273         buf->f_namelen  = BCH_NAME_MAX;
1274
1275         return 0;
1276 }
1277
1278 static int bch2_sync_fs(struct super_block *sb, int wait)
1279 {
1280         struct bch_fs *c = sb->s_fs_info;
1281
1282         if (c->opts.journal_flush_disabled)
1283                 return 0;
1284
1285         if (!wait) {
1286                 bch2_journal_flush_async(&c->journal, NULL);
1287                 return 0;
1288         }
1289
1290         return bch2_journal_flush(&c->journal);
1291 }
1292
1293 static struct bch_fs *bch2_path_to_fs(const char *dev)
1294 {
1295         struct bch_fs *c;
1296         struct block_device *bdev = lookup_bdev(dev);
1297
1298         if (IS_ERR(bdev))
1299                 return ERR_CAST(bdev);
1300
1301         c = bch2_bdev_to_fs(bdev);
1302         bdput(bdev);
1303         if (c)
1304                 closure_put(&c->cl);
1305         return c ?: ERR_PTR(-ENOENT);
1306 }
1307
1308 static char **split_devs(const char *_dev_name, unsigned *nr)
1309 {
1310         char *dev_name = NULL, **devs = NULL, *s;
1311         size_t i, nr_devs = 0;
1312
1313         dev_name = kstrdup(_dev_name, GFP_KERNEL);
1314         if (!dev_name)
1315                 return NULL;
1316
1317         for (s = dev_name; s; s = strchr(s + 1, ':'))
1318                 nr_devs++;
1319
1320         devs = kcalloc(nr_devs + 1, sizeof(const char *), GFP_KERNEL);
1321         if (!devs) {
1322                 kfree(dev_name);
1323                 return NULL;
1324         }
1325
1326         for (i = 0, s = dev_name;
1327              s;
1328              (s = strchr(s, ':')) && (*s++ = '\0'))
1329                 devs[i++] = s;
1330
1331         *nr = nr_devs;
1332         return devs;
1333 }
1334
1335 static int bch2_remount(struct super_block *sb, int *flags, char *data)
1336 {
1337         struct bch_fs *c = sb->s_fs_info;
1338         struct bch_opts opts = bch2_opts_empty();
1339         int ret;
1340
1341         opt_set(opts, read_only, (*flags & SB_RDONLY) != 0);
1342
1343         ret = bch2_parse_mount_opts(c, &opts, data);
1344         if (ret)
1345                 return ret;
1346
1347         if (opts.read_only != c->opts.read_only) {
1348                 down_write(&c->state_lock);
1349
1350                 if (opts.read_only) {
1351                         bch2_fs_read_only(c);
1352
1353                         sb->s_flags |= SB_RDONLY;
1354                 } else {
1355                         ret = bch2_fs_read_write(c);
1356                         if (ret) {
1357                                 bch_err(c, "error going rw: %i", ret);
1358                                 up_write(&c->state_lock);
1359                                 return -EINVAL;
1360                         }
1361
1362                         sb->s_flags &= ~SB_RDONLY;
1363                 }
1364
1365                 c->opts.read_only = opts.read_only;
1366
1367                 up_write(&c->state_lock);
1368         }
1369
1370         if (opts.errors >= 0)
1371                 c->opts.errors = opts.errors;
1372
1373         return ret;
1374 }
1375
1376 static int bch2_show_devname(struct seq_file *seq, struct dentry *root)
1377 {
1378         struct bch_fs *c = root->d_sb->s_fs_info;
1379         struct bch_dev *ca;
1380         unsigned i;
1381         bool first = true;
1382
1383         for_each_online_member(ca, c, i) {
1384                 if (!first)
1385                         seq_putc(seq, ':');
1386                 first = false;
1387                 seq_puts(seq, "/dev/");
1388                 seq_puts(seq, ca->name);
1389         }
1390
1391         return 0;
1392 }
1393
1394 static int bch2_show_options(struct seq_file *seq, struct dentry *root)
1395 {
1396         struct bch_fs *c = root->d_sb->s_fs_info;
1397         enum bch_opt_id i;
1398         char buf[512];
1399
1400         for (i = 0; i < bch2_opts_nr; i++) {
1401                 const struct bch_option *opt = &bch2_opt_table[i];
1402                 u64 v = bch2_opt_get_by_id(&c->opts, i);
1403
1404                 if (!(opt->mode & OPT_MOUNT))
1405                         continue;
1406
1407                 if (v == bch2_opt_get_by_id(&bch2_opts_default, i))
1408                         continue;
1409
1410                 bch2_opt_to_text(&PBUF(buf), c, opt, v,
1411                                  OPT_SHOW_MOUNT_STYLE);
1412                 seq_putc(seq, ',');
1413                 seq_puts(seq, buf);
1414         }
1415
1416         return 0;
1417 }
1418
1419 static void bch2_put_super(struct super_block *sb)
1420 {
1421         struct bch_fs *c = sb->s_fs_info;
1422
1423         __bch2_fs_stop(c);
1424 }
1425
1426 static const struct super_operations bch_super_operations = {
1427         .alloc_inode    = bch2_alloc_inode,
1428         .destroy_inode  = bch2_destroy_inode,
1429         .write_inode    = bch2_vfs_write_inode,
1430         .evict_inode    = bch2_evict_inode,
1431         .sync_fs        = bch2_sync_fs,
1432         .statfs         = bch2_statfs,
1433         .show_devname   = bch2_show_devname,
1434         .show_options   = bch2_show_options,
1435         .remount_fs     = bch2_remount,
1436         .put_super      = bch2_put_super,
1437 #if 0
1438         .freeze_fs      = bch2_freeze,
1439         .unfreeze_fs    = bch2_unfreeze,
1440 #endif
1441 };
1442
1443 static int bch2_set_super(struct super_block *s, void *data)
1444 {
1445         s->s_fs_info = data;
1446         return 0;
1447 }
1448
1449 static int bch2_noset_super(struct super_block *s, void *data)
1450 {
1451         return -EBUSY;
1452 }
1453
1454 static int bch2_test_super(struct super_block *s, void *data)
1455 {
1456         struct bch_fs *c = s->s_fs_info;
1457         struct bch_fs **devs = data;
1458         unsigned i;
1459
1460         if (!c)
1461                 return false;
1462
1463         for (i = 0; devs[i]; i++)
1464                 if (c != devs[i])
1465                         return false;
1466         return true;
1467 }
1468
1469 static struct dentry *bch2_mount(struct file_system_type *fs_type,
1470                                  int flags, const char *dev_name, void *data)
1471 {
1472         struct bch_fs *c;
1473         struct bch_dev *ca;
1474         struct super_block *sb;
1475         struct inode *vinode;
1476         struct bch_opts opts = bch2_opts_empty();
1477         char **devs;
1478         struct bch_fs **devs_to_fs = NULL;
1479         unsigned i, nr_devs;
1480         int ret;
1481
1482         opt_set(opts, read_only, (flags & SB_RDONLY) != 0);
1483
1484         ret = bch2_parse_mount_opts(NULL, &opts, data);
1485         if (ret)
1486                 return ERR_PTR(ret);
1487
1488         devs = split_devs(dev_name, &nr_devs);
1489         if (!devs)
1490                 return ERR_PTR(-ENOMEM);
1491
1492         devs_to_fs = kcalloc(nr_devs + 1, sizeof(void *), GFP_KERNEL);
1493         if (!devs_to_fs) {
1494                 sb = ERR_PTR(-ENOMEM);
1495                 goto got_sb;
1496         }
1497
1498         for (i = 0; i < nr_devs; i++)
1499                 devs_to_fs[i] = bch2_path_to_fs(devs[i]);
1500
1501         sb = sget(fs_type, bch2_test_super, bch2_noset_super,
1502                   flags|SB_NOSEC, devs_to_fs);
1503         if (!IS_ERR(sb))
1504                 goto got_sb;
1505
1506         c = bch2_fs_open(devs, nr_devs, opts);
1507         if (IS_ERR(c)) {
1508                 sb = ERR_CAST(c);
1509                 goto got_sb;
1510         }
1511
1512         /* Some options can't be parsed until after the fs is started: */
1513         ret = bch2_parse_mount_opts(c, &opts, data);
1514         if (ret) {
1515                 bch2_fs_stop(c);
1516                 sb = ERR_PTR(ret);
1517                 goto got_sb;
1518         }
1519
1520         bch2_opts_apply(&c->opts, opts);
1521
1522         sb = sget(fs_type, NULL, bch2_set_super, flags|SB_NOSEC, c);
1523         if (IS_ERR(sb))
1524                 bch2_fs_stop(c);
1525 got_sb:
1526         kfree(devs_to_fs);
1527         kfree(devs[0]);
1528         kfree(devs);
1529
1530         if (IS_ERR(sb))
1531                 return ERR_CAST(sb);
1532
1533         c = sb->s_fs_info;
1534
1535         if (sb->s_root) {
1536                 if ((flags ^ sb->s_flags) & SB_RDONLY) {
1537                         ret = -EBUSY;
1538                         goto err_put_super;
1539                 }
1540                 goto out;
1541         }
1542
1543         sb->s_blocksize         = block_bytes(c);
1544         sb->s_blocksize_bits    = ilog2(block_bytes(c));
1545         sb->s_maxbytes          = MAX_LFS_FILESIZE;
1546         sb->s_op                = &bch_super_operations;
1547         sb->s_export_op         = &bch_export_ops;
1548 #ifdef CONFIG_BCACHEFS_QUOTA
1549         sb->s_qcop              = &bch2_quotactl_operations;
1550         sb->s_quota_types       = QTYPE_MASK_USR|QTYPE_MASK_GRP|QTYPE_MASK_PRJ;
1551 #endif
1552         sb->s_xattr             = bch2_xattr_handlers;
1553         sb->s_magic             = BCACHEFS_STATFS_MAGIC;
1554         sb->s_time_gran         = c->sb.time_precision;
1555         c->vfs_sb               = sb;
1556         strlcpy(sb->s_id, c->name, sizeof(sb->s_id));
1557
1558         ret = super_setup_bdi(sb);
1559         if (ret)
1560                 goto err_put_super;
1561
1562         sb->s_bdi->ra_pages             = VM_READAHEAD_PAGES;
1563
1564         for_each_online_member(ca, c, i) {
1565                 struct block_device *bdev = ca->disk_sb.bdev;
1566
1567                 /* XXX: create an anonymous device for multi device filesystems */
1568                 sb->s_bdev      = bdev;
1569                 sb->s_dev       = bdev->bd_dev;
1570                 percpu_ref_put(&ca->io_ref);
1571                 break;
1572         }
1573
1574 #ifdef CONFIG_BCACHEFS_POSIX_ACL
1575         if (c->opts.acl)
1576                 sb->s_flags     |= SB_POSIXACL;
1577 #endif
1578
1579         vinode = bch2_vfs_inode_get(c, BCACHEFS_ROOT_INO);
1580         if (IS_ERR(vinode)) {
1581                 bch_err(c, "error mounting: error getting root inode %i",
1582                         (int) PTR_ERR(vinode));
1583                 ret = PTR_ERR(vinode);
1584                 goto err_put_super;
1585         }
1586
1587         sb->s_root = d_make_root(vinode);
1588         if (!sb->s_root) {
1589                 bch_err(c, "error mounting: error allocating root dentry");
1590                 ret = -ENOMEM;
1591                 goto err_put_super;
1592         }
1593
1594         sb->s_flags |= SB_ACTIVE;
1595 out:
1596         return dget(sb->s_root);
1597
1598 err_put_super:
1599         deactivate_locked_super(sb);
1600         return ERR_PTR(ret);
1601 }
1602
1603 static void bch2_kill_sb(struct super_block *sb)
1604 {
1605         struct bch_fs *c = sb->s_fs_info;
1606
1607         generic_shutdown_super(sb);
1608         bch2_fs_free(c);
1609 }
1610
1611 static struct file_system_type bcache_fs_type = {
1612         .owner          = THIS_MODULE,
1613         .name           = "bcachefs",
1614         .mount          = bch2_mount,
1615         .kill_sb        = bch2_kill_sb,
1616         .fs_flags       = FS_REQUIRES_DEV,
1617 };
1618
1619 MODULE_ALIAS_FS("bcachefs");
1620
1621 void bch2_vfs_exit(void)
1622 {
1623         unregister_filesystem(&bcache_fs_type);
1624         if (bch2_inode_cache)
1625                 kmem_cache_destroy(bch2_inode_cache);
1626 }
1627
1628 int __init bch2_vfs_init(void)
1629 {
1630         int ret = -ENOMEM;
1631
1632         bch2_inode_cache = KMEM_CACHE(bch_inode_info, 0);
1633         if (!bch2_inode_cache)
1634                 goto err;
1635
1636         ret = register_filesystem(&bcache_fs_type);
1637         if (ret)
1638                 goto err;
1639
1640         return 0;
1641 err:
1642         bch2_vfs_exit();
1643         return ret;
1644 }
1645
1646 #endif /* NO_BCACHEFS_FS */