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