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