]> CyberLeo.Net >> Repos - FreeBSD/stable/9.git/blob - sys/fs/nfsserver/nfs_nfsdport.c
MFC: r259845
[FreeBSD/stable/9.git] / sys / fs / nfsserver / nfs_nfsdport.c
1 /*-
2  * Copyright (c) 1989, 1993
3  *      The Regents of the University of California.  All rights reserved.
4  *
5  * This code is derived from software contributed to Berkeley by
6  * Rick Macklem at The University of Guelph.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 4. Neither the name of the University nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  *
32  */
33
34 #include <sys/cdefs.h>
35 __FBSDID("$FreeBSD$");
36
37 #include <sys/capability.h>
38
39 /*
40  * Functions that perform the vfs operations required by the routines in
41  * nfsd_serv.c. It is hoped that this change will make the server more
42  * portable.
43  */
44
45 #include <fs/nfs/nfsport.h>
46 #include <sys/hash.h>
47 #include <sys/sysctl.h>
48 #include <nlm/nlm_prot.h>
49 #include <nlm/nlm.h>
50
51 FEATURE(nfsd, "NFSv4 server");
52
53 extern u_int32_t newnfs_true, newnfs_false, newnfs_xdrneg1;
54 extern int nfsrv_useacl;
55 extern int newnfs_numnfsd;
56 extern struct mount nfsv4root_mnt;
57 extern struct nfsrv_stablefirst nfsrv_stablefirst;
58 extern void (*nfsd_call_servertimer)(void);
59 extern SVCPOOL  *nfsrvd_pool;
60 extern struct nfsv4lock nfsd_suspend_lock;
61 struct vfsoptlist nfsv4root_opt, nfsv4root_newopt;
62 NFSDLOCKMUTEX;
63 struct nfsrchash_bucket nfsrchash_table[NFSRVCACHE_HASHSIZE];
64 struct mtx nfsrc_udpmtx;
65 struct mtx nfs_v4root_mutex;
66 struct nfsrvfh nfs_rootfh, nfs_pubfh;
67 int nfs_pubfhset = 0, nfs_rootfhset = 0;
68 struct proc *nfsd_master_proc = NULL;
69 static pid_t nfsd_master_pid = (pid_t)-1;
70 static char nfsd_master_comm[MAXCOMLEN + 1];
71 static struct timeval nfsd_master_start;
72 static uint32_t nfsv4_sysid = 0;
73
74 static int nfssvc_srvcall(struct thread *, struct nfssvc_args *,
75     struct ucred *);
76
77 int nfsrv_enable_crossmntpt = 1;
78 static int nfs_commit_blks;
79 static int nfs_commit_miss;
80 extern int nfsrv_issuedelegs;
81 extern int nfsrv_dolocallocks;
82
83 SYSCTL_NODE(_vfs, OID_AUTO, nfsd, CTLFLAG_RW, 0, "New NFS server");
84 SYSCTL_INT(_vfs_nfsd, OID_AUTO, mirrormnt, CTLFLAG_RW,
85     &nfsrv_enable_crossmntpt, 0, "Enable nfsd to cross mount points");
86 SYSCTL_INT(_vfs_nfsd, OID_AUTO, commit_blks, CTLFLAG_RW, &nfs_commit_blks,
87     0, "");
88 SYSCTL_INT(_vfs_nfsd, OID_AUTO, commit_miss, CTLFLAG_RW, &nfs_commit_miss,
89     0, "");
90 SYSCTL_INT(_vfs_nfsd, OID_AUTO, issue_delegations, CTLFLAG_RW,
91     &nfsrv_issuedelegs, 0, "Enable nfsd to issue delegations");
92 SYSCTL_INT(_vfs_nfsd, OID_AUTO, enable_locallocks, CTLFLAG_RW,
93     &nfsrv_dolocallocks, 0, "Enable nfsd to acquire local locks on files");
94
95 #define MAX_REORDERED_RPC       16
96 #define NUM_HEURISTIC           1031
97 #define NHUSE_INIT              64
98 #define NHUSE_INC               16
99 #define NHUSE_MAX               2048
100
101 static struct nfsheur {
102         struct vnode *nh_vp;    /* vp to match (unreferenced pointer) */
103         off_t nh_nextoff;       /* next offset for sequential detection */
104         int nh_use;             /* use count for selection */
105         int nh_seqcount;        /* heuristic */
106 } nfsheur[NUM_HEURISTIC];
107
108
109 /*
110  * Heuristic to detect sequential operation.
111  */
112 static struct nfsheur *
113 nfsrv_sequential_heuristic(struct uio *uio, struct vnode *vp)
114 {
115         struct nfsheur *nh;
116         int hi, try;
117
118         /* Locate best candidate. */
119         try = 32;
120         hi = ((int)(vm_offset_t)vp / sizeof(struct vnode)) % NUM_HEURISTIC;
121         nh = &nfsheur[hi];
122         while (try--) {
123                 if (nfsheur[hi].nh_vp == vp) {
124                         nh = &nfsheur[hi];
125                         break;
126                 }
127                 if (nfsheur[hi].nh_use > 0)
128                         --nfsheur[hi].nh_use;
129                 hi = (hi + 1) % NUM_HEURISTIC;
130                 if (nfsheur[hi].nh_use < nh->nh_use)
131                         nh = &nfsheur[hi];
132         }
133
134         /* Initialize hint if this is a new file. */
135         if (nh->nh_vp != vp) {
136                 nh->nh_vp = vp;
137                 nh->nh_nextoff = uio->uio_offset;
138                 nh->nh_use = NHUSE_INIT;
139                 if (uio->uio_offset == 0)
140                         nh->nh_seqcount = 4;
141                 else
142                         nh->nh_seqcount = 1;
143         }
144
145         /* Calculate heuristic. */
146         if ((uio->uio_offset == 0 && nh->nh_seqcount > 0) ||
147             uio->uio_offset == nh->nh_nextoff) {
148                 /* See comments in vfs_vnops.c:sequential_heuristic(). */
149                 nh->nh_seqcount += howmany(uio->uio_resid, 16384);
150                 if (nh->nh_seqcount > IO_SEQMAX)
151                         nh->nh_seqcount = IO_SEQMAX;
152         } else if (qabs(uio->uio_offset - nh->nh_nextoff) <= MAX_REORDERED_RPC *
153             imax(vp->v_mount->mnt_stat.f_iosize, uio->uio_resid)) {
154                 /* Probably a reordered RPC, leave seqcount alone. */
155         } else if (nh->nh_seqcount > 1) {
156                 nh->nh_seqcount /= 2;
157         } else {
158                 nh->nh_seqcount = 0;
159         }
160         nh->nh_use += NHUSE_INC;
161         if (nh->nh_use > NHUSE_MAX)
162                 nh->nh_use = NHUSE_MAX;
163         return (nh);
164 }
165
166 /*
167  * Get attributes into nfsvattr structure.
168  */
169 int
170 nfsvno_getattr(struct vnode *vp, struct nfsvattr *nvap, struct ucred *cred,
171     struct thread *p, int vpislocked)
172 {
173         int error, lockedit = 0;
174
175         if (vpislocked == 0) {
176                 /*
177                  * When vpislocked == 0, the vnode is either exclusively
178                  * locked by this thread or not locked by this thread.
179                  * As such, shared lock it, if not exclusively locked.
180                  */
181                 if (NFSVOPISLOCKED(vp) != LK_EXCLUSIVE) {
182                         lockedit = 1;
183                         NFSVOPLOCK(vp, LK_SHARED | LK_RETRY);
184                 }
185         }
186         error = VOP_GETATTR(vp, &nvap->na_vattr, cred);
187         if (lockedit != 0)
188                 NFSVOPUNLOCK(vp, 0);
189
190         NFSEXITCODE(error);
191         return (error);
192 }
193
194 /*
195  * Get a file handle for a vnode.
196  */
197 int
198 nfsvno_getfh(struct vnode *vp, fhandle_t *fhp, struct thread *p)
199 {
200         int error;
201
202         NFSBZERO((caddr_t)fhp, sizeof(fhandle_t));
203         fhp->fh_fsid = vp->v_mount->mnt_stat.f_fsid;
204         error = VOP_VPTOFH(vp, &fhp->fh_fid);
205
206         NFSEXITCODE(error);
207         return (error);
208 }
209
210 /*
211  * Perform access checking for vnodes obtained from file handles that would
212  * refer to files already opened by a Unix client. You cannot just use
213  * vn_writechk() and VOP_ACCESSX() for two reasons.
214  * 1 - You must check for exported rdonly as well as MNT_RDONLY for the write
215  *     case.
216  * 2 - The owner is to be given access irrespective of mode bits for some
217  *     operations, so that processes that chmod after opening a file don't
218  *     break.
219  */
220 int
221 nfsvno_accchk(struct vnode *vp, accmode_t accmode, struct ucred *cred,
222     struct nfsexstuff *exp, struct thread *p, int override, int vpislocked,
223     u_int32_t *supportedtypep)
224 {
225         struct vattr vattr;
226         int error = 0, getret = 0;
227
228         if (vpislocked == 0) {
229                 if (NFSVOPLOCK(vp, LK_SHARED) != 0) {
230                         error = EPERM;
231                         goto out;
232                 }
233         }
234         if (accmode & VWRITE) {
235                 /* Just vn_writechk() changed to check rdonly */
236                 /*
237                  * Disallow write attempts on read-only file systems;
238                  * unless the file is a socket or a block or character
239                  * device resident on the file system.
240                  */
241                 if (NFSVNO_EXRDONLY(exp) ||
242                     (vp->v_mount->mnt_flag & MNT_RDONLY)) {
243                         switch (vp->v_type) {
244                         case VREG:
245                         case VDIR:
246                         case VLNK:
247                                 error = EROFS;
248                         default:
249                                 break;
250                         }
251                 }
252                 /*
253                  * If there's shared text associated with
254                  * the inode, try to free it up once.  If
255                  * we fail, we can't allow writing.
256                  */
257                 if (VOP_IS_TEXT(vp) && error == 0)
258                         error = ETXTBSY;
259         }
260         if (error != 0) {
261                 if (vpislocked == 0)
262                         NFSVOPUNLOCK(vp, 0);
263                 goto out;
264         }
265
266         /*
267          * Should the override still be applied when ACLs are enabled?
268          */
269         error = VOP_ACCESSX(vp, accmode, cred, p);
270         if (error != 0 && (accmode & (VDELETE | VDELETE_CHILD))) {
271                 /*
272                  * Try again with VEXPLICIT_DENY, to see if the test for
273                  * deletion is supported.
274                  */
275                 error = VOP_ACCESSX(vp, accmode | VEXPLICIT_DENY, cred, p);
276                 if (error == 0) {
277                         if (vp->v_type == VDIR) {
278                                 accmode &= ~(VDELETE | VDELETE_CHILD);
279                                 accmode |= VWRITE;
280                                 error = VOP_ACCESSX(vp, accmode, cred, p);
281                         } else if (supportedtypep != NULL) {
282                                 *supportedtypep &= ~NFSACCESS_DELETE;
283                         }
284                 }
285         }
286
287         /*
288          * Allow certain operations for the owner (reads and writes
289          * on files that are already open).
290          */
291         if (override != NFSACCCHK_NOOVERRIDE &&
292             (error == EPERM || error == EACCES)) {
293                 if (cred->cr_uid == 0 && (override & NFSACCCHK_ALLOWROOT))
294                         error = 0;
295                 else if (override & NFSACCCHK_ALLOWOWNER) {
296                         getret = VOP_GETATTR(vp, &vattr, cred);
297                         if (getret == 0 && cred->cr_uid == vattr.va_uid)
298                                 error = 0;
299                 }
300         }
301         if (vpislocked == 0)
302                 NFSVOPUNLOCK(vp, 0);
303
304 out:
305         NFSEXITCODE(error);
306         return (error);
307 }
308
309 /*
310  * Set attribute(s) vnop.
311  */
312 int
313 nfsvno_setattr(struct vnode *vp, struct nfsvattr *nvap, struct ucred *cred,
314     struct thread *p, struct nfsexstuff *exp)
315 {
316         int error;
317
318         error = VOP_SETATTR(vp, &nvap->na_vattr, cred);
319         NFSEXITCODE(error);
320         return (error);
321 }
322
323 /*
324  * Set up nameidata for a lookup() call and do it.
325  */
326 int
327 nfsvno_namei(struct nfsrv_descript *nd, struct nameidata *ndp,
328     struct vnode *dp, int islocked, struct nfsexstuff *exp, struct thread *p,
329     struct vnode **retdirp)
330 {
331         struct componentname *cnp = &ndp->ni_cnd;
332         int i;
333         struct iovec aiov;
334         struct uio auio;
335         int lockleaf = (cnp->cn_flags & LOCKLEAF) != 0, linklen;
336         int error = 0, crossmnt;
337         char *cp;
338
339         *retdirp = NULL;
340         cnp->cn_nameptr = cnp->cn_pnbuf;
341         ndp->ni_strictrelative = 0;
342         /*
343          * Extract and set starting directory.
344          */
345         if (dp->v_type != VDIR) {
346                 if (islocked)
347                         vput(dp);
348                 else
349                         vrele(dp);
350                 nfsvno_relpathbuf(ndp);
351                 error = ENOTDIR;
352                 goto out1;
353         }
354         if (islocked)
355                 NFSVOPUNLOCK(dp, 0);
356         VREF(dp);
357         *retdirp = dp;
358         if (NFSVNO_EXRDONLY(exp))
359                 cnp->cn_flags |= RDONLY;
360         ndp->ni_segflg = UIO_SYSSPACE;
361         crossmnt = 1;
362
363         if (nd->nd_flag & ND_PUBLOOKUP) {
364                 ndp->ni_loopcnt = 0;
365                 if (cnp->cn_pnbuf[0] == '/') {
366                         vrele(dp);
367                         /*
368                          * Check for degenerate pathnames here, since lookup()
369                          * panics on them.
370                          */
371                         for (i = 1; i < ndp->ni_pathlen; i++)
372                                 if (cnp->cn_pnbuf[i] != '/')
373                                         break;
374                         if (i == ndp->ni_pathlen) {
375                                 error = NFSERR_ACCES;
376                                 goto out;
377                         }
378                         dp = rootvnode;
379                         VREF(dp);
380                 }
381         } else if ((nfsrv_enable_crossmntpt == 0 && NFSVNO_EXPORTED(exp)) ||
382             (nd->nd_flag & ND_NFSV4) == 0) {
383                 /*
384                  * Only cross mount points for NFSv4 when doing a
385                  * mount while traversing the file system above
386                  * the mount point, unless nfsrv_enable_crossmntpt is set.
387                  */
388                 cnp->cn_flags |= NOCROSSMOUNT;
389                 crossmnt = 0;
390         }
391
392         /*
393          * Initialize for scan, set ni_startdir and bump ref on dp again
394          * becuase lookup() will dereference ni_startdir.
395          */
396
397         cnp->cn_thread = p;
398         ndp->ni_startdir = dp;
399         ndp->ni_rootdir = rootvnode;
400         ndp->ni_topdir = NULL;
401
402         if (!lockleaf)
403                 cnp->cn_flags |= LOCKLEAF;
404         for (;;) {
405                 cnp->cn_nameptr = cnp->cn_pnbuf;
406                 /*
407                  * Call lookup() to do the real work.  If an error occurs,
408                  * ndp->ni_vp and ni_dvp are left uninitialized or NULL and
409                  * we do not have to dereference anything before returning.
410                  * In either case ni_startdir will be dereferenced and NULLed
411                  * out.
412                  */
413                 error = lookup(ndp);
414                 if (error)
415                         break;
416
417                 /*
418                  * Check for encountering a symbolic link.  Trivial
419                  * termination occurs if no symlink encountered.
420                  */
421                 if ((cnp->cn_flags & ISSYMLINK) == 0) {
422                         if ((cnp->cn_flags & (SAVENAME | SAVESTART)) == 0)
423                                 nfsvno_relpathbuf(ndp);
424                         if (ndp->ni_vp && !lockleaf)
425                                 NFSVOPUNLOCK(ndp->ni_vp, 0);
426                         break;
427                 }
428
429                 /*
430                  * Validate symlink
431                  */
432                 if ((cnp->cn_flags & LOCKPARENT) && ndp->ni_pathlen == 1)
433                         NFSVOPUNLOCK(ndp->ni_dvp, 0);
434                 if (!(nd->nd_flag & ND_PUBLOOKUP)) {
435                         error = EINVAL;
436                         goto badlink2;
437                 }
438
439                 if (ndp->ni_loopcnt++ >= MAXSYMLINKS) {
440                         error = ELOOP;
441                         goto badlink2;
442                 }
443                 if (ndp->ni_pathlen > 1)
444                         cp = uma_zalloc(namei_zone, M_WAITOK);
445                 else
446                         cp = cnp->cn_pnbuf;
447                 aiov.iov_base = cp;
448                 aiov.iov_len = MAXPATHLEN;
449                 auio.uio_iov = &aiov;
450                 auio.uio_iovcnt = 1;
451                 auio.uio_offset = 0;
452                 auio.uio_rw = UIO_READ;
453                 auio.uio_segflg = UIO_SYSSPACE;
454                 auio.uio_td = NULL;
455                 auio.uio_resid = MAXPATHLEN;
456                 error = VOP_READLINK(ndp->ni_vp, &auio, cnp->cn_cred);
457                 if (error) {
458                 badlink1:
459                         if (ndp->ni_pathlen > 1)
460                                 uma_zfree(namei_zone, cp);
461                 badlink2:
462                         vrele(ndp->ni_dvp);
463                         vput(ndp->ni_vp);
464                         break;
465                 }
466                 linklen = MAXPATHLEN - auio.uio_resid;
467                 if (linklen == 0) {
468                         error = ENOENT;
469                         goto badlink1;
470                 }
471                 if (linklen + ndp->ni_pathlen >= MAXPATHLEN) {
472                         error = ENAMETOOLONG;
473                         goto badlink1;
474                 }
475
476                 /*
477                  * Adjust or replace path
478                  */
479                 if (ndp->ni_pathlen > 1) {
480                         NFSBCOPY(ndp->ni_next, cp + linklen, ndp->ni_pathlen);
481                         uma_zfree(namei_zone, cnp->cn_pnbuf);
482                         cnp->cn_pnbuf = cp;
483                 } else
484                         cnp->cn_pnbuf[linklen] = '\0';
485                 ndp->ni_pathlen += linklen;
486
487                 /*
488                  * Cleanup refs for next loop and check if root directory
489                  * should replace current directory.  Normally ni_dvp
490                  * becomes the new base directory and is cleaned up when
491                  * we loop.  Explicitly null pointers after invalidation
492                  * to clarify operation.
493                  */
494                 vput(ndp->ni_vp);
495                 ndp->ni_vp = NULL;
496
497                 if (cnp->cn_pnbuf[0] == '/') {
498                         vrele(ndp->ni_dvp);
499                         ndp->ni_dvp = ndp->ni_rootdir;
500                         VREF(ndp->ni_dvp);
501                 }
502                 ndp->ni_startdir = ndp->ni_dvp;
503                 ndp->ni_dvp = NULL;
504         }
505         if (!lockleaf)
506                 cnp->cn_flags &= ~LOCKLEAF;
507
508 out:
509         if (error) {
510                 uma_zfree(namei_zone, cnp->cn_pnbuf);
511                 ndp->ni_vp = NULL;
512                 ndp->ni_dvp = NULL;
513                 ndp->ni_startdir = NULL;
514                 cnp->cn_flags &= ~HASBUF;
515         } else if ((ndp->ni_cnd.cn_flags & (WANTPARENT|LOCKPARENT)) == 0) {
516                 ndp->ni_dvp = NULL;
517         }
518
519 out1:
520         NFSEXITCODE2(error, nd);
521         return (error);
522 }
523
524 /*
525  * Set up a pathname buffer and return a pointer to it and, optionally
526  * set a hash pointer.
527  */
528 void
529 nfsvno_setpathbuf(struct nameidata *ndp, char **bufpp, u_long **hashpp)
530 {
531         struct componentname *cnp = &ndp->ni_cnd;
532
533         cnp->cn_flags |= (NOMACCHECK | HASBUF);
534         cnp->cn_pnbuf = uma_zalloc(namei_zone, M_WAITOK);
535         if (hashpp != NULL)
536                 *hashpp = NULL;
537         *bufpp = cnp->cn_pnbuf;
538 }
539
540 /*
541  * Release the above path buffer, if not released by nfsvno_namei().
542  */
543 void
544 nfsvno_relpathbuf(struct nameidata *ndp)
545 {
546
547         if ((ndp->ni_cnd.cn_flags & HASBUF) == 0)
548                 panic("nfsrelpath");
549         uma_zfree(namei_zone, ndp->ni_cnd.cn_pnbuf);
550         ndp->ni_cnd.cn_flags &= ~HASBUF;
551 }
552
553 /*
554  * Readlink vnode op into an mbuf list.
555  */
556 int
557 nfsvno_readlink(struct vnode *vp, struct ucred *cred, struct thread *p,
558     struct mbuf **mpp, struct mbuf **mpendp, int *lenp)
559 {
560         struct iovec iv[(NFS_MAXPATHLEN+MLEN-1)/MLEN];
561         struct iovec *ivp = iv;
562         struct uio io, *uiop = &io;
563         struct mbuf *mp, *mp2 = NULL, *mp3 = NULL;
564         int i, len, tlen, error = 0;
565
566         len = 0;
567         i = 0;
568         while (len < NFS_MAXPATHLEN) {
569                 NFSMGET(mp);
570                 MCLGET(mp, M_WAIT);
571                 mp->m_len = NFSMSIZ(mp);
572                 if (len == 0) {
573                         mp3 = mp2 = mp;
574                 } else {
575                         mp2->m_next = mp;
576                         mp2 = mp;
577                 }
578                 if ((len + mp->m_len) > NFS_MAXPATHLEN) {
579                         mp->m_len = NFS_MAXPATHLEN - len;
580                         len = NFS_MAXPATHLEN;
581                 } else {
582                         len += mp->m_len;
583                 }
584                 ivp->iov_base = mtod(mp, caddr_t);
585                 ivp->iov_len = mp->m_len;
586                 i++;
587                 ivp++;
588         }
589         uiop->uio_iov = iv;
590         uiop->uio_iovcnt = i;
591         uiop->uio_offset = 0;
592         uiop->uio_resid = len;
593         uiop->uio_rw = UIO_READ;
594         uiop->uio_segflg = UIO_SYSSPACE;
595         uiop->uio_td = NULL;
596         error = VOP_READLINK(vp, uiop, cred);
597         if (error) {
598                 m_freem(mp3);
599                 *lenp = 0;
600                 goto out;
601         }
602         if (uiop->uio_resid > 0) {
603                 len -= uiop->uio_resid;
604                 tlen = NFSM_RNDUP(len);
605                 nfsrv_adj(mp3, NFS_MAXPATHLEN - tlen, tlen - len);
606         }
607         *lenp = len;
608         *mpp = mp3;
609         *mpendp = mp;
610
611 out:
612         NFSEXITCODE(error);
613         return (error);
614 }
615
616 /*
617  * Read vnode op call into mbuf list.
618  */
619 int
620 nfsvno_read(struct vnode *vp, off_t off, int cnt, struct ucred *cred,
621     struct thread *p, struct mbuf **mpp, struct mbuf **mpendp)
622 {
623         struct mbuf *m;
624         int i;
625         struct iovec *iv;
626         struct iovec *iv2;
627         int error = 0, len, left, siz, tlen, ioflag = 0;
628         struct mbuf *m2 = NULL, *m3;
629         struct uio io, *uiop = &io;
630         struct nfsheur *nh;
631
632         len = left = NFSM_RNDUP(cnt);
633         m3 = NULL;
634         /*
635          * Generate the mbuf list with the uio_iov ref. to it.
636          */
637         i = 0;
638         while (left > 0) {
639                 NFSMGET(m);
640                 MCLGET(m, M_WAIT);
641                 m->m_len = 0;
642                 siz = min(M_TRAILINGSPACE(m), left);
643                 left -= siz;
644                 i++;
645                 if (m3)
646                         m2->m_next = m;
647                 else
648                         m3 = m;
649                 m2 = m;
650         }
651         MALLOC(iv, struct iovec *, i * sizeof (struct iovec),
652             M_TEMP, M_WAITOK);
653         uiop->uio_iov = iv2 = iv;
654         m = m3;
655         left = len;
656         i = 0;
657         while (left > 0) {
658                 if (m == NULL)
659                         panic("nfsvno_read iov");
660                 siz = min(M_TRAILINGSPACE(m), left);
661                 if (siz > 0) {
662                         iv->iov_base = mtod(m, caddr_t) + m->m_len;
663                         iv->iov_len = siz;
664                         m->m_len += siz;
665                         left -= siz;
666                         iv++;
667                         i++;
668                 }
669                 m = m->m_next;
670         }
671         uiop->uio_iovcnt = i;
672         uiop->uio_offset = off;
673         uiop->uio_resid = len;
674         uiop->uio_rw = UIO_READ;
675         uiop->uio_segflg = UIO_SYSSPACE;
676         nh = nfsrv_sequential_heuristic(uiop, vp);
677         ioflag |= nh->nh_seqcount << IO_SEQSHIFT;
678         error = VOP_READ(vp, uiop, IO_NODELOCKED | ioflag, cred);
679         FREE((caddr_t)iv2, M_TEMP);
680         if (error) {
681                 m_freem(m3);
682                 *mpp = NULL;
683                 goto out;
684         }
685         nh->nh_nextoff = uiop->uio_offset;
686         tlen = len - uiop->uio_resid;
687         cnt = cnt < tlen ? cnt : tlen;
688         tlen = NFSM_RNDUP(cnt);
689         if (tlen == 0) {
690                 m_freem(m3);
691                 m3 = NULL;
692         } else if (len != tlen || tlen != cnt)
693                 nfsrv_adj(m3, len - tlen, tlen - cnt);
694         *mpp = m3;
695         *mpendp = m2;
696
697 out:
698         NFSEXITCODE(error);
699         return (error);
700 }
701
702 /*
703  * Write vnode op from an mbuf list.
704  */
705 int
706 nfsvno_write(struct vnode *vp, off_t off, int retlen, int cnt, int stable,
707     struct mbuf *mp, char *cp, struct ucred *cred, struct thread *p)
708 {
709         struct iovec *ivp;
710         int i, len;
711         struct iovec *iv;
712         int ioflags, error;
713         struct uio io, *uiop = &io;
714         struct nfsheur *nh;
715
716         MALLOC(ivp, struct iovec *, cnt * sizeof (struct iovec), M_TEMP,
717             M_WAITOK);
718         uiop->uio_iov = iv = ivp;
719         uiop->uio_iovcnt = cnt;
720         i = mtod(mp, caddr_t) + mp->m_len - cp;
721         len = retlen;
722         while (len > 0) {
723                 if (mp == NULL)
724                         panic("nfsvno_write");
725                 if (i > 0) {
726                         i = min(i, len);
727                         ivp->iov_base = cp;
728                         ivp->iov_len = i;
729                         ivp++;
730                         len -= i;
731                 }
732                 mp = mp->m_next;
733                 if (mp) {
734                         i = mp->m_len;
735                         cp = mtod(mp, caddr_t);
736                 }
737         }
738
739         if (stable == NFSWRITE_UNSTABLE)
740                 ioflags = IO_NODELOCKED;
741         else
742                 ioflags = (IO_SYNC | IO_NODELOCKED);
743         uiop->uio_resid = retlen;
744         uiop->uio_rw = UIO_WRITE;
745         uiop->uio_segflg = UIO_SYSSPACE;
746         NFSUIOPROC(uiop, p);
747         uiop->uio_offset = off;
748         nh = nfsrv_sequential_heuristic(uiop, vp);
749         ioflags |= nh->nh_seqcount << IO_SEQSHIFT;
750         error = VOP_WRITE(vp, uiop, ioflags, cred);
751         if (error == 0)
752                 nh->nh_nextoff = uiop->uio_offset;
753         FREE((caddr_t)iv, M_TEMP);
754
755         NFSEXITCODE(error);
756         return (error);
757 }
758
759 /*
760  * Common code for creating a regular file (plus special files for V2).
761  */
762 int
763 nfsvno_createsub(struct nfsrv_descript *nd, struct nameidata *ndp,
764     struct vnode **vpp, struct nfsvattr *nvap, int *exclusive_flagp,
765     int32_t *cverf, NFSDEV_T rdev, struct thread *p, struct nfsexstuff *exp)
766 {
767         u_quad_t tempsize;
768         int error;
769
770         error = nd->nd_repstat;
771         if (!error && ndp->ni_vp == NULL) {
772                 if (nvap->na_type == VREG || nvap->na_type == VSOCK) {
773                         vrele(ndp->ni_startdir);
774                         error = VOP_CREATE(ndp->ni_dvp,
775                             &ndp->ni_vp, &ndp->ni_cnd, &nvap->na_vattr);
776                         vput(ndp->ni_dvp);
777                         nfsvno_relpathbuf(ndp);
778                         if (!error) {
779                                 if (*exclusive_flagp) {
780                                         *exclusive_flagp = 0;
781                                         NFSVNO_ATTRINIT(nvap);
782                                         nvap->na_atime.tv_sec = cverf[0];
783                                         nvap->na_atime.tv_nsec = cverf[1];
784                                         error = VOP_SETATTR(ndp->ni_vp,
785                                             &nvap->na_vattr, nd->nd_cred);
786                                 }
787                         }
788                 /*
789                  * NFS V2 Only. nfsrvd_mknod() does this for V3.
790                  * (This implies, just get out on an error.)
791                  */
792                 } else if (nvap->na_type == VCHR || nvap->na_type == VBLK ||
793                         nvap->na_type == VFIFO) {
794                         if (nvap->na_type == VCHR && rdev == 0xffffffff)
795                                 nvap->na_type = VFIFO;
796                         if (nvap->na_type != VFIFO &&
797                             (error = priv_check_cred(nd->nd_cred,
798                              PRIV_VFS_MKNOD_DEV, 0))) {
799                                 vrele(ndp->ni_startdir);
800                                 nfsvno_relpathbuf(ndp);
801                                 vput(ndp->ni_dvp);
802                                 goto out;
803                         }
804                         nvap->na_rdev = rdev;
805                         error = VOP_MKNOD(ndp->ni_dvp, &ndp->ni_vp,
806                             &ndp->ni_cnd, &nvap->na_vattr);
807                         vput(ndp->ni_dvp);
808                         nfsvno_relpathbuf(ndp);
809                         vrele(ndp->ni_startdir);
810                         if (error)
811                                 goto out;
812                 } else {
813                         vrele(ndp->ni_startdir);
814                         nfsvno_relpathbuf(ndp);
815                         vput(ndp->ni_dvp);
816                         error = ENXIO;
817                         goto out;
818                 }
819                 *vpp = ndp->ni_vp;
820         } else {
821                 /*
822                  * Handle cases where error is already set and/or
823                  * the file exists.
824                  * 1 - clean up the lookup
825                  * 2 - iff !error and na_size set, truncate it
826                  */
827                 vrele(ndp->ni_startdir);
828                 nfsvno_relpathbuf(ndp);
829                 *vpp = ndp->ni_vp;
830                 if (ndp->ni_dvp == *vpp)
831                         vrele(ndp->ni_dvp);
832                 else
833                         vput(ndp->ni_dvp);
834                 if (!error && nvap->na_size != VNOVAL) {
835                         error = nfsvno_accchk(*vpp, VWRITE,
836                             nd->nd_cred, exp, p, NFSACCCHK_NOOVERRIDE,
837                             NFSACCCHK_VPISLOCKED, NULL);
838                         if (!error) {
839                                 tempsize = nvap->na_size;
840                                 NFSVNO_ATTRINIT(nvap);
841                                 nvap->na_size = tempsize;
842                                 error = VOP_SETATTR(*vpp,
843                                     &nvap->na_vattr, nd->nd_cred);
844                         }
845                 }
846                 if (error)
847                         vput(*vpp);
848         }
849
850 out:
851         NFSEXITCODE(error);
852         return (error);
853 }
854
855 /*
856  * Do a mknod vnode op.
857  */
858 int
859 nfsvno_mknod(struct nameidata *ndp, struct nfsvattr *nvap, struct ucred *cred,
860     struct thread *p)
861 {
862         int error = 0;
863         enum vtype vtyp;
864
865         vtyp = nvap->na_type;
866         /*
867          * Iff doesn't exist, create it.
868          */
869         if (ndp->ni_vp) {
870                 vrele(ndp->ni_startdir);
871                 nfsvno_relpathbuf(ndp);
872                 vput(ndp->ni_dvp);
873                 vrele(ndp->ni_vp);
874                 error = EEXIST;
875                 goto out;
876         }
877         if (vtyp != VCHR && vtyp != VBLK && vtyp != VSOCK && vtyp != VFIFO) {
878                 vrele(ndp->ni_startdir);
879                 nfsvno_relpathbuf(ndp);
880                 vput(ndp->ni_dvp);
881                 error = NFSERR_BADTYPE;
882                 goto out;
883         }
884         if (vtyp == VSOCK) {
885                 vrele(ndp->ni_startdir);
886                 error = VOP_CREATE(ndp->ni_dvp, &ndp->ni_vp,
887                     &ndp->ni_cnd, &nvap->na_vattr);
888                 vput(ndp->ni_dvp);
889                 nfsvno_relpathbuf(ndp);
890         } else {
891                 if (nvap->na_type != VFIFO &&
892                     (error = priv_check_cred(cred, PRIV_VFS_MKNOD_DEV, 0))) {
893                         vrele(ndp->ni_startdir);
894                         nfsvno_relpathbuf(ndp);
895                         vput(ndp->ni_dvp);
896                         goto out;
897                 }
898                 error = VOP_MKNOD(ndp->ni_dvp, &ndp->ni_vp,
899                     &ndp->ni_cnd, &nvap->na_vattr);
900                 vput(ndp->ni_dvp);
901                 nfsvno_relpathbuf(ndp);
902                 vrele(ndp->ni_startdir);
903                 /*
904                  * Since VOP_MKNOD returns the ni_vp, I can't
905                  * see any reason to do the lookup.
906                  */
907         }
908
909 out:
910         NFSEXITCODE(error);
911         return (error);
912 }
913
914 /*
915  * Mkdir vnode op.
916  */
917 int
918 nfsvno_mkdir(struct nameidata *ndp, struct nfsvattr *nvap, uid_t saved_uid,
919     struct ucred *cred, struct thread *p, struct nfsexstuff *exp)
920 {
921         int error = 0;
922
923         if (ndp->ni_vp != NULL) {
924                 if (ndp->ni_dvp == ndp->ni_vp)
925                         vrele(ndp->ni_dvp);
926                 else
927                         vput(ndp->ni_dvp);
928                 vrele(ndp->ni_vp);
929                 nfsvno_relpathbuf(ndp);
930                 error = EEXIST;
931                 goto out;
932         }
933         error = VOP_MKDIR(ndp->ni_dvp, &ndp->ni_vp, &ndp->ni_cnd,
934             &nvap->na_vattr);
935         vput(ndp->ni_dvp);
936         nfsvno_relpathbuf(ndp);
937
938 out:
939         NFSEXITCODE(error);
940         return (error);
941 }
942
943 /*
944  * symlink vnode op.
945  */
946 int
947 nfsvno_symlink(struct nameidata *ndp, struct nfsvattr *nvap, char *pathcp,
948     int pathlen, int not_v2, uid_t saved_uid, struct ucred *cred, struct thread *p,
949     struct nfsexstuff *exp)
950 {
951         int error = 0;
952
953         if (ndp->ni_vp) {
954                 vrele(ndp->ni_startdir);
955                 nfsvno_relpathbuf(ndp);
956                 if (ndp->ni_dvp == ndp->ni_vp)
957                         vrele(ndp->ni_dvp);
958                 else
959                         vput(ndp->ni_dvp);
960                 vrele(ndp->ni_vp);
961                 error = EEXIST;
962                 goto out;
963         }
964
965         error = VOP_SYMLINK(ndp->ni_dvp, &ndp->ni_vp, &ndp->ni_cnd,
966             &nvap->na_vattr, pathcp);
967         vput(ndp->ni_dvp);
968         vrele(ndp->ni_startdir);
969         nfsvno_relpathbuf(ndp);
970         /*
971          * Although FreeBSD still had the lookup code in
972          * it for 7/current, there doesn't seem to be any
973          * point, since VOP_SYMLINK() returns the ni_vp.
974          * Just vput it for v2.
975          */
976         if (!not_v2 && !error)
977                 vput(ndp->ni_vp);
978
979 out:
980         NFSEXITCODE(error);
981         return (error);
982 }
983
984 /*
985  * Parse symbolic link arguments.
986  * This function has an ugly side effect. It will MALLOC() an area for
987  * the symlink and set iov_base to point to it, only if it succeeds.
988  * So, if it returns with uiop->uio_iov->iov_base != NULL, that must
989  * be FREE'd later.
990  */
991 int
992 nfsvno_getsymlink(struct nfsrv_descript *nd, struct nfsvattr *nvap,
993     struct thread *p, char **pathcpp, int *lenp)
994 {
995         u_int32_t *tl;
996         char *pathcp = NULL;
997         int error = 0, len;
998         struct nfsv2_sattr *sp;
999
1000         *pathcpp = NULL;
1001         *lenp = 0;
1002         if ((nd->nd_flag & ND_NFSV3) &&
1003             (error = nfsrv_sattr(nd, nvap, NULL, NULL, p)))
1004                 goto nfsmout;
1005         NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
1006         len = fxdr_unsigned(int, *tl);
1007         if (len > NFS_MAXPATHLEN || len <= 0) {
1008                 error = EBADRPC;
1009                 goto nfsmout;
1010         }
1011         MALLOC(pathcp, caddr_t, len + 1, M_TEMP, M_WAITOK);
1012         error = nfsrv_mtostr(nd, pathcp, len);
1013         if (error)
1014                 goto nfsmout;
1015         if (nd->nd_flag & ND_NFSV2) {
1016                 NFSM_DISSECT(sp, struct nfsv2_sattr *, NFSX_V2SATTR);
1017                 nvap->na_mode = fxdr_unsigned(u_int16_t, sp->sa_mode);
1018         }
1019         *pathcpp = pathcp;
1020         *lenp = len;
1021         NFSEXITCODE2(0, nd);
1022         return (0);
1023 nfsmout:
1024         if (pathcp)
1025                 free(pathcp, M_TEMP);
1026         NFSEXITCODE2(error, nd);
1027         return (error);
1028 }
1029
1030 /*
1031  * Remove a non-directory object.
1032  */
1033 int
1034 nfsvno_removesub(struct nameidata *ndp, int is_v4, struct ucred *cred,
1035     struct thread *p, struct nfsexstuff *exp)
1036 {
1037         struct vnode *vp;
1038         int error = 0;
1039
1040         vp = ndp->ni_vp;
1041         if (vp->v_type == VDIR)
1042                 error = NFSERR_ISDIR;
1043         else if (is_v4)
1044                 error = nfsrv_checkremove(vp, 1, p);
1045         if (!error)
1046                 error = VOP_REMOVE(ndp->ni_dvp, vp, &ndp->ni_cnd);
1047         if (ndp->ni_dvp == vp)
1048                 vrele(ndp->ni_dvp);
1049         else
1050                 vput(ndp->ni_dvp);
1051         vput(vp);
1052         if ((ndp->ni_cnd.cn_flags & SAVENAME) != 0)
1053                 nfsvno_relpathbuf(ndp);
1054         NFSEXITCODE(error);
1055         return (error);
1056 }
1057
1058 /*
1059  * Remove a directory.
1060  */
1061 int
1062 nfsvno_rmdirsub(struct nameidata *ndp, int is_v4, struct ucred *cred,
1063     struct thread *p, struct nfsexstuff *exp)
1064 {
1065         struct vnode *vp;
1066         int error = 0;
1067
1068         vp = ndp->ni_vp;
1069         if (vp->v_type != VDIR) {
1070                 error = ENOTDIR;
1071                 goto out;
1072         }
1073         /*
1074          * No rmdir "." please.
1075          */
1076         if (ndp->ni_dvp == vp) {
1077                 error = EINVAL;
1078                 goto out;
1079         }
1080         /*
1081          * The root of a mounted filesystem cannot be deleted.
1082          */
1083         if (vp->v_vflag & VV_ROOT)
1084                 error = EBUSY;
1085 out:
1086         if (!error)
1087                 error = VOP_RMDIR(ndp->ni_dvp, vp, &ndp->ni_cnd);
1088         if (ndp->ni_dvp == vp)
1089                 vrele(ndp->ni_dvp);
1090         else
1091                 vput(ndp->ni_dvp);
1092         vput(vp);
1093         if ((ndp->ni_cnd.cn_flags & SAVENAME) != 0)
1094                 nfsvno_relpathbuf(ndp);
1095         NFSEXITCODE(error);
1096         return (error);
1097 }
1098
1099 /*
1100  * Rename vnode op.
1101  */
1102 int
1103 nfsvno_rename(struct nameidata *fromndp, struct nameidata *tondp,
1104     u_int32_t ndstat, u_int32_t ndflag, struct ucred *cred, struct thread *p)
1105 {
1106         struct vnode *fvp, *tvp, *tdvp;
1107         int error = 0;
1108
1109         fvp = fromndp->ni_vp;
1110         if (ndstat) {
1111                 vrele(fromndp->ni_dvp);
1112                 vrele(fvp);
1113                 error = ndstat;
1114                 goto out1;
1115         }
1116         tdvp = tondp->ni_dvp;
1117         tvp = tondp->ni_vp;
1118         if (tvp != NULL) {
1119                 if (fvp->v_type == VDIR && tvp->v_type != VDIR) {
1120                         error = (ndflag & ND_NFSV2) ? EISDIR : EEXIST;
1121                         goto out;
1122                 } else if (fvp->v_type != VDIR && tvp->v_type == VDIR) {
1123                         error = (ndflag & ND_NFSV2) ? ENOTDIR : EEXIST;
1124                         goto out;
1125                 }
1126                 if (tvp->v_type == VDIR && tvp->v_mountedhere) {
1127                         error = (ndflag & ND_NFSV2) ? ENOTEMPTY : EXDEV;
1128                         goto out;
1129                 }
1130
1131                 /*
1132                  * A rename to '.' or '..' results in a prematurely
1133                  * unlocked vnode on FreeBSD5, so I'm just going to fail that
1134                  * here.
1135                  */
1136                 if ((tondp->ni_cnd.cn_namelen == 1 &&
1137                      tondp->ni_cnd.cn_nameptr[0] == '.') ||
1138                     (tondp->ni_cnd.cn_namelen == 2 &&
1139                      tondp->ni_cnd.cn_nameptr[0] == '.' &&
1140                      tondp->ni_cnd.cn_nameptr[1] == '.')) {
1141                         error = EINVAL;
1142                         goto out;
1143                 }
1144         }
1145         if (fvp->v_type == VDIR && fvp->v_mountedhere) {
1146                 error = (ndflag & ND_NFSV2) ? ENOTEMPTY : EXDEV;
1147                 goto out;
1148         }
1149         if (fvp->v_mount != tdvp->v_mount) {
1150                 error = (ndflag & ND_NFSV2) ? ENOTEMPTY : EXDEV;
1151                 goto out;
1152         }
1153         if (fvp == tdvp) {
1154                 error = (ndflag & ND_NFSV2) ? ENOTEMPTY : EINVAL;
1155                 goto out;
1156         }
1157         if (fvp == tvp) {
1158                 /*
1159                  * If source and destination are the same, there is nothing to
1160                  * do. Set error to -1 to indicate this.
1161                  */
1162                 error = -1;
1163                 goto out;
1164         }
1165         if (ndflag & ND_NFSV4) {
1166                 if (NFSVOPLOCK(fvp, LK_EXCLUSIVE) == 0) {
1167                         error = nfsrv_checkremove(fvp, 0, p);
1168                         NFSVOPUNLOCK(fvp, 0);
1169                 } else
1170                         error = EPERM;
1171                 if (tvp && !error)
1172                         error = nfsrv_checkremove(tvp, 1, p);
1173         } else {
1174                 /*
1175                  * For NFSv2 and NFSv3, try to get rid of the delegation, so
1176                  * that the NFSv4 client won't be confused by the rename.
1177                  * Since nfsd_recalldelegation() can only be called on an
1178                  * unlocked vnode at this point and fvp is the file that will
1179                  * still exist after the rename, just do fvp.
1180                  */
1181                 nfsd_recalldelegation(fvp, p);
1182         }
1183 out:
1184         if (!error) {
1185                 error = VOP_RENAME(fromndp->ni_dvp, fromndp->ni_vp,
1186                     &fromndp->ni_cnd, tondp->ni_dvp, tondp->ni_vp,
1187                     &tondp->ni_cnd);
1188         } else {
1189                 if (tdvp == tvp)
1190                         vrele(tdvp);
1191                 else
1192                         vput(tdvp);
1193                 if (tvp)
1194                         vput(tvp);
1195                 vrele(fromndp->ni_dvp);
1196                 vrele(fvp);
1197                 if (error == -1)
1198                         error = 0;
1199         }
1200         vrele(tondp->ni_startdir);
1201         nfsvno_relpathbuf(tondp);
1202 out1:
1203         vrele(fromndp->ni_startdir);
1204         nfsvno_relpathbuf(fromndp);
1205         NFSEXITCODE(error);
1206         return (error);
1207 }
1208
1209 /*
1210  * Link vnode op.
1211  */
1212 int
1213 nfsvno_link(struct nameidata *ndp, struct vnode *vp, struct ucred *cred,
1214     struct thread *p, struct nfsexstuff *exp)
1215 {
1216         struct vnode *xp;
1217         int error = 0;
1218
1219         xp = ndp->ni_vp;
1220         if (xp != NULL) {
1221                 error = EEXIST;
1222         } else {
1223                 xp = ndp->ni_dvp;
1224                 if (vp->v_mount != xp->v_mount)
1225                         error = EXDEV;
1226         }
1227         if (!error) {
1228                 NFSVOPLOCK(vp, LK_EXCLUSIVE | LK_RETRY);
1229                 if ((vp->v_iflag & VI_DOOMED) == 0)
1230                         error = VOP_LINK(ndp->ni_dvp, vp, &ndp->ni_cnd);
1231                 else
1232                         error = EPERM;
1233                 if (ndp->ni_dvp == vp)
1234                         vrele(ndp->ni_dvp);
1235                 else
1236                         vput(ndp->ni_dvp);
1237                 NFSVOPUNLOCK(vp, 0);
1238         } else {
1239                 if (ndp->ni_dvp == ndp->ni_vp)
1240                         vrele(ndp->ni_dvp);
1241                 else
1242                         vput(ndp->ni_dvp);
1243                 if (ndp->ni_vp)
1244                         vrele(ndp->ni_vp);
1245         }
1246         nfsvno_relpathbuf(ndp);
1247         NFSEXITCODE(error);
1248         return (error);
1249 }
1250
1251 /*
1252  * Do the fsync() appropriate for the commit.
1253  */
1254 int
1255 nfsvno_fsync(struct vnode *vp, u_int64_t off, int cnt, struct ucred *cred,
1256     struct thread *td)
1257 {
1258         int error = 0;
1259
1260         /*
1261          * RFC 1813 3.3.21: if count is 0, a flush from offset to the end of
1262          * file is done.  At this time VOP_FSYNC does not accept offset and
1263          * byte count parameters so call VOP_FSYNC the whole file for now.
1264          * The same is true for NFSv4: RFC 3530 Sec. 14.2.3.
1265          */
1266         if (cnt == 0 || cnt > MAX_COMMIT_COUNT) {
1267                 /*
1268                  * Give up and do the whole thing
1269                  */
1270                 if (vp->v_object &&
1271                    (vp->v_object->flags & OBJ_MIGHTBEDIRTY)) {
1272                         VM_OBJECT_LOCK(vp->v_object);
1273                         vm_object_page_clean(vp->v_object, 0, 0, OBJPC_SYNC);
1274                         VM_OBJECT_UNLOCK(vp->v_object);
1275                 }
1276                 error = VOP_FSYNC(vp, MNT_WAIT, td);
1277         } else {
1278                 /*
1279                  * Locate and synchronously write any buffers that fall
1280                  * into the requested range.  Note:  we are assuming that
1281                  * f_iosize is a power of 2.
1282                  */
1283                 int iosize = vp->v_mount->mnt_stat.f_iosize;
1284                 int iomask = iosize - 1;
1285                 struct bufobj *bo;
1286                 daddr_t lblkno;
1287
1288                 /*
1289                  * Align to iosize boundry, super-align to page boundry.
1290                  */
1291                 if (off & iomask) {
1292                         cnt += off & iomask;
1293                         off &= ~(u_quad_t)iomask;
1294                 }
1295                 if (off & PAGE_MASK) {
1296                         cnt += off & PAGE_MASK;
1297                         off &= ~(u_quad_t)PAGE_MASK;
1298                 }
1299                 lblkno = off / iosize;
1300
1301                 if (vp->v_object &&
1302                    (vp->v_object->flags & OBJ_MIGHTBEDIRTY)) {
1303                         VM_OBJECT_LOCK(vp->v_object);
1304                         vm_object_page_clean(vp->v_object, off, off + cnt,
1305                             OBJPC_SYNC);
1306                         VM_OBJECT_UNLOCK(vp->v_object);
1307                 }
1308
1309                 bo = &vp->v_bufobj;
1310                 BO_LOCK(bo);
1311                 while (cnt > 0) {
1312                         struct buf *bp;
1313
1314                         /*
1315                          * If we have a buffer and it is marked B_DELWRI we
1316                          * have to lock and write it.  Otherwise the prior
1317                          * write is assumed to have already been committed.
1318                          *
1319                          * gbincore() can return invalid buffers now so we
1320                          * have to check that bit as well (though B_DELWRI
1321                          * should not be set if B_INVAL is set there could be
1322                          * a race here since we haven't locked the buffer).
1323                          */
1324                         if ((bp = gbincore(&vp->v_bufobj, lblkno)) != NULL) {
1325                                 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_SLEEPFAIL |
1326                                     LK_INTERLOCK, BO_MTX(bo)) == ENOLCK) {
1327                                         BO_LOCK(bo);
1328                                         continue; /* retry */
1329                                 }
1330                                 if ((bp->b_flags & (B_DELWRI|B_INVAL)) ==
1331                                     B_DELWRI) {
1332                                         bremfree(bp);
1333                                         bp->b_flags &= ~B_ASYNC;
1334                                         bwrite(bp);
1335                                         ++nfs_commit_miss;
1336                                 } else
1337                                         BUF_UNLOCK(bp);
1338                                 BO_LOCK(bo);
1339                         }
1340                         ++nfs_commit_blks;
1341                         if (cnt < iosize)
1342                                 break;
1343                         cnt -= iosize;
1344                         ++lblkno;
1345                 }
1346                 BO_UNLOCK(bo);
1347         }
1348         NFSEXITCODE(error);
1349         return (error);
1350 }
1351
1352 /*
1353  * Statfs vnode op.
1354  */
1355 int
1356 nfsvno_statfs(struct vnode *vp, struct statfs *sf)
1357 {
1358         int error;
1359
1360         error = VFS_STATFS(vp->v_mount, sf);
1361         if (error == 0) {
1362                 /*
1363                  * Since NFS handles these values as unsigned on the
1364                  * wire, there is no way to represent negative values,
1365                  * so set them to 0. Without this, they will appear
1366                  * to be very large positive values for clients like
1367                  * Solaris10.
1368                  */
1369                 if (sf->f_bavail < 0)
1370                         sf->f_bavail = 0;
1371                 if (sf->f_ffree < 0)
1372                         sf->f_ffree = 0;
1373         }
1374         NFSEXITCODE(error);
1375         return (error);
1376 }
1377
1378 /*
1379  * Do the vnode op stuff for Open. Similar to nfsvno_createsub(), but
1380  * must handle nfsrv_opencheck() calls after any other access checks.
1381  */
1382 void
1383 nfsvno_open(struct nfsrv_descript *nd, struct nameidata *ndp,
1384     nfsquad_t clientid, nfsv4stateid_t *stateidp, struct nfsstate *stp,
1385     int *exclusive_flagp, struct nfsvattr *nvap, int32_t *cverf, int create,
1386     NFSACL_T *aclp, nfsattrbit_t *attrbitp, struct ucred *cred, struct thread *p,
1387     struct nfsexstuff *exp, struct vnode **vpp)
1388 {
1389         struct vnode *vp = NULL;
1390         u_quad_t tempsize;
1391         struct nfsexstuff nes;
1392
1393         if (ndp->ni_vp == NULL)
1394                 nd->nd_repstat = nfsrv_opencheck(clientid,
1395                     stateidp, stp, NULL, nd, p, nd->nd_repstat);
1396         if (!nd->nd_repstat) {
1397                 if (ndp->ni_vp == NULL) {
1398                         vrele(ndp->ni_startdir);
1399                         nd->nd_repstat = VOP_CREATE(ndp->ni_dvp,
1400                             &ndp->ni_vp, &ndp->ni_cnd, &nvap->na_vattr);
1401                         vput(ndp->ni_dvp);
1402                         nfsvno_relpathbuf(ndp);
1403                         if (!nd->nd_repstat) {
1404                                 if (*exclusive_flagp) {
1405                                         *exclusive_flagp = 0;
1406                                         NFSVNO_ATTRINIT(nvap);
1407                                         nvap->na_atime.tv_sec = cverf[0];
1408                                         nvap->na_atime.tv_nsec = cverf[1];
1409                                         nd->nd_repstat = VOP_SETATTR(ndp->ni_vp,
1410                                             &nvap->na_vattr, cred);
1411                                 } else {
1412                                         nfsrv_fixattr(nd, ndp->ni_vp, nvap,
1413                                             aclp, p, attrbitp, exp);
1414                                 }
1415                         }
1416                         vp = ndp->ni_vp;
1417                 } else {
1418                         if (ndp->ni_startdir)
1419                                 vrele(ndp->ni_startdir);
1420                         nfsvno_relpathbuf(ndp);
1421                         vp = ndp->ni_vp;
1422                         if (create == NFSV4OPEN_CREATE) {
1423                                 if (ndp->ni_dvp == vp)
1424                                         vrele(ndp->ni_dvp);
1425                                 else
1426                                         vput(ndp->ni_dvp);
1427                         }
1428                         if (NFSVNO_ISSETSIZE(nvap) && vp->v_type == VREG) {
1429                                 if (ndp->ni_cnd.cn_flags & RDONLY)
1430                                         NFSVNO_SETEXRDONLY(&nes);
1431                                 else
1432                                         NFSVNO_EXINIT(&nes);
1433                                 nd->nd_repstat = nfsvno_accchk(vp, 
1434                                     VWRITE, cred, &nes, p,
1435                                     NFSACCCHK_NOOVERRIDE,
1436                                     NFSACCCHK_VPISLOCKED, NULL);
1437                                 nd->nd_repstat = nfsrv_opencheck(clientid,
1438                                     stateidp, stp, vp, nd, p, nd->nd_repstat);
1439                                 if (!nd->nd_repstat) {
1440                                         tempsize = nvap->na_size;
1441                                         NFSVNO_ATTRINIT(nvap);
1442                                         nvap->na_size = tempsize;
1443                                         nd->nd_repstat = VOP_SETATTR(vp,
1444                                             &nvap->na_vattr, cred);
1445                                 }
1446                         } else if (vp->v_type == VREG) {
1447                                 nd->nd_repstat = nfsrv_opencheck(clientid,
1448                                     stateidp, stp, vp, nd, p, nd->nd_repstat);
1449                         }
1450                 }
1451         } else {
1452                 if (ndp->ni_cnd.cn_flags & HASBUF)
1453                         nfsvno_relpathbuf(ndp);
1454                 if (ndp->ni_startdir && create == NFSV4OPEN_CREATE) {
1455                         vrele(ndp->ni_startdir);
1456                         if (ndp->ni_dvp == ndp->ni_vp)
1457                                 vrele(ndp->ni_dvp);
1458                         else
1459                                 vput(ndp->ni_dvp);
1460                         if (ndp->ni_vp)
1461                                 vput(ndp->ni_vp);
1462                 }
1463         }
1464         *vpp = vp;
1465
1466         NFSEXITCODE2(0, nd);
1467 }
1468
1469 /*
1470  * Updates the file rev and sets the mtime and ctime
1471  * to the current clock time, returning the va_filerev and va_Xtime
1472  * values.
1473  */
1474 void
1475 nfsvno_updfilerev(struct vnode *vp, struct nfsvattr *nvap,
1476     struct ucred *cred, struct thread *p)
1477 {
1478         struct vattr va;
1479
1480         VATTR_NULL(&va);
1481         vfs_timestamp(&va.va_mtime);
1482         (void) VOP_SETATTR(vp, &va, cred);
1483         (void) nfsvno_getattr(vp, nvap, cred, p, 1);
1484 }
1485
1486 /*
1487  * Glue routine to nfsv4_fillattr().
1488  */
1489 int
1490 nfsvno_fillattr(struct nfsrv_descript *nd, struct mount *mp, struct vnode *vp,
1491     struct nfsvattr *nvap, fhandle_t *fhp, int rderror, nfsattrbit_t *attrbitp,
1492     struct ucred *cred, struct thread *p, int isdgram, int reterr,
1493     int supports_nfsv4acls, int at_root, uint64_t mounted_on_fileno)
1494 {
1495         int error;
1496
1497         error = nfsv4_fillattr(nd, mp, vp, NULL, &nvap->na_vattr, fhp, rderror,
1498             attrbitp, cred, p, isdgram, reterr, supports_nfsv4acls, at_root,
1499             mounted_on_fileno);
1500         NFSEXITCODE2(0, nd);
1501         return (error);
1502 }
1503
1504 /* Since the Readdir vnode ops vary, put the entire functions in here. */
1505 /*
1506  * nfs readdir service
1507  * - mallocs what it thinks is enough to read
1508  *      count rounded up to a multiple of DIRBLKSIZ <= NFS_MAXREADDIR
1509  * - calls VOP_READDIR()
1510  * - loops around building the reply
1511  *      if the output generated exceeds count break out of loop
1512  *      The NFSM_CLGET macro is used here so that the reply will be packed
1513  *      tightly in mbuf clusters.
1514  * - it trims out records with d_fileno == 0
1515  *      this doesn't matter for Unix clients, but they might confuse clients
1516  *      for other os'.
1517  * - it trims out records with d_type == DT_WHT
1518  *      these cannot be seen through NFS (unless we extend the protocol)
1519  *     The alternate call nfsrvd_readdirplus() does lookups as well.
1520  * PS: The NFS protocol spec. does not clarify what the "count" byte
1521  *      argument is a count of.. just name strings and file id's or the
1522  *      entire reply rpc or ...
1523  *      I tried just file name and id sizes and it confused the Sun client,
1524  *      so I am using the full rpc size now. The "paranoia.." comment refers
1525  *      to including the status longwords that are not a part of the dir.
1526  *      "entry" structures, but are in the rpc.
1527  */
1528 int
1529 nfsrvd_readdir(struct nfsrv_descript *nd, int isdgram,
1530     struct vnode *vp, struct thread *p, struct nfsexstuff *exp)
1531 {
1532         struct dirent *dp;
1533         u_int32_t *tl;
1534         int dirlen;
1535         char *cpos, *cend, *rbuf;
1536         struct nfsvattr at;
1537         int nlen, error = 0, getret = 1;
1538         int siz, cnt, fullsiz, eofflag, ncookies;
1539         u_int64_t off, toff, verf;
1540         u_long *cookies = NULL, *cookiep;
1541         struct uio io;
1542         struct iovec iv;
1543         int not_zfs;
1544
1545         if (nd->nd_repstat) {
1546                 nfsrv_postopattr(nd, getret, &at);
1547                 goto out;
1548         }
1549         if (nd->nd_flag & ND_NFSV2) {
1550                 NFSM_DISSECT(tl, u_int32_t *, 2 * NFSX_UNSIGNED);
1551                 off = fxdr_unsigned(u_quad_t, *tl++);
1552         } else {
1553                 NFSM_DISSECT(tl, u_int32_t *, 5 * NFSX_UNSIGNED);
1554                 off = fxdr_hyper(tl);
1555                 tl += 2;
1556                 verf = fxdr_hyper(tl);
1557                 tl += 2;
1558         }
1559         toff = off;
1560         cnt = fxdr_unsigned(int, *tl);
1561         if (cnt > NFS_SRVMAXDATA(nd) || cnt < 0)
1562                 cnt = NFS_SRVMAXDATA(nd);
1563         siz = ((cnt + DIRBLKSIZ - 1) & ~(DIRBLKSIZ - 1));
1564         fullsiz = siz;
1565         if (nd->nd_flag & ND_NFSV3) {
1566                 nd->nd_repstat = getret = nfsvno_getattr(vp, &at, nd->nd_cred,
1567                     p, 1);
1568 #if 0
1569                 /*
1570                  * va_filerev is not sufficient as a cookie verifier,
1571                  * since it is not supposed to change when entries are
1572                  * removed/added unless that offset cookies returned to
1573                  * the client are no longer valid.
1574                  */
1575                 if (!nd->nd_repstat && toff && verf != at.na_filerev)
1576                         nd->nd_repstat = NFSERR_BAD_COOKIE;
1577 #endif
1578         }
1579         if (!nd->nd_repstat && vp->v_type != VDIR)
1580                 nd->nd_repstat = NFSERR_NOTDIR;
1581         if (nd->nd_repstat == 0 && cnt == 0) {
1582                 if (nd->nd_flag & ND_NFSV2)
1583                         /* NFSv2 does not have NFSERR_TOOSMALL */
1584                         nd->nd_repstat = EPERM;
1585                 else
1586                         nd->nd_repstat = NFSERR_TOOSMALL;
1587         }
1588         if (!nd->nd_repstat)
1589                 nd->nd_repstat = nfsvno_accchk(vp, VEXEC,
1590                     nd->nd_cred, exp, p, NFSACCCHK_NOOVERRIDE,
1591                     NFSACCCHK_VPISLOCKED, NULL);
1592         if (nd->nd_repstat) {
1593                 vput(vp);
1594                 if (nd->nd_flag & ND_NFSV3)
1595                         nfsrv_postopattr(nd, getret, &at);
1596                 goto out;
1597         }
1598         not_zfs = strcmp(vp->v_mount->mnt_vfc->vfc_name, "zfs");
1599         MALLOC(rbuf, caddr_t, siz, M_TEMP, M_WAITOK);
1600 again:
1601         eofflag = 0;
1602         if (cookies) {
1603                 free((caddr_t)cookies, M_TEMP);
1604                 cookies = NULL;
1605         }
1606
1607         iv.iov_base = rbuf;
1608         iv.iov_len = siz;
1609         io.uio_iov = &iv;
1610         io.uio_iovcnt = 1;
1611         io.uio_offset = (off_t)off;
1612         io.uio_resid = siz;
1613         io.uio_segflg = UIO_SYSSPACE;
1614         io.uio_rw = UIO_READ;
1615         io.uio_td = NULL;
1616         nd->nd_repstat = VOP_READDIR(vp, &io, nd->nd_cred, &eofflag, &ncookies,
1617             &cookies);
1618         off = (u_int64_t)io.uio_offset;
1619         if (io.uio_resid)
1620                 siz -= io.uio_resid;
1621
1622         if (!cookies && !nd->nd_repstat)
1623                 nd->nd_repstat = NFSERR_PERM;
1624         if (nd->nd_flag & ND_NFSV3) {
1625                 getret = nfsvno_getattr(vp, &at, nd->nd_cred, p, 1);
1626                 if (!nd->nd_repstat)
1627                         nd->nd_repstat = getret;
1628         }
1629
1630         /*
1631          * Handles the failed cases. nd->nd_repstat == 0 past here.
1632          */
1633         if (nd->nd_repstat) {
1634                 vput(vp);
1635                 free((caddr_t)rbuf, M_TEMP);
1636                 if (cookies)
1637                         free((caddr_t)cookies, M_TEMP);
1638                 if (nd->nd_flag & ND_NFSV3)
1639                         nfsrv_postopattr(nd, getret, &at);
1640                 goto out;
1641         }
1642         /*
1643          * If nothing read, return eof
1644          * rpc reply
1645          */
1646         if (siz == 0) {
1647                 vput(vp);
1648                 if (nd->nd_flag & ND_NFSV2) {
1649                         NFSM_BUILD(tl, u_int32_t *, 2 * NFSX_UNSIGNED);
1650                 } else {
1651                         nfsrv_postopattr(nd, getret, &at);
1652                         NFSM_BUILD(tl, u_int32_t *, 4 * NFSX_UNSIGNED);
1653                         txdr_hyper(at.na_filerev, tl);
1654                         tl += 2;
1655                 }
1656                 *tl++ = newnfs_false;
1657                 *tl = newnfs_true;
1658                 FREE((caddr_t)rbuf, M_TEMP);
1659                 FREE((caddr_t)cookies, M_TEMP);
1660                 goto out;
1661         }
1662
1663         /*
1664          * Check for degenerate cases of nothing useful read.
1665          * If so go try again
1666          */
1667         cpos = rbuf;
1668         cend = rbuf + siz;
1669         dp = (struct dirent *)cpos;
1670         cookiep = cookies;
1671
1672         /*
1673          * For some reason FreeBSD's ufs_readdir() chooses to back the
1674          * directory offset up to a block boundary, so it is necessary to
1675          * skip over the records that precede the requested offset. This
1676          * requires the assumption that file offset cookies monotonically
1677          * increase.
1678          * Since the offset cookies don't monotonically increase for ZFS,
1679          * this is not done when ZFS is the file system.
1680          */
1681         while (cpos < cend && ncookies > 0 &&
1682             (dp->d_fileno == 0 || dp->d_type == DT_WHT ||
1683              (not_zfs != 0 && ((u_quad_t)(*cookiep)) <= toff))) {
1684                 cpos += dp->d_reclen;
1685                 dp = (struct dirent *)cpos;
1686                 cookiep++;
1687                 ncookies--;
1688         }
1689         if (cpos >= cend || ncookies == 0) {
1690                 siz = fullsiz;
1691                 toff = off;
1692                 goto again;
1693         }
1694         vput(vp);
1695
1696         /*
1697          * dirlen is the size of the reply, including all XDR and must
1698          * not exceed cnt. For NFSv2, RFC1094 didn't clearly indicate
1699          * if the XDR should be included in "count", but to be safe, we do.
1700          * (Include the two booleans at the end of the reply in dirlen now.)
1701          */
1702         if (nd->nd_flag & ND_NFSV3) {
1703                 nfsrv_postopattr(nd, getret, &at);
1704                 NFSM_BUILD(tl, u_int32_t *, 2 * NFSX_UNSIGNED);
1705                 txdr_hyper(at.na_filerev, tl);
1706                 dirlen = NFSX_V3POSTOPATTR + NFSX_VERF + 2 * NFSX_UNSIGNED;
1707         } else {
1708                 dirlen = 2 * NFSX_UNSIGNED;
1709         }
1710
1711         /* Loop through the records and build reply */
1712         while (cpos < cend && ncookies > 0) {
1713                 nlen = dp->d_namlen;
1714                 if (dp->d_fileno != 0 && dp->d_type != DT_WHT &&
1715                         nlen <= NFS_MAXNAMLEN) {
1716                         if (nd->nd_flag & ND_NFSV3)
1717                                 dirlen += (6*NFSX_UNSIGNED + NFSM_RNDUP(nlen));
1718                         else
1719                                 dirlen += (4*NFSX_UNSIGNED + NFSM_RNDUP(nlen));
1720                         if (dirlen > cnt) {
1721                                 eofflag = 0;
1722                                 break;
1723                         }
1724
1725                         /*
1726                          * Build the directory record xdr from
1727                          * the dirent entry.
1728                          */
1729                         if (nd->nd_flag & ND_NFSV3) {
1730                                 NFSM_BUILD(tl, u_int32_t *, 3 * NFSX_UNSIGNED);
1731                                 *tl++ = newnfs_true;
1732                                 *tl++ = 0;
1733                         } else {
1734                                 NFSM_BUILD(tl, u_int32_t *, 2 * NFSX_UNSIGNED);
1735                                 *tl++ = newnfs_true;
1736                         }
1737                         *tl = txdr_unsigned(dp->d_fileno);
1738                         (void) nfsm_strtom(nd, dp->d_name, nlen);
1739                         if (nd->nd_flag & ND_NFSV3) {
1740                                 NFSM_BUILD(tl, u_int32_t *, 2 * NFSX_UNSIGNED);
1741                                 *tl++ = 0;
1742                         } else
1743                                 NFSM_BUILD(tl, u_int32_t *, NFSX_UNSIGNED);
1744                         *tl = txdr_unsigned(*cookiep);
1745                 }
1746                 cpos += dp->d_reclen;
1747                 dp = (struct dirent *)cpos;
1748                 cookiep++;
1749                 ncookies--;
1750         }
1751         if (cpos < cend)
1752                 eofflag = 0;
1753         NFSM_BUILD(tl, u_int32_t *, 2 * NFSX_UNSIGNED);
1754         *tl++ = newnfs_false;
1755         if (eofflag)
1756                 *tl = newnfs_true;
1757         else
1758                 *tl = newnfs_false;
1759         FREE((caddr_t)rbuf, M_TEMP);
1760         FREE((caddr_t)cookies, M_TEMP);
1761
1762 out:
1763         NFSEXITCODE2(0, nd);
1764         return (0);
1765 nfsmout:
1766         vput(vp);
1767         NFSEXITCODE2(error, nd);
1768         return (error);
1769 }
1770
1771 /*
1772  * Readdirplus for V3 and Readdir for V4.
1773  */
1774 int
1775 nfsrvd_readdirplus(struct nfsrv_descript *nd, int isdgram,
1776     struct vnode *vp, struct thread *p, struct nfsexstuff *exp)
1777 {
1778         struct dirent *dp;
1779         u_int32_t *tl;
1780         int dirlen;
1781         char *cpos, *cend, *rbuf;
1782         struct vnode *nvp;
1783         fhandle_t nfh;
1784         struct nfsvattr nva, at, *nvap = &nva;
1785         struct mbuf *mb0, *mb1;
1786         struct nfsreferral *refp;
1787         int nlen, r, error = 0, getret = 1, usevget = 1;
1788         int siz, cnt, fullsiz, eofflag, ncookies, entrycnt;
1789         caddr_t bpos0, bpos1;
1790         u_int64_t off, toff, verf;
1791         u_long *cookies = NULL, *cookiep;
1792         nfsattrbit_t attrbits, rderrbits, savbits;
1793         struct uio io;
1794         struct iovec iv;
1795         struct componentname cn;
1796         int at_root, needs_unbusy, not_zfs, supports_nfsv4acls;
1797         struct mount *mp, *new_mp;
1798         uint64_t mounted_on_fileno;
1799
1800         if (nd->nd_repstat) {
1801                 nfsrv_postopattr(nd, getret, &at);
1802                 goto out;
1803         }
1804         NFSM_DISSECT(tl, u_int32_t *, 6 * NFSX_UNSIGNED);
1805         off = fxdr_hyper(tl);
1806         toff = off;
1807         tl += 2;
1808         verf = fxdr_hyper(tl);
1809         tl += 2;
1810         siz = fxdr_unsigned(int, *tl++);
1811         cnt = fxdr_unsigned(int, *tl);
1812
1813         /*
1814          * Use the server's maximum data transfer size as the upper bound
1815          * on reply datalen.
1816          */
1817         if (cnt > NFS_SRVMAXDATA(nd) || cnt < 0)
1818                 cnt = NFS_SRVMAXDATA(nd);
1819
1820         /*
1821          * siz is a "hint" of how much directory information (name, fileid,
1822          * cookie) should be in the reply. At least one client "hints" 0,
1823          * so I set it to cnt for that case. I also round it up to the
1824          * next multiple of DIRBLKSIZ.
1825          */
1826         if (siz <= 0)
1827                 siz = cnt;
1828         siz = ((siz + DIRBLKSIZ - 1) & ~(DIRBLKSIZ - 1));
1829
1830         if (nd->nd_flag & ND_NFSV4) {
1831                 error = nfsrv_getattrbits(nd, &attrbits, NULL, NULL);
1832                 if (error)
1833                         goto nfsmout;
1834                 NFSSET_ATTRBIT(&savbits, &attrbits);
1835                 NFSCLRNOTFILLABLE_ATTRBIT(&attrbits);
1836                 NFSZERO_ATTRBIT(&rderrbits);
1837                 NFSSETBIT_ATTRBIT(&rderrbits, NFSATTRBIT_RDATTRERROR);
1838         } else {
1839                 NFSZERO_ATTRBIT(&attrbits);
1840         }
1841         fullsiz = siz;
1842         nd->nd_repstat = getret = nfsvno_getattr(vp, &at, nd->nd_cred, p, 1);
1843         if (!nd->nd_repstat) {
1844             if (off && verf != at.na_filerev) {
1845                 /*
1846                  * va_filerev is not sufficient as a cookie verifier,
1847                  * since it is not supposed to change when entries are
1848                  * removed/added unless that offset cookies returned to
1849                  * the client are no longer valid.
1850                  */
1851 #if 0
1852                 if (nd->nd_flag & ND_NFSV4) {
1853                         nd->nd_repstat = NFSERR_NOTSAME;
1854                 } else {
1855                         nd->nd_repstat = NFSERR_BAD_COOKIE;
1856                 }
1857 #endif
1858             } else if ((nd->nd_flag & ND_NFSV4) && off == 0 && verf != 0) {
1859                 nd->nd_repstat = NFSERR_BAD_COOKIE;
1860             }
1861         }
1862         if (!nd->nd_repstat && vp->v_type != VDIR)
1863                 nd->nd_repstat = NFSERR_NOTDIR;
1864         if (!nd->nd_repstat && cnt == 0)
1865                 nd->nd_repstat = NFSERR_TOOSMALL;
1866         if (!nd->nd_repstat)
1867                 nd->nd_repstat = nfsvno_accchk(vp, VEXEC,
1868                     nd->nd_cred, exp, p, NFSACCCHK_NOOVERRIDE,
1869                     NFSACCCHK_VPISLOCKED, NULL);
1870         if (nd->nd_repstat) {
1871                 vput(vp);
1872                 if (nd->nd_flag & ND_NFSV3)
1873                         nfsrv_postopattr(nd, getret, &at);
1874                 goto out;
1875         }
1876         not_zfs = strcmp(vp->v_mount->mnt_vfc->vfc_name, "zfs");
1877
1878         MALLOC(rbuf, caddr_t, siz, M_TEMP, M_WAITOK);
1879 again:
1880         eofflag = 0;
1881         if (cookies) {
1882                 free((caddr_t)cookies, M_TEMP);
1883                 cookies = NULL;
1884         }
1885
1886         iv.iov_base = rbuf;
1887         iv.iov_len = siz;
1888         io.uio_iov = &iv;
1889         io.uio_iovcnt = 1;
1890         io.uio_offset = (off_t)off;
1891         io.uio_resid = siz;
1892         io.uio_segflg = UIO_SYSSPACE;
1893         io.uio_rw = UIO_READ;
1894         io.uio_td = NULL;
1895         nd->nd_repstat = VOP_READDIR(vp, &io, nd->nd_cred, &eofflag, &ncookies,
1896             &cookies);
1897         off = (u_int64_t)io.uio_offset;
1898         if (io.uio_resid)
1899                 siz -= io.uio_resid;
1900
1901         getret = nfsvno_getattr(vp, &at, nd->nd_cred, p, 1);
1902
1903         if (!cookies && !nd->nd_repstat)
1904                 nd->nd_repstat = NFSERR_PERM;
1905         if (!nd->nd_repstat)
1906                 nd->nd_repstat = getret;
1907         if (nd->nd_repstat) {
1908                 vput(vp);
1909                 if (cookies)
1910                         free((caddr_t)cookies, M_TEMP);
1911                 free((caddr_t)rbuf, M_TEMP);
1912                 if (nd->nd_flag & ND_NFSV3)
1913                         nfsrv_postopattr(nd, getret, &at);
1914                 goto out;
1915         }
1916         /*
1917          * If nothing read, return eof
1918          * rpc reply
1919          */
1920         if (siz == 0) {
1921                 vput(vp);
1922                 if (nd->nd_flag & ND_NFSV3)
1923                         nfsrv_postopattr(nd, getret, &at);
1924                 NFSM_BUILD(tl, u_int32_t *, 4 * NFSX_UNSIGNED);
1925                 txdr_hyper(at.na_filerev, tl);
1926                 tl += 2;
1927                 *tl++ = newnfs_false;
1928                 *tl = newnfs_true;
1929                 free((caddr_t)cookies, M_TEMP);
1930                 free((caddr_t)rbuf, M_TEMP);
1931                 goto out;
1932         }
1933
1934         /*
1935          * Check for degenerate cases of nothing useful read.
1936          * If so go try again
1937          */
1938         cpos = rbuf;
1939         cend = rbuf + siz;
1940         dp = (struct dirent *)cpos;
1941         cookiep = cookies;
1942
1943         /*
1944          * For some reason FreeBSD's ufs_readdir() chooses to back the
1945          * directory offset up to a block boundary, so it is necessary to
1946          * skip over the records that precede the requested offset. This
1947          * requires the assumption that file offset cookies monotonically
1948          * increase.
1949          * Since the offset cookies don't monotonically increase for ZFS,
1950          * this is not done when ZFS is the file system.
1951          */
1952         while (cpos < cend && ncookies > 0 &&
1953           (dp->d_fileno == 0 || dp->d_type == DT_WHT ||
1954            (not_zfs != 0 && ((u_quad_t)(*cookiep)) <= toff) ||
1955            ((nd->nd_flag & ND_NFSV4) &&
1956             ((dp->d_namlen == 1 && dp->d_name[0] == '.') ||
1957              (dp->d_namlen==2 && dp->d_name[0]=='.' && dp->d_name[1]=='.'))))) {
1958                 cpos += dp->d_reclen;
1959                 dp = (struct dirent *)cpos;
1960                 cookiep++;
1961                 ncookies--;
1962         }
1963         if (cpos >= cend || ncookies == 0) {
1964                 siz = fullsiz;
1965                 toff = off;
1966                 goto again;
1967         }
1968
1969         /*
1970          * Busy the file system so that the mount point won't go away
1971          * and, as such, VFS_VGET() can be used safely.
1972          */
1973         mp = vp->v_mount;
1974         vfs_ref(mp);
1975         NFSVOPUNLOCK(vp, 0);
1976         nd->nd_repstat = vfs_busy(mp, 0);
1977         vfs_rel(mp);
1978         if (nd->nd_repstat != 0) {
1979                 vrele(vp);
1980                 free(cookies, M_TEMP);
1981                 free(rbuf, M_TEMP);
1982                 if (nd->nd_flag & ND_NFSV3)
1983                         nfsrv_postopattr(nd, getret, &at);
1984                 goto out;
1985         }
1986
1987         /*
1988          * Check to see if entries in this directory can be safely acquired
1989          * via VFS_VGET() or if a switch to VOP_LOOKUP() is required.
1990          * ZFS snapshot directories need VOP_LOOKUP(), so that any
1991          * automount of the snapshot directory that is required will
1992          * be done.
1993          * This needs to be done here for NFSv4, since NFSv4 never does
1994          * a VFS_VGET() for "." or "..".
1995          */
1996         if (not_zfs == 0) {
1997                 r = VFS_VGET(mp, at.na_fileid, LK_SHARED, &nvp);
1998                 if (r == EOPNOTSUPP) {
1999                         usevget = 0;
2000                         cn.cn_nameiop = LOOKUP;
2001                         cn.cn_lkflags = LK_SHARED | LK_RETRY;
2002                         cn.cn_cred = nd->nd_cred;
2003                         cn.cn_thread = p;
2004                 } else if (r == 0)
2005                         vput(nvp);
2006         }
2007
2008         /*
2009          * Save this position, in case there is an error before one entry
2010          * is created.
2011          */
2012         mb0 = nd->nd_mb;
2013         bpos0 = nd->nd_bpos;
2014
2015         /*
2016          * Fill in the first part of the reply.
2017          * dirlen is the reply length in bytes and cannot exceed cnt.
2018          * (Include the two booleans at the end of the reply in dirlen now,
2019          *  so we recognize when we have exceeded cnt.)
2020          */
2021         if (nd->nd_flag & ND_NFSV3) {
2022                 dirlen = NFSX_V3POSTOPATTR + NFSX_VERF + 2 * NFSX_UNSIGNED;
2023                 nfsrv_postopattr(nd, getret, &at);
2024         } else {
2025                 dirlen = NFSX_VERF + 2 * NFSX_UNSIGNED;
2026         }
2027         NFSM_BUILD(tl, u_int32_t *, NFSX_VERF);
2028         txdr_hyper(at.na_filerev, tl);
2029
2030         /*
2031          * Save this position, in case there is an empty reply needed.
2032          */
2033         mb1 = nd->nd_mb;
2034         bpos1 = nd->nd_bpos;
2035
2036         /* Loop through the records and build reply */
2037         entrycnt = 0;
2038         while (cpos < cend && ncookies > 0 && dirlen < cnt) {
2039                 nlen = dp->d_namlen;
2040                 if (dp->d_fileno != 0 && dp->d_type != DT_WHT &&
2041                     nlen <= NFS_MAXNAMLEN &&
2042                     ((nd->nd_flag & ND_NFSV3) || nlen > 2 ||
2043                      (nlen==2 && (dp->d_name[0]!='.' || dp->d_name[1]!='.'))
2044                       || (nlen == 1 && dp->d_name[0] != '.'))) {
2045                         /*
2046                          * Save the current position in the reply, in case
2047                          * this entry exceeds cnt.
2048                          */
2049                         mb1 = nd->nd_mb;
2050                         bpos1 = nd->nd_bpos;
2051         
2052                         /*
2053                          * For readdir_and_lookup get the vnode using
2054                          * the file number.
2055                          */
2056                         nvp = NULL;
2057                         refp = NULL;
2058                         r = 0;
2059                         at_root = 0;
2060                         needs_unbusy = 0;
2061                         new_mp = mp;
2062                         mounted_on_fileno = (uint64_t)dp->d_fileno;
2063                         if ((nd->nd_flag & ND_NFSV3) ||
2064                             NFSNONZERO_ATTRBIT(&savbits)) {
2065                                 if (nd->nd_flag & ND_NFSV4)
2066                                         refp = nfsv4root_getreferral(NULL,
2067                                             vp, dp->d_fileno);
2068                                 if (refp == NULL) {
2069                                         if (usevget)
2070                                                 r = VFS_VGET(mp, dp->d_fileno,
2071                                                     LK_SHARED, &nvp);
2072                                         else
2073                                                 r = EOPNOTSUPP;
2074                                         if (r == EOPNOTSUPP) {
2075                                                 if (usevget) {
2076                                                         usevget = 0;
2077                                                         cn.cn_nameiop = LOOKUP;
2078                                                         cn.cn_lkflags =
2079                                                             LK_SHARED |
2080                                                             LK_RETRY;
2081                                                         cn.cn_cred =
2082                                                             nd->nd_cred;
2083                                                         cn.cn_thread = p;
2084                                                 }
2085                                                 cn.cn_nameptr = dp->d_name;
2086                                                 cn.cn_namelen = nlen;
2087                                                 cn.cn_flags = ISLASTCN |
2088                                                     NOFOLLOW | LOCKLEAF |
2089                                                     MPSAFE;
2090                                                 if (nlen == 2 &&
2091                                                     dp->d_name[0] == '.' &&
2092                                                     dp->d_name[1] == '.')
2093                                                         cn.cn_flags |=
2094                                                             ISDOTDOT;
2095                                                 if (NFSVOPLOCK(vp, LK_SHARED)
2096                                                     != 0) {
2097                                                         nd->nd_repstat = EPERM;
2098                                                         break;
2099                                                 }
2100                                                 if ((vp->v_vflag & VV_ROOT) != 0
2101                                                     && (cn.cn_flags & ISDOTDOT)
2102                                                     != 0) {
2103                                                         vref(vp);
2104                                                         nvp = vp;
2105                                                         r = 0;
2106                                                 } else {
2107                                                         r = VOP_LOOKUP(vp, &nvp,
2108                                                             &cn);
2109                                                         if (vp != nvp)
2110                                                                 NFSVOPUNLOCK(vp,
2111                                                                     0);
2112                                                 }
2113                                         }
2114
2115                                         /*
2116                                          * For NFSv4, check to see if nvp is
2117                                          * a mount point and get the mount
2118                                          * point vnode, as required.
2119                                          */
2120                                         if (r == 0 &&
2121                                             nfsrv_enable_crossmntpt != 0 &&
2122                                             (nd->nd_flag & ND_NFSV4) != 0 &&
2123                                             nvp->v_type == VDIR &&
2124                                             nvp->v_mountedhere != NULL) {
2125                                                 new_mp = nvp->v_mountedhere;
2126                                                 r = vfs_busy(new_mp, 0);
2127                                                 vput(nvp);
2128                                                 nvp = NULL;
2129                                                 if (r == 0) {
2130                                                         r = VFS_ROOT(new_mp,
2131                                                             LK_SHARED, &nvp);
2132                                                         needs_unbusy = 1;
2133                                                         if (r == 0)
2134                                                                 at_root = 1;
2135                                                 }
2136                                         }
2137                                 }
2138                                 if (!r) {
2139                                     if (refp == NULL &&
2140                                         ((nd->nd_flag & ND_NFSV3) ||
2141                                          NFSNONZERO_ATTRBIT(&attrbits))) {
2142                                         r = nfsvno_getfh(nvp, &nfh, p);
2143                                         if (!r)
2144                                             r = nfsvno_getattr(nvp, nvap,
2145                                                 nd->nd_cred, p, 1);
2146                                         if (r == 0 && not_zfs == 0 &&
2147                                             nfsrv_enable_crossmntpt != 0 &&
2148                                             (nd->nd_flag & ND_NFSV4) != 0 &&
2149                                             nvp->v_type == VDIR &&
2150                                             vp->v_mount != nvp->v_mount) {
2151                                             /*
2152                                              * For a ZFS snapshot, there is a
2153                                              * pseudo mount that does not set
2154                                              * v_mountedhere, so it needs to
2155                                              * be detected via a different
2156                                              * mount structure.
2157                                              */
2158                                             at_root = 1;
2159                                             if (new_mp == mp)
2160                                                 new_mp = nvp->v_mount;
2161                                         }
2162                                     }
2163                                 } else {
2164                                     nvp = NULL;
2165                                 }
2166                                 if (r) {
2167                                         if (!NFSISSET_ATTRBIT(&attrbits,
2168                                             NFSATTRBIT_RDATTRERROR)) {
2169                                                 if (nvp != NULL)
2170                                                         vput(nvp);
2171                                                 if (needs_unbusy != 0)
2172                                                         vfs_unbusy(new_mp);
2173                                                 nd->nd_repstat = r;
2174                                                 break;
2175                                         }
2176                                 }
2177                         }
2178
2179                         /*
2180                          * Build the directory record xdr
2181                          */
2182                         if (nd->nd_flag & ND_NFSV3) {
2183                                 NFSM_BUILD(tl, u_int32_t *, 3 * NFSX_UNSIGNED);
2184                                 *tl++ = newnfs_true;
2185                                 *tl++ = 0;
2186                                 *tl = txdr_unsigned(dp->d_fileno);
2187                                 dirlen += nfsm_strtom(nd, dp->d_name, nlen);
2188                                 NFSM_BUILD(tl, u_int32_t *, 2 * NFSX_UNSIGNED);
2189                                 *tl++ = 0;
2190                                 *tl = txdr_unsigned(*cookiep);
2191                                 nfsrv_postopattr(nd, 0, nvap);
2192                                 dirlen += nfsm_fhtom(nd,(u_int8_t *)&nfh,0,1);
2193                                 dirlen += (5*NFSX_UNSIGNED+NFSX_V3POSTOPATTR);
2194                                 if (nvp != NULL)
2195                                         vput(nvp);
2196                         } else {
2197                                 NFSM_BUILD(tl, u_int32_t *, 3 * NFSX_UNSIGNED);
2198                                 *tl++ = newnfs_true;
2199                                 *tl++ = 0;
2200                                 *tl = txdr_unsigned(*cookiep);
2201                                 dirlen += nfsm_strtom(nd, dp->d_name, nlen);
2202                                 if (nvp != NULL) {
2203                                         supports_nfsv4acls =
2204                                             nfs_supportsnfsv4acls(nvp);
2205                                         NFSVOPUNLOCK(nvp, 0);
2206                                 } else
2207                                         supports_nfsv4acls = 0;
2208                                 if (refp != NULL) {
2209                                         dirlen += nfsrv_putreferralattr(nd,
2210                                             &savbits, refp, 0,
2211                                             &nd->nd_repstat);
2212                                         if (nd->nd_repstat) {
2213                                                 if (nvp != NULL)
2214                                                         vrele(nvp);
2215                                                 if (needs_unbusy != 0)
2216                                                         vfs_unbusy(new_mp);
2217                                                 break;
2218                                         }
2219                                 } else if (r) {
2220                                         dirlen += nfsvno_fillattr(nd, new_mp,
2221                                             nvp, nvap, &nfh, r, &rderrbits,
2222                                             nd->nd_cred, p, isdgram, 0,
2223                                             supports_nfsv4acls, at_root,
2224                                             mounted_on_fileno);
2225                                 } else {
2226                                         dirlen += nfsvno_fillattr(nd, new_mp,
2227                                             nvp, nvap, &nfh, r, &attrbits,
2228                                             nd->nd_cred, p, isdgram, 0,
2229                                             supports_nfsv4acls, at_root,
2230                                             mounted_on_fileno);
2231                                 }
2232                                 if (nvp != NULL)
2233                                         vrele(nvp);
2234                                 dirlen += (3 * NFSX_UNSIGNED);
2235                         }
2236                         if (needs_unbusy != 0)
2237                                 vfs_unbusy(new_mp);
2238                         if (dirlen <= cnt)
2239                                 entrycnt++;
2240                 }
2241                 cpos += dp->d_reclen;
2242                 dp = (struct dirent *)cpos;
2243                 cookiep++;
2244                 ncookies--;
2245         }
2246         vrele(vp);
2247         vfs_unbusy(mp);
2248
2249         /*
2250          * If dirlen > cnt, we must strip off the last entry. If that
2251          * results in an empty reply, report NFSERR_TOOSMALL.
2252          */
2253         if (dirlen > cnt || nd->nd_repstat) {
2254                 if (!nd->nd_repstat && entrycnt == 0)
2255                         nd->nd_repstat = NFSERR_TOOSMALL;
2256                 if (nd->nd_repstat)
2257                         newnfs_trimtrailing(nd, mb0, bpos0);
2258                 else
2259                         newnfs_trimtrailing(nd, mb1, bpos1);
2260                 eofflag = 0;
2261         } else if (cpos < cend)
2262                 eofflag = 0;
2263         if (!nd->nd_repstat) {
2264                 NFSM_BUILD(tl, u_int32_t *, 2 * NFSX_UNSIGNED);
2265                 *tl++ = newnfs_false;
2266                 if (eofflag)
2267                         *tl = newnfs_true;
2268                 else
2269                         *tl = newnfs_false;
2270         }
2271         FREE((caddr_t)cookies, M_TEMP);
2272         FREE((caddr_t)rbuf, M_TEMP);
2273
2274 out:
2275         NFSEXITCODE2(0, nd);
2276         return (0);
2277 nfsmout:
2278         vput(vp);
2279         NFSEXITCODE2(error, nd);
2280         return (error);
2281 }
2282
2283 /*
2284  * Get the settable attributes out of the mbuf list.
2285  * (Return 0 or EBADRPC)
2286  */
2287 int
2288 nfsrv_sattr(struct nfsrv_descript *nd, struct nfsvattr *nvap,
2289     nfsattrbit_t *attrbitp, NFSACL_T *aclp, struct thread *p)
2290 {
2291         u_int32_t *tl;
2292         struct nfsv2_sattr *sp;
2293         int error = 0, toclient = 0;
2294
2295         switch (nd->nd_flag & (ND_NFSV2 | ND_NFSV3 | ND_NFSV4)) {
2296         case ND_NFSV2:
2297                 NFSM_DISSECT(sp, struct nfsv2_sattr *, NFSX_V2SATTR);
2298                 /*
2299                  * Some old clients didn't fill in the high order 16bits.
2300                  * --> check the low order 2 bytes for 0xffff
2301                  */
2302                 if ((fxdr_unsigned(int, sp->sa_mode) & 0xffff) != 0xffff)
2303                         nvap->na_mode = nfstov_mode(sp->sa_mode);
2304                 if (sp->sa_uid != newnfs_xdrneg1)
2305                         nvap->na_uid = fxdr_unsigned(uid_t, sp->sa_uid);
2306                 if (sp->sa_gid != newnfs_xdrneg1)
2307                         nvap->na_gid = fxdr_unsigned(gid_t, sp->sa_gid);
2308                 if (sp->sa_size != newnfs_xdrneg1)
2309                         nvap->na_size = fxdr_unsigned(u_quad_t, sp->sa_size);
2310                 if (sp->sa_atime.nfsv2_sec != newnfs_xdrneg1) {
2311 #ifdef notyet
2312                         fxdr_nfsv2time(&sp->sa_atime, &nvap->na_atime);
2313 #else
2314                         nvap->na_atime.tv_sec =
2315                                 fxdr_unsigned(u_int32_t,sp->sa_atime.nfsv2_sec);
2316                         nvap->na_atime.tv_nsec = 0;
2317 #endif
2318                 }
2319                 if (sp->sa_mtime.nfsv2_sec != newnfs_xdrneg1)
2320                         fxdr_nfsv2time(&sp->sa_mtime, &nvap->na_mtime);
2321                 break;
2322         case ND_NFSV3:
2323                 NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
2324                 if (*tl == newnfs_true) {
2325                         NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
2326                         nvap->na_mode = nfstov_mode(*tl);
2327                 }
2328                 NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
2329                 if (*tl == newnfs_true) {
2330                         NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
2331                         nvap->na_uid = fxdr_unsigned(uid_t, *tl);
2332                 }
2333                 NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
2334                 if (*tl == newnfs_true) {
2335                         NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
2336                         nvap->na_gid = fxdr_unsigned(gid_t, *tl);
2337                 }
2338                 NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
2339                 if (*tl == newnfs_true) {
2340                         NFSM_DISSECT(tl, u_int32_t *, 2 * NFSX_UNSIGNED);
2341                         nvap->na_size = fxdr_hyper(tl);
2342                 }
2343                 NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
2344                 switch (fxdr_unsigned(int, *tl)) {
2345                 case NFSV3SATTRTIME_TOCLIENT:
2346                         NFSM_DISSECT(tl, u_int32_t *, 2 * NFSX_UNSIGNED);
2347                         fxdr_nfsv3time(tl, &nvap->na_atime);
2348                         toclient = 1;
2349                         break;
2350                 case NFSV3SATTRTIME_TOSERVER:
2351                         vfs_timestamp(&nvap->na_atime);
2352                         nvap->na_vaflags |= VA_UTIMES_NULL;
2353                         break;
2354                 };
2355                 NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
2356                 switch (fxdr_unsigned(int, *tl)) {
2357                 case NFSV3SATTRTIME_TOCLIENT:
2358                         NFSM_DISSECT(tl, u_int32_t *, 2 * NFSX_UNSIGNED);
2359                         fxdr_nfsv3time(tl, &nvap->na_mtime);
2360                         nvap->na_vaflags &= ~VA_UTIMES_NULL;
2361                         break;
2362                 case NFSV3SATTRTIME_TOSERVER:
2363                         vfs_timestamp(&nvap->na_mtime);
2364                         if (!toclient)
2365                                 nvap->na_vaflags |= VA_UTIMES_NULL;
2366                         break;
2367                 };
2368                 break;
2369         case ND_NFSV4:
2370                 error = nfsv4_sattr(nd, nvap, attrbitp, aclp, p);
2371         };
2372 nfsmout:
2373         NFSEXITCODE2(error, nd);
2374         return (error);
2375 }
2376
2377 /*
2378  * Handle the setable attributes for V4.
2379  * Returns NFSERR_BADXDR if it can't be parsed, 0 otherwise.
2380  */
2381 int
2382 nfsv4_sattr(struct nfsrv_descript *nd, struct nfsvattr *nvap,
2383     nfsattrbit_t *attrbitp, NFSACL_T *aclp, struct thread *p)
2384 {
2385         u_int32_t *tl;
2386         int attrsum = 0;
2387         int i, j;
2388         int error, attrsize, bitpos, aclsize, aceerr, retnotsup = 0;
2389         int toclient = 0;
2390         u_char *cp, namestr[NFSV4_SMALLSTR + 1];
2391         uid_t uid;
2392         gid_t gid;
2393
2394         error = nfsrv_getattrbits(nd, attrbitp, NULL, &retnotsup);
2395         if (error)
2396                 goto nfsmout;
2397         NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
2398         attrsize = fxdr_unsigned(int, *tl);
2399
2400         /*
2401          * Loop around getting the setable attributes. If an unsupported
2402          * one is found, set nd_repstat == NFSERR_ATTRNOTSUPP and return.
2403          */
2404         if (retnotsup) {
2405                 nd->nd_repstat = NFSERR_ATTRNOTSUPP;
2406                 bitpos = NFSATTRBIT_MAX;
2407         } else {
2408                 bitpos = 0;
2409         }
2410         for (; bitpos < NFSATTRBIT_MAX; bitpos++) {
2411             if (attrsum > attrsize) {
2412                 error = NFSERR_BADXDR;
2413                 goto nfsmout;
2414             }
2415             if (NFSISSET_ATTRBIT(attrbitp, bitpos))
2416                 switch (bitpos) {
2417                 case NFSATTRBIT_SIZE:
2418                         NFSM_DISSECT(tl, u_int32_t *, NFSX_HYPER);
2419                         nvap->na_size = fxdr_hyper(tl);
2420                         attrsum += NFSX_HYPER;
2421                         break;
2422                 case NFSATTRBIT_ACL:
2423                         error = nfsrv_dissectacl(nd, aclp, &aceerr, &aclsize,
2424                             p);
2425                         if (error)
2426                                 goto nfsmout;
2427                         if (aceerr && !nd->nd_repstat)
2428                                 nd->nd_repstat = aceerr;
2429                         attrsum += aclsize;
2430                         break;
2431                 case NFSATTRBIT_ARCHIVE:
2432                         NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
2433                         if (!nd->nd_repstat)
2434                                 nd->nd_repstat = NFSERR_ATTRNOTSUPP;
2435                         attrsum += NFSX_UNSIGNED;
2436                         break;
2437                 case NFSATTRBIT_HIDDEN:
2438                         NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
2439                         if (!nd->nd_repstat)
2440                                 nd->nd_repstat = NFSERR_ATTRNOTSUPP;
2441                         attrsum += NFSX_UNSIGNED;
2442                         break;
2443                 case NFSATTRBIT_MIMETYPE:
2444                         NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
2445                         i = fxdr_unsigned(int, *tl);
2446                         error = nfsm_advance(nd, NFSM_RNDUP(i), -1);
2447                         if (error)
2448                                 goto nfsmout;
2449                         if (!nd->nd_repstat)
2450                                 nd->nd_repstat = NFSERR_ATTRNOTSUPP;
2451                         attrsum += (NFSX_UNSIGNED + NFSM_RNDUP(i));
2452                         break;
2453                 case NFSATTRBIT_MODE:
2454                         NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
2455                         nvap->na_mode = nfstov_mode(*tl);
2456                         attrsum += NFSX_UNSIGNED;
2457                         break;
2458                 case NFSATTRBIT_OWNER:
2459                         NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
2460                         j = fxdr_unsigned(int, *tl);
2461                         if (j < 0) {
2462                                 error = NFSERR_BADXDR;
2463                                 goto nfsmout;
2464                         }
2465                         if (j > NFSV4_SMALLSTR)
2466                                 cp = malloc(j + 1, M_NFSSTRING, M_WAITOK);
2467                         else
2468                                 cp = namestr;
2469                         error = nfsrv_mtostr(nd, cp, j);
2470                         if (error) {
2471                                 if (j > NFSV4_SMALLSTR)
2472                                         free(cp, M_NFSSTRING);
2473                                 goto nfsmout;
2474                         }
2475                         if (!nd->nd_repstat) {
2476                                 nd->nd_repstat = nfsv4_strtouid(nd, cp, j, &uid,
2477                                     p);
2478                                 if (!nd->nd_repstat)
2479                                         nvap->na_uid = uid;
2480                         }
2481                         if (j > NFSV4_SMALLSTR)
2482                                 free(cp, M_NFSSTRING);
2483                         attrsum += (NFSX_UNSIGNED + NFSM_RNDUP(j));
2484                         break;
2485                 case NFSATTRBIT_OWNERGROUP:
2486                         NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
2487                         j = fxdr_unsigned(int, *tl);
2488                         if (j < 0) {
2489                                 error = NFSERR_BADXDR;
2490                                 goto nfsmout;
2491                         }
2492                         if (j > NFSV4_SMALLSTR)
2493                                 cp = malloc(j + 1, M_NFSSTRING, M_WAITOK);
2494                         else
2495                                 cp = namestr;
2496                         error = nfsrv_mtostr(nd, cp, j);
2497                         if (error) {
2498                                 if (j > NFSV4_SMALLSTR)
2499                                         free(cp, M_NFSSTRING);
2500                                 goto nfsmout;
2501                         }
2502                         if (!nd->nd_repstat) {
2503                                 nd->nd_repstat = nfsv4_strtogid(nd, cp, j, &gid,
2504                                     p);
2505                                 if (!nd->nd_repstat)
2506                                         nvap->na_gid = gid;
2507                         }
2508                         if (j > NFSV4_SMALLSTR)
2509                                 free(cp, M_NFSSTRING);
2510                         attrsum += (NFSX_UNSIGNED + NFSM_RNDUP(j));
2511                         break;
2512                 case NFSATTRBIT_SYSTEM:
2513                         NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
2514                         if (!nd->nd_repstat)
2515                                 nd->nd_repstat = NFSERR_ATTRNOTSUPP;
2516                         attrsum += NFSX_UNSIGNED;
2517                         break;
2518                 case NFSATTRBIT_TIMEACCESSSET:
2519                         NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
2520                         attrsum += NFSX_UNSIGNED;
2521                         if (fxdr_unsigned(int, *tl)==NFSV4SATTRTIME_TOCLIENT) {
2522                             NFSM_DISSECT(tl, u_int32_t *, NFSX_V4TIME);
2523                             fxdr_nfsv4time(tl, &nvap->na_atime);
2524                             toclient = 1;
2525                             attrsum += NFSX_V4TIME;
2526                         } else {
2527                             vfs_timestamp(&nvap->na_atime);
2528                             nvap->na_vaflags |= VA_UTIMES_NULL;
2529                         }
2530                         break;
2531                 case NFSATTRBIT_TIMEBACKUP:
2532                         NFSM_DISSECT(tl, u_int32_t *, NFSX_V4TIME);
2533                         if (!nd->nd_repstat)
2534                                 nd->nd_repstat = NFSERR_ATTRNOTSUPP;
2535                         attrsum += NFSX_V4TIME;
2536                         break;
2537                 case NFSATTRBIT_TIMECREATE:
2538                         NFSM_DISSECT(tl, u_int32_t *, NFSX_V4TIME);
2539                         if (!nd->nd_repstat)
2540                                 nd->nd_repstat = NFSERR_ATTRNOTSUPP;
2541                         attrsum += NFSX_V4TIME;
2542                         break;
2543                 case NFSATTRBIT_TIMEMODIFYSET:
2544                         NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
2545                         attrsum += NFSX_UNSIGNED;
2546                         if (fxdr_unsigned(int, *tl)==NFSV4SATTRTIME_TOCLIENT) {
2547                             NFSM_DISSECT(tl, u_int32_t *, NFSX_V4TIME);
2548                             fxdr_nfsv4time(tl, &nvap->na_mtime);
2549                             nvap->na_vaflags &= ~VA_UTIMES_NULL;
2550                             attrsum += NFSX_V4TIME;
2551                         } else {
2552                             vfs_timestamp(&nvap->na_mtime);
2553                             if (!toclient)
2554                                 nvap->na_vaflags |= VA_UTIMES_NULL;
2555                         }
2556                         break;
2557                 default:
2558                         nd->nd_repstat = NFSERR_ATTRNOTSUPP;
2559                         /*
2560                          * set bitpos so we drop out of the loop.
2561                          */
2562                         bitpos = NFSATTRBIT_MAX;
2563                         break;
2564                 };
2565         }
2566
2567         /*
2568          * some clients pad the attrlist, so we need to skip over the
2569          * padding.
2570          */
2571         if (attrsum > attrsize) {
2572                 error = NFSERR_BADXDR;
2573         } else {
2574                 attrsize = NFSM_RNDUP(attrsize);
2575                 if (attrsum < attrsize)
2576                         error = nfsm_advance(nd, attrsize - attrsum, -1);
2577         }
2578 nfsmout:
2579         NFSEXITCODE2(error, nd);
2580         return (error);
2581 }
2582
2583 /*
2584  * Check/setup export credentials.
2585  */
2586 int
2587 nfsd_excred(struct nfsrv_descript *nd, struct nfsexstuff *exp,
2588     struct ucred *credanon)
2589 {
2590         int error = 0;
2591
2592         /*
2593          * Check/setup credentials.
2594          */
2595         if (nd->nd_flag & ND_GSS)
2596                 exp->nes_exflag &= ~MNT_EXPORTANON;
2597
2598         /*
2599          * Check to see if the operation is allowed for this security flavor.
2600          * RFC2623 suggests that the NFSv3 Fsinfo RPC be allowed to
2601          * AUTH_NONE or AUTH_SYS for file systems requiring RPCSEC_GSS.
2602          * Also, allow Secinfo, so that it can acquire the correct flavor(s).
2603          */
2604         if (nfsvno_testexp(nd, exp) &&
2605             nd->nd_procnum != NFSV4OP_SECINFO &&
2606             nd->nd_procnum != NFSPROC_FSINFO) {
2607                 if (nd->nd_flag & ND_NFSV4)
2608                         error = NFSERR_WRONGSEC;
2609                 else
2610                         error = (NFSERR_AUTHERR | AUTH_TOOWEAK);
2611                 goto out;
2612         }
2613
2614         /*
2615          * Check to see if the file system is exported V4 only.
2616          */
2617         if (NFSVNO_EXV4ONLY(exp) && !(nd->nd_flag & ND_NFSV4)) {
2618                 error = NFSERR_PROGNOTV4;
2619                 goto out;
2620         }
2621
2622         /*
2623          * Now, map the user credentials.
2624          * (Note that ND_AUTHNONE will only be set for an NFSv3
2625          *  Fsinfo RPC. If set for anything else, this code might need
2626          *  to change.)
2627          */
2628         if (NFSVNO_EXPORTED(exp) &&
2629             ((!(nd->nd_flag & ND_GSS) && nd->nd_cred->cr_uid == 0) ||
2630              NFSVNO_EXPORTANON(exp) ||
2631              (nd->nd_flag & ND_AUTHNONE))) {
2632                 nd->nd_cred->cr_uid = credanon->cr_uid;
2633                 nd->nd_cred->cr_gid = credanon->cr_gid;
2634                 crsetgroups(nd->nd_cred, credanon->cr_ngroups,
2635                     credanon->cr_groups);
2636         }
2637
2638 out:
2639         NFSEXITCODE2(error, nd);
2640         return (error);
2641 }
2642
2643 /*
2644  * Check exports.
2645  */
2646 int
2647 nfsvno_checkexp(struct mount *mp, struct sockaddr *nam, struct nfsexstuff *exp,
2648     struct ucred **credp)
2649 {
2650         int i, error, *secflavors;
2651
2652         error = VFS_CHECKEXP(mp, nam, &exp->nes_exflag, credp,
2653             &exp->nes_numsecflavor, &secflavors);
2654         if (error) {
2655                 if (nfs_rootfhset) {
2656                         exp->nes_exflag = 0;
2657                         exp->nes_numsecflavor = 0;
2658                         error = 0;
2659                 }
2660         } else {
2661                 /* Copy the security flavors. */
2662                 for (i = 0; i < exp->nes_numsecflavor; i++)
2663                         exp->nes_secflavors[i] = secflavors[i];
2664         }
2665         NFSEXITCODE(error);
2666         return (error);
2667 }
2668
2669 /*
2670  * Get a vnode for a file handle and export stuff.
2671  */
2672 int
2673 nfsvno_fhtovp(struct mount *mp, fhandle_t *fhp, struct sockaddr *nam,
2674     int lktype, struct vnode **vpp, struct nfsexstuff *exp,
2675     struct ucred **credp)
2676 {
2677         int i, error, *secflavors;
2678
2679         *credp = NULL;
2680         exp->nes_numsecflavor = 0;
2681         if (VFS_NEEDSGIANT(mp))
2682                 error = ESTALE;
2683         else
2684                 error = VFS_FHTOVP(mp, &fhp->fh_fid, LK_EXCLUSIVE, vpp);
2685         if (error != 0)
2686                 /* Make sure the server replies ESTALE to the client. */
2687                 error = ESTALE;
2688         if (nam && !error) {
2689                 error = VFS_CHECKEXP(mp, nam, &exp->nes_exflag, credp,
2690                     &exp->nes_numsecflavor, &secflavors);
2691                 if (error) {
2692                         if (nfs_rootfhset) {
2693                                 exp->nes_exflag = 0;
2694                                 exp->nes_numsecflavor = 0;
2695                                 error = 0;
2696                         } else {
2697                                 vput(*vpp);
2698                         }
2699                 } else {
2700                         /* Copy the security flavors. */
2701                         for (i = 0; i < exp->nes_numsecflavor; i++)
2702                                 exp->nes_secflavors[i] = secflavors[i];
2703                 }
2704         }
2705         if (error == 0 && lktype == LK_SHARED)
2706                 /*
2707                  * It would be much better to pass lktype to VFS_FHTOVP(),
2708                  * but this will have to do until VFS_FHTOVP() has a lock
2709                  * type argument like VFS_VGET().
2710                  */
2711                 NFSVOPLOCK(*vpp, LK_DOWNGRADE | LK_RETRY);
2712
2713         NFSEXITCODE(error);
2714         return (error);
2715 }
2716
2717 /*
2718  * nfsd_fhtovp() - convert a fh to a vnode ptr
2719  *      - look up fsid in mount list (if not found ret error)
2720  *      - get vp and export rights by calling nfsvno_fhtovp()
2721  *      - if cred->cr_uid == 0 or MNT_EXPORTANON set it to credanon
2722  *        for AUTH_SYS
2723  *      - if mpp != NULL, return the mount point so that it can
2724  *        be used for vn_finished_write() by the caller
2725  */
2726 void
2727 nfsd_fhtovp(struct nfsrv_descript *nd, struct nfsrvfh *nfp, int lktype,
2728     struct vnode **vpp, struct nfsexstuff *exp,
2729     struct mount **mpp, int startwrite, struct thread *p)
2730 {
2731         struct mount *mp;
2732         struct ucred *credanon;
2733         fhandle_t *fhp;
2734
2735         fhp = (fhandle_t *)nfp->nfsrvfh_data;
2736         /*
2737          * Check for the special case of the nfsv4root_fh.
2738          */
2739         mp = vfs_busyfs(&fhp->fh_fsid);
2740         if (mpp != NULL)
2741                 *mpp = mp;
2742         if (mp == NULL) {
2743                 *vpp = NULL;
2744                 nd->nd_repstat = ESTALE;
2745                 goto out;
2746         }
2747
2748         if (startwrite) {
2749                 vn_start_write(NULL, mpp, V_WAIT);
2750                 if (lktype == LK_SHARED && !(MNT_SHARED_WRITES(mp)))
2751                         lktype = LK_EXCLUSIVE;
2752         }
2753         nd->nd_repstat = nfsvno_fhtovp(mp, fhp, nd->nd_nam, lktype, vpp, exp,
2754             &credanon);
2755         vfs_unbusy(mp);
2756
2757         /*
2758          * For NFSv4 without a pseudo root fs, unexported file handles
2759          * can be returned, so that Lookup works everywhere.
2760          */
2761         if (!nd->nd_repstat && exp->nes_exflag == 0 &&
2762             !(nd->nd_flag & ND_NFSV4)) {
2763                 vput(*vpp);
2764                 nd->nd_repstat = EACCES;
2765         }
2766
2767         /*
2768          * Personally, I've never seen any point in requiring a
2769          * reserved port#, since only in the rare case where the
2770          * clients are all boxes with secure system priviledges,
2771          * does it provide any enhanced security, but... some people
2772          * believe it to be useful and keep putting this code back in.
2773          * (There is also some "security checker" out there that
2774          *  complains if the nfs server doesn't enforce this.)
2775          * However, note the following:
2776          * RFC3530 (NFSv4) specifies that a reserved port# not be
2777          *      required.
2778          * RFC2623 recommends that, if a reserved port# is checked for,
2779          *      that there be a way to turn that off--> ifdef'd.
2780          */
2781 #ifdef NFS_REQRSVPORT
2782         if (!nd->nd_repstat) {
2783                 struct sockaddr_in *saddr;
2784                 struct sockaddr_in6 *saddr6;
2785
2786                 saddr = NFSSOCKADDR(nd->nd_nam, struct sockaddr_in *);
2787                 saddr6 = NFSSOCKADDR(nd->nd_nam, struct sockaddr_in6 *);
2788                 if (!(nd->nd_flag & ND_NFSV4) &&
2789                     ((saddr->sin_family == AF_INET &&
2790                       ntohs(saddr->sin_port) >= IPPORT_RESERVED) ||
2791                      (saddr6->sin6_family == AF_INET6 &&
2792                       ntohs(saddr6->sin6_port) >= IPPORT_RESERVED))) {
2793                         vput(*vpp);
2794                         nd->nd_repstat = (NFSERR_AUTHERR | AUTH_TOOWEAK);
2795                 }
2796         }
2797 #endif  /* NFS_REQRSVPORT */
2798
2799         /*
2800          * Check/setup credentials.
2801          */
2802         if (!nd->nd_repstat) {
2803                 nd->nd_saveduid = nd->nd_cred->cr_uid;
2804                 nd->nd_repstat = nfsd_excred(nd, exp, credanon);
2805                 if (nd->nd_repstat)
2806                         vput(*vpp);
2807         }
2808         if (credanon != NULL)
2809                 crfree(credanon);
2810         if (nd->nd_repstat) {
2811                 if (startwrite)
2812                         vn_finished_write(mp);
2813                 *vpp = NULL;
2814                 if (mpp != NULL)
2815                         *mpp = NULL;
2816         }
2817
2818 out:
2819         NFSEXITCODE2(0, nd);
2820 }
2821
2822 /*
2823  * glue for fp.
2824  */
2825 int
2826 fp_getfvp(struct thread *p, int fd, struct file **fpp, struct vnode **vpp)
2827 {
2828         struct filedesc *fdp;
2829         struct file *fp;
2830         int error = 0;
2831
2832         fdp = p->td_proc->p_fd;
2833         if (fd >= fdp->fd_nfiles ||
2834             (fp = fdp->fd_ofiles[fd]) == NULL) {
2835                 error = EBADF;
2836                 goto out;
2837         }
2838         *fpp = fp;
2839
2840 out:
2841         NFSEXITCODE(error);
2842         return (error);
2843 }
2844
2845 /*
2846  * Called from nfssvc() to update the exports list. Just call
2847  * vfs_export(). This has to be done, since the v4 root fake fs isn't
2848  * in the mount list.
2849  */
2850 int
2851 nfsrv_v4rootexport(void *argp, struct ucred *cred, struct thread *p)
2852 {
2853         struct nfsex_args *nfsexargp = (struct nfsex_args *)argp;
2854         int error = 0;
2855         struct nameidata nd;
2856         fhandle_t fh;
2857
2858         error = vfs_export(&nfsv4root_mnt, &nfsexargp->export);
2859         if ((nfsexargp->export.ex_flags & MNT_DELEXPORT) != 0)
2860                 nfs_rootfhset = 0;
2861         else if (error == 0) {
2862                 if (nfsexargp->fspec == NULL) {
2863                         error = EPERM;
2864                         goto out;
2865                 }
2866                 /*
2867                  * If fspec != NULL, this is the v4root path.
2868                  */
2869                 NDINIT(&nd, LOOKUP, FOLLOW | MPSAFE, UIO_USERSPACE,
2870                     nfsexargp->fspec, p);
2871                 if ((error = namei(&nd)) != 0)
2872                         goto out;
2873                 error = nfsvno_getfh(nd.ni_vp, &fh, p);
2874                 vrele(nd.ni_vp);
2875                 if (!error) {
2876                         nfs_rootfh.nfsrvfh_len = NFSX_MYFH;
2877                         NFSBCOPY((caddr_t)&fh,
2878                             nfs_rootfh.nfsrvfh_data,
2879                             sizeof (fhandle_t));
2880                         nfs_rootfhset = 1;
2881                 }
2882         }
2883
2884 out:
2885         NFSEXITCODE(error);
2886         return (error);
2887 }
2888
2889 /*
2890  * Get the tcp socket sequence numbers we need.
2891  * (Maybe this should be moved to the tcp sources?)
2892  */
2893 int
2894 nfsrv_getsocksndseq(struct socket *so, tcp_seq *maxp, tcp_seq *unap)
2895 {
2896         struct inpcb *inp;
2897         struct tcpcb *tp;
2898         int error = 0;
2899
2900         inp = sotoinpcb(so);
2901         KASSERT(inp != NULL, ("nfsrv_getsocksndseq: inp == NULL"));
2902         INP_RLOCK(inp);
2903         if (inp->inp_flags & (INP_TIMEWAIT | INP_DROPPED)) {
2904                 INP_RUNLOCK(inp);
2905                 error = EPIPE;
2906                 goto out;
2907         }
2908         tp = intotcpcb(inp);
2909         if (tp->t_state != TCPS_ESTABLISHED) {
2910                 INP_RUNLOCK(inp);
2911                 error = EPIPE;
2912                 goto out;
2913         }
2914         *maxp = tp->snd_max;
2915         *unap = tp->snd_una;
2916         INP_RUNLOCK(inp);
2917
2918 out:
2919         NFSEXITCODE(error);
2920         return (error);
2921 }
2922
2923 /*
2924  * This function needs to test to see if the system is near its limit
2925  * for memory allocation via malloc() or mget() and return True iff
2926  * either of these resources are near their limit.
2927  * XXX (For now, this is just a stub.)
2928  */
2929 int nfsrv_testmalloclimit = 0;
2930 int
2931 nfsrv_mallocmget_limit(void)
2932 {
2933         static int printmesg = 0;
2934         static int testval = 1;
2935
2936         if (nfsrv_testmalloclimit && (testval++ % 1000) == 0) {
2937                 if ((printmesg++ % 100) == 0)
2938                         printf("nfsd: malloc/mget near limit\n");
2939                 return (1);
2940         }
2941         return (0);
2942 }
2943
2944 /*
2945  * BSD specific initialization of a mount point.
2946  */
2947 void
2948 nfsd_mntinit(void)
2949 {
2950         static int inited = 0;
2951
2952         if (inited)
2953                 return;
2954         inited = 1;
2955         nfsv4root_mnt.mnt_flag = (MNT_RDONLY | MNT_EXPORTED);
2956         TAILQ_INIT(&nfsv4root_mnt.mnt_nvnodelist);
2957         TAILQ_INIT(&nfsv4root_mnt.mnt_activevnodelist);
2958         nfsv4root_mnt.mnt_export = NULL;
2959         TAILQ_INIT(&nfsv4root_opt);
2960         TAILQ_INIT(&nfsv4root_newopt);
2961         nfsv4root_mnt.mnt_opt = &nfsv4root_opt;
2962         nfsv4root_mnt.mnt_optnew = &nfsv4root_newopt;
2963         nfsv4root_mnt.mnt_nvnodelistsize = 0;
2964         nfsv4root_mnt.mnt_activevnodelistsize = 0;
2965 }
2966
2967 /*
2968  * Get a vnode for a file handle, without checking exports, etc.
2969  */
2970 struct vnode *
2971 nfsvno_getvp(fhandle_t *fhp)
2972 {
2973         struct mount *mp;
2974         struct vnode *vp;
2975         int error;
2976
2977         mp = vfs_busyfs(&fhp->fh_fsid);
2978         if (mp == NULL)
2979                 return (NULL);
2980         error = VFS_FHTOVP(mp, &fhp->fh_fid, LK_EXCLUSIVE, &vp);
2981         vfs_unbusy(mp);
2982         if (error)
2983                 return (NULL);
2984         return (vp);
2985 }
2986
2987 /*
2988  * Do a local VOP_ADVLOCK().
2989  */
2990 int
2991 nfsvno_advlock(struct vnode *vp, int ftype, u_int64_t first,
2992     u_int64_t end, struct thread *td)
2993 {
2994         int error = 0;
2995         struct flock fl;
2996         u_int64_t tlen;
2997
2998         if (nfsrv_dolocallocks == 0)
2999                 goto out;
3000
3001         /* Check for VI_DOOMED here, so that VOP_ADVLOCK() isn't performed. */
3002         if ((vp->v_iflag & VI_DOOMED) != 0) {
3003                 error = EPERM;
3004                 goto out;
3005         }
3006
3007         fl.l_whence = SEEK_SET;
3008         fl.l_type = ftype;
3009         fl.l_start = (off_t)first;
3010         if (end == NFS64BITSSET) {
3011                 fl.l_len = 0;
3012         } else {
3013                 tlen = end - first;
3014                 fl.l_len = (off_t)tlen;
3015         }
3016         /*
3017          * For FreeBSD8, the l_pid and l_sysid must be set to the same
3018          * values for all calls, so that all locks will be held by the
3019          * nfsd server. (The nfsd server handles conflicts between the
3020          * various clients.)
3021          * Since an NFSv4 lockowner is a ClientID plus an array of up to 1024
3022          * bytes, so it can't be put in l_sysid.
3023          */
3024         if (nfsv4_sysid == 0)
3025                 nfsv4_sysid = nlm_acquire_next_sysid();
3026         fl.l_pid = (pid_t)0;
3027         fl.l_sysid = (int)nfsv4_sysid;
3028
3029         NFSVOPUNLOCK(vp, 0);
3030         if (ftype == F_UNLCK)
3031                 error = VOP_ADVLOCK(vp, (caddr_t)td->td_proc, F_UNLCK, &fl,
3032                     (F_POSIX | F_REMOTE));
3033         else
3034                 error = VOP_ADVLOCK(vp, (caddr_t)td->td_proc, F_SETLK, &fl,
3035                     (F_POSIX | F_REMOTE));
3036         NFSVOPLOCK(vp, LK_EXCLUSIVE | LK_RETRY);
3037
3038 out:
3039         NFSEXITCODE(error);
3040         return (error);
3041 }
3042
3043 /*
3044  * Check the nfsv4 root exports.
3045  */
3046 int
3047 nfsvno_v4rootexport(struct nfsrv_descript *nd)
3048 {
3049         struct ucred *credanon;
3050         int exflags, error = 0, numsecflavor, *secflavors, i;
3051
3052         error = vfs_stdcheckexp(&nfsv4root_mnt, nd->nd_nam, &exflags,
3053             &credanon, &numsecflavor, &secflavors);
3054         if (error) {
3055                 error = NFSERR_PROGUNAVAIL;
3056                 goto out;
3057         }
3058         if (credanon != NULL)
3059                 crfree(credanon);
3060         for (i = 0; i < numsecflavor; i++) {
3061                 if (secflavors[i] == AUTH_SYS)
3062                         nd->nd_flag |= ND_EXAUTHSYS;
3063                 else if (secflavors[i] == RPCSEC_GSS_KRB5)
3064                         nd->nd_flag |= ND_EXGSS;
3065                 else if (secflavors[i] == RPCSEC_GSS_KRB5I)
3066                         nd->nd_flag |= ND_EXGSSINTEGRITY;
3067                 else if (secflavors[i] == RPCSEC_GSS_KRB5P)
3068                         nd->nd_flag |= ND_EXGSSPRIVACY;
3069         }
3070
3071 out:
3072         NFSEXITCODE(error);
3073         return (error);
3074 }
3075
3076 /*
3077  * Nfs server psuedo system call for the nfsd's
3078  */
3079 /*
3080  * MPSAFE
3081  */
3082 static int
3083 nfssvc_nfsd(struct thread *td, struct nfssvc_args *uap)
3084 {
3085         struct file *fp;
3086         struct nfsd_addsock_args sockarg;
3087         struct nfsd_nfsd_args nfsdarg;
3088         int error;
3089
3090         if (uap->flag & NFSSVC_NFSDADDSOCK) {
3091                 error = copyin(uap->argp, (caddr_t)&sockarg, sizeof (sockarg));
3092                 if (error)
3093                         goto out;
3094                 /*
3095                  * Since we don't know what rights might be required,
3096                  * pretend that we need them all. It is better to be too
3097                  * careful than too reckless.
3098                  */
3099                 if ((error = fget(td, sockarg.sock, CAP_SOCK_ALL, &fp)) != 0)
3100                         goto out;
3101                 if (fp->f_type != DTYPE_SOCKET) {
3102                         fdrop(fp, td);
3103                         error = EPERM;
3104                         goto out;
3105                 }
3106                 error = nfsrvd_addsock(fp);
3107                 fdrop(fp, td);
3108         } else if (uap->flag & NFSSVC_NFSDNFSD) {
3109                 if (uap->argp == NULL) {
3110                         error = EINVAL;
3111                         goto out;
3112                 }
3113                 error = copyin(uap->argp, (caddr_t)&nfsdarg,
3114                     sizeof (nfsdarg));
3115                 if (error)
3116                         goto out;
3117                 error = nfsrvd_nfsd(td, &nfsdarg);
3118         } else {
3119                 error = nfssvc_srvcall(td, uap, td->td_ucred);
3120         }
3121
3122 out:
3123         NFSEXITCODE(error);
3124         return (error);
3125 }
3126
3127 static int
3128 nfssvc_srvcall(struct thread *p, struct nfssvc_args *uap, struct ucred *cred)
3129 {
3130         struct nfsex_args export;
3131         struct file *fp = NULL;
3132         int stablefd, len;
3133         struct nfsd_clid adminrevoke;
3134         struct nfsd_dumplist dumplist;
3135         struct nfsd_dumpclients *dumpclients;
3136         struct nfsd_dumplocklist dumplocklist;
3137         struct nfsd_dumplocks *dumplocks;
3138         struct nameidata nd;
3139         vnode_t vp;
3140         int error = EINVAL, igotlock;
3141         struct proc *procp;
3142         static int suspend_nfsd = 0;
3143
3144         if (uap->flag & NFSSVC_PUBLICFH) {
3145                 NFSBZERO((caddr_t)&nfs_pubfh.nfsrvfh_data,
3146                     sizeof (fhandle_t));
3147                 error = copyin(uap->argp,
3148                     &nfs_pubfh.nfsrvfh_data, sizeof (fhandle_t));
3149                 if (!error)
3150                         nfs_pubfhset = 1;
3151         } else if (uap->flag & NFSSVC_V4ROOTEXPORT) {
3152                 error = copyin(uap->argp,(caddr_t)&export,
3153                     sizeof (struct nfsex_args));
3154                 if (!error)
3155                         error = nfsrv_v4rootexport(&export, cred, p);
3156         } else if (uap->flag & NFSSVC_NOPUBLICFH) {
3157                 nfs_pubfhset = 0;
3158                 error = 0;
3159         } else if (uap->flag & NFSSVC_STABLERESTART) {
3160                 error = copyin(uap->argp, (caddr_t)&stablefd,
3161                     sizeof (int));
3162                 if (!error)
3163                         error = fp_getfvp(p, stablefd, &fp, &vp);
3164                 if (!error && (NFSFPFLAG(fp) & (FREAD | FWRITE)) != (FREAD | FWRITE))
3165                         error = EBADF;
3166                 if (!error && newnfs_numnfsd != 0)
3167                         error = EPERM;
3168                 if (!error) {
3169                         nfsrv_stablefirst.nsf_fp = fp;
3170                         nfsrv_setupstable(p);
3171                 }
3172         } else if (uap->flag & NFSSVC_ADMINREVOKE) {
3173                 error = copyin(uap->argp, (caddr_t)&adminrevoke,
3174                     sizeof (struct nfsd_clid));
3175                 if (!error)
3176                         error = nfsrv_adminrevoke(&adminrevoke, p);
3177         } else if (uap->flag & NFSSVC_DUMPCLIENTS) {
3178                 error = copyin(uap->argp, (caddr_t)&dumplist,
3179                     sizeof (struct nfsd_dumplist));
3180                 if (!error && (dumplist.ndl_size < 1 ||
3181                         dumplist.ndl_size > NFSRV_MAXDUMPLIST))
3182                         error = EPERM;
3183                 if (!error) {
3184                     len = sizeof (struct nfsd_dumpclients) * dumplist.ndl_size;
3185                     dumpclients = (struct nfsd_dumpclients *)malloc(len,
3186                         M_TEMP, M_WAITOK);
3187                     nfsrv_dumpclients(dumpclients, dumplist.ndl_size);
3188                     error = copyout(dumpclients,
3189                         CAST_USER_ADDR_T(dumplist.ndl_list), len);
3190                     free((caddr_t)dumpclients, M_TEMP);
3191                 }
3192         } else if (uap->flag & NFSSVC_DUMPLOCKS) {
3193                 error = copyin(uap->argp, (caddr_t)&dumplocklist,
3194                     sizeof (struct nfsd_dumplocklist));
3195                 if (!error && (dumplocklist.ndllck_size < 1 ||
3196                         dumplocklist.ndllck_size > NFSRV_MAXDUMPLIST))
3197                         error = EPERM;
3198                 if (!error)
3199                         error = nfsrv_lookupfilename(&nd,
3200                                 dumplocklist.ndllck_fname, p);
3201                 if (!error) {
3202                         len = sizeof (struct nfsd_dumplocks) *
3203                                 dumplocklist.ndllck_size;
3204                         dumplocks = (struct nfsd_dumplocks *)malloc(len,
3205                                 M_TEMP, M_WAITOK);
3206                         nfsrv_dumplocks(nd.ni_vp, dumplocks,
3207                             dumplocklist.ndllck_size, p);
3208                         vput(nd.ni_vp);
3209                         error = copyout(dumplocks,
3210                             CAST_USER_ADDR_T(dumplocklist.ndllck_list), len);
3211                         free((caddr_t)dumplocks, M_TEMP);
3212                 }
3213         } else if (uap->flag & NFSSVC_BACKUPSTABLE) {
3214                 procp = p->td_proc;
3215                 PROC_LOCK(procp);
3216                 nfsd_master_pid = procp->p_pid;
3217                 bcopy(procp->p_comm, nfsd_master_comm, MAXCOMLEN + 1);
3218                 nfsd_master_start = procp->p_stats->p_start;
3219                 nfsd_master_proc = procp;
3220                 PROC_UNLOCK(procp);
3221         } else if ((uap->flag & NFSSVC_SUSPENDNFSD) != 0) {
3222                 NFSLOCKV4ROOTMUTEX();
3223                 if (suspend_nfsd == 0) {
3224                         /* Lock out all nfsd threads */
3225                         do {
3226                                 igotlock = nfsv4_lock(&nfsd_suspend_lock, 1,
3227                                     NULL, NFSV4ROOTLOCKMUTEXPTR, NULL);
3228                         } while (igotlock == 0 && suspend_nfsd == 0);
3229                         suspend_nfsd = 1;
3230                 }
3231                 NFSUNLOCKV4ROOTMUTEX();
3232                 error = 0;
3233         } else if ((uap->flag & NFSSVC_RESUMENFSD) != 0) {
3234                 NFSLOCKV4ROOTMUTEX();
3235                 if (suspend_nfsd != 0) {
3236                         nfsv4_unlock(&nfsd_suspend_lock, 0);
3237                         suspend_nfsd = 0;
3238                 }
3239                 NFSUNLOCKV4ROOTMUTEX();
3240                 error = 0;
3241         }
3242
3243         NFSEXITCODE(error);
3244         return (error);
3245 }
3246
3247 /*
3248  * Check exports.
3249  * Returns 0 if ok, 1 otherwise.
3250  */
3251 int
3252 nfsvno_testexp(struct nfsrv_descript *nd, struct nfsexstuff *exp)
3253 {
3254         int i;
3255
3256         /*
3257          * This seems odd, but allow the case where the security flavor
3258          * list is empty. This happens when NFSv4 is traversing non-exported
3259          * file systems. Exported file systems should always have a non-empty
3260          * security flavor list.
3261          */
3262         if (exp->nes_numsecflavor == 0)
3263                 return (0);
3264
3265         for (i = 0; i < exp->nes_numsecflavor; i++) {
3266                 /*
3267                  * The tests for privacy and integrity must be first,
3268                  * since ND_GSS is set for everything but AUTH_SYS.
3269                  */
3270                 if (exp->nes_secflavors[i] == RPCSEC_GSS_KRB5P &&
3271                     (nd->nd_flag & ND_GSSPRIVACY))
3272                         return (0);
3273                 if (exp->nes_secflavors[i] == RPCSEC_GSS_KRB5I &&
3274                     (nd->nd_flag & ND_GSSINTEGRITY))
3275                         return (0);
3276                 if (exp->nes_secflavors[i] == RPCSEC_GSS_KRB5 &&
3277                     (nd->nd_flag & ND_GSS))
3278                         return (0);
3279                 if (exp->nes_secflavors[i] == AUTH_SYS &&
3280                     (nd->nd_flag & ND_GSS) == 0)
3281                         return (0);
3282         }
3283         return (1);
3284 }
3285
3286 /*
3287  * Calculate a hash value for the fid in a file handle.
3288  */
3289 uint32_t
3290 nfsrv_hashfh(fhandle_t *fhp)
3291 {
3292         uint32_t hashval;
3293
3294         hashval = hash32_buf(&fhp->fh_fid, sizeof(struct fid), 0);
3295         return (hashval);
3296 }
3297
3298 /*
3299  * Signal the userland master nfsd to backup the stable restart file.
3300  */
3301 void
3302 nfsrv_backupstable(void)
3303 {
3304         struct proc *procp;
3305
3306         if (nfsd_master_proc != NULL) {
3307                 procp = pfind(nfsd_master_pid);
3308                 /* Try to make sure it is the correct process. */
3309                 if (procp == nfsd_master_proc &&
3310                     procp->p_stats->p_start.tv_sec ==
3311                     nfsd_master_start.tv_sec &&
3312                     procp->p_stats->p_start.tv_usec ==
3313                     nfsd_master_start.tv_usec &&
3314                     strcmp(procp->p_comm, nfsd_master_comm) == 0)
3315                         kern_psignal(procp, SIGUSR2);
3316                 else
3317                         nfsd_master_proc = NULL;
3318
3319                 if (procp != NULL)
3320                         PROC_UNLOCK(procp);
3321         }
3322 }
3323
3324 extern int (*nfsd_call_nfsd)(struct thread *, struct nfssvc_args *);
3325
3326 /*
3327  * Called once to initialize data structures...
3328  */
3329 static int
3330 nfsd_modevent(module_t mod, int type, void *data)
3331 {
3332         int error = 0, i;
3333         static int loaded = 0;
3334
3335         switch (type) {
3336         case MOD_LOAD:
3337                 if (loaded)
3338                         goto out;
3339                 newnfs_portinit();
3340                 for (i = 0; i < NFSRVCACHE_HASHSIZE; i++) {
3341                         snprintf(nfsrchash_table[i].lock_name,
3342                             sizeof(nfsrchash_table[i].lock_name), "nfsrc_tcp%d",
3343                             i);
3344                         mtx_init(&nfsrchash_table[i].mtx,
3345                             nfsrchash_table[i].lock_name, NULL, MTX_DEF);
3346                 }
3347                 mtx_init(&nfsrc_udpmtx, "nfs_udpcache_mutex", NULL, MTX_DEF);
3348                 mtx_init(&nfs_v4root_mutex, "nfs_v4root_mutex", NULL, MTX_DEF);
3349                 mtx_init(&nfsv4root_mnt.mnt_mtx, "struct mount mtx", NULL,
3350                     MTX_DEF);
3351                 lockinit(&nfsv4root_mnt.mnt_explock, PVFS, "explock", 0, 0);
3352                 nfsrvd_initcache();
3353                 nfsd_init();
3354                 NFSD_LOCK();
3355                 nfsrvd_init(0);
3356                 NFSD_UNLOCK();
3357                 nfsd_mntinit();
3358 #ifdef VV_DISABLEDELEG
3359                 vn_deleg_ops.vndeleg_recall = nfsd_recalldelegation;
3360                 vn_deleg_ops.vndeleg_disable = nfsd_disabledelegation;
3361 #endif
3362                 nfsd_call_servertimer = nfsrv_servertimer;
3363                 nfsd_call_nfsd = nfssvc_nfsd;
3364                 loaded = 1;
3365                 break;
3366
3367         case MOD_UNLOAD:
3368                 if (newnfs_numnfsd != 0) {
3369                         error = EBUSY;
3370                         break;
3371                 }
3372
3373 #ifdef VV_DISABLEDELEG
3374                 vn_deleg_ops.vndeleg_recall = NULL;
3375                 vn_deleg_ops.vndeleg_disable = NULL;
3376 #endif
3377                 nfsd_call_servertimer = NULL;
3378                 nfsd_call_nfsd = NULL;
3379
3380                 /* Clean out all NFSv4 state. */
3381                 nfsrv_throwawayallstate(curthread);
3382
3383                 /* Clean the NFS server reply cache */
3384                 nfsrvd_cleancache();
3385
3386                 /* Free up the krpc server pool. */
3387                 if (nfsrvd_pool != NULL)
3388                         svcpool_destroy(nfsrvd_pool);
3389
3390                 /* and get rid of the locks */
3391                 for (i = 0; i < NFSRVCACHE_HASHSIZE; i++)
3392                         mtx_destroy(&nfsrchash_table[i].mtx);
3393                 mtx_destroy(&nfsrc_udpmtx);
3394                 mtx_destroy(&nfs_v4root_mutex);
3395                 mtx_destroy(&nfsv4root_mnt.mnt_mtx);
3396                 lockdestroy(&nfsv4root_mnt.mnt_explock);
3397                 loaded = 0;
3398                 break;
3399         default:
3400                 error = EOPNOTSUPP;
3401                 break;
3402         }
3403
3404 out:
3405         NFSEXITCODE(error);
3406         return (error);
3407 }
3408 static moduledata_t nfsd_mod = {
3409         "nfsd",
3410         nfsd_modevent,
3411         NULL,
3412 };
3413 DECLARE_MODULE(nfsd, nfsd_mod, SI_SUB_VFS, SI_ORDER_ANY);
3414
3415 /* So that loader and kldload(2) can find us, wherever we are.. */
3416 MODULE_VERSION(nfsd, 1);
3417 MODULE_DEPEND(nfsd, nfscommon, 1, 1, 1);
3418 MODULE_DEPEND(nfsd, nfslock, 1, 1, 1);
3419 MODULE_DEPEND(nfsd, nfslockd, 1, 1, 1);
3420 MODULE_DEPEND(nfsd, krpc, 1, 1, 1);
3421 MODULE_DEPEND(nfsd, nfssvc, 1, 1, 1);
3422