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