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