File Index
Files and directories
Sign in
FILE

inode.c

File preview with syntax highlighting.

linux-6.19.14/fs/fuse/inode.c C
   1/*
   2  FUSE: Filesystem in Userspace
   3  Copyright (C) 2001-2008  Miklos Szeredi <miklos@szeredi.hu>
   4
   5  This program can be distributed under the terms of the GNU GPL.
   6  See the file COPYING.
   7*/
   8
   9#include "fuse_i.h"
  10#include "fuse_dev_i.h"
  11#include "dev_uring_i.h"
  12
  13#include <linux/dax.h>
  14#include <linux/pagemap.h>
  15#include <linux/slab.h>
  16#include <linux/file.h>
  17#include <linux/seq_file.h>
  18#include <linux/init.h>
  19#include <linux/module.h>
  20#include <linux/moduleparam.h>
  21#include <linux/fs_context.h>
  22#include <linux/fs_parser.h>
  23#include <linux/statfs.h>
  24#include <linux/random.h>
  25#include <linux/sched.h>
  26#include <linux/exportfs.h>
  27#include <linux/posix_acl.h>
  28#include <linux/pid_namespace.h>
  29#include <uapi/linux/magic.h>
  30
  31MODULE_AUTHOR("Miklos Szeredi <miklos@szeredi.hu>");
  32MODULE_DESCRIPTION("Filesystem in Userspace");
  33MODULE_LICENSE("GPL");
  34
  35static struct kmem_cache *fuse_inode_cachep;
  36struct list_head fuse_conn_list;
  37DEFINE_MUTEX(fuse_mutex);
  38DECLARE_WAIT_QUEUE_HEAD(fuse_dev_waitq);
  39
  40static int set_global_limit(const char *val, const struct kernel_param *kp);
  41
  42unsigned int fuse_max_pages_limit = 256;
  43/* default is no timeout */
  44unsigned int fuse_default_req_timeout;
  45unsigned int fuse_max_req_timeout;
  46
  47unsigned int max_user_bgreq;
  48module_param_call(max_user_bgreq, set_global_limit, param_get_uint,
  49		  &max_user_bgreq, 0644);
  50__MODULE_PARM_TYPE(max_user_bgreq, "uint");
  51MODULE_PARM_DESC(max_user_bgreq,
  52 "Global limit for the maximum number of backgrounded requests an "
  53 "unprivileged user can set");
  54
  55unsigned int max_user_congthresh;
  56module_param_call(max_user_congthresh, set_global_limit, param_get_uint,
  57		  &max_user_congthresh, 0644);
  58__MODULE_PARM_TYPE(max_user_congthresh, "uint");
  59MODULE_PARM_DESC(max_user_congthresh,
  60 "Global limit for the maximum congestion threshold an "
  61 "unprivileged user can set");
  62
  63#define FUSE_DEFAULT_BLKSIZE 512
  64
  65/** Maximum number of outstanding background requests */
  66#define FUSE_DEFAULT_MAX_BACKGROUND 12
  67
  68/** Congestion starts at 75% of maximum */
  69#define FUSE_DEFAULT_CONGESTION_THRESHOLD (FUSE_DEFAULT_MAX_BACKGROUND * 3 / 4)
  70
  71#ifdef CONFIG_BLOCK
  72static struct file_system_type fuseblk_fs_type;
  73#endif
  74
  75struct fuse_forget_link *fuse_alloc_forget(void)
  76{
  77	return kzalloc(sizeof(struct fuse_forget_link), GFP_KERNEL_ACCOUNT);
  78}
  79
  80static struct fuse_submount_lookup *fuse_alloc_submount_lookup(void)
  81{
  82	struct fuse_submount_lookup *sl;
  83
  84	sl = kzalloc(sizeof(struct fuse_submount_lookup), GFP_KERNEL_ACCOUNT);
  85	if (!sl)
  86		return NULL;
  87	sl->forget = fuse_alloc_forget();
  88	if (!sl->forget)
  89		goto out_free;
  90
  91	return sl;
  92
  93out_free:
  94	kfree(sl);
  95	return NULL;
  96}
  97
  98static struct inode *fuse_alloc_inode(struct super_block *sb)
  99{
 100	struct fuse_inode *fi;
 101
 102	fi = alloc_inode_sb(sb, fuse_inode_cachep, GFP_KERNEL);
 103	if (!fi)
 104		return NULL;
 105
 106	/* Initialize private data (i.e. everything except fi->inode) */
 107	BUILD_BUG_ON(offsetof(struct fuse_inode, inode) != 0);
 108	memset((void *) fi + sizeof(fi->inode), 0, sizeof(*fi) - sizeof(fi->inode));
 109
 110	fi->inval_mask = ~0;
 111	mutex_init(&fi->mutex);
 112	spin_lock_init(&fi->lock);
 113	fi->forget = fuse_alloc_forget();
 114	if (!fi->forget)
 115		goto out_free;
 116
 117	if (IS_ENABLED(CONFIG_FUSE_DAX) && !fuse_dax_inode_alloc(sb, fi))
 118		goto out_free_forget;
 119
 120	if (IS_ENABLED(CONFIG_FUSE_PASSTHROUGH))
 121		fuse_inode_backing_set(fi, NULL);
 122
 123	return &fi->inode;
 124
 125out_free_forget:
 126	kfree(fi->forget);
 127out_free:
 128	kmem_cache_free(fuse_inode_cachep, fi);
 129	return NULL;
 130}
 131
 132static void fuse_free_inode(struct inode *inode)
 133{
 134	struct fuse_inode *fi = get_fuse_inode(inode);
 135
 136	mutex_destroy(&fi->mutex);
 137	kfree(fi->forget);
 138#ifdef CONFIG_FUSE_DAX
 139	kfree(fi->dax);
 140#endif
 141	if (IS_ENABLED(CONFIG_FUSE_PASSTHROUGH))
 142		fuse_backing_put(fuse_inode_backing(fi));
 143
 144	kmem_cache_free(fuse_inode_cachep, fi);
 145}
 146
 147static void fuse_cleanup_submount_lookup(struct fuse_conn *fc,
 148					 struct fuse_submount_lookup *sl)
 149{
 150	if (!refcount_dec_and_test(&sl->count))
 151		return;
 152
 153	fuse_queue_forget(fc, sl->forget, sl->nodeid, 1);
 154	sl->forget = NULL;
 155	kfree(sl);
 156}
 157
 158static void fuse_evict_inode(struct inode *inode)
 159{
 160	struct fuse_inode *fi = get_fuse_inode(inode);
 161
 162	/* Will write inode on close/munmap and in all other dirtiers */
 163	WARN_ON(inode_state_read_once(inode) & I_DIRTY_INODE);
 164
 165	if (FUSE_IS_DAX(inode))
 166		dax_break_layout_final(inode);
 167
 168	truncate_inode_pages_final(&inode->i_data);
 169	clear_inode(inode);
 170	if (inode->i_sb->s_flags & SB_ACTIVE) {
 171		struct fuse_conn *fc = get_fuse_conn(inode);
 172
 173		if (FUSE_IS_DAX(inode))
 174			fuse_dax_inode_cleanup(inode);
 175		if (fi->nlookup) {
 176			fuse_queue_forget(fc, fi->forget, fi->nodeid,
 177					  fi->nlookup);
 178			fi->forget = NULL;
 179		}
 180
 181		if (fi->submount_lookup) {
 182			fuse_cleanup_submount_lookup(fc, fi->submount_lookup);
 183			fi->submount_lookup = NULL;
 184		}
 185		/*
 186		 * Evict of non-deleted inode may race with outstanding
 187		 * LOOKUP/READDIRPLUS requests and result in inconsistency when
 188		 * the request finishes.  Deal with that here by bumping a
 189		 * counter that can be compared to the starting value.
 190		 */
 191		if (inode->i_nlink > 0)
 192			atomic64_inc(&fc->evict_ctr);
 193	}
 194	if (S_ISREG(inode->i_mode) && !fuse_is_bad(inode)) {
 195		WARN_ON(fi->iocachectr != 0);
 196		WARN_ON(!list_empty(&fi->write_files));
 197		WARN_ON(!list_empty(&fi->queued_writes));
 198	}
 199}
 200
 201static int fuse_reconfigure(struct fs_context *fsc)
 202{
 203	struct super_block *sb = fsc->root->d_sb;
 204
 205	sync_filesystem(sb);
 206	if (fsc->sb_flags & SB_MANDLOCK)
 207		return -EINVAL;
 208
 209	return 0;
 210}
 211
 212/*
 213 * ino_t is 32-bits on 32-bit arch. We have to squash the 64-bit value down
 214 * so that it will fit.
 215 */
 216static ino_t fuse_squash_ino(u64 ino64)
 217{
 218	ino_t ino = (ino_t) ino64;
 219	if (sizeof(ino_t) < sizeof(u64))
 220		ino ^= ino64 >> (sizeof(u64) - sizeof(ino_t)) * 8;
 221	return ino;
 222}
 223
 224void fuse_change_attributes_common(struct inode *inode, struct fuse_attr *attr,
 225				   struct fuse_statx *sx,
 226				   u64 attr_valid, u32 cache_mask,
 227				   u64 evict_ctr)
 228{
 229	struct fuse_conn *fc = get_fuse_conn(inode);
 230	struct fuse_inode *fi = get_fuse_inode(inode);
 231
 232	lockdep_assert_held(&fi->lock);
 233
 234	/*
 235	 * Clear basic stats from invalid mask.
 236	 *
 237	 * Don't do this if this is coming from a fuse_iget() call and there
 238	 * might have been a racing evict which would've invalidated the result
 239	 * if the attr_version would've been preserved.
 240	 *
 241	 * !evict_ctr -> this is create
 242	 * fi->attr_version != 0 -> this is not a new inode
 243	 * evict_ctr == fuse_get_evict_ctr() -> no evicts while during request
 244	 */
 245	if (!evict_ctr || fi->attr_version || evict_ctr == fuse_get_evict_ctr(fc))
 246		set_mask_bits(&fi->inval_mask, STATX_BASIC_STATS, 0);
 247
 248	fi->attr_version = atomic64_inc_return(&fc->attr_version);
 249	fi->i_time = attr_valid;
 250
 251	inode->i_ino     = fuse_squash_ino(attr->ino);
 252	inode->i_mode    = (inode->i_mode & S_IFMT) | (attr->mode & 07777);
 253	set_nlink(inode, attr->nlink);
 254	inode->i_uid     = make_kuid(fc->user_ns, attr->uid);
 255	inode->i_gid     = make_kgid(fc->user_ns, attr->gid);
 256	inode->i_blocks  = attr->blocks;
 257
 258	/* Sanitize nsecs */
 259	attr->atimensec = min_t(u32, attr->atimensec, NSEC_PER_SEC - 1);
 260	attr->mtimensec = min_t(u32, attr->mtimensec, NSEC_PER_SEC - 1);
 261	attr->ctimensec = min_t(u32, attr->ctimensec, NSEC_PER_SEC - 1);
 262
 263	inode_set_atime(inode, attr->atime, attr->atimensec);
 264	/* mtime from server may be stale due to local buffered write */
 265	if (!(cache_mask & STATX_MTIME)) {
 266		inode_set_mtime(inode, attr->mtime, attr->mtimensec);
 267	}
 268	if (!(cache_mask & STATX_CTIME)) {
 269		inode_set_ctime(inode, attr->ctime, attr->ctimensec);
 270	}
 271	if (sx) {
 272		/* Sanitize nsecs */
 273		sx->btime.tv_nsec =
 274			min_t(u32, sx->btime.tv_nsec, NSEC_PER_SEC - 1);
 275
 276		/*
 277		 * Btime has been queried, cache is valid (whether or not btime
 278		 * is available or not) so clear STATX_BTIME from inval_mask.
 279		 *
 280		 * Availability of the btime attribute is indicated in
 281		 * FUSE_I_BTIME
 282		 */
 283		set_mask_bits(&fi->inval_mask, STATX_BTIME, 0);
 284		if (sx->mask & STATX_BTIME) {
 285			set_bit(FUSE_I_BTIME, &fi->state);
 286			fi->i_btime.tv_sec = sx->btime.tv_sec;
 287			fi->i_btime.tv_nsec = sx->btime.tv_nsec;
 288		}
 289	}
 290
 291	if (attr->blksize)
 292		fi->cached_i_blkbits = ilog2(attr->blksize);
 293	else
 294		fi->cached_i_blkbits = inode->i_sb->s_blocksize_bits;
 295
 296	/*
 297	 * Don't set the sticky bit in i_mode, unless we want the VFS
 298	 * to check permissions.  This prevents failures due to the
 299	 * check in may_delete().
 300	 */
 301	fi->orig_i_mode = inode->i_mode;
 302	if (!fc->default_permissions)
 303		inode->i_mode &= ~S_ISVTX;
 304
 305	fi->orig_ino = attr->ino;
 306
 307	/*
 308	 * We are refreshing inode data and it is possible that another
 309	 * client set suid/sgid or security.capability xattr. So clear
 310	 * S_NOSEC. Ideally, we could have cleared it only if suid/sgid
 311	 * was set or if security.capability xattr was set. But we don't
 312	 * know if security.capability has been set or not. So clear it
 313	 * anyway. Its less efficient but should be safe.
 314	 */
 315	inode->i_flags &= ~S_NOSEC;
 316}
 317
 318u32 fuse_get_cache_mask(struct inode *inode)
 319{
 320	struct fuse_conn *fc = get_fuse_conn(inode);
 321
 322	if (!fc->writeback_cache || !S_ISREG(inode->i_mode))
 323		return 0;
 324
 325	return STATX_MTIME | STATX_CTIME | STATX_SIZE;
 326}
 327
 328static void fuse_change_attributes_i(struct inode *inode, struct fuse_attr *attr,
 329				     struct fuse_statx *sx, u64 attr_valid,
 330				     u64 attr_version, u64 evict_ctr)
 331{
 332	struct fuse_conn *fc = get_fuse_conn(inode);
 333	struct fuse_inode *fi = get_fuse_inode(inode);
 334	u32 cache_mask;
 335	loff_t oldsize;
 336	struct timespec64 old_mtime;
 337
 338	spin_lock(&fi->lock);
 339	/*
 340	 * In case of writeback_cache enabled, writes update mtime, ctime and
 341	 * may update i_size.  In these cases trust the cached value in the
 342	 * inode.
 343	 */
 344	cache_mask = fuse_get_cache_mask(inode);
 345	if (cache_mask & STATX_SIZE)
 346		attr->size = i_size_read(inode);
 347
 348	if (cache_mask & STATX_MTIME) {
 349		attr->mtime = inode_get_mtime_sec(inode);
 350		attr->mtimensec = inode_get_mtime_nsec(inode);
 351	}
 352	if (cache_mask & STATX_CTIME) {
 353		attr->ctime = inode_get_ctime_sec(inode);
 354		attr->ctimensec = inode_get_ctime_nsec(inode);
 355	}
 356
 357	if ((attr_version != 0 && fi->attr_version > attr_version) ||
 358	    test_bit(FUSE_I_SIZE_UNSTABLE, &fi->state)) {
 359		spin_unlock(&fi->lock);
 360		return;
 361	}
 362
 363	old_mtime = inode_get_mtime(inode);
 364	fuse_change_attributes_common(inode, attr, sx, attr_valid, cache_mask,
 365				      evict_ctr);
 366
 367	oldsize = inode->i_size;
 368	/*
 369	 * In case of writeback_cache enabled, the cached writes beyond EOF
 370	 * extend local i_size without keeping userspace server in sync. So,
 371	 * attr->size coming from server can be stale. We cannot trust it.
 372	 */
 373	if (!(cache_mask & STATX_SIZE))
 374		i_size_write(inode, attr->size);
 375	spin_unlock(&fi->lock);
 376
 377	if (!cache_mask && S_ISREG(inode->i_mode)) {
 378		bool inval = false;
 379
 380		if (oldsize != attr->size) {
 381			truncate_pagecache(inode, attr->size);
 382			if (!fc->explicit_inval_data)
 383				inval = true;
 384		} else if (fc->auto_inval_data) {
 385			struct timespec64 new_mtime = {
 386				.tv_sec = attr->mtime,
 387				.tv_nsec = attr->mtimensec,
 388			};
 389
 390			/*
 391			 * Auto inval mode also checks and invalidates if mtime
 392			 * has changed.
 393			 */
 394			if (!timespec64_equal(&old_mtime, &new_mtime))
 395				inval = true;
 396		}
 397
 398		if (inval)
 399			invalidate_inode_pages2(inode->i_mapping);
 400	}
 401
 402	if (IS_ENABLED(CONFIG_FUSE_DAX))
 403		fuse_dax_dontcache(inode, attr->flags);
 404}
 405
 406void fuse_change_attributes(struct inode *inode, struct fuse_attr *attr,
 407			    struct fuse_statx *sx, u64 attr_valid,
 408			    u64 attr_version)
 409{
 410	fuse_change_attributes_i(inode, attr, sx, attr_valid, attr_version, 0);
 411}
 412
 413static void fuse_init_submount_lookup(struct fuse_submount_lookup *sl,
 414				      u64 nodeid)
 415{
 416	sl->nodeid = nodeid;
 417	refcount_set(&sl->count, 1);
 418}
 419
 420static void fuse_init_inode(struct inode *inode, struct fuse_attr *attr,
 421			    struct fuse_conn *fc)
 422{
 423	inode->i_mode = attr->mode & S_IFMT;
 424	inode->i_size = attr->size;
 425	inode_set_mtime(inode, attr->mtime, attr->mtimensec);
 426	inode_set_ctime(inode, attr->ctime, attr->ctimensec);
 427	if (S_ISREG(inode->i_mode)) {
 428		fuse_init_common(inode);
 429		fuse_init_file_inode(inode, attr->flags);
 430	} else if (S_ISDIR(inode->i_mode))
 431		fuse_init_dir(inode);
 432	else if (S_ISLNK(inode->i_mode))
 433		fuse_init_symlink(inode);
 434	else if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode) ||
 435		 S_ISFIFO(inode->i_mode) || S_ISSOCK(inode->i_mode)) {
 436		fuse_init_common(inode);
 437		init_special_inode(inode, inode->i_mode,
 438				   new_decode_dev(attr->rdev));
 439	} else
 440		BUG();
 441	/*
 442	 * Ensure that we don't cache acls for daemons without FUSE_POSIX_ACL
 443	 * so they see the exact same behavior as before.
 444	 */
 445	if (!fc->posix_acl)
 446		inode->i_acl = inode->i_default_acl = ACL_DONT_CACHE;
 447}
 448
 449static int fuse_inode_eq(struct inode *inode, void *_nodeidp)
 450{
 451	u64 nodeid = *(u64 *) _nodeidp;
 452	if (get_node_id(inode) == nodeid)
 453		return 1;
 454	else
 455		return 0;
 456}
 457
 458static int fuse_inode_set(struct inode *inode, void *_nodeidp)
 459{
 460	u64 nodeid = *(u64 *) _nodeidp;
 461	get_fuse_inode(inode)->nodeid = nodeid;
 462	return 0;
 463}
 464
 465struct inode *fuse_iget(struct super_block *sb, u64 nodeid,
 466			int generation, struct fuse_attr *attr,
 467			u64 attr_valid, u64 attr_version,
 468			u64 evict_ctr)
 469{
 470	struct inode *inode;
 471	struct fuse_inode *fi;
 472	struct fuse_conn *fc = get_fuse_conn_super(sb);
 473
 474	/*
 475	 * Auto mount points get their node id from the submount root, which is
 476	 * not a unique identifier within this filesystem.
 477	 *
 478	 * To avoid conflicts, do not place submount points into the inode hash
 479	 * table.
 480	 */
 481	if (fc->auto_submounts && (attr->flags & FUSE_ATTR_SUBMOUNT) &&
 482	    S_ISDIR(attr->mode)) {
 483		struct fuse_inode *fi;
 484
 485		inode = new_inode(sb);
 486		if (!inode)
 487			return NULL;
 488
 489		fuse_init_inode(inode, attr, fc);
 490		fi = get_fuse_inode(inode);
 491		fi->nodeid = nodeid;
 492		fi->submount_lookup = fuse_alloc_submount_lookup();
 493		if (!fi->submount_lookup) {
 494			iput(inode);
 495			return NULL;
 496		}
 497		/* Sets nlookup = 1 on fi->submount_lookup->nlookup */
 498		fuse_init_submount_lookup(fi->submount_lookup, nodeid);
 499		inode->i_flags |= S_AUTOMOUNT;
 500		goto done;
 501	}
 502
 503retry:
 504	inode = iget5_locked(sb, nodeid, fuse_inode_eq, fuse_inode_set, &nodeid);
 505	if (!inode)
 506		return NULL;
 507
 508	if ((inode_state_read_once(inode) & I_NEW)) {
 509		inode->i_flags |= S_NOATIME;
 510		if (!fc->writeback_cache || !S_ISREG(attr->mode))
 511			inode->i_flags |= S_NOCMTIME;
 512		inode->i_generation = generation;
 513		fuse_init_inode(inode, attr, fc);
 514		unlock_new_inode(inode);
 515	} else if (fuse_stale_inode(inode, generation, attr)) {
 516		/* nodeid was reused, any I/O on the old inode should fail */
 517		fuse_make_bad(inode);
 518		if (inode != d_inode(sb->s_root)) {
 519			remove_inode_hash(inode);
 520			iput(inode);
 521			goto retry;
 522		}
 523	}
 524	fi = get_fuse_inode(inode);
 525	spin_lock(&fi->lock);
 526	fi->nlookup++;
 527	spin_unlock(&fi->lock);
 528done:
 529	fuse_change_attributes_i(inode, attr, NULL, attr_valid, attr_version,
 530				 evict_ctr);
 531	return inode;
 532}
 533
 534struct inode *fuse_ilookup(struct fuse_conn *fc, u64 nodeid,
 535			   struct fuse_mount **fm)
 536{
 537	struct fuse_mount *fm_iter;
 538	struct inode *inode;
 539
 540	WARN_ON(!rwsem_is_locked(&fc->killsb));
 541	list_for_each_entry(fm_iter, &fc->mounts, fc_entry) {
 542		if (!fm_iter->sb)
 543			continue;
 544
 545		inode = ilookup5(fm_iter->sb, nodeid, fuse_inode_eq, &nodeid);
 546		if (inode) {
 547			if (fm)
 548				*fm = fm_iter;
 549			return inode;
 550		}
 551	}
 552
 553	return NULL;
 554}
 555
 556int fuse_reverse_inval_inode(struct fuse_conn *fc, u64 nodeid,
 557			     loff_t offset, loff_t len)
 558{
 559	struct fuse_inode *fi;
 560	struct inode *inode;
 561	pgoff_t pg_start;
 562	pgoff_t pg_end;
 563
 564	inode = fuse_ilookup(fc, nodeid, NULL);
 565	if (!inode)
 566		return -ENOENT;
 567
 568	fi = get_fuse_inode(inode);
 569	spin_lock(&fi->lock);
 570	fi->attr_version = atomic64_inc_return(&fc->attr_version);
 571	spin_unlock(&fi->lock);
 572
 573	fuse_invalidate_attr(inode);
 574	forget_all_cached_acls(inode);
 575	if (offset >= 0) {
 576		pg_start = offset >> PAGE_SHIFT;
 577		if (len <= 0)
 578			pg_end = -1;
 579		else
 580			pg_end = (offset + len - 1) >> PAGE_SHIFT;
 581		invalidate_inode_pages2_range(inode->i_mapping,
 582					      pg_start, pg_end);
 583	}
 584	iput(inode);
 585	return 0;
 586}
 587
 588void fuse_try_prune_one_inode(struct fuse_conn *fc, u64 nodeid)
 589{
 590	struct inode *inode;
 591
 592	inode = fuse_ilookup(fc, nodeid,  NULL);
 593	if (!inode)
 594		return;
 595	d_prune_aliases(inode);
 596	iput(inode);
 597}
 598
 599bool fuse_lock_inode(struct inode *inode)
 600{
 601	bool locked = false;
 602
 603	if (!get_fuse_conn(inode)->parallel_dirops) {
 604		mutex_lock(&get_fuse_inode(inode)->mutex);
 605		locked = true;
 606	}
 607
 608	return locked;
 609}
 610
 611void fuse_unlock_inode(struct inode *inode, bool locked)
 612{
 613	if (locked)
 614		mutex_unlock(&get_fuse_inode(inode)->mutex);
 615}
 616
 617static void fuse_umount_begin(struct super_block *sb)
 618{
 619	struct fuse_conn *fc = get_fuse_conn_super(sb);
 620
 621	if (fc->no_force_umount)
 622		return;
 623
 624	fuse_abort_conn(fc);
 625
 626	// Only retire block-device-based superblocks.
 627	if (sb->s_bdev != NULL)
 628		retire_super(sb);
 629}
 630
 631static void fuse_send_destroy(struct fuse_mount *fm)
 632{
 633	if (fm->fc->conn_init) {
 634		FUSE_ARGS(args);
 635
 636		args.opcode = FUSE_DESTROY;
 637		args.force = true;
 638		args.nocreds = true;
 639		fuse_simple_request(fm, &args);
 640	}
 641}
 642
 643static void convert_fuse_statfs(struct kstatfs *stbuf, struct fuse_kstatfs *attr)
 644{
 645	stbuf->f_type    = FUSE_SUPER_MAGIC;
 646	stbuf->f_bsize   = attr->bsize;
 647	stbuf->f_frsize  = attr->frsize;
 648	stbuf->f_blocks  = attr->blocks;
 649	stbuf->f_bfree   = attr->bfree;
 650	stbuf->f_bavail  = attr->bavail;
 651	stbuf->f_files   = attr->files;
 652	stbuf->f_ffree   = attr->ffree;
 653	stbuf->f_namelen = attr->namelen;
 654	/* fsid is left zero */
 655}
 656
 657static int fuse_statfs(struct dentry *dentry, struct kstatfs *buf)
 658{
 659	struct super_block *sb = dentry->d_sb;
 660	struct fuse_mount *fm = get_fuse_mount_super(sb);
 661	FUSE_ARGS(args);
 662	struct fuse_statfs_out outarg;
 663	int err;
 664
 665	if (!fuse_allow_current_process(fm->fc)) {
 666		buf->f_type = FUSE_SUPER_MAGIC;
 667		return 0;
 668	}
 669
 670	memset(&outarg, 0, sizeof(outarg));
 671	args.in_numargs = 0;
 672	args.opcode = FUSE_STATFS;
 673	args.nodeid = get_node_id(d_inode(dentry));
 674	args.out_numargs = 1;
 675	args.out_args[0].size = sizeof(outarg);
 676	args.out_args[0].value = &outarg;
 677	err = fuse_simple_request(fm, &args);
 678	if (!err)
 679		convert_fuse_statfs(buf, &outarg.st);
 680	return err;
 681}
 682
 683static struct fuse_sync_bucket *fuse_sync_bucket_alloc(void)
 684{
 685	struct fuse_sync_bucket *bucket;
 686
 687	bucket = kzalloc(sizeof(*bucket), GFP_KERNEL | __GFP_NOFAIL);
 688	if (bucket) {
 689		init_waitqueue_head(&bucket->waitq);
 690		/* Initial active count */
 691		atomic_set(&bucket->count, 1);
 692	}
 693	return bucket;
 694}
 695
 696static void fuse_sync_fs_writes(struct fuse_conn *fc)
 697{
 698	struct fuse_sync_bucket *bucket, *new_bucket;
 699	int count;
 700
 701	new_bucket = fuse_sync_bucket_alloc();
 702	spin_lock(&fc->lock);
 703	bucket = rcu_dereference_protected(fc->curr_bucket, 1);
 704	count = atomic_read(&bucket->count);
 705	WARN_ON(count < 1);
 706	/* No outstanding writes? */
 707	if (count == 1) {
 708		spin_unlock(&fc->lock);
 709		kfree(new_bucket);
 710		return;
 711	}
 712
 713	/*
 714	 * Completion of new bucket depends on completion of this bucket, so add
 715	 * one more count.
 716	 */
 717	atomic_inc(&new_bucket->count);
 718	rcu_assign_pointer(fc->curr_bucket, new_bucket);
 719	spin_unlock(&fc->lock);
 720	/*
 721	 * Drop initial active count.  At this point if all writes in this and
 722	 * ancestor buckets complete, the count will go to zero and this task
 723	 * will be woken up.
 724	 */
 725	atomic_dec(&bucket->count);
 726
 727	wait_event(bucket->waitq, atomic_read(&bucket->count) == 0);
 728
 729	/* Drop temp count on descendant bucket */
 730	fuse_sync_bucket_dec(new_bucket);
 731	kfree_rcu(bucket, rcu);
 732}
 733
 734static int fuse_sync_fs(struct super_block *sb, int wait)
 735{
 736	struct fuse_mount *fm = get_fuse_mount_super(sb);
 737	struct fuse_conn *fc = fm->fc;
 738	struct fuse_syncfs_in inarg;
 739	FUSE_ARGS(args);
 740	int err;
 741
 742	/*
 743	 * Userspace cannot handle the wait == 0 case.  Avoid a
 744	 * gratuitous roundtrip.
 745	 */
 746	if (!wait)
 747		return 0;
 748
 749	/* The filesystem is being unmounted.  Nothing to do. */
 750	if (!sb->s_root)
 751		return 0;
 752
 753	if (!fc->sync_fs)
 754		return 0;
 755
 756	fuse_sync_fs_writes(fc);
 757
 758	memset(&inarg, 0, sizeof(inarg));
 759	args.in_numargs = 1;
 760	args.in_args[0].size = sizeof(inarg);
 761	args.in_args[0].value = &inarg;
 762	args.opcode = FUSE_SYNCFS;
 763	args.nodeid = get_node_id(sb->s_root->d_inode);
 764	args.out_numargs = 0;
 765
 766	err = fuse_simple_request(fm, &args);
 767	if (err == -ENOSYS) {
 768		fc->sync_fs = 0;
 769		err = 0;
 770	}
 771
 772	return err;
 773}
 774
 775enum {
 776	OPT_SOURCE,
 777	OPT_SUBTYPE,
 778	OPT_FD,
 779	OPT_ROOTMODE,
 780	OPT_USER_ID,
 781	OPT_GROUP_ID,
 782	OPT_DEFAULT_PERMISSIONS,
 783	OPT_ALLOW_OTHER,
 784	OPT_MAX_READ,
 785	OPT_BLKSIZE,
 786	OPT_ERR
 787};
 788
 789static const struct fs_parameter_spec fuse_fs_parameters[] = {
 790	fsparam_string	("source",		OPT_SOURCE),
 791	fsparam_u32	("fd",			OPT_FD),
 792	fsparam_u32oct	("rootmode",		OPT_ROOTMODE),
 793	fsparam_uid	("user_id",		OPT_USER_ID),
 794	fsparam_gid	("group_id",		OPT_GROUP_ID),
 795	fsparam_flag	("default_permissions",	OPT_DEFAULT_PERMISSIONS),
 796	fsparam_flag	("allow_other",		OPT_ALLOW_OTHER),
 797	fsparam_u32	("max_read",		OPT_MAX_READ),
 798	fsparam_u32	("blksize",		OPT_BLKSIZE),
 799	fsparam_string	("subtype",		OPT_SUBTYPE),
 800	{}
 801};
 802
 803static int fuse_parse_param(struct fs_context *fsc, struct fs_parameter *param)
 804{
 805	struct fs_parse_result result;
 806	struct fuse_fs_context *ctx = fsc->fs_private;
 807	int opt;
 808	kuid_t kuid;
 809	kgid_t kgid;
 810
 811	if (fsc->purpose == FS_CONTEXT_FOR_RECONFIGURE) {
 812		/*
 813		 * Ignore options coming from mount(MS_REMOUNT) for backward
 814		 * compatibility.
 815		 */
 816		if (fsc->oldapi)
 817			return 0;
 818
 819		return invalfc(fsc, "No changes allowed in reconfigure");
 820	}
 821
 822	opt = fs_parse(fsc, fuse_fs_parameters, param, &result);
 823	if (opt < 0)
 824		return opt;
 825
 826	switch (opt) {
 827	case OPT_SOURCE:
 828		if (fsc->source)
 829			return invalfc(fsc, "Multiple sources specified");
 830		fsc->source = param->string;
 831		param->string = NULL;
 832		break;
 833
 834	case OPT_SUBTYPE:
 835		if (ctx->subtype)
 836			return invalfc(fsc, "Multiple subtypes specified");
 837		ctx->subtype = param->string;
 838		param->string = NULL;
 839		return 0;
 840
 841	case OPT_FD:
 842		ctx->fd = result.uint_32;
 843		ctx->fd_present = true;
 844		break;
 845
 846	case OPT_ROOTMODE:
 847		if (!fuse_valid_type(result.uint_32))
 848			return invalfc(fsc, "Invalid rootmode");
 849		ctx->rootmode = result.uint_32;
 850		ctx->rootmode_present = true;
 851		break;
 852
 853	case OPT_USER_ID:
 854		kuid = result.uid;
 855		/*
 856		 * The requested uid must be representable in the
 857		 * filesystem's idmapping.
 858		 */
 859		if (!kuid_has_mapping(fsc->user_ns, kuid))
 860			return invalfc(fsc, "Invalid user_id");
 861		ctx->user_id = kuid;
 862		ctx->user_id_present = true;
 863		break;
 864
 865	case OPT_GROUP_ID:
 866		kgid = result.gid;
 867		/*
 868		 * The requested gid must be representable in the
 869		 * filesystem's idmapping.
 870		 */
 871		if (!kgid_has_mapping(fsc->user_ns, kgid))
 872			return invalfc(fsc, "Invalid group_id");
 873		ctx->group_id = kgid;
 874		ctx->group_id_present = true;
 875		break;
 876
 877	case OPT_DEFAULT_PERMISSIONS:
 878		ctx->default_permissions = true;
 879		break;
 880
 881	case OPT_ALLOW_OTHER:
 882		ctx->allow_other = true;
 883		break;
 884
 885	case OPT_MAX_READ:
 886		ctx->max_read = result.uint_32;
 887		break;
 888
 889	case OPT_BLKSIZE:
 890		if (!ctx->is_bdev)
 891			return invalfc(fsc, "blksize only supported for fuseblk");
 892		ctx->blksize = result.uint_32;
 893		break;
 894
 895	default:
 896		return -EINVAL;
 897	}
 898
 899	return 0;
 900}
 901
 902static void fuse_free_fsc(struct fs_context *fsc)
 903{
 904	struct fuse_fs_context *ctx = fsc->fs_private;
 905
 906	if (ctx) {
 907		kfree(ctx->subtype);
 908		kfree(ctx);
 909	}
 910}
 911
 912static int fuse_show_options(struct seq_file *m, struct dentry *root)
 913{
 914	struct super_block *sb = root->d_sb;
 915	struct fuse_conn *fc = get_fuse_conn_super(sb);
 916
 917	if (fc->legacy_opts_show) {
 918		seq_printf(m, ",user_id=%u",
 919			   from_kuid_munged(fc->user_ns, fc->user_id));
 920		seq_printf(m, ",group_id=%u",
 921			   from_kgid_munged(fc->user_ns, fc->group_id));
 922		if (fc->default_permissions)
 923			seq_puts(m, ",default_permissions");
 924		if (fc->allow_other)
 925			seq_puts(m, ",allow_other");
 926		if (fc->max_read != ~0)
 927			seq_printf(m, ",max_read=%u", fc->max_read);
 928		if (sb->s_bdev && sb->s_blocksize != FUSE_DEFAULT_BLKSIZE)
 929			seq_printf(m, ",blksize=%lu", sb->s_blocksize);
 930	}
 931#ifdef CONFIG_FUSE_DAX
 932	if (fc->dax_mode == FUSE_DAX_ALWAYS)
 933		seq_puts(m, ",dax=always");
 934	else if (fc->dax_mode == FUSE_DAX_NEVER)
 935		seq_puts(m, ",dax=never");
 936	else if (fc->dax_mode == FUSE_DAX_INODE_USER)
 937		seq_puts(m, ",dax=inode");
 938#endif
 939
 940	return 0;
 941}
 942
 943static void fuse_iqueue_init(struct fuse_iqueue *fiq,
 944			     const struct fuse_iqueue_ops *ops,
 945			     void *priv)
 946{
 947	memset(fiq, 0, sizeof(struct fuse_iqueue));
 948	spin_lock_init(&fiq->lock);
 949	init_waitqueue_head(&fiq->waitq);
 950	INIT_LIST_HEAD(&fiq->pending);
 951	INIT_LIST_HEAD(&fiq->interrupts);
 952	fiq->forget_list_tail = &fiq->forget_list_head;
 953	fiq->connected = 1;
 954	fiq->ops = ops;
 955	fiq->priv = priv;
 956}
 957
 958void fuse_pqueue_init(struct fuse_pqueue *fpq)
 959{
 960	unsigned int i;
 961
 962	spin_lock_init(&fpq->lock);
 963	for (i = 0; i < FUSE_PQ_HASH_SIZE; i++)
 964		INIT_LIST_HEAD(&fpq->processing[i]);
 965	INIT_LIST_HEAD(&fpq->io);
 966	fpq->connected = 1;
 967}
 968
 969void fuse_conn_init(struct fuse_conn *fc, struct fuse_mount *fm,
 970		    struct user_namespace *user_ns,
 971		    const struct fuse_iqueue_ops *fiq_ops, void *fiq_priv)
 972{
 973	memset(fc, 0, sizeof(*fc));
 974	spin_lock_init(&fc->lock);
 975	spin_lock_init(&fc->bg_lock);
 976	init_rwsem(&fc->killsb);
 977	refcount_set(&fc->count, 1);
 978	atomic_set(&fc->dev_count, 1);
 979	atomic_set(&fc->epoch, 1);
 980	INIT_WORK(&fc->epoch_work, fuse_epoch_work);
 981	init_waitqueue_head(&fc->blocked_waitq);
 982	fuse_iqueue_init(&fc->iq, fiq_ops, fiq_priv);
 983	INIT_LIST_HEAD(&fc->bg_queue);
 984	INIT_LIST_HEAD(&fc->entry);
 985	INIT_LIST_HEAD(&fc->devices);
 986	atomic_set(&fc->num_waiting, 0);
 987	fc->max_background = FUSE_DEFAULT_MAX_BACKGROUND;
 988	fc->congestion_threshold = FUSE_DEFAULT_CONGESTION_THRESHOLD;
 989	atomic64_set(&fc->khctr, 0);
 990	fc->polled_files = RB_ROOT;
 991	fc->blocked = 0;
 992	fc->initialized = 0;
 993	fc->connected = 1;
 994	atomic64_set(&fc->attr_version, 1);
 995	atomic64_set(&fc->evict_ctr, 1);
 996	get_random_bytes(&fc->scramble_key, sizeof(fc->scramble_key));
 997	fc->pid_ns = get_pid_ns(task_active_pid_ns(current));
 998	fc->user_ns = get_user_ns(user_ns);
 999	fc->max_pages = FUSE_DEFAULT_MAX_PAGES_PER_REQ;
1000	fc->max_pages_limit = fuse_max_pages_limit;
1001	fc->name_max = FUSE_NAME_LOW_MAX;
1002	fc->timeout.req_timeout = 0;
1003
1004	if (IS_ENABLED(CONFIG_FUSE_PASSTHROUGH))
1005		fuse_backing_files_init(fc);
1006
1007	INIT_LIST_HEAD(&fc->mounts);
1008	list_add(&fm->fc_entry, &fc->mounts);
1009	fm->fc = fc;
1010}
1011EXPORT_SYMBOL_GPL(fuse_conn_init);
1012
1013static void delayed_release(struct rcu_head *p)
1014{
1015	struct fuse_conn *fc = container_of(p, struct fuse_conn, rcu);
1016
1017	fuse_uring_destruct(fc);
1018
1019	put_user_ns(fc->user_ns);
1020	fc->release(fc);
1021}
1022
1023void fuse_conn_put(struct fuse_conn *fc)
1024{
1025	struct fuse_iqueue *fiq = &fc->iq;
1026	struct fuse_sync_bucket *bucket;
1027
1028	if (!refcount_dec_and_test(&fc->count))
1029		return;
1030
1031	if (IS_ENABLED(CONFIG_FUSE_DAX))
1032		fuse_dax_conn_free(fc);
1033	if (fc->timeout.req_timeout)
1034		cancel_delayed_work_sync(&fc->timeout.work);
1035	cancel_work_sync(&fc->epoch_work);
1036	if (fiq->ops->release)
1037		fiq->ops->release(fiq);
1038	put_pid_ns(fc->pid_ns);
1039	bucket = rcu_dereference_protected(fc->curr_bucket, 1);
1040	if (bucket) {
1041		WARN_ON(atomic_read(&bucket->count) != 1);
1042		kfree(bucket);
1043	}
1044	if (IS_ENABLED(CONFIG_FUSE_PASSTHROUGH))
1045		fuse_backing_files_free(fc);
1046	call_rcu(&fc->rcu, delayed_release);
1047}
1048EXPORT_SYMBOL_GPL(fuse_conn_put);
1049
1050struct fuse_conn *fuse_conn_get(struct fuse_conn *fc)
1051{
1052	refcount_inc(&fc->count);
1053	return fc;
1054}
1055EXPORT_SYMBOL_GPL(fuse_conn_get);
1056
1057static struct inode *fuse_get_root_inode(struct super_block *sb, unsigned int mode)
1058{
1059	struct fuse_attr attr;
1060	memset(&attr, 0, sizeof(attr));
1061
1062	attr.mode = mode;
1063	attr.ino = FUSE_ROOT_ID;
1064	attr.nlink = 1;
1065	return fuse_iget(sb, FUSE_ROOT_ID, 0, &attr, 0, 0, 0);
1066}
1067
1068struct fuse_inode_handle {
1069	u64 nodeid;
1070	u32 generation;
1071};
1072
1073static struct dentry *fuse_get_dentry(struct super_block *sb,
1074				      struct fuse_inode_handle *handle)
1075{
1076	struct fuse_conn *fc = get_fuse_conn_super(sb);
1077	struct inode *inode;
1078	struct dentry *entry;
1079	int err = -ESTALE;
1080
1081	if (handle->nodeid == 0)
1082		goto out_err;
1083
1084	inode = ilookup5(sb, handle->nodeid, fuse_inode_eq, &handle->nodeid);
1085	if (!inode) {
1086		struct fuse_entry_out outarg;
1087		const struct qstr name = QSTR_INIT(".", 1);
1088
1089		if (!fc->export_support)
1090			goto out_err;
1091
1092		err = fuse_lookup_name(sb, handle->nodeid, &name, &outarg,
1093				       &inode);
1094		if (err && err != -ENOENT)
1095			goto out_err;
1096		if (err || !inode) {
1097			err = -ESTALE;
1098			goto out_err;
1099		}
1100		err = -EIO;
1101		if (get_node_id(inode) != handle->nodeid)
1102			goto out_iput;
1103	}
1104	err = -ESTALE;
1105	if (inode->i_generation != handle->generation)
1106		goto out_iput;
1107
1108	entry = d_obtain_alias(inode);
1109	if (!IS_ERR(entry) && get_node_id(inode) != FUSE_ROOT_ID)
1110		fuse_invalidate_entry_cache(entry);
1111
1112	return entry;
1113
1114 out_iput:
1115	iput(inode);
1116 out_err:
1117	return ERR_PTR(err);
1118}
1119
1120static int fuse_encode_fh(struct inode *inode, u32 *fh, int *max_len,
1121			   struct inode *parent)
1122{
1123	int len = parent ? 6 : 3;
1124	u64 nodeid;
1125	u32 generation;
1126
1127	if (*max_len < len) {
1128		*max_len = len;
1129		return  FILEID_INVALID;
1130	}
1131
1132	nodeid = get_fuse_inode(inode)->nodeid;
1133	generation = inode->i_generation;
1134
1135	fh[0] = (u32)(nodeid >> 32);
1136	fh[1] = (u32)(nodeid & 0xffffffff);
1137	fh[2] = generation;
1138
1139	if (parent) {
1140		nodeid = get_fuse_inode(parent)->nodeid;
1141		generation = parent->i_generation;
1142
1143		fh[3] = (u32)(nodeid >> 32);
1144		fh[4] = (u32)(nodeid & 0xffffffff);
1145		fh[5] = generation;
1146	}
1147
1148	*max_len = len;
1149	return parent ? FILEID_INO64_GEN_PARENT : FILEID_INO64_GEN;
1150}
1151
1152static struct dentry *fuse_fh_to_dentry(struct super_block *sb,
1153		struct fid *fid, int fh_len, int fh_type)
1154{
1155	struct fuse_inode_handle handle;
1156
1157	if ((fh_type != FILEID_INO64_GEN &&
1158	     fh_type != FILEID_INO64_GEN_PARENT) || fh_len < 3)
1159		return NULL;
1160
1161	handle.nodeid = (u64) fid->raw[0] << 32;
1162	handle.nodeid |= (u64) fid->raw[1];
1163	handle.generation = fid->raw[2];
1164	return fuse_get_dentry(sb, &handle);
1165}
1166
1167static struct dentry *fuse_fh_to_parent(struct super_block *sb,
1168		struct fid *fid, int fh_len, int fh_type)
1169{
1170	struct fuse_inode_handle parent;
1171
1172	if (fh_type != FILEID_INO64_GEN_PARENT || fh_len < 6)
1173		return NULL;
1174
1175	parent.nodeid = (u64) fid->raw[3] << 32;
1176	parent.nodeid |= (u64) fid->raw[4];
1177	parent.generation = fid->raw[5];
1178	return fuse_get_dentry(sb, &parent);
1179}
1180
1181static struct dentry *fuse_get_parent(struct dentry *child)
1182{
1183	struct inode *child_inode = d_inode(child);
1184	struct fuse_conn *fc = get_fuse_conn(child_inode);
1185	struct inode *inode;
1186	struct dentry *parent;
1187	struct fuse_entry_out outarg;
1188	int err;
1189
1190	if (!fc->export_support)
1191		return ERR_PTR(-ESTALE);
1192
1193	err = fuse_lookup_name(child_inode->i_sb, get_node_id(child_inode),
1194			       &dotdot_name, &outarg, &inode);
1195	if (err) {
1196		if (err == -ENOENT)
1197			return ERR_PTR(-ESTALE);
1198		return ERR_PTR(err);
1199	}
1200
1201	parent = d_obtain_alias(inode);
1202	if (!IS_ERR(parent) && get_node_id(inode) != FUSE_ROOT_ID)
1203		fuse_invalidate_entry_cache(parent);
1204
1205	return parent;
1206}
1207
1208/* only for fid encoding; no support for file handle */
1209static const struct export_operations fuse_export_fid_operations = {
1210	.encode_fh	= fuse_encode_fh,
1211};
1212
1213static const struct export_operations fuse_export_operations = {
1214	.fh_to_dentry	= fuse_fh_to_dentry,
1215	.fh_to_parent	= fuse_fh_to_parent,
1216	.encode_fh	= fuse_encode_fh,
1217	.get_parent	= fuse_get_parent,
1218};
1219
1220static const struct super_operations fuse_super_operations = {
1221	.alloc_inode    = fuse_alloc_inode,
1222	.free_inode     = fuse_free_inode,
1223	.evict_inode	= fuse_evict_inode,
1224	.write_inode	= fuse_write_inode,
1225	.drop_inode	= inode_just_drop,
1226	.umount_begin	= fuse_umount_begin,
1227	.statfs		= fuse_statfs,
1228	.sync_fs	= fuse_sync_fs,
1229	.show_options	= fuse_show_options,
1230};
1231
1232static void sanitize_global_limit(unsigned int *limit)
1233{
1234	/*
1235	 * The default maximum number of async requests is calculated to consume
1236	 * 1/2^13 of the total memory, assuming 392 bytes per request.
1237	 */
1238	if (*limit == 0)
1239		*limit = ((totalram_pages() << PAGE_SHIFT) >> 13) / 392;
1240
1241	if (*limit >= 1 << 16)
1242		*limit = (1 << 16) - 1;
1243}
1244
1245static int set_global_limit(const char *val, const struct kernel_param *kp)
1246{
1247	int rv;
1248
1249	rv = param_set_uint(val, kp);
1250	if (rv)
1251		return rv;
1252
1253	sanitize_global_limit((unsigned int *)kp->arg);
1254
1255	return 0;
1256}
1257
1258static void process_init_limits(struct fuse_conn *fc, struct fuse_init_out *arg)
1259{
1260	int cap_sys_admin = capable(CAP_SYS_ADMIN);
1261
1262	if (arg->minor < 13)
1263		return;
1264
1265	sanitize_global_limit(&max_user_bgreq);
1266	sanitize_global_limit(&max_user_congthresh);
1267
1268	spin_lock(&fc->bg_lock);
1269	if (arg->max_background) {
1270		fc->max_background = arg->max_background;
1271
1272		if (!cap_sys_admin && fc->max_background > max_user_bgreq)
1273			fc->max_background = max_user_bgreq;
1274	}
1275	if (arg->congestion_threshold) {
1276		fc->congestion_threshold = arg->congestion_threshold;
1277
1278		if (!cap_sys_admin &&
1279		    fc->congestion_threshold > max_user_congthresh)
1280			fc->congestion_threshold = max_user_congthresh;
1281	}
1282	spin_unlock(&fc->bg_lock);
1283}
1284
1285static void set_request_timeout(struct fuse_conn *fc, unsigned int timeout)
1286{
1287	fc->timeout.req_timeout = secs_to_jiffies(timeout);
1288	INIT_DELAYED_WORK(&fc->timeout.work, fuse_check_timeout);
1289	queue_delayed_work(system_percpu_wq, &fc->timeout.work,
1290			   fuse_timeout_timer_freq);
1291}
1292
1293static void init_server_timeout(struct fuse_conn *fc, unsigned int timeout)
1294{
1295	if (!timeout && !fuse_max_req_timeout && !fuse_default_req_timeout)
1296		return;
1297
1298	if (!timeout)
1299		timeout = fuse_default_req_timeout;
1300
1301	if (fuse_max_req_timeout) {
1302		if (timeout)
1303			timeout = min(fuse_max_req_timeout, timeout);
1304		else
1305			timeout = fuse_max_req_timeout;
1306	}
1307
1308	timeout = max(FUSE_TIMEOUT_TIMER_FREQ, timeout);
1309
1310	set_request_timeout(fc, timeout);
1311}
1312
1313struct fuse_init_args {
1314	struct fuse_args args;
1315	struct fuse_init_in in;
1316	struct fuse_init_out out;
1317};
1318
1319static void process_init_reply(struct fuse_mount *fm, struct fuse_args *args,
1320			       int error)
1321{
1322	struct fuse_conn *fc = fm->fc;
1323	struct fuse_init_args *ia = container_of(args, typeof(*ia), args);
1324	struct fuse_init_out *arg = &ia->out;
1325	bool ok = true;
1326
1327	if (error || arg->major != FUSE_KERNEL_VERSION)
1328		ok = false;
1329	else {
1330		unsigned long ra_pages;
1331		unsigned int timeout = 0;
1332
1333		process_init_limits(fc, arg);
1334
1335		if (arg->minor >= 6) {
1336			u64 flags = arg->flags;
1337
1338			if (flags & FUSE_INIT_EXT)
1339				flags |= (u64) arg->flags2 << 32;
1340
1341			ra_pages = arg->max_readahead / PAGE_SIZE;
1342			if (flags & FUSE_ASYNC_READ)
1343				fc->async_read = 1;
1344			if (!(flags & FUSE_POSIX_LOCKS))
1345				fc->no_lock = 1;
1346			if (arg->minor >= 17) {
1347				if (!(flags & FUSE_FLOCK_LOCKS))
1348					fc->no_flock = 1;
1349			} else {
1350				if (!(flags & FUSE_POSIX_LOCKS))
1351					fc->no_flock = 1;
1352			}
1353			if (flags & FUSE_ATOMIC_O_TRUNC)
1354				fc->atomic_o_trunc = 1;
1355			if (arg->minor >= 9) {
1356				/* LOOKUP has dependency on proto version */
1357				if (flags & FUSE_EXPORT_SUPPORT)
1358					fc->export_support = 1;
1359			}
1360			if (flags & FUSE_BIG_WRITES)
1361				fc->big_writes = 1;
1362			if (flags & FUSE_DONT_MASK)
1363				fc->dont_mask = 1;
1364			if (flags & FUSE_AUTO_INVAL_DATA)
1365				fc->auto_inval_data = 1;
1366			else if (flags & FUSE_EXPLICIT_INVAL_DATA)
1367				fc->explicit_inval_data = 1;
1368			if (flags & FUSE_DO_READDIRPLUS) {
1369				fc->do_readdirplus = 1;
1370				if (flags & FUSE_READDIRPLUS_AUTO)
1371					fc->readdirplus_auto = 1;
1372			}
1373			if (flags & FUSE_ASYNC_DIO)
1374				fc->async_dio = 1;
1375			if (flags & FUSE_WRITEBACK_CACHE)
1376				fc->writeback_cache = 1;
1377			if (flags & FUSE_PARALLEL_DIROPS)
1378				fc->parallel_dirops = 1;
1379			if (flags & FUSE_HANDLE_KILLPRIV)
1380				fc->handle_killpriv = 1;
1381			if (arg->time_gran && arg->time_gran <= 1000000000)
1382				fm->sb->s_time_gran = arg->time_gran;
1383			if ((flags & FUSE_POSIX_ACL)) {
1384				fc->default_permissions = 1;
1385				fc->posix_acl = 1;
1386			}
1387			if (flags & FUSE_CACHE_SYMLINKS)
1388				fc->cache_symlinks = 1;
1389			if (flags & FUSE_ABORT_ERROR)
1390				fc->abort_err = 1;
1391			if (flags & FUSE_MAX_PAGES) {
1392				fc->max_pages =
1393					min_t(unsigned int, fc->max_pages_limit,
1394					max_t(unsigned int, arg->max_pages, 1));
1395
1396				/*
1397				 * PATH_MAX file names might need two pages for
1398				 * ops like rename
1399				 */
1400				if (fc->max_pages > 1)
1401					fc->name_max = FUSE_NAME_MAX;
1402			}
1403			if (IS_ENABLED(CONFIG_FUSE_DAX)) {
1404				if (flags & FUSE_MAP_ALIGNMENT &&
1405				    !fuse_dax_check_alignment(fc, arg->map_alignment)) {
1406					ok = false;
1407				}
1408				if (flags & FUSE_HAS_INODE_DAX)
1409					fc->inode_dax = 1;
1410			}
1411			if (flags & FUSE_HANDLE_KILLPRIV_V2) {
1412				fc->handle_killpriv_v2 = 1;
1413				fm->sb->s_flags |= SB_NOSEC;
1414			}
1415			if (flags & FUSE_SETXATTR_EXT)
1416				fc->setxattr_ext = 1;
1417			if (flags & FUSE_SECURITY_CTX)
1418				fc->init_security = 1;
1419			if (flags & FUSE_CREATE_SUPP_GROUP)
1420				fc->create_supp_group = 1;
1421			if (flags & FUSE_DIRECT_IO_ALLOW_MMAP)
1422				fc->direct_io_allow_mmap = 1;
1423			/*
1424			 * max_stack_depth is the max stack depth of FUSE fs,
1425			 * so it has to be at least 1 to support passthrough
1426			 * to backing files.
1427			 *
1428			 * with max_stack_depth > 1, the backing files can be
1429			 * on a stacked fs (e.g. overlayfs) themselves and with
1430			 * max_stack_depth == 1, FUSE fs can be stacked as the
1431			 * underlying fs of a stacked fs (e.g. overlayfs).
1432			 *
1433			 * Also don't allow the combination of FUSE_PASSTHROUGH
1434			 * and FUSE_WRITEBACK_CACHE, current design doesn't handle
1435			 * them together.
1436			 */
1437			if (IS_ENABLED(CONFIG_FUSE_PASSTHROUGH) &&
1438			    (flags & FUSE_PASSTHROUGH) &&
1439			    arg->max_stack_depth > 0 &&
1440			    arg->max_stack_depth <= FILESYSTEM_MAX_STACK_DEPTH &&
1441			    !(flags & FUSE_WRITEBACK_CACHE))  {
1442				fc->passthrough = 1;
1443				fc->max_stack_depth = arg->max_stack_depth;
1444				fm->sb->s_stack_depth = arg->max_stack_depth;
1445			}
1446			if (flags & FUSE_NO_EXPORT_SUPPORT)
1447				fm->sb->s_export_op = &fuse_export_fid_operations;
1448			if (flags & FUSE_ALLOW_IDMAP) {
1449				if (fc->default_permissions)
1450					fm->sb->s_iflags &= ~SB_I_NOIDMAP;
1451				else
1452					ok = false;
1453			}
1454			if (flags & FUSE_OVER_IO_URING && fuse_uring_enabled())
1455				fc->io_uring = 1;
1456
1457			if (flags & FUSE_REQUEST_TIMEOUT)
1458				timeout = arg->request_timeout;
1459		} else {
1460			ra_pages = fc->max_read / PAGE_SIZE;
1461			fc->no_lock = 1;
1462			fc->no_flock = 1;
1463		}
1464
1465		init_server_timeout(fc, timeout);
1466
1467		fm->sb->s_bdi->ra_pages =
1468				min(fm->sb->s_bdi->ra_pages, ra_pages);
1469		fc->minor = arg->minor;
1470		fc->max_write = arg->minor < 5 ? 4096 : arg->max_write;
1471		fc->max_write = max_t(unsigned, 4096, fc->max_write);
1472		fc->conn_init = 1;
1473	}
1474	kfree(ia);
1475
1476	if (!ok) {
1477		fc->conn_init = 0;
1478		fc->conn_error = 1;
1479	}
1480
1481	fuse_set_initialized(fc);
1482	wake_up_all(&fc->blocked_waitq);
1483}
1484
1485static struct fuse_init_args *fuse_new_init(struct fuse_mount *fm)
1486{
1487	struct fuse_init_args *ia;
1488	u64 flags;
1489
1490	ia = kzalloc(sizeof(*ia), GFP_KERNEL | __GFP_NOFAIL);
1491
1492	ia->in.major = FUSE_KERNEL_VERSION;
1493	ia->in.minor = FUSE_KERNEL_MINOR_VERSION;
1494	ia->in.max_readahead = fm->sb->s_bdi->ra_pages * PAGE_SIZE;
1495	flags =
1496		FUSE_ASYNC_READ | FUSE_POSIX_LOCKS | FUSE_ATOMIC_O_TRUNC |
1497		FUSE_EXPORT_SUPPORT | FUSE_BIG_WRITES | FUSE_DONT_MASK |
1498		FUSE_SPLICE_WRITE | FUSE_SPLICE_MOVE | FUSE_SPLICE_READ |
1499		FUSE_FLOCK_LOCKS | FUSE_HAS_IOCTL_DIR | FUSE_AUTO_INVAL_DATA |
1500		FUSE_DO_READDIRPLUS | FUSE_READDIRPLUS_AUTO | FUSE_ASYNC_DIO |
1501		FUSE_WRITEBACK_CACHE | FUSE_NO_OPEN_SUPPORT |
1502		FUSE_PARALLEL_DIROPS | FUSE_HANDLE_KILLPRIV | FUSE_POSIX_ACL |
1503		FUSE_ABORT_ERROR | FUSE_MAX_PAGES | FUSE_CACHE_SYMLINKS |
1504		FUSE_NO_OPENDIR_SUPPORT | FUSE_EXPLICIT_INVAL_DATA |
1505		FUSE_HANDLE_KILLPRIV_V2 | FUSE_SETXATTR_EXT | FUSE_INIT_EXT |
1506		FUSE_SECURITY_CTX | FUSE_CREATE_SUPP_GROUP |
1507		FUSE_HAS_EXPIRE_ONLY | FUSE_DIRECT_IO_ALLOW_MMAP |
1508		FUSE_NO_EXPORT_SUPPORT | FUSE_HAS_RESEND | FUSE_ALLOW_IDMAP |
1509		FUSE_REQUEST_TIMEOUT;
1510#ifdef CONFIG_FUSE_DAX
1511	if (fm->fc->dax)
1512		flags |= FUSE_MAP_ALIGNMENT;
1513	if (fuse_is_inode_dax_mode(fm->fc->dax_mode))
1514		flags |= FUSE_HAS_INODE_DAX;
1515#endif
1516	if (fm->fc->auto_submounts)
1517		flags |= FUSE_SUBMOUNTS;
1518	if (IS_ENABLED(CONFIG_FUSE_PASSTHROUGH))
1519		flags |= FUSE_PASSTHROUGH;
1520
1521	/*
1522	 * This is just an information flag for fuse server. No need to check
1523	 * the reply - server is either sending IORING_OP_URING_CMD or not.
1524	 */
1525	if (fuse_uring_enabled())
1526		flags |= FUSE_OVER_IO_URING;
1527
1528	ia->in.flags = flags;
1529	ia->in.flags2 = flags >> 32;
1530
1531	ia->args.opcode = FUSE_INIT;
1532	ia->args.in_numargs = 1;
1533	ia->args.in_args[0].size = sizeof(ia->in);
1534	ia->args.in_args[0].value = &ia->in;
1535	ia->args.out_numargs = 1;
1536	/* Variable length argument used for backward compatibility
1537	   with interface version < 7.5.  Rest of init_out is zeroed
1538	   by do_get_request(), so a short reply is not a problem */
1539	ia->args.out_argvar = true;
1540	ia->args.out_args[0].size = sizeof(ia->out);
1541	ia->args.out_args[0].value = &ia->out;
1542	ia->args.force = true;
1543	ia->args.nocreds = true;
1544
1545	return ia;
1546}
1547
1548int fuse_send_init(struct fuse_mount *fm)
1549{
1550	struct fuse_init_args *ia = fuse_new_init(fm);
1551	int err;
1552
1553	if (fm->fc->sync_init) {
1554		err = fuse_simple_request(fm, &ia->args);
1555		/* Ignore size of init reply */
1556		if (err > 0)
1557			err = 0;
1558	} else {
1559		ia->args.end = process_init_reply;
1560		err = fuse_simple_background(fm, &ia->args, GFP_KERNEL);
1561		if (!err)
1562			return 0;
1563	}
1564	process_init_reply(fm, &ia->args, err);
1565	if (fm->fc->conn_error)
1566		return -ENOTCONN;
1567	return 0;
1568}
1569EXPORT_SYMBOL_GPL(fuse_send_init);
1570
1571void fuse_free_conn(struct fuse_conn *fc)
1572{
1573	WARN_ON(!list_empty(&fc->devices));
1574	kfree(fc);
1575}
1576EXPORT_SYMBOL_GPL(fuse_free_conn);
1577
1578static int fuse_bdi_init(struct fuse_conn *fc, struct super_block *sb)
1579{
1580	int err;
1581	char *suffix = "";
1582
1583	if (sb->s_bdev) {
1584		suffix = "-fuseblk";
1585		/*
1586		 * sb->s_bdi points to blkdev's bdi however we want to redirect
1587		 * it to our private bdi...
1588		 */
1589		bdi_put(sb->s_bdi);
1590		sb->s_bdi = &noop_backing_dev_info;
1591	}
1592	err = super_setup_bdi_name(sb, "%u:%u%s", MAJOR(fc->dev),
1593				   MINOR(fc->dev), suffix);
1594	if (err)
1595		return err;
1596
1597	sb->s_bdi->capabilities |= BDI_CAP_STRICTLIMIT;
1598
1599	/*
1600	 * For a single fuse filesystem use max 1% of dirty +
1601	 * writeback threshold.
1602	 *
1603	 * This gives about 1M of write buffer for memory maps on a
1604	 * machine with 1G and 10% dirty_ratio, which should be more
1605	 * than enough.
1606	 *
1607	 * Privileged users can raise it by writing to
1608	 *
1609	 *    /sys/class/bdi/<bdi>/max_ratio
1610	 */
1611	bdi_set_max_ratio(sb->s_bdi, 1);
1612
1613	return 0;
1614}
1615
1616struct fuse_dev *fuse_dev_alloc(void)
1617{
1618	struct fuse_dev *fud;
1619	struct list_head *pq;
1620
1621	fud = kzalloc(sizeof(struct fuse_dev), GFP_KERNEL);
1622	if (!fud)
1623		return NULL;
1624
1625	pq = kcalloc(FUSE_PQ_HASH_SIZE, sizeof(struct list_head), GFP_KERNEL);
1626	if (!pq) {
1627		kfree(fud);
1628		return NULL;
1629	}
1630
1631	fud->pq.processing = pq;
1632	fuse_pqueue_init(&fud->pq);
1633
1634	return fud;
1635}
1636EXPORT_SYMBOL_GPL(fuse_dev_alloc);
1637
1638void fuse_dev_install(struct fuse_dev *fud, struct fuse_conn *fc)
1639{
1640	fud->fc = fuse_conn_get(fc);
1641	spin_lock(&fc->lock);
1642	list_add_tail(&fud->entry, &fc->devices);
1643	spin_unlock(&fc->lock);
1644}
1645EXPORT_SYMBOL_GPL(fuse_dev_install);
1646
1647struct fuse_dev *fuse_dev_alloc_install(struct fuse_conn *fc)
1648{
1649	struct fuse_dev *fud;
1650
1651	fud = fuse_dev_alloc();
1652	if (!fud)
1653		return NULL;
1654
1655	fuse_dev_install(fud, fc);
1656	return fud;
1657}
1658EXPORT_SYMBOL_GPL(fuse_dev_alloc_install);
1659
1660void fuse_dev_free(struct fuse_dev *fud)
1661{
1662	struct fuse_conn *fc = fud->fc;
1663
1664	if (fc) {
1665		spin_lock(&fc->lock);
1666		list_del(&fud->entry);
1667		spin_unlock(&fc->lock);
1668
1669		fuse_conn_put(fc);
1670	}
1671	kfree(fud->pq.processing);
1672	kfree(fud);
1673}
1674EXPORT_SYMBOL_GPL(fuse_dev_free);
1675
1676static void fuse_fill_attr_from_inode(struct fuse_attr *attr,
1677				      const struct fuse_inode *fi)
1678{
1679	struct timespec64 atime = inode_get_atime(&fi->inode);
1680	struct timespec64 mtime = inode_get_mtime(&fi->inode);
1681	struct timespec64 ctime = inode_get_ctime(&fi->inode);
1682
1683	*attr = (struct fuse_attr){
1684		.ino		= fi->inode.i_ino,
1685		.size		= fi->inode.i_size,
1686		.blocks		= fi->inode.i_blocks,
1687		.atime		= atime.tv_sec,
1688		.mtime		= mtime.tv_sec,
1689		.ctime		= ctime.tv_sec,
1690		.atimensec	= atime.tv_nsec,
1691		.mtimensec	= mtime.tv_nsec,
1692		.ctimensec	= ctime.tv_nsec,
1693		.mode		= fi->inode.i_mode,
1694		.nlink		= fi->inode.i_nlink,
1695		.uid		= __kuid_val(fi->inode.i_uid),
1696		.gid		= __kgid_val(fi->inode.i_gid),
1697		.rdev		= fi->inode.i_rdev,
1698		.blksize	= 1u << fi->inode.i_blkbits,
1699	};
1700}
1701
1702static void fuse_sb_defaults(struct super_block *sb)
1703{
1704	sb->s_magic = FUSE_SUPER_MAGIC;
1705	sb->s_op = &fuse_super_operations;
1706	sb->s_xattr = fuse_xattr_handlers;
1707	sb->s_maxbytes = MAX_LFS_FILESIZE;
1708	sb->s_time_gran = 1;
1709	sb->s_export_op = &fuse_export_operations;
1710	sb->s_iflags |= SB_I_IMA_UNVERIFIABLE_SIGNATURE;
1711	sb->s_iflags |= SB_I_NOIDMAP;
1712	sb->s_iflags |= SB_I_NO_DATA_INTEGRITY;
1713	if (sb->s_user_ns != &init_user_ns)
1714		sb->s_iflags |= SB_I_UNTRUSTED_MOUNTER;
1715	sb->s_flags &= ~(SB_NOSEC | SB_I_VERSION);
1716}
1717
1718static int fuse_fill_super_submount(struct super_block *sb,
1719				    struct fuse_inode *parent_fi)
1720{
1721	struct fuse_mount *fm = get_fuse_mount_super(sb);
1722	struct super_block *parent_sb = parent_fi->inode.i_sb;
1723	struct fuse_attr root_attr;
1724	struct inode *root;
1725	struct fuse_submount_lookup *sl;
1726	struct fuse_inode *fi;
1727
1728	fuse_sb_defaults(sb);
1729	fm->sb = sb;
1730
1731	WARN_ON(sb->s_bdi != &noop_backing_dev_info);
1732	sb->s_bdi = bdi_get(parent_sb->s_bdi);
1733
1734	sb->s_xattr = parent_sb->s_xattr;
1735	sb->s_export_op = parent_sb->s_export_op;
1736	sb->s_time_gran = parent_sb->s_time_gran;
1737	sb->s_blocksize = parent_sb->s_blocksize;
1738	sb->s_blocksize_bits = parent_sb->s_blocksize_bits;
1739	sb->s_subtype = kstrdup(parent_sb->s_subtype, GFP_KERNEL);
1740	if (parent_sb->s_subtype && !sb->s_subtype)
1741		return -ENOMEM;
1742
1743	fuse_fill_attr_from_inode(&root_attr, parent_fi);
1744	root = fuse_iget(sb, parent_fi->nodeid, 0, &root_attr, 0, 0,
1745			 fuse_get_evict_ctr(fm->fc));
1746	/*
1747	 * This inode is just a duplicate, so it is not looked up and
1748	 * its nlookup should not be incremented.  fuse_iget() does
1749	 * that, though, so undo it here.
1750	 */
1751	fi = get_fuse_inode(root);
1752	fi->nlookup--;
1753
1754	set_default_d_op(sb, &fuse_dentry_operations);
1755	sb->s_root = d_make_root(root);
1756	if (!sb->s_root)
1757		return -ENOMEM;
1758
1759	/*
1760	 * Grab the parent's submount_lookup pointer and take a
1761	 * reference on the shared nlookup from the parent.  This is to
1762	 * prevent the last forget for this nodeid from getting
1763	 * triggered until all users have finished with it.
1764	 */
1765	sl = parent_fi->submount_lookup;
1766	WARN_ON(!sl);
1767	if (sl) {
1768		refcount_inc(&sl->count);
1769		fi->submount_lookup = sl;
1770	}
1771
1772	return 0;
1773}
1774
1775/* Filesystem context private data holds the FUSE inode of the mount point */
1776static int fuse_get_tree_submount(struct fs_context *fsc)
1777{
1778	struct fuse_mount *fm;
1779	struct fuse_inode *mp_fi = fsc->fs_private;
1780	struct fuse_conn *fc = get_fuse_conn(&mp_fi->inode);
1781	struct super_block *sb;
1782	int err;
1783
1784	fm = kzalloc(sizeof(struct fuse_mount), GFP_KERNEL);
1785	if (!fm)
1786		return -ENOMEM;
1787
1788	fm->fc = fuse_conn_get(fc);
1789	fsc->s_fs_info = fm;
1790	sb = sget_fc(fsc, NULL, set_anon_super_fc);
1791	if (fsc->s_fs_info)
1792		fuse_mount_destroy(fm);
1793	if (IS_ERR(sb))
1794		return PTR_ERR(sb);
1795
1796	/* Initialize superblock, making @mp_fi its root */
1797	err = fuse_fill_super_submount(sb, mp_fi);
1798	if (err) {
1799		deactivate_locked_super(sb);
1800		return err;
1801	}
1802
1803	down_write(&fc->killsb);
1804	list_add_tail(&fm->fc_entry, &fc->mounts);
1805	up_write(&fc->killsb);
1806
1807	sb->s_flags |= SB_ACTIVE;
1808	fsc->root = dget(sb->s_root);
1809
1810	return 0;
1811}
1812
1813static const struct fs_context_operations fuse_context_submount_ops = {
1814	.get_tree	= fuse_get_tree_submount,
1815};
1816
1817int fuse_init_fs_context_submount(struct fs_context *fsc)
1818{
1819	fsc->ops = &fuse_context_submount_ops;
1820	return 0;
1821}
1822EXPORT_SYMBOL_GPL(fuse_init_fs_context_submount);
1823
1824int fuse_fill_super_common(struct super_block *sb, struct fuse_fs_context *ctx)
1825{
1826	struct fuse_dev *fud = NULL;
1827	struct fuse_mount *fm = get_fuse_mount_super(sb);
1828	struct fuse_conn *fc = fm->fc;
1829	struct inode *root;
1830	struct dentry *root_dentry;
1831	int err;
1832
1833	err = -EINVAL;
1834	if (sb->s_flags & SB_MANDLOCK)
1835		goto err;
1836
1837	rcu_assign_pointer(fc->curr_bucket, fuse_sync_bucket_alloc());
1838	fuse_sb_defaults(sb);
1839
1840	if (ctx->is_bdev) {
1841#ifdef CONFIG_BLOCK
1842		err = -EINVAL;
1843		if (!sb_set_blocksize(sb, ctx->blksize))
1844			goto err;
1845#endif
1846		fc->sync_fs = 1;
1847	} else {
1848		sb->s_blocksize = PAGE_SIZE;
1849		sb->s_blocksize_bits = PAGE_SHIFT;
1850	}
1851
1852	sb->s_subtype = ctx->subtype;
1853	ctx->subtype = NULL;
1854	if (IS_ENABLED(CONFIG_FUSE_DAX)) {
1855		err = fuse_dax_conn_alloc(fc, ctx->dax_mode, ctx->dax_dev);
1856		if (err)
1857			goto err;
1858	}
1859
1860	if (ctx->fudptr) {
1861		err = -ENOMEM;
1862		fud = fuse_dev_alloc_install(fc);
1863		if (!fud)
1864			goto err_free_dax;
1865	}
1866
1867	fc->dev = sb->s_dev;
1868	fm->sb = sb;
1869	err = fuse_bdi_init(fc, sb);
1870	if (err)
1871		goto err_dev_free;
1872
1873	/* Handle umasking inside the fuse code */
1874	if (sb->s_flags & SB_POSIXACL)
1875		fc->dont_mask = 1;
1876	sb->s_flags |= SB_POSIXACL;
1877
1878	fc->default_permissions = ctx->default_permissions;
1879	fc->allow_other = ctx->allow_other;
1880	fc->user_id = ctx->user_id;
1881	fc->group_id = ctx->group_id;
1882	fc->legacy_opts_show = ctx->legacy_opts_show;
1883	fc->max_read = max_t(unsigned int, 4096, ctx->max_read);
1884	fc->destroy = ctx->destroy;
1885	fc->no_control = ctx->no_control;
1886	fc->no_force_umount = ctx->no_force_umount;
1887
1888	err = -ENOMEM;
1889	root = fuse_get_root_inode(sb, ctx->rootmode);
1890	set_default_d_op(sb, &fuse_dentry_operations);
1891	root_dentry = d_make_root(root);
1892	if (!root_dentry)
1893		goto err_dev_free;
1894
1895	mutex_lock(&fuse_mutex);
1896	err = -EINVAL;
1897	if (ctx->fudptr && *ctx->fudptr) {
1898		if (*ctx->fudptr == FUSE_DEV_SYNC_INIT)
1899			fc->sync_init = 1;
1900		else
1901			goto err_unlock;
1902	}
1903
1904	err = fuse_ctl_add_conn(fc);
1905	if (err)
1906		goto err_unlock;
1907
1908	list_add_tail(&fc->entry, &fuse_conn_list);
1909	sb->s_root = root_dentry;
1910	if (ctx->fudptr) {
1911		*ctx->fudptr = fud;
1912		wake_up_all(&fuse_dev_waitq);
1913	}
1914	mutex_unlock(&fuse_mutex);
1915	return 0;
1916
1917 err_unlock:
1918	mutex_unlock(&fuse_mutex);
1919	dput(root_dentry);
1920 err_dev_free:
1921	if (fud)
1922		fuse_dev_free(fud);
1923 err_free_dax:
1924	if (IS_ENABLED(CONFIG_FUSE_DAX))
1925		fuse_dax_conn_free(fc);
1926 err:
1927	return err;
1928}
1929EXPORT_SYMBOL_GPL(fuse_fill_super_common);
1930
1931static int fuse_fill_super(struct super_block *sb, struct fs_context *fsc)
1932{
1933	struct fuse_fs_context *ctx = fsc->fs_private;
1934	struct fuse_mount *fm;
1935	int err;
1936
1937	if (!ctx->file || !ctx->rootmode_present ||
1938	    !ctx->user_id_present || !ctx->group_id_present)
1939		return -EINVAL;
1940
1941	/*
1942	 * Require mount to happen from the same user namespace which
1943	 * opened /dev/fuse to prevent potential attacks.
1944	 */
1945	if ((ctx->file->f_op != &fuse_dev_operations) ||
1946	    (ctx->file->f_cred->user_ns != sb->s_user_ns))
1947		return -EINVAL;
1948	ctx->fudptr = &ctx->file->private_data;
1949
1950	err = fuse_fill_super_common(sb, ctx);
1951	if (err)
1952		return err;
1953	/* file->private_data shall be visible on all CPUs after this */
1954	smp_mb();
1955
1956	fm = get_fuse_mount_super(sb);
1957
1958	return fuse_send_init(fm);
1959}
1960
1961/*
1962 * This is the path where user supplied an already initialized fuse dev.  In
1963 * this case never create a new super if the old one is gone.
1964 */
1965static int fuse_set_no_super(struct super_block *sb, struct fs_context *fsc)
1966{
1967	return -ENOTCONN;
1968}
1969
1970static int fuse_test_super(struct super_block *sb, struct fs_context *fsc)
1971{
1972
1973	return fsc->sget_key == get_fuse_conn_super(sb);
1974}
1975
1976static int fuse_get_tree(struct fs_context *fsc)
1977{
1978	struct fuse_fs_context *ctx = fsc->fs_private;
1979	struct fuse_dev *fud;
1980	struct fuse_conn *fc;
1981	struct fuse_mount *fm;
1982	struct super_block *sb;
1983	int err;
1984
1985	fc = kmalloc(sizeof(*fc), GFP_KERNEL);
1986	if (!fc)
1987		return -ENOMEM;
1988
1989	fm = kzalloc(sizeof(*fm), GFP_KERNEL);
1990	if (!fm) {
1991		kfree(fc);
1992		return -ENOMEM;
1993	}
1994
1995	fuse_conn_init(fc, fm, fsc->user_ns, &fuse_dev_fiq_ops, NULL);
1996	fc->release = fuse_free_conn;
1997
1998	fsc->s_fs_info = fm;
1999
2000	if (ctx->fd_present)
2001		ctx->file = fget(ctx->fd);
2002
2003	if (IS_ENABLED(CONFIG_BLOCK) && ctx->is_bdev) {
2004		err = get_tree_bdev(fsc, fuse_fill_super);
2005		goto out;
2006	}
2007	/*
2008	 * While block dev mount can be initialized with a dummy device fd
2009	 * (found by device name), normal fuse mounts can't
2010	 */
2011	err = -EINVAL;
2012	if (!ctx->file)
2013		goto out;
2014
2015	/*
2016	 * Allow creating a fuse mount with an already initialized fuse
2017	 * connection
2018	 */
2019	fud = __fuse_get_dev(ctx->file);
2020	if (ctx->file->f_op == &fuse_dev_operations && fud) {
2021		fsc->sget_key = fud->fc;
2022		sb = sget_fc(fsc, fuse_test_super, fuse_set_no_super);
2023		err = PTR_ERR_OR_ZERO(sb);
2024		if (!IS_ERR(sb))
2025			fsc->root = dget(sb->s_root);
2026	} else {
2027		err = get_tree_nodev(fsc, fuse_fill_super);
2028	}
2029out:
2030	if (fsc->s_fs_info)
2031		fuse_mount_destroy(fm);
2032	if (ctx->file)
2033		fput(ctx->file);
2034	return err;
2035}
2036
2037static const struct fs_context_operations fuse_context_ops = {
2038	.free		= fuse_free_fsc,
2039	.parse_param	= fuse_parse_param,
2040	.reconfigure	= fuse_reconfigure,
2041	.get_tree	= fuse_get_tree,
2042};
2043
2044/*
2045 * Set up the filesystem mount context.
2046 */
2047static int fuse_init_fs_context(struct fs_context *fsc)
2048{
2049	struct fuse_fs_context *ctx;
2050
2051	ctx = kzalloc(sizeof(struct fuse_fs_context), GFP_KERNEL);
2052	if (!ctx)
2053		return -ENOMEM;
2054
2055	ctx->max_read = ~0;
2056	ctx->blksize = FUSE_DEFAULT_BLKSIZE;
2057	ctx->legacy_opts_show = true;
2058
2059#ifdef CONFIG_BLOCK
2060	if (fsc->fs_type == &fuseblk_fs_type) {
2061		ctx->is_bdev = true;
2062		ctx->destroy = true;
2063	}
2064#endif
2065
2066	fsc->fs_private = ctx;
2067	fsc->ops = &fuse_context_ops;
2068	return 0;
2069}
2070
2071bool fuse_mount_remove(struct fuse_mount *fm)
2072{
2073	struct fuse_conn *fc = fm->fc;
2074	bool last = false;
2075
2076	down_write(&fc->killsb);
2077	list_del_init(&fm->fc_entry);
2078	if (list_empty(&fc->mounts))
2079		last = true;
2080	up_write(&fc->killsb);
2081
2082	return last;
2083}
2084EXPORT_SYMBOL_GPL(fuse_mount_remove);
2085
2086void fuse_conn_destroy(struct fuse_mount *fm)
2087{
2088	struct fuse_conn *fc = fm->fc;
2089
2090	if (fc->destroy)
2091		fuse_send_destroy(fm);
2092
2093	fuse_abort_conn(fc);
2094	fuse_wait_aborted(fc);
2095
2096	if (!list_empty(&fc->entry)) {
2097		mutex_lock(&fuse_mutex);
2098		list_del(&fc->entry);
2099		fuse_ctl_remove_conn(fc);
2100		mutex_unlock(&fuse_mutex);
2101	}
2102}
2103EXPORT_SYMBOL_GPL(fuse_conn_destroy);
2104
2105static void fuse_sb_destroy(struct super_block *sb)
2106{
2107	struct fuse_mount *fm = get_fuse_mount_super(sb);
2108	bool last;
2109
2110	if (sb->s_root) {
2111		last = fuse_mount_remove(fm);
2112		if (last)
2113			fuse_conn_destroy(fm);
2114	}
2115}
2116
2117void fuse_mount_destroy(struct fuse_mount *fm)
2118{
2119	fuse_conn_put(fm->fc);
2120	kfree_rcu(fm, rcu);
2121}
2122EXPORT_SYMBOL(fuse_mount_destroy);
2123
2124static void fuse_kill_sb_anon(struct super_block *sb)
2125{
2126	fuse_sb_destroy(sb);
2127	kill_anon_super(sb);
2128	fuse_mount_destroy(get_fuse_mount_super(sb));
2129}
2130
2131static struct file_system_type fuse_fs_type = {
2132	.owner		= THIS_MODULE,
2133	.name		= "fuse",
2134	.fs_flags	= FS_HAS_SUBTYPE | FS_USERNS_MOUNT | FS_ALLOW_IDMAP,
2135	.init_fs_context = fuse_init_fs_context,
2136	.parameters	= fuse_fs_parameters,
2137	.kill_sb	= fuse_kill_sb_anon,
2138};
2139MODULE_ALIAS_FS("fuse");
2140
2141#ifdef CONFIG_BLOCK
2142static void fuse_kill_sb_blk(struct super_block *sb)
2143{
2144	fuse_sb_destroy(sb);
2145	kill_block_super(sb);
2146	fuse_mount_destroy(get_fuse_mount_super(sb));
2147}
2148
2149static struct file_system_type fuseblk_fs_type = {
2150	.owner		= THIS_MODULE,
2151	.name		= "fuseblk",
2152	.init_fs_context = fuse_init_fs_context,
2153	.parameters	= fuse_fs_parameters,
2154	.kill_sb	= fuse_kill_sb_blk,
2155	.fs_flags	= FS_REQUIRES_DEV | FS_HAS_SUBTYPE | FS_ALLOW_IDMAP,
2156};
2157MODULE_ALIAS_FS("fuseblk");
2158
2159static inline int register_fuseblk(void)
2160{
2161	return register_filesystem(&fuseblk_fs_type);
2162}
2163
2164static inline void unregister_fuseblk(void)
2165{
2166	unregister_filesystem(&fuseblk_fs_type);
2167}
2168#else
2169static inline int register_fuseblk(void)
2170{
2171	return 0;
2172}
2173
2174static inline void unregister_fuseblk(void)
2175{
2176}
2177#endif
2178
2179static void fuse_inode_init_once(void *foo)
2180{
2181	struct inode *inode = foo;
2182
2183	inode_init_once(inode);
2184}
2185
2186static int __init fuse_fs_init(void)
2187{
2188	int err;
2189
2190	fuse_inode_cachep = kmem_cache_create("fuse_inode",
2191			sizeof(struct fuse_inode), 0,
2192			SLAB_HWCACHE_ALIGN|SLAB_ACCOUNT|SLAB_RECLAIM_ACCOUNT,
2193			fuse_inode_init_once);
2194	err = -ENOMEM;
2195	if (!fuse_inode_cachep)
2196		goto out;
2197
2198	err = register_fuseblk();
2199	if (err)
2200		goto out2;
2201
2202	err = register_filesystem(&fuse_fs_type);
2203	if (err)
2204		goto out3;
2205
2206	err = fuse_sysctl_register();
2207	if (err)
2208		goto out4;
2209
2210	return 0;
2211
2212 out4:
2213	unregister_filesystem(&fuse_fs_type);
2214 out3:
2215	unregister_fuseblk();
2216 out2:
2217	kmem_cache_destroy(fuse_inode_cachep);
2218 out:
2219	return err;
2220}
2221
2222static void fuse_fs_cleanup(void)
2223{
2224	fuse_sysctl_unregister();
2225	unregister_filesystem(&fuse_fs_type);
2226	unregister_fuseblk();
2227
2228	/*
2229	 * Make sure all delayed rcu free inodes are flushed before we
2230	 * destroy cache.
2231	 */
2232	rcu_barrier();
2233	kmem_cache_destroy(fuse_inode_cachep);
2234}
2235
2236static struct kobject *fuse_kobj;
2237
2238static int fuse_sysfs_init(void)
2239{
2240	int err;
2241
2242	fuse_kobj = kobject_create_and_add("fuse", fs_kobj);
2243	if (!fuse_kobj) {
2244		err = -ENOMEM;
2245		goto out_err;
2246	}
2247
2248	err = sysfs_create_mount_point(fuse_kobj, "connections");
2249	if (err)
2250		goto out_fuse_unregister;
2251
2252	return 0;
2253
2254 out_fuse_unregister:
2255	kobject_put(fuse_kobj);
2256 out_err:
2257	return err;
2258}
2259
2260static void fuse_sysfs_cleanup(void)
2261{
2262	sysfs_remove_mount_point(fuse_kobj, "connections");
2263	kobject_put(fuse_kobj);
2264}
2265
2266static int __init fuse_init(void)
2267{
2268	int res;
2269
2270	pr_info("init (API version %i.%i)\n",
2271		FUSE_KERNEL_VERSION, FUSE_KERNEL_MINOR_VERSION);
2272
2273	INIT_LIST_HEAD(&fuse_conn_list);
2274	res = fuse_fs_init();
2275	if (res)
2276		goto err;
2277
2278	res = fuse_dev_init();
2279	if (res)
2280		goto err_fs_cleanup;
2281
2282	res = fuse_sysfs_init();
2283	if (res)
2284		goto err_dev_cleanup;
2285
2286	res = fuse_ctl_init();
2287	if (res)
2288		goto err_sysfs_cleanup;
2289
2290	fuse_dentry_tree_init();
2291
2292	sanitize_global_limit(&max_user_bgreq);
2293	sanitize_global_limit(&max_user_congthresh);
2294
2295	return 0;
2296
2297 err_sysfs_cleanup:
2298	fuse_sysfs_cleanup();
2299 err_dev_cleanup:
2300	fuse_dev_cleanup();
2301 err_fs_cleanup:
2302	fuse_fs_cleanup();
2303 err:
2304	return res;
2305}
2306
2307static void __exit fuse_exit(void)
2308{
2309	pr_debug("exit\n");
2310
2311	fuse_dentry_tree_cleanup();
2312	fuse_ctl_cleanup();
2313	fuse_sysfs_cleanup();
2314	fuse_fs_cleanup();
2315	fuse_dev_cleanup();
2316}
2317
2318module_init(fuse_init);
2319module_exit(fuse_exit);
~/ Read-only file preview.