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