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