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