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