]> git.sesse.net Git - bcachefs-tools-debian/blob - libbcachefs/fs.c
Update bcachefs sources to c7defb5793 bcachefs: Split btree_iter_traverse and 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 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         bch2_trans_iter_put(&trans, inode_iter);
729
730         if (ret == -EINTR)
731                 goto retry;
732         if (unlikely(ret))
733                 goto err_trans;
734
735         bch2_inode_update_after_write(c, inode, &inode_u, attr->ia_valid);
736
737         if (acl)
738                 set_cached_acl(&inode->v, ACL_TYPE_ACCESS, acl);
739 err_trans:
740         bch2_trans_exit(&trans);
741 err:
742         mutex_unlock(&inode->ei_update_lock);
743
744         return ret;
745 }
746
747 static int bch2_getattr(const struct path *path, struct kstat *stat,
748                         u32 request_mask, unsigned query_flags)
749 {
750         struct bch_inode_info *inode = to_bch_ei(d_inode(path->dentry));
751         struct bch_fs *c = inode->v.i_sb->s_fs_info;
752
753         stat->dev       = inode->v.i_sb->s_dev;
754         stat->ino       = inode->v.i_ino;
755         stat->mode      = inode->v.i_mode;
756         stat->nlink     = inode->v.i_nlink;
757         stat->uid       = inode->v.i_uid;
758         stat->gid       = inode->v.i_gid;
759         stat->rdev      = inode->v.i_rdev;
760         stat->size      = i_size_read(&inode->v);
761         stat->atime     = inode->v.i_atime;
762         stat->mtime     = inode->v.i_mtime;
763         stat->ctime     = inode->v.i_ctime;
764         stat->blksize   = block_bytes(c);
765         stat->blocks    = inode->v.i_blocks;
766
767         if (request_mask & STATX_BTIME) {
768                 stat->result_mask |= STATX_BTIME;
769                 stat->btime = bch2_time_to_timespec(c, inode->ei_inode.bi_otime);
770         }
771
772         if (inode->ei_inode.bi_flags & BCH_INODE_IMMUTABLE)
773                 stat->attributes |= STATX_ATTR_IMMUTABLE;
774         stat->attributes_mask    |= STATX_ATTR_IMMUTABLE;
775
776         if (inode->ei_inode.bi_flags & BCH_INODE_APPEND)
777                 stat->attributes |= STATX_ATTR_APPEND;
778         stat->attributes_mask    |= STATX_ATTR_APPEND;
779
780         if (inode->ei_inode.bi_flags & BCH_INODE_NODUMP)
781                 stat->attributes |= STATX_ATTR_NODUMP;
782         stat->attributes_mask    |= STATX_ATTR_NODUMP;
783
784         return 0;
785 }
786
787 static int bch2_setattr(struct dentry *dentry, struct iattr *iattr)
788 {
789         struct bch_inode_info *inode = to_bch_ei(dentry->d_inode);
790         int ret;
791
792         lockdep_assert_held(&inode->v.i_rwsem);
793
794         ret = setattr_prepare(dentry, iattr);
795         if (ret)
796                 return ret;
797
798         return iattr->ia_valid & ATTR_SIZE
799                 ? bch2_truncate(inode, iattr)
800                 : bch2_setattr_nonsize(inode, iattr);
801 }
802
803 static int bch2_tmpfile(struct inode *vdir, struct dentry *dentry, umode_t mode)
804 {
805         struct bch_inode_info *inode =
806                 __bch2_create(to_bch_ei(vdir), dentry, mode, 0, true);
807
808         if (IS_ERR(inode))
809                 return PTR_ERR(inode);
810
811         d_mark_tmpfile(dentry, &inode->v);
812         d_instantiate(dentry, &inode->v);
813         return 0;
814 }
815
816 static int bch2_fill_extent(struct bch_fs *c,
817                             struct fiemap_extent_info *info,
818                             struct bkey_s_c k, unsigned flags)
819 {
820         if (bkey_extent_is_direct_data(k.k)) {
821                 struct bkey_ptrs_c ptrs = bch2_bkey_ptrs_c(k);
822                 const union bch_extent_entry *entry;
823                 struct extent_ptr_decoded p;
824                 int ret;
825
826                 if (k.k->type == KEY_TYPE_reflink_v)
827                         flags |= FIEMAP_EXTENT_SHARED;
828
829                 bkey_for_each_ptr_decode(k.k, ptrs, p, entry) {
830                         int flags2 = 0;
831                         u64 offset = p.ptr.offset;
832
833                         if (p.crc.compression_type)
834                                 flags2 |= FIEMAP_EXTENT_ENCODED;
835                         else
836                                 offset += p.crc.offset;
837
838                         if ((offset & (c->opts.block_size - 1)) ||
839                             (k.k->size & (c->opts.block_size - 1)))
840                                 flags2 |= FIEMAP_EXTENT_NOT_ALIGNED;
841
842                         ret = fiemap_fill_next_extent(info,
843                                                 bkey_start_offset(k.k) << 9,
844                                                 offset << 9,
845                                                 k.k->size << 9, flags|flags2);
846                         if (ret)
847                                 return ret;
848                 }
849
850                 return 0;
851         } else if (bkey_extent_is_inline_data(k.k)) {
852                 return fiemap_fill_next_extent(info,
853                                                bkey_start_offset(k.k) << 9,
854                                                0, k.k->size << 9,
855                                                flags|
856                                                FIEMAP_EXTENT_DATA_INLINE);
857         } else if (k.k->type == KEY_TYPE_reservation) {
858                 return fiemap_fill_next_extent(info,
859                                                bkey_start_offset(k.k) << 9,
860                                                0, k.k->size << 9,
861                                                flags|
862                                                FIEMAP_EXTENT_DELALLOC|
863                                                FIEMAP_EXTENT_UNWRITTEN);
864         } else {
865                 BUG();
866         }
867 }
868
869 static int bch2_fiemap(struct inode *vinode, struct fiemap_extent_info *info,
870                        u64 start, u64 len)
871 {
872         struct bch_fs *c = vinode->i_sb->s_fs_info;
873         struct bch_inode_info *ei = to_bch_ei(vinode);
874         struct btree_trans trans;
875         struct btree_iter *iter;
876         struct bkey_s_c k;
877         struct bkey_buf cur, prev;
878         struct bpos end = POS(ei->v.i_ino, (start + len) >> 9);
879         unsigned offset_into_extent, sectors;
880         bool have_extent = false;
881         int ret = 0;
882
883         ret = fiemap_prep(&ei->v, info, start, &len, FIEMAP_FLAG_SYNC);
884         if (ret)
885                 return ret;
886
887         if (start + len < start)
888                 return -EINVAL;
889
890         bch2_bkey_buf_init(&cur);
891         bch2_bkey_buf_init(&prev);
892         bch2_trans_init(&trans, c, 0, 0);
893
894         iter = bch2_trans_get_iter(&trans, BTREE_ID_extents,
895                                    POS(ei->v.i_ino, start >> 9), 0);
896 retry:
897         while ((k = bch2_btree_iter_peek(iter)).k &&
898                !(ret = bkey_err(k)) &&
899                bkey_cmp(iter->pos, end) < 0) {
900                 enum btree_id data_btree = BTREE_ID_extents;
901
902                 if (!bkey_extent_is_data(k.k) &&
903                     k.k->type != KEY_TYPE_reservation) {
904                         bch2_btree_iter_advance(iter);
905                         continue;
906                 }
907
908                 offset_into_extent      = iter->pos.offset -
909                         bkey_start_offset(k.k);
910                 sectors                 = k.k->size - offset_into_extent;
911
912                 bch2_bkey_buf_reassemble(&cur, c, k);
913
914                 ret = bch2_read_indirect_extent(&trans, &data_btree,
915                                         &offset_into_extent, &cur);
916                 if (ret)
917                         break;
918
919                 k = bkey_i_to_s_c(cur.k);
920                 bch2_bkey_buf_realloc(&prev, c, k.k->u64s);
921
922                 sectors = min(sectors, k.k->size - offset_into_extent);
923
924                 bch2_cut_front(POS(k.k->p.inode,
925                                    bkey_start_offset(k.k) +
926                                    offset_into_extent),
927                                cur.k);
928                 bch2_key_resize(&cur.k->k, sectors);
929                 cur.k->k.p = iter->pos;
930                 cur.k->k.p.offset += cur.k->k.size;
931
932                 if (have_extent) {
933                         ret = bch2_fill_extent(c, info,
934                                         bkey_i_to_s_c(prev.k), 0);
935                         if (ret)
936                                 break;
937                 }
938
939                 bkey_copy(prev.k, cur.k);
940                 have_extent = true;
941
942                 bch2_btree_iter_set_pos(iter,
943                         POS(iter->pos.inode, iter->pos.offset + sectors));
944         }
945
946         if (ret == -EINTR)
947                 goto retry;
948
949         if (!ret && have_extent)
950                 ret = bch2_fill_extent(c, info, bkey_i_to_s_c(prev.k),
951                                        FIEMAP_EXTENT_LAST);
952
953         bch2_trans_iter_put(&trans, iter);
954         ret = bch2_trans_exit(&trans) ?: ret;
955         bch2_bkey_buf_exit(&cur, c);
956         bch2_bkey_buf_exit(&prev, c);
957         return ret < 0 ? ret : 0;
958 }
959
960 static const struct vm_operations_struct bch_vm_ops = {
961         .fault          = bch2_page_fault,
962         .map_pages      = filemap_map_pages,
963         .page_mkwrite   = bch2_page_mkwrite,
964 };
965
966 static int bch2_mmap(struct file *file, struct vm_area_struct *vma)
967 {
968         file_accessed(file);
969
970         vma->vm_ops = &bch_vm_ops;
971         return 0;
972 }
973
974 /* Directories: */
975
976 static loff_t bch2_dir_llseek(struct file *file, loff_t offset, int whence)
977 {
978         return generic_file_llseek_size(file, offset, whence,
979                                         S64_MAX, S64_MAX);
980 }
981
982 static int bch2_vfs_readdir(struct file *file, struct dir_context *ctx)
983 {
984         struct bch_inode_info *inode = file_bch_inode(file);
985         struct bch_fs *c = inode->v.i_sb->s_fs_info;
986
987         if (!dir_emit_dots(file, ctx))
988                 return 0;
989
990         return bch2_readdir(c, inode->v.i_ino, ctx);
991 }
992
993 static const struct file_operations bch_file_operations = {
994         .llseek         = bch2_llseek,
995         .read_iter      = bch2_read_iter,
996         .write_iter     = bch2_write_iter,
997         .mmap           = bch2_mmap,
998         .open           = generic_file_open,
999         .fsync          = bch2_fsync,
1000         .splice_read    = generic_file_splice_read,
1001 #if 0
1002         /* Busted: */
1003         .splice_write   = iter_file_splice_write,
1004 #endif
1005         .fallocate      = bch2_fallocate_dispatch,
1006         .unlocked_ioctl = bch2_fs_file_ioctl,
1007 #ifdef CONFIG_COMPAT
1008         .compat_ioctl   = bch2_compat_fs_ioctl,
1009 #endif
1010         .remap_file_range = bch2_remap_file_range,
1011 };
1012
1013 static const struct inode_operations bch_file_inode_operations = {
1014         .getattr        = bch2_getattr,
1015         .setattr        = bch2_setattr,
1016         .fiemap         = bch2_fiemap,
1017         .listxattr      = bch2_xattr_list,
1018 #ifdef CONFIG_BCACHEFS_POSIX_ACL
1019         .get_acl        = bch2_get_acl,
1020         .set_acl        = bch2_set_acl,
1021 #endif
1022 };
1023
1024 static const struct inode_operations bch_dir_inode_operations = {
1025         .lookup         = bch2_lookup,
1026         .create         = bch2_create,
1027         .link           = bch2_link,
1028         .unlink         = bch2_unlink,
1029         .symlink        = bch2_symlink,
1030         .mkdir          = bch2_mkdir,
1031         .rmdir          = bch2_unlink,
1032         .mknod          = bch2_mknod,
1033         .rename         = bch2_rename2,
1034         .getattr        = bch2_getattr,
1035         .setattr        = bch2_setattr,
1036         .tmpfile        = bch2_tmpfile,
1037         .listxattr      = bch2_xattr_list,
1038 #ifdef CONFIG_BCACHEFS_POSIX_ACL
1039         .get_acl        = bch2_get_acl,
1040         .set_acl        = bch2_set_acl,
1041 #endif
1042 };
1043
1044 static const struct file_operations bch_dir_file_operations = {
1045         .llseek         = bch2_dir_llseek,
1046         .read           = generic_read_dir,
1047         .iterate_shared = bch2_vfs_readdir,
1048         .fsync          = bch2_fsync,
1049         .unlocked_ioctl = bch2_fs_file_ioctl,
1050 #ifdef CONFIG_COMPAT
1051         .compat_ioctl   = bch2_compat_fs_ioctl,
1052 #endif
1053 };
1054
1055 static const struct inode_operations bch_symlink_inode_operations = {
1056         .get_link       = page_get_link,
1057         .getattr        = bch2_getattr,
1058         .setattr        = bch2_setattr,
1059         .listxattr      = bch2_xattr_list,
1060 #ifdef CONFIG_BCACHEFS_POSIX_ACL
1061         .get_acl        = bch2_get_acl,
1062         .set_acl        = bch2_set_acl,
1063 #endif
1064 };
1065
1066 static const struct inode_operations bch_special_inode_operations = {
1067         .getattr        = bch2_getattr,
1068         .setattr        = bch2_setattr,
1069         .listxattr      = bch2_xattr_list,
1070 #ifdef CONFIG_BCACHEFS_POSIX_ACL
1071         .get_acl        = bch2_get_acl,
1072         .set_acl        = bch2_set_acl,
1073 #endif
1074 };
1075
1076 static const struct address_space_operations bch_address_space_operations = {
1077         .writepage      = bch2_writepage,
1078         .readpage       = bch2_readpage,
1079         .writepages     = bch2_writepages,
1080         .readahead      = bch2_readahead,
1081         .set_page_dirty = __set_page_dirty_nobuffers,
1082         .write_begin    = bch2_write_begin,
1083         .write_end      = bch2_write_end,
1084         .invalidatepage = bch2_invalidatepage,
1085         .releasepage    = bch2_releasepage,
1086         .direct_IO      = noop_direct_IO,
1087 #ifdef CONFIG_MIGRATION
1088         .migratepage    = bch2_migrate_page,
1089 #endif
1090         .error_remove_page = generic_error_remove_page,
1091 };
1092
1093 static struct inode *bch2_nfs_get_inode(struct super_block *sb,
1094                 u64 ino, u32 generation)
1095 {
1096         struct bch_fs *c = sb->s_fs_info;
1097         struct inode *vinode;
1098
1099         if (ino < BCACHEFS_ROOT_INO)
1100                 return ERR_PTR(-ESTALE);
1101
1102         vinode = bch2_vfs_inode_get(c, ino);
1103         if (IS_ERR(vinode))
1104                 return ERR_CAST(vinode);
1105         if (generation && vinode->i_generation != generation) {
1106                 /* we didn't find the right inode.. */
1107                 iput(vinode);
1108                 return ERR_PTR(-ESTALE);
1109         }
1110         return vinode;
1111 }
1112
1113 static struct dentry *bch2_fh_to_dentry(struct super_block *sb, struct fid *fid,
1114                 int fh_len, int fh_type)
1115 {
1116         return generic_fh_to_dentry(sb, fid, fh_len, fh_type,
1117                                     bch2_nfs_get_inode);
1118 }
1119
1120 static struct dentry *bch2_fh_to_parent(struct super_block *sb, struct fid *fid,
1121                 int fh_len, int fh_type)
1122 {
1123         return generic_fh_to_parent(sb, fid, fh_len, fh_type,
1124                                     bch2_nfs_get_inode);
1125 }
1126
1127 static const struct export_operations bch_export_ops = {
1128         .fh_to_dentry   = bch2_fh_to_dentry,
1129         .fh_to_parent   = bch2_fh_to_parent,
1130         //.get_parent   = bch2_get_parent,
1131 };
1132
1133 static void bch2_vfs_inode_init(struct bch_fs *c,
1134                                 struct bch_inode_info *inode,
1135                                 struct bch_inode_unpacked *bi)
1136 {
1137         bch2_inode_update_after_write(c, inode, bi, ~0);
1138
1139         inode->v.i_blocks       = bi->bi_sectors;
1140         inode->v.i_ino          = bi->bi_inum;
1141         inode->v.i_rdev         = bi->bi_dev;
1142         inode->v.i_generation   = bi->bi_generation;
1143         inode->v.i_size         = bi->bi_size;
1144
1145         inode->ei_flags         = 0;
1146         inode->ei_journal_seq   = 0;
1147         inode->ei_quota_reserved = 0;
1148         inode->ei_qid           = bch_qid(bi);
1149
1150         inode->v.i_mapping->a_ops = &bch_address_space_operations;
1151
1152         switch (inode->v.i_mode & S_IFMT) {
1153         case S_IFREG:
1154                 inode->v.i_op   = &bch_file_inode_operations;
1155                 inode->v.i_fop  = &bch_file_operations;
1156                 break;
1157         case S_IFDIR:
1158                 inode->v.i_op   = &bch_dir_inode_operations;
1159                 inode->v.i_fop  = &bch_dir_file_operations;
1160                 break;
1161         case S_IFLNK:
1162                 inode_nohighmem(&inode->v);
1163                 inode->v.i_op   = &bch_symlink_inode_operations;
1164                 break;
1165         default:
1166                 init_special_inode(&inode->v, inode->v.i_mode, inode->v.i_rdev);
1167                 inode->v.i_op   = &bch_special_inode_operations;
1168                 break;
1169         }
1170 }
1171
1172 static struct inode *bch2_alloc_inode(struct super_block *sb)
1173 {
1174         struct bch_inode_info *inode;
1175
1176         inode = kmem_cache_alloc(bch2_inode_cache, GFP_NOFS);
1177         if (!inode)
1178                 return NULL;
1179
1180         inode_init_once(&inode->v);
1181         mutex_init(&inode->ei_update_lock);
1182         pagecache_lock_init(&inode->ei_pagecache_lock);
1183         mutex_init(&inode->ei_quota_lock);
1184         inode->ei_journal_seq = 0;
1185
1186         return &inode->v;
1187 }
1188
1189 static void bch2_i_callback(struct rcu_head *head)
1190 {
1191         struct inode *vinode = container_of(head, struct inode, i_rcu);
1192         struct bch_inode_info *inode = to_bch_ei(vinode);
1193
1194         kmem_cache_free(bch2_inode_cache, inode);
1195 }
1196
1197 static void bch2_destroy_inode(struct inode *vinode)
1198 {
1199         call_rcu(&vinode->i_rcu, bch2_i_callback);
1200 }
1201
1202 static int inode_update_times_fn(struct bch_inode_info *inode,
1203                                  struct bch_inode_unpacked *bi,
1204                                  void *p)
1205 {
1206         struct bch_fs *c = inode->v.i_sb->s_fs_info;
1207
1208         bi->bi_atime    = timespec_to_bch2_time(c, inode->v.i_atime);
1209         bi->bi_mtime    = timespec_to_bch2_time(c, inode->v.i_mtime);
1210         bi->bi_ctime    = timespec_to_bch2_time(c, inode->v.i_ctime);
1211
1212         return 0;
1213 }
1214
1215 static int bch2_vfs_write_inode(struct inode *vinode,
1216                                 struct writeback_control *wbc)
1217 {
1218         struct bch_fs *c = vinode->i_sb->s_fs_info;
1219         struct bch_inode_info *inode = to_bch_ei(vinode);
1220         int ret;
1221
1222         mutex_lock(&inode->ei_update_lock);
1223         ret = bch2_write_inode(c, inode, inode_update_times_fn, NULL,
1224                                ATTR_ATIME|ATTR_MTIME|ATTR_CTIME);
1225         mutex_unlock(&inode->ei_update_lock);
1226
1227         return ret;
1228 }
1229
1230 static void bch2_evict_inode(struct inode *vinode)
1231 {
1232         struct bch_fs *c = vinode->i_sb->s_fs_info;
1233         struct bch_inode_info *inode = to_bch_ei(vinode);
1234
1235         truncate_inode_pages_final(&inode->v.i_data);
1236
1237         clear_inode(&inode->v);
1238
1239         BUG_ON(!is_bad_inode(&inode->v) && inode->ei_quota_reserved);
1240
1241         if (!inode->v.i_nlink && !is_bad_inode(&inode->v)) {
1242                 bch2_quota_acct(c, inode->ei_qid, Q_SPC, -((s64) inode->v.i_blocks),
1243                                 KEY_TYPE_QUOTA_WARN);
1244                 bch2_quota_acct(c, inode->ei_qid, Q_INO, -1,
1245                                 KEY_TYPE_QUOTA_WARN);
1246                 bch2_inode_rm(c, inode->v.i_ino, true);
1247         }
1248 }
1249
1250 static int bch2_statfs(struct dentry *dentry, struct kstatfs *buf)
1251 {
1252         struct super_block *sb = dentry->d_sb;
1253         struct bch_fs *c = sb->s_fs_info;
1254         struct bch_fs_usage_short usage = bch2_fs_usage_read_short(c);
1255         unsigned shift = sb->s_blocksize_bits - 9;
1256         /*
1257          * this assumes inodes take up 64 bytes, which is a decent average
1258          * number:
1259          */
1260         u64 avail_inodes = ((usage.capacity - usage.used) << 3);
1261         u64 fsid;
1262
1263         buf->f_type     = BCACHEFS_STATFS_MAGIC;
1264         buf->f_bsize    = sb->s_blocksize;
1265         buf->f_blocks   = usage.capacity >> shift;
1266         buf->f_bfree    = (usage.capacity - usage.used) >> shift;
1267         buf->f_bavail   = buf->f_bfree;
1268
1269         buf->f_files    = usage.nr_inodes + avail_inodes;
1270         buf->f_ffree    = avail_inodes;
1271
1272         fsid = le64_to_cpup((void *) c->sb.user_uuid.b) ^
1273                le64_to_cpup((void *) c->sb.user_uuid.b + sizeof(u64));
1274         buf->f_fsid.val[0] = fsid & 0xFFFFFFFFUL;
1275         buf->f_fsid.val[1] = (fsid >> 32) & 0xFFFFFFFFUL;
1276         buf->f_namelen  = BCH_NAME_MAX;
1277
1278         return 0;
1279 }
1280
1281 static int bch2_sync_fs(struct super_block *sb, int wait)
1282 {
1283         struct bch_fs *c = sb->s_fs_info;
1284
1285         if (c->opts.journal_flush_disabled)
1286                 return 0;
1287
1288         if (!wait) {
1289                 bch2_journal_flush_async(&c->journal, NULL);
1290                 return 0;
1291         }
1292
1293         return bch2_journal_flush(&c->journal);
1294 }
1295
1296 static struct bch_fs *bch2_path_to_fs(const char *dev)
1297 {
1298         struct bch_fs *c;
1299         struct block_device *bdev = lookup_bdev(dev);
1300
1301         if (IS_ERR(bdev))
1302                 return ERR_CAST(bdev);
1303
1304         c = bch2_bdev_to_fs(bdev);
1305         bdput(bdev);
1306         if (c)
1307                 closure_put(&c->cl);
1308         return c ?: ERR_PTR(-ENOENT);
1309 }
1310
1311 static char **split_devs(const char *_dev_name, unsigned *nr)
1312 {
1313         char *dev_name = NULL, **devs = NULL, *s;
1314         size_t i, nr_devs = 0;
1315
1316         dev_name = kstrdup(_dev_name, GFP_KERNEL);
1317         if (!dev_name)
1318                 return NULL;
1319
1320         for (s = dev_name; s; s = strchr(s + 1, ':'))
1321                 nr_devs++;
1322
1323         devs = kcalloc(nr_devs + 1, sizeof(const char *), GFP_KERNEL);
1324         if (!devs) {
1325                 kfree(dev_name);
1326                 return NULL;
1327         }
1328
1329         for (i = 0, s = dev_name;
1330              s;
1331              (s = strchr(s, ':')) && (*s++ = '\0'))
1332                 devs[i++] = s;
1333
1334         *nr = nr_devs;
1335         return devs;
1336 }
1337
1338 static int bch2_remount(struct super_block *sb, int *flags, char *data)
1339 {
1340         struct bch_fs *c = sb->s_fs_info;
1341         struct bch_opts opts = bch2_opts_empty();
1342         int ret;
1343
1344         opt_set(opts, read_only, (*flags & SB_RDONLY) != 0);
1345
1346         ret = bch2_parse_mount_opts(c, &opts, data);
1347         if (ret)
1348                 return ret;
1349
1350         if (opts.read_only != c->opts.read_only) {
1351                 down_write(&c->state_lock);
1352
1353                 if (opts.read_only) {
1354                         bch2_fs_read_only(c);
1355
1356                         sb->s_flags |= SB_RDONLY;
1357                 } else {
1358                         ret = bch2_fs_read_write(c);
1359                         if (ret) {
1360                                 bch_err(c, "error going rw: %i", ret);
1361                                 up_write(&c->state_lock);
1362                                 return -EINVAL;
1363                         }
1364
1365                         sb->s_flags &= ~SB_RDONLY;
1366                 }
1367
1368                 c->opts.read_only = opts.read_only;
1369
1370                 up_write(&c->state_lock);
1371         }
1372
1373         if (opts.errors >= 0)
1374                 c->opts.errors = opts.errors;
1375
1376         return ret;
1377 }
1378
1379 static int bch2_show_devname(struct seq_file *seq, struct dentry *root)
1380 {
1381         struct bch_fs *c = root->d_sb->s_fs_info;
1382         struct bch_dev *ca;
1383         unsigned i;
1384         bool first = true;
1385
1386         for_each_online_member(ca, c, i) {
1387                 if (!first)
1388                         seq_putc(seq, ':');
1389                 first = false;
1390                 seq_puts(seq, "/dev/");
1391                 seq_puts(seq, ca->name);
1392         }
1393
1394         return 0;
1395 }
1396
1397 static int bch2_show_options(struct seq_file *seq, struct dentry *root)
1398 {
1399         struct bch_fs *c = root->d_sb->s_fs_info;
1400         enum bch_opt_id i;
1401         char buf[512];
1402
1403         for (i = 0; i < bch2_opts_nr; i++) {
1404                 const struct bch_option *opt = &bch2_opt_table[i];
1405                 u64 v = bch2_opt_get_by_id(&c->opts, i);
1406
1407                 if (!(opt->mode & OPT_MOUNT))
1408                         continue;
1409
1410                 if (v == bch2_opt_get_by_id(&bch2_opts_default, i))
1411                         continue;
1412
1413                 bch2_opt_to_text(&PBUF(buf), c, opt, v,
1414                                  OPT_SHOW_MOUNT_STYLE);
1415                 seq_putc(seq, ',');
1416                 seq_puts(seq, buf);
1417         }
1418
1419         return 0;
1420 }
1421
1422 static void bch2_put_super(struct super_block *sb)
1423 {
1424         struct bch_fs *c = sb->s_fs_info;
1425
1426         __bch2_fs_stop(c);
1427 }
1428
1429 static const struct super_operations bch_super_operations = {
1430         .alloc_inode    = bch2_alloc_inode,
1431         .destroy_inode  = bch2_destroy_inode,
1432         .write_inode    = bch2_vfs_write_inode,
1433         .evict_inode    = bch2_evict_inode,
1434         .sync_fs        = bch2_sync_fs,
1435         .statfs         = bch2_statfs,
1436         .show_devname   = bch2_show_devname,
1437         .show_options   = bch2_show_options,
1438         .remount_fs     = bch2_remount,
1439         .put_super      = bch2_put_super,
1440 #if 0
1441         .freeze_fs      = bch2_freeze,
1442         .unfreeze_fs    = bch2_unfreeze,
1443 #endif
1444 };
1445
1446 static int bch2_set_super(struct super_block *s, void *data)
1447 {
1448         s->s_fs_info = data;
1449         return 0;
1450 }
1451
1452 static int bch2_noset_super(struct super_block *s, void *data)
1453 {
1454         return -EBUSY;
1455 }
1456
1457 static int bch2_test_super(struct super_block *s, void *data)
1458 {
1459         struct bch_fs *c = s->s_fs_info;
1460         struct bch_fs **devs = data;
1461         unsigned i;
1462
1463         if (!c)
1464                 return false;
1465
1466         for (i = 0; devs[i]; i++)
1467                 if (c != devs[i])
1468                         return false;
1469         return true;
1470 }
1471
1472 static struct dentry *bch2_mount(struct file_system_type *fs_type,
1473                                  int flags, const char *dev_name, void *data)
1474 {
1475         struct bch_fs *c;
1476         struct bch_dev *ca;
1477         struct super_block *sb;
1478         struct inode *vinode;
1479         struct bch_opts opts = bch2_opts_empty();
1480         char **devs;
1481         struct bch_fs **devs_to_fs = NULL;
1482         unsigned i, nr_devs;
1483         int ret;
1484
1485         opt_set(opts, read_only, (flags & SB_RDONLY) != 0);
1486
1487         ret = bch2_parse_mount_opts(NULL, &opts, data);
1488         if (ret)
1489                 return ERR_PTR(ret);
1490
1491         devs = split_devs(dev_name, &nr_devs);
1492         if (!devs)
1493                 return ERR_PTR(-ENOMEM);
1494
1495         devs_to_fs = kcalloc(nr_devs + 1, sizeof(void *), GFP_KERNEL);
1496         if (!devs_to_fs) {
1497                 sb = ERR_PTR(-ENOMEM);
1498                 goto got_sb;
1499         }
1500
1501         for (i = 0; i < nr_devs; i++)
1502                 devs_to_fs[i] = bch2_path_to_fs(devs[i]);
1503
1504         sb = sget(fs_type, bch2_test_super, bch2_noset_super,
1505                   flags|SB_NOSEC, devs_to_fs);
1506         if (!IS_ERR(sb))
1507                 goto got_sb;
1508
1509         c = bch2_fs_open(devs, nr_devs, opts);
1510         if (IS_ERR(c)) {
1511                 sb = ERR_CAST(c);
1512                 goto got_sb;
1513         }
1514
1515         /* Some options can't be parsed until after the fs is started: */
1516         ret = bch2_parse_mount_opts(c, &opts, data);
1517         if (ret) {
1518                 bch2_fs_stop(c);
1519                 sb = ERR_PTR(ret);
1520                 goto got_sb;
1521         }
1522
1523         bch2_opts_apply(&c->opts, opts);
1524
1525         sb = sget(fs_type, NULL, bch2_set_super, flags|SB_NOSEC, c);
1526         if (IS_ERR(sb))
1527                 bch2_fs_stop(c);
1528 got_sb:
1529         kfree(devs_to_fs);
1530         kfree(devs[0]);
1531         kfree(devs);
1532
1533         if (IS_ERR(sb))
1534                 return ERR_CAST(sb);
1535
1536         c = sb->s_fs_info;
1537
1538         if (sb->s_root) {
1539                 if ((flags ^ sb->s_flags) & SB_RDONLY) {
1540                         ret = -EBUSY;
1541                         goto err_put_super;
1542                 }
1543                 goto out;
1544         }
1545
1546         sb->s_blocksize         = block_bytes(c);
1547         sb->s_blocksize_bits    = ilog2(block_bytes(c));
1548         sb->s_maxbytes          = MAX_LFS_FILESIZE;
1549         sb->s_op                = &bch_super_operations;
1550         sb->s_export_op         = &bch_export_ops;
1551 #ifdef CONFIG_BCACHEFS_QUOTA
1552         sb->s_qcop              = &bch2_quotactl_operations;
1553         sb->s_quota_types       = QTYPE_MASK_USR|QTYPE_MASK_GRP|QTYPE_MASK_PRJ;
1554 #endif
1555         sb->s_xattr             = bch2_xattr_handlers;
1556         sb->s_magic             = BCACHEFS_STATFS_MAGIC;
1557         sb->s_time_gran         = c->sb.time_precision;
1558         c->vfs_sb               = sb;
1559         strlcpy(sb->s_id, c->name, sizeof(sb->s_id));
1560
1561         ret = super_setup_bdi(sb);
1562         if (ret)
1563                 goto err_put_super;
1564
1565         sb->s_bdi->ra_pages             = VM_READAHEAD_PAGES;
1566
1567         for_each_online_member(ca, c, i) {
1568                 struct block_device *bdev = ca->disk_sb.bdev;
1569
1570                 /* XXX: create an anonymous device for multi device filesystems */
1571                 sb->s_bdev      = bdev;
1572                 sb->s_dev       = bdev->bd_dev;
1573                 percpu_ref_put(&ca->io_ref);
1574                 break;
1575         }
1576
1577 #ifdef CONFIG_BCACHEFS_POSIX_ACL
1578         if (c->opts.acl)
1579                 sb->s_flags     |= SB_POSIXACL;
1580 #endif
1581
1582         vinode = bch2_vfs_inode_get(c, BCACHEFS_ROOT_INO);
1583         if (IS_ERR(vinode)) {
1584                 bch_err(c, "error mounting: error getting root inode %i",
1585                         (int) PTR_ERR(vinode));
1586                 ret = PTR_ERR(vinode);
1587                 goto err_put_super;
1588         }
1589
1590         sb->s_root = d_make_root(vinode);
1591         if (!sb->s_root) {
1592                 bch_err(c, "error mounting: error allocating root dentry");
1593                 ret = -ENOMEM;
1594                 goto err_put_super;
1595         }
1596
1597         sb->s_flags |= SB_ACTIVE;
1598 out:
1599         return dget(sb->s_root);
1600
1601 err_put_super:
1602         deactivate_locked_super(sb);
1603         return ERR_PTR(ret);
1604 }
1605
1606 static void bch2_kill_sb(struct super_block *sb)
1607 {
1608         struct bch_fs *c = sb->s_fs_info;
1609
1610         generic_shutdown_super(sb);
1611         bch2_fs_free(c);
1612 }
1613
1614 static struct file_system_type bcache_fs_type = {
1615         .owner          = THIS_MODULE,
1616         .name           = "bcachefs",
1617         .mount          = bch2_mount,
1618         .kill_sb        = bch2_kill_sb,
1619         .fs_flags       = FS_REQUIRES_DEV,
1620 };
1621
1622 MODULE_ALIAS_FS("bcachefs");
1623
1624 void bch2_vfs_exit(void)
1625 {
1626         unregister_filesystem(&bcache_fs_type);
1627         if (bch2_inode_cache)
1628                 kmem_cache_destroy(bch2_inode_cache);
1629 }
1630
1631 int __init bch2_vfs_init(void)
1632 {
1633         int ret = -ENOMEM;
1634
1635         bch2_inode_cache = KMEM_CACHE(bch_inode_info, 0);
1636         if (!bch2_inode_cache)
1637                 goto err;
1638
1639         ret = register_filesystem(&bcache_fs_type);
1640         if (ret)
1641                 goto err;
1642
1643         return 0;
1644 err:
1645         bch2_vfs_exit();
1646         return ret;
1647 }
1648
1649 #endif /* NO_BCACHEFS_FS */