xref: /linux/fs/fuse/dir.c (revision 85cdaca6970028bf6f544c355c90035586836ddf)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3   FUSE: Filesystem in Userspace
4   Copyright (C) 2001-2008  Miklos Szeredi <miklos@szeredi.hu>
5 */
6 
7 #include "dev.h"
8 #include "fuse_i.h"
9 
10 #include <linux/pagemap.h>
11 #include <linux/file.h>
12 #include <linux/fs_context.h>
13 #include <linux/moduleparam.h>
14 #include <linux/sched.h>
15 #include <linux/namei.h>
16 #include <linux/slab.h>
17 #include <linux/xattr.h>
18 #include <linux/iversion.h>
19 #include <linux/posix_acl.h>
20 #include <linux/security.h>
21 #include <linux/types.h>
22 #include <linux/kernel.h>
23 
24 static bool __read_mostly allow_sys_admin_access;
25 module_param(allow_sys_admin_access, bool, 0644);
26 MODULE_PARM_DESC(allow_sys_admin_access,
27 		 "Allow users with CAP_SYS_ADMIN in initial userns to bypass allow_other access check");
28 
29 struct dentry_bucket {
30 	struct rb_root tree;
31 	spinlock_t lock;
32 };
33 
34 #define FUSE_HASH_BITS	5
35 #define FUSE_HASH_SIZE	(1 << FUSE_HASH_BITS)
36 static struct dentry_bucket dentry_hash[FUSE_HASH_SIZE];
37 struct delayed_work dentry_tree_work;
38 
39 /* Minimum invalidation work queue frequency */
40 #define FUSE_DENTRY_INVAL_FREQ_MIN 5
41 
42 unsigned __read_mostly inval_wq;
43 static int inval_wq_set(const char *val, const struct kernel_param *kp)
44 {
45 	unsigned int num;
46 	unsigned int old = inval_wq;
47 	int ret;
48 
49 	if (!val)
50 		return -EINVAL;
51 
52 	ret = kstrtouint(val, 0, &num);
53 	if (ret)
54 		return ret;
55 
56 	if ((num < FUSE_DENTRY_INVAL_FREQ_MIN) && (num != 0))
57 		return -EINVAL;
58 
59 	/* This should prevent overflow in secs_to_jiffies() */
60 	if (num > USHRT_MAX)
61 		return -EINVAL;
62 
63 	*((unsigned int *)kp->arg) = num;
64 
65 	if (num && !old)
66 		schedule_delayed_work(&dentry_tree_work,
67 				      secs_to_jiffies(num));
68 	else if (!num && old)
69 		cancel_delayed_work_sync(&dentry_tree_work);
70 
71 	return 0;
72 }
73 static const struct kernel_param_ops inval_wq_ops = {
74 	.set = inval_wq_set,
75 	.get = param_get_uint,
76 };
77 module_param_cb(inval_wq, &inval_wq_ops, &inval_wq, 0644);
78 __MODULE_PARM_TYPE(inval_wq, "uint");
79 MODULE_PARM_DESC(inval_wq,
80 		 "Dentries invalidation work queue period in secs (>= "
81 		 __stringify(FUSE_DENTRY_INVAL_FREQ_MIN) ").");
82 
83 static inline struct dentry_bucket *get_dentry_bucket(struct dentry *dentry)
84 {
85 	int i = hash_ptr(dentry, FUSE_HASH_BITS);
86 
87 	return &dentry_hash[i];
88 }
89 
90 static void fuse_advise_use_readdirplus(struct inode *dir)
91 {
92 	struct fuse_inode *fi = get_fuse_inode(dir);
93 
94 	set_bit(FUSE_I_ADVISE_RDPLUS, &fi->state);
95 }
96 
97 struct fuse_dentry {
98 	u64 time;
99 	union {
100 		struct rcu_head rcu;
101 		struct rb_node node;
102 	};
103 	struct dentry *dentry;
104 };
105 
106 static void __fuse_dentry_tree_del_node(struct fuse_dentry *fd,
107 					struct dentry_bucket *bucket)
108 {
109 	if (!RB_EMPTY_NODE(&fd->node)) {
110 		rb_erase(&fd->node, &bucket->tree);
111 		RB_CLEAR_NODE(&fd->node);
112 	}
113 }
114 
115 static void fuse_dentry_tree_del_node(struct dentry *dentry)
116 {
117 	struct fuse_dentry *fd = dentry->d_fsdata;
118 	struct dentry_bucket *bucket = get_dentry_bucket(dentry);
119 
120 	spin_lock(&bucket->lock);
121 	__fuse_dentry_tree_del_node(fd, bucket);
122 	spin_unlock(&bucket->lock);
123 }
124 
125 static void fuse_dentry_tree_add_node(struct dentry *dentry)
126 {
127 	struct fuse_dentry *fd = dentry->d_fsdata;
128 	struct dentry_bucket *bucket;
129 	struct fuse_dentry *cur;
130 	struct rb_node **p, *parent = NULL;
131 
132 	if (!inval_wq)
133 		return;
134 
135 	bucket = get_dentry_bucket(dentry);
136 
137 	spin_lock(&bucket->lock);
138 
139 	__fuse_dentry_tree_del_node(fd, bucket);
140 
141 	p = &bucket->tree.rb_node;
142 	while (*p) {
143 		parent = *p;
144 		cur = rb_entry(*p, struct fuse_dentry, node);
145 		if (fd->time < cur->time)
146 			p = &(*p)->rb_left;
147 		else
148 			p = &(*p)->rb_right;
149 	}
150 	rb_link_node(&fd->node, parent, p);
151 	rb_insert_color(&fd->node, &bucket->tree);
152 	spin_unlock(&bucket->lock);
153 }
154 
155 /*
156  * work queue which, when enabled, will periodically check for expired dentries
157  * in the dentries tree.
158  */
159 static void fuse_dentry_tree_work(struct work_struct *work)
160 {
161 	LIST_HEAD(dispose);
162 	struct fuse_dentry *fd;
163 	struct rb_node *node;
164 	int i;
165 
166 	for (i = 0; i < FUSE_HASH_SIZE; i++) {
167 		spin_lock(&dentry_hash[i].lock);
168 		node = rb_first(&dentry_hash[i].tree);
169 		while (node) {
170 			fd = rb_entry(node, struct fuse_dentry, node);
171 			if (!time_before64(fd->time, get_jiffies_64()))
172 				break;
173 
174 			rb_erase(&fd->node, &dentry_hash[i].tree);
175 			RB_CLEAR_NODE(&fd->node);
176 			spin_lock(&fd->dentry->d_lock);
177 			/* If dentry is still referenced, let next dput release it */
178 			fd->dentry->d_flags |= DCACHE_OP_DELETE;
179 			__move_to_shrink_list(fd->dentry, &dispose);
180 			spin_unlock(&fd->dentry->d_lock);
181 			if (need_resched()) {
182 				spin_unlock(&dentry_hash[i].lock);
183 				cond_resched();
184 				spin_lock(&dentry_hash[i].lock);
185 			}
186 			node = rb_first(&dentry_hash[i].tree);
187 		}
188 		spin_unlock(&dentry_hash[i].lock);
189 	}
190 	shrink_dentry_list(&dispose);
191 
192 	if (inval_wq)
193 		schedule_delayed_work(&dentry_tree_work,
194 				      secs_to_jiffies(inval_wq));
195 }
196 
197 void fuse_epoch_work(struct work_struct *work)
198 {
199 	struct fuse_conn *fc = container_of(work, struct fuse_conn,
200 					    epoch_work);
201 	struct fuse_mount *fm;
202 	struct inode *inode;
203 
204 	down_read(&fc->killsb);
205 
206 	inode = fuse_ilookup(fc, FUSE_ROOT_ID, &fm);
207 	if (inode) {
208 		iput(inode);
209 		/* Remove all possible active references to cached inodes */
210 		shrink_dcache_sb(fm->sb);
211 	} else
212 		pr_warn("Failed to get root inode");
213 
214 	up_read(&fc->killsb);
215 }
216 
217 void fuse_dentry_tree_init(void)
218 {
219 	int i;
220 
221 	for (i = 0; i < FUSE_HASH_SIZE; i++) {
222 		spin_lock_init(&dentry_hash[i].lock);
223 		dentry_hash[i].tree = RB_ROOT;
224 	}
225 	INIT_DELAYED_WORK(&dentry_tree_work, fuse_dentry_tree_work);
226 }
227 
228 void fuse_dentry_tree_cleanup(void)
229 {
230 	int i;
231 
232 	inval_wq = 0;
233 	cancel_delayed_work_sync(&dentry_tree_work);
234 
235 	for (i = 0; i < FUSE_HASH_SIZE; i++)
236 		WARN_ON_ONCE(!RB_EMPTY_ROOT(&dentry_hash[i].tree));
237 }
238 
239 static inline void __fuse_dentry_settime(struct dentry *dentry, u64 time)
240 {
241 	((struct fuse_dentry *) dentry->d_fsdata)->time = time;
242 }
243 
244 static inline u64 fuse_dentry_time(const struct dentry *entry)
245 {
246 	return ((struct fuse_dentry *) entry->d_fsdata)->time;
247 }
248 
249 static void fuse_dentry_settime(struct dentry *dentry, u64 time)
250 {
251 	struct fuse_conn *fc = get_fuse_conn_super(dentry->d_sb);
252 	bool delete = !time && fc->delete_stale;
253 	/*
254 	 * Mess with DCACHE_OP_DELETE because dput() will be faster without it.
255 	 * Don't care about races, either way it's just an optimization
256 	 */
257 	if ((!delete && (dentry->d_flags & DCACHE_OP_DELETE)) ||
258 	    (delete && !(dentry->d_flags & DCACHE_OP_DELETE))) {
259 		spin_lock(&dentry->d_lock);
260 		if (!delete)
261 			dentry->d_flags &= ~DCACHE_OP_DELETE;
262 		else
263 			dentry->d_flags |= DCACHE_OP_DELETE;
264 		spin_unlock(&dentry->d_lock);
265 	}
266 
267 	__fuse_dentry_settime(dentry, time);
268 	fuse_dentry_tree_add_node(dentry);
269 }
270 
271 /*
272  * FUSE caches dentries and attributes with separate timeout.  The
273  * time in jiffies until the dentry/attributes are valid is stored in
274  * dentry->d_fsdata and fuse_inode->i_time respectively.
275  */
276 
277 /*
278  * Calculate the time in jiffies until a dentry/attributes are valid
279  */
280 u64 fuse_time_to_jiffies(u64 sec, u32 nsec)
281 {
282 	if (sec || nsec) {
283 		struct timespec64 ts = {
284 			sec,
285 			min_t(u32, nsec, NSEC_PER_SEC - 1)
286 		};
287 
288 		return get_jiffies_64() + timespec64_to_jiffies(&ts);
289 	} else
290 		return 0;
291 }
292 
293 /*
294  * Set dentry and possibly attribute timeouts from the lookup/mk*
295  * replies
296  */
297 void fuse_change_entry_timeout(struct dentry *entry, struct fuse_entry_out *o)
298 {
299 	fuse_dentry_settime(entry,
300 		fuse_time_to_jiffies(o->entry_valid, o->entry_valid_nsec));
301 }
302 
303 void fuse_invalidate_attr_mask(struct inode *inode, u32 mask)
304 {
305 	set_mask_bits(&get_fuse_inode(inode)->inval_mask, 0, mask);
306 }
307 
308 /*
309  * Mark the attributes as stale, so that at the next call to
310  * ->getattr() they will be fetched from userspace
311  */
312 void fuse_invalidate_attr(struct inode *inode)
313 {
314 	fuse_invalidate_attr_mask(inode, STATX_BASIC_STATS);
315 }
316 
317 static void fuse_dir_changed(struct inode *dir)
318 {
319 	fuse_invalidate_attr_mask(dir, FUSE_STATX_MODDIR);
320 	inode_maybe_inc_iversion(dir, false);
321 }
322 
323 /*
324  * Mark the attributes as stale due to an atime change.  Avoid the invalidate if
325  * atime is not used.
326  */
327 void fuse_invalidate_atime(struct inode *inode)
328 {
329 	if (!IS_RDONLY(inode))
330 		fuse_invalidate_attr_mask(inode, STATX_ATIME);
331 }
332 
333 /*
334  * Just mark the entry as stale, so that a next attempt to look it up
335  * will result in a new lookup call to userspace
336  *
337  * This is called when a dentry is about to become negative and the
338  * timeout is unknown (unlink, rmdir, rename and in some cases
339  * lookup)
340  */
341 void fuse_invalidate_entry_cache(struct dentry *entry)
342 {
343 	fuse_dentry_settime(entry, 0);
344 }
345 
346 /*
347  * Same as fuse_invalidate_entry_cache(), but also try to remove the
348  * dentry from the hash
349  */
350 static void fuse_invalidate_entry(struct dentry *entry)
351 {
352 	d_invalidate(entry);
353 	fuse_invalidate_entry_cache(entry);
354 }
355 
356 static void fuse_lookup_init(struct fuse_args *args, u64 nodeid,
357 			     const struct qstr *name,
358 			     struct fuse_entry_out *outarg)
359 {
360 	memset(outarg, 0, sizeof(struct fuse_entry_out));
361 	args->opcode = FUSE_LOOKUP;
362 	args->nodeid = nodeid;
363 	args->in_numargs = 3;
364 	fuse_set_zero_arg0(args);
365 	args->in_args[1].size = name->len;
366 	args->in_args[1].value = name->name;
367 	args->in_args[2].size = 1;
368 	args->in_args[2].value = "";
369 	args->out_numargs = 1;
370 	args->out_args[0].size = sizeof(struct fuse_entry_out);
371 	args->out_args[0].value = outarg;
372 }
373 
374 /*
375  * Check whether the dentry is still valid
376  *
377  * If the entry validity timeout has expired and the dentry is
378  * positive, try to redo the lookup.  If the lookup results in a
379  * different inode, then let the VFS invalidate the dentry and redo
380  * the lookup once more.  If the lookup results in the same inode,
381  * then refresh the attributes, timeouts and mark the dentry valid.
382  */
383 static int fuse_dentry_revalidate(struct inode *dir, const struct qstr *name,
384 				  struct dentry *entry, unsigned int flags)
385 {
386 	struct inode *inode;
387 	struct fuse_mount *fm;
388 	struct fuse_conn *fc;
389 	struct fuse_inode *fi;
390 	int ret;
391 
392 	fc = get_fuse_conn_super(dir->i_sb);
393 	if (entry->d_time < atomic_read(&fc->epoch))
394 		goto invalid;
395 
396 	inode = d_inode_rcu(entry);
397 	if (inode && fuse_is_bad(inode))
398 		goto invalid;
399 	else if (time_before64(fuse_dentry_time(entry), get_jiffies_64()) ||
400 		 (flags & (LOOKUP_EXCL | LOOKUP_REVAL | LOOKUP_RENAME_TARGET))) {
401 		struct fuse_entry_out outarg;
402 		FUSE_ARGS(args);
403 		struct fuse_forget_link *forget;
404 		u64 attr_version;
405 
406 		/* For negative dentries, always do a fresh lookup */
407 		if (!inode)
408 			goto invalid;
409 
410 		ret = -ECHILD;
411 		if (flags & LOOKUP_RCU)
412 			goto out;
413 
414 		fm = get_fuse_mount(inode);
415 
416 		forget = fuse_alloc_forget();
417 		ret = -ENOMEM;
418 		if (!forget)
419 			goto out;
420 
421 		attr_version = fuse_get_attr_version(fm->fc);
422 
423 		fuse_lookup_init(&args, get_node_id(dir), name, &outarg);
424 		ret = fuse_simple_request(fm, &args);
425 		/* Zero nodeid is same as -ENOENT */
426 		if (!ret && !outarg.nodeid)
427 			ret = -ENOENT;
428 		if (!ret) {
429 			fi = get_fuse_inode(inode);
430 			if (outarg.nodeid != get_node_id(inode) ||
431 			    (bool) IS_AUTOMOUNT(inode) != (bool) (outarg.attr.flags & FUSE_ATTR_SUBMOUNT)) {
432 				fuse_chan_queue_forget(fm->fc->chan, forget,
433 						  outarg.nodeid, 1);
434 				goto invalid;
435 			}
436 			spin_lock(&fi->lock);
437 			fi->nlookup++;
438 			spin_unlock(&fi->lock);
439 		}
440 		kfree(forget);
441 		if (ret == -ENOMEM || ret == -EINTR)
442 			goto out;
443 		if (ret || fuse_invalid_attr(&outarg.attr) ||
444 		    fuse_stale_inode(inode, outarg.generation, &outarg.attr))
445 			goto invalid;
446 
447 		forget_all_cached_acls(inode);
448 		fuse_change_attributes(inode, &outarg.attr, NULL,
449 				       ATTR_TIMEOUT(&outarg),
450 				       attr_version);
451 		fuse_change_entry_timeout(entry, &outarg);
452 	} else if (inode) {
453 		fi = get_fuse_inode(inode);
454 		if (flags & LOOKUP_RCU) {
455 			if (test_bit(FUSE_I_INIT_RDPLUS, &fi->state))
456 				return -ECHILD;
457 		} else if (test_and_clear_bit(FUSE_I_INIT_RDPLUS, &fi->state)) {
458 			fuse_advise_use_readdirplus(dir);
459 		}
460 	}
461 	ret = 1;
462 out:
463 	return ret;
464 
465 invalid:
466 	ret = 0;
467 	goto out;
468 }
469 
470 static int fuse_dentry_init(struct dentry *dentry)
471 {
472 	struct fuse_dentry *fd;
473 
474 	fd = kzalloc_obj(struct fuse_dentry,
475 			 GFP_KERNEL_ACCOUNT | __GFP_RECLAIMABLE);
476 	if (!fd)
477 		return -ENOMEM;
478 
479 	fd->dentry = dentry;
480 	RB_CLEAR_NODE(&fd->node);
481 	dentry->d_fsdata = fd;
482 	/*
483 	 * Initialising d_time (epoch) to '0' ensures the dentry is invalid
484 	 * if compared to fc->epoch, which is initialized to '1'.
485 	 */
486 	dentry->d_time = 0;
487 
488 	return 0;
489 }
490 
491 static void fuse_dentry_release(struct dentry *dentry)
492 {
493 	struct fuse_dentry *fd = dentry->d_fsdata;
494 
495 	if (!RB_EMPTY_NODE(&fd->node))
496 		fuse_dentry_tree_del_node(dentry);
497 	kfree_rcu(fd, rcu);
498 }
499 
500 static int fuse_dentry_delete(const struct dentry *dentry)
501 {
502 	return time_before64(fuse_dentry_time(dentry), get_jiffies_64());
503 }
504 
505 /*
506  * Create a fuse_mount object with a new superblock (with path->dentry
507  * as the root), and return that mount so it can be auto-mounted on
508  * @path.
509  */
510 static struct vfsmount *fuse_dentry_automount(struct path *path)
511 {
512 	struct fs_context *fsc;
513 	struct vfsmount *mnt;
514 	struct fuse_inode *mp_fi = get_fuse_inode(d_inode(path->dentry));
515 
516 	fsc = fs_context_for_submount(path->mnt->mnt_sb->s_type, path->dentry);
517 	if (IS_ERR(fsc))
518 		return ERR_CAST(fsc);
519 
520 	/* Pass the FUSE inode of the mount for fuse_get_tree_submount() */
521 	fsc->fs_private = mp_fi;
522 
523 	/* Create the submount */
524 	mnt = fc_mount(fsc);
525 	put_fs_context(fsc);
526 	return mnt;
527 }
528 
529 const struct dentry_operations fuse_dentry_operations = {
530 	.d_revalidate	= fuse_dentry_revalidate,
531 	.d_delete	= fuse_dentry_delete,
532 	.d_init		= fuse_dentry_init,
533 	.d_release	= fuse_dentry_release,
534 	.d_automount	= fuse_dentry_automount,
535 };
536 
537 int fuse_valid_type(int m)
538 {
539 	return S_ISREG(m) || S_ISDIR(m) || S_ISLNK(m) || S_ISCHR(m) ||
540 		S_ISBLK(m) || S_ISFIFO(m) || S_ISSOCK(m);
541 }
542 
543 static bool fuse_valid_size(u64 size)
544 {
545 	return size <= LLONG_MAX;
546 }
547 
548 bool fuse_invalid_attr(struct fuse_attr *attr)
549 {
550 	return !fuse_valid_type(attr->mode) || !fuse_valid_size(attr->size);
551 }
552 
553 int fuse_lookup_name(struct super_block *sb, u64 nodeid, const struct qstr *name,
554 		     struct fuse_entry_out *outarg, struct inode **inode)
555 {
556 	struct fuse_mount *fm = get_fuse_mount_super(sb);
557 	FUSE_ARGS(args);
558 	struct fuse_forget_link *forget;
559 	u64 attr_version, evict_ctr;
560 	int err;
561 
562 	*inode = NULL;
563 	err = -ENAMETOOLONG;
564 	if (name->len > fm->fc->name_max)
565 		goto out;
566 
567 
568 	forget = fuse_alloc_forget();
569 	err = -ENOMEM;
570 	if (!forget)
571 		goto out;
572 
573 	attr_version = fuse_get_attr_version(fm->fc);
574 	evict_ctr = fuse_get_evict_ctr(fm->fc);
575 
576 	fuse_lookup_init(&args, nodeid, name, outarg);
577 	err = fuse_simple_request(fm, &args);
578 	/* Zero nodeid is same as -ENOENT, but with valid timeout */
579 	if (err || !outarg->nodeid)
580 		goto out_put_forget;
581 
582 	err = -EIO;
583 	if (fuse_invalid_attr(&outarg->attr))
584 		goto out_put_forget;
585 	if (outarg->nodeid == FUSE_ROOT_ID && outarg->generation != 0) {
586 		pr_warn_once("root generation should be zero\n");
587 		outarg->generation = 0;
588 	}
589 
590 	*inode = fuse_iget(sb, outarg->nodeid, outarg->generation,
591 			   &outarg->attr, ATTR_TIMEOUT(outarg),
592 			   attr_version, evict_ctr);
593 	err = -ENOMEM;
594 	if (!*inode) {
595 		fuse_chan_queue_forget(fm->fc->chan, forget, outarg->nodeid, 1);
596 		goto out;
597 	}
598 	err = 0;
599 
600  out_put_forget:
601 	kfree(forget);
602  out:
603 	return err;
604 }
605 
606 static struct dentry *fuse_lookup(struct inode *dir, struct dentry *entry,
607 				  unsigned int flags)
608 {
609 	struct fuse_entry_out outarg;
610 	struct fuse_conn *fc;
611 	struct inode *inode;
612 	struct dentry *newent;
613 	int err, epoch;
614 	bool outarg_valid = true;
615 	bool locked;
616 
617 	if (fuse_is_bad(dir))
618 		return ERR_PTR(-EIO);
619 
620 	fc = get_fuse_conn_super(dir->i_sb);
621 	epoch = atomic_read(&fc->epoch);
622 
623 	locked = fuse_lock_inode(dir);
624 	err = fuse_lookup_name(dir->i_sb, get_node_id(dir), &entry->d_name,
625 			       &outarg, &inode);
626 	fuse_unlock_inode(dir, locked);
627 	if (err == -ENOENT) {
628 		outarg_valid = false;
629 		err = 0;
630 	}
631 	if (err)
632 		goto out_err;
633 
634 	err = -EIO;
635 	if (inode && get_node_id(inode) == FUSE_ROOT_ID)
636 		goto out_iput;
637 
638 	newent = d_splice_alias(inode, entry);
639 	err = PTR_ERR(newent);
640 	if (IS_ERR(newent))
641 		goto out_err;
642 
643 	entry = newent ? newent : entry;
644 	entry->d_time = epoch;
645 	if (outarg_valid)
646 		fuse_change_entry_timeout(entry, &outarg);
647 	else
648 		fuse_invalidate_entry_cache(entry);
649 
650 	if (inode)
651 		fuse_advise_use_readdirplus(dir);
652 	return newent;
653 
654  out_iput:
655 	iput(inode);
656  out_err:
657 	return ERR_PTR(err);
658 }
659 
660 static int get_security_context(struct dentry *entry, umode_t mode,
661 				struct fuse_in_arg *ext)
662 {
663 	struct fuse_secctx *fctx;
664 	struct fuse_secctx_header *header;
665 	struct lsm_context lsmctx = { };
666 	void *ptr;
667 	u32 total_len = sizeof(*header);
668 	int err, nr_ctx = 0;
669 	const char *name = NULL;
670 	size_t namesize;
671 
672 	err = security_dentry_init_security(entry, mode, &entry->d_name,
673 					    &name, &lsmctx);
674 
675 	/* If no LSM is supporting this security hook ignore error */
676 	if (err && err != -EOPNOTSUPP)
677 		goto out_err;
678 
679 	if (lsmctx.len) {
680 		nr_ctx = 1;
681 		namesize = strlen(name) + 1;
682 		err = -EIO;
683 		if (WARN_ON(namesize > XATTR_NAME_MAX + 1 ||
684 		    lsmctx.len > S32_MAX))
685 			goto out_err;
686 		total_len += FUSE_REC_ALIGN(sizeof(*fctx) + namesize +
687 					    lsmctx.len);
688 	}
689 
690 	err = -ENOMEM;
691 	header = ptr = kzalloc(total_len, GFP_KERNEL);
692 	if (!ptr)
693 		goto out_err;
694 
695 	header->nr_secctx = nr_ctx;
696 	header->size = total_len;
697 	ptr += sizeof(*header);
698 	if (nr_ctx) {
699 		fctx = ptr;
700 		fctx->size = lsmctx.len;
701 		ptr += sizeof(*fctx);
702 
703 		strscpy(ptr, name, namesize);
704 		ptr += namesize;
705 
706 		memcpy(ptr, lsmctx.context, lsmctx.len);
707 	}
708 	ext->size = total_len;
709 	ext->value = header;
710 	err = 0;
711 out_err:
712 	if (nr_ctx)
713 		security_release_secctx(&lsmctx);
714 	return err;
715 }
716 
717 static void *extend_arg(struct fuse_in_arg *buf, u32 bytes)
718 {
719 	void *p;
720 	u32 newlen = buf->size + bytes;
721 
722 	p = krealloc(buf->value, newlen, GFP_KERNEL);
723 	if (!p) {
724 		kfree(buf->value);
725 		buf->size = 0;
726 		buf->value = NULL;
727 		return NULL;
728 	}
729 
730 	memset(p + buf->size, 0, bytes);
731 	buf->value = p;
732 	buf->size = newlen;
733 
734 	return p + newlen - bytes;
735 }
736 
737 static u32 fuse_ext_size(size_t size)
738 {
739 	return FUSE_REC_ALIGN(sizeof(struct fuse_ext_header) + size);
740 }
741 
742 /*
743  * This adds just a single supplementary group that matches the parent's group.
744  */
745 static int get_create_supp_group(struct mnt_idmap *idmap,
746 				 struct inode *dir,
747 				 struct fuse_in_arg *ext)
748 {
749 	struct fuse_conn *fc = get_fuse_conn(dir);
750 	struct fuse_ext_header *xh;
751 	struct fuse_supp_groups *sg;
752 	kgid_t kgid = dir->i_gid;
753 	vfsgid_t vfsgid = make_vfsgid(idmap, fc->user_ns, kgid);
754 	gid_t parent_gid = from_kgid(fc->user_ns, kgid);
755 
756 	u32 sg_len = fuse_ext_size(sizeof(*sg) + sizeof(sg->groups[0]));
757 
758 	if (parent_gid == (gid_t) -1 || vfsgid_eq_kgid(vfsgid, current_fsgid()) ||
759 	    !vfsgid_in_group_p(vfsgid))
760 		return 0;
761 
762 	xh = extend_arg(ext, sg_len);
763 	if (!xh)
764 		return -ENOMEM;
765 
766 	xh->size = sg_len;
767 	xh->type = FUSE_EXT_GROUPS;
768 
769 	sg = (struct fuse_supp_groups *) &xh[1];
770 	sg->nr_groups = 1;
771 	sg->groups[0] = parent_gid;
772 
773 	return 0;
774 }
775 
776 static int get_create_ext(struct mnt_idmap *idmap,
777 			  struct fuse_args *args,
778 			  struct inode *dir, struct dentry *dentry,
779 			  umode_t mode)
780 {
781 	struct fuse_conn *fc = get_fuse_conn_super(dentry->d_sb);
782 	struct fuse_in_arg ext = { .size = 0, .value = NULL };
783 	int err = 0;
784 
785 	if (fc->init_security)
786 		err = get_security_context(dentry, mode, &ext);
787 	if (!err && fc->create_supp_group)
788 		err = get_create_supp_group(idmap, dir, &ext);
789 
790 	if (!err && ext.size) {
791 		WARN_ON(args->in_numargs >= ARRAY_SIZE(args->in_args));
792 		args->is_ext = true;
793 		args->ext_idx = args->in_numargs++;
794 		args->in_args[args->ext_idx] = ext;
795 	} else {
796 		kfree(ext.value);
797 	}
798 
799 	return err;
800 }
801 
802 static void free_ext_value(struct fuse_args *args)
803 {
804 	if (args->is_ext)
805 		kfree(args->in_args[args->ext_idx].value);
806 }
807 
808 /*
809  * Atomic create+open operation
810  *
811  * If the filesystem doesn't support this, then fall back to separate
812  * 'mknod' + 'open' requests.
813  */
814 static int fuse_create_open(struct mnt_idmap *idmap, struct inode *dir,
815 			    struct dentry *entry, struct file *file,
816 			    unsigned int flags, umode_t mode, u32 opcode)
817 {
818 	struct inode *inode;
819 	struct fuse_mount *fm = get_fuse_mount(dir);
820 	FUSE_ARGS(args);
821 	struct fuse_forget_link *forget;
822 	struct fuse_create_in inarg;
823 	struct fuse_open_out *outopenp;
824 	struct fuse_entry_out outentry;
825 	struct fuse_inode *fi;
826 	struct fuse_file *ff;
827 	int epoch, err;
828 	bool trunc = flags & O_TRUNC;
829 
830 	/* Userspace expects S_IFREG in create mode */
831 	BUG_ON((mode & S_IFMT) != S_IFREG);
832 
833 	epoch = atomic_read(&fm->fc->epoch);
834 	forget = fuse_alloc_forget();
835 	err = -ENOMEM;
836 	if (!forget)
837 		goto out_err;
838 
839 	ff = fuse_file_alloc(fm, true);
840 	if (!ff)
841 		goto out_put_forget_req;
842 
843 	if (!fm->fc->dont_mask)
844 		mode &= ~current_umask();
845 
846 	flags &= ~O_NOCTTY;
847 	memset(&inarg, 0, sizeof(inarg));
848 	memset(&outentry, 0, sizeof(outentry));
849 	inarg.flags = flags;
850 	inarg.mode = mode;
851 	inarg.umask = current_umask();
852 
853 	if (fm->fc->handle_killpriv_v2 && trunc &&
854 	    !(flags & O_EXCL) && !capable(CAP_FSETID)) {
855 		inarg.open_flags |= FUSE_OPEN_KILL_SUIDGID;
856 	}
857 
858 	args.opcode = opcode;
859 	args.nodeid = get_node_id(dir);
860 	args.in_numargs = 2;
861 	args.in_args[0].size = sizeof(inarg);
862 	args.in_args[0].value = &inarg;
863 	args.in_args[1].size = entry->d_name.len + 1;
864 	args.in_args[1].value = entry->d_name.name;
865 	args.out_numargs = 2;
866 	args.out_args[0].size = sizeof(outentry);
867 	args.out_args[0].value = &outentry;
868 	/* Store outarg for fuse_finish_open() */
869 	outopenp = &ff->args->open_outarg;
870 	args.out_args[1].size = sizeof(*outopenp);
871 	args.out_args[1].value = outopenp;
872 
873 	err = get_create_ext(idmap, &args, dir, entry, mode);
874 	if (err)
875 		goto out_free_ff;
876 
877 	err = fuse_simple_idmap_request(idmap, fm, &args);
878 	free_ext_value(&args);
879 	if (err)
880 		goto out_free_ff;
881 
882 	err = -EIO;
883 	if (!S_ISREG(outentry.attr.mode) || invalid_nodeid(outentry.nodeid) ||
884 	    fuse_invalid_attr(&outentry.attr))
885 		goto out_free_ff;
886 
887 	ff->fh = outopenp->fh;
888 	ff->nodeid = outentry.nodeid;
889 	ff->open_flags = outopenp->open_flags;
890 	inode = fuse_iget(dir->i_sb, outentry.nodeid, outentry.generation,
891 			  &outentry.attr, ATTR_TIMEOUT(&outentry), 0, 0);
892 	if (!inode) {
893 		flags &= ~(O_CREAT | O_EXCL | O_TRUNC);
894 		fuse_sync_release(NULL, ff, flags);
895 		fuse_chan_queue_forget(fm->fc->chan, forget, outentry.nodeid, 1);
896 		err = -ENOMEM;
897 		goto out_err;
898 	}
899 	kfree(forget);
900 	d_instantiate(entry, inode);
901 	entry->d_time = epoch;
902 	fuse_change_entry_timeout(entry, &outentry);
903 	fuse_dir_changed(dir);
904 	err = generic_file_open(inode, file);
905 	if (!err) {
906 		file->private_data = ff;
907 		err = finish_open(file, entry, fuse_finish_open);
908 	}
909 	if (err) {
910 		fi = get_fuse_inode(inode);
911 		fuse_sync_release(fi, ff, flags);
912 	} else {
913 		if (fm->fc->atomic_o_trunc && trunc)
914 			truncate_pagecache(inode, 0);
915 		else if (!(ff->open_flags & FOPEN_KEEP_CACHE))
916 			invalidate_inode_pages2(inode->i_mapping);
917 	}
918 	return err;
919 
920 out_free_ff:
921 	fuse_file_free(ff);
922 out_put_forget_req:
923 	kfree(forget);
924 out_err:
925 	return err;
926 }
927 
928 static int fuse_mknod(struct mnt_idmap *, struct inode *, struct dentry *,
929 		      umode_t, dev_t);
930 static int fuse_atomic_open(struct inode *dir, struct dentry *entry,
931 			    struct file *file, unsigned flags,
932 			    umode_t mode)
933 {
934 	int err;
935 	struct mnt_idmap *idmap = file_mnt_idmap(file);
936 	struct fuse_conn *fc = get_fuse_conn(dir);
937 
938 	if (fuse_is_bad(dir))
939 		return -EIO;
940 
941 	if (d_in_lookup(entry)) {
942 		struct dentry *res = fuse_lookup(dir, entry, 0);
943 		if (res || d_really_is_positive(entry))
944 			return finish_no_open(file, res);
945 	}
946 
947 	if (!(flags & O_CREAT))
948 		return finish_no_open(file, NULL);
949 
950 	/* Only creates */
951 	file->f_mode |= FMODE_CREATED;
952 
953 	if (fc->no_create)
954 		goto mknod;
955 
956 	err = fuse_create_open(idmap, dir, entry, file, flags, mode, FUSE_CREATE);
957 	if (err == -ENOSYS) {
958 		fc->no_create = 1;
959 		goto mknod;
960 	} else if (err == -EEXIST)
961 		fuse_invalidate_entry(entry);
962 	return err;
963 
964 mknod:
965 	err = fuse_mknod(idmap, dir, entry, mode, 0);
966 	if (err)
967 		return err;
968 	return finish_no_open(file, NULL);
969 }
970 
971 /*
972  * Code shared between mknod, mkdir, symlink and link
973  */
974 static struct dentry *create_new_entry(struct mnt_idmap *idmap, struct fuse_mount *fm,
975 				       struct fuse_args *args, struct inode *dir,
976 				       struct dentry *entry, umode_t mode)
977 {
978 	struct fuse_entry_out outarg;
979 	struct inode *inode;
980 	struct dentry *d;
981 	struct fuse_forget_link *forget;
982 	int epoch, err;
983 
984 	if (fuse_is_bad(dir))
985 		return ERR_PTR(-EIO);
986 
987 	epoch = atomic_read(&fm->fc->epoch);
988 
989 	forget = fuse_alloc_forget();
990 	if (!forget)
991 		return ERR_PTR(-ENOMEM);
992 
993 	memset(&outarg, 0, sizeof(outarg));
994 	args->nodeid = get_node_id(dir);
995 	args->out_numargs = 1;
996 	args->out_args[0].size = sizeof(outarg);
997 	args->out_args[0].value = &outarg;
998 
999 	if (args->opcode != FUSE_LINK) {
1000 		err = get_create_ext(idmap, args, dir, entry, mode);
1001 		if (err)
1002 			goto out_put_forget_req;
1003 	}
1004 
1005 	err = fuse_simple_idmap_request(idmap, fm, args);
1006 	free_ext_value(args);
1007 	if (err)
1008 		goto out_put_forget_req;
1009 
1010 	err = -EIO;
1011 	if (invalid_nodeid(outarg.nodeid) || fuse_invalid_attr(&outarg.attr))
1012 		goto out_put_forget_req;
1013 
1014 	if ((outarg.attr.mode ^ mode) & S_IFMT)
1015 		goto out_put_forget_req;
1016 
1017 	inode = fuse_iget(dir->i_sb, outarg.nodeid, outarg.generation,
1018 			  &outarg.attr, ATTR_TIMEOUT(&outarg), 0, 0);
1019 	if (!inode) {
1020 		fuse_chan_queue_forget(fm->fc->chan, forget, outarg.nodeid, 1);
1021 		return ERR_PTR(-ENOMEM);
1022 	}
1023 	kfree(forget);
1024 
1025 	d_drop(entry);
1026 	d = d_splice_alias(inode, entry);
1027 	if (IS_ERR(d))
1028 		return d;
1029 
1030 	if (d) {
1031 		d->d_time = epoch;
1032 		fuse_change_entry_timeout(d, &outarg);
1033 	} else {
1034 		entry->d_time = epoch;
1035 		fuse_change_entry_timeout(entry, &outarg);
1036 	}
1037 	fuse_dir_changed(dir);
1038 	return d;
1039 
1040  out_put_forget_req:
1041 	if (err == -EEXIST)
1042 		fuse_invalidate_entry(entry);
1043 	kfree(forget);
1044 	return ERR_PTR(err);
1045 }
1046 
1047 static int create_new_nondir(struct mnt_idmap *idmap, struct fuse_mount *fm,
1048 			     struct fuse_args *args, struct inode *dir,
1049 			     struct dentry *entry, umode_t mode)
1050 {
1051 	/*
1052 	 * Note that when creating anything other than a directory we
1053 	 * can be sure create_new_entry() will NOT return an alternate
1054 	 * dentry as d_splice_alias() only returns an alternate dentry
1055 	 * for directories.  So we don't need to check for that case
1056 	 * when passing back the result.
1057 	 */
1058 	WARN_ON_ONCE(S_ISDIR(mode));
1059 
1060 	return PTR_ERR(create_new_entry(idmap, fm, args, dir, entry, mode));
1061 }
1062 
1063 static int fuse_mknod(struct mnt_idmap *idmap, struct inode *dir,
1064 		      struct dentry *entry, umode_t mode, dev_t rdev)
1065 {
1066 	struct fuse_mknod_in inarg;
1067 	struct fuse_mount *fm = get_fuse_mount(dir);
1068 	FUSE_ARGS(args);
1069 
1070 	if (!fm->fc->dont_mask)
1071 		mode &= ~current_umask();
1072 
1073 	memset(&inarg, 0, sizeof(inarg));
1074 	inarg.mode = mode;
1075 	inarg.rdev = new_encode_dev(rdev);
1076 	inarg.umask = current_umask();
1077 	args.opcode = FUSE_MKNOD;
1078 	args.in_numargs = 2;
1079 	args.in_args[0].size = sizeof(inarg);
1080 	args.in_args[0].value = &inarg;
1081 	args.in_args[1].size = entry->d_name.len + 1;
1082 	args.in_args[1].value = entry->d_name.name;
1083 	return create_new_nondir(idmap, fm, &args, dir, entry, mode);
1084 }
1085 
1086 static int fuse_create(struct mnt_idmap *idmap, struct inode *dir,
1087 		       struct dentry *entry, umode_t mode)
1088 {
1089 	return fuse_mknod(idmap, dir, entry, mode, 0);
1090 }
1091 
1092 static int fuse_tmpfile(struct mnt_idmap *idmap, struct inode *dir,
1093 			struct file *file, umode_t mode)
1094 {
1095 	struct fuse_conn *fc = get_fuse_conn(dir);
1096 	int err;
1097 
1098 	if (fc->no_tmpfile)
1099 		return -EOPNOTSUPP;
1100 
1101 	err = fuse_create_open(idmap, dir, file->f_path.dentry, file,
1102 			       file->f_flags, mode, FUSE_TMPFILE);
1103 	if (err == -ENOSYS) {
1104 		fc->no_tmpfile = 1;
1105 		err = -EOPNOTSUPP;
1106 	}
1107 	return err;
1108 }
1109 
1110 static struct dentry *fuse_mkdir(struct mnt_idmap *idmap, struct inode *dir,
1111 				 struct dentry *entry, umode_t mode)
1112 {
1113 	struct fuse_mkdir_in inarg;
1114 	struct fuse_mount *fm = get_fuse_mount(dir);
1115 	FUSE_ARGS(args);
1116 
1117 	if (!fm->fc->dont_mask)
1118 		mode &= ~current_umask();
1119 
1120 	/*
1121 	 * vfs_mkdir() now passes S_IFDIR in @mode, but @mode is forwarded
1122 	 * verbatim to the userspace server which has only ever been given the
1123 	 * permission bits. Strip the type bit until the protocol is known to
1124 	 * cope with it.
1125 	 */
1126 	mode &= ~S_IFDIR;
1127 
1128 	memset(&inarg, 0, sizeof(inarg));
1129 	inarg.mode = mode;
1130 	inarg.umask = current_umask();
1131 	args.opcode = FUSE_MKDIR;
1132 	args.in_numargs = 2;
1133 	args.in_args[0].size = sizeof(inarg);
1134 	args.in_args[0].value = &inarg;
1135 	args.in_args[1].size = entry->d_name.len + 1;
1136 	args.in_args[1].value = entry->d_name.name;
1137 	return create_new_entry(idmap, fm, &args, dir, entry, S_IFDIR);
1138 }
1139 
1140 static int fuse_symlink(struct mnt_idmap *idmap, struct inode *dir,
1141 			struct dentry *entry, const char *link)
1142 {
1143 	struct fuse_mount *fm = get_fuse_mount(dir);
1144 	unsigned len = strlen(link) + 1;
1145 	FUSE_ARGS(args);
1146 
1147 	args.opcode = FUSE_SYMLINK;
1148 	args.in_numargs = 3;
1149 	fuse_set_zero_arg0(&args);
1150 	args.in_args[1].size = entry->d_name.len + 1;
1151 	args.in_args[1].value = entry->d_name.name;
1152 	args.in_args[2].size = len;
1153 	args.in_args[2].value = link;
1154 	return create_new_nondir(idmap, fm, &args, dir, entry, S_IFLNK);
1155 }
1156 
1157 void fuse_flush_time_update(struct inode *inode)
1158 {
1159 	int err = sync_inode_metadata(inode, 1);
1160 
1161 	mapping_set_error(inode->i_mapping, err);
1162 }
1163 
1164 static void fuse_update_ctime_in_cache(struct inode *inode)
1165 {
1166 	if (!IS_NOCMTIME(inode)) {
1167 		inode_set_ctime_current(inode);
1168 		mark_inode_dirty_sync(inode);
1169 		fuse_flush_time_update(inode);
1170 	}
1171 }
1172 
1173 void fuse_update_ctime(struct inode *inode)
1174 {
1175 	fuse_invalidate_attr_mask(inode, STATX_CTIME);
1176 	fuse_update_ctime_in_cache(inode);
1177 }
1178 
1179 static void fuse_entry_unlinked(struct dentry *entry)
1180 {
1181 	struct inode *inode = d_inode(entry);
1182 	struct fuse_conn *fc = get_fuse_conn(inode);
1183 	struct fuse_inode *fi = get_fuse_inode(inode);
1184 
1185 	spin_lock(&fi->lock);
1186 	fi->attr_version = atomic64_inc_return(&fc->attr_version);
1187 	/*
1188 	 * If i_nlink == 0 then unlink doesn't make sense, yet this can
1189 	 * happen if userspace filesystem is careless.  It would be
1190 	 * difficult to enforce correct nlink usage so just ignore this
1191 	 * condition here
1192 	 */
1193 	if (S_ISDIR(inode->i_mode))
1194 		clear_nlink(inode);
1195 	else if (inode->i_nlink > 0)
1196 		drop_nlink(inode);
1197 	spin_unlock(&fi->lock);
1198 	fuse_invalidate_entry_cache(entry);
1199 	fuse_update_ctime(inode);
1200 }
1201 
1202 static int fuse_unlink(struct inode *dir, struct dentry *entry)
1203 {
1204 	int err;
1205 	struct fuse_mount *fm = get_fuse_mount(dir);
1206 	FUSE_ARGS(args);
1207 
1208 	if (fuse_is_bad(dir))
1209 		return -EIO;
1210 
1211 	args.opcode = FUSE_UNLINK;
1212 	args.nodeid = get_node_id(dir);
1213 	args.in_numargs = 2;
1214 	fuse_set_zero_arg0(&args);
1215 	args.in_args[1].size = entry->d_name.len + 1;
1216 	args.in_args[1].value = entry->d_name.name;
1217 	err = fuse_simple_request(fm, &args);
1218 	if (!err) {
1219 		fuse_dir_changed(dir);
1220 		fuse_entry_unlinked(entry);
1221 	} else if (err == -EINTR || err == -ENOENT)
1222 		fuse_invalidate_entry(entry);
1223 	return err;
1224 }
1225 
1226 static int fuse_rmdir(struct inode *dir, struct dentry *entry)
1227 {
1228 	int err;
1229 	struct fuse_mount *fm = get_fuse_mount(dir);
1230 	FUSE_ARGS(args);
1231 
1232 	if (fuse_is_bad(dir))
1233 		return -EIO;
1234 
1235 	args.opcode = FUSE_RMDIR;
1236 	args.nodeid = get_node_id(dir);
1237 	args.in_numargs = 2;
1238 	fuse_set_zero_arg0(&args);
1239 	args.in_args[1].size = entry->d_name.len + 1;
1240 	args.in_args[1].value = entry->d_name.name;
1241 	err = fuse_simple_request(fm, &args);
1242 	if (!err) {
1243 		fuse_dir_changed(dir);
1244 		fuse_entry_unlinked(entry);
1245 	} else if (err == -EINTR || err == -ENOENT)
1246 		fuse_invalidate_entry(entry);
1247 	return err;
1248 }
1249 
1250 static int fuse_rename_common(struct mnt_idmap *idmap, struct inode *olddir, struct dentry *oldent,
1251 			      struct inode *newdir, struct dentry *newent,
1252 			      unsigned int flags, int opcode, size_t argsize)
1253 {
1254 	int err;
1255 	struct fuse_rename2_in inarg;
1256 	struct fuse_mount *fm = get_fuse_mount(olddir);
1257 	FUSE_ARGS(args);
1258 
1259 	memset(&inarg, 0, argsize);
1260 	inarg.newdir = get_node_id(newdir);
1261 	inarg.flags = flags;
1262 	args.opcode = opcode;
1263 	args.nodeid = get_node_id(olddir);
1264 	args.in_numargs = 3;
1265 	args.in_args[0].size = argsize;
1266 	args.in_args[0].value = &inarg;
1267 	args.in_args[1].size = oldent->d_name.len + 1;
1268 	args.in_args[1].value = oldent->d_name.name;
1269 	args.in_args[2].size = newent->d_name.len + 1;
1270 	args.in_args[2].value = newent->d_name.name;
1271 	err = fuse_simple_idmap_request(idmap, fm, &args);
1272 	if (!err) {
1273 		/* ctime changes */
1274 		fuse_update_ctime(d_inode(oldent));
1275 
1276 		if (flags & RENAME_EXCHANGE)
1277 			fuse_update_ctime(d_inode(newent));
1278 
1279 		fuse_dir_changed(olddir);
1280 		if (olddir != newdir)
1281 			fuse_dir_changed(newdir);
1282 
1283 		/* newent will end up negative */
1284 		if (!(flags & RENAME_EXCHANGE) && d_really_is_positive(newent))
1285 			fuse_entry_unlinked(newent);
1286 	} else if (err == -EINTR || err == -ENOENT) {
1287 		/* If request was interrupted, DEITY only knows if the
1288 		   rename actually took place.  If the invalidation
1289 		   fails (e.g. some process has CWD under the renamed
1290 		   directory), then there can be inconsistency between
1291 		   the dcache and the real filesystem.  Tough luck. */
1292 		fuse_invalidate_entry(oldent);
1293 		if (d_really_is_positive(newent))
1294 			fuse_invalidate_entry(newent);
1295 	}
1296 
1297 	return err;
1298 }
1299 
1300 static int fuse_rename2(struct mnt_idmap *idmap, struct inode *olddir,
1301 			struct dentry *oldent, struct inode *newdir,
1302 			struct dentry *newent, unsigned int flags)
1303 {
1304 	struct fuse_conn *fc = get_fuse_conn(olddir);
1305 	int err;
1306 
1307 	if (fuse_is_bad(olddir))
1308 		return -EIO;
1309 
1310 	if (flags & ~(RENAME_NOREPLACE | RENAME_EXCHANGE | RENAME_WHITEOUT))
1311 		return -EINVAL;
1312 
1313 	if (flags) {
1314 		if (fc->no_rename2 || fc->minor < 23)
1315 			return -EINVAL;
1316 
1317 		err = fuse_rename_common((flags & RENAME_WHITEOUT) ? idmap : &invalid_mnt_idmap,
1318 					 olddir, oldent, newdir, newent, flags,
1319 					 FUSE_RENAME2,
1320 					 sizeof(struct fuse_rename2_in));
1321 		if (err == -ENOSYS) {
1322 			fc->no_rename2 = 1;
1323 			err = -EINVAL;
1324 		}
1325 	} else {
1326 		err = fuse_rename_common(&invalid_mnt_idmap, olddir, oldent, newdir, newent, 0,
1327 					 FUSE_RENAME,
1328 					 sizeof(struct fuse_rename_in));
1329 	}
1330 
1331 	return err;
1332 }
1333 
1334 static int fuse_link(struct dentry *entry, struct inode *newdir,
1335 		     struct dentry *newent)
1336 {
1337 	int err;
1338 	struct fuse_link_in inarg;
1339 	struct inode *inode = d_inode(entry);
1340 	struct fuse_mount *fm = get_fuse_mount(inode);
1341 	FUSE_ARGS(args);
1342 
1343 	if (fm->fc->no_link)
1344 		goto out;
1345 
1346 	memset(&inarg, 0, sizeof(inarg));
1347 	inarg.oldnodeid = get_node_id(inode);
1348 	args.opcode = FUSE_LINK;
1349 	args.in_numargs = 2;
1350 	args.in_args[0].size = sizeof(inarg);
1351 	args.in_args[0].value = &inarg;
1352 	args.in_args[1].size = newent->d_name.len + 1;
1353 	args.in_args[1].value = newent->d_name.name;
1354 	err = create_new_nondir(&invalid_mnt_idmap, fm, &args, newdir, newent, inode->i_mode);
1355 	if (!err)
1356 		fuse_update_ctime_in_cache(inode);
1357 	else if (err == -EINTR)
1358 		fuse_invalidate_attr(inode);
1359 
1360 	if (err == -ENOSYS)
1361 		fm->fc->no_link = 1;
1362 out:
1363 	if (fm->fc->no_link)
1364 		return -EPERM;
1365 
1366 	return err;
1367 }
1368 
1369 static void fuse_fillattr(struct mnt_idmap *idmap, struct inode *inode,
1370 			  struct fuse_attr *attr, struct kstat *stat)
1371 {
1372 	unsigned int blkbits;
1373 	struct fuse_conn *fc = get_fuse_conn(inode);
1374 	vfsuid_t vfsuid = make_vfsuid(idmap, fc->user_ns,
1375 				      make_kuid(fc->user_ns, attr->uid));
1376 	vfsgid_t vfsgid = make_vfsgid(idmap, fc->user_ns,
1377 				      make_kgid(fc->user_ns, attr->gid));
1378 
1379 	stat->dev = inode->i_sb->s_dev;
1380 	stat->ino = attr->ino;
1381 	stat->mode = (inode->i_mode & S_IFMT) | (attr->mode & 07777);
1382 	stat->nlink = attr->nlink;
1383 	stat->uid = vfsuid_into_kuid(vfsuid);
1384 	stat->gid = vfsgid_into_kgid(vfsgid);
1385 	stat->rdev = inode->i_rdev;
1386 	stat->atime.tv_sec = attr->atime;
1387 	stat->atime.tv_nsec = attr->atimensec;
1388 	stat->mtime.tv_sec = attr->mtime;
1389 	stat->mtime.tv_nsec = attr->mtimensec;
1390 	stat->ctime.tv_sec = attr->ctime;
1391 	stat->ctime.tv_nsec = attr->ctimensec;
1392 	stat->size = attr->size;
1393 	stat->blocks = attr->blocks;
1394 
1395 	if (attr->blksize != 0)
1396 		blkbits = ilog2(attr->blksize);
1397 	else
1398 		blkbits = inode->i_sb->s_blocksize_bits;
1399 
1400 	stat->blksize = 1 << blkbits;
1401 }
1402 
1403 static void fuse_statx_to_attr(struct fuse_statx *sx, struct fuse_attr *attr)
1404 {
1405 	memset(attr, 0, sizeof(*attr));
1406 	attr->ino = sx->ino;
1407 	attr->size = sx->size;
1408 	attr->blocks = sx->blocks;
1409 	attr->atime = sx->atime.tv_sec;
1410 	attr->mtime = sx->mtime.tv_sec;
1411 	attr->ctime = sx->ctime.tv_sec;
1412 	attr->atimensec = sx->atime.tv_nsec;
1413 	attr->mtimensec = sx->mtime.tv_nsec;
1414 	attr->ctimensec = sx->ctime.tv_nsec;
1415 	attr->mode = sx->mode;
1416 	attr->nlink = sx->nlink;
1417 	attr->uid = sx->uid;
1418 	attr->gid = sx->gid;
1419 	attr->rdev = new_encode_dev(MKDEV(sx->rdev_major, sx->rdev_minor));
1420 	attr->blksize = sx->blksize;
1421 }
1422 
1423 static int fuse_do_statx(struct mnt_idmap *idmap, struct inode *inode,
1424 			 struct file *file, struct kstat *stat)
1425 {
1426 	int err;
1427 	struct fuse_attr attr;
1428 	struct fuse_statx *sx;
1429 	struct fuse_statx_in inarg;
1430 	struct fuse_statx_out outarg;
1431 	struct fuse_mount *fm = get_fuse_mount(inode);
1432 	u64 attr_version = fuse_get_attr_version(fm->fc);
1433 	FUSE_ARGS(args);
1434 
1435 	memset(&inarg, 0, sizeof(inarg));
1436 	memset(&outarg, 0, sizeof(outarg));
1437 	/* Directories have separate file-handle space */
1438 	if (file && S_ISREG(inode->i_mode)) {
1439 		struct fuse_file *ff = file->private_data;
1440 
1441 		inarg.getattr_flags |= FUSE_GETATTR_FH;
1442 		inarg.fh = ff->fh;
1443 	}
1444 	/* For now leave sync hints as the default, request all stats. */
1445 	inarg.sx_flags = 0;
1446 	inarg.sx_mask = STATX_BASIC_STATS | STATX_BTIME;
1447 	args.opcode = FUSE_STATX;
1448 	args.nodeid = get_node_id(inode);
1449 	args.in_numargs = 1;
1450 	args.in_args[0].size = sizeof(inarg);
1451 	args.in_args[0].value = &inarg;
1452 	args.out_numargs = 1;
1453 	args.out_args[0].size = sizeof(outarg);
1454 	args.out_args[0].value = &outarg;
1455 	err = fuse_simple_request(fm, &args);
1456 	if (err)
1457 		return err;
1458 
1459 	sx = &outarg.stat;
1460 	if (((sx->mask & STATX_SIZE) && !fuse_valid_size(sx->size)) ||
1461 	    ((sx->mask & STATX_TYPE) && (!fuse_valid_type(sx->mode) ||
1462 					 inode_wrong_type(inode, sx->mode)))) {
1463 		fuse_make_bad(inode);
1464 		return -EIO;
1465 	}
1466 
1467 	fuse_statx_to_attr(&outarg.stat, &attr);
1468 	if ((sx->mask & STATX_BASIC_STATS) == STATX_BASIC_STATS) {
1469 		fuse_change_attributes(inode, &attr, &outarg.stat,
1470 				       ATTR_TIMEOUT(&outarg), attr_version);
1471 	}
1472 
1473 	if (stat) {
1474 		stat->result_mask = sx->mask & (STATX_BASIC_STATS | STATX_BTIME);
1475 		stat->btime.tv_sec = sx->btime.tv_sec;
1476 		stat->btime.tv_nsec = min_t(u32, sx->btime.tv_nsec, NSEC_PER_SEC - 1);
1477 		fuse_fillattr(idmap, inode, &attr, stat);
1478 		stat->result_mask |= STATX_TYPE;
1479 	}
1480 
1481 	return 0;
1482 }
1483 
1484 static int fuse_do_getattr(struct mnt_idmap *idmap, struct inode *inode,
1485 			   struct kstat *stat, struct file *file)
1486 {
1487 	int err;
1488 	struct fuse_getattr_in inarg;
1489 	struct fuse_attr_out outarg;
1490 	struct fuse_mount *fm = get_fuse_mount(inode);
1491 	FUSE_ARGS(args);
1492 	u64 attr_version;
1493 
1494 	attr_version = fuse_get_attr_version(fm->fc);
1495 
1496 	memset(&inarg, 0, sizeof(inarg));
1497 	memset(&outarg, 0, sizeof(outarg));
1498 	/* Directories have separate file-handle space */
1499 	if (file && S_ISREG(inode->i_mode)) {
1500 		struct fuse_file *ff = file->private_data;
1501 
1502 		inarg.getattr_flags |= FUSE_GETATTR_FH;
1503 		inarg.fh = ff->fh;
1504 	}
1505 	args.opcode = FUSE_GETATTR;
1506 	args.nodeid = get_node_id(inode);
1507 	args.in_numargs = 1;
1508 	args.in_args[0].size = sizeof(inarg);
1509 	args.in_args[0].value = &inarg;
1510 	args.out_numargs = 1;
1511 	args.out_args[0].size = sizeof(outarg);
1512 	args.out_args[0].value = &outarg;
1513 	err = fuse_simple_request(fm, &args);
1514 	if (!err) {
1515 		if (fuse_invalid_attr(&outarg.attr) ||
1516 		    inode_wrong_type(inode, outarg.attr.mode)) {
1517 			fuse_make_bad(inode);
1518 			err = -EIO;
1519 		} else {
1520 			fuse_change_attributes(inode, &outarg.attr, NULL,
1521 					       ATTR_TIMEOUT(&outarg),
1522 					       attr_version);
1523 			if (stat)
1524 				fuse_fillattr(idmap, inode, &outarg.attr, stat);
1525 		}
1526 	}
1527 	return err;
1528 }
1529 
1530 static int fuse_update_get_attr(struct mnt_idmap *idmap, struct inode *inode,
1531 				struct file *file, struct kstat *stat,
1532 				u32 request_mask, unsigned int flags)
1533 {
1534 	struct fuse_inode *fi = get_fuse_inode(inode);
1535 	struct fuse_conn *fc = get_fuse_conn(inode);
1536 	int err = 0;
1537 	bool sync;
1538 	u32 inval_mask = READ_ONCE(fi->inval_mask);
1539 	u32 cache_mask = fuse_get_cache_mask(inode);
1540 
1541 
1542 	/* FUSE only supports basic stats and possibly btime */
1543 	request_mask &= STATX_BASIC_STATS | STATX_BTIME;
1544 retry:
1545 	if (fc->no_statx)
1546 		request_mask &= STATX_BASIC_STATS;
1547 
1548 	if (!request_mask)
1549 		sync = false;
1550 	else if (flags & AT_STATX_FORCE_SYNC)
1551 		sync = true;
1552 	else if (flags & AT_STATX_DONT_SYNC)
1553 		sync = false;
1554 	else if (request_mask & inval_mask & ~cache_mask)
1555 		sync = true;
1556 	else
1557 		sync = time_before64(fi->i_time, get_jiffies_64());
1558 
1559 	if (sync) {
1560 		forget_all_cached_acls(inode);
1561 		/* Try statx if BTIME is requested */
1562 		if (!fc->no_statx && (request_mask & ~STATX_BASIC_STATS)) {
1563 			err = fuse_do_statx(idmap, inode, file, stat);
1564 			if (err == -ENOSYS) {
1565 				fc->no_statx = 1;
1566 				err = 0;
1567 				goto retry;
1568 			}
1569 		} else {
1570 			err = fuse_do_getattr(idmap, inode, stat, file);
1571 		}
1572 	} else if (stat) {
1573 		generic_fillattr(idmap, request_mask, inode, stat);
1574 		stat->mode = fi->orig_i_mode;
1575 		stat->ino = fi->orig_ino;
1576 		stat->blksize = 1 << fi->cached_i_blkbits;
1577 		if (test_bit(FUSE_I_BTIME, &fi->state)) {
1578 			stat->btime = fi->i_btime;
1579 			stat->result_mask |= STATX_BTIME;
1580 		}
1581 	}
1582 
1583 	return err;
1584 }
1585 
1586 int fuse_update_attributes(struct inode *inode, struct file *file, u32 mask)
1587 {
1588 	return fuse_update_get_attr(&nop_mnt_idmap, inode, file, NULL, mask, 0);
1589 }
1590 
1591 int fuse_reverse_inval_entry(struct fuse_conn *fc, u64 parent_nodeid,
1592 			     u64 child_nodeid, struct qstr *name, u32 flags)
1593 {
1594 	int err = -ENOTDIR;
1595 	struct inode *parent;
1596 	struct dentry *dir;
1597 	struct dentry *entry;
1598 
1599 	parent = fuse_ilookup(fc, parent_nodeid, NULL);
1600 	if (!parent)
1601 		return -ENOENT;
1602 
1603 	inode_lock_nested(parent, I_MUTEX_PARENT);
1604 	if (!S_ISDIR(parent->i_mode))
1605 		goto unlock;
1606 
1607 	err = -ENOENT;
1608 	dir = d_find_alias(parent);
1609 	if (!dir)
1610 		goto unlock;
1611 
1612 	name->hash = full_name_hash(dir, name->name, name->len);
1613 	entry = d_lookup(dir, name);
1614 	dput(dir);
1615 	if (!entry)
1616 		goto unlock;
1617 
1618 	fuse_dir_changed(parent);
1619 	if (!(flags & FUSE_EXPIRE_ONLY))
1620 		d_invalidate(entry);
1621 	fuse_invalidate_entry_cache(entry);
1622 
1623 	if (child_nodeid != 0 && d_really_is_positive(entry)) {
1624 		inode_lock(d_inode(entry));
1625 		if (get_node_id(d_inode(entry)) != child_nodeid) {
1626 			err = -ENOENT;
1627 			goto badentry;
1628 		}
1629 		if (d_mountpoint(entry)) {
1630 			err = -EBUSY;
1631 			goto badentry;
1632 		}
1633 		if (d_is_dir(entry)) {
1634 			shrink_dcache_parent(entry);
1635 			if (!simple_empty(entry)) {
1636 				err = -ENOTEMPTY;
1637 				goto badentry;
1638 			}
1639 			d_inode(entry)->i_flags |= S_DEAD;
1640 		}
1641 		dont_mount(entry);
1642 		clear_nlink(d_inode(entry));
1643 		err = 0;
1644  badentry:
1645 		inode_unlock(d_inode(entry));
1646 		if (!err)
1647 			d_delete(entry);
1648 	} else {
1649 		err = 0;
1650 	}
1651 	dput(entry);
1652 
1653  unlock:
1654 	inode_unlock(parent);
1655 	iput(parent);
1656 	return err;
1657 }
1658 
1659 static inline bool fuse_permissible_uidgid(struct fuse_conn *fc)
1660 {
1661 	const struct cred *cred = current_cred();
1662 
1663 	return (uid_eq(cred->euid, fc->user_id) &&
1664 		uid_eq(cred->suid, fc->user_id) &&
1665 		uid_eq(cred->uid,  fc->user_id) &&
1666 		gid_eq(cred->egid, fc->group_id) &&
1667 		gid_eq(cred->sgid, fc->group_id) &&
1668 		gid_eq(cred->gid,  fc->group_id));
1669 }
1670 
1671 /*
1672  * Calling into a user-controlled filesystem gives the filesystem
1673  * daemon ptrace-like capabilities over the current process.  This
1674  * means, that the filesystem daemon is able to record the exact
1675  * filesystem operations performed, and can also control the behavior
1676  * of the requester process in otherwise impossible ways.  For example
1677  * it can delay the operation for arbitrary length of time allowing
1678  * DoS against the requester.
1679  *
1680  * For this reason only those processes can call into the filesystem,
1681  * for which the owner of the mount has ptrace privilege.  This
1682  * excludes processes started by other users, suid or sgid processes.
1683  */
1684 bool fuse_allow_current_process(struct fuse_conn *fc)
1685 {
1686 	bool allow;
1687 
1688 	if (fc->allow_other)
1689 		allow = current_in_userns(fc->user_ns);
1690 	else
1691 		allow = fuse_permissible_uidgid(fc);
1692 
1693 	if (!allow && allow_sys_admin_access && capable(CAP_SYS_ADMIN))
1694 		allow = true;
1695 
1696 	return allow;
1697 }
1698 
1699 static int fuse_access(struct inode *inode, int mask)
1700 {
1701 	struct fuse_mount *fm = get_fuse_mount(inode);
1702 	FUSE_ARGS(args);
1703 	struct fuse_access_in inarg;
1704 	int err;
1705 
1706 	BUG_ON(mask & MAY_NOT_BLOCK);
1707 
1708 	/*
1709 	 * We should not send FUSE_ACCESS to the userspace
1710 	 * when idmapped mounts are enabled as for this case
1711 	 * we have fc->default_permissions = 1 and access
1712 	 * permission checks are done on the kernel side.
1713 	 */
1714 	WARN_ON_ONCE(!(fm->sb->s_iflags & SB_I_NOIDMAP));
1715 
1716 	if (fm->fc->no_access)
1717 		return 0;
1718 
1719 	memset(&inarg, 0, sizeof(inarg));
1720 	inarg.mask = mask & (MAY_READ | MAY_WRITE | MAY_EXEC);
1721 	args.opcode = FUSE_ACCESS;
1722 	args.nodeid = get_node_id(inode);
1723 	args.in_numargs = 1;
1724 	args.in_args[0].size = sizeof(inarg);
1725 	args.in_args[0].value = &inarg;
1726 	err = fuse_simple_request(fm, &args);
1727 	if (err == -ENOSYS) {
1728 		fm->fc->no_access = 1;
1729 		err = 0;
1730 	}
1731 	return err;
1732 }
1733 
1734 static int fuse_perm_getattr(struct inode *inode, int mask)
1735 {
1736 	if (mask & MAY_NOT_BLOCK)
1737 		return -ECHILD;
1738 
1739 	forget_all_cached_acls(inode);
1740 	return fuse_do_getattr(&nop_mnt_idmap, inode, NULL, NULL);
1741 }
1742 
1743 /*
1744  * Check permission.  The two basic access models of FUSE are:
1745  *
1746  * 1) Local access checking ('default_permissions' mount option) based
1747  * on file mode.  This is the plain old disk filesystem permission
1748  * model.
1749  *
1750  * 2) "Remote" access checking, where server is responsible for
1751  * checking permission in each inode operation.  An exception to this
1752  * is if ->permission() was invoked from sys_access() in which case an
1753  * access request is sent.  Execute permission is still checked
1754  * locally based on file mode.
1755  */
1756 static int fuse_permission(struct mnt_idmap *idmap,
1757 			   struct inode *inode, int mask)
1758 {
1759 	struct fuse_conn *fc = get_fuse_conn(inode);
1760 	bool refreshed = false;
1761 	int err = 0;
1762 
1763 	if (fuse_is_bad(inode))
1764 		return -EIO;
1765 
1766 	if (!fuse_allow_current_process(fc))
1767 		return -EACCES;
1768 
1769 	/*
1770 	 * If attributes are needed, refresh them before proceeding
1771 	 */
1772 	if (fc->default_permissions ||
1773 	    ((mask & MAY_EXEC) && S_ISREG(inode->i_mode))) {
1774 		struct fuse_inode *fi = get_fuse_inode(inode);
1775 		u32 perm_mask = STATX_MODE | STATX_UID | STATX_GID;
1776 
1777 		if (perm_mask & READ_ONCE(fi->inval_mask) ||
1778 		    time_before64(fi->i_time, get_jiffies_64())) {
1779 			refreshed = true;
1780 
1781 			err = fuse_perm_getattr(inode, mask);
1782 			if (err)
1783 				return err;
1784 		}
1785 	}
1786 
1787 	if (fc->default_permissions) {
1788 		err = generic_permission(idmap, inode, mask);
1789 
1790 		/* If permission is denied, try to refresh file
1791 		   attributes.  This is also needed, because the root
1792 		   node will at first have no permissions */
1793 		if (err == -EACCES && !refreshed) {
1794 			err = fuse_perm_getattr(inode, mask);
1795 			if (!err)
1796 				err = generic_permission(idmap,
1797 							 inode, mask);
1798 		}
1799 
1800 		/* Note: the opposite of the above test does not
1801 		   exist.  So if permissions are revoked this won't be
1802 		   noticed immediately, only after the attribute
1803 		   timeout has expired */
1804 	} else if (mask & (MAY_ACCESS | MAY_CHDIR)) {
1805 		err = fuse_access(inode, mask);
1806 	} else if ((mask & MAY_EXEC) && S_ISREG(inode->i_mode)) {
1807 		if (!(inode->i_mode & S_IXUGO)) {
1808 			if (refreshed)
1809 				return -EACCES;
1810 
1811 			err = fuse_perm_getattr(inode, mask);
1812 			if (!err && !(inode->i_mode & S_IXUGO))
1813 				return -EACCES;
1814 		}
1815 	}
1816 	return err;
1817 }
1818 
1819 static int fuse_readlink_folio(struct inode *inode, struct folio *folio)
1820 {
1821 	struct fuse_mount *fm = get_fuse_mount(inode);
1822 	struct fuse_folio_desc desc = { .length = folio_size(folio) - 1 };
1823 	struct fuse_args_pages ap = {
1824 		.num_folios = 1,
1825 		.folios = &folio,
1826 		.descs = &desc,
1827 	};
1828 	char *link;
1829 	ssize_t res;
1830 
1831 	ap.args.opcode = FUSE_READLINK;
1832 	ap.args.nodeid = get_node_id(inode);
1833 	ap.args.out_pages = true;
1834 	ap.args.out_argvar = true;
1835 	ap.args.page_zeroing = true;
1836 	ap.args.out_numargs = 1;
1837 	ap.args.out_args[0].size = desc.length;
1838 	res = fuse_simple_request(fm, &ap.args);
1839 
1840 	fuse_invalidate_atime(inode);
1841 
1842 	if (res < 0)
1843 		return res;
1844 
1845 	if (WARN_ON(res >= PAGE_SIZE))
1846 		return -EIO;
1847 
1848 	link = folio_address(folio);
1849 	link[res] = '\0';
1850 
1851 	return 0;
1852 }
1853 
1854 static const char *fuse_get_link(struct dentry *dentry, struct inode *inode,
1855 				 struct delayed_call *callback)
1856 {
1857 	struct fuse_conn *fc = get_fuse_conn(inode);
1858 	struct folio *folio;
1859 	int err;
1860 
1861 	err = -EIO;
1862 	if (fuse_is_bad(inode))
1863 		goto out_err;
1864 
1865 	if (fc->cache_symlinks)
1866 		return page_get_link_raw(dentry, inode, callback);
1867 
1868 	err = -ECHILD;
1869 	if (!dentry)
1870 		goto out_err;
1871 
1872 	folio = folio_alloc(GFP_KERNEL, 0);
1873 	err = -ENOMEM;
1874 	if (!folio)
1875 		goto out_err;
1876 
1877 	err = fuse_readlink_folio(inode, folio);
1878 	if (err) {
1879 		folio_put(folio);
1880 		goto out_err;
1881 	}
1882 
1883 	set_delayed_call(callback, page_put_link, folio);
1884 
1885 	return folio_address(folio);
1886 
1887 out_err:
1888 	return ERR_PTR(err);
1889 }
1890 
1891 static int fuse_dir_open(struct inode *inode, struct file *file)
1892 {
1893 	struct fuse_mount *fm = get_fuse_mount(inode);
1894 	int err;
1895 
1896 	if (fuse_is_bad(inode))
1897 		return -EIO;
1898 
1899 	err = generic_file_open(inode, file);
1900 	if (err)
1901 		return err;
1902 
1903 	err = fuse_do_open(fm, get_node_id(inode), file, true);
1904 	if (!err) {
1905 		struct fuse_file *ff = file->private_data;
1906 
1907 		/*
1908 		 * Keep handling FOPEN_STREAM and FOPEN_NONSEEKABLE for
1909 		 * directories for backward compatibility, though it's unlikely
1910 		 * to be useful.
1911 		 */
1912 		if (ff->open_flags & (FOPEN_STREAM | FOPEN_NONSEEKABLE))
1913 			nonseekable_open(inode, file);
1914 		if (!(ff->open_flags & FOPEN_KEEP_CACHE))
1915 			invalidate_inode_pages2(inode->i_mapping);
1916 	}
1917 
1918 	return err;
1919 }
1920 
1921 static int fuse_dir_release(struct inode *inode, struct file *file)
1922 {
1923 	fuse_release_common(file, true);
1924 
1925 	return 0;
1926 }
1927 
1928 static int fuse_dir_fsync(struct file *file, loff_t start, loff_t end,
1929 			  int datasync)
1930 {
1931 	struct inode *inode = file->f_mapping->host;
1932 	struct fuse_conn *fc = get_fuse_conn(inode);
1933 	int err;
1934 
1935 	if (fuse_is_bad(inode))
1936 		return -EIO;
1937 
1938 	if (fc->no_fsyncdir)
1939 		return 0;
1940 
1941 	inode_lock(inode);
1942 	err = fuse_fsync_common(file, start, end, datasync, FUSE_FSYNCDIR);
1943 	if (err == -ENOSYS) {
1944 		fc->no_fsyncdir = 1;
1945 		err = 0;
1946 	}
1947 	inode_unlock(inode);
1948 
1949 	return err;
1950 }
1951 
1952 static long fuse_dir_ioctl(struct file *file, unsigned int cmd,
1953 			    unsigned long arg)
1954 {
1955 	struct fuse_conn *fc = get_fuse_conn(file->f_mapping->host);
1956 
1957 	/* FUSE_IOCTL_DIR only supported for API version >= 7.18 */
1958 	if (fc->minor < 18)
1959 		return -ENOTTY;
1960 
1961 	return fuse_ioctl_common(file, cmd, arg, FUSE_IOCTL_DIR);
1962 }
1963 
1964 static long fuse_dir_compat_ioctl(struct file *file, unsigned int cmd,
1965 				   unsigned long arg)
1966 {
1967 	struct fuse_conn *fc = get_fuse_conn(file->f_mapping->host);
1968 
1969 	if (fc->minor < 18)
1970 		return -ENOTTY;
1971 
1972 	return fuse_ioctl_common(file, cmd, arg,
1973 				 FUSE_IOCTL_COMPAT | FUSE_IOCTL_DIR);
1974 }
1975 
1976 static bool update_mtime(unsigned ivalid, bool trust_local_mtime)
1977 {
1978 	/* Always update if mtime is explicitly set  */
1979 	if (ivalid & ATTR_MTIME_SET)
1980 		return true;
1981 
1982 	/* Or if kernel i_mtime is the official one */
1983 	if (trust_local_mtime)
1984 		return true;
1985 
1986 	/* If it's an open(O_TRUNC) or an ftruncate(), don't update */
1987 	if ((ivalid & ATTR_SIZE) && (ivalid & (ATTR_OPEN | ATTR_FILE)))
1988 		return false;
1989 
1990 	/* In all other cases update */
1991 	return true;
1992 }
1993 
1994 static void iattr_to_fattr(struct mnt_idmap *idmap, struct fuse_conn *fc,
1995 			   struct iattr *iattr, struct fuse_setattr_in *arg,
1996 			   bool trust_local_cmtime)
1997 {
1998 	unsigned ivalid = iattr->ia_valid;
1999 
2000 	if (ivalid & ATTR_MODE)
2001 		arg->valid |= FATTR_MODE,   arg->mode = iattr->ia_mode;
2002 
2003 	if (ivalid & ATTR_UID) {
2004 		kuid_t fsuid = from_vfsuid(idmap, fc->user_ns, iattr->ia_vfsuid);
2005 
2006 		arg->valid |= FATTR_UID;
2007 		arg->uid = from_kuid(fc->user_ns, fsuid);
2008 	}
2009 
2010 	if (ivalid & ATTR_GID) {
2011 		kgid_t fsgid = from_vfsgid(idmap, fc->user_ns, iattr->ia_vfsgid);
2012 
2013 		arg->valid |= FATTR_GID;
2014 		arg->gid = from_kgid(fc->user_ns, fsgid);
2015 	}
2016 
2017 	if (ivalid & ATTR_SIZE)
2018 		arg->valid |= FATTR_SIZE,   arg->size = iattr->ia_size;
2019 	if (ivalid & ATTR_ATIME) {
2020 		arg->valid |= FATTR_ATIME;
2021 		arg->atime = iattr->ia_atime.tv_sec;
2022 		arg->atimensec = iattr->ia_atime.tv_nsec;
2023 		if (!(ivalid & ATTR_ATIME_SET))
2024 			arg->valid |= FATTR_ATIME_NOW;
2025 	}
2026 	if ((ivalid & ATTR_MTIME) && update_mtime(ivalid, trust_local_cmtime)) {
2027 		arg->valid |= FATTR_MTIME;
2028 		arg->mtime = iattr->ia_mtime.tv_sec;
2029 		arg->mtimensec = iattr->ia_mtime.tv_nsec;
2030 		if (!(ivalid & ATTR_MTIME_SET) && !trust_local_cmtime)
2031 			arg->valid |= FATTR_MTIME_NOW;
2032 	}
2033 	if ((ivalid & ATTR_CTIME) && trust_local_cmtime) {
2034 		arg->valid |= FATTR_CTIME;
2035 		arg->ctime = iattr->ia_ctime.tv_sec;
2036 		arg->ctimensec = iattr->ia_ctime.tv_nsec;
2037 	}
2038 }
2039 
2040 /*
2041  * Prevent concurrent writepages on inode
2042  *
2043  * This is done by adding a negative bias to the inode write counter
2044  * and waiting for all pending writes to finish.
2045  */
2046 void fuse_set_nowrite(struct inode *inode)
2047 {
2048 	struct fuse_inode *fi = get_fuse_inode(inode);
2049 
2050 	BUG_ON(!inode_is_locked(inode));
2051 
2052 	spin_lock(&fi->lock);
2053 	BUG_ON(fi->writectr < 0);
2054 	fi->writectr += FUSE_NOWRITE;
2055 	spin_unlock(&fi->lock);
2056 	wait_event(fi->page_waitq, fi->writectr == FUSE_NOWRITE);
2057 }
2058 
2059 /*
2060  * Allow writepages on inode
2061  *
2062  * Remove the bias from the writecounter and send any queued
2063  * writepages.
2064  */
2065 static void __fuse_release_nowrite(struct inode *inode)
2066 {
2067 	struct fuse_inode *fi = get_fuse_inode(inode);
2068 
2069 	BUG_ON(fi->writectr != FUSE_NOWRITE);
2070 	fi->writectr = 0;
2071 	fuse_flush_writepages(inode);
2072 }
2073 
2074 void fuse_release_nowrite(struct inode *inode)
2075 {
2076 	struct fuse_inode *fi = get_fuse_inode(inode);
2077 
2078 	spin_lock(&fi->lock);
2079 	__fuse_release_nowrite(inode);
2080 	spin_unlock(&fi->lock);
2081 }
2082 
2083 static void fuse_setattr_fill(struct fuse_conn *fc, struct fuse_args *args,
2084 			      struct inode *inode,
2085 			      struct fuse_setattr_in *inarg_p,
2086 			      struct fuse_attr_out *outarg_p)
2087 {
2088 	args->opcode = FUSE_SETATTR;
2089 	args->nodeid = get_node_id(inode);
2090 	args->in_numargs = 1;
2091 	args->in_args[0].size = sizeof(*inarg_p);
2092 	args->in_args[0].value = inarg_p;
2093 	args->out_numargs = 1;
2094 	args->out_args[0].size = sizeof(*outarg_p);
2095 	args->out_args[0].value = outarg_p;
2096 }
2097 
2098 /*
2099  * Flush inode->i_mtime to the server
2100  */
2101 int fuse_flush_times(struct inode *inode, struct fuse_file *ff)
2102 {
2103 	struct fuse_mount *fm = get_fuse_mount(inode);
2104 	FUSE_ARGS(args);
2105 	struct fuse_setattr_in inarg;
2106 	struct fuse_attr_out outarg;
2107 
2108 	memset(&inarg, 0, sizeof(inarg));
2109 	memset(&outarg, 0, sizeof(outarg));
2110 
2111 	inarg.valid = FATTR_MTIME;
2112 	inarg.mtime = inode_get_mtime_sec(inode);
2113 	inarg.mtimensec = inode_get_mtime_nsec(inode);
2114 	if (fm->fc->minor >= 23) {
2115 		inarg.valid |= FATTR_CTIME;
2116 		inarg.ctime = inode_get_ctime_sec(inode);
2117 		inarg.ctimensec = inode_get_ctime_nsec(inode);
2118 	}
2119 	if (ff) {
2120 		inarg.valid |= FATTR_FH;
2121 		inarg.fh = ff->fh;
2122 	}
2123 	fuse_setattr_fill(fm->fc, &args, inode, &inarg, &outarg);
2124 
2125 	return fuse_simple_request(fm, &args);
2126 }
2127 
2128 /*
2129  * Set attributes, and at the same time refresh them.
2130  *
2131  * Truncation is slightly complicated, because the 'truncate' request
2132  * may fail, in which case we don't want to touch the mapping.
2133  * vmtruncate() doesn't allow for this case, so do the rlimit checking
2134  * and the actual truncation by hand.
2135  */
2136 int fuse_do_setattr(struct mnt_idmap *idmap, struct dentry *dentry,
2137 		    struct iattr *attr, struct file *file)
2138 {
2139 	struct inode *inode = d_inode(dentry);
2140 	struct fuse_mount *fm = get_fuse_mount(inode);
2141 	struct fuse_conn *fc = fm->fc;
2142 	struct fuse_inode *fi = get_fuse_inode(inode);
2143 	struct address_space *mapping = inode->i_mapping;
2144 	FUSE_ARGS(args);
2145 	struct fuse_setattr_in inarg;
2146 	struct fuse_attr_out outarg;
2147 	bool is_truncate = false;
2148 	bool is_wb = fc->writeback_cache && S_ISREG(inode->i_mode);
2149 	loff_t oldsize;
2150 	int err;
2151 	bool trust_local_cmtime = is_wb;
2152 	bool fault_blocked = false;
2153 	u64 attr_version;
2154 
2155 	if (!fc->default_permissions)
2156 		attr->ia_valid |= ATTR_FORCE;
2157 
2158 	err = setattr_prepare(idmap, dentry, attr);
2159 	if (err)
2160 		return err;
2161 
2162 	if (attr->ia_valid & ATTR_SIZE) {
2163 		if (WARN_ON(!S_ISREG(inode->i_mode)))
2164 			return -EIO;
2165 		is_truncate = true;
2166 	}
2167 
2168 	if (FUSE_IS_DAX(inode) && is_truncate) {
2169 		filemap_invalidate_lock(mapping);
2170 		fault_blocked = true;
2171 		err = fuse_dax_break_layouts(inode, 0, -1);
2172 		if (err) {
2173 			filemap_invalidate_unlock(mapping);
2174 			return err;
2175 		}
2176 	}
2177 
2178 	if (attr->ia_valid & ATTR_OPEN) {
2179 		/* This is coming from open(..., ... | O_TRUNC); */
2180 		WARN_ON(!(attr->ia_valid & ATTR_SIZE));
2181 		WARN_ON(attr->ia_size != 0);
2182 		if (fc->atomic_o_trunc) {
2183 			/*
2184 			 * No need to send request to userspace, since actual
2185 			 * truncation has already been done by OPEN.  But still
2186 			 * need to truncate page cache.
2187 			 */
2188 			i_size_write(inode, 0);
2189 			truncate_pagecache(inode, 0);
2190 			goto out;
2191 		}
2192 		file = NULL;
2193 	}
2194 
2195 	/* Flush dirty data/metadata before non-truncate SETATTR */
2196 	if (is_wb &&
2197 	    attr->ia_valid &
2198 			(ATTR_MODE | ATTR_UID | ATTR_GID | ATTR_MTIME_SET |
2199 			 ATTR_TIMES_SET)) {
2200 		err = write_inode_now(inode, true);
2201 		if (err)
2202 			return err;
2203 
2204 		fuse_set_nowrite(inode);
2205 		fuse_release_nowrite(inode);
2206 	}
2207 
2208 	if (is_truncate) {
2209 		fuse_set_nowrite(inode);
2210 		set_bit(FUSE_I_SIZE_UNSTABLE, &fi->state);
2211 		if (trust_local_cmtime && attr->ia_size != inode->i_size)
2212 			attr->ia_valid |= ATTR_MTIME | ATTR_CTIME;
2213 	}
2214 
2215 	memset(&inarg, 0, sizeof(inarg));
2216 	memset(&outarg, 0, sizeof(outarg));
2217 	iattr_to_fattr(idmap, fc, attr, &inarg, trust_local_cmtime);
2218 	if (file) {
2219 		struct fuse_file *ff = file->private_data;
2220 		inarg.valid |= FATTR_FH;
2221 		inarg.fh = ff->fh;
2222 	}
2223 
2224 	/* Kill suid/sgid for non-directory chown unconditionally */
2225 	if (fc->handle_killpriv_v2 && !S_ISDIR(inode->i_mode) &&
2226 	    attr->ia_valid & (ATTR_UID | ATTR_GID))
2227 		inarg.valid |= FATTR_KILL_SUIDGID;
2228 
2229 	if (attr->ia_valid & ATTR_SIZE) {
2230 		/* For mandatory locking in truncate */
2231 		inarg.valid |= FATTR_LOCKOWNER;
2232 		inarg.lock_owner = fuse_lock_owner_id(fc, current->files);
2233 
2234 		/* Kill suid/sgid for truncate only if no CAP_FSETID */
2235 		if (fc->handle_killpriv_v2 && !capable(CAP_FSETID))
2236 			inarg.valid |= FATTR_KILL_SUIDGID;
2237 	}
2238 
2239 	attr_version = fuse_get_attr_version(fm->fc);
2240 	fuse_setattr_fill(fc, &args, inode, &inarg, &outarg);
2241 	err = fuse_simple_request(fm, &args);
2242 	if (err) {
2243 		if (err == -EINTR)
2244 			fuse_invalidate_attr(inode);
2245 		goto error;
2246 	}
2247 
2248 	if (fuse_invalid_attr(&outarg.attr) ||
2249 	    inode_wrong_type(inode, outarg.attr.mode)) {
2250 		fuse_make_bad(inode);
2251 		err = -EIO;
2252 		goto error;
2253 	}
2254 
2255 	spin_lock(&fi->lock);
2256 	/* the kernel maintains i_mtime locally */
2257 	if (trust_local_cmtime) {
2258 		if (attr->ia_valid & ATTR_MTIME)
2259 			inode_set_mtime_to_ts(inode, attr->ia_mtime);
2260 		if (attr->ia_valid & ATTR_CTIME)
2261 			inode_set_ctime_to_ts(inode, attr->ia_ctime);
2262 		/* FIXME: clear I_DIRTY_SYNC? */
2263 	}
2264 
2265 	if (fi->attr_version > attr_version) {
2266 		/*
2267 		 * Apply attributes, for example for fsnotify_change(), but set
2268 		 * attribute timeout to zero.
2269 		 */
2270 		outarg.attr_valid = outarg.attr_valid_nsec = 0;
2271 	}
2272 
2273 	fuse_change_attributes_common(inode, &outarg.attr, NULL,
2274 				      ATTR_TIMEOUT(&outarg),
2275 				      fuse_get_cache_mask(inode), 0);
2276 	oldsize = inode->i_size;
2277 	/* see the comment in fuse_change_attributes() */
2278 	if (!is_wb || is_truncate)
2279 		i_size_write(inode, outarg.attr.size);
2280 
2281 	if (is_truncate) {
2282 		/* NOTE: this may release/reacquire fi->lock */
2283 		__fuse_release_nowrite(inode);
2284 	}
2285 	spin_unlock(&fi->lock);
2286 
2287 	/*
2288 	 * Only call invalidate_inode_pages2() after removing
2289 	 * FUSE_NOWRITE, otherwise fuse_launder_folio() would deadlock.
2290 	 */
2291 	if ((is_truncate || !is_wb) &&
2292 	    S_ISREG(inode->i_mode) && oldsize != outarg.attr.size) {
2293 		truncate_pagecache(inode, outarg.attr.size);
2294 		invalidate_inode_pages2(mapping);
2295 	}
2296 
2297 	clear_bit(FUSE_I_SIZE_UNSTABLE, &fi->state);
2298 out:
2299 	if (fault_blocked)
2300 		filemap_invalidate_unlock(mapping);
2301 
2302 	return 0;
2303 
2304 error:
2305 	if (is_truncate)
2306 		fuse_release_nowrite(inode);
2307 
2308 	clear_bit(FUSE_I_SIZE_UNSTABLE, &fi->state);
2309 
2310 	if (fault_blocked)
2311 		filemap_invalidate_unlock(mapping);
2312 	return err;
2313 }
2314 
2315 static int fuse_setattr(struct mnt_idmap *idmap, struct dentry *entry,
2316 			struct iattr *attr)
2317 {
2318 	struct inode *inode = d_inode(entry);
2319 	struct fuse_conn *fc = get_fuse_conn(inode);
2320 	struct file *file = (attr->ia_valid & ATTR_FILE) ? attr->ia_file : NULL;
2321 	int ret;
2322 
2323 	if (fuse_is_bad(inode))
2324 		return -EIO;
2325 
2326 	if (!fuse_allow_current_process(get_fuse_conn(inode)))
2327 		return -EACCES;
2328 
2329 	if (attr->ia_valid & (ATTR_KILL_SUID | ATTR_KILL_SGID)) {
2330 		attr->ia_valid &= ~(ATTR_KILL_SUID | ATTR_KILL_SGID |
2331 				    ATTR_MODE);
2332 
2333 		/*
2334 		 * The only sane way to reliably kill suid/sgid is to do it in
2335 		 * the userspace filesystem
2336 		 *
2337 		 * This should be done on write(), truncate() and chown().
2338 		 */
2339 		if (!fc->handle_killpriv && !fc->handle_killpriv_v2) {
2340 			/*
2341 			 * ia_mode calculation may have used stale i_mode.
2342 			 * Refresh and recalculate.
2343 			 */
2344 			ret = fuse_do_getattr(idmap, inode, NULL, file);
2345 			if (ret)
2346 				return ret;
2347 
2348 			attr->ia_mode = inode->i_mode;
2349 			if (inode->i_mode & S_ISUID) {
2350 				attr->ia_valid |= ATTR_MODE;
2351 				attr->ia_mode &= ~S_ISUID;
2352 			}
2353 			if ((inode->i_mode & (S_ISGID | S_IXGRP)) == (S_ISGID | S_IXGRP)) {
2354 				attr->ia_valid |= ATTR_MODE;
2355 				attr->ia_mode &= ~S_ISGID;
2356 			}
2357 		}
2358 	}
2359 	if (!attr->ia_valid)
2360 		return 0;
2361 
2362 	ret = fuse_do_setattr(idmap, entry, attr, file);
2363 	if (!ret) {
2364 		/*
2365 		 * If filesystem supports acls it may have updated acl xattrs in
2366 		 * the filesystem, so forget cached acls for the inode.
2367 		 */
2368 		if (fc->posix_acl)
2369 			forget_all_cached_acls(inode);
2370 
2371 		/* Directory mode changed, may need to revalidate access */
2372 		if (d_is_dir(entry) && (attr->ia_valid & ATTR_MODE))
2373 			fuse_invalidate_entry_cache(entry);
2374 	}
2375 	return ret;
2376 }
2377 
2378 static int fuse_getattr(struct mnt_idmap *idmap,
2379 			const struct path *path, struct kstat *stat,
2380 			u32 request_mask, unsigned int flags)
2381 {
2382 	struct inode *inode = d_inode(path->dentry);
2383 	struct fuse_conn *fc = get_fuse_conn(inode);
2384 
2385 	if (fuse_is_bad(inode))
2386 		return -EIO;
2387 
2388 	if (!fuse_allow_current_process(fc)) {
2389 		if (!request_mask) {
2390 			/*
2391 			 * If user explicitly requested *nothing* then don't
2392 			 * error out, but return st_dev only.
2393 			 */
2394 			stat->result_mask = 0;
2395 			stat->dev = inode->i_sb->s_dev;
2396 			return 0;
2397 		}
2398 		return -EACCES;
2399 	}
2400 
2401 	return fuse_update_get_attr(idmap, inode, NULL, stat, request_mask, flags);
2402 }
2403 
2404 static const struct inode_operations fuse_dir_inode_operations = {
2405 	.lookup		= fuse_lookup,
2406 	.mkdir		= fuse_mkdir,
2407 	.symlink	= fuse_symlink,
2408 	.unlink		= fuse_unlink,
2409 	.rmdir		= fuse_rmdir,
2410 	.rename		= fuse_rename2,
2411 	.link		= fuse_link,
2412 	.setattr	= fuse_setattr,
2413 	.create		= fuse_create,
2414 	.atomic_open	= fuse_atomic_open,
2415 	.tmpfile	= fuse_tmpfile,
2416 	.mknod		= fuse_mknod,
2417 	.permission	= fuse_permission,
2418 	.getattr	= fuse_getattr,
2419 	.listxattr	= fuse_listxattr,
2420 	.get_inode_acl	= fuse_get_inode_acl,
2421 	.get_acl	= fuse_get_acl,
2422 	.set_acl	= fuse_set_acl,
2423 	.fileattr_get	= fuse_fileattr_get,
2424 	.fileattr_set	= fuse_fileattr_set,
2425 };
2426 
2427 static const struct file_operations fuse_dir_operations = {
2428 	.llseek		= generic_file_llseek,
2429 	.read		= generic_read_dir,
2430 	.iterate_shared	= fuse_readdir,
2431 	.open		= fuse_dir_open,
2432 	.release	= fuse_dir_release,
2433 	.fsync		= fuse_dir_fsync,
2434 	.unlocked_ioctl	= fuse_dir_ioctl,
2435 	.compat_ioctl	= fuse_dir_compat_ioctl,
2436 };
2437 
2438 static const struct inode_operations fuse_common_inode_operations = {
2439 	.setattr	= fuse_setattr,
2440 	.permission	= fuse_permission,
2441 	.getattr	= fuse_getattr,
2442 	.listxattr	= fuse_listxattr,
2443 	.get_inode_acl	= fuse_get_inode_acl,
2444 	.get_acl	= fuse_get_acl,
2445 	.set_acl	= fuse_set_acl,
2446 	.fileattr_get	= fuse_fileattr_get,
2447 	.fileattr_set	= fuse_fileattr_set,
2448 };
2449 
2450 static const struct inode_operations fuse_symlink_inode_operations = {
2451 	.setattr	= fuse_setattr,
2452 	.get_link	= fuse_get_link,
2453 	.getattr	= fuse_getattr,
2454 	.listxattr	= fuse_listxattr,
2455 };
2456 
2457 void fuse_init_common(struct inode *inode)
2458 {
2459 	inode->i_op = &fuse_common_inode_operations;
2460 }
2461 
2462 void fuse_init_dir(struct inode *inode)
2463 {
2464 	struct fuse_inode *fi = get_fuse_inode(inode);
2465 
2466 	inode->i_op = &fuse_dir_inode_operations;
2467 	inode->i_fop = &fuse_dir_operations;
2468 
2469 	spin_lock_init(&fi->rdc.lock);
2470 	fi->rdc.cached = false;
2471 	fi->rdc.size = 0;
2472 	fi->rdc.pos = 0;
2473 	fi->rdc.version = 0;
2474 }
2475 
2476 static int fuse_symlink_read_folio(struct file *null, struct folio *folio)
2477 {
2478 	int err = fuse_readlink_folio(folio->mapping->host, folio);
2479 
2480 	if (!err)
2481 		folio_mark_uptodate(folio);
2482 
2483 	folio_unlock(folio);
2484 
2485 	return err;
2486 }
2487 
2488 static const struct address_space_operations fuse_symlink_aops = {
2489 	.read_folio	= fuse_symlink_read_folio,
2490 };
2491 
2492 void fuse_init_symlink(struct inode *inode)
2493 {
2494 	inode->i_op = &fuse_symlink_inode_operations;
2495 	inode->i_data.a_ops = &fuse_symlink_aops;
2496 	inode_nohighmem(inode);
2497 }
2498