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