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