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