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