1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * File operations used by nfsd. Some of these have been ripped from
4  * other parts of the kernel because they weren't exported, others
5  * are partial duplicates with added or changed functionality.
6  *
7  * Note that several functions dget() the dentry upon which they want
8  * to act, most notably those that create directory entries. Response
9  * dentry's are dput()'d if necessary in the release callback.
10  * So if you notice code paths that apparently fail to dput() the
11  * dentry, don't worry--they have been taken care of.
12  *
13  * Copyright (C) 1995-1999 Olaf Kirch <okir@monad.swb.de>
14  * Zerocpy NFS support (C) 2002 Hirokazu Takahashi <taka@valinux.co.jp>
15  */
16 
17 #include <linux/fs.h>
18 #include <linux/file.h>
19 #include <linux/splice.h>
20 #include <linux/falloc.h>
21 #include <linux/fcntl.h>
22 #include <linux/namei.h>
23 #include <linux/delay.h>
24 #include <linux/fsnotify.h>
25 #include <linux/posix_acl_xattr.h>
26 #include <linux/xattr.h>
27 #include <linux/jhash.h>
28 #include <linux/pagemap.h>
29 #include <linux/slab.h>
30 #include <linux/uaccess.h>
31 #include <linux/exportfs.h>
32 #include <linux/writeback.h>
33 #include <linux/security.h>
34 #include <linux/sunrpc/xdr.h>
35 
36 #include "xdr3.h"
37 
38 #ifdef CONFIG_NFSD_V4
39 #include "acl.h"
40 #include "idmap.h"
41 #include "xdr4.h"
42 #endif /* CONFIG_NFSD_V4 */
43 
44 #include "nfsd.h"
45 #include "vfs.h"
46 #include "filecache.h"
47 #include "trace.h"
48 
49 #define NFSDDBG_FACILITY		NFSDDBG_FILEOP
50 
51 bool nfsd_disable_splice_read __read_mostly;
52 
53 /**
54  * nfserrno - Map Linux errnos to NFS errnos
55  * @errno: POSIX(-ish) error code to be mapped
56  *
57  * Returns the appropriate (net-endian) nfserr_* (or nfs_ok if errno is 0). If
58  * it's an error we don't expect, log it once and return nfserr_io.
59  */
60 __be32
61 nfserrno (int errno)
62 {
63 	static struct {
64 		__be32	nfserr;
65 		int	syserr;
66 	} nfs_errtbl[] = {
67 		{ nfs_ok, 0 },
68 		{ nfserr_perm, -EPERM },
69 		{ nfserr_noent, -ENOENT },
70 		{ nfserr_io, -EIO },
71 		{ nfserr_nxio, -ENXIO },
72 		{ nfserr_fbig, -E2BIG },
73 		{ nfserr_stale, -EBADF },
74 		{ nfserr_acces, -EACCES },
75 		{ nfserr_exist, -EEXIST },
76 		{ nfserr_xdev, -EXDEV },
77 		{ nfserr_nodev, -ENODEV },
78 		{ nfserr_notdir, -ENOTDIR },
79 		{ nfserr_isdir, -EISDIR },
80 		{ nfserr_inval, -EINVAL },
81 		{ nfserr_fbig, -EFBIG },
82 		{ nfserr_nospc, -ENOSPC },
83 		{ nfserr_rofs, -EROFS },
84 		{ nfserr_mlink, -EMLINK },
85 		{ nfserr_nametoolong, -ENAMETOOLONG },
86 		{ nfserr_notempty, -ENOTEMPTY },
87 		{ nfserr_dquot, -EDQUOT },
88 		{ nfserr_stale, -ESTALE },
89 		{ nfserr_jukebox, -ETIMEDOUT },
90 		{ nfserr_jukebox, -ERESTARTSYS },
91 		{ nfserr_jukebox, -EAGAIN },
92 		{ nfserr_jukebox, -EWOULDBLOCK },
93 		{ nfserr_jukebox, -ENOMEM },
94 		{ nfserr_io, -ETXTBSY },
95 		{ nfserr_notsupp, -EOPNOTSUPP },
96 		{ nfserr_toosmall, -ETOOSMALL },
97 		{ nfserr_serverfault, -ESERVERFAULT },
98 		{ nfserr_serverfault, -ENFILE },
99 		{ nfserr_io, -EREMOTEIO },
100 		{ nfserr_stale, -EOPENSTALE },
101 		{ nfserr_io, -EUCLEAN },
102 		{ nfserr_perm, -ENOKEY },
103 		{ nfserr_no_grace, -ENOGRACE},
104 		{ nfserr_io, -EBADMSG },
105 	};
106 	int	i;
107 
108 	for (i = 0; i < ARRAY_SIZE(nfs_errtbl); i++) {
109 		if (nfs_errtbl[i].syserr == errno)
110 			return nfs_errtbl[i].nfserr;
111 	}
112 	WARN_ONCE(1, "nfsd: non-standard errno: %d\n", errno);
113 	return nfserr_io;
114 }
115 
116 /*
117  * Called from nfsd_lookup and encode_dirent. Check if we have crossed
118  * a mount point.
119  * Returns -EAGAIN or -ETIMEDOUT leaving *dpp and *expp unchanged,
120  *  or nfs_ok having possibly changed *dpp and *expp
121  */
122 int
123 nfsd_cross_mnt(struct svc_rqst *rqstp, struct dentry **dpp,
124 		        struct svc_export **expp)
125 {
126 	struct svc_export *exp = *expp, *exp2 = NULL;
127 	struct dentry *dentry = *dpp;
128 	struct path path = {.mnt = mntget(exp->ex_path.mnt),
129 			    .dentry = dget(dentry)};
130 	unsigned int follow_flags = 0;
131 	int err = 0;
132 
133 	if (exp->ex_flags & NFSEXP_CROSSMOUNT)
134 		follow_flags = LOOKUP_AUTOMOUNT;
135 
136 	err = follow_down(&path, follow_flags);
137 	if (err < 0)
138 		goto out;
139 	if (path.mnt == exp->ex_path.mnt && path.dentry == dentry &&
140 	    nfsd_mountpoint(dentry, exp) == 2) {
141 		/* This is only a mountpoint in some other namespace */
142 		path_put(&path);
143 		goto out;
144 	}
145 
146 	exp2 = rqst_exp_get_by_name(rqstp, &path);
147 	if (IS_ERR(exp2)) {
148 		err = PTR_ERR(exp2);
149 		/*
150 		 * We normally allow NFS clients to continue
151 		 * "underneath" a mountpoint that is not exported.
152 		 * The exception is V4ROOT, where no traversal is ever
153 		 * allowed without an explicit export of the new
154 		 * directory.
155 		 */
156 		if (err == -ENOENT && !(exp->ex_flags & NFSEXP_V4ROOT))
157 			err = 0;
158 		path_put(&path);
159 		goto out;
160 	}
161 	if (nfsd_v4client(rqstp) ||
162 		(exp->ex_flags & NFSEXP_CROSSMOUNT) || EX_NOHIDE(exp2)) {
163 		/* successfully crossed mount point */
164 		/*
165 		 * This is subtle: path.dentry is *not* on path.mnt
166 		 * at this point.  The only reason we are safe is that
167 		 * original mnt is pinned down by exp, so we should
168 		 * put path *before* putting exp
169 		 */
170 		*dpp = path.dentry;
171 		path.dentry = dentry;
172 		*expp = exp2;
173 		exp2 = exp;
174 	}
175 	path_put(&path);
176 	exp_put(exp2);
177 out:
178 	return err;
179 }
180 
181 static void follow_to_parent(struct path *path)
182 {
183 	struct dentry *dp;
184 
185 	while (path->dentry == path->mnt->mnt_root && follow_up(path))
186 		;
187 	dp = dget_parent(path->dentry);
188 	dput(path->dentry);
189 	path->dentry = dp;
190 }
191 
192 static int nfsd_lookup_parent(struct svc_rqst *rqstp, struct dentry *dparent, struct svc_export **exp, struct dentry **dentryp)
193 {
194 	struct svc_export *exp2;
195 	struct path path = {.mnt = mntget((*exp)->ex_path.mnt),
196 			    .dentry = dget(dparent)};
197 
198 	follow_to_parent(&path);
199 
200 	exp2 = rqst_exp_parent(rqstp, &path);
201 	if (PTR_ERR(exp2) == -ENOENT) {
202 		*dentryp = dget(dparent);
203 	} else if (IS_ERR(exp2)) {
204 		path_put(&path);
205 		return PTR_ERR(exp2);
206 	} else {
207 		*dentryp = dget(path.dentry);
208 		exp_put(*exp);
209 		*exp = exp2;
210 	}
211 	path_put(&path);
212 	return 0;
213 }
214 
215 /*
216  * For nfsd purposes, we treat V4ROOT exports as though there was an
217  * export at *every* directory.
218  * We return:
219  * '1' if this dentry *must* be an export point,
220  * '2' if it might be, if there is really a mount here, and
221  * '0' if there is no chance of an export point here.
222  */
223 int nfsd_mountpoint(struct dentry *dentry, struct svc_export *exp)
224 {
225 	if (!d_inode(dentry))
226 		return 0;
227 	if (exp->ex_flags & NFSEXP_V4ROOT)
228 		return 1;
229 	if (nfsd4_is_junction(dentry))
230 		return 1;
231 	if (d_managed(dentry))
232 		/*
233 		 * Might only be a mountpoint in a different namespace,
234 		 * but we need to check.
235 		 */
236 		return 2;
237 	return 0;
238 }
239 
240 __be32
241 nfsd_lookup_dentry(struct svc_rqst *rqstp, struct svc_fh *fhp,
242 		   const char *name, unsigned int len,
243 		   struct svc_export **exp_ret, struct dentry **dentry_ret)
244 {
245 	struct svc_export	*exp;
246 	struct dentry		*dparent;
247 	struct dentry		*dentry;
248 	int			host_err;
249 
250 	trace_nfsd_vfs_lookup(rqstp, fhp, name, len);
251 
252 	dparent = fhp->fh_dentry;
253 	exp = exp_get(fhp->fh_export);
254 
255 	/* Lookup the name, but don't follow links */
256 	if (isdotent(name, len)) {
257 		if (len==1)
258 			dentry = dget(dparent);
259 		else if (dparent != exp->ex_path.dentry)
260 			dentry = dget_parent(dparent);
261 		else if (!EX_NOHIDE(exp) && !nfsd_v4client(rqstp))
262 			dentry = dget(dparent); /* .. == . just like at / */
263 		else {
264 			/* checking mountpoint crossing is very different when stepping up */
265 			host_err = nfsd_lookup_parent(rqstp, dparent, &exp, &dentry);
266 			if (host_err)
267 				goto out_nfserr;
268 		}
269 	} else {
270 		dentry = lookup_one_unlocked(&nop_mnt_idmap,
271 					     &QSTR_LEN(name, len), dparent);
272 		host_err = PTR_ERR(dentry);
273 		if (IS_ERR(dentry))
274 			goto out_nfserr;
275 		if (nfsd_mountpoint(dentry, exp)) {
276 			host_err = nfsd_cross_mnt(rqstp, &dentry, &exp);
277 			if (host_err) {
278 				dput(dentry);
279 				goto out_nfserr;
280 			}
281 		}
282 	}
283 	*dentry_ret = dentry;
284 	*exp_ret = exp;
285 	return 0;
286 
287 out_nfserr:
288 	exp_put(exp);
289 	return nfserrno(host_err);
290 }
291 
292 /**
293  * nfsd_lookup - look up a single path component for nfsd
294  *
295  * @rqstp:   the request context
296  * @fhp:     the file handle of the directory
297  * @name:    the component name, or %NULL to look up parent
298  * @len:     length of name to examine
299  * @resfh:   pointer to pre-initialised filehandle to hold result.
300  *
301  * Look up one component of a pathname.
302  * N.B. After this call _both_ fhp and resfh need an fh_put
303  *
304  * If the lookup would cross a mountpoint, and the mounted filesystem
305  * is exported to the client with NFSEXP_NOHIDE, then the lookup is
306  * accepted as it stands and the mounted directory is
307  * returned. Otherwise the covered directory is returned.
308  * NOTE: this mountpoint crossing is not supported properly by all
309  *   clients and is explicitly disallowed for NFSv3
310  *
311  */
312 __be32
313 nfsd_lookup(struct svc_rqst *rqstp, struct svc_fh *fhp, const char *name,
314 	    unsigned int len, struct svc_fh *resfh)
315 {
316 	struct svc_export	*exp;
317 	struct dentry		*dentry;
318 	__be32 err;
319 
320 	err = fh_verify(rqstp, fhp, S_IFDIR, NFSD_MAY_EXEC);
321 	if (err)
322 		return err;
323 	err = nfsd_lookup_dentry(rqstp, fhp, name, len, &exp, &dentry);
324 	if (err)
325 		return err;
326 	err = check_nfsd_access(exp, rqstp, false);
327 	if (err)
328 		goto out;
329 	/*
330 	 * Note: we compose the file handle now, but as the
331 	 * dentry may be negative, it may need to be updated.
332 	 */
333 	err = fh_compose(resfh, exp, dentry, fhp);
334 	if (!err && d_really_is_negative(dentry))
335 		err = nfserr_noent;
336 out:
337 	dput(dentry);
338 	exp_put(exp);
339 	return err;
340 }
341 
342 static void
343 commit_reset_write_verifier(struct nfsd_net *nn, struct svc_rqst *rqstp,
344 			    int err)
345 {
346 	switch (err) {
347 	case -EAGAIN:
348 	case -ESTALE:
349 		/*
350 		 * Neither of these are the result of a problem with
351 		 * durable storage, so avoid a write verifier reset.
352 		 */
353 		break;
354 	default:
355 		nfsd_reset_write_verifier(nn);
356 		trace_nfsd_writeverf_reset(nn, rqstp, err);
357 	}
358 }
359 
360 /*
361  * Commit metadata changes to stable storage.
362  */
363 static int
364 commit_inode_metadata(struct inode *inode)
365 {
366 	const struct export_operations *export_ops = inode->i_sb->s_export_op;
367 
368 	if (export_ops->commit_metadata)
369 		return export_ops->commit_metadata(inode);
370 	return sync_inode_metadata(inode, 1);
371 }
372 
373 static int
374 commit_metadata(struct svc_fh *fhp)
375 {
376 	struct inode *inode = d_inode(fhp->fh_dentry);
377 
378 	if (!EX_ISSYNC(fhp->fh_export))
379 		return 0;
380 	return commit_inode_metadata(inode);
381 }
382 
383 /*
384  * Go over the attributes and take care of the small differences between
385  * NFS semantics and what Linux expects.
386  */
387 static void
388 nfsd_sanitize_attrs(struct inode *inode, struct iattr *iap)
389 {
390 	/* Ignore mode updates on symlinks */
391 	if (S_ISLNK(inode->i_mode))
392 		iap->ia_valid &= ~ATTR_MODE;
393 
394 	/* sanitize the mode change */
395 	if (iap->ia_valid & ATTR_MODE) {
396 		iap->ia_mode &= S_IALLUGO;
397 		iap->ia_mode |= (inode->i_mode & ~S_IALLUGO);
398 	}
399 
400 	/* Revoke setuid/setgid on chown */
401 	if (!S_ISDIR(inode->i_mode) &&
402 	    ((iap->ia_valid & ATTR_UID) || (iap->ia_valid & ATTR_GID))) {
403 		iap->ia_valid |= ATTR_KILL_PRIV;
404 		if (iap->ia_valid & ATTR_MODE) {
405 			/* we're setting mode too, just clear the s*id bits */
406 			iap->ia_mode &= ~S_ISUID;
407 			if (iap->ia_mode & S_IXGRP)
408 				iap->ia_mode &= ~S_ISGID;
409 		} else {
410 			/* set ATTR_KILL_* bits and let VFS handle it */
411 			iap->ia_valid |= ATTR_KILL_SUID;
412 			iap->ia_valid |=
413 				setattr_should_drop_sgid(&nop_mnt_idmap, inode);
414 		}
415 	}
416 }
417 
418 static __be32
419 nfsd_get_write_access(struct svc_rqst *rqstp, struct svc_fh *fhp,
420 		struct iattr *iap)
421 {
422 	struct inode *inode = d_inode(fhp->fh_dentry);
423 
424 	if (iap->ia_size < inode->i_size) {
425 		__be32 err;
426 
427 		err = nfsd_permission(&rqstp->rq_cred,
428 				      fhp->fh_export, fhp->fh_dentry,
429 				      NFSD_MAY_TRUNC | NFSD_MAY_OWNER_OVERRIDE);
430 		if (err)
431 			return err;
432 	}
433 	return nfserrno(get_write_access(inode));
434 }
435 
436 static int __nfsd_setattr(struct dentry *dentry, struct iattr *iap)
437 {
438 	int host_err;
439 
440 	if (iap->ia_valid & ATTR_SIZE) {
441 		/*
442 		 * RFC5661, Section 18.30.4:
443 		 *   Changing the size of a file with SETATTR indirectly
444 		 *   changes the time_modify and change attributes.
445 		 *
446 		 * (and similar for the older RFCs)
447 		 */
448 		struct iattr size_attr = {
449 			.ia_valid	= ATTR_SIZE | ATTR_CTIME | ATTR_MTIME,
450 			.ia_size	= iap->ia_size,
451 		};
452 
453 		if (iap->ia_size < 0)
454 			return -EFBIG;
455 
456 		host_err = notify_change(&nop_mnt_idmap, dentry, &size_attr, NULL);
457 		if (host_err)
458 			return host_err;
459 		iap->ia_valid &= ~ATTR_SIZE;
460 
461 		/*
462 		 * Avoid the additional setattr call below if the only other
463 		 * attribute that the client sends is the mtime, as we update
464 		 * it as part of the size change above.
465 		 */
466 		if ((iap->ia_valid & ~ATTR_MTIME) == 0)
467 			return 0;
468 	}
469 
470 	if (!iap->ia_valid)
471 		return 0;
472 
473 	iap->ia_valid |= ATTR_CTIME;
474 	return notify_change(&nop_mnt_idmap, dentry, iap, NULL);
475 }
476 
477 /**
478  * nfsd_setattr - Set various file attributes.
479  * @rqstp: controlling RPC transaction
480  * @fhp: filehandle of target
481  * @attr: attributes to set
482  * @guardtime: do not act if ctime.tv_sec does not match this timestamp
483  *
484  * This call may adjust the contents of @attr (in particular, this
485  * call may change the bits in the na_iattr.ia_valid field).
486  *
487  * Returns nfs_ok on success, otherwise an NFS status code is
488  * returned. Caller must release @fhp by calling fh_put in either
489  * case.
490  */
491 __be32
492 nfsd_setattr(struct svc_rqst *rqstp, struct svc_fh *fhp,
493 	     struct nfsd_attrs *attr, const struct timespec64 *guardtime)
494 {
495 	struct dentry	*dentry;
496 	struct inode	*inode;
497 	struct iattr	*iap = attr->na_iattr;
498 	int		accmode = NFSD_MAY_SATTR;
499 	umode_t		ftype = 0;
500 	__be32		err;
501 	int		host_err = 0;
502 	bool		get_write_count;
503 	bool		size_change = (iap->ia_valid & ATTR_SIZE);
504 	int		retries;
505 
506 	trace_nfsd_vfs_setattr(rqstp, fhp, iap, guardtime);
507 
508 	if (iap->ia_valid & ATTR_SIZE) {
509 		accmode |= NFSD_MAY_WRITE|NFSD_MAY_OWNER_OVERRIDE;
510 		ftype = S_IFREG;
511 	}
512 
513 	/*
514 	 * If utimes(2) and friends are called with times not NULL, we should
515 	 * not set NFSD_MAY_WRITE bit. Otherwise fh_verify->nfsd_permission
516 	 * will return EACCES, when the caller's effective UID does not match
517 	 * the owner of the file, and the caller is not privileged. In this
518 	 * situation, we should return EPERM(notify_change will return this).
519 	 */
520 	if (iap->ia_valid & (ATTR_ATIME | ATTR_MTIME)) {
521 		accmode |= NFSD_MAY_OWNER_OVERRIDE;
522 		if (!(iap->ia_valid & (ATTR_ATIME_SET | ATTR_MTIME_SET)))
523 			accmode |= NFSD_MAY_WRITE;
524 	}
525 
526 	/* Callers that do fh_verify should do the fh_want_write: */
527 	get_write_count = !fhp->fh_dentry;
528 
529 	/* Get inode */
530 	err = fh_verify(rqstp, fhp, ftype, accmode);
531 	if (err)
532 		return err;
533 	if (get_write_count) {
534 		host_err = fh_want_write(fhp);
535 		if (host_err)
536 			goto out;
537 	}
538 
539 	dentry = fhp->fh_dentry;
540 	inode = d_inode(dentry);
541 
542 	nfsd_sanitize_attrs(inode, iap);
543 
544 	/*
545 	 * The size case is special, it changes the file in addition to the
546 	 * attributes, and file systems don't expect it to be mixed with
547 	 * "random" attribute changes.  We thus split out the size change
548 	 * into a separate call to ->setattr, and do the rest as a separate
549 	 * setattr call.
550 	 */
551 	if (size_change) {
552 		err = nfsd_get_write_access(rqstp, fhp, iap);
553 		if (err)
554 			return err;
555 	}
556 
557 	inode_lock(inode);
558 	err = fh_fill_pre_attrs(fhp);
559 	if (err)
560 		goto out_unlock;
561 
562 	if (guardtime) {
563 		struct timespec64 ctime = inode_get_ctime(inode);
564 		if ((u32)guardtime->tv_sec != (u32)ctime.tv_sec ||
565 		    guardtime->tv_nsec != ctime.tv_nsec) {
566 			err = nfserr_notsync;
567 			goto out_fill_attrs;
568 		}
569 	}
570 
571 	for (retries = 1;;) {
572 		struct iattr attrs;
573 
574 		/*
575 		 * notify_change() can alter its iattr argument, making
576 		 * @iap unsuitable for submission multiple times. Make a
577 		 * copy for every loop iteration.
578 		 */
579 		attrs = *iap;
580 		host_err = __nfsd_setattr(dentry, &attrs);
581 		if (host_err != -EAGAIN || !retries--)
582 			break;
583 		if (!nfsd_wait_for_delegreturn(rqstp, inode))
584 			break;
585 	}
586 	if (attr->na_seclabel && attr->na_seclabel->len)
587 		attr->na_labelerr = security_inode_setsecctx(dentry,
588 			attr->na_seclabel->data, attr->na_seclabel->len);
589 	if (IS_ENABLED(CONFIG_FS_POSIX_ACL) && attr->na_pacl)
590 		attr->na_aclerr = set_posix_acl(&nop_mnt_idmap,
591 						dentry, ACL_TYPE_ACCESS,
592 						attr->na_pacl);
593 	if (IS_ENABLED(CONFIG_FS_POSIX_ACL) &&
594 	    !attr->na_aclerr && attr->na_dpacl && S_ISDIR(inode->i_mode))
595 		attr->na_aclerr = set_posix_acl(&nop_mnt_idmap,
596 						dentry, ACL_TYPE_DEFAULT,
597 						attr->na_dpacl);
598 out_fill_attrs:
599 	/*
600 	 * RFC 1813 Section 3.3.2 does not mandate that an NFS server
601 	 * returns wcc_data for SETATTR. Some client implementations
602 	 * depend on receiving wcc_data, however, to sort out partial
603 	 * updates (eg., the client requested that size and mode be
604 	 * modified, but the server changed only the file mode).
605 	 */
606 	fh_fill_post_attrs(fhp);
607 out_unlock:
608 	inode_unlock(inode);
609 	if (size_change)
610 		put_write_access(inode);
611 out:
612 	if (!host_err)
613 		host_err = commit_metadata(fhp);
614 	return err != 0 ? err : nfserrno(host_err);
615 }
616 
617 #if defined(CONFIG_NFSD_V4)
618 /*
619  * NFS junction information is stored in an extended attribute.
620  */
621 #define NFSD_JUNCTION_XATTR_NAME	XATTR_TRUSTED_PREFIX "junction.nfs"
622 
623 /**
624  * nfsd4_is_junction - Test if an object could be an NFS junction
625  *
626  * @dentry: object to test
627  *
628  * Returns 1 if "dentry" appears to contain NFS junction information.
629  * Otherwise 0 is returned.
630  */
631 int nfsd4_is_junction(struct dentry *dentry)
632 {
633 	struct inode *inode = d_inode(dentry);
634 
635 	if (inode == NULL)
636 		return 0;
637 	if (inode->i_mode & S_IXUGO)
638 		return 0;
639 	if (!(inode->i_mode & S_ISVTX))
640 		return 0;
641 	if (vfs_getxattr(&nop_mnt_idmap, dentry, NFSD_JUNCTION_XATTR_NAME,
642 			 NULL, 0) <= 0)
643 		return 0;
644 	return 1;
645 }
646 
647 static struct nfsd4_compound_state *nfsd4_get_cstate(struct svc_rqst *rqstp)
648 {
649 	return &((struct nfsd4_compoundres *)rqstp->rq_resp)->cstate;
650 }
651 
652 __be32 nfsd4_clone_file_range(struct svc_rqst *rqstp,
653 		struct nfsd_file *nf_src, u64 src_pos,
654 		struct nfsd_file *nf_dst, u64 dst_pos,
655 		u64 count, bool sync)
656 {
657 	struct file *src = nf_src->nf_file;
658 	struct file *dst = nf_dst->nf_file;
659 	errseq_t since;
660 	loff_t cloned;
661 	__be32 ret = 0;
662 
663 	since = READ_ONCE(dst->f_wb_err);
664 	cloned = vfs_clone_file_range(src, src_pos, dst, dst_pos, count, 0);
665 	if (cloned < 0) {
666 		ret = nfserrno(cloned);
667 		goto out_err;
668 	}
669 	if (count && cloned != count) {
670 		ret = nfserrno(-EINVAL);
671 		goto out_err;
672 	}
673 	if (sync) {
674 		loff_t dst_end = count ? dst_pos + count - 1 : LLONG_MAX;
675 		int status = vfs_fsync_range(dst, dst_pos, dst_end, 0);
676 
677 		if (!status)
678 			status = filemap_check_wb_err(dst->f_mapping, since);
679 		if (!status)
680 			status = commit_inode_metadata(file_inode(src));
681 		if (status < 0) {
682 			struct nfsd_net *nn = net_generic(nf_dst->nf_net,
683 							  nfsd_net_id);
684 
685 			trace_nfsd_clone_file_range_err(rqstp,
686 					&nfsd4_get_cstate(rqstp)->save_fh,
687 					src_pos,
688 					&nfsd4_get_cstate(rqstp)->current_fh,
689 					dst_pos,
690 					count, status);
691 			commit_reset_write_verifier(nn, rqstp, status);
692 			ret = nfserrno(status);
693 		}
694 	}
695 out_err:
696 	return ret;
697 }
698 
699 ssize_t nfsd_copy_file_range(struct file *src, u64 src_pos, struct file *dst,
700 			     u64 dst_pos, u64 count)
701 {
702 	ssize_t ret;
703 
704 	/*
705 	 * Limit copy to 4MB to prevent indefinitely blocking an nfsd
706 	 * thread and client rpc slot.  The choice of 4MB is somewhat
707 	 * arbitrary.  We might instead base this on r/wsize, or make it
708 	 * tunable, or use a time instead of a byte limit, or implement
709 	 * asynchronous copy.  In theory a client could also recognize a
710 	 * limit like this and pipeline multiple COPY requests.
711 	 */
712 	count = min_t(u64, count, 1 << 22);
713 	ret = vfs_copy_file_range(src, src_pos, dst, dst_pos, count, 0);
714 
715 	if (ret == -EOPNOTSUPP || ret == -EXDEV)
716 		ret = vfs_copy_file_range(src, src_pos, dst, dst_pos, count,
717 					  COPY_FILE_SPLICE);
718 	return ret;
719 }
720 
721 __be32 nfsd4_vfs_fallocate(struct svc_rqst *rqstp, struct svc_fh *fhp,
722 			   struct file *file, loff_t offset, loff_t len,
723 			   int flags)
724 {
725 	int error;
726 
727 	if (!S_ISREG(file_inode(file)->i_mode))
728 		return nfserr_inval;
729 
730 	error = vfs_fallocate(file, flags, offset, len);
731 	if (!error)
732 		error = commit_metadata(fhp);
733 
734 	return nfserrno(error);
735 }
736 #endif /* defined(CONFIG_NFSD_V4) */
737 
738 /*
739  * Check server access rights to a file system object
740  */
741 struct accessmap {
742 	u32		access;
743 	int		how;
744 };
745 static struct accessmap	nfs3_regaccess[] = {
746     {	NFS3_ACCESS_READ,	NFSD_MAY_READ			},
747     {	NFS3_ACCESS_EXECUTE,	NFSD_MAY_EXEC			},
748     {	NFS3_ACCESS_MODIFY,	NFSD_MAY_WRITE|NFSD_MAY_TRUNC	},
749     {	NFS3_ACCESS_EXTEND,	NFSD_MAY_WRITE			},
750 
751 #ifdef CONFIG_NFSD_V4
752     {	NFS4_ACCESS_XAREAD,	NFSD_MAY_READ			},
753     {	NFS4_ACCESS_XAWRITE,	NFSD_MAY_WRITE			},
754     {	NFS4_ACCESS_XALIST,	NFSD_MAY_READ			},
755 #endif
756 
757     {	0,			0				}
758 };
759 
760 static struct accessmap	nfs3_diraccess[] = {
761     {	NFS3_ACCESS_READ,	NFSD_MAY_READ			},
762     {	NFS3_ACCESS_LOOKUP,	NFSD_MAY_EXEC			},
763     {	NFS3_ACCESS_MODIFY,	NFSD_MAY_EXEC|NFSD_MAY_WRITE|NFSD_MAY_TRUNC},
764     {	NFS3_ACCESS_EXTEND,	NFSD_MAY_EXEC|NFSD_MAY_WRITE	},
765     {	NFS3_ACCESS_DELETE,	NFSD_MAY_REMOVE			},
766 
767 #ifdef CONFIG_NFSD_V4
768     {	NFS4_ACCESS_XAREAD,	NFSD_MAY_READ			},
769     {	NFS4_ACCESS_XAWRITE,	NFSD_MAY_WRITE			},
770     {	NFS4_ACCESS_XALIST,	NFSD_MAY_READ			},
771 #endif
772 
773     {	0,			0				}
774 };
775 
776 static struct accessmap	nfs3_anyaccess[] = {
777 	/* Some clients - Solaris 2.6 at least, make an access call
778 	 * to the server to check for access for things like /dev/null
779 	 * (which really, the server doesn't care about).  So
780 	 * We provide simple access checking for them, looking
781 	 * mainly at mode bits, and we make sure to ignore read-only
782 	 * filesystem checks
783 	 */
784     {	NFS3_ACCESS_READ,	NFSD_MAY_READ			},
785     {	NFS3_ACCESS_EXECUTE,	NFSD_MAY_EXEC			},
786     {	NFS3_ACCESS_MODIFY,	NFSD_MAY_WRITE|NFSD_MAY_LOCAL_ACCESS	},
787     {	NFS3_ACCESS_EXTEND,	NFSD_MAY_WRITE|NFSD_MAY_LOCAL_ACCESS	},
788 
789     {	0,			0				}
790 };
791 
792 __be32
793 nfsd_access(struct svc_rqst *rqstp, struct svc_fh *fhp, u32 *access, u32 *supported)
794 {
795 	struct accessmap	*map;
796 	struct svc_export	*export;
797 	struct dentry		*dentry;
798 	u32			query, result = 0, sresult = 0;
799 	__be32			error;
800 
801 	error = fh_verify(rqstp, fhp, 0, NFSD_MAY_NOP);
802 	if (error)
803 		goto out;
804 
805 	export = fhp->fh_export;
806 	dentry = fhp->fh_dentry;
807 
808 	if (d_is_reg(dentry))
809 		map = nfs3_regaccess;
810 	else if (d_is_dir(dentry))
811 		map = nfs3_diraccess;
812 	else
813 		map = nfs3_anyaccess;
814 
815 
816 	query = *access;
817 	for  (; map->access; map++) {
818 		if (map->access & query) {
819 			__be32 err2;
820 
821 			sresult |= map->access;
822 
823 			err2 = nfsd_permission(&rqstp->rq_cred, export,
824 					       dentry, map->how);
825 			switch (err2) {
826 			case nfs_ok:
827 				result |= map->access;
828 				break;
829 
830 			/* the following error codes just mean the access was not allowed,
831 			 * rather than an error occurred */
832 			case nfserr_rofs:
833 			case nfserr_acces:
834 			case nfserr_perm:
835 				/* simply don't "or" in the access bit. */
836 				break;
837 			default:
838 				error = err2;
839 				goto out;
840 			}
841 		}
842 	}
843 	*access = result;
844 	if (supported)
845 		*supported = sresult;
846 
847  out:
848 	return error;
849 }
850 
851 int nfsd_open_break_lease(struct inode *inode, int access)
852 {
853 	unsigned int mode;
854 
855 	if (access & NFSD_MAY_NOT_BREAK_LEASE)
856 		return 0;
857 	mode = (access & NFSD_MAY_WRITE) ? O_WRONLY : O_RDONLY;
858 	return break_lease(inode, mode | O_NONBLOCK);
859 }
860 
861 /*
862  * Open an existing file or directory.
863  * The may_flags argument indicates the type of open (read/write/lock)
864  * and additional flags.
865  * N.B. After this call fhp needs an fh_put
866  */
867 static int
868 __nfsd_open(struct svc_fh *fhp, umode_t type, int may_flags, struct file **filp)
869 {
870 	struct path	path;
871 	struct inode	*inode;
872 	struct file	*file;
873 	int		flags = O_RDONLY|O_LARGEFILE;
874 	int		host_err = -EPERM;
875 
876 	path.mnt = fhp->fh_export->ex_path.mnt;
877 	path.dentry = fhp->fh_dentry;
878 	inode = d_inode(path.dentry);
879 
880 	if (IS_APPEND(inode) && (may_flags & NFSD_MAY_WRITE))
881 		goto out;
882 
883 	if (!inode->i_fop)
884 		goto out;
885 
886 	host_err = nfsd_open_break_lease(inode, may_flags);
887 	if (host_err) /* NOMEM or WOULDBLOCK */
888 		goto out;
889 
890 	if (may_flags & NFSD_MAY_WRITE) {
891 		if (may_flags & NFSD_MAY_READ)
892 			flags = O_RDWR|O_LARGEFILE;
893 		else
894 			flags = O_WRONLY|O_LARGEFILE;
895 	}
896 
897 	file = dentry_open(&path, flags, current_cred());
898 	if (IS_ERR(file)) {
899 		host_err = PTR_ERR(file);
900 		goto out;
901 	}
902 
903 	host_err = security_file_post_open(file, may_flags);
904 	if (host_err) {
905 		fput(file);
906 		goto out;
907 	}
908 
909 	*filp = file;
910 out:
911 	return host_err;
912 }
913 
914 __be32
915 nfsd_open(struct svc_rqst *rqstp, struct svc_fh *fhp, umode_t type,
916 		int may_flags, struct file **filp)
917 {
918 	__be32 err;
919 	int host_err;
920 	bool retried = false;
921 
922 	/*
923 	 * If we get here, then the client has already done an "open",
924 	 * and (hopefully) checked permission - so allow OWNER_OVERRIDE
925 	 * in case a chmod has now revoked permission.
926 	 *
927 	 * Arguably we should also allow the owner override for
928 	 * directories, but we never have and it doesn't seem to have
929 	 * caused anyone a problem.  If we were to change this, note
930 	 * also that our filldir callbacks would need a variant of
931 	 * lookup_one_positive_unlocked() that doesn't check permissions.
932 	 */
933 	if (type == S_IFREG)
934 		may_flags |= NFSD_MAY_OWNER_OVERRIDE;
935 retry:
936 	err = fh_verify(rqstp, fhp, type, may_flags);
937 	if (!err) {
938 		host_err = __nfsd_open(fhp, type, may_flags, filp);
939 		if (host_err == -EOPENSTALE && !retried) {
940 			retried = true;
941 			fh_put(fhp);
942 			goto retry;
943 		}
944 		err = nfserrno(host_err);
945 	}
946 	return err;
947 }
948 
949 /**
950  * nfsd_open_verified - Open a regular file for the filecache
951  * @fhp: NFS filehandle of the file to open
952  * @may_flags: internal permission flags
953  * @filp: OUT: open "struct file *"
954  *
955  * Returns zero on success, or a negative errno value.
956  */
957 int
958 nfsd_open_verified(struct svc_fh *fhp, int may_flags, struct file **filp)
959 {
960 	return __nfsd_open(fhp, S_IFREG, may_flags, filp);
961 }
962 
963 /*
964  * Grab and keep cached pages associated with a file in the svc_rqst
965  * so that they can be passed to the network sendmsg routines
966  * directly. They will be released after the sending has completed.
967  *
968  * Return values: Number of bytes consumed, or -EIO if there are no
969  * remaining pages in rqstp->rq_pages.
970  */
971 static int
972 nfsd_splice_actor(struct pipe_inode_info *pipe, struct pipe_buffer *buf,
973 		  struct splice_desc *sd)
974 {
975 	struct svc_rqst *rqstp = sd->u.data;
976 	struct page *page = buf->page;	// may be a compound one
977 	unsigned offset = buf->offset;
978 	struct page *last_page;
979 
980 	last_page = page + (offset + sd->len - 1) / PAGE_SIZE;
981 	for (page += offset / PAGE_SIZE; page <= last_page; page++) {
982 		/*
983 		 * Skip page replacement when extending the contents of the
984 		 * current page.  But note that we may get two zero_pages in a
985 		 * row from shmem.
986 		 */
987 		if (page == *(rqstp->rq_next_page - 1) &&
988 		    offset_in_page(rqstp->rq_res.page_base +
989 				   rqstp->rq_res.page_len))
990 			continue;
991 		if (unlikely(!svc_rqst_replace_page(rqstp, page)))
992 			return -EIO;
993 	}
994 	if (rqstp->rq_res.page_len == 0)	// first call
995 		rqstp->rq_res.page_base = offset % PAGE_SIZE;
996 	rqstp->rq_res.page_len += sd->len;
997 	return sd->len;
998 }
999 
1000 static int nfsd_direct_splice_actor(struct pipe_inode_info *pipe,
1001 				    struct splice_desc *sd)
1002 {
1003 	return __splice_from_pipe(pipe, sd, nfsd_splice_actor);
1004 }
1005 
1006 static u32 nfsd_eof_on_read(struct file *file, loff_t offset, ssize_t len,
1007 		size_t expected)
1008 {
1009 	if (expected != 0 && len == 0)
1010 		return 1;
1011 	if (offset+len >= i_size_read(file_inode(file)))
1012 		return 1;
1013 	return 0;
1014 }
1015 
1016 static __be32 nfsd_finish_read(struct svc_rqst *rqstp, struct svc_fh *fhp,
1017 			       struct file *file, loff_t offset,
1018 			       unsigned long *count, u32 *eof, ssize_t host_err)
1019 {
1020 	if (host_err >= 0) {
1021 		struct nfsd_net *nn = net_generic(SVC_NET(rqstp), nfsd_net_id);
1022 
1023 		nfsd_stats_io_read_add(nn, fhp->fh_export, host_err);
1024 		*eof = nfsd_eof_on_read(file, offset, host_err, *count);
1025 		*count = host_err;
1026 		fsnotify_access(file);
1027 		trace_nfsd_read_io_done(rqstp, fhp, offset, *count);
1028 		return 0;
1029 	} else {
1030 		trace_nfsd_read_err(rqstp, fhp, offset, host_err);
1031 		return nfserrno(host_err);
1032 	}
1033 }
1034 
1035 /**
1036  * nfsd_splice_read - Perform a VFS read using a splice pipe
1037  * @rqstp: RPC transaction context
1038  * @fhp: file handle of file to be read
1039  * @file: opened struct file of file to be read
1040  * @offset: starting byte offset
1041  * @count: IN: requested number of bytes; OUT: number of bytes read
1042  * @eof: OUT: set non-zero if operation reached the end of the file
1043  *
1044  * Returns nfs_ok on success, otherwise an nfserr stat value is
1045  * returned.
1046  */
1047 __be32 nfsd_splice_read(struct svc_rqst *rqstp, struct svc_fh *fhp,
1048 			struct file *file, loff_t offset, unsigned long *count,
1049 			u32 *eof)
1050 {
1051 	struct splice_desc sd = {
1052 		.len		= 0,
1053 		.total_len	= *count,
1054 		.pos		= offset,
1055 		.u.data		= rqstp,
1056 	};
1057 	ssize_t host_err;
1058 
1059 	trace_nfsd_read_splice(rqstp, fhp, offset, *count);
1060 	host_err = rw_verify_area(READ, file, &offset, *count);
1061 	if (!host_err)
1062 		host_err = splice_direct_to_actor(file, &sd,
1063 						  nfsd_direct_splice_actor);
1064 	return nfsd_finish_read(rqstp, fhp, file, offset, count, eof, host_err);
1065 }
1066 
1067 /**
1068  * nfsd_iter_read - Perform a VFS read using an iterator
1069  * @rqstp: RPC transaction context
1070  * @fhp: file handle of file to be read
1071  * @file: opened struct file of file to be read
1072  * @offset: starting byte offset
1073  * @count: IN: requested number of bytes; OUT: number of bytes read
1074  * @base: offset in first page of read buffer
1075  * @eof: OUT: set non-zero if operation reached the end of the file
1076  *
1077  * Some filesystems or situations cannot use nfsd_splice_read. This
1078  * function is the slightly less-performant fallback for those cases.
1079  *
1080  * Returns nfs_ok on success, otherwise an nfserr stat value is
1081  * returned.
1082  */
1083 __be32 nfsd_iter_read(struct svc_rqst *rqstp, struct svc_fh *fhp,
1084 		      struct file *file, loff_t offset, unsigned long *count,
1085 		      unsigned int base, u32 *eof)
1086 {
1087 	unsigned long v, total;
1088 	struct iov_iter iter;
1089 	loff_t ppos = offset;
1090 	ssize_t host_err;
1091 	size_t len;
1092 
1093 	v = 0;
1094 	total = *count;
1095 	while (total) {
1096 		len = min_t(size_t, total, PAGE_SIZE - base);
1097 		bvec_set_page(&rqstp->rq_bvec[v], *(rqstp->rq_next_page++),
1098 			      len, base);
1099 		total -= len;
1100 		++v;
1101 		base = 0;
1102 	}
1103 	WARN_ON_ONCE(v > rqstp->rq_maxpages);
1104 
1105 	trace_nfsd_read_vector(rqstp, fhp, offset, *count);
1106 	iov_iter_bvec(&iter, ITER_DEST, rqstp->rq_bvec, v, *count);
1107 	host_err = vfs_iter_read(file, &iter, &ppos, 0);
1108 	return nfsd_finish_read(rqstp, fhp, file, offset, count, eof, host_err);
1109 }
1110 
1111 /*
1112  * Gathered writes: If another process is currently writing to the file,
1113  * there's a high chance this is another nfsd (triggered by a bulk write
1114  * from a client's biod). Rather than syncing the file with each write
1115  * request, we sleep for 10 msec.
1116  *
1117  * I don't know if this roughly approximates C. Juszak's idea of
1118  * gathered writes, but it's a nice and simple solution (IMHO), and it
1119  * seems to work:-)
1120  *
1121  * Note: we do this only in the NFSv2 case, since v3 and higher have a
1122  * better tool (separate unstable writes and commits) for solving this
1123  * problem.
1124  */
1125 static int wait_for_concurrent_writes(struct file *file)
1126 {
1127 	struct inode *inode = file_inode(file);
1128 	static ino_t last_ino;
1129 	static dev_t last_dev;
1130 	int err = 0;
1131 
1132 	if (atomic_read(&inode->i_writecount) > 1
1133 	    || (last_ino == inode->i_ino && last_dev == inode->i_sb->s_dev)) {
1134 		dprintk("nfsd: write defer %d\n", task_pid_nr(current));
1135 		msleep(10);
1136 		dprintk("nfsd: write resume %d\n", task_pid_nr(current));
1137 	}
1138 
1139 	if (inode->i_state & I_DIRTY) {
1140 		dprintk("nfsd: write sync %d\n", task_pid_nr(current));
1141 		err = vfs_fsync(file, 0);
1142 	}
1143 	last_ino = inode->i_ino;
1144 	last_dev = inode->i_sb->s_dev;
1145 	return err;
1146 }
1147 
1148 /**
1149  * nfsd_vfs_write - write data to an already-open file
1150  * @rqstp: RPC execution context
1151  * @fhp: File handle of file to write into
1152  * @nf: An open file matching @fhp
1153  * @offset: Byte offset of start
1154  * @payload: xdr_buf containing the write payload
1155  * @cnt: IN: number of bytes to write, OUT: number of bytes actually written
1156  * @stable: An NFS stable_how value
1157  * @verf: NFS WRITE verifier
1158  *
1159  * Upon return, caller must invoke fh_put on @fhp.
1160  *
1161  * Return values:
1162  *   An nfsstat value in network byte order.
1163  */
1164 __be32
1165 nfsd_vfs_write(struct svc_rqst *rqstp, struct svc_fh *fhp,
1166 	       struct nfsd_file *nf, loff_t offset,
1167 	       const struct xdr_buf *payload, unsigned long *cnt,
1168 	       int stable, __be32 *verf)
1169 {
1170 	struct nfsd_net		*nn = net_generic(SVC_NET(rqstp), nfsd_net_id);
1171 	struct file		*file = nf->nf_file;
1172 	struct super_block	*sb = file_inode(file)->i_sb;
1173 	struct svc_export	*exp;
1174 	struct iov_iter		iter;
1175 	errseq_t		since;
1176 	__be32			nfserr;
1177 	int			host_err;
1178 	loff_t			pos = offset;
1179 	unsigned long		exp_op_flags = 0;
1180 	unsigned int		pflags = current->flags;
1181 	rwf_t			flags = 0;
1182 	bool			restore_flags = false;
1183 	unsigned int		nvecs;
1184 
1185 	trace_nfsd_write_opened(rqstp, fhp, offset, *cnt);
1186 
1187 	if (sb->s_export_op)
1188 		exp_op_flags = sb->s_export_op->flags;
1189 
1190 	if (test_bit(RQ_LOCAL, &rqstp->rq_flags) &&
1191 	    !(exp_op_flags & EXPORT_OP_REMOTE_FS)) {
1192 		/*
1193 		 * We want throttling in balance_dirty_pages()
1194 		 * and shrink_inactive_list() to only consider
1195 		 * the backingdev we are writing to, so that nfs to
1196 		 * localhost doesn't cause nfsd to lock up due to all
1197 		 * the client's dirty pages or its congested queue.
1198 		 */
1199 		current->flags |= PF_LOCAL_THROTTLE;
1200 		restore_flags = true;
1201 	}
1202 
1203 	exp = fhp->fh_export;
1204 
1205 	if (!EX_ISSYNC(exp))
1206 		stable = NFS_UNSTABLE;
1207 
1208 	if (stable && !fhp->fh_use_wgather)
1209 		flags |= RWF_SYNC;
1210 
1211 	nvecs = xdr_buf_to_bvec(rqstp->rq_bvec, rqstp->rq_maxpages, payload);
1212 	iov_iter_bvec(&iter, ITER_SOURCE, rqstp->rq_bvec, nvecs, *cnt);
1213 	since = READ_ONCE(file->f_wb_err);
1214 	if (verf)
1215 		nfsd_copy_write_verifier(verf, nn);
1216 	host_err = vfs_iter_write(file, &iter, &pos, flags);
1217 	if (host_err < 0) {
1218 		commit_reset_write_verifier(nn, rqstp, host_err);
1219 		goto out_nfserr;
1220 	}
1221 	*cnt = host_err;
1222 	nfsd_stats_io_write_add(nn, exp, *cnt);
1223 	fsnotify_modify(file);
1224 	host_err = filemap_check_wb_err(file->f_mapping, since);
1225 	if (host_err < 0)
1226 		goto out_nfserr;
1227 
1228 	if (stable && fhp->fh_use_wgather) {
1229 		host_err = wait_for_concurrent_writes(file);
1230 		if (host_err < 0)
1231 			commit_reset_write_verifier(nn, rqstp, host_err);
1232 	}
1233 
1234 out_nfserr:
1235 	if (host_err >= 0) {
1236 		trace_nfsd_write_io_done(rqstp, fhp, offset, *cnt);
1237 		nfserr = nfs_ok;
1238 	} else {
1239 		trace_nfsd_write_err(rqstp, fhp, offset, host_err);
1240 		nfserr = nfserrno(host_err);
1241 	}
1242 	if (restore_flags)
1243 		current_restore_flags(pflags, PF_LOCAL_THROTTLE);
1244 	return nfserr;
1245 }
1246 
1247 /**
1248  * nfsd_read_splice_ok - check if spliced reading is supported
1249  * @rqstp: RPC transaction context
1250  *
1251  * Return values:
1252  *   %true: nfsd_splice_read() may be used
1253  *   %false: nfsd_splice_read() must not be used
1254  *
1255  * NFS READ normally uses splice to send data in-place. However the
1256  * data in cache can change after the reply's MIC is computed but
1257  * before the RPC reply is sent. To prevent the client from
1258  * rejecting the server-computed MIC in this somewhat rare case, do
1259  * not use splice with the GSS integrity and privacy services.
1260  */
1261 bool nfsd_read_splice_ok(struct svc_rqst *rqstp)
1262 {
1263 	if (nfsd_disable_splice_read)
1264 		return false;
1265 	switch (svc_auth_flavor(rqstp)) {
1266 	case RPC_AUTH_GSS_KRB5I:
1267 	case RPC_AUTH_GSS_KRB5P:
1268 		return false;
1269 	}
1270 	return true;
1271 }
1272 
1273 /**
1274  * nfsd_read - Read data from a file
1275  * @rqstp: RPC transaction context
1276  * @fhp: file handle of file to be read
1277  * @offset: starting byte offset
1278  * @count: IN: requested number of bytes; OUT: number of bytes read
1279  * @eof: OUT: set non-zero if operation reached the end of the file
1280  *
1281  * The caller must verify that there is enough space in @rqstp.rq_res
1282  * to perform this operation.
1283  *
1284  * N.B. After this call fhp needs an fh_put
1285  *
1286  * Returns nfs_ok on success, otherwise an nfserr stat value is
1287  * returned.
1288  */
1289 __be32 nfsd_read(struct svc_rqst *rqstp, struct svc_fh *fhp,
1290 		 loff_t offset, unsigned long *count, u32 *eof)
1291 {
1292 	struct nfsd_file	*nf;
1293 	struct file *file;
1294 	__be32 err;
1295 
1296 	trace_nfsd_read_start(rqstp, fhp, offset, *count);
1297 	err = nfsd_file_acquire_gc(rqstp, fhp, NFSD_MAY_READ, &nf);
1298 	if (err)
1299 		return err;
1300 
1301 	file = nf->nf_file;
1302 	if (file->f_op->splice_read && nfsd_read_splice_ok(rqstp))
1303 		err = nfsd_splice_read(rqstp, fhp, file, offset, count, eof);
1304 	else
1305 		err = nfsd_iter_read(rqstp, fhp, file, offset, count, 0, eof);
1306 
1307 	nfsd_file_put(nf);
1308 	trace_nfsd_read_done(rqstp, fhp, offset, *count);
1309 	return err;
1310 }
1311 
1312 /**
1313  * nfsd_write - open a file and write data to it
1314  * @rqstp: RPC execution context
1315  * @fhp: File handle of file to write into; nfsd_write() may modify it
1316  * @offset: Byte offset of start
1317  * @payload: xdr_buf containing the write payload
1318  * @cnt: IN: number of bytes to write, OUT: number of bytes actually written
1319  * @stable: An NFS stable_how value
1320  * @verf: NFS WRITE verifier
1321  *
1322  * Upon return, caller must invoke fh_put on @fhp.
1323  *
1324  * Return values:
1325  *   An nfsstat value in network byte order.
1326  */
1327 __be32
1328 nfsd_write(struct svc_rqst *rqstp, struct svc_fh *fhp, loff_t offset,
1329 	   const struct xdr_buf *payload, unsigned long *cnt, int stable,
1330 	   __be32 *verf)
1331 {
1332 	struct nfsd_file *nf;
1333 	__be32 err;
1334 
1335 	trace_nfsd_write_start(rqstp, fhp, offset, *cnt);
1336 
1337 	err = nfsd_file_acquire_gc(rqstp, fhp, NFSD_MAY_WRITE, &nf);
1338 	if (err)
1339 		goto out;
1340 
1341 	err = nfsd_vfs_write(rqstp, fhp, nf, offset, payload, cnt,
1342 			     stable, verf);
1343 	nfsd_file_put(nf);
1344 out:
1345 	trace_nfsd_write_done(rqstp, fhp, offset, *cnt);
1346 	return err;
1347 }
1348 
1349 /**
1350  * nfsd_commit - Commit pending writes to stable storage
1351  * @rqstp: RPC request being processed
1352  * @fhp: NFS filehandle
1353  * @nf: target file
1354  * @offset: raw offset from beginning of file
1355  * @count: raw count of bytes to sync
1356  * @verf: filled in with the server's current write verifier
1357  *
1358  * Note: we guarantee that data that lies within the range specified
1359  * by the 'offset' and 'count' parameters will be synced. The server
1360  * is permitted to sync data that lies outside this range at the
1361  * same time.
1362  *
1363  * Unfortunately we cannot lock the file to make sure we return full WCC
1364  * data to the client, as locking happens lower down in the filesystem.
1365  *
1366  * Return values:
1367  *   An nfsstat value in network byte order.
1368  */
1369 __be32
1370 nfsd_commit(struct svc_rqst *rqstp, struct svc_fh *fhp, struct nfsd_file *nf,
1371 	    u64 offset, u32 count, __be32 *verf)
1372 {
1373 	__be32			err = nfs_ok;
1374 	u64			maxbytes;
1375 	loff_t			start, end;
1376 	struct nfsd_net		*nn;
1377 
1378 	trace_nfsd_commit_start(rqstp, fhp, offset, count);
1379 
1380 	/*
1381 	 * Convert the client-provided (offset, count) range to a
1382 	 * (start, end) range. If the client-provided range falls
1383 	 * outside the maximum file size of the underlying FS,
1384 	 * clamp the sync range appropriately.
1385 	 */
1386 	start = 0;
1387 	end = LLONG_MAX;
1388 	maxbytes = (u64)fhp->fh_dentry->d_sb->s_maxbytes;
1389 	if (offset < maxbytes) {
1390 		start = offset;
1391 		if (count && (offset + count - 1 < maxbytes))
1392 			end = offset + count - 1;
1393 	}
1394 
1395 	nn = net_generic(nf->nf_net, nfsd_net_id);
1396 	if (EX_ISSYNC(fhp->fh_export)) {
1397 		errseq_t since = READ_ONCE(nf->nf_file->f_wb_err);
1398 		int err2;
1399 
1400 		err2 = vfs_fsync_range(nf->nf_file, start, end, 0);
1401 		switch (err2) {
1402 		case 0:
1403 			nfsd_copy_write_verifier(verf, nn);
1404 			err2 = filemap_check_wb_err(nf->nf_file->f_mapping,
1405 						    since);
1406 			err = nfserrno(err2);
1407 			break;
1408 		case -EINVAL:
1409 			err = nfserr_notsupp;
1410 			break;
1411 		default:
1412 			commit_reset_write_verifier(nn, rqstp, err2);
1413 			err = nfserrno(err2);
1414 		}
1415 	} else
1416 		nfsd_copy_write_verifier(verf, nn);
1417 
1418 	trace_nfsd_commit_done(rqstp, fhp, offset, count);
1419 	return err;
1420 }
1421 
1422 /**
1423  * nfsd_create_setattr - Set a created file's attributes
1424  * @rqstp: RPC transaction being executed
1425  * @fhp: NFS filehandle of parent directory
1426  * @resfhp: NFS filehandle of new object
1427  * @attrs: requested attributes of new object
1428  *
1429  * Returns nfs_ok on success, or an nfsstat in network byte order.
1430  */
1431 __be32
1432 nfsd_create_setattr(struct svc_rqst *rqstp, struct svc_fh *fhp,
1433 		    struct svc_fh *resfhp, struct nfsd_attrs *attrs)
1434 {
1435 	struct iattr *iap = attrs->na_iattr;
1436 	__be32 status;
1437 
1438 	/*
1439 	 * Mode has already been set by file creation.
1440 	 */
1441 	iap->ia_valid &= ~ATTR_MODE;
1442 
1443 	/*
1444 	 * Setting uid/gid works only for root.  Irix appears to
1445 	 * send along the gid on create when it tries to implement
1446 	 * setgid directories via NFS:
1447 	 */
1448 	if (!uid_eq(current_fsuid(), GLOBAL_ROOT_UID))
1449 		iap->ia_valid &= ~(ATTR_UID|ATTR_GID);
1450 
1451 	/*
1452 	 * Callers expect new file metadata to be committed even
1453 	 * if the attributes have not changed.
1454 	 */
1455 	if (nfsd_attrs_valid(attrs))
1456 		status = nfsd_setattr(rqstp, resfhp, attrs, NULL);
1457 	else
1458 		status = nfserrno(commit_metadata(resfhp));
1459 
1460 	/*
1461 	 * Transactional filesystems had a chance to commit changes
1462 	 * for both parent and child simultaneously making the
1463 	 * following commit_metadata a noop in many cases.
1464 	 */
1465 	if (!status)
1466 		status = nfserrno(commit_metadata(fhp));
1467 
1468 	/*
1469 	 * Update the new filehandle to pick up the new attributes.
1470 	 */
1471 	if (!status)
1472 		status = fh_update(resfhp);
1473 
1474 	return status;
1475 }
1476 
1477 /* HPUX client sometimes creates a file in mode 000, and sets size to 0.
1478  * setting size to 0 may fail for some specific file systems by the permission
1479  * checking which requires WRITE permission but the mode is 000.
1480  * we ignore the resizing(to 0) on the just new created file, since the size is
1481  * 0 after file created.
1482  *
1483  * call this only after vfs_create() is called.
1484  * */
1485 static void
1486 nfsd_check_ignore_resizing(struct iattr *iap)
1487 {
1488 	if ((iap->ia_valid & ATTR_SIZE) && (iap->ia_size == 0))
1489 		iap->ia_valid &= ~ATTR_SIZE;
1490 }
1491 
1492 /* The parent directory should already be locked: */
1493 __be32
1494 nfsd_create_locked(struct svc_rqst *rqstp, struct svc_fh *fhp,
1495 		   struct nfsd_attrs *attrs,
1496 		   int type, dev_t rdev, struct svc_fh *resfhp)
1497 {
1498 	struct dentry	*dentry, *dchild;
1499 	struct inode	*dirp;
1500 	struct iattr	*iap = attrs->na_iattr;
1501 	__be32		err;
1502 	int		host_err = 0;
1503 
1504 	dentry = fhp->fh_dentry;
1505 	dirp = d_inode(dentry);
1506 
1507 	dchild = dget(resfhp->fh_dentry);
1508 	err = nfsd_permission(&rqstp->rq_cred, fhp->fh_export, dentry,
1509 			      NFSD_MAY_CREATE);
1510 	if (err)
1511 		goto out;
1512 
1513 	if (!(iap->ia_valid & ATTR_MODE))
1514 		iap->ia_mode = 0;
1515 	iap->ia_mode = (iap->ia_mode & S_IALLUGO) | type;
1516 
1517 	if (!IS_POSIXACL(dirp))
1518 		iap->ia_mode &= ~current_umask();
1519 
1520 	err = 0;
1521 	switch (type) {
1522 	case S_IFREG:
1523 		host_err = vfs_create(&nop_mnt_idmap, dirp, dchild,
1524 				      iap->ia_mode, true);
1525 		if (!host_err)
1526 			nfsd_check_ignore_resizing(iap);
1527 		break;
1528 	case S_IFDIR:
1529 		dchild = vfs_mkdir(&nop_mnt_idmap, dirp, dchild, iap->ia_mode);
1530 		if (IS_ERR(dchild)) {
1531 			host_err = PTR_ERR(dchild);
1532 		} else if (d_is_negative(dchild)) {
1533 			err = nfserr_serverfault;
1534 			goto out;
1535 		} else if (unlikely(dchild != resfhp->fh_dentry)) {
1536 			dput(resfhp->fh_dentry);
1537 			resfhp->fh_dentry = dget(dchild);
1538 		}
1539 		break;
1540 	case S_IFCHR:
1541 	case S_IFBLK:
1542 	case S_IFIFO:
1543 	case S_IFSOCK:
1544 		host_err = vfs_mknod(&nop_mnt_idmap, dirp, dchild,
1545 				     iap->ia_mode, rdev);
1546 		break;
1547 	default:
1548 		printk(KERN_WARNING "nfsd: bad file type %o in nfsd_create\n",
1549 		       type);
1550 		host_err = -EINVAL;
1551 	}
1552 	if (host_err < 0)
1553 		goto out_nfserr;
1554 
1555 	err = nfsd_create_setattr(rqstp, fhp, resfhp, attrs);
1556 
1557 out:
1558 	if (!IS_ERR(dchild))
1559 		dput(dchild);
1560 	return err;
1561 
1562 out_nfserr:
1563 	err = nfserrno(host_err);
1564 	goto out;
1565 }
1566 
1567 /*
1568  * Create a filesystem object (regular, directory, special).
1569  * Note that the parent directory is left locked.
1570  *
1571  * N.B. Every call to nfsd_create needs an fh_put for _both_ fhp and resfhp
1572  */
1573 __be32
1574 nfsd_create(struct svc_rqst *rqstp, struct svc_fh *fhp,
1575 	    char *fname, int flen, struct nfsd_attrs *attrs,
1576 	    int type, dev_t rdev, struct svc_fh *resfhp)
1577 {
1578 	struct dentry	*dentry, *dchild = NULL;
1579 	__be32		err;
1580 	int		host_err;
1581 
1582 	trace_nfsd_vfs_create(rqstp, fhp, type, fname, flen);
1583 
1584 	if (isdotent(fname, flen))
1585 		return nfserr_exist;
1586 
1587 	err = fh_verify(rqstp, fhp, S_IFDIR, NFSD_MAY_NOP);
1588 	if (err)
1589 		return err;
1590 
1591 	dentry = fhp->fh_dentry;
1592 
1593 	host_err = fh_want_write(fhp);
1594 	if (host_err)
1595 		return nfserrno(host_err);
1596 
1597 	inode_lock_nested(dentry->d_inode, I_MUTEX_PARENT);
1598 	dchild = lookup_one(&nop_mnt_idmap, &QSTR_LEN(fname, flen), dentry);
1599 	host_err = PTR_ERR(dchild);
1600 	if (IS_ERR(dchild)) {
1601 		err = nfserrno(host_err);
1602 		goto out_unlock;
1603 	}
1604 	err = fh_compose(resfhp, fhp->fh_export, dchild, fhp);
1605 	/*
1606 	 * We unconditionally drop our ref to dchild as fh_compose will have
1607 	 * already grabbed its own ref for it.
1608 	 */
1609 	dput(dchild);
1610 	if (err)
1611 		goto out_unlock;
1612 	err = fh_fill_pre_attrs(fhp);
1613 	if (err != nfs_ok)
1614 		goto out_unlock;
1615 	err = nfsd_create_locked(rqstp, fhp, attrs, type, rdev, resfhp);
1616 	fh_fill_post_attrs(fhp);
1617 out_unlock:
1618 	inode_unlock(dentry->d_inode);
1619 	return err;
1620 }
1621 
1622 /*
1623  * Read a symlink. On entry, *lenp must contain the maximum path length that
1624  * fits into the buffer. On return, it contains the true length.
1625  * N.B. After this call fhp needs an fh_put
1626  */
1627 __be32
1628 nfsd_readlink(struct svc_rqst *rqstp, struct svc_fh *fhp, char *buf, int *lenp)
1629 {
1630 	__be32		err;
1631 	const char *link;
1632 	struct path path;
1633 	DEFINE_DELAYED_CALL(done);
1634 	int len;
1635 
1636 	err = fh_verify(rqstp, fhp, S_IFLNK, NFSD_MAY_NOP);
1637 	if (unlikely(err))
1638 		return err;
1639 
1640 	path.mnt = fhp->fh_export->ex_path.mnt;
1641 	path.dentry = fhp->fh_dentry;
1642 
1643 	if (unlikely(!d_is_symlink(path.dentry)))
1644 		return nfserr_inval;
1645 
1646 	touch_atime(&path);
1647 
1648 	link = vfs_get_link(path.dentry, &done);
1649 	if (IS_ERR(link))
1650 		return nfserrno(PTR_ERR(link));
1651 
1652 	len = strlen(link);
1653 	if (len < *lenp)
1654 		*lenp = len;
1655 	memcpy(buf, link, *lenp);
1656 	do_delayed_call(&done);
1657 	return 0;
1658 }
1659 
1660 /**
1661  * nfsd_symlink - Create a symlink and look up its inode
1662  * @rqstp: RPC transaction being executed
1663  * @fhp: NFS filehandle of parent directory
1664  * @fname: filename of the new symlink
1665  * @flen: length of @fname
1666  * @path: content of the new symlink (NUL-terminated)
1667  * @attrs: requested attributes of new object
1668  * @resfhp: NFS filehandle of new object
1669  *
1670  * N.B. After this call _both_ fhp and resfhp need an fh_put
1671  *
1672  * Returns nfs_ok on success, or an nfsstat in network byte order.
1673  */
1674 __be32
1675 nfsd_symlink(struct svc_rqst *rqstp, struct svc_fh *fhp,
1676 	     char *fname, int flen,
1677 	     char *path, struct nfsd_attrs *attrs,
1678 	     struct svc_fh *resfhp)
1679 {
1680 	struct dentry	*dentry, *dnew;
1681 	__be32		err, cerr;
1682 	int		host_err;
1683 
1684 	trace_nfsd_vfs_symlink(rqstp, fhp, fname, flen, path);
1685 
1686 	err = nfserr_noent;
1687 	if (!flen || path[0] == '\0')
1688 		goto out;
1689 	err = nfserr_exist;
1690 	if (isdotent(fname, flen))
1691 		goto out;
1692 
1693 	err = fh_verify(rqstp, fhp, S_IFDIR, NFSD_MAY_CREATE);
1694 	if (err)
1695 		goto out;
1696 
1697 	host_err = fh_want_write(fhp);
1698 	if (host_err) {
1699 		err = nfserrno(host_err);
1700 		goto out;
1701 	}
1702 
1703 	dentry = fhp->fh_dentry;
1704 	inode_lock_nested(dentry->d_inode, I_MUTEX_PARENT);
1705 	dnew = lookup_one(&nop_mnt_idmap, &QSTR_LEN(fname, flen), dentry);
1706 	if (IS_ERR(dnew)) {
1707 		err = nfserrno(PTR_ERR(dnew));
1708 		inode_unlock(dentry->d_inode);
1709 		goto out_drop_write;
1710 	}
1711 	err = fh_fill_pre_attrs(fhp);
1712 	if (err != nfs_ok)
1713 		goto out_unlock;
1714 	host_err = vfs_symlink(&nop_mnt_idmap, d_inode(dentry), dnew, path);
1715 	err = nfserrno(host_err);
1716 	cerr = fh_compose(resfhp, fhp->fh_export, dnew, fhp);
1717 	if (!err)
1718 		nfsd_create_setattr(rqstp, fhp, resfhp, attrs);
1719 	fh_fill_post_attrs(fhp);
1720 out_unlock:
1721 	inode_unlock(dentry->d_inode);
1722 	if (!err)
1723 		err = nfserrno(commit_metadata(fhp));
1724 	dput(dnew);
1725 	if (err==0) err = cerr;
1726 out_drop_write:
1727 	fh_drop_write(fhp);
1728 out:
1729 	return err;
1730 }
1731 
1732 /**
1733  * nfsd_link - create a link
1734  * @rqstp: RPC transaction context
1735  * @ffhp: the file handle of the directory where the new link is to be created
1736  * @name: the filename of the new link
1737  * @len: the length of @name in octets
1738  * @tfhp: the file handle of an existing file object
1739  *
1740  * After this call _both_ ffhp and tfhp need an fh_put.
1741  *
1742  * Returns a generic NFS status code in network byte-order.
1743  */
1744 __be32
1745 nfsd_link(struct svc_rqst *rqstp, struct svc_fh *ffhp,
1746 				char *name, int len, struct svc_fh *tfhp)
1747 {
1748 	struct dentry	*ddir, *dnew, *dold;
1749 	struct inode	*dirp;
1750 	int		type;
1751 	__be32		err;
1752 	int		host_err;
1753 
1754 	trace_nfsd_vfs_link(rqstp, ffhp, tfhp, name, len);
1755 
1756 	err = fh_verify(rqstp, ffhp, S_IFDIR, NFSD_MAY_CREATE);
1757 	if (err)
1758 		goto out;
1759 	err = fh_verify(rqstp, tfhp, 0, NFSD_MAY_NOP);
1760 	if (err)
1761 		goto out;
1762 	err = nfserr_isdir;
1763 	if (d_is_dir(tfhp->fh_dentry))
1764 		goto out;
1765 	err = nfserr_perm;
1766 	if (!len)
1767 		goto out;
1768 	err = nfserr_exist;
1769 	if (isdotent(name, len))
1770 		goto out;
1771 
1772 	err = nfs_ok;
1773 	type = d_inode(tfhp->fh_dentry)->i_mode & S_IFMT;
1774 	host_err = fh_want_write(tfhp);
1775 	if (host_err)
1776 		goto out;
1777 
1778 	ddir = ffhp->fh_dentry;
1779 	dirp = d_inode(ddir);
1780 	inode_lock_nested(dirp, I_MUTEX_PARENT);
1781 
1782 	dnew = lookup_one(&nop_mnt_idmap, &QSTR_LEN(name, len), ddir);
1783 	if (IS_ERR(dnew)) {
1784 		host_err = PTR_ERR(dnew);
1785 		goto out_unlock;
1786 	}
1787 
1788 	dold = tfhp->fh_dentry;
1789 
1790 	err = nfserr_noent;
1791 	if (d_really_is_negative(dold))
1792 		goto out_dput;
1793 	err = fh_fill_pre_attrs(ffhp);
1794 	if (err != nfs_ok)
1795 		goto out_dput;
1796 	host_err = vfs_link(dold, &nop_mnt_idmap, dirp, dnew, NULL);
1797 	fh_fill_post_attrs(ffhp);
1798 	inode_unlock(dirp);
1799 	if (!host_err) {
1800 		host_err = commit_metadata(ffhp);
1801 		if (!host_err)
1802 			host_err = commit_metadata(tfhp);
1803 	}
1804 
1805 	dput(dnew);
1806 out_drop_write:
1807 	fh_drop_write(tfhp);
1808 	if (host_err == -EBUSY) {
1809 		/*
1810 		 * See RFC 8881 Section 18.9.4 para 1-2: NFSv4 LINK
1811 		 * wants a status unique to the object type.
1812 		 */
1813 		if (type != S_IFDIR)
1814 			err = nfserr_file_open;
1815 		else
1816 			err = nfserr_acces;
1817 	}
1818 out:
1819 	return err != nfs_ok ? err : nfserrno(host_err);
1820 
1821 out_dput:
1822 	dput(dnew);
1823 out_unlock:
1824 	inode_unlock(dirp);
1825 	goto out_drop_write;
1826 }
1827 
1828 static void
1829 nfsd_close_cached_files(struct dentry *dentry)
1830 {
1831 	struct inode *inode = d_inode(dentry);
1832 
1833 	if (inode && S_ISREG(inode->i_mode))
1834 		nfsd_file_close_inode_sync(inode);
1835 }
1836 
1837 static bool
1838 nfsd_has_cached_files(struct dentry *dentry)
1839 {
1840 	bool		ret = false;
1841 	struct inode *inode = d_inode(dentry);
1842 
1843 	if (inode && S_ISREG(inode->i_mode))
1844 		ret = nfsd_file_is_cached(inode);
1845 	return ret;
1846 }
1847 
1848 /**
1849  * nfsd_rename - rename a directory entry
1850  * @rqstp: RPC transaction context
1851  * @ffhp: the file handle of parent directory containing the entry to be renamed
1852  * @fname: the filename of directory entry to be renamed
1853  * @flen: the length of @fname in octets
1854  * @tfhp: the file handle of parent directory to contain the renamed entry
1855  * @tname: the filename of the new entry
1856  * @tlen: the length of @tlen in octets
1857  *
1858  * After this call _both_ ffhp and tfhp need an fh_put.
1859  *
1860  * Returns a generic NFS status code in network byte-order.
1861  */
1862 __be32
1863 nfsd_rename(struct svc_rqst *rqstp, struct svc_fh *ffhp, char *fname, int flen,
1864 			    struct svc_fh *tfhp, char *tname, int tlen)
1865 {
1866 	struct dentry	*fdentry, *tdentry, *odentry, *ndentry, *trap;
1867 	struct inode	*fdir, *tdir;
1868 	int		type = S_IFDIR;
1869 	__be32		err;
1870 	int		host_err;
1871 	bool		close_cached = false;
1872 
1873 	trace_nfsd_vfs_rename(rqstp, ffhp, tfhp, fname, flen, tname, tlen);
1874 
1875 	err = fh_verify(rqstp, ffhp, S_IFDIR, NFSD_MAY_REMOVE);
1876 	if (err)
1877 		goto out;
1878 	err = fh_verify(rqstp, tfhp, S_IFDIR, NFSD_MAY_CREATE);
1879 	if (err)
1880 		goto out;
1881 
1882 	fdentry = ffhp->fh_dentry;
1883 	fdir = d_inode(fdentry);
1884 
1885 	tdentry = tfhp->fh_dentry;
1886 	tdir = d_inode(tdentry);
1887 
1888 	err = nfserr_perm;
1889 	if (!flen || isdotent(fname, flen) || !tlen || isdotent(tname, tlen))
1890 		goto out;
1891 
1892 	err = nfserr_xdev;
1893 	if (ffhp->fh_export->ex_path.mnt != tfhp->fh_export->ex_path.mnt)
1894 		goto out;
1895 	if (ffhp->fh_export->ex_path.dentry != tfhp->fh_export->ex_path.dentry)
1896 		goto out;
1897 
1898 retry:
1899 	host_err = fh_want_write(ffhp);
1900 	if (host_err) {
1901 		err = nfserrno(host_err);
1902 		goto out;
1903 	}
1904 
1905 	trap = lock_rename(tdentry, fdentry);
1906 	if (IS_ERR(trap)) {
1907 		err = nfserr_xdev;
1908 		goto out_want_write;
1909 	}
1910 	err = fh_fill_pre_attrs(ffhp);
1911 	if (err != nfs_ok)
1912 		goto out_unlock;
1913 	err = fh_fill_pre_attrs(tfhp);
1914 	if (err != nfs_ok)
1915 		goto out_unlock;
1916 
1917 	odentry = lookup_one(&nop_mnt_idmap, &QSTR_LEN(fname, flen), fdentry);
1918 	host_err = PTR_ERR(odentry);
1919 	if (IS_ERR(odentry))
1920 		goto out_nfserr;
1921 
1922 	host_err = -ENOENT;
1923 	if (d_really_is_negative(odentry))
1924 		goto out_dput_old;
1925 	host_err = -EINVAL;
1926 	if (odentry == trap)
1927 		goto out_dput_old;
1928 	type = d_inode(odentry)->i_mode & S_IFMT;
1929 
1930 	ndentry = lookup_one(&nop_mnt_idmap, &QSTR_LEN(tname, tlen), tdentry);
1931 	host_err = PTR_ERR(ndentry);
1932 	if (IS_ERR(ndentry))
1933 		goto out_dput_old;
1934 	if (d_inode(ndentry))
1935 		type = d_inode(ndentry)->i_mode & S_IFMT;
1936 	host_err = -ENOTEMPTY;
1937 	if (ndentry == trap)
1938 		goto out_dput_new;
1939 
1940 	if ((ndentry->d_sb->s_export_op->flags & EXPORT_OP_CLOSE_BEFORE_UNLINK) &&
1941 	    nfsd_has_cached_files(ndentry)) {
1942 		close_cached = true;
1943 		goto out_dput_old;
1944 	} else {
1945 		struct renamedata rd = {
1946 			.old_mnt_idmap	= &nop_mnt_idmap,
1947 			.old_dir	= fdir,
1948 			.old_dentry	= odentry,
1949 			.new_mnt_idmap	= &nop_mnt_idmap,
1950 			.new_dir	= tdir,
1951 			.new_dentry	= ndentry,
1952 		};
1953 		int retries;
1954 
1955 		for (retries = 1;;) {
1956 			host_err = vfs_rename(&rd);
1957 			if (host_err != -EAGAIN || !retries--)
1958 				break;
1959 			if (!nfsd_wait_for_delegreturn(rqstp, d_inode(odentry)))
1960 				break;
1961 		}
1962 		if (!host_err) {
1963 			host_err = commit_metadata(tfhp);
1964 			if (!host_err)
1965 				host_err = commit_metadata(ffhp);
1966 		}
1967 	}
1968  out_dput_new:
1969 	dput(ndentry);
1970  out_dput_old:
1971 	dput(odentry);
1972  out_nfserr:
1973 	if (host_err == -EBUSY) {
1974 		/*
1975 		 * See RFC 8881 Section 18.26.4 para 1-3: NFSv4 RENAME
1976 		 * wants a status unique to the object type.
1977 		 */
1978 		if (type != S_IFDIR)
1979 			err = nfserr_file_open;
1980 		else
1981 			err = nfserr_acces;
1982 	} else {
1983 		err = nfserrno(host_err);
1984 	}
1985 
1986 	if (!close_cached) {
1987 		fh_fill_post_attrs(ffhp);
1988 		fh_fill_post_attrs(tfhp);
1989 	}
1990 out_unlock:
1991 	unlock_rename(tdentry, fdentry);
1992 out_want_write:
1993 	fh_drop_write(ffhp);
1994 
1995 	/*
1996 	 * If the target dentry has cached open files, then we need to
1997 	 * try to close them prior to doing the rename.  Final fput
1998 	 * shouldn't be done with locks held however, so we delay it
1999 	 * until this point and then reattempt the whole shebang.
2000 	 */
2001 	if (close_cached) {
2002 		close_cached = false;
2003 		nfsd_close_cached_files(ndentry);
2004 		dput(ndentry);
2005 		goto retry;
2006 	}
2007 out:
2008 	return err;
2009 }
2010 
2011 /**
2012  * nfsd_unlink - remove a directory entry
2013  * @rqstp: RPC transaction context
2014  * @fhp: the file handle of the parent directory to be modified
2015  * @type: enforced file type of the object to be removed
2016  * @fname: the name of directory entry to be removed
2017  * @flen: length of @fname in octets
2018  *
2019  * After this call fhp needs an fh_put.
2020  *
2021  * Returns a generic NFS status code in network byte-order.
2022  */
2023 __be32
2024 nfsd_unlink(struct svc_rqst *rqstp, struct svc_fh *fhp, int type,
2025 				char *fname, int flen)
2026 {
2027 	struct dentry	*dentry, *rdentry;
2028 	struct inode	*dirp;
2029 	struct inode	*rinode;
2030 	__be32		err;
2031 	int		host_err;
2032 
2033 	trace_nfsd_vfs_unlink(rqstp, fhp, fname, flen);
2034 
2035 	err = nfserr_acces;
2036 	if (!flen || isdotent(fname, flen))
2037 		goto out;
2038 	err = fh_verify(rqstp, fhp, S_IFDIR, NFSD_MAY_REMOVE);
2039 	if (err)
2040 		goto out;
2041 
2042 	host_err = fh_want_write(fhp);
2043 	if (host_err)
2044 		goto out_nfserr;
2045 
2046 	dentry = fhp->fh_dentry;
2047 	dirp = d_inode(dentry);
2048 	inode_lock_nested(dirp, I_MUTEX_PARENT);
2049 
2050 	rdentry = lookup_one(&nop_mnt_idmap, &QSTR_LEN(fname, flen), dentry);
2051 	host_err = PTR_ERR(rdentry);
2052 	if (IS_ERR(rdentry))
2053 		goto out_unlock;
2054 
2055 	if (d_really_is_negative(rdentry)) {
2056 		dput(rdentry);
2057 		host_err = -ENOENT;
2058 		goto out_unlock;
2059 	}
2060 	rinode = d_inode(rdentry);
2061 	err = fh_fill_pre_attrs(fhp);
2062 	if (err != nfs_ok)
2063 		goto out_unlock;
2064 
2065 	ihold(rinode);
2066 	if (!type)
2067 		type = d_inode(rdentry)->i_mode & S_IFMT;
2068 
2069 	if (type != S_IFDIR) {
2070 		int retries;
2071 
2072 		if (rdentry->d_sb->s_export_op->flags & EXPORT_OP_CLOSE_BEFORE_UNLINK)
2073 			nfsd_close_cached_files(rdentry);
2074 
2075 		for (retries = 1;;) {
2076 			host_err = vfs_unlink(&nop_mnt_idmap, dirp, rdentry, NULL);
2077 			if (host_err != -EAGAIN || !retries--)
2078 				break;
2079 			if (!nfsd_wait_for_delegreturn(rqstp, rinode))
2080 				break;
2081 		}
2082 	} else {
2083 		host_err = vfs_rmdir(&nop_mnt_idmap, dirp, rdentry);
2084 	}
2085 	fh_fill_post_attrs(fhp);
2086 
2087 	inode_unlock(dirp);
2088 	if (!host_err)
2089 		host_err = commit_metadata(fhp);
2090 	dput(rdentry);
2091 	iput(rinode);    /* truncate the inode here */
2092 
2093 out_drop_write:
2094 	fh_drop_write(fhp);
2095 out_nfserr:
2096 	if (host_err == -EBUSY) {
2097 		/*
2098 		 * See RFC 8881 Section 18.25.4 para 4: NFSv4 REMOVE
2099 		 * wants a status unique to the object type.
2100 		 */
2101 		if (type != S_IFDIR)
2102 			err = nfserr_file_open;
2103 		else
2104 			err = nfserr_acces;
2105 	}
2106 out:
2107 	return err != nfs_ok ? err : nfserrno(host_err);
2108 out_unlock:
2109 	inode_unlock(dirp);
2110 	goto out_drop_write;
2111 }
2112 
2113 /*
2114  * We do this buffering because we must not call back into the file
2115  * system's ->lookup() method from the filldir callback. That may well
2116  * deadlock a number of file systems.
2117  *
2118  * This is based heavily on the implementation of same in XFS.
2119  */
2120 struct buffered_dirent {
2121 	u64		ino;
2122 	loff_t		offset;
2123 	int		namlen;
2124 	unsigned int	d_type;
2125 	char		name[];
2126 };
2127 
2128 struct readdir_data {
2129 	struct dir_context ctx;
2130 	char		*dirent;
2131 	size_t		used;
2132 	int		full;
2133 };
2134 
2135 static bool nfsd_buffered_filldir(struct dir_context *ctx, const char *name,
2136 				 int namlen, loff_t offset, u64 ino,
2137 				 unsigned int d_type)
2138 {
2139 	struct readdir_data *buf =
2140 		container_of(ctx, struct readdir_data, ctx);
2141 	struct buffered_dirent *de = (void *)(buf->dirent + buf->used);
2142 	unsigned int reclen;
2143 
2144 	reclen = ALIGN(sizeof(struct buffered_dirent) + namlen, sizeof(u64));
2145 	if (buf->used + reclen > PAGE_SIZE) {
2146 		buf->full = 1;
2147 		return false;
2148 	}
2149 
2150 	de->namlen = namlen;
2151 	de->offset = offset;
2152 	de->ino = ino;
2153 	de->d_type = d_type;
2154 	memcpy(de->name, name, namlen);
2155 	buf->used += reclen;
2156 
2157 	return true;
2158 }
2159 
2160 static __be32 nfsd_buffered_readdir(struct file *file, struct svc_fh *fhp,
2161 				    nfsd_filldir_t func, struct readdir_cd *cdp,
2162 				    loff_t *offsetp)
2163 {
2164 	struct buffered_dirent *de;
2165 	int host_err;
2166 	int size;
2167 	loff_t offset;
2168 	struct readdir_data buf = {
2169 		.ctx.actor = nfsd_buffered_filldir,
2170 		.dirent = (void *)__get_free_page(GFP_KERNEL)
2171 	};
2172 
2173 	if (!buf.dirent)
2174 		return nfserrno(-ENOMEM);
2175 
2176 	offset = *offsetp;
2177 
2178 	while (1) {
2179 		unsigned int reclen;
2180 
2181 		cdp->err = nfserr_eof; /* will be cleared on successful read */
2182 		buf.used = 0;
2183 		buf.full = 0;
2184 
2185 		host_err = iterate_dir(file, &buf.ctx);
2186 		if (buf.full)
2187 			host_err = 0;
2188 
2189 		if (host_err < 0)
2190 			break;
2191 
2192 		size = buf.used;
2193 
2194 		if (!size)
2195 			break;
2196 
2197 		de = (struct buffered_dirent *)buf.dirent;
2198 		while (size > 0) {
2199 			offset = de->offset;
2200 
2201 			if (func(cdp, de->name, de->namlen, de->offset,
2202 				 de->ino, de->d_type))
2203 				break;
2204 
2205 			if (cdp->err != nfs_ok)
2206 				break;
2207 
2208 			trace_nfsd_dirent(fhp, de->ino, de->name, de->namlen);
2209 
2210 			reclen = ALIGN(sizeof(*de) + de->namlen,
2211 				       sizeof(u64));
2212 			size -= reclen;
2213 			de = (struct buffered_dirent *)((char *)de + reclen);
2214 		}
2215 		if (size > 0) /* We bailed out early */
2216 			break;
2217 
2218 		offset = vfs_llseek(file, 0, SEEK_CUR);
2219 	}
2220 
2221 	free_page((unsigned long)(buf.dirent));
2222 
2223 	if (host_err)
2224 		return nfserrno(host_err);
2225 
2226 	*offsetp = offset;
2227 	return cdp->err;
2228 }
2229 
2230 /**
2231  * nfsd_readdir - Read entries from a directory
2232  * @rqstp: RPC transaction context
2233  * @fhp: NFS file handle of directory to be read
2234  * @offsetp: OUT: seek offset of final entry that was read
2235  * @cdp: OUT: an eof error value
2236  * @func: entry filler actor
2237  *
2238  * This implementation ignores the NFSv3/4 verifier cookie.
2239  *
2240  * NB: normal system calls hold file->f_pos_lock when calling
2241  * ->iterate_shared and ->llseek, but nfsd_readdir() does not.
2242  * Because the struct file acquired here is not visible to other
2243  * threads, it's internal state does not need mutex protection.
2244  *
2245  * Returns nfs_ok on success, otherwise an nfsstat code is
2246  * returned.
2247  */
2248 __be32
2249 nfsd_readdir(struct svc_rqst *rqstp, struct svc_fh *fhp, loff_t *offsetp,
2250 	     struct readdir_cd *cdp, nfsd_filldir_t func)
2251 {
2252 	__be32		err;
2253 	struct file	*file;
2254 	loff_t		offset = *offsetp;
2255 	int             may_flags = NFSD_MAY_READ;
2256 
2257 	err = nfsd_open(rqstp, fhp, S_IFDIR, may_flags, &file);
2258 	if (err)
2259 		goto out;
2260 
2261 	if (fhp->fh_64bit_cookies)
2262 		file->f_mode |= FMODE_64BITHASH;
2263 	else
2264 		file->f_mode |= FMODE_32BITHASH;
2265 
2266 	offset = vfs_llseek(file, offset, SEEK_SET);
2267 	if (offset < 0) {
2268 		err = nfserrno((int)offset);
2269 		goto out_close;
2270 	}
2271 
2272 	err = nfsd_buffered_readdir(file, fhp, func, cdp, offsetp);
2273 
2274 	if (err == nfserr_eof || err == nfserr_toosmall)
2275 		err = nfs_ok; /* can still be found in ->err */
2276 out_close:
2277 	nfsd_filp_close(file);
2278 out:
2279 	return err;
2280 }
2281 
2282 /**
2283  * nfsd_filp_close: close a file synchronously
2284  * @fp: the file to close
2285  *
2286  * nfsd_filp_close() is similar in behaviour to filp_close().
2287  * The difference is that if this is the final close on the
2288  * file, the that finalisation happens immediately, rather then
2289  * being handed over to a work_queue, as it the case for
2290  * filp_close().
2291  * When a user-space process closes a file (even when using
2292  * filp_close() the finalisation happens before returning to
2293  * userspace, so it is effectively synchronous.  When a kernel thread
2294  * uses file_close(), on the other hand, the handling is completely
2295  * asynchronous.  This means that any cost imposed by that finalisation
2296  * is not imposed on the nfsd thread, and nfsd could potentually
2297  * close files more quickly than the work queue finalises the close,
2298  * which would lead to unbounded growth in the queue.
2299  *
2300  * In some contexts is it not safe to synchronously wait for
2301  * close finalisation (see comment for __fput_sync()), but nfsd
2302  * does not match those contexts.  In partcilarly it does not, at the
2303  * time that this function is called, hold and locks and no finalisation
2304  * of any file, socket, or device driver would have any cause to wait
2305  * for nfsd to make progress.
2306  */
2307 void nfsd_filp_close(struct file *fp)
2308 {
2309 	get_file(fp);
2310 	filp_close(fp, NULL);
2311 	__fput_sync(fp);
2312 }
2313 
2314 /*
2315  * Get file system stats
2316  * N.B. After this call fhp needs an fh_put
2317  */
2318 __be32
2319 nfsd_statfs(struct svc_rqst *rqstp, struct svc_fh *fhp, struct kstatfs *stat, int access)
2320 {
2321 	__be32 err;
2322 
2323 	trace_nfsd_vfs_statfs(rqstp, fhp);
2324 
2325 	err = fh_verify(rqstp, fhp, 0, NFSD_MAY_NOP | access);
2326 	if (!err) {
2327 		struct path path = {
2328 			.mnt	= fhp->fh_export->ex_path.mnt,
2329 			.dentry	= fhp->fh_dentry,
2330 		};
2331 		if (vfs_statfs(&path, stat))
2332 			err = nfserr_io;
2333 	}
2334 	return err;
2335 }
2336 
2337 static int exp_rdonly(struct svc_cred *cred, struct svc_export *exp)
2338 {
2339 	return nfsexp_flags(cred, exp) & NFSEXP_READONLY;
2340 }
2341 
2342 #ifdef CONFIG_NFSD_V4
2343 /*
2344  * Helper function to translate error numbers. In the case of xattr operations,
2345  * some error codes need to be translated outside of the standard translations.
2346  *
2347  * ENODATA needs to be translated to nfserr_noxattr.
2348  * E2BIG to nfserr_xattr2big.
2349  *
2350  * Additionally, vfs_listxattr can return -ERANGE. This means that the
2351  * file has too many extended attributes to retrieve inside an
2352  * XATTR_LIST_MAX sized buffer. This is a bug in the xattr implementation:
2353  * filesystems will allow the adding of extended attributes until they hit
2354  * their own internal limit. This limit may be larger than XATTR_LIST_MAX.
2355  * So, at that point, the attributes are present and valid, but can't
2356  * be retrieved using listxattr, since the upper level xattr code enforces
2357  * the XATTR_LIST_MAX limit.
2358  *
2359  * This bug means that we need to deal with listxattr returning -ERANGE. The
2360  * best mapping is to return TOOSMALL.
2361  */
2362 static __be32
2363 nfsd_xattr_errno(int err)
2364 {
2365 	switch (err) {
2366 	case -ENODATA:
2367 		return nfserr_noxattr;
2368 	case -E2BIG:
2369 		return nfserr_xattr2big;
2370 	case -ERANGE:
2371 		return nfserr_toosmall;
2372 	}
2373 	return nfserrno(err);
2374 }
2375 
2376 /*
2377  * Retrieve the specified user extended attribute. To avoid always
2378  * having to allocate the maximum size (since we are not getting
2379  * a maximum size from the RPC), do a probe + alloc. Hold a reader
2380  * lock on i_rwsem to prevent the extended attribute from changing
2381  * size while we're doing this.
2382  */
2383 __be32
2384 nfsd_getxattr(struct svc_rqst *rqstp, struct svc_fh *fhp, char *name,
2385 	      void **bufp, int *lenp)
2386 {
2387 	ssize_t len;
2388 	__be32 err;
2389 	char *buf;
2390 	struct inode *inode;
2391 	struct dentry *dentry;
2392 
2393 	err = fh_verify(rqstp, fhp, 0, NFSD_MAY_READ);
2394 	if (err)
2395 		return err;
2396 
2397 	err = nfs_ok;
2398 	dentry = fhp->fh_dentry;
2399 	inode = d_inode(dentry);
2400 
2401 	inode_lock_shared(inode);
2402 
2403 	len = vfs_getxattr(&nop_mnt_idmap, dentry, name, NULL, 0);
2404 
2405 	/*
2406 	 * Zero-length attribute, just return.
2407 	 */
2408 	if (len == 0) {
2409 		*bufp = NULL;
2410 		*lenp = 0;
2411 		goto out;
2412 	}
2413 
2414 	if (len < 0) {
2415 		err = nfsd_xattr_errno(len);
2416 		goto out;
2417 	}
2418 
2419 	if (len > *lenp) {
2420 		err = nfserr_toosmall;
2421 		goto out;
2422 	}
2423 
2424 	buf = kvmalloc(len, GFP_KERNEL);
2425 	if (buf == NULL) {
2426 		err = nfserr_jukebox;
2427 		goto out;
2428 	}
2429 
2430 	len = vfs_getxattr(&nop_mnt_idmap, dentry, name, buf, len);
2431 	if (len <= 0) {
2432 		kvfree(buf);
2433 		buf = NULL;
2434 		err = nfsd_xattr_errno(len);
2435 	}
2436 
2437 	*lenp = len;
2438 	*bufp = buf;
2439 
2440 out:
2441 	inode_unlock_shared(inode);
2442 
2443 	return err;
2444 }
2445 
2446 /*
2447  * Retrieve the xattr names. Since we can't know how many are
2448  * user extended attributes, we must get all attributes here,
2449  * and have the XDR encode filter out the "user." ones.
2450  *
2451  * While this could always just allocate an XATTR_LIST_MAX
2452  * buffer, that's a waste, so do a probe + allocate. To
2453  * avoid any changes between the probe and allocate, wrap
2454  * this in inode_lock.
2455  */
2456 __be32
2457 nfsd_listxattr(struct svc_rqst *rqstp, struct svc_fh *fhp, char **bufp,
2458 	       int *lenp)
2459 {
2460 	ssize_t len;
2461 	__be32 err;
2462 	char *buf;
2463 	struct inode *inode;
2464 	struct dentry *dentry;
2465 
2466 	err = fh_verify(rqstp, fhp, 0, NFSD_MAY_READ);
2467 	if (err)
2468 		return err;
2469 
2470 	dentry = fhp->fh_dentry;
2471 	inode = d_inode(dentry);
2472 	*lenp = 0;
2473 
2474 	inode_lock_shared(inode);
2475 
2476 	len = vfs_listxattr(dentry, NULL, 0);
2477 	if (len <= 0) {
2478 		err = nfsd_xattr_errno(len);
2479 		goto out;
2480 	}
2481 
2482 	if (len > XATTR_LIST_MAX) {
2483 		err = nfserr_xattr2big;
2484 		goto out;
2485 	}
2486 
2487 	buf = kvmalloc(len, GFP_KERNEL);
2488 	if (buf == NULL) {
2489 		err = nfserr_jukebox;
2490 		goto out;
2491 	}
2492 
2493 	len = vfs_listxattr(dentry, buf, len);
2494 	if (len <= 0) {
2495 		kvfree(buf);
2496 		err = nfsd_xattr_errno(len);
2497 		goto out;
2498 	}
2499 
2500 	*lenp = len;
2501 	*bufp = buf;
2502 
2503 	err = nfs_ok;
2504 out:
2505 	inode_unlock_shared(inode);
2506 
2507 	return err;
2508 }
2509 
2510 /**
2511  * nfsd_removexattr - Remove an extended attribute
2512  * @rqstp: RPC transaction being executed
2513  * @fhp: NFS filehandle of object with xattr to remove
2514  * @name: name of xattr to remove (NUL-terminate)
2515  *
2516  * Pass in a NULL pointer for delegated_inode, and let the client deal
2517  * with NFS4ERR_DELAY (same as with e.g. setattr and remove).
2518  *
2519  * Returns nfs_ok on success, or an nfsstat in network byte order.
2520  */
2521 __be32
2522 nfsd_removexattr(struct svc_rqst *rqstp, struct svc_fh *fhp, char *name)
2523 {
2524 	__be32 err;
2525 	int ret;
2526 
2527 	err = fh_verify(rqstp, fhp, 0, NFSD_MAY_WRITE);
2528 	if (err)
2529 		return err;
2530 
2531 	ret = fh_want_write(fhp);
2532 	if (ret)
2533 		return nfserrno(ret);
2534 
2535 	inode_lock(fhp->fh_dentry->d_inode);
2536 	err = fh_fill_pre_attrs(fhp);
2537 	if (err != nfs_ok)
2538 		goto out_unlock;
2539 	ret = __vfs_removexattr_locked(&nop_mnt_idmap, fhp->fh_dentry,
2540 				       name, NULL);
2541 	err = nfsd_xattr_errno(ret);
2542 	fh_fill_post_attrs(fhp);
2543 out_unlock:
2544 	inode_unlock(fhp->fh_dentry->d_inode);
2545 	fh_drop_write(fhp);
2546 
2547 	return err;
2548 }
2549 
2550 __be32
2551 nfsd_setxattr(struct svc_rqst *rqstp, struct svc_fh *fhp, char *name,
2552 	      void *buf, u32 len, u32 flags)
2553 {
2554 	__be32 err;
2555 	int ret;
2556 
2557 	err = fh_verify(rqstp, fhp, 0, NFSD_MAY_WRITE);
2558 	if (err)
2559 		return err;
2560 
2561 	ret = fh_want_write(fhp);
2562 	if (ret)
2563 		return nfserrno(ret);
2564 	inode_lock(fhp->fh_dentry->d_inode);
2565 	err = fh_fill_pre_attrs(fhp);
2566 	if (err != nfs_ok)
2567 		goto out_unlock;
2568 	ret = __vfs_setxattr_locked(&nop_mnt_idmap, fhp->fh_dentry,
2569 				    name, buf, len, flags, NULL);
2570 	fh_fill_post_attrs(fhp);
2571 	err = nfsd_xattr_errno(ret);
2572 out_unlock:
2573 	inode_unlock(fhp->fh_dentry->d_inode);
2574 	fh_drop_write(fhp);
2575 	return err;
2576 }
2577 #endif
2578 
2579 /*
2580  * Check for a user's access permissions to this inode.
2581  */
2582 __be32
2583 nfsd_permission(struct svc_cred *cred, struct svc_export *exp,
2584 		struct dentry *dentry, int acc)
2585 {
2586 	struct inode	*inode = d_inode(dentry);
2587 	int		err;
2588 
2589 	if ((acc & NFSD_MAY_MASK) == NFSD_MAY_NOP)
2590 		return 0;
2591 #if 0
2592 	dprintk("nfsd: permission 0x%x%s%s%s%s%s%s%s mode 0%o%s%s%s\n",
2593 		acc,
2594 		(acc & NFSD_MAY_READ)?	" read"  : "",
2595 		(acc & NFSD_MAY_WRITE)?	" write" : "",
2596 		(acc & NFSD_MAY_EXEC)?	" exec"  : "",
2597 		(acc & NFSD_MAY_SATTR)?	" sattr" : "",
2598 		(acc & NFSD_MAY_TRUNC)?	" trunc" : "",
2599 		(acc & NFSD_MAY_NLM)?	" nlm"  : "",
2600 		(acc & NFSD_MAY_OWNER_OVERRIDE)? " owneroverride" : "",
2601 		inode->i_mode,
2602 		IS_IMMUTABLE(inode)?	" immut" : "",
2603 		IS_APPEND(inode)?	" append" : "",
2604 		__mnt_is_readonly(exp->ex_path.mnt)?	" ro" : "");
2605 	dprintk("      owner %d/%d user %d/%d\n",
2606 		inode->i_uid, inode->i_gid, current_fsuid(), current_fsgid());
2607 #endif
2608 
2609 	/* Normally we reject any write/sattr etc access on a read-only file
2610 	 * system.  But if it is IRIX doing check on write-access for a
2611 	 * device special file, we ignore rofs.
2612 	 */
2613 	if (!(acc & NFSD_MAY_LOCAL_ACCESS))
2614 		if (acc & (NFSD_MAY_WRITE | NFSD_MAY_SATTR | NFSD_MAY_TRUNC)) {
2615 			if (exp_rdonly(cred, exp) ||
2616 			    __mnt_is_readonly(exp->ex_path.mnt))
2617 				return nfserr_rofs;
2618 			if (/* (acc & NFSD_MAY_WRITE) && */ IS_IMMUTABLE(inode))
2619 				return nfserr_perm;
2620 		}
2621 	if ((acc & NFSD_MAY_TRUNC) && IS_APPEND(inode))
2622 		return nfserr_perm;
2623 
2624 	/*
2625 	 * The file owner always gets access permission for accesses that
2626 	 * would normally be checked at open time. This is to make
2627 	 * file access work even when the client has done a fchmod(fd, 0).
2628 	 *
2629 	 * However, `cp foo bar' should fail nevertheless when bar is
2630 	 * readonly. A sensible way to do this might be to reject all
2631 	 * attempts to truncate a read-only file, because a creat() call
2632 	 * always implies file truncation.
2633 	 * ... but this isn't really fair.  A process may reasonably call
2634 	 * ftruncate on an open file descriptor on a file with perm 000.
2635 	 * We must trust the client to do permission checking - using "ACCESS"
2636 	 * with NFSv3.
2637 	 */
2638 	if ((acc & NFSD_MAY_OWNER_OVERRIDE) &&
2639 	    uid_eq(inode->i_uid, current_fsuid()))
2640 		return 0;
2641 
2642 	/* This assumes  NFSD_MAY_{READ,WRITE,EXEC} == MAY_{READ,WRITE,EXEC} */
2643 	err = inode_permission(&nop_mnt_idmap, inode,
2644 			       acc & (MAY_READ | MAY_WRITE | MAY_EXEC));
2645 
2646 	/* Allow read access to binaries even when mode 111 */
2647 	if (err == -EACCES && S_ISREG(inode->i_mode) &&
2648 	     (acc == (NFSD_MAY_READ | NFSD_MAY_OWNER_OVERRIDE) ||
2649 	      acc == (NFSD_MAY_READ | NFSD_MAY_READ_IF_EXEC)))
2650 		err = inode_permission(&nop_mnt_idmap, inode, MAY_EXEC);
2651 
2652 	return err? nfserrno(err) : 0;
2653 }
2654