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 fsnotify_access(file);
1066 trace_nfsd_read_io_done(rqstp, fhp, offset, *count);
1067 return 0;
1068 } else {
1069 trace_nfsd_read_err(rqstp, fhp, offset, host_err);
1070 return nfserrno(host_err);
1071 }
1072 }
1073
1074 /**
1075 * nfsd_splice_read - Perform a VFS read using a splice pipe
1076 * @rqstp: RPC transaction context
1077 * @fhp: file handle of file to be read
1078 * @file: opened struct file of file to be read
1079 * @offset: starting byte offset
1080 * @count: IN: requested number of bytes; OUT: number of bytes read
1081 * @eof: OUT: set non-zero if operation reached the end of the file
1082 *
1083 * Returns nfs_ok on success, otherwise an nfserr stat value is
1084 * returned.
1085 */
nfsd_splice_read(struct svc_rqst * rqstp,struct svc_fh * fhp,struct file * file,loff_t offset,unsigned long * count,u32 * eof)1086 __be32 nfsd_splice_read(struct svc_rqst *rqstp, struct svc_fh *fhp,
1087 struct file *file, loff_t offset, unsigned long *count,
1088 u32 *eof)
1089 {
1090 struct splice_desc sd = {
1091 .len = 0,
1092 .total_len = *count,
1093 .pos = offset,
1094 .u.data = rqstp,
1095 };
1096 ssize_t host_err;
1097
1098 trace_nfsd_read_splice(rqstp, fhp, offset, *count);
1099 host_err = rw_verify_area(READ, file, &offset, *count);
1100 if (!host_err)
1101 host_err = splice_direct_to_actor(file, &sd,
1102 nfsd_direct_splice_actor);
1103 return nfsd_finish_read(rqstp, fhp, file, offset, count, eof, host_err);
1104 }
1105
1106 /*
1107 * The byte range of the client's READ request is expanded on both ends
1108 * until it meets the underlying file system's direct I/O alignment
1109 * requirements. After the internal read is complete, the byte range of
1110 * the NFS READ payload is reduced to the byte range that was originally
1111 * requested.
1112 *
1113 * Note that a direct read can be done only when the xdr_buf containing
1114 * the NFS READ reply does not already have contents in its .pages array.
1115 * This is due to potentially restrictive alignment requirements on the
1116 * read buffer. When .page_len and @base are zero, the .pages array is
1117 * guaranteed to be page-aligned.
1118 */
1119 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)1120 nfsd_direct_read(struct svc_rqst *rqstp, struct svc_fh *fhp,
1121 struct nfsd_file *nf, loff_t offset, unsigned long *count,
1122 u32 *eof)
1123 {
1124 u64 dio_start, dio_end;
1125 unsigned long v, total;
1126 struct iov_iter iter;
1127 struct kiocb kiocb;
1128 ssize_t host_err;
1129 size_t len;
1130
1131 init_sync_kiocb(&kiocb, nf->nf_file);
1132 kiocb.ki_flags |= IOCB_DIRECT;
1133
1134 /* Read a properly-aligned region of bytes into rq_bvec */
1135 dio_start = round_down(offset, nf->nf_dio_read_offset_align);
1136 dio_end = round_up((u64)offset + *count, nf->nf_dio_read_offset_align);
1137
1138 kiocb.ki_pos = dio_start;
1139
1140 v = 0;
1141 total = dio_end - dio_start;
1142 while (total && v < rqstp->rq_maxpages &&
1143 rqstp->rq_next_page < rqstp->rq_page_end) {
1144 len = min_t(size_t, total, PAGE_SIZE);
1145 bvec_set_page(&rqstp->rq_bvec[v], *rqstp->rq_next_page,
1146 len, 0);
1147
1148 total -= len;
1149 ++rqstp->rq_next_page;
1150 ++v;
1151 }
1152
1153 trace_nfsd_read_direct(rqstp, fhp, offset, *count - total);
1154 iov_iter_bvec(&iter, ITER_DEST, rqstp->rq_bvec, v,
1155 dio_end - dio_start - total);
1156
1157 host_err = vfs_iocb_iter_read(nf->nf_file, &kiocb, &iter);
1158 if (host_err >= 0) {
1159 unsigned int pad = offset - dio_start;
1160
1161 /* The returned payload starts after the pad */
1162 rqstp->rq_res.page_base = pad;
1163
1164 /* Compute the count of bytes to be returned */
1165 if (host_err > pad + *count)
1166 host_err = *count;
1167 else if (host_err > pad)
1168 host_err -= pad;
1169 else
1170 host_err = 0;
1171 } else if (unlikely(host_err == -EINVAL)) {
1172 struct inode *inode = d_inode(fhp->fh_dentry);
1173
1174 pr_info_ratelimited("nfsd: Direct I/O alignment failure on %s/%llu\n",
1175 inode->i_sb->s_id, inode->i_ino);
1176 host_err = -ESERVERFAULT;
1177 }
1178
1179 return nfsd_finish_read(rqstp, fhp, nf->nf_file, offset, count,
1180 eof, host_err);
1181 }
1182
1183 /**
1184 * nfsd_iter_read - Perform a VFS read using an iterator
1185 * @rqstp: RPC transaction context
1186 * @fhp: file handle of file to be read
1187 * @nf: opened struct nfsd_file of file to be read
1188 * @offset: starting byte offset
1189 * @count: IN: requested number of bytes; OUT: number of bytes read
1190 * @base: offset in first page of read buffer
1191 * @eof: OUT: set non-zero if operation reached the end of the file
1192 *
1193 * Some filesystems or situations cannot use nfsd_splice_read. This
1194 * function is the slightly less-performant fallback for those cases.
1195 *
1196 * Returns nfs_ok on success, otherwise an nfserr stat value is
1197 * returned.
1198 */
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)1199 __be32 nfsd_iter_read(struct svc_rqst *rqstp, struct svc_fh *fhp,
1200 struct nfsd_file *nf, loff_t offset, unsigned long *count,
1201 unsigned int base, u32 *eof)
1202 {
1203 struct file *file = nf->nf_file;
1204 unsigned long v, total;
1205 struct iov_iter iter;
1206 struct kiocb kiocb;
1207 ssize_t host_err;
1208 size_t len;
1209
1210 init_sync_kiocb(&kiocb, file);
1211
1212 switch (nfsd_io_cache_read) {
1213 case NFSD_IO_BUFFERED:
1214 break;
1215 case NFSD_IO_DIRECT:
1216 /* When dio_read_offset_align is zero, dio is not supported */
1217 if (nf->nf_dio_read_offset_align && !rqstp->rq_res.page_len)
1218 return nfsd_direct_read(rqstp, fhp, nf, offset,
1219 count, eof);
1220 fallthrough;
1221 case NFSD_IO_DONTCACHE:
1222 if (file->f_op->fop_flags & FOP_DONTCACHE)
1223 kiocb.ki_flags = IOCB_DONTCACHE;
1224 break;
1225 }
1226
1227 kiocb.ki_pos = offset;
1228
1229 v = 0;
1230 total = *count;
1231 while (total && v < rqstp->rq_maxpages &&
1232 rqstp->rq_next_page < rqstp->rq_page_end) {
1233 len = min_t(size_t, total, PAGE_SIZE - base);
1234 bvec_set_page(&rqstp->rq_bvec[v], *rqstp->rq_next_page,
1235 len, base);
1236
1237 total -= len;
1238 ++rqstp->rq_next_page;
1239 ++v;
1240 base = 0;
1241 }
1242
1243 trace_nfsd_read_vector(rqstp, fhp, offset, *count - total);
1244 iov_iter_bvec(&iter, ITER_DEST, rqstp->rq_bvec, v, *count - total);
1245 host_err = vfs_iocb_iter_read(file, &kiocb, &iter);
1246 return nfsd_finish_read(rqstp, fhp, file, offset, count, eof, host_err);
1247 }
1248
1249 /*
1250 * Gathered writes: If another process is currently writing to the file,
1251 * there's a high chance this is another nfsd (triggered by a bulk write
1252 * from a client's biod). Rather than syncing the file with each write
1253 * request, we sleep for 10 msec.
1254 *
1255 * I don't know if this roughly approximates C. Juszak's idea of
1256 * gathered writes, but it's a nice and simple solution (IMHO), and it
1257 * seems to work:-)
1258 *
1259 * Note: we do this only in the NFSv2 case, since v3 and higher have a
1260 * better tool (separate unstable writes and commits) for solving this
1261 * problem.
1262 */
wait_for_concurrent_writes(struct file * file)1263 static int wait_for_concurrent_writes(struct file *file)
1264 {
1265 struct inode *inode = file_inode(file);
1266 static ino_t last_ino;
1267 static dev_t last_dev;
1268 int err = 0;
1269
1270 if (atomic_read(&inode->i_writecount) > 1
1271 || (last_ino == inode->i_ino && last_dev == inode->i_sb->s_dev)) {
1272 dprintk("nfsd: write defer %d\n", task_pid_nr(current));
1273 msleep(10);
1274 dprintk("nfsd: write resume %d\n", task_pid_nr(current));
1275 }
1276
1277 if (inode_state_read_once(inode) & I_DIRTY) {
1278 dprintk("nfsd: write sync %d\n", task_pid_nr(current));
1279 err = vfs_fsync(file, 0);
1280 }
1281 last_ino = inode->i_ino;
1282 last_dev = inode->i_sb->s_dev;
1283 return err;
1284 }
1285
1286 struct nfsd_write_dio_seg {
1287 struct iov_iter iter;
1288 int flags;
1289 };
1290
1291 static unsigned long
iov_iter_bvec_offset(const struct iov_iter * iter)1292 iov_iter_bvec_offset(const struct iov_iter *iter)
1293 {
1294 return (unsigned long)(iter->bvec->bv_offset + iter->iov_offset);
1295 }
1296
1297 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)1298 nfsd_write_dio_seg_init(struct nfsd_write_dio_seg *segment,
1299 struct bio_vec *bvec, unsigned int nvecs,
1300 unsigned long total, size_t start, size_t len,
1301 struct kiocb *iocb)
1302 {
1303 iov_iter_bvec(&segment->iter, ITER_SOURCE, bvec, nvecs, total);
1304 if (start)
1305 iov_iter_advance(&segment->iter, start);
1306 iov_iter_truncate(&segment->iter, len);
1307 segment->flags = iocb->ki_flags;
1308 }
1309
1310 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])1311 nfsd_write_dio_iters_init(struct nfsd_file *nf, struct bio_vec *bvec,
1312 unsigned int nvecs, struct kiocb *iocb,
1313 unsigned long total,
1314 struct nfsd_write_dio_seg segments[3])
1315 {
1316 u32 offset_align = nf->nf_dio_offset_align;
1317 loff_t prefix_end, orig_end, middle_end;
1318 u32 mem_align = nf->nf_dio_mem_align;
1319 size_t prefix, middle, suffix;
1320 loff_t offset = iocb->ki_pos;
1321 unsigned int nsegs = 0;
1322
1323 /*
1324 * Check if direct I/O is feasible for this write request.
1325 * If alignments are not available, the write is too small,
1326 * or no alignment can be found, fall back to buffered I/O.
1327 */
1328 if (unlikely(!mem_align || !offset_align) ||
1329 unlikely(total < max(offset_align, mem_align)))
1330 goto no_dio;
1331
1332 prefix_end = round_up(offset, offset_align);
1333 orig_end = offset + total;
1334 middle_end = round_down(orig_end, offset_align);
1335
1336 prefix = prefix_end - offset;
1337 middle = middle_end - prefix_end;
1338 suffix = orig_end - middle_end;
1339
1340 if (!middle)
1341 goto no_dio;
1342
1343 if (prefix)
1344 nfsd_write_dio_seg_init(&segments[nsegs++], bvec,
1345 nvecs, total, 0, prefix, iocb);
1346
1347 nfsd_write_dio_seg_init(&segments[nsegs], bvec, nvecs,
1348 total, prefix, middle, iocb);
1349
1350 /*
1351 * Check if the bvec iterator is aligned for direct I/O.
1352 *
1353 * bvecs generated from RPC receive buffers are contiguous: After
1354 * the first bvec, all subsequent bvecs start at bv_offset zero
1355 * (page-aligned). Therefore, only the first bvec is checked.
1356 */
1357 if (iov_iter_bvec_offset(&segments[nsegs].iter) & (mem_align - 1))
1358 goto no_dio;
1359 segments[nsegs].flags |= IOCB_DIRECT;
1360 nsegs++;
1361
1362 if (suffix)
1363 nfsd_write_dio_seg_init(&segments[nsegs++], bvec, nvecs, total,
1364 prefix + middle, suffix, iocb);
1365
1366 return nsegs;
1367
1368 no_dio:
1369 /* No DIO alignment possible - pack into single non-DIO segment. */
1370 nfsd_write_dio_seg_init(&segments[0], bvec, nvecs, total, 0,
1371 total, iocb);
1372 return 1;
1373 }
1374
1375 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)1376 nfsd_direct_write(struct svc_rqst *rqstp, struct svc_fh *fhp,
1377 struct nfsd_file *nf, unsigned int nvecs,
1378 unsigned long *cnt, struct kiocb *kiocb)
1379 {
1380 struct nfsd_write_dio_seg segments[3];
1381 struct file *file = nf->nf_file;
1382 unsigned int nsegs, i;
1383 ssize_t host_err;
1384 size_t expected;
1385
1386 nsegs = nfsd_write_dio_iters_init(nf, rqstp->rq_bvec, nvecs,
1387 kiocb, *cnt, segments);
1388
1389 *cnt = 0;
1390 for (i = 0; i < nsegs; i++) {
1391 kiocb->ki_flags = segments[i].flags;
1392 if (kiocb->ki_flags & IOCB_DIRECT)
1393 trace_nfsd_write_direct(rqstp, fhp, kiocb->ki_pos,
1394 segments[i].iter.count);
1395 else {
1396 trace_nfsd_write_vector(rqstp, fhp, kiocb->ki_pos,
1397 segments[i].iter.count);
1398 /*
1399 * Mark the I/O buffer as evict-able to reduce
1400 * memory contention.
1401 */
1402 if (nf->nf_file->f_op->fop_flags & FOP_DONTCACHE)
1403 kiocb->ki_flags |= IOCB_DONTCACHE;
1404 }
1405
1406 expected = iov_iter_count(&segments[i].iter);
1407
1408 host_err = vfs_iocb_iter_write(file, kiocb, &segments[i].iter);
1409 if (host_err < 0)
1410 return host_err;
1411 *cnt += host_err;
1412 if (host_err < (ssize_t)expected)
1413 break; /* partial write */
1414 }
1415
1416 return 0;
1417 }
1418
1419 /**
1420 * nfsd_vfs_write - write data to an already-open file
1421 * @rqstp: RPC execution context
1422 * @fhp: File handle of file to write into
1423 * @nf: An open file matching @fhp
1424 * @offset: Byte offset of start
1425 * @payload: xdr_buf containing the write payload
1426 * @cnt: IN: number of bytes to write, OUT: number of bytes actually written
1427 * @stable: An NFS stable_how value
1428 * @verf: NFS WRITE verifier
1429 *
1430 * Upon return, caller must invoke fh_put on @fhp.
1431 *
1432 * Return values:
1433 * An nfsstat value in network byte order.
1434 */
1435 __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)1436 nfsd_vfs_write(struct svc_rqst *rqstp, struct svc_fh *fhp,
1437 struct nfsd_file *nf, loff_t offset,
1438 const struct xdr_buf *payload, unsigned long *cnt,
1439 int stable, __be32 *verf)
1440 {
1441 struct nfsd_net *nn = net_generic(SVC_NET(rqstp), nfsd_net_id);
1442 struct file *file = nf->nf_file;
1443 struct super_block *sb = file_inode(file)->i_sb;
1444 struct kiocb kiocb;
1445 struct svc_export *exp;
1446 struct iov_iter iter;
1447 errseq_t since;
1448 __be32 nfserr;
1449 int host_err;
1450 unsigned long exp_op_flags = 0;
1451 unsigned int pflags = current->flags;
1452 bool restore_flags = false;
1453 int nvecs;
1454
1455 trace_nfsd_write_opened(rqstp, fhp, offset, *cnt);
1456
1457 if (sb->s_export_op)
1458 exp_op_flags = sb->s_export_op->flags;
1459
1460 if (test_bit(RQ_LOCAL, &rqstp->rq_flags) &&
1461 !(exp_op_flags & EXPORT_OP_REMOTE_FS)) {
1462 /*
1463 * We want throttling in balance_dirty_pages()
1464 * and shrink_inactive_list() to only consider
1465 * the backingdev we are writing to, so that nfs to
1466 * localhost doesn't cause nfsd to lock up due to all
1467 * the client's dirty pages or its congested queue.
1468 */
1469 current->flags |= PF_LOCAL_THROTTLE;
1470 restore_flags = true;
1471 }
1472
1473 exp = fhp->fh_export;
1474
1475 if (!EX_ISSYNC(exp))
1476 stable = NFS_UNSTABLE;
1477 init_sync_kiocb(&kiocb, file);
1478 kiocb.ki_pos = offset;
1479 if (likely(!fhp->fh_use_wgather)) {
1480 switch (stable) {
1481 case NFS_FILE_SYNC:
1482 /* persist data and timestamps */
1483 kiocb.ki_flags |= IOCB_DSYNC | IOCB_SYNC;
1484 break;
1485 case NFS_DATA_SYNC:
1486 /* persist data only */
1487 kiocb.ki_flags |= IOCB_DSYNC;
1488 break;
1489 }
1490 }
1491
1492 nvecs = xdr_buf_to_bvec(rqstp->rq_bvec, rqstp->rq_maxpages, payload);
1493 if (nvecs < 0) {
1494 host_err = nvecs;
1495 goto out_nfserr;
1496 }
1497
1498 since = READ_ONCE(file->f_wb_err);
1499 if (verf)
1500 nfsd_copy_write_verifier(verf, nn);
1501
1502 switch (nfsd_io_cache_write) {
1503 case NFSD_IO_DIRECT:
1504 host_err = nfsd_direct_write(rqstp, fhp, nf, nvecs,
1505 cnt, &kiocb);
1506 break;
1507 case NFSD_IO_DONTCACHE:
1508 if (file->f_op->fop_flags & FOP_DONTCACHE)
1509 kiocb.ki_flags |= IOCB_DONTCACHE;
1510 fallthrough;
1511 case NFSD_IO_BUFFERED:
1512 iov_iter_bvec(&iter, ITER_SOURCE, rqstp->rq_bvec, nvecs, *cnt);
1513 host_err = vfs_iocb_iter_write(file, &kiocb, &iter);
1514 if (host_err < 0)
1515 break;
1516 *cnt = host_err;
1517 break;
1518 }
1519 if (host_err < 0) {
1520 commit_reset_write_verifier(nn, rqstp, host_err);
1521 goto out_nfserr;
1522 }
1523 nfsd_stats_io_write_add(nn, exp, *cnt);
1524 fsnotify_modify(file);
1525 host_err = filemap_check_wb_err(file->f_mapping, since);
1526 if (host_err < 0) {
1527 commit_reset_write_verifier(nn, rqstp, host_err);
1528 goto out_nfserr;
1529 }
1530
1531 if (stable && fhp->fh_use_wgather) {
1532 host_err = wait_for_concurrent_writes(file);
1533 if (host_err < 0)
1534 commit_reset_write_verifier(nn, rqstp, host_err);
1535 }
1536
1537 out_nfserr:
1538 if (host_err >= 0) {
1539 trace_nfsd_write_io_done(rqstp, fhp, offset, *cnt);
1540 nfserr = nfs_ok;
1541 } else {
1542 trace_nfsd_write_err(rqstp, fhp, offset, host_err);
1543 nfserr = nfserrno(host_err);
1544 }
1545 if (restore_flags)
1546 current_restore_flags(pflags, PF_LOCAL_THROTTLE);
1547 return nfserr;
1548 }
1549
1550 /**
1551 * nfsd_read_splice_ok - check if spliced reading is supported
1552 * @rqstp: RPC transaction context
1553 *
1554 * Return values:
1555 * %true: nfsd_splice_read() may be used
1556 * %false: nfsd_splice_read() must not be used
1557 *
1558 * NFS READ normally uses splice to send data in-place. However the
1559 * data in cache can change after the reply's MIC is computed but
1560 * before the RPC reply is sent. To prevent the client from
1561 * rejecting the server-computed MIC in this somewhat rare case, do
1562 * not use splice with the GSS integrity and privacy services.
1563 */
nfsd_read_splice_ok(struct svc_rqst * rqstp)1564 bool nfsd_read_splice_ok(struct svc_rqst *rqstp)
1565 {
1566 if (nfsd_disable_splice_read)
1567 return false;
1568 switch (svc_auth_flavor(rqstp)) {
1569 case RPC_AUTH_GSS_KRB5I:
1570 case RPC_AUTH_GSS_KRB5P:
1571 return false;
1572 }
1573 return true;
1574 }
1575
1576 /**
1577 * nfsd_read - Read data from a file
1578 * @rqstp: RPC transaction context
1579 * @fhp: file handle of file to be read
1580 * @offset: starting byte offset
1581 * @count: IN: requested number of bytes; OUT: number of bytes read
1582 * @eof: OUT: set non-zero if operation reached the end of the file
1583 *
1584 * The caller must verify that there is enough space in @rqstp.rq_res
1585 * to perform this operation.
1586 *
1587 * N.B. After this call fhp needs an fh_put
1588 *
1589 * Returns nfs_ok on success, otherwise an nfserr stat value is
1590 * returned.
1591 */
nfsd_read(struct svc_rqst * rqstp,struct svc_fh * fhp,loff_t offset,unsigned long * count,u32 * eof)1592 __be32 nfsd_read(struct svc_rqst *rqstp, struct svc_fh *fhp,
1593 loff_t offset, unsigned long *count, u32 *eof)
1594 {
1595 struct nfsd_file *nf;
1596 struct file *file;
1597 __be32 err;
1598
1599 trace_nfsd_read_start(rqstp, fhp, offset, *count);
1600 err = nfsd_file_acquire_gc(rqstp, fhp, NFSD_MAY_READ, &nf);
1601 if (err)
1602 return err;
1603
1604 file = nf->nf_file;
1605 if (file->f_op->splice_read && nfsd_read_splice_ok(rqstp))
1606 err = nfsd_splice_read(rqstp, fhp, file, offset, count, eof);
1607 else
1608 err = nfsd_iter_read(rqstp, fhp, nf, offset, count, 0, eof);
1609
1610 nfsd_file_put(nf);
1611 trace_nfsd_read_done(rqstp, fhp, offset, *count);
1612 return err;
1613 }
1614
1615 /**
1616 * nfsd_write - open a file and write data to it
1617 * @rqstp: RPC execution context
1618 * @fhp: File handle of file to write into; nfsd_write() may modify it
1619 * @offset: Byte offset of start
1620 * @payload: xdr_buf containing the write payload
1621 * @cnt: IN: number of bytes to write, OUT: number of bytes actually written
1622 * @stable: An NFS stable_how value
1623 * @verf: NFS WRITE verifier
1624 *
1625 * Upon return, caller must invoke fh_put on @fhp.
1626 *
1627 * Return values:
1628 * An nfsstat value in network byte order.
1629 */
1630 __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)1631 nfsd_write(struct svc_rqst *rqstp, struct svc_fh *fhp, loff_t offset,
1632 const struct xdr_buf *payload, unsigned long *cnt, int stable,
1633 __be32 *verf)
1634 {
1635 struct nfsd_file *nf;
1636 __be32 err;
1637
1638 trace_nfsd_write_start(rqstp, fhp, offset, *cnt);
1639
1640 err = nfsd_file_acquire_gc(rqstp, fhp, NFSD_MAY_WRITE, &nf);
1641 if (err)
1642 goto out;
1643
1644 err = nfsd_vfs_write(rqstp, fhp, nf, offset, payload, cnt,
1645 stable, verf);
1646 nfsd_file_put(nf);
1647 out:
1648 trace_nfsd_write_done(rqstp, fhp, offset, *cnt);
1649 return err;
1650 }
1651
1652 /**
1653 * nfsd_commit - Commit pending writes to stable storage
1654 * @rqstp: RPC request being processed
1655 * @fhp: NFS filehandle
1656 * @nf: target file
1657 * @offset: raw offset from beginning of file
1658 * @count: raw count of bytes to sync
1659 * @verf: filled in with the server's current write verifier
1660 *
1661 * Note: we guarantee that data that lies within the range specified
1662 * by the 'offset' and 'count' parameters will be synced. The server
1663 * is permitted to sync data that lies outside this range at the
1664 * same time.
1665 *
1666 * Unfortunately we cannot lock the file to make sure we return full WCC
1667 * data to the client, as locking happens lower down in the filesystem.
1668 *
1669 * Return values:
1670 * An nfsstat value in network byte order.
1671 */
1672 __be32
nfsd_commit(struct svc_rqst * rqstp,struct svc_fh * fhp,struct nfsd_file * nf,u64 offset,u32 count,__be32 * verf)1673 nfsd_commit(struct svc_rqst *rqstp, struct svc_fh *fhp, struct nfsd_file *nf,
1674 u64 offset, u32 count, __be32 *verf)
1675 {
1676 __be32 err = nfs_ok;
1677 u64 maxbytes;
1678 loff_t start, end;
1679 struct nfsd_net *nn;
1680
1681 trace_nfsd_commit_start(rqstp, fhp, offset, count);
1682
1683 /*
1684 * Convert the client-provided (offset, count) range to a
1685 * (start, end) range. If the client-provided range falls
1686 * outside the maximum file size of the underlying FS,
1687 * clamp the sync range appropriately.
1688 */
1689 start = 0;
1690 end = LLONG_MAX;
1691 maxbytes = (u64)fhp->fh_dentry->d_sb->s_maxbytes;
1692 if (offset < maxbytes) {
1693 start = offset;
1694 if (count && (offset + count - 1 < maxbytes))
1695 end = offset + count - 1;
1696 }
1697
1698 nn = net_generic(nf->nf_net, nfsd_net_id);
1699 if (EX_ISSYNC(fhp->fh_export)) {
1700 errseq_t since = READ_ONCE(nf->nf_file->f_wb_err);
1701 int err2;
1702
1703 err2 = vfs_fsync_range(nf->nf_file, start, end, 0);
1704 switch (err2) {
1705 case 0:
1706 nfsd_copy_write_verifier(verf, nn);
1707 err2 = filemap_check_wb_err(nf->nf_file->f_mapping,
1708 since);
1709 if (err2 < 0)
1710 commit_reset_write_verifier(nn, rqstp, err2);
1711 err = nfserrno(err2);
1712 break;
1713 case -EINVAL:
1714 err = nfserr_notsupp;
1715 break;
1716 default:
1717 commit_reset_write_verifier(nn, rqstp, err2);
1718 err = nfserrno(err2);
1719 }
1720 } else
1721 nfsd_copy_write_verifier(verf, nn);
1722
1723 trace_nfsd_commit_done(rqstp, fhp, offset, count);
1724 return err;
1725 }
1726
1727 /**
1728 * nfsd_create_setattr - Set a created file's attributes
1729 * @rqstp: RPC transaction being executed
1730 * @fhp: NFS filehandle of parent directory
1731 * @resfhp: NFS filehandle of new object
1732 * @attrs: requested attributes of new object
1733 *
1734 * Returns nfs_ok on success, or an nfsstat in network byte order.
1735 */
1736 __be32
nfsd_create_setattr(struct svc_rqst * rqstp,struct svc_fh * fhp,struct svc_fh * resfhp,struct nfsd_attrs * attrs)1737 nfsd_create_setattr(struct svc_rqst *rqstp, struct svc_fh *fhp,
1738 struct svc_fh *resfhp, struct nfsd_attrs *attrs)
1739 {
1740 struct iattr *iap = attrs->na_iattr;
1741 __be32 status;
1742
1743 /*
1744 * Mode has already been set by file creation.
1745 */
1746 iap->ia_valid &= ~ATTR_MODE;
1747
1748 /*
1749 * Setting uid/gid works only for root. Irix appears to
1750 * send along the gid on create when it tries to implement
1751 * setgid directories via NFS:
1752 */
1753 if (!uid_eq(current_fsuid(), GLOBAL_ROOT_UID))
1754 iap->ia_valid &= ~(ATTR_UID|ATTR_GID);
1755
1756 /*
1757 * Callers expect new file metadata to be committed even
1758 * if the attributes have not changed.
1759 */
1760 if (nfsd_attrs_valid(attrs))
1761 status = nfsd_setattr(rqstp, resfhp, attrs, NULL);
1762 else
1763 status = nfserrno(commit_metadata(resfhp));
1764
1765 /*
1766 * Transactional filesystems had a chance to commit changes
1767 * for both parent and child simultaneously making the
1768 * following commit_metadata a noop in many cases.
1769 */
1770 if (!status)
1771 status = nfserrno(commit_metadata(fhp));
1772
1773 /*
1774 * Update the new filehandle to pick up the new attributes.
1775 */
1776 if (!status)
1777 status = fh_update(resfhp);
1778
1779 return status;
1780 }
1781
1782 /* HPUX client sometimes creates a file in mode 000, and sets size to 0.
1783 * setting size to 0 may fail for some specific file systems by the permission
1784 * checking which requires WRITE permission but the mode is 000.
1785 * we ignore the resizing(to 0) on the just new created file, since the size is
1786 * 0 after file created.
1787 *
1788 * call this only after vfs_create() is called.
1789 * */
1790 static void
nfsd_check_ignore_resizing(struct iattr * iap)1791 nfsd_check_ignore_resizing(struct iattr *iap)
1792 {
1793 if ((iap->ia_valid & ATTR_SIZE) && (iap->ia_size == 0))
1794 iap->ia_valid &= ~ATTR_SIZE;
1795 }
1796
1797 /* The parent directory should already be locked - we will unlock */
1798 __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)1799 nfsd_create_locked(struct svc_rqst *rqstp, struct svc_fh *fhp,
1800 struct nfsd_attrs *attrs,
1801 int type, dev_t rdev, struct svc_fh *resfhp)
1802 {
1803 struct dentry *dentry, *dchild;
1804 struct inode *dirp;
1805 struct iattr *iap = attrs->na_iattr;
1806 __be32 err;
1807 int host_err = 0;
1808
1809 dentry = fhp->fh_dentry;
1810 dirp = d_inode(dentry);
1811
1812 dchild = dget(resfhp->fh_dentry);
1813 err = nfsd_permission(&rqstp->rq_cred, fhp->fh_export, dentry,
1814 NFSD_MAY_CREATE);
1815 if (err)
1816 goto out;
1817
1818 if (!(iap->ia_valid & ATTR_MODE))
1819 iap->ia_mode = 0;
1820 iap->ia_mode = (iap->ia_mode & S_IALLUGO) | type;
1821
1822 if (!IS_POSIXACL(dirp))
1823 iap->ia_mode &= ~current_umask();
1824
1825 err = 0;
1826 switch (type) {
1827 case S_IFREG:
1828 host_err = vfs_create(&nop_mnt_idmap, dchild, iap->ia_mode, NULL);
1829 if (!host_err)
1830 nfsd_check_ignore_resizing(iap);
1831 break;
1832 case S_IFDIR:
1833 dchild = vfs_mkdir(&nop_mnt_idmap, dirp, dchild, iap->ia_mode, NULL);
1834 if (IS_ERR(dchild)) {
1835 host_err = PTR_ERR(dchild);
1836 } else if (d_is_negative(dchild)) {
1837 err = nfserr_serverfault;
1838 goto out;
1839 } else if (unlikely(dchild != resfhp->fh_dentry)) {
1840 dput(resfhp->fh_dentry);
1841 resfhp->fh_dentry = dget(dchild);
1842 }
1843 break;
1844 case S_IFCHR:
1845 case S_IFBLK:
1846 case S_IFIFO:
1847 case S_IFSOCK:
1848 host_err = vfs_mknod(&nop_mnt_idmap, dirp, dchild,
1849 iap->ia_mode, rdev, NULL);
1850 break;
1851 default:
1852 printk(KERN_WARNING "nfsd: bad file type %o in nfsd_create\n",
1853 type);
1854 host_err = -EINVAL;
1855 }
1856 if (host_err < 0)
1857 goto out_nfserr;
1858
1859 err = nfsd_create_setattr(rqstp, fhp, resfhp, attrs);
1860
1861 out:
1862 if (!err)
1863 fh_fill_post_attrs(fhp);
1864 end_creating(dchild);
1865 return err;
1866
1867 out_nfserr:
1868 err = nfserrno(host_err);
1869 goto out;
1870 }
1871
1872 /*
1873 * Create a filesystem object (regular, directory, special).
1874 * Note that the parent directory is left locked.
1875 *
1876 * N.B. Every call to nfsd_create needs an fh_put for _both_ fhp and resfhp
1877 */
1878 __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)1879 nfsd_create(struct svc_rqst *rqstp, struct svc_fh *fhp,
1880 char *fname, int flen, struct nfsd_attrs *attrs,
1881 int type, dev_t rdev, struct svc_fh *resfhp)
1882 {
1883 struct dentry *dentry, *dchild = NULL;
1884 __be32 err;
1885 int host_err;
1886
1887 trace_nfsd_vfs_create(rqstp, fhp, type, fname, flen);
1888
1889 if (name_is_dot_dotdot(fname, flen))
1890 return nfserr_exist;
1891
1892 err = fh_verify(rqstp, fhp, S_IFDIR, NFSD_MAY_NOP);
1893 if (err)
1894 return err;
1895
1896 dentry = fhp->fh_dentry;
1897
1898 host_err = fh_want_write(fhp);
1899 if (host_err)
1900 return nfserrno(host_err);
1901
1902 dchild = start_creating(&nop_mnt_idmap, dentry, &QSTR_LEN(fname, flen));
1903 host_err = PTR_ERR(dchild);
1904 if (IS_ERR(dchild))
1905 return nfserrno(host_err);
1906
1907 err = fh_compose(resfhp, fhp->fh_export, dchild, fhp);
1908 if (err)
1909 goto out_unlock;
1910 err = fh_fill_pre_attrs(fhp);
1911 if (err != nfs_ok)
1912 goto out_unlock;
1913 err = nfsd_create_locked(rqstp, fhp, attrs, type, rdev, resfhp);
1914 /* nfsd_create_locked() unlocked the parent */
1915 dput(dchild);
1916 return err;
1917
1918 out_unlock:
1919 end_creating(dchild);
1920 return err;
1921 }
1922
1923 /*
1924 * Read a symlink. On entry, *lenp must contain the maximum path length that
1925 * fits into the buffer. On return, it contains the true length.
1926 * N.B. After this call fhp needs an fh_put
1927 */
1928 __be32
nfsd_readlink(struct svc_rqst * rqstp,struct svc_fh * fhp,char * buf,int * lenp)1929 nfsd_readlink(struct svc_rqst *rqstp, struct svc_fh *fhp, char *buf, int *lenp)
1930 {
1931 __be32 err;
1932 const char *link;
1933 struct path path;
1934 DEFINE_DELAYED_CALL(done);
1935 int len;
1936
1937 err = fh_verify(rqstp, fhp, S_IFLNK, NFSD_MAY_NOP);
1938 if (unlikely(err))
1939 return err;
1940
1941 path.mnt = fhp->fh_export->ex_path.mnt;
1942 path.dentry = fhp->fh_dentry;
1943
1944 if (unlikely(!d_is_symlink(path.dentry)))
1945 return nfserr_inval;
1946
1947 touch_atime(&path);
1948
1949 link = vfs_get_link(path.dentry, &done);
1950 if (IS_ERR(link))
1951 return nfserrno(PTR_ERR(link));
1952
1953 len = strlen(link);
1954 if (len < *lenp)
1955 *lenp = len;
1956 memcpy(buf, link, *lenp);
1957 do_delayed_call(&done);
1958 return 0;
1959 }
1960
1961 /**
1962 * nfsd_symlink - Create a symlink and look up its inode
1963 * @rqstp: RPC transaction being executed
1964 * @fhp: NFS filehandle of parent directory
1965 * @fname: filename of the new symlink
1966 * @flen: length of @fname
1967 * @path: content of the new symlink (NUL-terminated)
1968 * @attrs: requested attributes of new object
1969 * @resfhp: NFS filehandle of new object
1970 *
1971 * N.B. After this call _both_ fhp and resfhp need an fh_put
1972 *
1973 * Returns nfs_ok on success, or an nfsstat in network byte order.
1974 */
1975 __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)1976 nfsd_symlink(struct svc_rqst *rqstp, struct svc_fh *fhp,
1977 char *fname, int flen,
1978 char *path, struct nfsd_attrs *attrs,
1979 struct svc_fh *resfhp)
1980 {
1981 struct dentry *dentry, *dnew;
1982 __be32 err, cerr;
1983 int host_err;
1984
1985 trace_nfsd_vfs_symlink(rqstp, fhp, fname, flen, path);
1986
1987 err = nfserr_noent;
1988 if (!flen || path[0] == '\0')
1989 goto out;
1990 err = nfserr_exist;
1991 if (name_is_dot_dotdot(fname, flen))
1992 goto out;
1993
1994 err = fh_verify(rqstp, fhp, S_IFDIR, NFSD_MAY_CREATE);
1995 if (err)
1996 goto out;
1997
1998 host_err = fh_want_write(fhp);
1999 if (host_err) {
2000 err = nfserrno(host_err);
2001 goto out;
2002 }
2003
2004 dentry = fhp->fh_dentry;
2005 dnew = start_creating(&nop_mnt_idmap, dentry, &QSTR_LEN(fname, flen));
2006 if (IS_ERR(dnew)) {
2007 err = nfserrno(PTR_ERR(dnew));
2008 goto out_drop_write;
2009 }
2010 err = fh_fill_pre_attrs(fhp);
2011 if (err != nfs_ok)
2012 goto out_unlock;
2013 host_err = vfs_symlink(&nop_mnt_idmap, d_inode(dentry), dnew, path, NULL);
2014 err = nfserrno(host_err);
2015 cerr = fh_compose(resfhp, fhp->fh_export, dnew, fhp);
2016 if (!err)
2017 nfsd_create_setattr(rqstp, fhp, resfhp, attrs);
2018 fh_fill_post_attrs(fhp);
2019 out_unlock:
2020 end_creating(dnew);
2021 if (!err)
2022 err = nfserrno(commit_metadata(fhp));
2023 if (!err)
2024 err = cerr;
2025 out_drop_write:
2026 fh_drop_write(fhp);
2027 out:
2028 return err;
2029 }
2030
2031 /**
2032 * nfsd_link - create a link
2033 * @rqstp: RPC transaction context
2034 * @ffhp: the file handle of the directory where the new link is to be created
2035 * @name: the filename of the new link
2036 * @len: the length of @name in octets
2037 * @tfhp: the file handle of an existing file object
2038 *
2039 * After this call _both_ ffhp and tfhp need an fh_put.
2040 *
2041 * Returns a generic NFS status code in network byte-order.
2042 */
2043 __be32
nfsd_link(struct svc_rqst * rqstp,struct svc_fh * ffhp,char * name,int len,struct svc_fh * tfhp)2044 nfsd_link(struct svc_rqst *rqstp, struct svc_fh *ffhp,
2045 char *name, int len, struct svc_fh *tfhp)
2046 {
2047 struct dentry *ddir, *dnew, *dold;
2048 struct inode *dirp;
2049 int type;
2050 __be32 err;
2051 int host_err;
2052
2053 trace_nfsd_vfs_link(rqstp, ffhp, tfhp, name, len);
2054
2055 err = fh_verify(rqstp, ffhp, S_IFDIR, NFSD_MAY_CREATE);
2056 if (err)
2057 goto out;
2058 err = fh_verify(rqstp, tfhp, 0, NFSD_MAY_NOP);
2059 if (err)
2060 goto out;
2061 err = nfserr_isdir;
2062 if (d_is_dir(tfhp->fh_dentry))
2063 goto out;
2064 err = nfserr_perm;
2065 if (!len)
2066 goto out;
2067 err = nfserr_exist;
2068 if (name_is_dot_dotdot(name, len))
2069 goto out;
2070
2071 err = nfs_ok;
2072 type = d_inode(tfhp->fh_dentry)->i_mode & S_IFMT;
2073 host_err = fh_want_write(tfhp);
2074 if (host_err)
2075 goto out;
2076
2077 ddir = ffhp->fh_dentry;
2078 dirp = d_inode(ddir);
2079 dnew = start_creating(&nop_mnt_idmap, ddir, &QSTR_LEN(name, len));
2080
2081 if (IS_ERR(dnew)) {
2082 host_err = PTR_ERR(dnew);
2083 goto out_drop_write;
2084 }
2085
2086 dold = tfhp->fh_dentry;
2087
2088 err = nfserr_noent;
2089 if (d_really_is_negative(dold))
2090 goto out_unlock;
2091 err = fh_fill_pre_attrs(ffhp);
2092 if (err != nfs_ok)
2093 goto out_unlock;
2094 host_err = vfs_link(dold, &nop_mnt_idmap, dirp, dnew, NULL);
2095 fh_fill_post_attrs(ffhp);
2096 out_unlock:
2097 end_creating(dnew);
2098 if (!host_err) {
2099 host_err = commit_metadata(ffhp);
2100 if (!host_err)
2101 host_err = commit_metadata(tfhp);
2102 }
2103
2104 out_drop_write:
2105 fh_drop_write(tfhp);
2106 if (host_err == -EBUSY) {
2107 /*
2108 * See RFC 8881 Section 18.9.4 para 1-2: NFSv4 LINK
2109 * wants a status unique to the object type.
2110 */
2111 if (type != S_IFDIR)
2112 err = nfserr_file_open;
2113 else
2114 err = nfserr_acces;
2115 }
2116 out:
2117 return err != nfs_ok ? err : nfserrno(host_err);
2118 }
2119
2120 static void
nfsd_close_cached_files(struct dentry * dentry)2121 nfsd_close_cached_files(struct dentry *dentry)
2122 {
2123 struct inode *inode = d_inode(dentry);
2124
2125 if (inode && S_ISREG(inode->i_mode))
2126 nfsd_file_close_inode_sync(inode);
2127 }
2128
2129 static bool
nfsd_has_cached_files(struct dentry * dentry)2130 nfsd_has_cached_files(struct dentry *dentry)
2131 {
2132 bool ret = false;
2133 struct inode *inode = d_inode(dentry);
2134
2135 if (inode && S_ISREG(inode->i_mode))
2136 ret = nfsd_file_is_cached(inode);
2137 return ret;
2138 }
2139
2140 /**
2141 * nfsd_rename - rename a directory entry
2142 * @rqstp: RPC transaction context
2143 * @ffhp: the file handle of parent directory containing the entry to be renamed
2144 * @fname: the filename of directory entry to be renamed
2145 * @flen: the length of @fname in octets
2146 * @tfhp: the file handle of parent directory to contain the renamed entry
2147 * @tname: the filename of the new entry
2148 * @tlen: the length of @tlen in octets
2149 *
2150 * After this call _both_ ffhp and tfhp need an fh_put.
2151 *
2152 * Returns a generic NFS status code in network byte-order.
2153 */
2154 __be32
nfsd_rename(struct svc_rqst * rqstp,struct svc_fh * ffhp,char * fname,int flen,struct svc_fh * tfhp,char * tname,int tlen)2155 nfsd_rename(struct svc_rqst *rqstp, struct svc_fh *ffhp, char *fname, int flen,
2156 struct svc_fh *tfhp, char *tname, int tlen)
2157 {
2158 struct dentry *fdentry, *tdentry;
2159 int type = S_IFDIR;
2160 struct renamedata rd = {};
2161 __be32 err;
2162 int host_err;
2163 struct dentry *close_cached;
2164
2165 trace_nfsd_vfs_rename(rqstp, ffhp, tfhp, fname, flen, tname, tlen);
2166
2167 err = fh_verify(rqstp, ffhp, S_IFDIR, NFSD_MAY_REMOVE);
2168 if (err)
2169 goto out;
2170 err = fh_verify(rqstp, tfhp, S_IFDIR, NFSD_MAY_CREATE);
2171 if (err)
2172 goto out;
2173
2174 fdentry = ffhp->fh_dentry;
2175
2176 tdentry = tfhp->fh_dentry;
2177
2178 err = nfserr_perm;
2179 if (!flen || name_is_dot_dotdot(fname, flen) ||
2180 !tlen || name_is_dot_dotdot(tname, tlen))
2181 goto out;
2182
2183 err = nfserr_xdev;
2184 if (ffhp->fh_export->ex_path.mnt != tfhp->fh_export->ex_path.mnt)
2185 goto out;
2186 if (ffhp->fh_export->ex_path.dentry != tfhp->fh_export->ex_path.dentry)
2187 goto out;
2188
2189 retry:
2190 close_cached = NULL;
2191 host_err = fh_want_write(ffhp);
2192 if (host_err) {
2193 err = nfserrno(host_err);
2194 goto out;
2195 }
2196
2197 rd.mnt_idmap = &nop_mnt_idmap;
2198 rd.old_parent = fdentry;
2199 rd.new_parent = tdentry;
2200
2201 host_err = start_renaming(&rd, 0, &QSTR_LEN(fname, flen),
2202 &QSTR_LEN(tname, tlen));
2203
2204 if (host_err) {
2205 err = nfserrno(host_err);
2206 goto out_want_write;
2207 }
2208 err = fh_fill_pre_attrs(ffhp);
2209 if (err != nfs_ok)
2210 goto out_unlock;
2211 err = fh_fill_pre_attrs(tfhp);
2212 if (err != nfs_ok)
2213 goto out_unlock;
2214
2215 type = d_inode(rd.old_dentry)->i_mode & S_IFMT;
2216
2217 if (d_inode(rd.new_dentry))
2218 type = d_inode(rd.new_dentry)->i_mode & S_IFMT;
2219
2220 if ((rd.new_dentry->d_sb->s_export_op->flags & EXPORT_OP_CLOSE_BEFORE_UNLINK) &&
2221 nfsd_has_cached_files(rd.new_dentry)) {
2222 close_cached = dget(rd.new_dentry);
2223 goto out_unlock;
2224 } else {
2225 int retries;
2226
2227 for (retries = 1;;) {
2228 host_err = vfs_rename(&rd);
2229 if (host_err != -EAGAIN || !retries--)
2230 break;
2231 if (!nfsd_wait_for_delegreturn(rqstp, d_inode(rd.old_dentry)))
2232 break;
2233 }
2234 if (!host_err) {
2235 host_err = commit_metadata(tfhp);
2236 if (!host_err)
2237 host_err = commit_metadata(ffhp);
2238 }
2239 }
2240 if (host_err == -EBUSY) {
2241 /*
2242 * See RFC 8881 Section 18.26.4 para 1-3: NFSv4 RENAME
2243 * wants a status unique to the object type.
2244 */
2245 if (type != S_IFDIR)
2246 err = nfserr_file_open;
2247 else
2248 err = nfserr_acces;
2249 } else {
2250 err = nfserrno(host_err);
2251 }
2252
2253 if (!close_cached) {
2254 fh_fill_post_attrs(ffhp);
2255 fh_fill_post_attrs(tfhp);
2256 }
2257 out_unlock:
2258 end_renaming(&rd);
2259 out_want_write:
2260 fh_drop_write(ffhp);
2261
2262 /*
2263 * If the target dentry has cached open files, then we need to
2264 * try to close them prior to doing the rename. Final fput
2265 * shouldn't be done with locks held however, so we delay it
2266 * until this point and then reattempt the whole shebang.
2267 */
2268 if (close_cached) {
2269 nfsd_close_cached_files(close_cached);
2270 dput(close_cached);
2271 goto retry;
2272 }
2273 out:
2274 return err;
2275 }
2276
2277 /**
2278 * nfsd_unlink - remove a directory entry
2279 * @rqstp: RPC transaction context
2280 * @fhp: the file handle of the parent directory to be modified
2281 * @type: enforced file type of the object to be removed
2282 * @fname: the name of directory entry to be removed
2283 * @flen: length of @fname in octets
2284 *
2285 * After this call fhp needs an fh_put.
2286 *
2287 * Returns a generic NFS status code in network byte-order.
2288 */
2289 __be32
nfsd_unlink(struct svc_rqst * rqstp,struct svc_fh * fhp,int type,char * fname,int flen)2290 nfsd_unlink(struct svc_rqst *rqstp, struct svc_fh *fhp, int type,
2291 char *fname, int flen)
2292 {
2293 struct dentry *dentry, *rdentry;
2294 struct inode *dirp;
2295 struct inode *rinode = NULL;
2296 __be32 err;
2297 int host_err;
2298
2299 trace_nfsd_vfs_unlink(rqstp, fhp, fname, flen);
2300
2301 err = nfserr_acces;
2302 if (!flen || name_is_dot_dotdot(fname, flen))
2303 goto out;
2304 err = fh_verify(rqstp, fhp, S_IFDIR, NFSD_MAY_REMOVE);
2305 if (err)
2306 goto out;
2307
2308 host_err = fh_want_write(fhp);
2309 if (host_err)
2310 goto out_nfserr;
2311
2312 dentry = fhp->fh_dentry;
2313 dirp = d_inode(dentry);
2314
2315 rdentry = start_removing(&nop_mnt_idmap, dentry, &QSTR_LEN(fname, flen));
2316
2317 host_err = PTR_ERR(rdentry);
2318 if (IS_ERR(rdentry))
2319 goto out_drop_write;
2320
2321 err = fh_fill_pre_attrs(fhp);
2322 if (err != nfs_ok)
2323 goto out_unlock;
2324
2325 rinode = d_inode(rdentry);
2326 /* Prevent truncation until after locks dropped */
2327 ihold(rinode);
2328
2329 if (!type)
2330 type = d_inode(rdentry)->i_mode & S_IFMT;
2331
2332 if (type != S_IFDIR) {
2333 int retries;
2334
2335 if (rdentry->d_sb->s_export_op->flags & EXPORT_OP_CLOSE_BEFORE_UNLINK)
2336 nfsd_close_cached_files(rdentry);
2337
2338 for (retries = 1;;) {
2339 host_err = vfs_unlink(&nop_mnt_idmap, dirp, rdentry, NULL);
2340 if (host_err != -EAGAIN || !retries--)
2341 break;
2342 if (!nfsd_wait_for_delegreturn(rqstp, rinode))
2343 break;
2344 }
2345 } else {
2346 host_err = vfs_rmdir(&nop_mnt_idmap, dirp, rdentry, NULL);
2347 }
2348 fh_fill_post_attrs(fhp);
2349
2350 out_unlock:
2351 end_removing(rdentry);
2352 if (!err && !host_err)
2353 host_err = commit_metadata(fhp);
2354 iput(rinode); /* truncate the inode here */
2355
2356 out_drop_write:
2357 fh_drop_write(fhp);
2358 out_nfserr:
2359 if (host_err == -EBUSY) {
2360 /*
2361 * See RFC 8881 Section 18.25.4 para 4: NFSv4 REMOVE
2362 * wants a status unique to the object type.
2363 */
2364 if (type != S_IFDIR)
2365 err = nfserr_file_open;
2366 else
2367 err = nfserr_acces;
2368 }
2369 out:
2370 return err != nfs_ok ? err : nfserrno(host_err);
2371 }
2372
2373 /*
2374 * We do this buffering because we must not call back into the file
2375 * system's ->lookup() method from the filldir callback. That may well
2376 * deadlock a number of file systems.
2377 *
2378 * This is based heavily on the implementation of same in XFS.
2379 */
2380 struct buffered_dirent {
2381 u64 ino;
2382 loff_t offset;
2383 int namlen;
2384 unsigned int d_type;
2385 char name[];
2386 };
2387
2388 struct readdir_data {
2389 struct dir_context ctx;
2390 char *dirent;
2391 size_t used;
2392 int full;
2393 };
2394
nfsd_buffered_filldir(struct dir_context * ctx,const char * name,int namlen,loff_t offset,u64 ino,unsigned int d_type)2395 static bool nfsd_buffered_filldir(struct dir_context *ctx, const char *name,
2396 int namlen, loff_t offset, u64 ino,
2397 unsigned int d_type)
2398 {
2399 struct readdir_data *buf =
2400 container_of(ctx, struct readdir_data, ctx);
2401 struct buffered_dirent *de = (void *)(buf->dirent + buf->used);
2402 unsigned int reclen;
2403
2404 reclen = ALIGN(sizeof(struct buffered_dirent) + namlen, sizeof(u64));
2405 if (buf->used + reclen > PAGE_SIZE) {
2406 buf->full = 1;
2407 return false;
2408 }
2409
2410 de->namlen = namlen;
2411 de->offset = offset;
2412 de->ino = ino;
2413 de->d_type = d_type;
2414 memcpy(de->name, name, namlen);
2415 buf->used += reclen;
2416
2417 return true;
2418 }
2419
nfsd_buffered_readdir(struct file * file,struct svc_fh * fhp,nfsd_filldir_t func,struct readdir_cd * cdp,loff_t * offsetp)2420 static __be32 nfsd_buffered_readdir(struct file *file, struct svc_fh *fhp,
2421 nfsd_filldir_t func, struct readdir_cd *cdp,
2422 loff_t *offsetp)
2423 {
2424 struct buffered_dirent *de;
2425 int host_err;
2426 int size;
2427 loff_t offset;
2428 struct readdir_data buf = {
2429 .ctx.actor = nfsd_buffered_filldir,
2430 .dirent = kmalloc(PAGE_SIZE, GFP_KERNEL)
2431 };
2432
2433 if (!buf.dirent)
2434 return nfserrno(-ENOMEM);
2435
2436 offset = *offsetp;
2437
2438 while (1) {
2439 unsigned int reclen;
2440
2441 cdp->err = nfserr_eof; /* will be cleared on successful read */
2442 buf.used = 0;
2443 buf.full = 0;
2444
2445 host_err = iterate_dir(file, &buf.ctx);
2446 if (buf.full)
2447 host_err = 0;
2448
2449 if (host_err < 0)
2450 break;
2451
2452 size = buf.used;
2453
2454 if (!size)
2455 break;
2456
2457 de = (struct buffered_dirent *)buf.dirent;
2458 while (size > 0) {
2459 offset = de->offset;
2460
2461 if (func(cdp, de->name, de->namlen, de->offset,
2462 de->ino, de->d_type))
2463 break;
2464
2465 if (cdp->err != nfs_ok)
2466 break;
2467
2468 trace_nfsd_dirent(fhp, de->ino, de->name, de->namlen);
2469
2470 reclen = ALIGN(sizeof(*de) + de->namlen,
2471 sizeof(u64));
2472 size -= reclen;
2473 de = (struct buffered_dirent *)((char *)de + reclen);
2474 }
2475 if (size > 0) /* We bailed out early */
2476 break;
2477
2478 offset = vfs_llseek(file, 0, SEEK_CUR);
2479 }
2480
2481 kfree((buf.dirent));
2482
2483 if (host_err)
2484 return nfserrno(host_err);
2485
2486 *offsetp = offset;
2487 return cdp->err;
2488 }
2489
2490 /**
2491 * nfsd_readdir - Read entries from a directory
2492 * @rqstp: RPC transaction context
2493 * @fhp: NFS file handle of directory to be read
2494 * @offsetp: OUT: seek offset of final entry that was read
2495 * @cdp: OUT: an eof error value
2496 * @func: entry filler actor
2497 *
2498 * This implementation ignores the NFSv3/4 verifier cookie.
2499 *
2500 * NB: normal system calls hold file->f_pos_lock when calling
2501 * ->iterate_shared and ->llseek, but nfsd_readdir() does not.
2502 * Because the struct file acquired here is not visible to other
2503 * threads, it's internal state does not need mutex protection.
2504 *
2505 * Returns nfs_ok on success, otherwise an nfsstat code is
2506 * returned.
2507 */
2508 __be32
nfsd_readdir(struct svc_rqst * rqstp,struct svc_fh * fhp,loff_t * offsetp,struct readdir_cd * cdp,nfsd_filldir_t func)2509 nfsd_readdir(struct svc_rqst *rqstp, struct svc_fh *fhp, loff_t *offsetp,
2510 struct readdir_cd *cdp, nfsd_filldir_t func)
2511 {
2512 __be32 err;
2513 struct file *file;
2514 loff_t offset = *offsetp;
2515 int may_flags = NFSD_MAY_READ;
2516
2517 err = nfsd_open(rqstp, fhp, S_IFDIR, may_flags, &file);
2518 if (err)
2519 goto out;
2520
2521 if (fhp->fh_64bit_cookies)
2522 file->f_mode |= FMODE_64BITHASH;
2523 else
2524 file->f_mode |= FMODE_32BITHASH;
2525
2526 offset = vfs_llseek(file, offset, SEEK_SET);
2527 if (offset < 0) {
2528 err = nfserrno((int)offset);
2529 goto out_close;
2530 }
2531
2532 err = nfsd_buffered_readdir(file, fhp, func, cdp, offsetp);
2533
2534 if (err == nfserr_eof || err == nfserr_toosmall)
2535 err = nfs_ok; /* can still be found in ->err */
2536 out_close:
2537 nfsd_filp_close(file);
2538 out:
2539 return err;
2540 }
2541
2542 /**
2543 * nfsd_filp_close: close a file synchronously
2544 * @fp: the file to close
2545 *
2546 * nfsd_filp_close() is similar in behaviour to filp_close().
2547 * The difference is that if this is the final close on the
2548 * file, the that finalisation happens immediately, rather then
2549 * being handed over to a work_queue, as it the case for
2550 * filp_close().
2551 * When a user-space process closes a file (even when using
2552 * filp_close() the finalisation happens before returning to
2553 * userspace, so it is effectively synchronous. When a kernel thread
2554 * uses file_close(), on the other hand, the handling is completely
2555 * asynchronous. This means that any cost imposed by that finalisation
2556 * is not imposed on the nfsd thread, and nfsd could potentually
2557 * close files more quickly than the work queue finalises the close,
2558 * which would lead to unbounded growth in the queue.
2559 *
2560 * In some contexts is it not safe to synchronously wait for
2561 * close finalisation (see comment for __fput_sync()), but nfsd
2562 * does not match those contexts. In partcilarly it does not, at the
2563 * time that this function is called, hold and locks and no finalisation
2564 * of any file, socket, or device driver would have any cause to wait
2565 * for nfsd to make progress.
2566 */
nfsd_filp_close(struct file * fp)2567 void nfsd_filp_close(struct file *fp)
2568 {
2569 get_file(fp);
2570 filp_close(fp, NULL);
2571 __fput_sync(fp);
2572 }
2573
2574 /*
2575 * Get file system stats
2576 * N.B. After this call fhp needs an fh_put
2577 */
2578 __be32
nfsd_statfs(struct svc_rqst * rqstp,struct svc_fh * fhp,struct kstatfs * stat,int access)2579 nfsd_statfs(struct svc_rqst *rqstp, struct svc_fh *fhp, struct kstatfs *stat, int access)
2580 {
2581 __be32 err;
2582
2583 trace_nfsd_vfs_statfs(rqstp, fhp);
2584
2585 err = fh_verify(rqstp, fhp, 0, NFSD_MAY_NOP | access);
2586 if (!err) {
2587 struct path path = {
2588 .mnt = fhp->fh_export->ex_path.mnt,
2589 .dentry = fhp->fh_dentry,
2590 };
2591 if (vfs_statfs(&path, stat))
2592 err = nfserr_io;
2593 }
2594 return err;
2595 }
2596
exp_rdonly(struct svc_cred * cred,struct svc_export * exp)2597 static int exp_rdonly(struct svc_cred *cred, struct svc_export *exp)
2598 {
2599 return nfsexp_flags(cred, exp) & NFSEXP_READONLY;
2600 }
2601
2602 #ifdef CONFIG_NFSD_V4
2603 /*
2604 * Helper function to translate error numbers. In the case of xattr operations,
2605 * some error codes need to be translated outside of the standard translations.
2606 *
2607 * ENODATA needs to be translated to nfserr_noxattr.
2608 * E2BIG to nfserr_xattr2big.
2609 *
2610 * Additionally, vfs_listxattr can return -ERANGE. This means that the
2611 * file has too many extended attributes to retrieve inside an
2612 * XATTR_LIST_MAX sized buffer. This is a bug in the xattr implementation:
2613 * filesystems will allow the adding of extended attributes until they hit
2614 * their own internal limit. This limit may be larger than XATTR_LIST_MAX.
2615 * So, at that point, the attributes are present and valid, but can't
2616 * be retrieved using listxattr, since the upper level xattr code enforces
2617 * the XATTR_LIST_MAX limit.
2618 *
2619 * This bug means that we need to deal with listxattr returning -ERANGE. The
2620 * best mapping is to return TOOSMALL.
2621 */
2622 static __be32
nfsd_xattr_errno(int err)2623 nfsd_xattr_errno(int err)
2624 {
2625 switch (err) {
2626 case -ENODATA:
2627 return nfserr_noxattr;
2628 case -E2BIG:
2629 return nfserr_xattr2big;
2630 case -ERANGE:
2631 return nfserr_toosmall;
2632 }
2633 return nfserrno(err);
2634 }
2635
2636 /*
2637 * Retrieve the specified user extended attribute. To avoid always
2638 * having to allocate the maximum size (since we are not getting
2639 * a maximum size from the RPC), do a probe + alloc. Hold a reader
2640 * lock on i_rwsem to prevent the extended attribute from changing
2641 * size while we're doing this.
2642 */
2643 __be32
nfsd_getxattr(struct svc_rqst * rqstp,struct svc_fh * fhp,char * name,void ** bufp,int * lenp)2644 nfsd_getxattr(struct svc_rqst *rqstp, struct svc_fh *fhp, char *name,
2645 void **bufp, int *lenp)
2646 {
2647 ssize_t len;
2648 __be32 err;
2649 char *buf;
2650 struct inode *inode;
2651 struct dentry *dentry;
2652
2653 err = fh_verify(rqstp, fhp, 0, NFSD_MAY_READ);
2654 if (err)
2655 return err;
2656
2657 err = nfs_ok;
2658 dentry = fhp->fh_dentry;
2659 inode = d_inode(dentry);
2660
2661 inode_lock_shared(inode);
2662
2663 len = vfs_getxattr(&nop_mnt_idmap, dentry, name, NULL, 0);
2664
2665 /*
2666 * Zero-length attribute, just return.
2667 */
2668 if (len == 0) {
2669 *bufp = NULL;
2670 *lenp = 0;
2671 goto out;
2672 }
2673
2674 if (len < 0) {
2675 err = nfsd_xattr_errno(len);
2676 goto out;
2677 }
2678
2679 if (len > *lenp) {
2680 err = nfserr_toosmall;
2681 goto out;
2682 }
2683
2684 buf = kvmalloc(len, GFP_KERNEL);
2685 if (buf == NULL) {
2686 err = nfserr_jukebox;
2687 goto out;
2688 }
2689
2690 len = vfs_getxattr(&nop_mnt_idmap, dentry, name, buf, len);
2691 if (len <= 0) {
2692 kvfree(buf);
2693 buf = NULL;
2694 err = nfsd_xattr_errno(len);
2695 }
2696
2697 *lenp = len;
2698 *bufp = buf;
2699
2700 out:
2701 inode_unlock_shared(inode);
2702
2703 return err;
2704 }
2705
2706 /*
2707 * Retrieve the xattr names. Since we can't know how many are
2708 * user extended attributes, we must get all attributes here,
2709 * and have the XDR encode filter out the "user." ones.
2710 *
2711 * While this could always just allocate an XATTR_LIST_MAX
2712 * buffer, that's a waste, so do a probe + allocate. To
2713 * avoid any changes between the probe and allocate, wrap
2714 * this in inode_lock.
2715 */
2716 __be32
nfsd_listxattr(struct svc_rqst * rqstp,struct svc_fh * fhp,char ** bufp,int * lenp)2717 nfsd_listxattr(struct svc_rqst *rqstp, struct svc_fh *fhp, char **bufp,
2718 int *lenp)
2719 {
2720 ssize_t len;
2721 __be32 err;
2722 char *buf;
2723 struct inode *inode;
2724 struct dentry *dentry;
2725
2726 err = fh_verify(rqstp, fhp, 0, NFSD_MAY_READ);
2727 if (err)
2728 return err;
2729
2730 dentry = fhp->fh_dentry;
2731 inode = d_inode(dentry);
2732 *lenp = 0;
2733
2734 inode_lock_shared(inode);
2735
2736 len = vfs_listxattr(dentry, NULL, 0);
2737 if (len <= 0) {
2738 err = nfsd_xattr_errno(len);
2739 goto out;
2740 }
2741
2742 if (len > XATTR_LIST_MAX) {
2743 err = nfserr_xattr2big;
2744 goto out;
2745 }
2746
2747 buf = kvmalloc(len, GFP_KERNEL);
2748 if (buf == NULL) {
2749 err = nfserr_jukebox;
2750 goto out;
2751 }
2752
2753 len = vfs_listxattr(dentry, buf, len);
2754 if (len <= 0) {
2755 kvfree(buf);
2756 err = nfsd_xattr_errno(len);
2757 goto out;
2758 }
2759
2760 *lenp = len;
2761 *bufp = buf;
2762
2763 err = nfs_ok;
2764 out:
2765 inode_unlock_shared(inode);
2766
2767 return err;
2768 }
2769
2770 /**
2771 * nfsd_removexattr - Remove an extended attribute
2772 * @rqstp: RPC transaction being executed
2773 * @fhp: NFS filehandle of object with xattr to remove
2774 * @name: name of xattr to remove (NUL-terminate)
2775 *
2776 * Pass in a NULL pointer for delegated_inode, and let the client deal
2777 * with NFS4ERR_DELAY (same as with e.g. setattr and remove).
2778 *
2779 * Returns nfs_ok on success, or an nfsstat in network byte order.
2780 */
2781 __be32
nfsd_removexattr(struct svc_rqst * rqstp,struct svc_fh * fhp,char * name)2782 nfsd_removexattr(struct svc_rqst *rqstp, struct svc_fh *fhp, char *name)
2783 {
2784 __be32 err;
2785 int ret;
2786
2787 err = fh_verify(rqstp, fhp, 0, NFSD_MAY_WRITE);
2788 if (err)
2789 return err;
2790
2791 ret = fh_want_write(fhp);
2792 if (ret)
2793 return nfserrno(ret);
2794
2795 inode_lock(fhp->fh_dentry->d_inode);
2796 err = fh_fill_pre_attrs(fhp);
2797 if (err != nfs_ok)
2798 goto out_unlock;
2799 ret = __vfs_removexattr_locked(&nop_mnt_idmap, fhp->fh_dentry,
2800 name, NULL);
2801 err = nfsd_xattr_errno(ret);
2802 fh_fill_post_attrs(fhp);
2803 out_unlock:
2804 inode_unlock(fhp->fh_dentry->d_inode);
2805 fh_drop_write(fhp);
2806
2807 return err;
2808 }
2809
2810 __be32
nfsd_setxattr(struct svc_rqst * rqstp,struct svc_fh * fhp,char * name,void * buf,u32 len,u32 flags)2811 nfsd_setxattr(struct svc_rqst *rqstp, struct svc_fh *fhp, char *name,
2812 void *buf, u32 len, u32 flags)
2813 {
2814 __be32 err;
2815 int ret;
2816
2817 err = fh_verify(rqstp, fhp, 0, NFSD_MAY_WRITE);
2818 if (err)
2819 return err;
2820
2821 ret = fh_want_write(fhp);
2822 if (ret)
2823 return nfserrno(ret);
2824 inode_lock(fhp->fh_dentry->d_inode);
2825 err = fh_fill_pre_attrs(fhp);
2826 if (err != nfs_ok)
2827 goto out_unlock;
2828 ret = __vfs_setxattr_locked(&nop_mnt_idmap, fhp->fh_dentry,
2829 name, buf, len, flags, NULL);
2830 fh_fill_post_attrs(fhp);
2831 err = nfsd_xattr_errno(ret);
2832 out_unlock:
2833 inode_unlock(fhp->fh_dentry->d_inode);
2834 fh_drop_write(fhp);
2835 return err;
2836 }
2837 #endif
2838
2839 /*
2840 * Check for a user's access permissions to this inode.
2841 */
2842 __be32
nfsd_permission(struct svc_cred * cred,struct svc_export * exp,struct dentry * dentry,int acc)2843 nfsd_permission(struct svc_cred *cred, struct svc_export *exp,
2844 struct dentry *dentry, int acc)
2845 {
2846 struct inode *inode = d_inode(dentry);
2847 int err;
2848
2849 if ((acc & NFSD_MAY_MASK) == NFSD_MAY_NOP)
2850 return 0;
2851 #if 0
2852 dprintk("nfsd: permission 0x%x%s%s%s%s%s%s%s mode 0%o%s%s%s\n",
2853 acc,
2854 (acc & NFSD_MAY_READ)? " read" : "",
2855 (acc & NFSD_MAY_WRITE)? " write" : "",
2856 (acc & NFSD_MAY_EXEC)? " exec" : "",
2857 (acc & NFSD_MAY_SATTR)? " sattr" : "",
2858 (acc & NFSD_MAY_TRUNC)? " trunc" : "",
2859 (acc & NFSD_MAY_NLM)? " nlm" : "",
2860 (acc & NFSD_MAY_OWNER_OVERRIDE)? " owneroverride" : "",
2861 inode->i_mode,
2862 IS_IMMUTABLE(inode)? " immut" : "",
2863 IS_APPEND(inode)? " append" : "",
2864 __mnt_is_readonly(exp->ex_path.mnt)? " ro" : "");
2865 dprintk(" owner %d/%d user %d/%d\n",
2866 inode->i_uid, inode->i_gid, current_fsuid(), current_fsgid());
2867 #endif
2868
2869 /* Normally we reject any write/sattr etc access on a read-only file
2870 * system. But if it is IRIX doing check on write-access for a
2871 * device special file, we ignore rofs.
2872 */
2873 if (!(acc & NFSD_MAY_LOCAL_ACCESS))
2874 if (acc & (NFSD_MAY_WRITE | NFSD_MAY_SATTR | NFSD_MAY_TRUNC)) {
2875 if (exp_rdonly(cred, exp) ||
2876 __mnt_is_readonly(exp->ex_path.mnt))
2877 return nfserr_rofs;
2878 if (/* (acc & NFSD_MAY_WRITE) && */ IS_IMMUTABLE(inode))
2879 return nfserr_perm;
2880 }
2881 if ((acc & NFSD_MAY_TRUNC) && IS_APPEND(inode))
2882 return nfserr_perm;
2883
2884 /*
2885 * The file owner always gets access permission for accesses that
2886 * would normally be checked at open time. This is to make
2887 * file access work even when the client has done a fchmod(fd, 0).
2888 *
2889 * However, `cp foo bar' should fail nevertheless when bar is
2890 * readonly. A sensible way to do this might be to reject all
2891 * attempts to truncate a read-only file, because a creat() call
2892 * always implies file truncation.
2893 * ... but this isn't really fair. A process may reasonably call
2894 * ftruncate on an open file descriptor on a file with perm 000.
2895 * We must trust the client to do permission checking - using "ACCESS"
2896 * with NFSv3.
2897 */
2898 if ((acc & NFSD_MAY_OWNER_OVERRIDE) &&
2899 uid_eq(inode->i_uid, current_fsuid()))
2900 return 0;
2901
2902 /* This assumes NFSD_MAY_{READ,WRITE,EXEC} == MAY_{READ,WRITE,EXEC} */
2903 err = inode_permission(&nop_mnt_idmap, inode,
2904 acc & (MAY_READ | MAY_WRITE | MAY_EXEC));
2905
2906 /* Allow read access to binaries even when mode 111 */
2907 if (err == -EACCES && S_ISREG(inode->i_mode) &&
2908 (((acc & NFSD_MAY_MASK) == NFSD_MAY_READ) &&
2909 (acc & (NFSD_MAY_OWNER_OVERRIDE | NFSD_MAY_READ_IF_EXEC))))
2910 err = inode_permission(&nop_mnt_idmap, inode, MAY_EXEC);
2911
2912 return err? nfserrno(err) : 0;
2913 }
2914
2915 /**
2916 * nfsd_get_case_info - get case sensitivity info for a dentry
2917 * @dentry: dentry to query
2918 * @case_insensitive: set to true if name comparison ignores case
2919 * @case_preserving: set to true if case is preserved on disk
2920 *
2921 * On casefold-capable filesystems the flag lives on the directory,
2922 * not on its entries, so for a non-directory @dentry the parent is
2923 * queried instead. A directory (including an export root, whose
2924 * parent lies outside the export) is queried as-is so its own
2925 * contents' lookup behavior is reported. NFSD advertises
2926 * fattr4_homogeneous as FALSE, so per-directory answers may differ
2927 * within an export.
2928 *
2929 * The probe runs with kernel credentials. case_insensitive and
2930 * case_preserving describe the directory's structural lookup
2931 * behavior, not the caller's identity; running under the calling
2932 * client's mapped credentials would let per-client MAC policy on
2933 * the parent directory turn this query into NFS4ERR_ACCESS even
2934 * though the underlying property is the same for every client.
2935 *
2936 * When the filesystem does not expose case-folding state (no
2937 * ->fileattr_get, or the callback returns -EOPNOTSUPP /
2938 * -ENOIOCTLCMD / -ENOTTY / -EINVAL), the outputs are filled with
2939 * POSIX defaults (case-sensitive, case-preserving) on the premise
2940 * that a filesystem with case-folding support wires up
2941 * fileattr_get.
2942 *
2943 * Return: 0 with outputs filled, -EOPNOTSUPP with outputs filled
2944 * to POSIX defaults, or a negative errno (e.g., -EIO,
2945 * -ESTALE, -ENOMEM) with outputs unmodified.
2946 */
2947 int
nfsd_get_case_info(struct dentry * dentry,bool * case_insensitive,bool * case_preserving)2948 nfsd_get_case_info(struct dentry *dentry, bool *case_insensitive,
2949 bool *case_preserving)
2950 {
2951 struct file_kattr fa = {};
2952 const struct cred *saved;
2953 struct cred *probe;
2954 struct dentry *cd;
2955 bool put = false;
2956 int err;
2957
2958 if (d_is_dir(dentry)) {
2959 cd = dentry;
2960 } else {
2961 cd = dget_parent(dentry);
2962 put = true;
2963 }
2964
2965 probe = prepare_kernel_cred(&init_task);
2966 if (!probe) {
2967 err = -ENOMEM;
2968 goto out;
2969 }
2970 saved = override_creds(probe);
2971
2972 err = vfs_fileattr_get(cd, &fa);
2973
2974 put_cred(revert_creds(saved));
2975 out:
2976 if (put)
2977 dput(cd);
2978 switch (err) {
2979 case 0:
2980 *case_insensitive = fa.fsx_xflags & FS_XFLAG_CASEFOLD;
2981 *case_preserving =
2982 !(fa.fsx_xflags & FS_XFLAG_CASENONPRESERVING);
2983 return 0;
2984 case -EINVAL:
2985 case -ENOTTY:
2986 case -ENOIOCTLCMD:
2987 case -EOPNOTSUPP:
2988 /*
2989 * Filesystem does not expose case state.
2990 * Report POSIX defaults.
2991 */
2992 *case_insensitive = false;
2993 *case_preserving = true;
2994 return -EOPNOTSUPP;
2995 default:
2996 return err;
2997 }
2998 }
2999