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
nfsd_cross_mnt(struct svc_rqst * rqstp,struct dentry ** dpp,struct svc_export ** expp)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 
follow_to_parent(struct path * path)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 
nfsd_lookup_parent(struct svc_rqst * rqstp,struct dentry * dparent,struct svc_export ** exp,struct dentry ** dentryp)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  */
nfsd_mountpoint(struct dentry * dentry,struct svc_export * exp)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
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)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
nfsd_lookup(struct svc_rqst * rqstp,struct svc_fh * fhp,const char * name,unsigned int len,struct svc_fh * resfh)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
commit_inode_metadata(struct inode * inode)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
commit_metadata(struct svc_fh * fhp)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
nfsd_sanitize_attrs(struct inode * inode,struct iattr * iap)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
nfsd_get_write_access(struct svc_rqst * rqstp,struct svc_fh * fhp,struct iattr * iap)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 
__nfsd_setattr(struct dentry * dentry,struct iattr * iap)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
nfsd_setattr(struct svc_rqst * rqstp,struct svc_fh * fhp,struct nfsd_attrs * attr,int check_guard,time64_t guardtime)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  */
nfsd4_is_junction(struct dentry * dentry)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 
nfsd4_get_cstate(struct svc_rqst * rqstp)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 
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)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 
nfsd_copy_file_range(struct file * src,u64 src_pos,struct file * dst,u64 dst_pos,u64 count)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 
nfsd4_vfs_fallocate(struct svc_rqst * rqstp,struct svc_fh * fhp,struct file * file,loff_t offset,loff_t len,int flags)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
nfsd_access(struct svc_rqst * rqstp,struct svc_fh * fhp,u32 * access,u32 * supported)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 
nfsd_open_break_lease(struct inode * inode,int access)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
__nfsd_open(struct svc_rqst * rqstp,struct svc_fh * fhp,umode_t type,int may_flags,struct file ** filp)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
nfsd_open(struct svc_rqst * rqstp,struct svc_fh * fhp,umode_t type,int may_flags,struct file ** filp)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
nfsd_open_verified(struct svc_rqst * rqstp,struct svc_fh * fhp,int may_flags,struct file ** filp)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
nfsd_splice_actor(struct pipe_inode_info * pipe,struct pipe_buffer * buf,struct splice_desc * sd)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 
nfsd_direct_splice_actor(struct pipe_inode_info * pipe,struct splice_desc * sd)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 
nfsd_eof_on_read(struct file * file,loff_t offset,ssize_t len,size_t expected)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 
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)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 
nfsd_splice_read(struct svc_rqst * rqstp,struct svc_fh * fhp,struct file * file,loff_t offset,unsigned long * count,u32 * eof)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 
nfsd_readv(struct svc_rqst * rqstp,struct svc_fh * fhp,struct file * file,loff_t offset,struct kvec * vec,int vlen,unsigned long * count,u32 * eof)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  */
wait_for_concurrent_writes(struct file * file)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
nfsd_vfs_write(struct svc_rqst * rqstp,struct svc_fh * fhp,struct nfsd_file * nf,loff_t offset,struct kvec * vec,int vlen,unsigned long * cnt,int stable,__be32 * verf)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  */
nfsd_read(struct svc_rqst * rqstp,struct svc_fh * fhp,loff_t offset,struct kvec * vec,int vlen,unsigned long * count,u32 * eof)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_gc(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
nfsd_write(struct svc_rqst * rqstp,struct svc_fh * fhp,loff_t offset,struct kvec * vec,int vlen,unsigned long * cnt,int stable,__be32 * verf)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_gc(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  * @nf: target file
1137  * @offset: raw offset from beginning of file
1138  * @count: raw count of bytes to sync
1139  * @verf: filled in with the server's current write verifier
1140  *
1141  * Note: we guarantee that data that lies within the range specified
1142  * by the 'offset' and 'count' parameters will be synced. The server
1143  * is permitted to sync data that lies outside this range at the
1144  * same time.
1145  *
1146  * Unfortunately we cannot lock the file to make sure we return full WCC
1147  * data to the client, as locking happens lower down in the filesystem.
1148  *
1149  * Return values:
1150  *   An nfsstat value in network byte order.
1151  */
1152 __be32
nfsd_commit(struct svc_rqst * rqstp,struct svc_fh * fhp,struct nfsd_file * nf,u64 offset,u32 count,__be32 * verf)1153 nfsd_commit(struct svc_rqst *rqstp, struct svc_fh *fhp, struct nfsd_file *nf,
1154 	    u64 offset, u32 count, __be32 *verf)
1155 {
1156 	__be32			err = nfs_ok;
1157 	u64			maxbytes;
1158 	loff_t			start, end;
1159 	struct nfsd_net		*nn;
1160 
1161 	/*
1162 	 * Convert the client-provided (offset, count) range to a
1163 	 * (start, end) range. If the client-provided range falls
1164 	 * outside the maximum file size of the underlying FS,
1165 	 * clamp the sync range appropriately.
1166 	 */
1167 	start = 0;
1168 	end = LLONG_MAX;
1169 	maxbytes = (u64)fhp->fh_dentry->d_sb->s_maxbytes;
1170 	if (offset < maxbytes) {
1171 		start = offset;
1172 		if (count && (offset + count - 1 < maxbytes))
1173 			end = offset + count - 1;
1174 	}
1175 
1176 	nn = net_generic(nf->nf_net, nfsd_net_id);
1177 	if (EX_ISSYNC(fhp->fh_export)) {
1178 		errseq_t since = READ_ONCE(nf->nf_file->f_wb_err);
1179 		int err2;
1180 
1181 		err2 = vfs_fsync_range(nf->nf_file, start, end, 0);
1182 		switch (err2) {
1183 		case 0:
1184 			nfsd_copy_write_verifier(verf, nn);
1185 			err2 = filemap_check_wb_err(nf->nf_file->f_mapping,
1186 						    since);
1187 			err = nfserrno(err2);
1188 			break;
1189 		case -EINVAL:
1190 			err = nfserr_notsupp;
1191 			break;
1192 		default:
1193 			nfsd_reset_write_verifier(nn);
1194 			trace_nfsd_writeverf_reset(nn, rqstp, err2);
1195 			err = nfserrno(err2);
1196 		}
1197 	} else
1198 		nfsd_copy_write_verifier(verf, nn);
1199 
1200 	return err;
1201 }
1202 
1203 /**
1204  * nfsd_create_setattr - Set a created file's attributes
1205  * @rqstp: RPC transaction being executed
1206  * @fhp: NFS filehandle of parent directory
1207  * @resfhp: NFS filehandle of new object
1208  * @attrs: requested attributes of new object
1209  *
1210  * Returns nfs_ok on success, or an nfsstat in network byte order.
1211  */
1212 __be32
nfsd_create_setattr(struct svc_rqst * rqstp,struct svc_fh * fhp,struct svc_fh * resfhp,struct nfsd_attrs * attrs)1213 nfsd_create_setattr(struct svc_rqst *rqstp, struct svc_fh *fhp,
1214 		    struct svc_fh *resfhp, struct nfsd_attrs *attrs)
1215 {
1216 	struct iattr *iap = attrs->na_iattr;
1217 	__be32 status;
1218 
1219 	/*
1220 	 * Mode has already been set by file creation.
1221 	 */
1222 	iap->ia_valid &= ~ATTR_MODE;
1223 
1224 	/*
1225 	 * Setting uid/gid works only for root.  Irix appears to
1226 	 * send along the gid on create when it tries to implement
1227 	 * setgid directories via NFS:
1228 	 */
1229 	if (!uid_eq(current_fsuid(), GLOBAL_ROOT_UID))
1230 		iap->ia_valid &= ~(ATTR_UID|ATTR_GID);
1231 
1232 	/*
1233 	 * Callers expect new file metadata to be committed even
1234 	 * if the attributes have not changed.
1235 	 */
1236 	if (iap->ia_valid)
1237 		status = nfsd_setattr(rqstp, resfhp, attrs, 0, (time64_t)0);
1238 	else
1239 		status = nfserrno(commit_metadata(resfhp));
1240 
1241 	/*
1242 	 * Transactional filesystems had a chance to commit changes
1243 	 * for both parent and child simultaneously making the
1244 	 * following commit_metadata a noop in many cases.
1245 	 */
1246 	if (!status)
1247 		status = nfserrno(commit_metadata(fhp));
1248 
1249 	/*
1250 	 * Update the new filehandle to pick up the new attributes.
1251 	 */
1252 	if (!status)
1253 		status = fh_update(resfhp);
1254 
1255 	return status;
1256 }
1257 
1258 /* HPUX client sometimes creates a file in mode 000, and sets size to 0.
1259  * setting size to 0 may fail for some specific file systems by the permission
1260  * checking which requires WRITE permission but the mode is 000.
1261  * we ignore the resizing(to 0) on the just new created file, since the size is
1262  * 0 after file created.
1263  *
1264  * call this only after vfs_create() is called.
1265  * */
1266 static void
nfsd_check_ignore_resizing(struct iattr * iap)1267 nfsd_check_ignore_resizing(struct iattr *iap)
1268 {
1269 	if ((iap->ia_valid & ATTR_SIZE) && (iap->ia_size == 0))
1270 		iap->ia_valid &= ~ATTR_SIZE;
1271 }
1272 
1273 /* The parent directory should already be locked: */
1274 __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)1275 nfsd_create_locked(struct svc_rqst *rqstp, struct svc_fh *fhp,
1276 		   struct nfsd_attrs *attrs,
1277 		   int type, dev_t rdev, struct svc_fh *resfhp)
1278 {
1279 	struct dentry	*dentry, *dchild;
1280 	struct inode	*dirp;
1281 	struct iattr	*iap = attrs->na_iattr;
1282 	__be32		err;
1283 	int		host_err;
1284 
1285 	dentry = fhp->fh_dentry;
1286 	dirp = d_inode(dentry);
1287 
1288 	dchild = dget(resfhp->fh_dentry);
1289 	err = nfsd_permission(rqstp, fhp->fh_export, dentry, NFSD_MAY_CREATE);
1290 	if (err)
1291 		goto out;
1292 
1293 	if (!(iap->ia_valid & ATTR_MODE))
1294 		iap->ia_mode = 0;
1295 	iap->ia_mode = (iap->ia_mode & S_IALLUGO) | type;
1296 
1297 	if (!IS_POSIXACL(dirp))
1298 		iap->ia_mode &= ~current_umask();
1299 
1300 	err = 0;
1301 	host_err = 0;
1302 	switch (type) {
1303 	case S_IFREG:
1304 		host_err = vfs_create(&init_user_ns, dirp, dchild, iap->ia_mode, true);
1305 		if (!host_err)
1306 			nfsd_check_ignore_resizing(iap);
1307 		break;
1308 	case S_IFDIR:
1309 		host_err = vfs_mkdir(&init_user_ns, dirp, dchild, iap->ia_mode);
1310 		if (!host_err && unlikely(d_unhashed(dchild))) {
1311 			struct dentry *d;
1312 			d = lookup_one_len(dchild->d_name.name,
1313 					   dchild->d_parent,
1314 					   dchild->d_name.len);
1315 			if (IS_ERR(d)) {
1316 				host_err = PTR_ERR(d);
1317 				break;
1318 			}
1319 			if (unlikely(d_is_negative(d))) {
1320 				dput(d);
1321 				err = nfserr_serverfault;
1322 				goto out;
1323 			}
1324 			dput(resfhp->fh_dentry);
1325 			resfhp->fh_dentry = dget(d);
1326 			err = fh_update(resfhp);
1327 			dput(dchild);
1328 			dchild = d;
1329 			if (err)
1330 				goto out;
1331 		}
1332 		break;
1333 	case S_IFCHR:
1334 	case S_IFBLK:
1335 	case S_IFIFO:
1336 	case S_IFSOCK:
1337 		host_err = vfs_mknod(&init_user_ns, dirp, dchild,
1338 				     iap->ia_mode, rdev);
1339 		break;
1340 	default:
1341 		printk(KERN_WARNING "nfsd: bad file type %o in nfsd_create\n",
1342 		       type);
1343 		host_err = -EINVAL;
1344 	}
1345 	if (host_err < 0)
1346 		goto out_nfserr;
1347 
1348 	err = nfsd_create_setattr(rqstp, fhp, resfhp, attrs);
1349 
1350 out:
1351 	dput(dchild);
1352 	return err;
1353 
1354 out_nfserr:
1355 	err = nfserrno(host_err);
1356 	goto out;
1357 }
1358 
1359 /*
1360  * Create a filesystem object (regular, directory, special).
1361  * Note that the parent directory is left locked.
1362  *
1363  * N.B. Every call to nfsd_create needs an fh_put for _both_ fhp and resfhp
1364  */
1365 __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)1366 nfsd_create(struct svc_rqst *rqstp, struct svc_fh *fhp,
1367 	    char *fname, int flen, struct nfsd_attrs *attrs,
1368 	    int type, dev_t rdev, struct svc_fh *resfhp)
1369 {
1370 	struct dentry	*dentry, *dchild = NULL;
1371 	__be32		err;
1372 	int		host_err;
1373 
1374 	if (isdotent(fname, flen))
1375 		return nfserr_exist;
1376 
1377 	err = fh_verify(rqstp, fhp, S_IFDIR, NFSD_MAY_NOP);
1378 	if (err)
1379 		return err;
1380 
1381 	dentry = fhp->fh_dentry;
1382 
1383 	host_err = fh_want_write(fhp);
1384 	if (host_err)
1385 		return nfserrno(host_err);
1386 
1387 	inode_lock_nested(dentry->d_inode, I_MUTEX_PARENT);
1388 	dchild = lookup_one_len(fname, dentry, flen);
1389 	host_err = PTR_ERR(dchild);
1390 	if (IS_ERR(dchild)) {
1391 		err = nfserrno(host_err);
1392 		goto out_unlock;
1393 	}
1394 	err = fh_compose(resfhp, fhp->fh_export, dchild, fhp);
1395 	/*
1396 	 * We unconditionally drop our ref to dchild as fh_compose will have
1397 	 * already grabbed its own ref for it.
1398 	 */
1399 	dput(dchild);
1400 	if (err)
1401 		goto out_unlock;
1402 	fh_fill_pre_attrs(fhp);
1403 	err = nfsd_create_locked(rqstp, fhp, attrs, type, rdev, resfhp);
1404 	fh_fill_post_attrs(fhp);
1405 out_unlock:
1406 	inode_unlock(dentry->d_inode);
1407 	return err;
1408 }
1409 
1410 /*
1411  * Read a symlink. On entry, *lenp must contain the maximum path length that
1412  * fits into the buffer. On return, it contains the true length.
1413  * N.B. After this call fhp needs an fh_put
1414  */
1415 __be32
nfsd_readlink(struct svc_rqst * rqstp,struct svc_fh * fhp,char * buf,int * lenp)1416 nfsd_readlink(struct svc_rqst *rqstp, struct svc_fh *fhp, char *buf, int *lenp)
1417 {
1418 	__be32		err;
1419 	const char *link;
1420 	struct path path;
1421 	DEFINE_DELAYED_CALL(done);
1422 	int len;
1423 
1424 	err = fh_verify(rqstp, fhp, S_IFLNK, NFSD_MAY_NOP);
1425 	if (unlikely(err))
1426 		return err;
1427 
1428 	path.mnt = fhp->fh_export->ex_path.mnt;
1429 	path.dentry = fhp->fh_dentry;
1430 
1431 	if (unlikely(!d_is_symlink(path.dentry)))
1432 		return nfserr_inval;
1433 
1434 	touch_atime(&path);
1435 
1436 	link = vfs_get_link(path.dentry, &done);
1437 	if (IS_ERR(link))
1438 		return nfserrno(PTR_ERR(link));
1439 
1440 	len = strlen(link);
1441 	if (len < *lenp)
1442 		*lenp = len;
1443 	memcpy(buf, link, *lenp);
1444 	do_delayed_call(&done);
1445 	return 0;
1446 }
1447 
1448 /**
1449  * nfsd_symlink - Create a symlink and look up its inode
1450  * @rqstp: RPC transaction being executed
1451  * @fhp: NFS filehandle of parent directory
1452  * @fname: filename of the new symlink
1453  * @flen: length of @fname
1454  * @path: content of the new symlink (NUL-terminated)
1455  * @attrs: requested attributes of new object
1456  * @resfhp: NFS filehandle of new object
1457  *
1458  * N.B. After this call _both_ fhp and resfhp need an fh_put
1459  *
1460  * Returns nfs_ok on success, or an nfsstat in network byte order.
1461  */
1462 __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)1463 nfsd_symlink(struct svc_rqst *rqstp, struct svc_fh *fhp,
1464 	     char *fname, int flen,
1465 	     char *path, struct nfsd_attrs *attrs,
1466 	     struct svc_fh *resfhp)
1467 {
1468 	struct dentry	*dentry, *dnew;
1469 	__be32		err, cerr;
1470 	int		host_err;
1471 
1472 	err = nfserr_noent;
1473 	if (!flen || path[0] == '\0')
1474 		goto out;
1475 	err = nfserr_exist;
1476 	if (isdotent(fname, flen))
1477 		goto out;
1478 
1479 	err = fh_verify(rqstp, fhp, S_IFDIR, NFSD_MAY_CREATE);
1480 	if (err)
1481 		goto out;
1482 
1483 	host_err = fh_want_write(fhp);
1484 	if (host_err) {
1485 		err = nfserrno(host_err);
1486 		goto out;
1487 	}
1488 
1489 	dentry = fhp->fh_dentry;
1490 	inode_lock_nested(dentry->d_inode, I_MUTEX_PARENT);
1491 	dnew = lookup_one_len(fname, dentry, flen);
1492 	if (IS_ERR(dnew)) {
1493 		err = nfserrno(PTR_ERR(dnew));
1494 		inode_unlock(dentry->d_inode);
1495 		goto out_drop_write;
1496 	}
1497 	fh_fill_pre_attrs(fhp);
1498 	host_err = vfs_symlink(&init_user_ns, d_inode(dentry), dnew, path);
1499 	err = nfserrno(host_err);
1500 	cerr = fh_compose(resfhp, fhp->fh_export, dnew, fhp);
1501 	if (!err)
1502 		nfsd_create_setattr(rqstp, fhp, resfhp, attrs);
1503 	fh_fill_post_attrs(fhp);
1504 	inode_unlock(dentry->d_inode);
1505 	if (!err)
1506 		err = nfserrno(commit_metadata(fhp));
1507 	dput(dnew);
1508 	if (err==0) err = cerr;
1509 out_drop_write:
1510 	fh_drop_write(fhp);
1511 out:
1512 	return err;
1513 }
1514 
1515 /*
1516  * Create a hardlink
1517  * N.B. After this call _both_ ffhp and tfhp need an fh_put
1518  */
1519 __be32
nfsd_link(struct svc_rqst * rqstp,struct svc_fh * ffhp,char * name,int len,struct svc_fh * tfhp)1520 nfsd_link(struct svc_rqst *rqstp, struct svc_fh *ffhp,
1521 				char *name, int len, struct svc_fh *tfhp)
1522 {
1523 	struct dentry	*ddir, *dnew, *dold;
1524 	struct inode	*dirp;
1525 	__be32		err;
1526 	int		host_err;
1527 
1528 	err = fh_verify(rqstp, ffhp, S_IFDIR, NFSD_MAY_CREATE);
1529 	if (err)
1530 		goto out;
1531 	err = fh_verify(rqstp, tfhp, 0, NFSD_MAY_NOP);
1532 	if (err)
1533 		goto out;
1534 	err = nfserr_isdir;
1535 	if (d_is_dir(tfhp->fh_dentry))
1536 		goto out;
1537 	err = nfserr_perm;
1538 	if (!len)
1539 		goto out;
1540 	err = nfserr_exist;
1541 	if (isdotent(name, len))
1542 		goto out;
1543 
1544 	host_err = fh_want_write(tfhp);
1545 	if (host_err) {
1546 		err = nfserrno(host_err);
1547 		goto out;
1548 	}
1549 
1550 	ddir = ffhp->fh_dentry;
1551 	dirp = d_inode(ddir);
1552 	inode_lock_nested(dirp, I_MUTEX_PARENT);
1553 
1554 	dnew = lookup_one_len(name, ddir, len);
1555 	if (IS_ERR(dnew)) {
1556 		err = nfserrno(PTR_ERR(dnew));
1557 		goto out_unlock;
1558 	}
1559 
1560 	dold = tfhp->fh_dentry;
1561 
1562 	err = nfserr_noent;
1563 	if (d_really_is_negative(dold))
1564 		goto out_dput;
1565 	fh_fill_pre_attrs(ffhp);
1566 	host_err = vfs_link(dold, &init_user_ns, dirp, dnew, NULL);
1567 	fh_fill_post_attrs(ffhp);
1568 	inode_unlock(dirp);
1569 	if (!host_err) {
1570 		err = nfserrno(commit_metadata(ffhp));
1571 		if (!err)
1572 			err = nfserrno(commit_metadata(tfhp));
1573 	} else {
1574 		if (host_err == -EXDEV && rqstp->rq_vers == 2)
1575 			err = nfserr_acces;
1576 		else
1577 			err = nfserrno(host_err);
1578 	}
1579 	dput(dnew);
1580 out_drop_write:
1581 	fh_drop_write(tfhp);
1582 out:
1583 	return err;
1584 
1585 out_dput:
1586 	dput(dnew);
1587 out_unlock:
1588 	inode_unlock(dirp);
1589 	goto out_drop_write;
1590 }
1591 
1592 static void
nfsd_close_cached_files(struct dentry * dentry)1593 nfsd_close_cached_files(struct dentry *dentry)
1594 {
1595 	struct inode *inode = d_inode(dentry);
1596 
1597 	if (inode && S_ISREG(inode->i_mode))
1598 		nfsd_file_close_inode_sync(inode);
1599 }
1600 
1601 static bool
nfsd_has_cached_files(struct dentry * dentry)1602 nfsd_has_cached_files(struct dentry *dentry)
1603 {
1604 	bool		ret = false;
1605 	struct inode *inode = d_inode(dentry);
1606 
1607 	if (inode && S_ISREG(inode->i_mode))
1608 		ret = nfsd_file_is_cached(inode);
1609 	return ret;
1610 }
1611 
1612 /*
1613  * Rename a file
1614  * N.B. After this call _both_ ffhp and tfhp need an fh_put
1615  */
1616 __be32
nfsd_rename(struct svc_rqst * rqstp,struct svc_fh * ffhp,char * fname,int flen,struct svc_fh * tfhp,char * tname,int tlen)1617 nfsd_rename(struct svc_rqst *rqstp, struct svc_fh *ffhp, char *fname, int flen,
1618 			    struct svc_fh *tfhp, char *tname, int tlen)
1619 {
1620 	struct dentry	*fdentry, *tdentry, *odentry, *ndentry, *trap;
1621 	struct inode	*fdir, *tdir;
1622 	__be32		err;
1623 	int		host_err;
1624 	bool		close_cached = false;
1625 
1626 	err = fh_verify(rqstp, ffhp, S_IFDIR, NFSD_MAY_REMOVE);
1627 	if (err)
1628 		goto out;
1629 	err = fh_verify(rqstp, tfhp, S_IFDIR, NFSD_MAY_CREATE);
1630 	if (err)
1631 		goto out;
1632 
1633 	fdentry = ffhp->fh_dentry;
1634 	fdir = d_inode(fdentry);
1635 
1636 	tdentry = tfhp->fh_dentry;
1637 	tdir = d_inode(tdentry);
1638 
1639 	err = nfserr_perm;
1640 	if (!flen || isdotent(fname, flen) || !tlen || isdotent(tname, tlen))
1641 		goto out;
1642 
1643 retry:
1644 	host_err = fh_want_write(ffhp);
1645 	if (host_err) {
1646 		err = nfserrno(host_err);
1647 		goto out;
1648 	}
1649 
1650 	trap = lock_rename(tdentry, fdentry);
1651 	fh_fill_pre_attrs(ffhp);
1652 	fh_fill_pre_attrs(tfhp);
1653 
1654 	odentry = lookup_one_len(fname, fdentry, flen);
1655 	host_err = PTR_ERR(odentry);
1656 	if (IS_ERR(odentry))
1657 		goto out_nfserr;
1658 
1659 	host_err = -ENOENT;
1660 	if (d_really_is_negative(odentry))
1661 		goto out_dput_old;
1662 	host_err = -EINVAL;
1663 	if (odentry == trap)
1664 		goto out_dput_old;
1665 
1666 	ndentry = lookup_one_len(tname, tdentry, tlen);
1667 	host_err = PTR_ERR(ndentry);
1668 	if (IS_ERR(ndentry))
1669 		goto out_dput_old;
1670 	host_err = -ENOTEMPTY;
1671 	if (ndentry == trap)
1672 		goto out_dput_new;
1673 
1674 	host_err = -EXDEV;
1675 	if (ffhp->fh_export->ex_path.mnt != tfhp->fh_export->ex_path.mnt)
1676 		goto out_dput_new;
1677 	if (ffhp->fh_export->ex_path.dentry != tfhp->fh_export->ex_path.dentry)
1678 		goto out_dput_new;
1679 
1680 	if ((ndentry->d_sb->s_export_op->flags & EXPORT_OP_CLOSE_BEFORE_UNLINK) &&
1681 	    nfsd_has_cached_files(ndentry)) {
1682 		close_cached = true;
1683 		goto out_dput_old;
1684 	} else {
1685 		struct renamedata rd = {
1686 			.old_mnt_userns	= &init_user_ns,
1687 			.old_dir	= fdir,
1688 			.old_dentry	= odentry,
1689 			.new_mnt_userns	= &init_user_ns,
1690 			.new_dir	= tdir,
1691 			.new_dentry	= ndentry,
1692 		};
1693 		int retries;
1694 
1695 		for (retries = 1;;) {
1696 			host_err = vfs_rename(&rd);
1697 			if (host_err != -EAGAIN || !retries--)
1698 				break;
1699 			if (!nfsd_wait_for_delegreturn(rqstp, d_inode(odentry)))
1700 				break;
1701 		}
1702 		if (!host_err) {
1703 			host_err = commit_metadata(tfhp);
1704 			if (!host_err)
1705 				host_err = commit_metadata(ffhp);
1706 		}
1707 	}
1708  out_dput_new:
1709 	dput(ndentry);
1710  out_dput_old:
1711 	dput(odentry);
1712  out_nfserr:
1713 	err = nfserrno(host_err);
1714 
1715 	if (!close_cached) {
1716 		fh_fill_post_attrs(ffhp);
1717 		fh_fill_post_attrs(tfhp);
1718 	}
1719 	unlock_rename(tdentry, fdentry);
1720 	fh_drop_write(ffhp);
1721 
1722 	/*
1723 	 * If the target dentry has cached open files, then we need to try to
1724 	 * close them prior to doing the rename. Flushing delayed fput
1725 	 * shouldn't be done with locks held however, so we delay it until this
1726 	 * point and then reattempt the whole shebang.
1727 	 */
1728 	if (close_cached) {
1729 		close_cached = false;
1730 		nfsd_close_cached_files(ndentry);
1731 		dput(ndentry);
1732 		goto retry;
1733 	}
1734 out:
1735 	return err;
1736 }
1737 
1738 /*
1739  * Unlink a file or directory
1740  * N.B. After this call fhp needs an fh_put
1741  */
1742 __be32
nfsd_unlink(struct svc_rqst * rqstp,struct svc_fh * fhp,int type,char * fname,int flen)1743 nfsd_unlink(struct svc_rqst *rqstp, struct svc_fh *fhp, int type,
1744 				char *fname, int flen)
1745 {
1746 	struct dentry	*dentry, *rdentry;
1747 	struct inode	*dirp;
1748 	struct inode	*rinode;
1749 	__be32		err;
1750 	int		host_err;
1751 
1752 	err = nfserr_acces;
1753 	if (!flen || isdotent(fname, flen))
1754 		goto out;
1755 	err = fh_verify(rqstp, fhp, S_IFDIR, NFSD_MAY_REMOVE);
1756 	if (err)
1757 		goto out;
1758 
1759 	host_err = fh_want_write(fhp);
1760 	if (host_err)
1761 		goto out_nfserr;
1762 
1763 	dentry = fhp->fh_dentry;
1764 	dirp = d_inode(dentry);
1765 	inode_lock_nested(dirp, I_MUTEX_PARENT);
1766 
1767 	rdentry = lookup_one_len(fname, dentry, flen);
1768 	host_err = PTR_ERR(rdentry);
1769 	if (IS_ERR(rdentry))
1770 		goto out_unlock;
1771 
1772 	if (d_really_is_negative(rdentry)) {
1773 		dput(rdentry);
1774 		host_err = -ENOENT;
1775 		goto out_unlock;
1776 	}
1777 	rinode = d_inode(rdentry);
1778 	ihold(rinode);
1779 
1780 	if (!type)
1781 		type = d_inode(rdentry)->i_mode & S_IFMT;
1782 
1783 	fh_fill_pre_attrs(fhp);
1784 	if (type != S_IFDIR) {
1785 		int retries;
1786 
1787 		if (rdentry->d_sb->s_export_op->flags & EXPORT_OP_CLOSE_BEFORE_UNLINK)
1788 			nfsd_close_cached_files(rdentry);
1789 
1790 		for (retries = 1;;) {
1791 			host_err = vfs_unlink(&init_user_ns, dirp, rdentry, NULL);
1792 			if (host_err != -EAGAIN || !retries--)
1793 				break;
1794 			if (!nfsd_wait_for_delegreturn(rqstp, rinode))
1795 				break;
1796 		}
1797 	} else {
1798 		host_err = vfs_rmdir(&init_user_ns, dirp, rdentry);
1799 	}
1800 	fh_fill_post_attrs(fhp);
1801 
1802 	inode_unlock(dirp);
1803 	if (!host_err)
1804 		host_err = commit_metadata(fhp);
1805 	dput(rdentry);
1806 	iput(rinode);    /* truncate the inode here */
1807 
1808 out_drop_write:
1809 	fh_drop_write(fhp);
1810 out_nfserr:
1811 	if (host_err == -EBUSY) {
1812 		/* name is mounted-on. There is no perfect
1813 		 * error status.
1814 		 */
1815 		if (nfsd_v4client(rqstp))
1816 			err = nfserr_file_open;
1817 		else
1818 			err = nfserr_acces;
1819 	} else {
1820 		err = nfserrno(host_err);
1821 	}
1822 out:
1823 	return err;
1824 out_unlock:
1825 	inode_unlock(dirp);
1826 	goto out_drop_write;
1827 }
1828 
1829 /*
1830  * We do this buffering because we must not call back into the file
1831  * system's ->lookup() method from the filldir callback. That may well
1832  * deadlock a number of file systems.
1833  *
1834  * This is based heavily on the implementation of same in XFS.
1835  */
1836 struct buffered_dirent {
1837 	u64		ino;
1838 	loff_t		offset;
1839 	int		namlen;
1840 	unsigned int	d_type;
1841 	char		name[];
1842 };
1843 
1844 struct readdir_data {
1845 	struct dir_context ctx;
1846 	char		*dirent;
1847 	size_t		used;
1848 	int		full;
1849 };
1850 
nfsd_buffered_filldir(struct dir_context * ctx,const char * name,int namlen,loff_t offset,u64 ino,unsigned int d_type)1851 static bool nfsd_buffered_filldir(struct dir_context *ctx, const char *name,
1852 				 int namlen, loff_t offset, u64 ino,
1853 				 unsigned int d_type)
1854 {
1855 	struct readdir_data *buf =
1856 		container_of(ctx, struct readdir_data, ctx);
1857 	struct buffered_dirent *de = (void *)(buf->dirent + buf->used);
1858 	unsigned int reclen;
1859 
1860 	reclen = ALIGN(sizeof(struct buffered_dirent) + namlen, sizeof(u64));
1861 	if (buf->used + reclen > PAGE_SIZE) {
1862 		buf->full = 1;
1863 		return false;
1864 	}
1865 
1866 	de->namlen = namlen;
1867 	de->offset = offset;
1868 	de->ino = ino;
1869 	de->d_type = d_type;
1870 	memcpy(de->name, name, namlen);
1871 	buf->used += reclen;
1872 
1873 	return true;
1874 }
1875 
nfsd_buffered_readdir(struct file * file,struct svc_fh * fhp,nfsd_filldir_t func,struct readdir_cd * cdp,loff_t * offsetp)1876 static __be32 nfsd_buffered_readdir(struct file *file, struct svc_fh *fhp,
1877 				    nfsd_filldir_t func, struct readdir_cd *cdp,
1878 				    loff_t *offsetp)
1879 {
1880 	struct buffered_dirent *de;
1881 	int host_err;
1882 	int size;
1883 	loff_t offset;
1884 	struct readdir_data buf = {
1885 		.ctx.actor = nfsd_buffered_filldir,
1886 		.dirent = (void *)__get_free_page(GFP_KERNEL)
1887 	};
1888 
1889 	if (!buf.dirent)
1890 		return nfserrno(-ENOMEM);
1891 
1892 	offset = *offsetp;
1893 
1894 	while (1) {
1895 		unsigned int reclen;
1896 
1897 		cdp->err = nfserr_eof; /* will be cleared on successful read */
1898 		buf.used = 0;
1899 		buf.full = 0;
1900 
1901 		host_err = iterate_dir(file, &buf.ctx);
1902 		if (buf.full)
1903 			host_err = 0;
1904 
1905 		if (host_err < 0)
1906 			break;
1907 
1908 		size = buf.used;
1909 
1910 		if (!size)
1911 			break;
1912 
1913 		de = (struct buffered_dirent *)buf.dirent;
1914 		while (size > 0) {
1915 			offset = de->offset;
1916 
1917 			if (func(cdp, de->name, de->namlen, de->offset,
1918 				 de->ino, de->d_type))
1919 				break;
1920 
1921 			if (cdp->err != nfs_ok)
1922 				break;
1923 
1924 			trace_nfsd_dirent(fhp, de->ino, de->name, de->namlen);
1925 
1926 			reclen = ALIGN(sizeof(*de) + de->namlen,
1927 				       sizeof(u64));
1928 			size -= reclen;
1929 			de = (struct buffered_dirent *)((char *)de + reclen);
1930 		}
1931 		if (size > 0) /* We bailed out early */
1932 			break;
1933 
1934 		offset = vfs_llseek(file, 0, SEEK_CUR);
1935 	}
1936 
1937 	free_page((unsigned long)(buf.dirent));
1938 
1939 	if (host_err)
1940 		return nfserrno(host_err);
1941 
1942 	*offsetp = offset;
1943 	return cdp->err;
1944 }
1945 
1946 /*
1947  * Read entries from a directory.
1948  * The  NFSv3/4 verifier we ignore for now.
1949  */
1950 __be32
nfsd_readdir(struct svc_rqst * rqstp,struct svc_fh * fhp,loff_t * offsetp,struct readdir_cd * cdp,nfsd_filldir_t func)1951 nfsd_readdir(struct svc_rqst *rqstp, struct svc_fh *fhp, loff_t *offsetp,
1952 	     struct readdir_cd *cdp, nfsd_filldir_t func)
1953 {
1954 	__be32		err;
1955 	struct file	*file;
1956 	loff_t		offset = *offsetp;
1957 	int             may_flags = NFSD_MAY_READ;
1958 
1959 	/* NFSv2 only supports 32 bit cookies */
1960 	if (rqstp->rq_vers > 2)
1961 		may_flags |= NFSD_MAY_64BIT_COOKIE;
1962 
1963 	err = nfsd_open(rqstp, fhp, S_IFDIR, may_flags, &file);
1964 	if (err)
1965 		goto out;
1966 
1967 	offset = vfs_llseek(file, offset, SEEK_SET);
1968 	if (offset < 0) {
1969 		err = nfserrno((int)offset);
1970 		goto out_close;
1971 	}
1972 
1973 	err = nfsd_buffered_readdir(file, fhp, func, cdp, offsetp);
1974 
1975 	if (err == nfserr_eof || err == nfserr_toosmall)
1976 		err = nfs_ok; /* can still be found in ->err */
1977 out_close:
1978 	fput(file);
1979 out:
1980 	return err;
1981 }
1982 
1983 /*
1984  * Get file system stats
1985  * N.B. After this call fhp needs an fh_put
1986  */
1987 __be32
nfsd_statfs(struct svc_rqst * rqstp,struct svc_fh * fhp,struct kstatfs * stat,int access)1988 nfsd_statfs(struct svc_rqst *rqstp, struct svc_fh *fhp, struct kstatfs *stat, int access)
1989 {
1990 	__be32 err;
1991 
1992 	err = fh_verify(rqstp, fhp, 0, NFSD_MAY_NOP | access);
1993 	if (!err) {
1994 		struct path path = {
1995 			.mnt	= fhp->fh_export->ex_path.mnt,
1996 			.dentry	= fhp->fh_dentry,
1997 		};
1998 		if (vfs_statfs(&path, stat))
1999 			err = nfserr_io;
2000 	}
2001 	return err;
2002 }
2003 
exp_rdonly(struct svc_rqst * rqstp,struct svc_export * exp)2004 static int exp_rdonly(struct svc_rqst *rqstp, struct svc_export *exp)
2005 {
2006 	return nfsexp_flags(rqstp, exp) & NFSEXP_READONLY;
2007 }
2008 
2009 #ifdef CONFIG_NFSD_V4
2010 /*
2011  * Helper function to translate error numbers. In the case of xattr operations,
2012  * some error codes need to be translated outside of the standard translations.
2013  *
2014  * ENODATA needs to be translated to nfserr_noxattr.
2015  * E2BIG to nfserr_xattr2big.
2016  *
2017  * Additionally, vfs_listxattr can return -ERANGE. This means that the
2018  * file has too many extended attributes to retrieve inside an
2019  * XATTR_LIST_MAX sized buffer. This is a bug in the xattr implementation:
2020  * filesystems will allow the adding of extended attributes until they hit
2021  * their own internal limit. This limit may be larger than XATTR_LIST_MAX.
2022  * So, at that point, the attributes are present and valid, but can't
2023  * be retrieved using listxattr, since the upper level xattr code enforces
2024  * the XATTR_LIST_MAX limit.
2025  *
2026  * This bug means that we need to deal with listxattr returning -ERANGE. The
2027  * best mapping is to return TOOSMALL.
2028  */
2029 static __be32
nfsd_xattr_errno(int err)2030 nfsd_xattr_errno(int err)
2031 {
2032 	switch (err) {
2033 	case -ENODATA:
2034 		return nfserr_noxattr;
2035 	case -E2BIG:
2036 		return nfserr_xattr2big;
2037 	case -ERANGE:
2038 		return nfserr_toosmall;
2039 	}
2040 	return nfserrno(err);
2041 }
2042 
2043 /*
2044  * Retrieve the specified user extended attribute. To avoid always
2045  * having to allocate the maximum size (since we are not getting
2046  * a maximum size from the RPC), do a probe + alloc. Hold a reader
2047  * lock on i_rwsem to prevent the extended attribute from changing
2048  * size while we're doing this.
2049  */
2050 __be32
nfsd_getxattr(struct svc_rqst * rqstp,struct svc_fh * fhp,char * name,void ** bufp,int * lenp)2051 nfsd_getxattr(struct svc_rqst *rqstp, struct svc_fh *fhp, char *name,
2052 	      void **bufp, int *lenp)
2053 {
2054 	ssize_t len;
2055 	__be32 err;
2056 	char *buf;
2057 	struct inode *inode;
2058 	struct dentry *dentry;
2059 
2060 	err = fh_verify(rqstp, fhp, 0, NFSD_MAY_READ);
2061 	if (err)
2062 		return err;
2063 
2064 	err = nfs_ok;
2065 	dentry = fhp->fh_dentry;
2066 	inode = d_inode(dentry);
2067 
2068 	inode_lock_shared(inode);
2069 
2070 	len = vfs_getxattr(&init_user_ns, dentry, name, NULL, 0);
2071 
2072 	/*
2073 	 * Zero-length attribute, just return.
2074 	 */
2075 	if (len == 0) {
2076 		*bufp = NULL;
2077 		*lenp = 0;
2078 		goto out;
2079 	}
2080 
2081 	if (len < 0) {
2082 		err = nfsd_xattr_errno(len);
2083 		goto out;
2084 	}
2085 
2086 	if (len > *lenp) {
2087 		err = nfserr_toosmall;
2088 		goto out;
2089 	}
2090 
2091 	buf = kvmalloc(len, GFP_KERNEL | GFP_NOFS);
2092 	if (buf == NULL) {
2093 		err = nfserr_jukebox;
2094 		goto out;
2095 	}
2096 
2097 	len = vfs_getxattr(&init_user_ns, dentry, name, buf, len);
2098 	if (len <= 0) {
2099 		kvfree(buf);
2100 		buf = NULL;
2101 		err = nfsd_xattr_errno(len);
2102 	}
2103 
2104 	*lenp = len;
2105 	*bufp = buf;
2106 
2107 out:
2108 	inode_unlock_shared(inode);
2109 
2110 	return err;
2111 }
2112 
2113 /*
2114  * Retrieve the xattr names. Since we can't know how many are
2115  * user extended attributes, we must get all attributes here,
2116  * and have the XDR encode filter out the "user." ones.
2117  *
2118  * While this could always just allocate an XATTR_LIST_MAX
2119  * buffer, that's a waste, so do a probe + allocate. To
2120  * avoid any changes between the probe and allocate, wrap
2121  * this in inode_lock.
2122  */
2123 __be32
nfsd_listxattr(struct svc_rqst * rqstp,struct svc_fh * fhp,char ** bufp,int * lenp)2124 nfsd_listxattr(struct svc_rqst *rqstp, struct svc_fh *fhp, char **bufp,
2125 	       int *lenp)
2126 {
2127 	ssize_t len;
2128 	__be32 err;
2129 	char *buf;
2130 	struct inode *inode;
2131 	struct dentry *dentry;
2132 
2133 	err = fh_verify(rqstp, fhp, 0, NFSD_MAY_READ);
2134 	if (err)
2135 		return err;
2136 
2137 	dentry = fhp->fh_dentry;
2138 	inode = d_inode(dentry);
2139 	*lenp = 0;
2140 
2141 	inode_lock_shared(inode);
2142 
2143 	len = vfs_listxattr(dentry, NULL, 0);
2144 	if (len <= 0) {
2145 		err = nfsd_xattr_errno(len);
2146 		goto out;
2147 	}
2148 
2149 	if (len > XATTR_LIST_MAX) {
2150 		err = nfserr_xattr2big;
2151 		goto out;
2152 	}
2153 
2154 	/*
2155 	 * We're holding i_rwsem - use GFP_NOFS.
2156 	 */
2157 	buf = kvmalloc(len, GFP_KERNEL | GFP_NOFS);
2158 	if (buf == NULL) {
2159 		err = nfserr_jukebox;
2160 		goto out;
2161 	}
2162 
2163 	len = vfs_listxattr(dentry, buf, len);
2164 	if (len <= 0) {
2165 		kvfree(buf);
2166 		err = nfsd_xattr_errno(len);
2167 		goto out;
2168 	}
2169 
2170 	*lenp = len;
2171 	*bufp = buf;
2172 
2173 	err = nfs_ok;
2174 out:
2175 	inode_unlock_shared(inode);
2176 
2177 	return err;
2178 }
2179 
2180 /**
2181  * nfsd_removexattr - Remove an extended attribute
2182  * @rqstp: RPC transaction being executed
2183  * @fhp: NFS filehandle of object with xattr to remove
2184  * @name: name of xattr to remove (NUL-terminate)
2185  *
2186  * Pass in a NULL pointer for delegated_inode, and let the client deal
2187  * with NFS4ERR_DELAY (same as with e.g. setattr and remove).
2188  *
2189  * Returns nfs_ok on success, or an nfsstat in network byte order.
2190  */
2191 __be32
nfsd_removexattr(struct svc_rqst * rqstp,struct svc_fh * fhp,char * name)2192 nfsd_removexattr(struct svc_rqst *rqstp, struct svc_fh *fhp, char *name)
2193 {
2194 	__be32 err;
2195 	int ret;
2196 
2197 	err = fh_verify(rqstp, fhp, 0, NFSD_MAY_WRITE);
2198 	if (err)
2199 		return err;
2200 
2201 	ret = fh_want_write(fhp);
2202 	if (ret)
2203 		return nfserrno(ret);
2204 
2205 	inode_lock(fhp->fh_dentry->d_inode);
2206 	fh_fill_pre_attrs(fhp);
2207 
2208 	ret = __vfs_removexattr_locked(&init_user_ns, fhp->fh_dentry,
2209 				       name, NULL);
2210 
2211 	fh_fill_post_attrs(fhp);
2212 	inode_unlock(fhp->fh_dentry->d_inode);
2213 	fh_drop_write(fhp);
2214 
2215 	return nfsd_xattr_errno(ret);
2216 }
2217 
2218 __be32
nfsd_setxattr(struct svc_rqst * rqstp,struct svc_fh * fhp,char * name,void * buf,u32 len,u32 flags)2219 nfsd_setxattr(struct svc_rqst *rqstp, struct svc_fh *fhp, char *name,
2220 	      void *buf, u32 len, u32 flags)
2221 {
2222 	__be32 err;
2223 	int ret;
2224 
2225 	err = fh_verify(rqstp, fhp, 0, NFSD_MAY_WRITE);
2226 	if (err)
2227 		return err;
2228 
2229 	ret = fh_want_write(fhp);
2230 	if (ret)
2231 		return nfserrno(ret);
2232 	inode_lock(fhp->fh_dentry->d_inode);
2233 	fh_fill_pre_attrs(fhp);
2234 
2235 	ret = __vfs_setxattr_locked(&init_user_ns, fhp->fh_dentry, name, buf,
2236 				    len, flags, NULL);
2237 	fh_fill_post_attrs(fhp);
2238 	inode_unlock(fhp->fh_dentry->d_inode);
2239 	fh_drop_write(fhp);
2240 
2241 	return nfsd_xattr_errno(ret);
2242 }
2243 #endif
2244 
2245 /*
2246  * Check for a user's access permissions to this inode.
2247  */
2248 __be32
nfsd_permission(struct svc_rqst * rqstp,struct svc_export * exp,struct dentry * dentry,int acc)2249 nfsd_permission(struct svc_rqst *rqstp, struct svc_export *exp,
2250 					struct dentry *dentry, int acc)
2251 {
2252 	struct inode	*inode = d_inode(dentry);
2253 	int		err;
2254 
2255 	if ((acc & NFSD_MAY_MASK) == NFSD_MAY_NOP)
2256 		return 0;
2257 #if 0
2258 	dprintk("nfsd: permission 0x%x%s%s%s%s%s%s%s mode 0%o%s%s%s\n",
2259 		acc,
2260 		(acc & NFSD_MAY_READ)?	" read"  : "",
2261 		(acc & NFSD_MAY_WRITE)?	" write" : "",
2262 		(acc & NFSD_MAY_EXEC)?	" exec"  : "",
2263 		(acc & NFSD_MAY_SATTR)?	" sattr" : "",
2264 		(acc & NFSD_MAY_TRUNC)?	" trunc" : "",
2265 		(acc & NFSD_MAY_LOCK)?	" lock"  : "",
2266 		(acc & NFSD_MAY_OWNER_OVERRIDE)? " owneroverride" : "",
2267 		inode->i_mode,
2268 		IS_IMMUTABLE(inode)?	" immut" : "",
2269 		IS_APPEND(inode)?	" append" : "",
2270 		__mnt_is_readonly(exp->ex_path.mnt)?	" ro" : "");
2271 	dprintk("      owner %d/%d user %d/%d\n",
2272 		inode->i_uid, inode->i_gid, current_fsuid(), current_fsgid());
2273 #endif
2274 
2275 	/* Normally we reject any write/sattr etc access on a read-only file
2276 	 * system.  But if it is IRIX doing check on write-access for a
2277 	 * device special file, we ignore rofs.
2278 	 */
2279 	if (!(acc & NFSD_MAY_LOCAL_ACCESS))
2280 		if (acc & (NFSD_MAY_WRITE | NFSD_MAY_SATTR | NFSD_MAY_TRUNC)) {
2281 			if (exp_rdonly(rqstp, exp) ||
2282 			    __mnt_is_readonly(exp->ex_path.mnt))
2283 				return nfserr_rofs;
2284 			if (/* (acc & NFSD_MAY_WRITE) && */ IS_IMMUTABLE(inode))
2285 				return nfserr_perm;
2286 		}
2287 	if ((acc & NFSD_MAY_TRUNC) && IS_APPEND(inode))
2288 		return nfserr_perm;
2289 
2290 	if (acc & NFSD_MAY_LOCK) {
2291 		/* If we cannot rely on authentication in NLM requests,
2292 		 * just allow locks, otherwise require read permission, or
2293 		 * ownership
2294 		 */
2295 		if (exp->ex_flags & NFSEXP_NOAUTHNLM)
2296 			return 0;
2297 		else
2298 			acc = NFSD_MAY_READ | NFSD_MAY_OWNER_OVERRIDE;
2299 	}
2300 	/*
2301 	 * The file owner always gets access permission for accesses that
2302 	 * would normally be checked at open time. This is to make
2303 	 * file access work even when the client has done a fchmod(fd, 0).
2304 	 *
2305 	 * However, `cp foo bar' should fail nevertheless when bar is
2306 	 * readonly. A sensible way to do this might be to reject all
2307 	 * attempts to truncate a read-only file, because a creat() call
2308 	 * always implies file truncation.
2309 	 * ... but this isn't really fair.  A process may reasonably call
2310 	 * ftruncate on an open file descriptor on a file with perm 000.
2311 	 * We must trust the client to do permission checking - using "ACCESS"
2312 	 * with NFSv3.
2313 	 */
2314 	if ((acc & NFSD_MAY_OWNER_OVERRIDE) &&
2315 	    uid_eq(inode->i_uid, current_fsuid()))
2316 		return 0;
2317 
2318 	/* This assumes  NFSD_MAY_{READ,WRITE,EXEC} == MAY_{READ,WRITE,EXEC} */
2319 	err = inode_permission(&init_user_ns, inode,
2320 			       acc & (MAY_READ | MAY_WRITE | MAY_EXEC));
2321 
2322 	/* Allow read access to binaries even when mode 111 */
2323 	if (err == -EACCES && S_ISREG(inode->i_mode) &&
2324 	     (acc == (NFSD_MAY_READ | NFSD_MAY_OWNER_OVERRIDE) ||
2325 	      acc == (NFSD_MAY_READ | NFSD_MAY_READ_IF_EXEC)))
2326 		err = inode_permission(&init_user_ns, inode, MAY_EXEC);
2327 
2328 	return err? nfserrno(err) : 0;
2329 }
2330