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