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