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