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