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