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