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