xref: /linux/fs/bcachefs/fs.c (revision 6e7fd890f1d6ac83805409e9c346240de2705584)
1 // SPDX-License-Identifier: GPL-2.0
2 #ifndef NO_BCACHEFS_FS
3 
4 #include "bcachefs.h"
5 #include "acl.h"
6 #include "bkey_buf.h"
7 #include "btree_update.h"
8 #include "buckets.h"
9 #include "chardev.h"
10 #include "dirent.h"
11 #include "errcode.h"
12 #include "extents.h"
13 #include "fs.h"
14 #include "fs-common.h"
15 #include "fs-io.h"
16 #include "fs-ioctl.h"
17 #include "fs-io-buffered.h"
18 #include "fs-io-direct.h"
19 #include "fs-io-pagecache.h"
20 #include "fsck.h"
21 #include "inode.h"
22 #include "io_read.h"
23 #include "journal.h"
24 #include "keylist.h"
25 #include "quota.h"
26 #include "snapshot.h"
27 #include "super.h"
28 #include "xattr.h"
29 #include "trace.h"
30 
31 #include <linux/aio.h>
32 #include <linux/backing-dev.h>
33 #include <linux/exportfs.h>
34 #include <linux/fiemap.h>
35 #include <linux/fs_context.h>
36 #include <linux/module.h>
37 #include <linux/pagemap.h>
38 #include <linux/posix_acl.h>
39 #include <linux/random.h>
40 #include <linux/seq_file.h>
41 #include <linux/statfs.h>
42 #include <linux/string.h>
43 #include <linux/xattr.h>
44 
45 static struct kmem_cache *bch2_inode_cache;
46 
47 static void bch2_vfs_inode_init(struct btree_trans *, subvol_inum,
48 				struct bch_inode_info *,
49 				struct bch_inode_unpacked *,
50 				struct bch_subvolume *);
51 
52 void bch2_inode_update_after_write(struct btree_trans *trans,
53 				   struct bch_inode_info *inode,
54 				   struct bch_inode_unpacked *bi,
55 				   unsigned fields)
56 {
57 	struct bch_fs *c = trans->c;
58 
59 	BUG_ON(bi->bi_inum != inode->v.i_ino);
60 
61 	bch2_assert_pos_locked(trans, BTREE_ID_inodes, POS(0, bi->bi_inum));
62 
63 	set_nlink(&inode->v, bch2_inode_nlink_get(bi));
64 	i_uid_write(&inode->v, bi->bi_uid);
65 	i_gid_write(&inode->v, bi->bi_gid);
66 	inode->v.i_mode	= bi->bi_mode;
67 
68 	if (fields & ATTR_ATIME)
69 		inode_set_atime_to_ts(&inode->v, bch2_time_to_timespec(c, bi->bi_atime));
70 	if (fields & ATTR_MTIME)
71 		inode_set_mtime_to_ts(&inode->v, bch2_time_to_timespec(c, bi->bi_mtime));
72 	if (fields & ATTR_CTIME)
73 		inode_set_ctime_to_ts(&inode->v, bch2_time_to_timespec(c, bi->bi_ctime));
74 
75 	inode->ei_inode		= *bi;
76 
77 	bch2_inode_flags_to_vfs(inode);
78 }
79 
80 int __must_check bch2_write_inode(struct bch_fs *c,
81 				  struct bch_inode_info *inode,
82 				  inode_set_fn set,
83 				  void *p, unsigned fields)
84 {
85 	struct btree_trans *trans = bch2_trans_get(c);
86 	struct btree_iter iter = { NULL };
87 	struct bch_inode_unpacked inode_u;
88 	int ret;
89 retry:
90 	bch2_trans_begin(trans);
91 
92 	ret   = bch2_inode_peek(trans, &iter, &inode_u, inode_inum(inode),
93 				BTREE_ITER_intent) ?:
94 		(set ? set(trans, inode, &inode_u, p) : 0) ?:
95 		bch2_inode_write(trans, &iter, &inode_u) ?:
96 		bch2_trans_commit(trans, NULL, NULL, BCH_TRANS_COMMIT_no_enospc);
97 
98 	/*
99 	 * the btree node lock protects inode->ei_inode, not ei_update_lock;
100 	 * this is important for inode updates via bchfs_write_index_update
101 	 */
102 	if (!ret)
103 		bch2_inode_update_after_write(trans, inode, &inode_u, fields);
104 
105 	bch2_trans_iter_exit(trans, &iter);
106 
107 	if (bch2_err_matches(ret, BCH_ERR_transaction_restart))
108 		goto retry;
109 
110 	bch2_fs_fatal_err_on(bch2_err_matches(ret, ENOENT), c,
111 			     "%s: inode %u:%llu not found when updating",
112 			     bch2_err_str(ret),
113 			     inode_inum(inode).subvol,
114 			     inode_inum(inode).inum);
115 
116 	bch2_trans_put(trans);
117 	return ret < 0 ? ret : 0;
118 }
119 
120 int bch2_fs_quota_transfer(struct bch_fs *c,
121 			   struct bch_inode_info *inode,
122 			   struct bch_qid new_qid,
123 			   unsigned qtypes,
124 			   enum quota_acct_mode mode)
125 {
126 	unsigned i;
127 	int ret;
128 
129 	qtypes &= enabled_qtypes(c);
130 
131 	for (i = 0; i < QTYP_NR; i++)
132 		if (new_qid.q[i] == inode->ei_qid.q[i])
133 			qtypes &= ~(1U << i);
134 
135 	if (!qtypes)
136 		return 0;
137 
138 	mutex_lock(&inode->ei_quota_lock);
139 
140 	ret = bch2_quota_transfer(c, qtypes, new_qid,
141 				  inode->ei_qid,
142 				  inode->v.i_blocks +
143 				  inode->ei_quota_reserved,
144 				  mode);
145 	if (!ret)
146 		for (i = 0; i < QTYP_NR; i++)
147 			if (qtypes & (1 << i))
148 				inode->ei_qid.q[i] = new_qid.q[i];
149 
150 	mutex_unlock(&inode->ei_quota_lock);
151 
152 	return ret;
153 }
154 
155 static int bch2_iget5_test(struct inode *vinode, void *p)
156 {
157 	struct bch_inode_info *inode = to_bch_ei(vinode);
158 	subvol_inum *inum = p;
159 
160 	return inode->ei_subvol == inum->subvol &&
161 		inode->ei_inode.bi_inum == inum->inum;
162 }
163 
164 static int bch2_iget5_set(struct inode *vinode, void *p)
165 {
166 	struct bch_inode_info *inode = to_bch_ei(vinode);
167 	subvol_inum *inum = p;
168 
169 	inode->v.i_ino		= inum->inum;
170 	inode->ei_subvol	= inum->subvol;
171 	inode->ei_inode.bi_inum	= inum->inum;
172 	return 0;
173 }
174 
175 static unsigned bch2_inode_hash(subvol_inum inum)
176 {
177 	return jhash_3words(inum.subvol, inum.inum >> 32, inum.inum, JHASH_INITVAL);
178 }
179 
180 static struct bch_inode_info *bch2_inode_insert(struct bch_fs *c, struct bch_inode_info *inode)
181 {
182 	subvol_inum inum = inode_inum(inode);
183 	struct bch_inode_info *old = to_bch_ei(inode_insert5(&inode->v,
184 				      bch2_inode_hash(inum),
185 				      bch2_iget5_test,
186 				      bch2_iget5_set,
187 				      &inum));
188 	BUG_ON(!old);
189 
190 	if (unlikely(old != inode)) {
191 		/*
192 		 * bcachefs doesn't use I_NEW; we have no use for it since we
193 		 * only insert fully created inodes in the inode hash table. But
194 		 * discard_new_inode() expects it to be set...
195 		 */
196 		inode->v.i_state |= I_NEW;
197 		/*
198 		 * We don't want bch2_evict_inode() to delete the inode on disk,
199 		 * we just raced and had another inode in cache. Normally new
200 		 * inodes don't have nlink == 0 - except tmpfiles do...
201 		 */
202 		set_nlink(&inode->v, 1);
203 		discard_new_inode(&inode->v);
204 		inode = old;
205 	} else {
206 		mutex_lock(&c->vfs_inodes_lock);
207 		list_add(&inode->ei_vfs_inode_list, &c->vfs_inodes_list);
208 		mutex_unlock(&c->vfs_inodes_lock);
209 		/*
210 		 * Again, I_NEW makes no sense for bcachefs. This is only needed
211 		 * for clearing I_NEW, but since the inode was already fully
212 		 * created and initialized we didn't actually want
213 		 * inode_insert5() to set it for us.
214 		 */
215 		unlock_new_inode(&inode->v);
216 	}
217 
218 	return inode;
219 }
220 
221 #define memalloc_flags_do(_flags, _do)						\
222 ({										\
223 	unsigned _saved_flags = memalloc_flags_save(_flags);			\
224 	typeof(_do) _ret = _do;							\
225 	memalloc_noreclaim_restore(_saved_flags);				\
226 	_ret;									\
227 })
228 
229 static struct inode *bch2_alloc_inode(struct super_block *sb)
230 {
231 	BUG();
232 }
233 
234 static struct bch_inode_info *__bch2_new_inode(struct bch_fs *c)
235 {
236 	struct bch_inode_info *inode = kmem_cache_alloc(bch2_inode_cache, GFP_NOFS);
237 	if (!inode)
238 		return NULL;
239 
240 	inode_init_once(&inode->v);
241 	mutex_init(&inode->ei_update_lock);
242 	two_state_lock_init(&inode->ei_pagecache_lock);
243 	INIT_LIST_HEAD(&inode->ei_vfs_inode_list);
244 	inode->ei_flags = 0;
245 	mutex_init(&inode->ei_quota_lock);
246 	memset(&inode->ei_devs_need_flush, 0, sizeof(inode->ei_devs_need_flush));
247 
248 	if (unlikely(inode_init_always(c->vfs_sb, &inode->v))) {
249 		kmem_cache_free(bch2_inode_cache, inode);
250 		return NULL;
251 	}
252 
253 	return inode;
254 }
255 
256 /*
257  * Allocate a new inode, dropping/retaking btree locks if necessary:
258  */
259 static struct bch_inode_info *bch2_new_inode(struct btree_trans *trans)
260 {
261 	struct bch_inode_info *inode =
262 		memalloc_flags_do(PF_MEMALLOC_NORECLAIM|PF_MEMALLOC_NOWARN,
263 				  __bch2_new_inode(trans->c));
264 
265 	if (unlikely(!inode)) {
266 		int ret = drop_locks_do(trans, (inode = __bch2_new_inode(trans->c)) ? 0 : -ENOMEM);
267 		if (ret && inode) {
268 			__destroy_inode(&inode->v);
269 			kmem_cache_free(bch2_inode_cache, inode);
270 		}
271 		if (ret)
272 			return ERR_PTR(ret);
273 	}
274 
275 	return inode;
276 }
277 
278 struct inode *bch2_vfs_inode_get(struct bch_fs *c, subvol_inum inum)
279 {
280 	struct bch_inode_info *inode =
281 		to_bch_ei(ilookup5_nowait(c->vfs_sb,
282 					  bch2_inode_hash(inum),
283 					  bch2_iget5_test,
284 					  &inum));
285 	if (inode)
286 		return &inode->v;
287 
288 	struct btree_trans *trans = bch2_trans_get(c);
289 
290 	struct bch_inode_unpacked inode_u;
291 	struct bch_subvolume subvol;
292 	int ret = lockrestart_do(trans,
293 		bch2_subvolume_get(trans, inum.subvol, true, 0, &subvol) ?:
294 		bch2_inode_find_by_inum_trans(trans, inum, &inode_u)) ?:
295 		PTR_ERR_OR_ZERO(inode = bch2_new_inode(trans));
296 	if (!ret) {
297 		bch2_vfs_inode_init(trans, inum, inode, &inode_u, &subvol);
298 		inode = bch2_inode_insert(c, inode);
299 	}
300 	bch2_trans_put(trans);
301 
302 	return ret ? ERR_PTR(ret) : &inode->v;
303 }
304 
305 struct bch_inode_info *
306 __bch2_create(struct mnt_idmap *idmap,
307 	      struct bch_inode_info *dir, struct dentry *dentry,
308 	      umode_t mode, dev_t rdev, subvol_inum snapshot_src,
309 	      unsigned flags)
310 {
311 	struct bch_fs *c = dir->v.i_sb->s_fs_info;
312 	struct btree_trans *trans;
313 	struct bch_inode_unpacked dir_u;
314 	struct bch_inode_info *inode;
315 	struct bch_inode_unpacked inode_u;
316 	struct posix_acl *default_acl = NULL, *acl = NULL;
317 	subvol_inum inum;
318 	struct bch_subvolume subvol;
319 	u64 journal_seq = 0;
320 	int ret;
321 
322 	/*
323 	 * preallocate acls + vfs inode before btree transaction, so that
324 	 * nothing can fail after the transaction succeeds:
325 	 */
326 #ifdef CONFIG_BCACHEFS_POSIX_ACL
327 	ret = posix_acl_create(&dir->v, &mode, &default_acl, &acl);
328 	if (ret)
329 		return ERR_PTR(ret);
330 #endif
331 	inode = __bch2_new_inode(c);
332 	if (unlikely(!inode)) {
333 		inode = ERR_PTR(-ENOMEM);
334 		goto err;
335 	}
336 
337 	bch2_inode_init_early(c, &inode_u);
338 
339 	if (!(flags & BCH_CREATE_TMPFILE))
340 		mutex_lock(&dir->ei_update_lock);
341 
342 	trans = bch2_trans_get(c);
343 retry:
344 	bch2_trans_begin(trans);
345 
346 	ret   = bch2_subvol_is_ro_trans(trans, dir->ei_subvol) ?:
347 		bch2_create_trans(trans,
348 				  inode_inum(dir), &dir_u, &inode_u,
349 				  !(flags & BCH_CREATE_TMPFILE)
350 				  ? &dentry->d_name : NULL,
351 				  from_kuid(i_user_ns(&dir->v), current_fsuid()),
352 				  from_kgid(i_user_ns(&dir->v), current_fsgid()),
353 				  mode, rdev,
354 				  default_acl, acl, snapshot_src, flags) ?:
355 		bch2_quota_acct(c, bch_qid(&inode_u), Q_INO, 1,
356 				KEY_TYPE_QUOTA_PREALLOC);
357 	if (unlikely(ret))
358 		goto err_before_quota;
359 
360 	inum.subvol = inode_u.bi_subvol ?: dir->ei_subvol;
361 	inum.inum = inode_u.bi_inum;
362 
363 	ret   = bch2_subvolume_get(trans, inum.subvol, true,
364 				   BTREE_ITER_with_updates, &subvol) ?:
365 		bch2_trans_commit(trans, NULL, &journal_seq, 0);
366 	if (unlikely(ret)) {
367 		bch2_quota_acct(c, bch_qid(&inode_u), Q_INO, -1,
368 				KEY_TYPE_QUOTA_WARN);
369 err_before_quota:
370 		if (bch2_err_matches(ret, BCH_ERR_transaction_restart))
371 			goto retry;
372 		goto err_trans;
373 	}
374 
375 	if (!(flags & BCH_CREATE_TMPFILE)) {
376 		bch2_inode_update_after_write(trans, dir, &dir_u,
377 					      ATTR_MTIME|ATTR_CTIME);
378 		mutex_unlock(&dir->ei_update_lock);
379 	}
380 
381 	bch2_vfs_inode_init(trans, inum, inode, &inode_u, &subvol);
382 
383 	set_cached_acl(&inode->v, ACL_TYPE_ACCESS, acl);
384 	set_cached_acl(&inode->v, ACL_TYPE_DEFAULT, default_acl);
385 
386 	/*
387 	 * we must insert the new inode into the inode cache before calling
388 	 * bch2_trans_exit() and dropping locks, else we could race with another
389 	 * thread pulling the inode in and modifying it:
390 	 */
391 	inode = bch2_inode_insert(c, inode);
392 	bch2_trans_put(trans);
393 err:
394 	posix_acl_release(default_acl);
395 	posix_acl_release(acl);
396 	return inode;
397 err_trans:
398 	if (!(flags & BCH_CREATE_TMPFILE))
399 		mutex_unlock(&dir->ei_update_lock);
400 
401 	bch2_trans_put(trans);
402 	make_bad_inode(&inode->v);
403 	iput(&inode->v);
404 	inode = ERR_PTR(ret);
405 	goto err;
406 }
407 
408 /* methods */
409 
410 static struct bch_inode_info *bch2_lookup_trans(struct btree_trans *trans,
411 			subvol_inum dir, struct bch_hash_info *dir_hash_info,
412 			const struct qstr *name)
413 {
414 	struct bch_fs *c = trans->c;
415 	struct btree_iter dirent_iter = {};
416 	subvol_inum inum = {};
417 	struct printbuf buf = PRINTBUF;
418 
419 	struct bkey_s_c k = bch2_hash_lookup(trans, &dirent_iter, bch2_dirent_hash_desc,
420 					     dir_hash_info, dir, name, 0);
421 	int ret = bkey_err(k);
422 	if (ret)
423 		return ERR_PTR(ret);
424 
425 	ret = bch2_dirent_read_target(trans, dir, bkey_s_c_to_dirent(k), &inum);
426 	if (ret > 0)
427 		ret = -ENOENT;
428 	if (ret)
429 		goto err;
430 
431 	struct bch_inode_info *inode =
432 		to_bch_ei(ilookup5_nowait(c->vfs_sb,
433 					  bch2_inode_hash(inum),
434 					  bch2_iget5_test,
435 					  &inum));
436 	if (inode)
437 		goto out;
438 
439 	struct bch_subvolume subvol;
440 	struct bch_inode_unpacked inode_u;
441 	ret =   bch2_subvolume_get(trans, inum.subvol, true, 0, &subvol) ?:
442 		bch2_inode_find_by_inum_nowarn_trans(trans, inum, &inode_u) ?:
443 		PTR_ERR_OR_ZERO(inode = bch2_new_inode(trans));
444 
445 	bch2_fs_inconsistent_on(bch2_err_matches(ret, ENOENT),
446 				c, "dirent to missing inode:\n  %s",
447 				(bch2_bkey_val_to_text(&buf, c, k), buf.buf));
448 	if (ret)
449 		goto err;
450 
451 	/* regular files may have hardlinks: */
452 	if (bch2_fs_inconsistent_on(bch2_inode_should_have_bp(&inode_u) &&
453 				    !bkey_eq(k.k->p, POS(inode_u.bi_dir, inode_u.bi_dir_offset)),
454 				    c,
455 				    "dirent points to inode that does not point back:\n  %s",
456 				    (bch2_bkey_val_to_text(&buf, c, k),
457 				     prt_printf(&buf, "\n  "),
458 				     bch2_inode_unpacked_to_text(&buf, &inode_u),
459 				     buf.buf))) {
460 		ret = -ENOENT;
461 		goto err;
462 	}
463 
464 	bch2_vfs_inode_init(trans, inum, inode, &inode_u, &subvol);
465 	inode = bch2_inode_insert(c, inode);
466 out:
467 	bch2_trans_iter_exit(trans, &dirent_iter);
468 	printbuf_exit(&buf);
469 	return inode;
470 err:
471 	inode = ERR_PTR(ret);
472 	goto out;
473 }
474 
475 static struct dentry *bch2_lookup(struct inode *vdir, struct dentry *dentry,
476 				  unsigned int flags)
477 {
478 	struct bch_fs *c = vdir->i_sb->s_fs_info;
479 	struct bch_inode_info *dir = to_bch_ei(vdir);
480 	struct bch_hash_info hash = bch2_hash_info_init(c, &dir->ei_inode);
481 
482 	struct bch_inode_info *inode;
483 	bch2_trans_do(c, NULL, NULL, 0,
484 		PTR_ERR_OR_ZERO(inode = bch2_lookup_trans(trans, inode_inum(dir),
485 							  &hash, &dentry->d_name)));
486 	if (IS_ERR(inode))
487 		inode = NULL;
488 
489 	return d_splice_alias(&inode->v, dentry);
490 }
491 
492 static int bch2_mknod(struct mnt_idmap *idmap,
493 		      struct inode *vdir, struct dentry *dentry,
494 		      umode_t mode, dev_t rdev)
495 {
496 	struct bch_inode_info *inode =
497 		__bch2_create(idmap, to_bch_ei(vdir), dentry, mode, rdev,
498 			      (subvol_inum) { 0 }, 0);
499 
500 	if (IS_ERR(inode))
501 		return bch2_err_class(PTR_ERR(inode));
502 
503 	d_instantiate(dentry, &inode->v);
504 	return 0;
505 }
506 
507 static int bch2_create(struct mnt_idmap *idmap,
508 		       struct inode *vdir, struct dentry *dentry,
509 		       umode_t mode, bool excl)
510 {
511 	return bch2_mknod(idmap, vdir, dentry, mode|S_IFREG, 0);
512 }
513 
514 static int __bch2_link(struct bch_fs *c,
515 		       struct bch_inode_info *inode,
516 		       struct bch_inode_info *dir,
517 		       struct dentry *dentry)
518 {
519 	struct bch_inode_unpacked dir_u, inode_u;
520 	int ret;
521 
522 	mutex_lock(&inode->ei_update_lock);
523 	struct btree_trans *trans = bch2_trans_get(c);
524 
525 	ret = commit_do(trans, NULL, NULL, 0,
526 			bch2_link_trans(trans,
527 					inode_inum(dir),   &dir_u,
528 					inode_inum(inode), &inode_u,
529 					&dentry->d_name));
530 
531 	if (likely(!ret)) {
532 		bch2_inode_update_after_write(trans, dir, &dir_u,
533 					      ATTR_MTIME|ATTR_CTIME);
534 		bch2_inode_update_after_write(trans, inode, &inode_u, ATTR_CTIME);
535 	}
536 
537 	bch2_trans_put(trans);
538 	mutex_unlock(&inode->ei_update_lock);
539 	return ret;
540 }
541 
542 static int bch2_link(struct dentry *old_dentry, struct inode *vdir,
543 		     struct dentry *dentry)
544 {
545 	struct bch_fs *c = vdir->i_sb->s_fs_info;
546 	struct bch_inode_info *dir = to_bch_ei(vdir);
547 	struct bch_inode_info *inode = to_bch_ei(old_dentry->d_inode);
548 	int ret;
549 
550 	lockdep_assert_held(&inode->v.i_rwsem);
551 
552 	ret   = bch2_subvol_is_ro(c, dir->ei_subvol) ?:
553 		bch2_subvol_is_ro(c, inode->ei_subvol) ?:
554 		__bch2_link(c, inode, dir, dentry);
555 	if (unlikely(ret))
556 		return bch2_err_class(ret);
557 
558 	ihold(&inode->v);
559 	d_instantiate(dentry, &inode->v);
560 	return 0;
561 }
562 
563 int __bch2_unlink(struct inode *vdir, struct dentry *dentry,
564 		  bool deleting_snapshot)
565 {
566 	struct bch_fs *c = vdir->i_sb->s_fs_info;
567 	struct bch_inode_info *dir = to_bch_ei(vdir);
568 	struct bch_inode_info *inode = to_bch_ei(dentry->d_inode);
569 	struct bch_inode_unpacked dir_u, inode_u;
570 	int ret;
571 
572 	bch2_lock_inodes(INODE_UPDATE_LOCK, dir, inode);
573 
574 	struct btree_trans *trans = bch2_trans_get(c);
575 
576 	ret = commit_do(trans, NULL, NULL,
577 			BCH_TRANS_COMMIT_no_enospc,
578 		bch2_unlink_trans(trans,
579 				  inode_inum(dir), &dir_u,
580 				  &inode_u, &dentry->d_name,
581 				  deleting_snapshot));
582 	if (unlikely(ret))
583 		goto err;
584 
585 	bch2_inode_update_after_write(trans, dir, &dir_u,
586 				      ATTR_MTIME|ATTR_CTIME);
587 	bch2_inode_update_after_write(trans, inode, &inode_u,
588 				      ATTR_MTIME);
589 
590 	if (inode_u.bi_subvol) {
591 		/*
592 		 * Subvolume deletion is asynchronous, but we still want to tell
593 		 * the VFS that it's been deleted here:
594 		 */
595 		set_nlink(&inode->v, 0);
596 	}
597 err:
598 	bch2_trans_put(trans);
599 	bch2_unlock_inodes(INODE_UPDATE_LOCK, dir, inode);
600 
601 	return ret;
602 }
603 
604 static int bch2_unlink(struct inode *vdir, struct dentry *dentry)
605 {
606 	struct bch_inode_info *dir= to_bch_ei(vdir);
607 	struct bch_fs *c = dir->v.i_sb->s_fs_info;
608 
609 	int ret = bch2_subvol_is_ro(c, dir->ei_subvol) ?:
610 		__bch2_unlink(vdir, dentry, false);
611 	return bch2_err_class(ret);
612 }
613 
614 static int bch2_symlink(struct mnt_idmap *idmap,
615 			struct inode *vdir, struct dentry *dentry,
616 			const char *symname)
617 {
618 	struct bch_fs *c = vdir->i_sb->s_fs_info;
619 	struct bch_inode_info *dir = to_bch_ei(vdir), *inode;
620 	int ret;
621 
622 	inode = __bch2_create(idmap, dir, dentry, S_IFLNK|S_IRWXUGO, 0,
623 			      (subvol_inum) { 0 }, BCH_CREATE_TMPFILE);
624 	if (IS_ERR(inode))
625 		return bch2_err_class(PTR_ERR(inode));
626 
627 	inode_lock(&inode->v);
628 	ret = page_symlink(&inode->v, symname, strlen(symname) + 1);
629 	inode_unlock(&inode->v);
630 
631 	if (unlikely(ret))
632 		goto err;
633 
634 	ret = filemap_write_and_wait_range(inode->v.i_mapping, 0, LLONG_MAX);
635 	if (unlikely(ret))
636 		goto err;
637 
638 	ret = __bch2_link(c, inode, dir, dentry);
639 	if (unlikely(ret))
640 		goto err;
641 
642 	d_instantiate(dentry, &inode->v);
643 	return 0;
644 err:
645 	iput(&inode->v);
646 	return bch2_err_class(ret);
647 }
648 
649 static int bch2_mkdir(struct mnt_idmap *idmap,
650 		      struct inode *vdir, struct dentry *dentry, umode_t mode)
651 {
652 	return bch2_mknod(idmap, vdir, dentry, mode|S_IFDIR, 0);
653 }
654 
655 static int bch2_rename2(struct mnt_idmap *idmap,
656 			struct inode *src_vdir, struct dentry *src_dentry,
657 			struct inode *dst_vdir, struct dentry *dst_dentry,
658 			unsigned flags)
659 {
660 	struct bch_fs *c = src_vdir->i_sb->s_fs_info;
661 	struct bch_inode_info *src_dir = to_bch_ei(src_vdir);
662 	struct bch_inode_info *dst_dir = to_bch_ei(dst_vdir);
663 	struct bch_inode_info *src_inode = to_bch_ei(src_dentry->d_inode);
664 	struct bch_inode_info *dst_inode = to_bch_ei(dst_dentry->d_inode);
665 	struct bch_inode_unpacked dst_dir_u, src_dir_u;
666 	struct bch_inode_unpacked src_inode_u, dst_inode_u;
667 	struct btree_trans *trans;
668 	enum bch_rename_mode mode = flags & RENAME_EXCHANGE
669 		? BCH_RENAME_EXCHANGE
670 		: dst_dentry->d_inode
671 		? BCH_RENAME_OVERWRITE : BCH_RENAME;
672 	int ret;
673 
674 	if (flags & ~(RENAME_NOREPLACE|RENAME_EXCHANGE))
675 		return -EINVAL;
676 
677 	if (mode == BCH_RENAME_OVERWRITE) {
678 		ret = filemap_write_and_wait_range(src_inode->v.i_mapping,
679 						   0, LLONG_MAX);
680 		if (ret)
681 			return ret;
682 	}
683 
684 	bch2_lock_inodes(INODE_UPDATE_LOCK,
685 			 src_dir,
686 			 dst_dir,
687 			 src_inode,
688 			 dst_inode);
689 
690 	trans = bch2_trans_get(c);
691 
692 	ret   = bch2_subvol_is_ro_trans(trans, src_dir->ei_subvol) ?:
693 		bch2_subvol_is_ro_trans(trans, dst_dir->ei_subvol);
694 	if (ret)
695 		goto err;
696 
697 	if (inode_attr_changing(dst_dir, src_inode, Inode_opt_project)) {
698 		ret = bch2_fs_quota_transfer(c, src_inode,
699 					     dst_dir->ei_qid,
700 					     1 << QTYP_PRJ,
701 					     KEY_TYPE_QUOTA_PREALLOC);
702 		if (ret)
703 			goto err;
704 	}
705 
706 	if (mode == BCH_RENAME_EXCHANGE &&
707 	    inode_attr_changing(src_dir, dst_inode, Inode_opt_project)) {
708 		ret = bch2_fs_quota_transfer(c, dst_inode,
709 					     src_dir->ei_qid,
710 					     1 << QTYP_PRJ,
711 					     KEY_TYPE_QUOTA_PREALLOC);
712 		if (ret)
713 			goto err;
714 	}
715 
716 	ret = commit_do(trans, NULL, NULL, 0,
717 			bch2_rename_trans(trans,
718 					  inode_inum(src_dir), &src_dir_u,
719 					  inode_inum(dst_dir), &dst_dir_u,
720 					  &src_inode_u,
721 					  &dst_inode_u,
722 					  &src_dentry->d_name,
723 					  &dst_dentry->d_name,
724 					  mode));
725 	if (unlikely(ret))
726 		goto err;
727 
728 	BUG_ON(src_inode->v.i_ino != src_inode_u.bi_inum);
729 	BUG_ON(dst_inode &&
730 	       dst_inode->v.i_ino != dst_inode_u.bi_inum);
731 
732 	bch2_inode_update_after_write(trans, src_dir, &src_dir_u,
733 				      ATTR_MTIME|ATTR_CTIME);
734 
735 	if (src_dir != dst_dir)
736 		bch2_inode_update_after_write(trans, dst_dir, &dst_dir_u,
737 					      ATTR_MTIME|ATTR_CTIME);
738 
739 	bch2_inode_update_after_write(trans, src_inode, &src_inode_u,
740 				      ATTR_CTIME);
741 
742 	if (dst_inode)
743 		bch2_inode_update_after_write(trans, dst_inode, &dst_inode_u,
744 					      ATTR_CTIME);
745 err:
746 	bch2_trans_put(trans);
747 
748 	bch2_fs_quota_transfer(c, src_inode,
749 			       bch_qid(&src_inode->ei_inode),
750 			       1 << QTYP_PRJ,
751 			       KEY_TYPE_QUOTA_NOCHECK);
752 	if (dst_inode)
753 		bch2_fs_quota_transfer(c, dst_inode,
754 				       bch_qid(&dst_inode->ei_inode),
755 				       1 << QTYP_PRJ,
756 				       KEY_TYPE_QUOTA_NOCHECK);
757 
758 	bch2_unlock_inodes(INODE_UPDATE_LOCK,
759 			   src_dir,
760 			   dst_dir,
761 			   src_inode,
762 			   dst_inode);
763 
764 	return bch2_err_class(ret);
765 }
766 
767 static void bch2_setattr_copy(struct mnt_idmap *idmap,
768 			      struct bch_inode_info *inode,
769 			      struct bch_inode_unpacked *bi,
770 			      struct iattr *attr)
771 {
772 	struct bch_fs *c = inode->v.i_sb->s_fs_info;
773 	unsigned int ia_valid = attr->ia_valid;
774 
775 	if (ia_valid & ATTR_UID)
776 		bi->bi_uid = from_kuid(i_user_ns(&inode->v), attr->ia_uid);
777 	if (ia_valid & ATTR_GID)
778 		bi->bi_gid = from_kgid(i_user_ns(&inode->v), attr->ia_gid);
779 
780 	if (ia_valid & ATTR_SIZE)
781 		bi->bi_size = attr->ia_size;
782 
783 	if (ia_valid & ATTR_ATIME)
784 		bi->bi_atime = timespec_to_bch2_time(c, attr->ia_atime);
785 	if (ia_valid & ATTR_MTIME)
786 		bi->bi_mtime = timespec_to_bch2_time(c, attr->ia_mtime);
787 	if (ia_valid & ATTR_CTIME)
788 		bi->bi_ctime = timespec_to_bch2_time(c, attr->ia_ctime);
789 
790 	if (ia_valid & ATTR_MODE) {
791 		umode_t mode = attr->ia_mode;
792 		kgid_t gid = ia_valid & ATTR_GID
793 			? attr->ia_gid
794 			: inode->v.i_gid;
795 
796 		if (!in_group_p(gid) &&
797 		    !capable_wrt_inode_uidgid(idmap, &inode->v, CAP_FSETID))
798 			mode &= ~S_ISGID;
799 		bi->bi_mode = mode;
800 	}
801 }
802 
803 int bch2_setattr_nonsize(struct mnt_idmap *idmap,
804 			 struct bch_inode_info *inode,
805 			 struct iattr *attr)
806 {
807 	struct bch_fs *c = inode->v.i_sb->s_fs_info;
808 	struct bch_qid qid;
809 	struct btree_trans *trans;
810 	struct btree_iter inode_iter = { NULL };
811 	struct bch_inode_unpacked inode_u;
812 	struct posix_acl *acl = NULL;
813 	int ret;
814 
815 	mutex_lock(&inode->ei_update_lock);
816 
817 	qid = inode->ei_qid;
818 
819 	if (attr->ia_valid & ATTR_UID)
820 		qid.q[QTYP_USR] = from_kuid(i_user_ns(&inode->v), attr->ia_uid);
821 
822 	if (attr->ia_valid & ATTR_GID)
823 		qid.q[QTYP_GRP] = from_kgid(i_user_ns(&inode->v), attr->ia_gid);
824 
825 	ret = bch2_fs_quota_transfer(c, inode, qid, ~0,
826 				     KEY_TYPE_QUOTA_PREALLOC);
827 	if (ret)
828 		goto err;
829 
830 	trans = bch2_trans_get(c);
831 retry:
832 	bch2_trans_begin(trans);
833 	kfree(acl);
834 	acl = NULL;
835 
836 	ret = bch2_inode_peek(trans, &inode_iter, &inode_u, inode_inum(inode),
837 			      BTREE_ITER_intent);
838 	if (ret)
839 		goto btree_err;
840 
841 	bch2_setattr_copy(idmap, inode, &inode_u, attr);
842 
843 	if (attr->ia_valid & ATTR_MODE) {
844 		ret = bch2_acl_chmod(trans, inode_inum(inode), &inode_u,
845 				     inode_u.bi_mode, &acl);
846 		if (ret)
847 			goto btree_err;
848 	}
849 
850 	ret =   bch2_inode_write(trans, &inode_iter, &inode_u) ?:
851 		bch2_trans_commit(trans, NULL, NULL,
852 				  BCH_TRANS_COMMIT_no_enospc);
853 btree_err:
854 	bch2_trans_iter_exit(trans, &inode_iter);
855 
856 	if (bch2_err_matches(ret, BCH_ERR_transaction_restart))
857 		goto retry;
858 	if (unlikely(ret))
859 		goto err_trans;
860 
861 	bch2_inode_update_after_write(trans, inode, &inode_u, attr->ia_valid);
862 
863 	if (acl)
864 		set_cached_acl(&inode->v, ACL_TYPE_ACCESS, acl);
865 err_trans:
866 	bch2_trans_put(trans);
867 err:
868 	mutex_unlock(&inode->ei_update_lock);
869 
870 	return bch2_err_class(ret);
871 }
872 
873 static int bch2_getattr(struct mnt_idmap *idmap,
874 			const struct path *path, struct kstat *stat,
875 			u32 request_mask, unsigned query_flags)
876 {
877 	struct bch_inode_info *inode = to_bch_ei(d_inode(path->dentry));
878 	struct bch_fs *c = inode->v.i_sb->s_fs_info;
879 
880 	stat->dev	= inode->v.i_sb->s_dev;
881 	stat->ino	= inode->v.i_ino;
882 	stat->mode	= inode->v.i_mode;
883 	stat->nlink	= inode->v.i_nlink;
884 	stat->uid	= inode->v.i_uid;
885 	stat->gid	= inode->v.i_gid;
886 	stat->rdev	= inode->v.i_rdev;
887 	stat->size	= i_size_read(&inode->v);
888 	stat->atime	= inode_get_atime(&inode->v);
889 	stat->mtime	= inode_get_mtime(&inode->v);
890 	stat->ctime	= inode_get_ctime(&inode->v);
891 	stat->blksize	= block_bytes(c);
892 	stat->blocks	= inode->v.i_blocks;
893 
894 	stat->subvol	= inode->ei_subvol;
895 	stat->result_mask |= STATX_SUBVOL;
896 
897 	if ((request_mask & STATX_DIOALIGN) && S_ISREG(inode->v.i_mode)) {
898 		stat->result_mask |= STATX_DIOALIGN;
899 		/*
900 		 * this is incorrect; we should be tracking this in superblock,
901 		 * and checking the alignment of open devices
902 		 */
903 		stat->dio_mem_align = SECTOR_SIZE;
904 		stat->dio_offset_align = block_bytes(c);
905 	}
906 
907 	if (request_mask & STATX_BTIME) {
908 		stat->result_mask |= STATX_BTIME;
909 		stat->btime = bch2_time_to_timespec(c, inode->ei_inode.bi_otime);
910 	}
911 
912 	if (inode->ei_inode.bi_flags & BCH_INODE_immutable)
913 		stat->attributes |= STATX_ATTR_IMMUTABLE;
914 	stat->attributes_mask	 |= STATX_ATTR_IMMUTABLE;
915 
916 	if (inode->ei_inode.bi_flags & BCH_INODE_append)
917 		stat->attributes |= STATX_ATTR_APPEND;
918 	stat->attributes_mask	 |= STATX_ATTR_APPEND;
919 
920 	if (inode->ei_inode.bi_flags & BCH_INODE_nodump)
921 		stat->attributes |= STATX_ATTR_NODUMP;
922 	stat->attributes_mask	 |= STATX_ATTR_NODUMP;
923 
924 	return 0;
925 }
926 
927 static int bch2_setattr(struct mnt_idmap *idmap,
928 			struct dentry *dentry, struct iattr *iattr)
929 {
930 	struct bch_inode_info *inode = to_bch_ei(dentry->d_inode);
931 	struct bch_fs *c = inode->v.i_sb->s_fs_info;
932 	int ret;
933 
934 	lockdep_assert_held(&inode->v.i_rwsem);
935 
936 	ret   = bch2_subvol_is_ro(c, inode->ei_subvol) ?:
937 		setattr_prepare(idmap, dentry, iattr);
938 	if (ret)
939 		return ret;
940 
941 	return iattr->ia_valid & ATTR_SIZE
942 		? bchfs_truncate(idmap, inode, iattr)
943 		: bch2_setattr_nonsize(idmap, inode, iattr);
944 }
945 
946 static int bch2_tmpfile(struct mnt_idmap *idmap,
947 			struct inode *vdir, struct file *file, umode_t mode)
948 {
949 	struct bch_inode_info *inode =
950 		__bch2_create(idmap, to_bch_ei(vdir),
951 			      file->f_path.dentry, mode, 0,
952 			      (subvol_inum) { 0 }, BCH_CREATE_TMPFILE);
953 
954 	if (IS_ERR(inode))
955 		return bch2_err_class(PTR_ERR(inode));
956 
957 	d_mark_tmpfile(file, &inode->v);
958 	d_instantiate(file->f_path.dentry, &inode->v);
959 	return finish_open_simple(file, 0);
960 }
961 
962 static int bch2_fill_extent(struct bch_fs *c,
963 			    struct fiemap_extent_info *info,
964 			    struct bkey_s_c k, unsigned flags)
965 {
966 	if (bkey_extent_is_direct_data(k.k)) {
967 		struct bkey_ptrs_c ptrs = bch2_bkey_ptrs_c(k);
968 		const union bch_extent_entry *entry;
969 		struct extent_ptr_decoded p;
970 		int ret;
971 
972 		if (k.k->type == KEY_TYPE_reflink_v)
973 			flags |= FIEMAP_EXTENT_SHARED;
974 
975 		bkey_for_each_ptr_decode(k.k, ptrs, p, entry) {
976 			int flags2 = 0;
977 			u64 offset = p.ptr.offset;
978 
979 			if (p.ptr.unwritten)
980 				flags2 |= FIEMAP_EXTENT_UNWRITTEN;
981 
982 			if (p.crc.compression_type)
983 				flags2 |= FIEMAP_EXTENT_ENCODED;
984 			else
985 				offset += p.crc.offset;
986 
987 			if ((offset & (block_sectors(c) - 1)) ||
988 			    (k.k->size & (block_sectors(c) - 1)))
989 				flags2 |= FIEMAP_EXTENT_NOT_ALIGNED;
990 
991 			ret = fiemap_fill_next_extent(info,
992 						bkey_start_offset(k.k) << 9,
993 						offset << 9,
994 						k.k->size << 9, flags|flags2);
995 			if (ret)
996 				return ret;
997 		}
998 
999 		return 0;
1000 	} else if (bkey_extent_is_inline_data(k.k)) {
1001 		return fiemap_fill_next_extent(info,
1002 					       bkey_start_offset(k.k) << 9,
1003 					       0, k.k->size << 9,
1004 					       flags|
1005 					       FIEMAP_EXTENT_DATA_INLINE);
1006 	} else if (k.k->type == KEY_TYPE_reservation) {
1007 		return fiemap_fill_next_extent(info,
1008 					       bkey_start_offset(k.k) << 9,
1009 					       0, k.k->size << 9,
1010 					       flags|
1011 					       FIEMAP_EXTENT_DELALLOC|
1012 					       FIEMAP_EXTENT_UNWRITTEN);
1013 	} else {
1014 		BUG();
1015 	}
1016 }
1017 
1018 static int bch2_fiemap(struct inode *vinode, struct fiemap_extent_info *info,
1019 		       u64 start, u64 len)
1020 {
1021 	struct bch_fs *c = vinode->i_sb->s_fs_info;
1022 	struct bch_inode_info *ei = to_bch_ei(vinode);
1023 	struct btree_trans *trans;
1024 	struct btree_iter iter;
1025 	struct bkey_s_c k;
1026 	struct bkey_buf cur, prev;
1027 	unsigned offset_into_extent, sectors;
1028 	bool have_extent = false;
1029 	u32 snapshot;
1030 	int ret = 0;
1031 
1032 	ret = fiemap_prep(&ei->v, info, start, &len, FIEMAP_FLAG_SYNC);
1033 	if (ret)
1034 		return ret;
1035 
1036 	struct bpos end = POS(ei->v.i_ino, (start + len) >> 9);
1037 	if (start + len < start)
1038 		return -EINVAL;
1039 
1040 	start >>= 9;
1041 
1042 	bch2_bkey_buf_init(&cur);
1043 	bch2_bkey_buf_init(&prev);
1044 	trans = bch2_trans_get(c);
1045 retry:
1046 	bch2_trans_begin(trans);
1047 
1048 	ret = bch2_subvolume_get_snapshot(trans, ei->ei_subvol, &snapshot);
1049 	if (ret)
1050 		goto err;
1051 
1052 	bch2_trans_iter_init(trans, &iter, BTREE_ID_extents,
1053 			     SPOS(ei->v.i_ino, start, snapshot), 0);
1054 
1055 	while (!(ret = btree_trans_too_many_iters(trans)) &&
1056 	       (k = bch2_btree_iter_peek_upto(&iter, end)).k &&
1057 	       !(ret = bkey_err(k))) {
1058 		enum btree_id data_btree = BTREE_ID_extents;
1059 
1060 		if (!bkey_extent_is_data(k.k) &&
1061 		    k.k->type != KEY_TYPE_reservation) {
1062 			bch2_btree_iter_advance(&iter);
1063 			continue;
1064 		}
1065 
1066 		offset_into_extent	= iter.pos.offset -
1067 			bkey_start_offset(k.k);
1068 		sectors			= k.k->size - offset_into_extent;
1069 
1070 		bch2_bkey_buf_reassemble(&cur, c, k);
1071 
1072 		ret = bch2_read_indirect_extent(trans, &data_btree,
1073 					&offset_into_extent, &cur);
1074 		if (ret)
1075 			break;
1076 
1077 		k = bkey_i_to_s_c(cur.k);
1078 		bch2_bkey_buf_realloc(&prev, c, k.k->u64s);
1079 
1080 		sectors = min(sectors, k.k->size - offset_into_extent);
1081 
1082 		bch2_cut_front(POS(k.k->p.inode,
1083 				   bkey_start_offset(k.k) +
1084 				   offset_into_extent),
1085 			       cur.k);
1086 		bch2_key_resize(&cur.k->k, sectors);
1087 		cur.k->k.p = iter.pos;
1088 		cur.k->k.p.offset += cur.k->k.size;
1089 
1090 		if (have_extent) {
1091 			bch2_trans_unlock(trans);
1092 			ret = bch2_fill_extent(c, info,
1093 					bkey_i_to_s_c(prev.k), 0);
1094 			if (ret)
1095 				break;
1096 		}
1097 
1098 		bkey_copy(prev.k, cur.k);
1099 		have_extent = true;
1100 
1101 		bch2_btree_iter_set_pos(&iter,
1102 			POS(iter.pos.inode, iter.pos.offset + sectors));
1103 
1104 		ret = bch2_trans_relock(trans);
1105 		if (ret)
1106 			break;
1107 	}
1108 	start = iter.pos.offset;
1109 	bch2_trans_iter_exit(trans, &iter);
1110 err:
1111 	if (bch2_err_matches(ret, BCH_ERR_transaction_restart))
1112 		goto retry;
1113 
1114 	if (!ret && have_extent) {
1115 		bch2_trans_unlock(trans);
1116 		ret = bch2_fill_extent(c, info, bkey_i_to_s_c(prev.k),
1117 				       FIEMAP_EXTENT_LAST);
1118 	}
1119 
1120 	bch2_trans_put(trans);
1121 	bch2_bkey_buf_exit(&cur, c);
1122 	bch2_bkey_buf_exit(&prev, c);
1123 	return ret < 0 ? ret : 0;
1124 }
1125 
1126 static const struct vm_operations_struct bch_vm_ops = {
1127 	.fault		= bch2_page_fault,
1128 	.map_pages	= filemap_map_pages,
1129 	.page_mkwrite   = bch2_page_mkwrite,
1130 };
1131 
1132 static int bch2_mmap(struct file *file, struct vm_area_struct *vma)
1133 {
1134 	file_accessed(file);
1135 
1136 	vma->vm_ops = &bch_vm_ops;
1137 	return 0;
1138 }
1139 
1140 /* Directories: */
1141 
1142 static loff_t bch2_dir_llseek(struct file *file, loff_t offset, int whence)
1143 {
1144 	return generic_file_llseek_size(file, offset, whence,
1145 					S64_MAX, S64_MAX);
1146 }
1147 
1148 static int bch2_vfs_readdir(struct file *file, struct dir_context *ctx)
1149 {
1150 	struct bch_inode_info *inode = file_bch_inode(file);
1151 	struct bch_fs *c = inode->v.i_sb->s_fs_info;
1152 
1153 	if (!dir_emit_dots(file, ctx))
1154 		return 0;
1155 
1156 	int ret = bch2_readdir(c, inode_inum(inode), ctx);
1157 
1158 	bch_err_fn(c, ret);
1159 	return bch2_err_class(ret);
1160 }
1161 
1162 static int bch2_open(struct inode *vinode, struct file *file)
1163 {
1164 	if (file->f_flags & (O_WRONLY|O_RDWR)) {
1165 		struct bch_inode_info *inode = to_bch_ei(vinode);
1166 		struct bch_fs *c = inode->v.i_sb->s_fs_info;
1167 
1168 		int ret = bch2_subvol_is_ro(c, inode->ei_subvol);
1169 		if (ret)
1170 			return ret;
1171 	}
1172 
1173 	file->f_mode |= FMODE_CAN_ODIRECT;
1174 
1175 	return generic_file_open(vinode, file);
1176 }
1177 
1178 static const struct file_operations bch_file_operations = {
1179 	.open		= bch2_open,
1180 	.llseek		= bch2_llseek,
1181 	.read_iter	= bch2_read_iter,
1182 	.write_iter	= bch2_write_iter,
1183 	.mmap		= bch2_mmap,
1184 	.get_unmapped_area = thp_get_unmapped_area,
1185 	.fsync		= bch2_fsync,
1186 	.splice_read	= filemap_splice_read,
1187 	.splice_write	= iter_file_splice_write,
1188 	.fallocate	= bch2_fallocate_dispatch,
1189 	.unlocked_ioctl = bch2_fs_file_ioctl,
1190 #ifdef CONFIG_COMPAT
1191 	.compat_ioctl	= bch2_compat_fs_ioctl,
1192 #endif
1193 	.remap_file_range = bch2_remap_file_range,
1194 };
1195 
1196 static const struct inode_operations bch_file_inode_operations = {
1197 	.getattr	= bch2_getattr,
1198 	.setattr	= bch2_setattr,
1199 	.fiemap		= bch2_fiemap,
1200 	.listxattr	= bch2_xattr_list,
1201 #ifdef CONFIG_BCACHEFS_POSIX_ACL
1202 	.get_inode_acl	= bch2_get_acl,
1203 	.set_acl	= bch2_set_acl,
1204 #endif
1205 };
1206 
1207 static const struct inode_operations bch_dir_inode_operations = {
1208 	.lookup		= bch2_lookup,
1209 	.create		= bch2_create,
1210 	.link		= bch2_link,
1211 	.unlink		= bch2_unlink,
1212 	.symlink	= bch2_symlink,
1213 	.mkdir		= bch2_mkdir,
1214 	.rmdir		= bch2_unlink,
1215 	.mknod		= bch2_mknod,
1216 	.rename		= bch2_rename2,
1217 	.getattr	= bch2_getattr,
1218 	.setattr	= bch2_setattr,
1219 	.tmpfile	= bch2_tmpfile,
1220 	.listxattr	= bch2_xattr_list,
1221 #ifdef CONFIG_BCACHEFS_POSIX_ACL
1222 	.get_inode_acl	= bch2_get_acl,
1223 	.set_acl	= bch2_set_acl,
1224 #endif
1225 };
1226 
1227 static const struct file_operations bch_dir_file_operations = {
1228 	.llseek		= bch2_dir_llseek,
1229 	.read		= generic_read_dir,
1230 	.iterate_shared	= bch2_vfs_readdir,
1231 	.fsync		= bch2_fsync,
1232 	.unlocked_ioctl = bch2_fs_file_ioctl,
1233 #ifdef CONFIG_COMPAT
1234 	.compat_ioctl	= bch2_compat_fs_ioctl,
1235 #endif
1236 };
1237 
1238 static const struct inode_operations bch_symlink_inode_operations = {
1239 	.get_link	= page_get_link,
1240 	.getattr	= bch2_getattr,
1241 	.setattr	= bch2_setattr,
1242 	.listxattr	= bch2_xattr_list,
1243 #ifdef CONFIG_BCACHEFS_POSIX_ACL
1244 	.get_inode_acl	= bch2_get_acl,
1245 	.set_acl	= bch2_set_acl,
1246 #endif
1247 };
1248 
1249 static const struct inode_operations bch_special_inode_operations = {
1250 	.getattr	= bch2_getattr,
1251 	.setattr	= bch2_setattr,
1252 	.listxattr	= bch2_xattr_list,
1253 #ifdef CONFIG_BCACHEFS_POSIX_ACL
1254 	.get_inode_acl	= bch2_get_acl,
1255 	.set_acl	= bch2_set_acl,
1256 #endif
1257 };
1258 
1259 static const struct address_space_operations bch_address_space_operations = {
1260 	.read_folio	= bch2_read_folio,
1261 	.writepages	= bch2_writepages,
1262 	.readahead	= bch2_readahead,
1263 	.dirty_folio	= filemap_dirty_folio,
1264 	.write_begin	= bch2_write_begin,
1265 	.write_end	= bch2_write_end,
1266 	.invalidate_folio = bch2_invalidate_folio,
1267 	.release_folio	= bch2_release_folio,
1268 #ifdef CONFIG_MIGRATION
1269 	.migrate_folio	= filemap_migrate_folio,
1270 #endif
1271 	.error_remove_folio = generic_error_remove_folio,
1272 };
1273 
1274 struct bcachefs_fid {
1275 	u64		inum;
1276 	u32		subvol;
1277 	u32		gen;
1278 } __packed;
1279 
1280 struct bcachefs_fid_with_parent {
1281 	struct bcachefs_fid	fid;
1282 	struct bcachefs_fid	dir;
1283 } __packed;
1284 
1285 static int bcachefs_fid_valid(int fh_len, int fh_type)
1286 {
1287 	switch (fh_type) {
1288 	case FILEID_BCACHEFS_WITHOUT_PARENT:
1289 		return fh_len == sizeof(struct bcachefs_fid) / sizeof(u32);
1290 	case FILEID_BCACHEFS_WITH_PARENT:
1291 		return fh_len == sizeof(struct bcachefs_fid_with_parent) / sizeof(u32);
1292 	default:
1293 		return false;
1294 	}
1295 }
1296 
1297 static struct bcachefs_fid bch2_inode_to_fid(struct bch_inode_info *inode)
1298 {
1299 	return (struct bcachefs_fid) {
1300 		.inum	= inode->ei_inode.bi_inum,
1301 		.subvol	= inode->ei_subvol,
1302 		.gen	= inode->ei_inode.bi_generation,
1303 	};
1304 }
1305 
1306 static int bch2_encode_fh(struct inode *vinode, u32 *fh, int *len,
1307 			  struct inode *vdir)
1308 {
1309 	struct bch_inode_info *inode	= to_bch_ei(vinode);
1310 	struct bch_inode_info *dir	= to_bch_ei(vdir);
1311 	int min_len;
1312 
1313 	if (!S_ISDIR(inode->v.i_mode) && dir) {
1314 		struct bcachefs_fid_with_parent *fid = (void *) fh;
1315 
1316 		min_len = sizeof(*fid) / sizeof(u32);
1317 		if (*len < min_len) {
1318 			*len = min_len;
1319 			return FILEID_INVALID;
1320 		}
1321 
1322 		fid->fid = bch2_inode_to_fid(inode);
1323 		fid->dir = bch2_inode_to_fid(dir);
1324 
1325 		*len = min_len;
1326 		return FILEID_BCACHEFS_WITH_PARENT;
1327 	} else {
1328 		struct bcachefs_fid *fid = (void *) fh;
1329 
1330 		min_len = sizeof(*fid) / sizeof(u32);
1331 		if (*len < min_len) {
1332 			*len = min_len;
1333 			return FILEID_INVALID;
1334 		}
1335 		*fid = bch2_inode_to_fid(inode);
1336 
1337 		*len = min_len;
1338 		return FILEID_BCACHEFS_WITHOUT_PARENT;
1339 	}
1340 }
1341 
1342 static struct inode *bch2_nfs_get_inode(struct super_block *sb,
1343 					struct bcachefs_fid fid)
1344 {
1345 	struct bch_fs *c = sb->s_fs_info;
1346 	struct inode *vinode = bch2_vfs_inode_get(c, (subvol_inum) {
1347 				    .subvol = fid.subvol,
1348 				    .inum = fid.inum,
1349 	});
1350 	if (!IS_ERR(vinode) && vinode->i_generation != fid.gen) {
1351 		iput(vinode);
1352 		vinode = ERR_PTR(-ESTALE);
1353 	}
1354 	return vinode;
1355 }
1356 
1357 static struct dentry *bch2_fh_to_dentry(struct super_block *sb, struct fid *_fid,
1358 		int fh_len, int fh_type)
1359 {
1360 	struct bcachefs_fid *fid = (void *) _fid;
1361 
1362 	if (!bcachefs_fid_valid(fh_len, fh_type))
1363 		return NULL;
1364 
1365 	return d_obtain_alias(bch2_nfs_get_inode(sb, *fid));
1366 }
1367 
1368 static struct dentry *bch2_fh_to_parent(struct super_block *sb, struct fid *_fid,
1369 		int fh_len, int fh_type)
1370 {
1371 	struct bcachefs_fid_with_parent *fid = (void *) _fid;
1372 
1373 	if (!bcachefs_fid_valid(fh_len, fh_type) ||
1374 	    fh_type != FILEID_BCACHEFS_WITH_PARENT)
1375 		return NULL;
1376 
1377 	return d_obtain_alias(bch2_nfs_get_inode(sb, fid->dir));
1378 }
1379 
1380 static struct dentry *bch2_get_parent(struct dentry *child)
1381 {
1382 	struct bch_inode_info *inode = to_bch_ei(child->d_inode);
1383 	struct bch_fs *c = inode->v.i_sb->s_fs_info;
1384 	subvol_inum parent_inum = {
1385 		.subvol = inode->ei_inode.bi_parent_subvol ?:
1386 			inode->ei_subvol,
1387 		.inum = inode->ei_inode.bi_dir,
1388 	};
1389 
1390 	return d_obtain_alias(bch2_vfs_inode_get(c, parent_inum));
1391 }
1392 
1393 static int bch2_get_name(struct dentry *parent, char *name, struct dentry *child)
1394 {
1395 	struct bch_inode_info *inode	= to_bch_ei(child->d_inode);
1396 	struct bch_inode_info *dir	= to_bch_ei(parent->d_inode);
1397 	struct bch_fs *c = inode->v.i_sb->s_fs_info;
1398 	struct btree_trans *trans;
1399 	struct btree_iter iter1;
1400 	struct btree_iter iter2;
1401 	struct bkey_s_c k;
1402 	struct bkey_s_c_dirent d;
1403 	struct bch_inode_unpacked inode_u;
1404 	subvol_inum target;
1405 	u32 snapshot;
1406 	struct qstr dirent_name;
1407 	unsigned name_len = 0;
1408 	int ret;
1409 
1410 	if (!S_ISDIR(dir->v.i_mode))
1411 		return -EINVAL;
1412 
1413 	trans = bch2_trans_get(c);
1414 
1415 	bch2_trans_iter_init(trans, &iter1, BTREE_ID_dirents,
1416 			     POS(dir->ei_inode.bi_inum, 0), 0);
1417 	bch2_trans_iter_init(trans, &iter2, BTREE_ID_dirents,
1418 			     POS(dir->ei_inode.bi_inum, 0), 0);
1419 retry:
1420 	bch2_trans_begin(trans);
1421 
1422 	ret = bch2_subvolume_get_snapshot(trans, dir->ei_subvol, &snapshot);
1423 	if (ret)
1424 		goto err;
1425 
1426 	bch2_btree_iter_set_snapshot(&iter1, snapshot);
1427 	bch2_btree_iter_set_snapshot(&iter2, snapshot);
1428 
1429 	ret = bch2_inode_find_by_inum_trans(trans, inode_inum(inode), &inode_u);
1430 	if (ret)
1431 		goto err;
1432 
1433 	if (inode_u.bi_dir == dir->ei_inode.bi_inum) {
1434 		bch2_btree_iter_set_pos(&iter1, POS(inode_u.bi_dir, inode_u.bi_dir_offset));
1435 
1436 		k = bch2_btree_iter_peek_slot(&iter1);
1437 		ret = bkey_err(k);
1438 		if (ret)
1439 			goto err;
1440 
1441 		if (k.k->type != KEY_TYPE_dirent) {
1442 			ret = -BCH_ERR_ENOENT_dirent_doesnt_match_inode;
1443 			goto err;
1444 		}
1445 
1446 		d = bkey_s_c_to_dirent(k);
1447 		ret = bch2_dirent_read_target(trans, inode_inum(dir), d, &target);
1448 		if (ret > 0)
1449 			ret = -BCH_ERR_ENOENT_dirent_doesnt_match_inode;
1450 		if (ret)
1451 			goto err;
1452 
1453 		if (target.subvol	== inode->ei_subvol &&
1454 		    target.inum		== inode->ei_inode.bi_inum)
1455 			goto found;
1456 	} else {
1457 		/*
1458 		 * File with multiple hardlinks and our backref is to the wrong
1459 		 * directory - linear search:
1460 		 */
1461 		for_each_btree_key_continue_norestart(iter2, 0, k, ret) {
1462 			if (k.k->p.inode > dir->ei_inode.bi_inum)
1463 				break;
1464 
1465 			if (k.k->type != KEY_TYPE_dirent)
1466 				continue;
1467 
1468 			d = bkey_s_c_to_dirent(k);
1469 			ret = bch2_dirent_read_target(trans, inode_inum(dir), d, &target);
1470 			if (ret < 0)
1471 				break;
1472 			if (ret)
1473 				continue;
1474 
1475 			if (target.subvol	== inode->ei_subvol &&
1476 			    target.inum		== inode->ei_inode.bi_inum)
1477 				goto found;
1478 		}
1479 	}
1480 
1481 	ret = -ENOENT;
1482 	goto err;
1483 found:
1484 	dirent_name = bch2_dirent_get_name(d);
1485 
1486 	name_len = min_t(unsigned, dirent_name.len, NAME_MAX);
1487 	memcpy(name, dirent_name.name, name_len);
1488 	name[name_len] = '\0';
1489 err:
1490 	if (bch2_err_matches(ret, BCH_ERR_transaction_restart))
1491 		goto retry;
1492 
1493 	bch2_trans_iter_exit(trans, &iter1);
1494 	bch2_trans_iter_exit(trans, &iter2);
1495 	bch2_trans_put(trans);
1496 
1497 	return ret;
1498 }
1499 
1500 static const struct export_operations bch_export_ops = {
1501 	.encode_fh	= bch2_encode_fh,
1502 	.fh_to_dentry	= bch2_fh_to_dentry,
1503 	.fh_to_parent	= bch2_fh_to_parent,
1504 	.get_parent	= bch2_get_parent,
1505 	.get_name	= bch2_get_name,
1506 };
1507 
1508 static void bch2_vfs_inode_init(struct btree_trans *trans, subvol_inum inum,
1509 				struct bch_inode_info *inode,
1510 				struct bch_inode_unpacked *bi,
1511 				struct bch_subvolume *subvol)
1512 {
1513 	bch2_iget5_set(&inode->v, &inum);
1514 	bch2_inode_update_after_write(trans, inode, bi, ~0);
1515 
1516 	inode->v.i_blocks	= bi->bi_sectors;
1517 	inode->v.i_ino		= bi->bi_inum;
1518 	inode->v.i_rdev		= bi->bi_dev;
1519 	inode->v.i_generation	= bi->bi_generation;
1520 	inode->v.i_size		= bi->bi_size;
1521 
1522 	inode->ei_flags		= 0;
1523 	inode->ei_quota_reserved = 0;
1524 	inode->ei_qid		= bch_qid(bi);
1525 	inode->ei_subvol	= inum.subvol;
1526 
1527 	if (BCH_SUBVOLUME_SNAP(subvol))
1528 		set_bit(EI_INODE_SNAPSHOT, &inode->ei_flags);
1529 
1530 	inode->v.i_mapping->a_ops = &bch_address_space_operations;
1531 
1532 	switch (inode->v.i_mode & S_IFMT) {
1533 	case S_IFREG:
1534 		inode->v.i_op	= &bch_file_inode_operations;
1535 		inode->v.i_fop	= &bch_file_operations;
1536 		break;
1537 	case S_IFDIR:
1538 		inode->v.i_op	= &bch_dir_inode_operations;
1539 		inode->v.i_fop	= &bch_dir_file_operations;
1540 		break;
1541 	case S_IFLNK:
1542 		inode_nohighmem(&inode->v);
1543 		inode->v.i_op	= &bch_symlink_inode_operations;
1544 		break;
1545 	default:
1546 		init_special_inode(&inode->v, inode->v.i_mode, inode->v.i_rdev);
1547 		inode->v.i_op	= &bch_special_inode_operations;
1548 		break;
1549 	}
1550 
1551 	mapping_set_large_folios(inode->v.i_mapping);
1552 }
1553 
1554 static void bch2_free_inode(struct inode *vinode)
1555 {
1556 	kmem_cache_free(bch2_inode_cache, to_bch_ei(vinode));
1557 }
1558 
1559 static int inode_update_times_fn(struct btree_trans *trans,
1560 				 struct bch_inode_info *inode,
1561 				 struct bch_inode_unpacked *bi,
1562 				 void *p)
1563 {
1564 	struct bch_fs *c = inode->v.i_sb->s_fs_info;
1565 
1566 	bi->bi_atime	= timespec_to_bch2_time(c, inode_get_atime(&inode->v));
1567 	bi->bi_mtime	= timespec_to_bch2_time(c, inode_get_mtime(&inode->v));
1568 	bi->bi_ctime	= timespec_to_bch2_time(c, inode_get_ctime(&inode->v));
1569 
1570 	return 0;
1571 }
1572 
1573 static int bch2_vfs_write_inode(struct inode *vinode,
1574 				struct writeback_control *wbc)
1575 {
1576 	struct bch_fs *c = vinode->i_sb->s_fs_info;
1577 	struct bch_inode_info *inode = to_bch_ei(vinode);
1578 	int ret;
1579 
1580 	mutex_lock(&inode->ei_update_lock);
1581 	ret = bch2_write_inode(c, inode, inode_update_times_fn, NULL,
1582 			       ATTR_ATIME|ATTR_MTIME|ATTR_CTIME);
1583 	mutex_unlock(&inode->ei_update_lock);
1584 
1585 	return bch2_err_class(ret);
1586 }
1587 
1588 static void bch2_evict_inode(struct inode *vinode)
1589 {
1590 	struct bch_fs *c = vinode->i_sb->s_fs_info;
1591 	struct bch_inode_info *inode = to_bch_ei(vinode);
1592 
1593 	truncate_inode_pages_final(&inode->v.i_data);
1594 
1595 	clear_inode(&inode->v);
1596 
1597 	BUG_ON(!is_bad_inode(&inode->v) && inode->ei_quota_reserved);
1598 
1599 	if (!inode->v.i_nlink && !is_bad_inode(&inode->v)) {
1600 		bch2_quota_acct(c, inode->ei_qid, Q_SPC, -((s64) inode->v.i_blocks),
1601 				KEY_TYPE_QUOTA_WARN);
1602 		bch2_quota_acct(c, inode->ei_qid, Q_INO, -1,
1603 				KEY_TYPE_QUOTA_WARN);
1604 		bch2_inode_rm(c, inode_inum(inode));
1605 	}
1606 
1607 	mutex_lock(&c->vfs_inodes_lock);
1608 	list_del_init(&inode->ei_vfs_inode_list);
1609 	mutex_unlock(&c->vfs_inodes_lock);
1610 }
1611 
1612 void bch2_evict_subvolume_inodes(struct bch_fs *c, snapshot_id_list *s)
1613 {
1614 	struct bch_inode_info *inode;
1615 	DARRAY(struct bch_inode_info *) grabbed;
1616 	bool clean_pass = false, this_pass_clean;
1617 
1618 	/*
1619 	 * Initially, we scan for inodes without I_DONTCACHE, then mark them to
1620 	 * be pruned with d_mark_dontcache().
1621 	 *
1622 	 * Once we've had a clean pass where we didn't find any inodes without
1623 	 * I_DONTCACHE, we wait for them to be freed:
1624 	 */
1625 
1626 	darray_init(&grabbed);
1627 	darray_make_room(&grabbed, 1024);
1628 again:
1629 	cond_resched();
1630 	this_pass_clean = true;
1631 
1632 	mutex_lock(&c->vfs_inodes_lock);
1633 	list_for_each_entry(inode, &c->vfs_inodes_list, ei_vfs_inode_list) {
1634 		if (!snapshot_list_has_id(s, inode->ei_subvol))
1635 			continue;
1636 
1637 		if (!(inode->v.i_state & I_DONTCACHE) &&
1638 		    !(inode->v.i_state & I_FREEING) &&
1639 		    igrab(&inode->v)) {
1640 			this_pass_clean = false;
1641 
1642 			if (darray_push_gfp(&grabbed, inode, GFP_ATOMIC|__GFP_NOWARN)) {
1643 				iput(&inode->v);
1644 				break;
1645 			}
1646 		} else if (clean_pass && this_pass_clean) {
1647 			wait_queue_head_t *wq = bit_waitqueue(&inode->v.i_state, __I_NEW);
1648 			DEFINE_WAIT_BIT(wait, &inode->v.i_state, __I_NEW);
1649 
1650 			prepare_to_wait(wq, &wait.wq_entry, TASK_UNINTERRUPTIBLE);
1651 			mutex_unlock(&c->vfs_inodes_lock);
1652 
1653 			schedule();
1654 			finish_wait(wq, &wait.wq_entry);
1655 			goto again;
1656 		}
1657 	}
1658 	mutex_unlock(&c->vfs_inodes_lock);
1659 
1660 	darray_for_each(grabbed, i) {
1661 		inode = *i;
1662 		d_mark_dontcache(&inode->v);
1663 		d_prune_aliases(&inode->v);
1664 		iput(&inode->v);
1665 	}
1666 	grabbed.nr = 0;
1667 
1668 	if (!clean_pass || !this_pass_clean) {
1669 		clean_pass = this_pass_clean;
1670 		goto again;
1671 	}
1672 
1673 	darray_exit(&grabbed);
1674 }
1675 
1676 static int bch2_statfs(struct dentry *dentry, struct kstatfs *buf)
1677 {
1678 	struct super_block *sb = dentry->d_sb;
1679 	struct bch_fs *c = sb->s_fs_info;
1680 	struct bch_fs_usage_short usage = bch2_fs_usage_read_short(c);
1681 	unsigned shift = sb->s_blocksize_bits - 9;
1682 	/*
1683 	 * this assumes inodes take up 64 bytes, which is a decent average
1684 	 * number:
1685 	 */
1686 	u64 avail_inodes = ((usage.capacity - usage.used) << 3);
1687 
1688 	buf->f_type	= BCACHEFS_STATFS_MAGIC;
1689 	buf->f_bsize	= sb->s_blocksize;
1690 	buf->f_blocks	= usage.capacity >> shift;
1691 	buf->f_bfree	= usage.free >> shift;
1692 	buf->f_bavail	= avail_factor(usage.free) >> shift;
1693 
1694 	buf->f_files	= usage.nr_inodes + avail_inodes;
1695 	buf->f_ffree	= avail_inodes;
1696 
1697 	buf->f_fsid	= uuid_to_fsid(c->sb.user_uuid.b);
1698 	buf->f_namelen	= BCH_NAME_MAX;
1699 
1700 	return 0;
1701 }
1702 
1703 static int bch2_sync_fs(struct super_block *sb, int wait)
1704 {
1705 	struct bch_fs *c = sb->s_fs_info;
1706 	int ret;
1707 
1708 	trace_bch2_sync_fs(sb, wait);
1709 
1710 	if (c->opts.journal_flush_disabled)
1711 		return 0;
1712 
1713 	if (!wait) {
1714 		bch2_journal_flush_async(&c->journal, NULL);
1715 		return 0;
1716 	}
1717 
1718 	ret = bch2_journal_flush(&c->journal);
1719 	return bch2_err_class(ret);
1720 }
1721 
1722 static struct bch_fs *bch2_path_to_fs(const char *path)
1723 {
1724 	struct bch_fs *c;
1725 	dev_t dev;
1726 	int ret;
1727 
1728 	ret = lookup_bdev(path, &dev);
1729 	if (ret)
1730 		return ERR_PTR(ret);
1731 
1732 	c = bch2_dev_to_fs(dev);
1733 	if (c)
1734 		closure_put(&c->cl);
1735 	return c ?: ERR_PTR(-ENOENT);
1736 }
1737 
1738 static int bch2_remount(struct super_block *sb, int *flags,
1739 			struct bch_opts opts)
1740 {
1741 	struct bch_fs *c = sb->s_fs_info;
1742 	int ret = 0;
1743 
1744 	opt_set(opts, read_only, (*flags & SB_RDONLY) != 0);
1745 
1746 	if (opts.read_only != c->opts.read_only) {
1747 		down_write(&c->state_lock);
1748 
1749 		if (opts.read_only) {
1750 			bch2_fs_read_only(c);
1751 
1752 			sb->s_flags |= SB_RDONLY;
1753 		} else {
1754 			ret = bch2_fs_read_write(c);
1755 			if (ret) {
1756 				bch_err(c, "error going rw: %i", ret);
1757 				up_write(&c->state_lock);
1758 				ret = -EINVAL;
1759 				goto err;
1760 			}
1761 
1762 			sb->s_flags &= ~SB_RDONLY;
1763 		}
1764 
1765 		c->opts.read_only = opts.read_only;
1766 
1767 		up_write(&c->state_lock);
1768 	}
1769 
1770 	if (opt_defined(opts, errors))
1771 		c->opts.errors = opts.errors;
1772 err:
1773 	return bch2_err_class(ret);
1774 }
1775 
1776 static int bch2_show_devname(struct seq_file *seq, struct dentry *root)
1777 {
1778 	struct bch_fs *c = root->d_sb->s_fs_info;
1779 	bool first = true;
1780 
1781 	for_each_online_member(c, ca) {
1782 		if (!first)
1783 			seq_putc(seq, ':');
1784 		first = false;
1785 		seq_puts(seq, ca->disk_sb.sb_name);
1786 	}
1787 
1788 	return 0;
1789 }
1790 
1791 static int bch2_show_options(struct seq_file *seq, struct dentry *root)
1792 {
1793 	struct bch_fs *c = root->d_sb->s_fs_info;
1794 	enum bch_opt_id i;
1795 	struct printbuf buf = PRINTBUF;
1796 	int ret = 0;
1797 
1798 	for (i = 0; i < bch2_opts_nr; i++) {
1799 		const struct bch_option *opt = &bch2_opt_table[i];
1800 		u64 v = bch2_opt_get_by_id(&c->opts, i);
1801 
1802 		if ((opt->flags & OPT_HIDDEN) ||
1803 		    !(opt->flags & OPT_MOUNT))
1804 			continue;
1805 
1806 		if (v == bch2_opt_get_by_id(&bch2_opts_default, i))
1807 			continue;
1808 
1809 		printbuf_reset(&buf);
1810 		bch2_opt_to_text(&buf, c, c->disk_sb.sb, opt, v,
1811 				 OPT_SHOW_MOUNT_STYLE);
1812 		seq_putc(seq, ',');
1813 		seq_puts(seq, buf.buf);
1814 	}
1815 
1816 	if (buf.allocation_failure)
1817 		ret = -ENOMEM;
1818 	printbuf_exit(&buf);
1819 	return ret;
1820 }
1821 
1822 static void bch2_put_super(struct super_block *sb)
1823 {
1824 	struct bch_fs *c = sb->s_fs_info;
1825 
1826 	__bch2_fs_stop(c);
1827 }
1828 
1829 /*
1830  * bcachefs doesn't currently integrate intwrite freeze protection but the
1831  * internal write references serve the same purpose. Therefore reuse the
1832  * read-only transition code to perform the quiesce. The caveat is that we don't
1833  * currently have the ability to block tasks that want a write reference while
1834  * the superblock is frozen. This is fine for now, but we should either add
1835  * blocking support or find a way to integrate sb_start_intwrite() and friends.
1836  */
1837 static int bch2_freeze(struct super_block *sb)
1838 {
1839 	struct bch_fs *c = sb->s_fs_info;
1840 
1841 	down_write(&c->state_lock);
1842 	bch2_fs_read_only(c);
1843 	up_write(&c->state_lock);
1844 	return 0;
1845 }
1846 
1847 static int bch2_unfreeze(struct super_block *sb)
1848 {
1849 	struct bch_fs *c = sb->s_fs_info;
1850 	int ret;
1851 
1852 	if (test_bit(BCH_FS_emergency_ro, &c->flags))
1853 		return 0;
1854 
1855 	down_write(&c->state_lock);
1856 	ret = bch2_fs_read_write(c);
1857 	up_write(&c->state_lock);
1858 	return ret;
1859 }
1860 
1861 static const struct super_operations bch_super_operations = {
1862 	.alloc_inode	= bch2_alloc_inode,
1863 	.free_inode	= bch2_free_inode,
1864 	.write_inode	= bch2_vfs_write_inode,
1865 	.evict_inode	= bch2_evict_inode,
1866 	.sync_fs	= bch2_sync_fs,
1867 	.statfs		= bch2_statfs,
1868 	.show_devname	= bch2_show_devname,
1869 	.show_options	= bch2_show_options,
1870 	.put_super	= bch2_put_super,
1871 	.freeze_fs	= bch2_freeze,
1872 	.unfreeze_fs	= bch2_unfreeze,
1873 };
1874 
1875 static int bch2_set_super(struct super_block *s, void *data)
1876 {
1877 	s->s_fs_info = data;
1878 	return 0;
1879 }
1880 
1881 static int bch2_noset_super(struct super_block *s, void *data)
1882 {
1883 	return -EBUSY;
1884 }
1885 
1886 typedef DARRAY(struct bch_fs *) darray_fs;
1887 
1888 static int bch2_test_super(struct super_block *s, void *data)
1889 {
1890 	struct bch_fs *c = s->s_fs_info;
1891 	darray_fs *d = data;
1892 
1893 	if (!c)
1894 		return false;
1895 
1896 	darray_for_each(*d, i)
1897 		if (c != *i)
1898 			return false;
1899 	return true;
1900 }
1901 
1902 static int bch2_fs_get_tree(struct fs_context *fc)
1903 {
1904 	struct bch_fs *c;
1905 	struct super_block *sb;
1906 	struct inode *vinode;
1907 	struct bch2_opts_parse *opts_parse = fc->fs_private;
1908 	struct bch_opts opts = opts_parse->opts;
1909 	darray_str devs;
1910 	darray_fs devs_to_fs = {};
1911 	int ret;
1912 
1913 	opt_set(opts, read_only, (fc->sb_flags & SB_RDONLY) != 0);
1914 	opt_set(opts, nostart, true);
1915 
1916 	if (!fc->source || strlen(fc->source) == 0)
1917 		return -EINVAL;
1918 
1919 	ret = bch2_split_devs(fc->source, &devs);
1920 	if (ret)
1921 		return ret;
1922 
1923 	darray_for_each(devs, i) {
1924 		ret = darray_push(&devs_to_fs, bch2_path_to_fs(*i));
1925 		if (ret)
1926 			goto err;
1927 	}
1928 
1929 	sb = sget(fc->fs_type, bch2_test_super, bch2_noset_super, fc->sb_flags|SB_NOSEC, &devs_to_fs);
1930 	if (!IS_ERR(sb))
1931 		goto got_sb;
1932 
1933 	c = bch2_fs_open(devs.data, devs.nr, opts);
1934 	ret = PTR_ERR_OR_ZERO(c);
1935 	if (ret)
1936 		goto err;
1937 
1938 	/* Some options can't be parsed until after the fs is started: */
1939 	opts = bch2_opts_empty();
1940 	ret = bch2_parse_mount_opts(c, &opts, NULL, opts_parse->parse_later.buf);
1941 	if (ret)
1942 		goto err_stop_fs;
1943 
1944 	bch2_opts_apply(&c->opts, opts);
1945 
1946 	ret = bch2_fs_start(c);
1947 	if (ret)
1948 		goto err_stop_fs;
1949 
1950 	sb = sget(fc->fs_type, NULL, bch2_set_super, fc->sb_flags|SB_NOSEC, c);
1951 	ret = PTR_ERR_OR_ZERO(sb);
1952 	if (ret)
1953 		goto err_stop_fs;
1954 got_sb:
1955 	c = sb->s_fs_info;
1956 
1957 	if (sb->s_root) {
1958 		if ((fc->sb_flags ^ sb->s_flags) & SB_RDONLY) {
1959 			ret = -EBUSY;
1960 			goto err_put_super;
1961 		}
1962 		goto out;
1963 	}
1964 
1965 	sb->s_blocksize		= block_bytes(c);
1966 	sb->s_blocksize_bits	= ilog2(block_bytes(c));
1967 	sb->s_maxbytes		= MAX_LFS_FILESIZE;
1968 	sb->s_op		= &bch_super_operations;
1969 	sb->s_export_op		= &bch_export_ops;
1970 #ifdef CONFIG_BCACHEFS_QUOTA
1971 	sb->s_qcop		= &bch2_quotactl_operations;
1972 	sb->s_quota_types	= QTYPE_MASK_USR|QTYPE_MASK_GRP|QTYPE_MASK_PRJ;
1973 #endif
1974 	sb->s_xattr		= bch2_xattr_handlers;
1975 	sb->s_magic		= BCACHEFS_STATFS_MAGIC;
1976 	sb->s_time_gran		= c->sb.nsec_per_time_unit;
1977 	sb->s_time_min		= div_s64(S64_MIN, c->sb.time_units_per_sec) + 1;
1978 	sb->s_time_max		= div_s64(S64_MAX, c->sb.time_units_per_sec);
1979 	sb->s_uuid		= c->sb.user_uuid;
1980 	sb->s_shrink->seeks	= 0;
1981 	c->vfs_sb		= sb;
1982 	strscpy(sb->s_id, c->name, sizeof(sb->s_id));
1983 
1984 	ret = super_setup_bdi(sb);
1985 	if (ret)
1986 		goto err_put_super;
1987 
1988 	sb->s_bdi->ra_pages		= VM_READAHEAD_PAGES;
1989 
1990 	for_each_online_member(c, ca) {
1991 		struct block_device *bdev = ca->disk_sb.bdev;
1992 
1993 		/* XXX: create an anonymous device for multi device filesystems */
1994 		sb->s_bdev	= bdev;
1995 		sb->s_dev	= bdev->bd_dev;
1996 		percpu_ref_put(&ca->io_ref);
1997 		break;
1998 	}
1999 
2000 	c->dev = sb->s_dev;
2001 
2002 #ifdef CONFIG_BCACHEFS_POSIX_ACL
2003 	if (c->opts.acl)
2004 		sb->s_flags	|= SB_POSIXACL;
2005 #endif
2006 
2007 	sb->s_shrink->seeks = 0;
2008 
2009 	vinode = bch2_vfs_inode_get(c, BCACHEFS_ROOT_SUBVOL_INUM);
2010 	ret = PTR_ERR_OR_ZERO(vinode);
2011 	bch_err_msg(c, ret, "mounting: error getting root inode");
2012 	if (ret)
2013 		goto err_put_super;
2014 
2015 	sb->s_root = d_make_root(vinode);
2016 	if (!sb->s_root) {
2017 		bch_err(c, "error mounting: error allocating root dentry");
2018 		ret = -ENOMEM;
2019 		goto err_put_super;
2020 	}
2021 
2022 	sb->s_flags |= SB_ACTIVE;
2023 out:
2024 	fc->root = dget(sb->s_root);
2025 err:
2026 	darray_exit(&devs_to_fs);
2027 	bch2_darray_str_exit(&devs);
2028 	if (ret)
2029 		pr_err("error: %s", bch2_err_str(ret));
2030 	/*
2031 	 * On an inconsistency error in recovery we might see an -EROFS derived
2032 	 * errorcode (from the journal), but we don't want to return that to
2033 	 * userspace as that causes util-linux to retry the mount RO - which is
2034 	 * confusing:
2035 	 */
2036 	if (bch2_err_matches(ret, EROFS) && ret != -EROFS)
2037 		ret = -EIO;
2038 	return bch2_err_class(ret);
2039 
2040 err_stop_fs:
2041 	bch2_fs_stop(c);
2042 	goto err;
2043 
2044 err_put_super:
2045 	__bch2_fs_stop(c);
2046 	deactivate_locked_super(sb);
2047 	goto err;
2048 }
2049 
2050 static void bch2_kill_sb(struct super_block *sb)
2051 {
2052 	struct bch_fs *c = sb->s_fs_info;
2053 
2054 	generic_shutdown_super(sb);
2055 	bch2_fs_free(c);
2056 }
2057 
2058 static void bch2_fs_context_free(struct fs_context *fc)
2059 {
2060 	struct bch2_opts_parse *opts = fc->fs_private;
2061 
2062 	if (opts) {
2063 		printbuf_exit(&opts->parse_later);
2064 		kfree(opts);
2065 	}
2066 }
2067 
2068 static int bch2_fs_parse_param(struct fs_context *fc,
2069 			       struct fs_parameter *param)
2070 {
2071 	/*
2072 	 * the "source" param, i.e., the name of the device(s) to mount,
2073 	 * is handled by the VFS layer.
2074 	 */
2075 	if (!strcmp(param->key, "source"))
2076 		return -ENOPARAM;
2077 
2078 	struct bch2_opts_parse *opts = fc->fs_private;
2079 	struct bch_fs *c = NULL;
2080 
2081 	/* for reconfigure, we already have a struct bch_fs */
2082 	if (fc->root)
2083 		c = fc->root->d_sb->s_fs_info;
2084 
2085 	int ret = bch2_parse_one_mount_opt(c, &opts->opts,
2086 					   &opts->parse_later, param->key,
2087 					   param->string);
2088 
2089 	return bch2_err_class(ret);
2090 }
2091 
2092 static int bch2_fs_reconfigure(struct fs_context *fc)
2093 {
2094 	struct super_block *sb = fc->root->d_sb;
2095 	struct bch2_opts_parse *opts = fc->fs_private;
2096 
2097 	return bch2_remount(sb, &fc->sb_flags, opts->opts);
2098 }
2099 
2100 static const struct fs_context_operations bch2_context_ops = {
2101 	.free        = bch2_fs_context_free,
2102 	.parse_param = bch2_fs_parse_param,
2103 	.get_tree    = bch2_fs_get_tree,
2104 	.reconfigure = bch2_fs_reconfigure,
2105 };
2106 
2107 static int bch2_init_fs_context(struct fs_context *fc)
2108 {
2109 	struct bch2_opts_parse *opts = kzalloc(sizeof(*opts), GFP_KERNEL);
2110 
2111 	if (!opts)
2112 		return -ENOMEM;
2113 
2114 	opts->parse_later = PRINTBUF;
2115 
2116 	fc->ops = &bch2_context_ops;
2117 	fc->fs_private = opts;
2118 
2119 	return 0;
2120 }
2121 
2122 static struct file_system_type bcache_fs_type = {
2123 	.owner			= THIS_MODULE,
2124 	.name			= "bcachefs",
2125 	.init_fs_context	= bch2_init_fs_context,
2126 	.kill_sb		= bch2_kill_sb,
2127 	.fs_flags		= FS_REQUIRES_DEV,
2128 };
2129 
2130 MODULE_ALIAS_FS("bcachefs");
2131 
2132 void bch2_vfs_exit(void)
2133 {
2134 	unregister_filesystem(&bcache_fs_type);
2135 	kmem_cache_destroy(bch2_inode_cache);
2136 }
2137 
2138 int __init bch2_vfs_init(void)
2139 {
2140 	int ret = -ENOMEM;
2141 
2142 	bch2_inode_cache = KMEM_CACHE(bch_inode_info, SLAB_RECLAIM_ACCOUNT);
2143 	if (!bch2_inode_cache)
2144 		goto err;
2145 
2146 	ret = register_filesystem(&bcache_fs_type);
2147 	if (ret)
2148 		goto err;
2149 
2150 	return 0;
2151 err:
2152 	bch2_vfs_exit();
2153 	return ret;
2154 }
2155 
2156 #endif /* NO_BCACHEFS_FS */
2157