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 347040 2019-05-03 02:30:01Z 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					if (error != 0) {
798						vput(ndp->ni_vp);
799						ndp->ni_vp = NULL;
800						error = NFSERR_NOTSUPP;
801					}
802				}
803			}
804		/*
805		 * NFS V2 Only. nfsrvd_mknod() does this for V3.
806		 * (This implies, just get out on an error.)
807		 */
808		} else if (nvap->na_type == VCHR || nvap->na_type == VBLK ||
809			nvap->na_type == VFIFO) {
810			if (nvap->na_type == VCHR && rdev == 0xffffffff)
811				nvap->na_type = VFIFO;
812                        if (nvap->na_type != VFIFO &&
813			    (error = priv_check_cred(nd->nd_cred,
814			     PRIV_VFS_MKNOD_DEV, 0))) {
815				vrele(ndp->ni_startdir);
816				nfsvno_relpathbuf(ndp);
817				vput(ndp->ni_dvp);
818				goto out;
819			}
820			nvap->na_rdev = rdev;
821			error = VOP_MKNOD(ndp->ni_dvp, &ndp->ni_vp,
822			    &ndp->ni_cnd, &nvap->na_vattr);
823			vput(ndp->ni_dvp);
824			nfsvno_relpathbuf(ndp);
825			vrele(ndp->ni_startdir);
826			if (error)
827				goto out;
828		} else {
829			vrele(ndp->ni_startdir);
830			nfsvno_relpathbuf(ndp);
831			vput(ndp->ni_dvp);
832			error = ENXIO;
833			goto out;
834		}
835		*vpp = ndp->ni_vp;
836	} else {
837		/*
838		 * Handle cases where error is already set and/or
839		 * the file exists.
840		 * 1 - clean up the lookup
841		 * 2 - iff !error and na_size set, truncate it
842		 */
843		vrele(ndp->ni_startdir);
844		nfsvno_relpathbuf(ndp);
845		*vpp = ndp->ni_vp;
846		if (ndp->ni_dvp == *vpp)
847			vrele(ndp->ni_dvp);
848		else
849			vput(ndp->ni_dvp);
850		if (!error && nvap->na_size != VNOVAL) {
851			error = nfsvno_accchk(*vpp, VWRITE,
852			    nd->nd_cred, exp, p, NFSACCCHK_NOOVERRIDE,
853			    NFSACCCHK_VPISLOCKED, NULL);
854			if (!error) {
855				tempsize = nvap->na_size;
856				NFSVNO_ATTRINIT(nvap);
857				nvap->na_size = tempsize;
858				error = VOP_SETATTR(*vpp,
859				    &nvap->na_vattr, nd->nd_cred);
860			}
861		}
862		if (error)
863			vput(*vpp);
864	}
865
866out:
867	NFSEXITCODE(error);
868	return (error);
869}
870
871/*
872 * Do a mknod vnode op.
873 */
874int
875nfsvno_mknod(struct nameidata *ndp, struct nfsvattr *nvap, struct ucred *cred,
876    struct thread *p)
877{
878	int error = 0;
879	enum vtype vtyp;
880
881	vtyp = nvap->na_type;
882	/*
883	 * Iff doesn't exist, create it.
884	 */
885	if (ndp->ni_vp) {
886		vrele(ndp->ni_startdir);
887		nfsvno_relpathbuf(ndp);
888		vput(ndp->ni_dvp);
889		vrele(ndp->ni_vp);
890		error = EEXIST;
891		goto out;
892	}
893	if (vtyp != VCHR && vtyp != VBLK && vtyp != VSOCK && vtyp != VFIFO) {
894		vrele(ndp->ni_startdir);
895		nfsvno_relpathbuf(ndp);
896		vput(ndp->ni_dvp);
897		error = NFSERR_BADTYPE;
898		goto out;
899	}
900	if (vtyp == VSOCK) {
901		vrele(ndp->ni_startdir);
902		error = VOP_CREATE(ndp->ni_dvp, &ndp->ni_vp,
903		    &ndp->ni_cnd, &nvap->na_vattr);
904		vput(ndp->ni_dvp);
905		nfsvno_relpathbuf(ndp);
906	} else {
907		if (nvap->na_type != VFIFO &&
908		    (error = priv_check_cred(cred, PRIV_VFS_MKNOD_DEV, 0))) {
909			vrele(ndp->ni_startdir);
910			nfsvno_relpathbuf(ndp);
911			vput(ndp->ni_dvp);
912			goto out;
913		}
914		error = VOP_MKNOD(ndp->ni_dvp, &ndp->ni_vp,
915		    &ndp->ni_cnd, &nvap->na_vattr);
916		vput(ndp->ni_dvp);
917		nfsvno_relpathbuf(ndp);
918		vrele(ndp->ni_startdir);
919		/*
920		 * Since VOP_MKNOD returns the ni_vp, I can't
921		 * see any reason to do the lookup.
922		 */
923	}
924
925out:
926	NFSEXITCODE(error);
927	return (error);
928}
929
930/*
931 * Mkdir vnode op.
932 */
933int
934nfsvno_mkdir(struct nameidata *ndp, struct nfsvattr *nvap, uid_t saved_uid,
935    struct ucred *cred, struct thread *p, struct nfsexstuff *exp)
936{
937	int error = 0;
938
939	if (ndp->ni_vp != NULL) {
940		if (ndp->ni_dvp == ndp->ni_vp)
941			vrele(ndp->ni_dvp);
942		else
943			vput(ndp->ni_dvp);
944		vrele(ndp->ni_vp);
945		nfsvno_relpathbuf(ndp);
946		error = EEXIST;
947		goto out;
948	}
949	error = VOP_MKDIR(ndp->ni_dvp, &ndp->ni_vp, &ndp->ni_cnd,
950	    &nvap->na_vattr);
951	vput(ndp->ni_dvp);
952	nfsvno_relpathbuf(ndp);
953
954out:
955	NFSEXITCODE(error);
956	return (error);
957}
958
959/*
960 * symlink vnode op.
961 */
962int
963nfsvno_symlink(struct nameidata *ndp, struct nfsvattr *nvap, char *pathcp,
964    int pathlen, int not_v2, uid_t saved_uid, struct ucred *cred, struct thread *p,
965    struct nfsexstuff *exp)
966{
967	int error = 0;
968
969	if (ndp->ni_vp) {
970		vrele(ndp->ni_startdir);
971		nfsvno_relpathbuf(ndp);
972		if (ndp->ni_dvp == ndp->ni_vp)
973			vrele(ndp->ni_dvp);
974		else
975			vput(ndp->ni_dvp);
976		vrele(ndp->ni_vp);
977		error = EEXIST;
978		goto out;
979	}
980
981	error = VOP_SYMLINK(ndp->ni_dvp, &ndp->ni_vp, &ndp->ni_cnd,
982	    &nvap->na_vattr, pathcp);
983	vput(ndp->ni_dvp);
984	vrele(ndp->ni_startdir);
985	nfsvno_relpathbuf(ndp);
986	/*
987	 * Although FreeBSD still had the lookup code in
988	 * it for 7/current, there doesn't seem to be any
989	 * point, since VOP_SYMLINK() returns the ni_vp.
990	 * Just vput it for v2.
991	 */
992	if (!not_v2 && !error)
993		vput(ndp->ni_vp);
994
995out:
996	NFSEXITCODE(error);
997	return (error);
998}
999
1000/*
1001 * Parse symbolic link arguments.
1002 * This function has an ugly side effect. It will MALLOC() an area for
1003 * the symlink and set iov_base to point to it, only if it succeeds.
1004 * So, if it returns with uiop->uio_iov->iov_base != NULL, that must
1005 * be FREE'd later.
1006 */
1007int
1008nfsvno_getsymlink(struct nfsrv_descript *nd, struct nfsvattr *nvap,
1009    struct thread *p, char **pathcpp, int *lenp)
1010{
1011	u_int32_t *tl;
1012	char *pathcp = NULL;
1013	int error = 0, len;
1014	struct nfsv2_sattr *sp;
1015
1016	*pathcpp = NULL;
1017	*lenp = 0;
1018	if ((nd->nd_flag & ND_NFSV3) &&
1019	    (error = nfsrv_sattr(nd, nvap, NULL, NULL, p)))
1020		goto nfsmout;
1021	NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
1022	len = fxdr_unsigned(int, *tl);
1023	if (len > NFS_MAXPATHLEN || len <= 0) {
1024		error = EBADRPC;
1025		goto nfsmout;
1026	}
1027	MALLOC(pathcp, caddr_t, len + 1, M_TEMP, M_WAITOK);
1028	error = nfsrv_mtostr(nd, pathcp, len);
1029	if (error)
1030		goto nfsmout;
1031	if (nd->nd_flag & ND_NFSV2) {
1032		NFSM_DISSECT(sp, struct nfsv2_sattr *, NFSX_V2SATTR);
1033		nvap->na_mode = fxdr_unsigned(u_int16_t, sp->sa_mode);
1034	}
1035	*pathcpp = pathcp;
1036	*lenp = len;
1037	NFSEXITCODE2(0, nd);
1038	return (0);
1039nfsmout:
1040	if (pathcp)
1041		free(pathcp, M_TEMP);
1042	NFSEXITCODE2(error, nd);
1043	return (error);
1044}
1045
1046/*
1047 * Remove a non-directory object.
1048 */
1049int
1050nfsvno_removesub(struct nameidata *ndp, int is_v4, struct ucred *cred,
1051    struct thread *p, struct nfsexstuff *exp)
1052{
1053	struct vnode *vp;
1054	int error = 0;
1055
1056	vp = ndp->ni_vp;
1057	if (vp->v_type == VDIR)
1058		error = NFSERR_ISDIR;
1059	else if (is_v4)
1060		error = nfsrv_checkremove(vp, 1, p);
1061	if (!error)
1062		error = VOP_REMOVE(ndp->ni_dvp, vp, &ndp->ni_cnd);
1063	if (ndp->ni_dvp == vp)
1064		vrele(ndp->ni_dvp);
1065	else
1066		vput(ndp->ni_dvp);
1067	vput(vp);
1068	if ((ndp->ni_cnd.cn_flags & SAVENAME) != 0)
1069		nfsvno_relpathbuf(ndp);
1070	NFSEXITCODE(error);
1071	return (error);
1072}
1073
1074/*
1075 * Remove a directory.
1076 */
1077int
1078nfsvno_rmdirsub(struct nameidata *ndp, int is_v4, struct ucred *cred,
1079    struct thread *p, struct nfsexstuff *exp)
1080{
1081	struct vnode *vp;
1082	int error = 0;
1083
1084	vp = ndp->ni_vp;
1085	if (vp->v_type != VDIR) {
1086		error = ENOTDIR;
1087		goto out;
1088	}
1089	/*
1090	 * No rmdir "." please.
1091	 */
1092	if (ndp->ni_dvp == vp) {
1093		error = EINVAL;
1094		goto out;
1095	}
1096	/*
1097	 * The root of a mounted filesystem cannot be deleted.
1098	 */
1099	if (vp->v_vflag & VV_ROOT)
1100		error = EBUSY;
1101out:
1102	if (!error)
1103		error = VOP_RMDIR(ndp->ni_dvp, vp, &ndp->ni_cnd);
1104	if (ndp->ni_dvp == vp)
1105		vrele(ndp->ni_dvp);
1106	else
1107		vput(ndp->ni_dvp);
1108	vput(vp);
1109	if ((ndp->ni_cnd.cn_flags & SAVENAME) != 0)
1110		nfsvno_relpathbuf(ndp);
1111	NFSEXITCODE(error);
1112	return (error);
1113}
1114
1115/*
1116 * Rename vnode op.
1117 */
1118int
1119nfsvno_rename(struct nameidata *fromndp, struct nameidata *tondp,
1120    u_int32_t ndstat, u_int32_t ndflag, struct ucred *cred, struct thread *p)
1121{
1122	struct vnode *fvp, *tvp, *tdvp;
1123	int error = 0;
1124
1125	fvp = fromndp->ni_vp;
1126	if (ndstat) {
1127		vrele(fromndp->ni_dvp);
1128		vrele(fvp);
1129		error = ndstat;
1130		goto out1;
1131	}
1132	tdvp = tondp->ni_dvp;
1133	tvp = tondp->ni_vp;
1134	if (tvp != NULL) {
1135		if (fvp->v_type == VDIR && tvp->v_type != VDIR) {
1136			error = (ndflag & ND_NFSV2) ? EISDIR : EEXIST;
1137			goto out;
1138		} else if (fvp->v_type != VDIR && tvp->v_type == VDIR) {
1139			error = (ndflag & ND_NFSV2) ? ENOTDIR : EEXIST;
1140			goto out;
1141		}
1142		if (tvp->v_type == VDIR && tvp->v_mountedhere) {
1143			error = (ndflag & ND_NFSV2) ? ENOTEMPTY : EXDEV;
1144			goto out;
1145		}
1146
1147		/*
1148		 * A rename to '.' or '..' results in a prematurely
1149		 * unlocked vnode on FreeBSD5, so I'm just going to fail that
1150		 * here.
1151		 */
1152		if ((tondp->ni_cnd.cn_namelen == 1 &&
1153		     tondp->ni_cnd.cn_nameptr[0] == '.') ||
1154		    (tondp->ni_cnd.cn_namelen == 2 &&
1155		     tondp->ni_cnd.cn_nameptr[0] == '.' &&
1156		     tondp->ni_cnd.cn_nameptr[1] == '.')) {
1157			error = EINVAL;
1158			goto out;
1159		}
1160	}
1161	if (fvp->v_type == VDIR && fvp->v_mountedhere) {
1162		error = (ndflag & ND_NFSV2) ? ENOTEMPTY : EXDEV;
1163		goto out;
1164	}
1165	if (fvp->v_mount != tdvp->v_mount) {
1166		error = (ndflag & ND_NFSV2) ? ENOTEMPTY : EXDEV;
1167		goto out;
1168	}
1169	if (fvp == tdvp) {
1170		error = (ndflag & ND_NFSV2) ? ENOTEMPTY : EINVAL;
1171		goto out;
1172	}
1173	if (fvp == tvp) {
1174		/*
1175		 * If source and destination are the same, there is nothing to
1176		 * do. Set error to -1 to indicate this.
1177		 */
1178		error = -1;
1179		goto out;
1180	}
1181	if (ndflag & ND_NFSV4) {
1182		if (NFSVOPLOCK(fvp, LK_EXCLUSIVE) == 0) {
1183			error = nfsrv_checkremove(fvp, 0, p);
1184			NFSVOPUNLOCK(fvp, 0);
1185		} else
1186			error = EPERM;
1187		if (tvp && !error)
1188			error = nfsrv_checkremove(tvp, 1, p);
1189	} else {
1190		/*
1191		 * For NFSv2 and NFSv3, try to get rid of the delegation, so
1192		 * that the NFSv4 client won't be confused by the rename.
1193		 * Since nfsd_recalldelegation() can only be called on an
1194		 * unlocked vnode at this point and fvp is the file that will
1195		 * still exist after the rename, just do fvp.
1196		 */
1197		nfsd_recalldelegation(fvp, p);
1198	}
1199out:
1200	if (!error) {
1201		error = VOP_RENAME(fromndp->ni_dvp, fromndp->ni_vp,
1202		    &fromndp->ni_cnd, tondp->ni_dvp, tondp->ni_vp,
1203		    &tondp->ni_cnd);
1204	} else {
1205		if (tdvp == tvp)
1206			vrele(tdvp);
1207		else
1208			vput(tdvp);
1209		if (tvp)
1210			vput(tvp);
1211		vrele(fromndp->ni_dvp);
1212		vrele(fvp);
1213		if (error == -1)
1214			error = 0;
1215	}
1216	vrele(tondp->ni_startdir);
1217	nfsvno_relpathbuf(tondp);
1218out1:
1219	vrele(fromndp->ni_startdir);
1220	nfsvno_relpathbuf(fromndp);
1221	NFSEXITCODE(error);
1222	return (error);
1223}
1224
1225/*
1226 * Link vnode op.
1227 */
1228int
1229nfsvno_link(struct nameidata *ndp, struct vnode *vp, struct ucred *cred,
1230    struct thread *p, struct nfsexstuff *exp)
1231{
1232	struct vnode *xp;
1233	int error = 0;
1234
1235	xp = ndp->ni_vp;
1236	if (xp != NULL) {
1237		error = EEXIST;
1238	} else {
1239		xp = ndp->ni_dvp;
1240		if (vp->v_mount != xp->v_mount)
1241			error = EXDEV;
1242	}
1243	if (!error) {
1244		NFSVOPLOCK(vp, LK_EXCLUSIVE | LK_RETRY);
1245		if ((vp->v_iflag & VI_DOOMED) == 0)
1246			error = VOP_LINK(ndp->ni_dvp, vp, &ndp->ni_cnd);
1247		else
1248			error = EPERM;
1249		if (ndp->ni_dvp == vp)
1250			vrele(ndp->ni_dvp);
1251		else
1252			vput(ndp->ni_dvp);
1253		NFSVOPUNLOCK(vp, 0);
1254	} else {
1255		if (ndp->ni_dvp == ndp->ni_vp)
1256			vrele(ndp->ni_dvp);
1257		else
1258			vput(ndp->ni_dvp);
1259		if (ndp->ni_vp)
1260			vrele(ndp->ni_vp);
1261	}
1262	nfsvno_relpathbuf(ndp);
1263	NFSEXITCODE(error);
1264	return (error);
1265}
1266
1267/*
1268 * Do the fsync() appropriate for the commit.
1269 */
1270int
1271nfsvno_fsync(struct vnode *vp, u_int64_t off, int cnt, struct ucred *cred,
1272    struct thread *td)
1273{
1274	int error = 0;
1275
1276	/*
1277	 * RFC 1813 3.3.21: if count is 0, a flush from offset to the end of
1278	 * file is done.  At this time VOP_FSYNC does not accept offset and
1279	 * byte count parameters so call VOP_FSYNC the whole file for now.
1280	 * The same is true for NFSv4: RFC 3530 Sec. 14.2.3.
1281	 * File systems that do not use the buffer cache (as indicated
1282	 * by MNTK_USES_BCACHE not being set) must use VOP_FSYNC().
1283	 */
1284	if (cnt == 0 || cnt > MAX_COMMIT_COUNT ||
1285	    (vp->v_mount->mnt_kern_flag & MNTK_USES_BCACHE) == 0) {
1286		/*
1287		 * Give up and do the whole thing
1288		 */
1289		if (vp->v_object &&
1290		   (vp->v_object->flags & OBJ_MIGHTBEDIRTY)) {
1291			VM_OBJECT_WLOCK(vp->v_object);
1292			vm_object_page_clean(vp->v_object, 0, 0, OBJPC_SYNC);
1293			VM_OBJECT_WUNLOCK(vp->v_object);
1294		}
1295		error = VOP_FSYNC(vp, MNT_WAIT, td);
1296	} else {
1297		/*
1298		 * Locate and synchronously write any buffers that fall
1299		 * into the requested range.  Note:  we are assuming that
1300		 * f_iosize is a power of 2.
1301		 */
1302		int iosize = vp->v_mount->mnt_stat.f_iosize;
1303		int iomask = iosize - 1;
1304		struct bufobj *bo;
1305		daddr_t lblkno;
1306
1307		/*
1308		 * Align to iosize boundry, super-align to page boundry.
1309		 */
1310		if (off & iomask) {
1311			cnt += off & iomask;
1312			off &= ~(u_quad_t)iomask;
1313		}
1314		if (off & PAGE_MASK) {
1315			cnt += off & PAGE_MASK;
1316			off &= ~(u_quad_t)PAGE_MASK;
1317		}
1318		lblkno = off / iosize;
1319
1320		if (vp->v_object &&
1321		   (vp->v_object->flags & OBJ_MIGHTBEDIRTY)) {
1322			VM_OBJECT_WLOCK(vp->v_object);
1323			vm_object_page_clean(vp->v_object, off, off + cnt,
1324			    OBJPC_SYNC);
1325			VM_OBJECT_WUNLOCK(vp->v_object);
1326		}
1327
1328		bo = &vp->v_bufobj;
1329		BO_LOCK(bo);
1330		while (cnt > 0) {
1331			struct buf *bp;
1332
1333			/*
1334			 * If we have a buffer and it is marked B_DELWRI we
1335			 * have to lock and write it.  Otherwise the prior
1336			 * write is assumed to have already been committed.
1337			 *
1338			 * gbincore() can return invalid buffers now so we
1339			 * have to check that bit as well (though B_DELWRI
1340			 * should not be set if B_INVAL is set there could be
1341			 * a race here since we haven't locked the buffer).
1342			 */
1343			if ((bp = gbincore(&vp->v_bufobj, lblkno)) != NULL) {
1344				if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_SLEEPFAIL |
1345				    LK_INTERLOCK, BO_LOCKPTR(bo)) == ENOLCK) {
1346					BO_LOCK(bo);
1347					continue; /* retry */
1348				}
1349			    	if ((bp->b_flags & (B_DELWRI|B_INVAL)) ==
1350				    B_DELWRI) {
1351					bremfree(bp);
1352					bp->b_flags &= ~B_ASYNC;
1353					bwrite(bp);
1354					++nfs_commit_miss;
1355				} else
1356					BUF_UNLOCK(bp);
1357				BO_LOCK(bo);
1358			}
1359			++nfs_commit_blks;
1360			if (cnt < iosize)
1361				break;
1362			cnt -= iosize;
1363			++lblkno;
1364		}
1365		BO_UNLOCK(bo);
1366	}
1367	NFSEXITCODE(error);
1368	return (error);
1369}
1370
1371/*
1372 * Statfs vnode op.
1373 */
1374int
1375nfsvno_statfs(struct vnode *vp, struct statfs *sf)
1376{
1377	int error;
1378
1379	error = VFS_STATFS(vp->v_mount, sf);
1380	if (error == 0) {
1381		/*
1382		 * Since NFS handles these values as unsigned on the
1383		 * wire, there is no way to represent negative values,
1384		 * so set them to 0. Without this, they will appear
1385		 * to be very large positive values for clients like
1386		 * Solaris10.
1387		 */
1388		if (sf->f_bavail < 0)
1389			sf->f_bavail = 0;
1390		if (sf->f_ffree < 0)
1391			sf->f_ffree = 0;
1392	}
1393	NFSEXITCODE(error);
1394	return (error);
1395}
1396
1397/*
1398 * Do the vnode op stuff for Open. Similar to nfsvno_createsub(), but
1399 * must handle nfsrv_opencheck() calls after any other access checks.
1400 */
1401void
1402nfsvno_open(struct nfsrv_descript *nd, struct nameidata *ndp,
1403    nfsquad_t clientid, nfsv4stateid_t *stateidp, struct nfsstate *stp,
1404    int *exclusive_flagp, struct nfsvattr *nvap, int32_t *cverf, int create,
1405    NFSACL_T *aclp, nfsattrbit_t *attrbitp, struct ucred *cred, struct thread *p,
1406    struct nfsexstuff *exp, struct vnode **vpp)
1407{
1408	struct vnode *vp = NULL;
1409	u_quad_t tempsize;
1410	struct nfsexstuff nes;
1411
1412	if (ndp->ni_vp == NULL)
1413		nd->nd_repstat = nfsrv_opencheck(clientid,
1414		    stateidp, stp, NULL, nd, p, nd->nd_repstat);
1415	if (!nd->nd_repstat) {
1416		if (ndp->ni_vp == NULL) {
1417			vrele(ndp->ni_startdir);
1418			nd->nd_repstat = VOP_CREATE(ndp->ni_dvp,
1419			    &ndp->ni_vp, &ndp->ni_cnd, &nvap->na_vattr);
1420			vput(ndp->ni_dvp);
1421			nfsvno_relpathbuf(ndp);
1422			if (!nd->nd_repstat) {
1423				if (*exclusive_flagp) {
1424					*exclusive_flagp = 0;
1425					NFSVNO_ATTRINIT(nvap);
1426					nvap->na_atime.tv_sec = cverf[0];
1427					nvap->na_atime.tv_nsec = cverf[1];
1428					nd->nd_repstat = VOP_SETATTR(ndp->ni_vp,
1429					    &nvap->na_vattr, cred);
1430					if (nd->nd_repstat != 0) {
1431						vput(ndp->ni_vp);
1432						ndp->ni_vp = NULL;
1433						nd->nd_repstat = NFSERR_NOTSUPP;
1434					} else
1435						NFSSETBIT_ATTRBIT(attrbitp,
1436						    NFSATTRBIT_TIMEACCESS);
1437				} else {
1438					nfsrv_fixattr(nd, ndp->ni_vp, nvap,
1439					    aclp, p, attrbitp, exp);
1440				}
1441			}
1442			vp = ndp->ni_vp;
1443		} else {
1444			if (ndp->ni_startdir)
1445				vrele(ndp->ni_startdir);
1446			nfsvno_relpathbuf(ndp);
1447			vp = ndp->ni_vp;
1448			if (create == NFSV4OPEN_CREATE) {
1449				if (ndp->ni_dvp == vp)
1450					vrele(ndp->ni_dvp);
1451				else
1452					vput(ndp->ni_dvp);
1453			}
1454			if (NFSVNO_ISSETSIZE(nvap) && vp->v_type == VREG) {
1455				if (ndp->ni_cnd.cn_flags & RDONLY)
1456					NFSVNO_SETEXRDONLY(&nes);
1457				else
1458					NFSVNO_EXINIT(&nes);
1459				nd->nd_repstat = nfsvno_accchk(vp,
1460				    VWRITE, cred, &nes, p,
1461				    NFSACCCHK_NOOVERRIDE,
1462				    NFSACCCHK_VPISLOCKED, NULL);
1463				nd->nd_repstat = nfsrv_opencheck(clientid,
1464				    stateidp, stp, vp, nd, p, nd->nd_repstat);
1465				if (!nd->nd_repstat) {
1466					tempsize = nvap->na_size;
1467					NFSVNO_ATTRINIT(nvap);
1468					nvap->na_size = tempsize;
1469					nd->nd_repstat = VOP_SETATTR(vp,
1470					    &nvap->na_vattr, cred);
1471				}
1472			} else if (vp->v_type == VREG) {
1473				nd->nd_repstat = nfsrv_opencheck(clientid,
1474				    stateidp, stp, vp, nd, p, nd->nd_repstat);
1475			}
1476		}
1477	} else {
1478		if (ndp->ni_cnd.cn_flags & HASBUF)
1479			nfsvno_relpathbuf(ndp);
1480		if (ndp->ni_startdir && create == NFSV4OPEN_CREATE) {
1481			vrele(ndp->ni_startdir);
1482			if (ndp->ni_dvp == ndp->ni_vp)
1483				vrele(ndp->ni_dvp);
1484			else
1485				vput(ndp->ni_dvp);
1486			if (ndp->ni_vp)
1487				vput(ndp->ni_vp);
1488		}
1489	}
1490	*vpp = vp;
1491
1492	NFSEXITCODE2(0, nd);
1493}
1494
1495/*
1496 * Updates the file rev and sets the mtime and ctime
1497 * to the current clock time, returning the va_filerev and va_Xtime
1498 * values.
1499 * Return ESTALE to indicate the vnode is VI_DOOMED.
1500 */
1501int
1502nfsvno_updfilerev(struct vnode *vp, struct nfsvattr *nvap,
1503    struct ucred *cred, struct thread *p)
1504{
1505	struct vattr va;
1506
1507	VATTR_NULL(&va);
1508	vfs_timestamp(&va.va_mtime);
1509	if (NFSVOPISLOCKED(vp) != LK_EXCLUSIVE) {
1510		NFSVOPLOCK(vp, LK_UPGRADE | LK_RETRY);
1511		if ((vp->v_iflag & VI_DOOMED) != 0)
1512			return (ESTALE);
1513	}
1514	(void) VOP_SETATTR(vp, &va, cred);
1515	(void) nfsvno_getattr(vp, nvap, cred, p, 1);
1516	return (0);
1517}
1518
1519/*
1520 * Glue routine to nfsv4_fillattr().
1521 */
1522int
1523nfsvno_fillattr(struct nfsrv_descript *nd, struct mount *mp, struct vnode *vp,
1524    struct nfsvattr *nvap, fhandle_t *fhp, int rderror, nfsattrbit_t *attrbitp,
1525    struct ucred *cred, struct thread *p, int isdgram, int reterr,
1526    int supports_nfsv4acls, int at_root, uint64_t mounted_on_fileno)
1527{
1528	int error;
1529
1530	error = nfsv4_fillattr(nd, mp, vp, NULL, &nvap->na_vattr, fhp, rderror,
1531	    attrbitp, cred, p, isdgram, reterr, supports_nfsv4acls, at_root,
1532	    mounted_on_fileno);
1533	NFSEXITCODE2(0, nd);
1534	return (error);
1535}
1536
1537/* Since the Readdir vnode ops vary, put the entire functions in here. */
1538/*
1539 * nfs readdir service
1540 * - mallocs what it thinks is enough to read
1541 *	count rounded up to a multiple of DIRBLKSIZ <= NFS_MAXREADDIR
1542 * - calls VOP_READDIR()
1543 * - loops around building the reply
1544 *	if the output generated exceeds count break out of loop
1545 *	The NFSM_CLGET macro is used here so that the reply will be packed
1546 *	tightly in mbuf clusters.
1547 * - it trims out records with d_fileno == 0
1548 *	this doesn't matter for Unix clients, but they might confuse clients
1549 *	for other os'.
1550 * - it trims out records with d_type == DT_WHT
1551 *	these cannot be seen through NFS (unless we extend the protocol)
1552 *     The alternate call nfsrvd_readdirplus() does lookups as well.
1553 * PS: The NFS protocol spec. does not clarify what the "count" byte
1554 *	argument is a count of.. just name strings and file id's or the
1555 *	entire reply rpc or ...
1556 *	I tried just file name and id sizes and it confused the Sun client,
1557 *	so I am using the full rpc size now. The "paranoia.." comment refers
1558 *	to including the status longwords that are not a part of the dir.
1559 *	"entry" structures, but are in the rpc.
1560 */
1561int
1562nfsrvd_readdir(struct nfsrv_descript *nd, int isdgram,
1563    struct vnode *vp, struct thread *p, struct nfsexstuff *exp)
1564{
1565	struct dirent *dp;
1566	u_int32_t *tl;
1567	int dirlen;
1568	char *cpos, *cend, *rbuf;
1569	struct nfsvattr at;
1570	int nlen, error = 0, getret = 1;
1571	int siz, cnt, fullsiz, eofflag, ncookies;
1572	u_int64_t off, toff, verf;
1573	u_long *cookies = NULL, *cookiep;
1574	struct uio io;
1575	struct iovec iv;
1576	int is_ufs;
1577
1578	if (nd->nd_repstat) {
1579		nfsrv_postopattr(nd, getret, &at);
1580		goto out;
1581	}
1582	if (nd->nd_flag & ND_NFSV2) {
1583		NFSM_DISSECT(tl, u_int32_t *, 2 * NFSX_UNSIGNED);
1584		off = fxdr_unsigned(u_quad_t, *tl++);
1585	} else {
1586		NFSM_DISSECT(tl, u_int32_t *, 5 * NFSX_UNSIGNED);
1587		off = fxdr_hyper(tl);
1588		tl += 2;
1589		verf = fxdr_hyper(tl);
1590		tl += 2;
1591	}
1592	toff = off;
1593	cnt = fxdr_unsigned(int, *tl);
1594	if (cnt > NFS_SRVMAXDATA(nd) || cnt < 0)
1595		cnt = NFS_SRVMAXDATA(nd);
1596	siz = ((cnt + DIRBLKSIZ - 1) & ~(DIRBLKSIZ - 1));
1597	fullsiz = siz;
1598	if (nd->nd_flag & ND_NFSV3) {
1599		nd->nd_repstat = getret = nfsvno_getattr(vp, &at, nd->nd_cred,
1600		    p, 1);
1601#if 0
1602		/*
1603		 * va_filerev is not sufficient as a cookie verifier,
1604		 * since it is not supposed to change when entries are
1605		 * removed/added unless that offset cookies returned to
1606		 * the client are no longer valid.
1607		 */
1608		if (!nd->nd_repstat && toff && verf != at.na_filerev)
1609			nd->nd_repstat = NFSERR_BAD_COOKIE;
1610#endif
1611	}
1612	if (!nd->nd_repstat && vp->v_type != VDIR)
1613		nd->nd_repstat = NFSERR_NOTDIR;
1614	if (nd->nd_repstat == 0 && cnt == 0) {
1615		if (nd->nd_flag & ND_NFSV2)
1616			/* NFSv2 does not have NFSERR_TOOSMALL */
1617			nd->nd_repstat = EPERM;
1618		else
1619			nd->nd_repstat = NFSERR_TOOSMALL;
1620	}
1621	if (!nd->nd_repstat)
1622		nd->nd_repstat = nfsvno_accchk(vp, VEXEC,
1623		    nd->nd_cred, exp, p, NFSACCCHK_NOOVERRIDE,
1624		    NFSACCCHK_VPISLOCKED, NULL);
1625	if (nd->nd_repstat) {
1626		vput(vp);
1627		if (nd->nd_flag & ND_NFSV3)
1628			nfsrv_postopattr(nd, getret, &at);
1629		goto out;
1630	}
1631	is_ufs = strcmp(vp->v_mount->mnt_vfc->vfc_name, "ufs") == 0;
1632	MALLOC(rbuf, caddr_t, siz, M_TEMP, M_WAITOK);
1633again:
1634	eofflag = 0;
1635	if (cookies) {
1636		free((caddr_t)cookies, M_TEMP);
1637		cookies = NULL;
1638	}
1639
1640	iv.iov_base = rbuf;
1641	iv.iov_len = siz;
1642	io.uio_iov = &iv;
1643	io.uio_iovcnt = 1;
1644	io.uio_offset = (off_t)off;
1645	io.uio_resid = siz;
1646	io.uio_segflg = UIO_SYSSPACE;
1647	io.uio_rw = UIO_READ;
1648	io.uio_td = NULL;
1649	nd->nd_repstat = VOP_READDIR(vp, &io, nd->nd_cred, &eofflag, &ncookies,
1650	    &cookies);
1651	off = (u_int64_t)io.uio_offset;
1652	if (io.uio_resid)
1653		siz -= io.uio_resid;
1654
1655	if (!cookies && !nd->nd_repstat)
1656		nd->nd_repstat = NFSERR_PERM;
1657	if (nd->nd_flag & ND_NFSV3) {
1658		getret = nfsvno_getattr(vp, &at, nd->nd_cred, p, 1);
1659		if (!nd->nd_repstat)
1660			nd->nd_repstat = getret;
1661	}
1662
1663	/*
1664	 * Handles the failed cases. nd->nd_repstat == 0 past here.
1665	 */
1666	if (nd->nd_repstat) {
1667		vput(vp);
1668		free((caddr_t)rbuf, M_TEMP);
1669		if (cookies)
1670			free((caddr_t)cookies, M_TEMP);
1671		if (nd->nd_flag & ND_NFSV3)
1672			nfsrv_postopattr(nd, getret, &at);
1673		goto out;
1674	}
1675	/*
1676	 * If nothing read, return eof
1677	 * rpc reply
1678	 */
1679	if (siz == 0) {
1680		vput(vp);
1681		if (nd->nd_flag & ND_NFSV2) {
1682			NFSM_BUILD(tl, u_int32_t *, 2 * NFSX_UNSIGNED);
1683		} else {
1684			nfsrv_postopattr(nd, getret, &at);
1685			NFSM_BUILD(tl, u_int32_t *, 4 * NFSX_UNSIGNED);
1686			txdr_hyper(at.na_filerev, tl);
1687			tl += 2;
1688		}
1689		*tl++ = newnfs_false;
1690		*tl = newnfs_true;
1691		FREE((caddr_t)rbuf, M_TEMP);
1692		FREE((caddr_t)cookies, M_TEMP);
1693		goto out;
1694	}
1695
1696	/*
1697	 * Check for degenerate cases of nothing useful read.
1698	 * If so go try again
1699	 */
1700	cpos = rbuf;
1701	cend = rbuf + siz;
1702	dp = (struct dirent *)cpos;
1703	cookiep = cookies;
1704
1705	/*
1706	 * For some reason FreeBSD's ufs_readdir() chooses to back the
1707	 * directory offset up to a block boundary, so it is necessary to
1708	 * skip over the records that precede the requested offset. This
1709	 * requires the assumption that file offset cookies monotonically
1710	 * increase.
1711	 */
1712	while (cpos < cend && ncookies > 0 &&
1713	    (dp->d_fileno == 0 || dp->d_type == DT_WHT ||
1714	     (is_ufs == 1 && ((u_quad_t)(*cookiep)) <= toff))) {
1715		cpos += dp->d_reclen;
1716		dp = (struct dirent *)cpos;
1717		cookiep++;
1718		ncookies--;
1719	}
1720	if (cpos >= cend || ncookies == 0) {
1721		siz = fullsiz;
1722		toff = off;
1723		goto again;
1724	}
1725	vput(vp);
1726
1727	/*
1728	 * dirlen is the size of the reply, including all XDR and must
1729	 * not exceed cnt. For NFSv2, RFC1094 didn't clearly indicate
1730	 * if the XDR should be included in "count", but to be safe, we do.
1731	 * (Include the two booleans at the end of the reply in dirlen now.)
1732	 */
1733	if (nd->nd_flag & ND_NFSV3) {
1734		nfsrv_postopattr(nd, getret, &at);
1735		NFSM_BUILD(tl, u_int32_t *, 2 * NFSX_UNSIGNED);
1736		txdr_hyper(at.na_filerev, tl);
1737		dirlen = NFSX_V3POSTOPATTR + NFSX_VERF + 2 * NFSX_UNSIGNED;
1738	} else {
1739		dirlen = 2 * NFSX_UNSIGNED;
1740	}
1741
1742	/* Loop through the records and build reply */
1743	while (cpos < cend && ncookies > 0) {
1744		nlen = dp->d_namlen;
1745		if (dp->d_fileno != 0 && dp->d_type != DT_WHT &&
1746			nlen <= NFS_MAXNAMLEN) {
1747			if (nd->nd_flag & ND_NFSV3)
1748				dirlen += (6*NFSX_UNSIGNED + NFSM_RNDUP(nlen));
1749			else
1750				dirlen += (4*NFSX_UNSIGNED + NFSM_RNDUP(nlen));
1751			if (dirlen > cnt) {
1752				eofflag = 0;
1753				break;
1754			}
1755
1756			/*
1757			 * Build the directory record xdr from
1758			 * the dirent entry.
1759			 */
1760			if (nd->nd_flag & ND_NFSV3) {
1761				NFSM_BUILD(tl, u_int32_t *, 3 * NFSX_UNSIGNED);
1762				*tl++ = newnfs_true;
1763				*tl++ = 0;
1764			} else {
1765				NFSM_BUILD(tl, u_int32_t *, 2 * NFSX_UNSIGNED);
1766				*tl++ = newnfs_true;
1767			}
1768			*tl = txdr_unsigned(dp->d_fileno);
1769			(void) nfsm_strtom(nd, dp->d_name, nlen);
1770			if (nd->nd_flag & ND_NFSV3) {
1771				NFSM_BUILD(tl, u_int32_t *, 2 * NFSX_UNSIGNED);
1772				*tl++ = 0;
1773			} else
1774				NFSM_BUILD(tl, u_int32_t *, NFSX_UNSIGNED);
1775			*tl = txdr_unsigned(*cookiep);
1776		}
1777		cpos += dp->d_reclen;
1778		dp = (struct dirent *)cpos;
1779		cookiep++;
1780		ncookies--;
1781	}
1782	if (cpos < cend)
1783		eofflag = 0;
1784	NFSM_BUILD(tl, u_int32_t *, 2 * NFSX_UNSIGNED);
1785	*tl++ = newnfs_false;
1786	if (eofflag)
1787		*tl = newnfs_true;
1788	else
1789		*tl = newnfs_false;
1790	FREE((caddr_t)rbuf, M_TEMP);
1791	FREE((caddr_t)cookies, M_TEMP);
1792
1793out:
1794	NFSEXITCODE2(0, nd);
1795	return (0);
1796nfsmout:
1797	vput(vp);
1798	NFSEXITCODE2(error, nd);
1799	return (error);
1800}
1801
1802/*
1803 * Readdirplus for V3 and Readdir for V4.
1804 */
1805int
1806nfsrvd_readdirplus(struct nfsrv_descript *nd, int isdgram,
1807    struct vnode *vp, struct thread *p, struct nfsexstuff *exp)
1808{
1809	struct dirent *dp;
1810	u_int32_t *tl;
1811	int dirlen;
1812	char *cpos, *cend, *rbuf;
1813	struct vnode *nvp;
1814	fhandle_t nfh;
1815	struct nfsvattr nva, at, *nvap = &nva;
1816	struct mbuf *mb0, *mb1;
1817	struct nfsreferral *refp;
1818	int nlen, r, error = 0, getret = 1, usevget = 1;
1819	int siz, cnt, fullsiz, eofflag, ncookies, entrycnt;
1820	caddr_t bpos0, bpos1;
1821	u_int64_t off, toff, verf;
1822	u_long *cookies = NULL, *cookiep;
1823	nfsattrbit_t attrbits, rderrbits, savbits;
1824	struct uio io;
1825	struct iovec iv;
1826	struct componentname cn;
1827	int at_root, is_ufs, is_zfs, needs_unbusy, supports_nfsv4acls;
1828	struct mount *mp, *new_mp;
1829	uint64_t mounted_on_fileno;
1830
1831	if (nd->nd_repstat) {
1832		nfsrv_postopattr(nd, getret, &at);
1833		goto out;
1834	}
1835	NFSM_DISSECT(tl, u_int32_t *, 6 * NFSX_UNSIGNED);
1836	off = fxdr_hyper(tl);
1837	toff = off;
1838	tl += 2;
1839	verf = fxdr_hyper(tl);
1840	tl += 2;
1841	siz = fxdr_unsigned(int, *tl++);
1842	cnt = fxdr_unsigned(int, *tl);
1843
1844	/*
1845	 * Use the server's maximum data transfer size as the upper bound
1846	 * on reply datalen.
1847	 */
1848	if (cnt > NFS_SRVMAXDATA(nd) || cnt < 0)
1849		cnt = NFS_SRVMAXDATA(nd);
1850
1851	/*
1852	 * siz is a "hint" of how much directory information (name, fileid,
1853	 * cookie) should be in the reply. At least one client "hints" 0,
1854	 * so I set it to cnt for that case. I also round it up to the
1855	 * next multiple of DIRBLKSIZ.
1856	 */
1857	if (siz <= 0)
1858		siz = cnt;
1859	siz = ((siz + DIRBLKSIZ - 1) & ~(DIRBLKSIZ - 1));
1860
1861	if (nd->nd_flag & ND_NFSV4) {
1862		error = nfsrv_getattrbits(nd, &attrbits, NULL, NULL);
1863		if (error)
1864			goto nfsmout;
1865		NFSSET_ATTRBIT(&savbits, &attrbits);
1866		NFSCLRNOTFILLABLE_ATTRBIT(&attrbits, nd);
1867		NFSZERO_ATTRBIT(&rderrbits);
1868		NFSSETBIT_ATTRBIT(&rderrbits, NFSATTRBIT_RDATTRERROR);
1869	} else {
1870		NFSZERO_ATTRBIT(&attrbits);
1871	}
1872	fullsiz = siz;
1873	nd->nd_repstat = getret = nfsvno_getattr(vp, &at, nd->nd_cred, p, 1);
1874#if 0
1875	if (!nd->nd_repstat) {
1876	    if (off && verf != at.na_filerev) {
1877		/*
1878		 * va_filerev is not sufficient as a cookie verifier,
1879		 * since it is not supposed to change when entries are
1880		 * removed/added unless that offset cookies returned to
1881		 * the client are no longer valid.
1882		 */
1883		if (nd->nd_flag & ND_NFSV4) {
1884			nd->nd_repstat = NFSERR_NOTSAME;
1885		} else {
1886			nd->nd_repstat = NFSERR_BAD_COOKIE;
1887		}
1888	    }
1889	}
1890#endif
1891	if (!nd->nd_repstat && vp->v_type != VDIR)
1892		nd->nd_repstat = NFSERR_NOTDIR;
1893	if (!nd->nd_repstat && cnt == 0)
1894		nd->nd_repstat = NFSERR_TOOSMALL;
1895	if (!nd->nd_repstat)
1896		nd->nd_repstat = nfsvno_accchk(vp, VEXEC,
1897		    nd->nd_cred, exp, p, NFSACCCHK_NOOVERRIDE,
1898		    NFSACCCHK_VPISLOCKED, NULL);
1899	if (nd->nd_repstat) {
1900		vput(vp);
1901		if (nd->nd_flag & ND_NFSV3)
1902			nfsrv_postopattr(nd, getret, &at);
1903		goto out;
1904	}
1905	is_ufs = strcmp(vp->v_mount->mnt_vfc->vfc_name, "ufs") == 0;
1906	is_zfs = strcmp(vp->v_mount->mnt_vfc->vfc_name, "zfs") == 0;
1907
1908	MALLOC(rbuf, caddr_t, siz, M_TEMP, M_WAITOK);
1909again:
1910	eofflag = 0;
1911	if (cookies) {
1912		free((caddr_t)cookies, M_TEMP);
1913		cookies = NULL;
1914	}
1915
1916	iv.iov_base = rbuf;
1917	iv.iov_len = siz;
1918	io.uio_iov = &iv;
1919	io.uio_iovcnt = 1;
1920	io.uio_offset = (off_t)off;
1921	io.uio_resid = siz;
1922	io.uio_segflg = UIO_SYSSPACE;
1923	io.uio_rw = UIO_READ;
1924	io.uio_td = NULL;
1925	nd->nd_repstat = VOP_READDIR(vp, &io, nd->nd_cred, &eofflag, &ncookies,
1926	    &cookies);
1927	off = (u_int64_t)io.uio_offset;
1928	if (io.uio_resid)
1929		siz -= io.uio_resid;
1930
1931	getret = nfsvno_getattr(vp, &at, nd->nd_cred, p, 1);
1932
1933	if (!cookies && !nd->nd_repstat)
1934		nd->nd_repstat = NFSERR_PERM;
1935	if (!nd->nd_repstat)
1936		nd->nd_repstat = getret;
1937	if (nd->nd_repstat) {
1938		vput(vp);
1939		if (cookies)
1940			free((caddr_t)cookies, M_TEMP);
1941		free((caddr_t)rbuf, M_TEMP);
1942		if (nd->nd_flag & ND_NFSV3)
1943			nfsrv_postopattr(nd, getret, &at);
1944		goto out;
1945	}
1946	/*
1947	 * If nothing read, return eof
1948	 * rpc reply
1949	 */
1950	if (siz == 0) {
1951		vput(vp);
1952		if (nd->nd_flag & ND_NFSV3)
1953			nfsrv_postopattr(nd, getret, &at);
1954		NFSM_BUILD(tl, u_int32_t *, 4 * NFSX_UNSIGNED);
1955		txdr_hyper(at.na_filerev, tl);
1956		tl += 2;
1957		*tl++ = newnfs_false;
1958		*tl = newnfs_true;
1959		free((caddr_t)cookies, M_TEMP);
1960		free((caddr_t)rbuf, M_TEMP);
1961		goto out;
1962	}
1963
1964	/*
1965	 * Check for degenerate cases of nothing useful read.
1966	 * If so go try again
1967	 */
1968	cpos = rbuf;
1969	cend = rbuf + siz;
1970	dp = (struct dirent *)cpos;
1971	cookiep = cookies;
1972
1973	/*
1974	 * For some reason FreeBSD's ufs_readdir() chooses to back the
1975	 * directory offset up to a block boundary, so it is necessary to
1976	 * skip over the records that precede the requested offset. This
1977	 * requires the assumption that file offset cookies monotonically
1978	 * increase.
1979	 */
1980	while (cpos < cend && ncookies > 0 &&
1981	  (dp->d_fileno == 0 || dp->d_type == DT_WHT ||
1982	   (is_ufs == 1 && ((u_quad_t)(*cookiep)) <= toff) ||
1983	   ((nd->nd_flag & ND_NFSV4) &&
1984	    ((dp->d_namlen == 1 && dp->d_name[0] == '.') ||
1985	     (dp->d_namlen==2 && dp->d_name[0]=='.' && dp->d_name[1]=='.'))))) {
1986		cpos += dp->d_reclen;
1987		dp = (struct dirent *)cpos;
1988		cookiep++;
1989		ncookies--;
1990	}
1991	if (cpos >= cend || ncookies == 0) {
1992		siz = fullsiz;
1993		toff = off;
1994		goto again;
1995	}
1996
1997	/*
1998	 * Busy the file system so that the mount point won't go away
1999	 * and, as such, VFS_VGET() can be used safely.
2000	 */
2001	mp = vp->v_mount;
2002	vfs_ref(mp);
2003	NFSVOPUNLOCK(vp, 0);
2004	nd->nd_repstat = vfs_busy(mp, 0);
2005	vfs_rel(mp);
2006	if (nd->nd_repstat != 0) {
2007		vrele(vp);
2008		free(cookies, M_TEMP);
2009		free(rbuf, M_TEMP);
2010		if (nd->nd_flag & ND_NFSV3)
2011			nfsrv_postopattr(nd, getret, &at);
2012		goto out;
2013	}
2014
2015	/*
2016	 * For now ZFS requires VOP_LOOKUP as a workaround.  Until ino_t is changed
2017	 * to 64 bit type a ZFS filesystem with over 1 billion files in it
2018	 * will suffer from 64bit -> 32bit truncation.
2019	 */
2020	if (is_zfs == 1)
2021		usevget = 0;
2022
2023	cn.cn_nameiop = LOOKUP;
2024	cn.cn_lkflags = LK_SHARED | LK_RETRY;
2025	cn.cn_cred = nd->nd_cred;
2026	cn.cn_thread = p;
2027
2028	/*
2029	 * Save this position, in case there is an error before one entry
2030	 * is created.
2031	 */
2032	mb0 = nd->nd_mb;
2033	bpos0 = nd->nd_bpos;
2034
2035	/*
2036	 * Fill in the first part of the reply.
2037	 * dirlen is the reply length in bytes and cannot exceed cnt.
2038	 * (Include the two booleans at the end of the reply in dirlen now,
2039	 *  so we recognize when we have exceeded cnt.)
2040	 */
2041	if (nd->nd_flag & ND_NFSV3) {
2042		dirlen = NFSX_V3POSTOPATTR + NFSX_VERF + 2 * NFSX_UNSIGNED;
2043		nfsrv_postopattr(nd, getret, &at);
2044	} else {
2045		dirlen = NFSX_VERF + 2 * NFSX_UNSIGNED;
2046	}
2047	NFSM_BUILD(tl, u_int32_t *, NFSX_VERF);
2048	txdr_hyper(at.na_filerev, tl);
2049
2050	/*
2051	 * Save this position, in case there is an empty reply needed.
2052	 */
2053	mb1 = nd->nd_mb;
2054	bpos1 = nd->nd_bpos;
2055
2056	/* Loop through the records and build reply */
2057	entrycnt = 0;
2058	while (cpos < cend && ncookies > 0 && dirlen < cnt) {
2059		nlen = dp->d_namlen;
2060		if (dp->d_fileno != 0 && dp->d_type != DT_WHT &&
2061		    nlen <= NFS_MAXNAMLEN &&
2062		    ((nd->nd_flag & ND_NFSV3) || nlen > 2 ||
2063		     (nlen==2 && (dp->d_name[0]!='.' || dp->d_name[1]!='.'))
2064		      || (nlen == 1 && dp->d_name[0] != '.'))) {
2065			/*
2066			 * Save the current position in the reply, in case
2067			 * this entry exceeds cnt.
2068			 */
2069			mb1 = nd->nd_mb;
2070			bpos1 = nd->nd_bpos;
2071
2072			/*
2073			 * For readdir_and_lookup get the vnode using
2074			 * the file number.
2075			 */
2076			nvp = NULL;
2077			refp = NULL;
2078			r = 0;
2079			at_root = 0;
2080			needs_unbusy = 0;
2081			new_mp = mp;
2082			mounted_on_fileno = (uint64_t)dp->d_fileno;
2083			if ((nd->nd_flag & ND_NFSV3) ||
2084			    NFSNONZERO_ATTRBIT(&savbits)) {
2085				if (nd->nd_flag & ND_NFSV4)
2086					refp = nfsv4root_getreferral(NULL,
2087					    vp, dp->d_fileno);
2088				if (refp == NULL) {
2089					if (usevget)
2090						r = VFS_VGET(mp, dp->d_fileno,
2091						    LK_SHARED, &nvp);
2092					else
2093						r = EOPNOTSUPP;
2094					if (r == EOPNOTSUPP) {
2095						usevget = 0;
2096						cn.cn_nameptr = dp->d_name;
2097						cn.cn_namelen = nlen;
2098						cn.cn_flags = ISLASTCN |
2099						    NOFOLLOW | LOCKLEAF;
2100						if (nlen == 2 &&
2101						    dp->d_name[0] == '.' &&
2102						    dp->d_name[1] == '.')
2103							cn.cn_flags |=
2104							    ISDOTDOT;
2105						if (NFSVOPLOCK(vp, LK_SHARED)
2106						    != 0) {
2107							nd->nd_repstat = EPERM;
2108							break;
2109						}
2110						if ((vp->v_vflag & VV_ROOT) != 0
2111						    && (cn.cn_flags & ISDOTDOT)
2112						    != 0) {
2113							vref(vp);
2114							nvp = vp;
2115							r = 0;
2116						} else {
2117							r = VOP_LOOKUP(vp, &nvp,
2118							    &cn);
2119							if (vp != nvp)
2120								NFSVOPUNLOCK(vp,
2121								    0);
2122						}
2123					}
2124
2125					/*
2126					 * For NFSv4, check to see if nvp is
2127					 * a mount point and get the mount
2128					 * point vnode, as required.
2129					 */
2130					if (r == 0 &&
2131					    nfsrv_enable_crossmntpt != 0 &&
2132					    (nd->nd_flag & ND_NFSV4) != 0 &&
2133					    nvp->v_type == VDIR &&
2134					    nvp->v_mountedhere != NULL) {
2135						new_mp = nvp->v_mountedhere;
2136						r = vfs_busy(new_mp, 0);
2137						vput(nvp);
2138						nvp = NULL;
2139						if (r == 0) {
2140							r = VFS_ROOT(new_mp,
2141							    LK_SHARED, &nvp);
2142							needs_unbusy = 1;
2143							if (r == 0)
2144								at_root = 1;
2145						}
2146					}
2147				}
2148
2149				/*
2150				 * If we failed to look up the entry, then it
2151				 * has become invalid, most likely removed.
2152				 */
2153				if (r != 0) {
2154					if (needs_unbusy)
2155						vfs_unbusy(new_mp);
2156					goto invalid;
2157				}
2158				KASSERT(refp != NULL || nvp != NULL,
2159				    ("%s: undetected lookup error", __func__));
2160
2161				if (refp == NULL &&
2162				    ((nd->nd_flag & ND_NFSV3) ||
2163				     NFSNONZERO_ATTRBIT(&attrbits))) {
2164					r = nfsvno_getfh(nvp, &nfh, p);
2165					if (!r)
2166					    r = nfsvno_getattr(nvp, nvap,
2167						nd->nd_cred, p, 1);
2168					if (r == 0 && is_zfs == 1 &&
2169					    nfsrv_enable_crossmntpt != 0 &&
2170					    (nd->nd_flag & ND_NFSV4) != 0 &&
2171					    nvp->v_type == VDIR &&
2172					    vp->v_mount != nvp->v_mount) {
2173					    /*
2174					     * For a ZFS snapshot, there is a
2175					     * pseudo mount that does not set
2176					     * v_mountedhere, so it needs to
2177					     * be detected via a different
2178					     * mount structure.
2179					     */
2180					    at_root = 1;
2181					    if (new_mp == mp)
2182						new_mp = nvp->v_mount;
2183					}
2184				}
2185
2186				/*
2187				 * If we failed to get attributes of the entry,
2188				 * then just skip it for NFSv3 (the traditional
2189				 * behavior in the old NFS server).
2190				 * For NFSv4 the behavior is controlled by
2191				 * RDATTRERROR: we either ignore the error or
2192				 * fail the request.
2193				 * Note that RDATTRERROR is never set for NFSv3.
2194				 */
2195				if (r != 0) {
2196					if (!NFSISSET_ATTRBIT(&attrbits,
2197					    NFSATTRBIT_RDATTRERROR)) {
2198						vput(nvp);
2199						if (needs_unbusy != 0)
2200							vfs_unbusy(new_mp);
2201						if ((nd->nd_flag & ND_NFSV3))
2202							goto invalid;
2203						nd->nd_repstat = r;
2204						break;
2205					}
2206				}
2207			}
2208
2209			/*
2210			 * Build the directory record xdr
2211			 */
2212			if (nd->nd_flag & ND_NFSV3) {
2213				NFSM_BUILD(tl, u_int32_t *, 3 * NFSX_UNSIGNED);
2214				*tl++ = newnfs_true;
2215				*tl++ = 0;
2216				*tl = txdr_unsigned(dp->d_fileno);
2217				dirlen += nfsm_strtom(nd, dp->d_name, nlen);
2218				NFSM_BUILD(tl, u_int32_t *, 2 * NFSX_UNSIGNED);
2219				*tl++ = 0;
2220				*tl = txdr_unsigned(*cookiep);
2221				nfsrv_postopattr(nd, 0, nvap);
2222				dirlen += nfsm_fhtom(nd,(u_int8_t *)&nfh,0,1);
2223				dirlen += (5*NFSX_UNSIGNED+NFSX_V3POSTOPATTR);
2224				if (nvp != NULL)
2225					vput(nvp);
2226			} else {
2227				NFSM_BUILD(tl, u_int32_t *, 3 * NFSX_UNSIGNED);
2228				*tl++ = newnfs_true;
2229				*tl++ = 0;
2230				*tl = txdr_unsigned(*cookiep);
2231				dirlen += nfsm_strtom(nd, dp->d_name, nlen);
2232				if (nvp != NULL) {
2233					supports_nfsv4acls =
2234					    nfs_supportsnfsv4acls(nvp);
2235					NFSVOPUNLOCK(nvp, 0);
2236				} else
2237					supports_nfsv4acls = 0;
2238				if (refp != NULL) {
2239					dirlen += nfsrv_putreferralattr(nd,
2240					    &savbits, refp, 0,
2241					    &nd->nd_repstat);
2242					if (nd->nd_repstat) {
2243						if (nvp != NULL)
2244							vrele(nvp);
2245						if (needs_unbusy != 0)
2246							vfs_unbusy(new_mp);
2247						break;
2248					}
2249				} else if (r) {
2250					dirlen += nfsvno_fillattr(nd, new_mp,
2251					    nvp, nvap, &nfh, r, &rderrbits,
2252					    nd->nd_cred, p, isdgram, 0,
2253					    supports_nfsv4acls, at_root,
2254					    mounted_on_fileno);
2255				} else {
2256					dirlen += nfsvno_fillattr(nd, new_mp,
2257					    nvp, nvap, &nfh, r, &attrbits,
2258					    nd->nd_cred, p, isdgram, 0,
2259					    supports_nfsv4acls, at_root,
2260					    mounted_on_fileno);
2261				}
2262				if (nvp != NULL)
2263					vrele(nvp);
2264				dirlen += (3 * NFSX_UNSIGNED);
2265			}
2266			if (needs_unbusy != 0)
2267				vfs_unbusy(new_mp);
2268			if (dirlen <= cnt)
2269				entrycnt++;
2270		}
2271invalid:
2272		cpos += dp->d_reclen;
2273		dp = (struct dirent *)cpos;
2274		cookiep++;
2275		ncookies--;
2276	}
2277	vrele(vp);
2278	vfs_unbusy(mp);
2279
2280	/*
2281	 * If dirlen > cnt, we must strip off the last entry. If that
2282	 * results in an empty reply, report NFSERR_TOOSMALL.
2283	 */
2284	if (dirlen > cnt || nd->nd_repstat) {
2285		if (!nd->nd_repstat && entrycnt == 0)
2286			nd->nd_repstat = NFSERR_TOOSMALL;
2287		if (nd->nd_repstat) {
2288			newnfs_trimtrailing(nd, mb0, bpos0);
2289			if (nd->nd_flag & ND_NFSV3)
2290				nfsrv_postopattr(nd, getret, &at);
2291		} else
2292			newnfs_trimtrailing(nd, mb1, bpos1);
2293		eofflag = 0;
2294	} else if (cpos < cend)
2295		eofflag = 0;
2296	if (!nd->nd_repstat) {
2297		NFSM_BUILD(tl, u_int32_t *, 2 * NFSX_UNSIGNED);
2298		*tl++ = newnfs_false;
2299		if (eofflag)
2300			*tl = newnfs_true;
2301		else
2302			*tl = newnfs_false;
2303	}
2304	FREE((caddr_t)cookies, M_TEMP);
2305	FREE((caddr_t)rbuf, M_TEMP);
2306
2307out:
2308	NFSEXITCODE2(0, nd);
2309	return (0);
2310nfsmout:
2311	vput(vp);
2312	NFSEXITCODE2(error, nd);
2313	return (error);
2314}
2315
2316/*
2317 * Get the settable attributes out of the mbuf list.
2318 * (Return 0 or EBADRPC)
2319 */
2320int
2321nfsrv_sattr(struct nfsrv_descript *nd, struct nfsvattr *nvap,
2322    nfsattrbit_t *attrbitp, NFSACL_T *aclp, struct thread *p)
2323{
2324	u_int32_t *tl;
2325	struct nfsv2_sattr *sp;
2326	int error = 0, toclient = 0;
2327
2328	switch (nd->nd_flag & (ND_NFSV2 | ND_NFSV3 | ND_NFSV4)) {
2329	case ND_NFSV2:
2330		NFSM_DISSECT(sp, struct nfsv2_sattr *, NFSX_V2SATTR);
2331		/*
2332		 * Some old clients didn't fill in the high order 16bits.
2333		 * --> check the low order 2 bytes for 0xffff
2334		 */
2335		if ((fxdr_unsigned(int, sp->sa_mode) & 0xffff) != 0xffff)
2336			nvap->na_mode = nfstov_mode(sp->sa_mode);
2337		if (sp->sa_uid != newnfs_xdrneg1)
2338			nvap->na_uid = fxdr_unsigned(uid_t, sp->sa_uid);
2339		if (sp->sa_gid != newnfs_xdrneg1)
2340			nvap->na_gid = fxdr_unsigned(gid_t, sp->sa_gid);
2341		if (sp->sa_size != newnfs_xdrneg1)
2342			nvap->na_size = fxdr_unsigned(u_quad_t, sp->sa_size);
2343		if (sp->sa_atime.nfsv2_sec != newnfs_xdrneg1) {
2344#ifdef notyet
2345			fxdr_nfsv2time(&sp->sa_atime, &nvap->na_atime);
2346#else
2347			nvap->na_atime.tv_sec =
2348				fxdr_unsigned(u_int32_t,sp->sa_atime.nfsv2_sec);
2349			nvap->na_atime.tv_nsec = 0;
2350#endif
2351		}
2352		if (sp->sa_mtime.nfsv2_sec != newnfs_xdrneg1)
2353			fxdr_nfsv2time(&sp->sa_mtime, &nvap->na_mtime);
2354		break;
2355	case ND_NFSV3:
2356		NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
2357		if (*tl == newnfs_true) {
2358			NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
2359			nvap->na_mode = nfstov_mode(*tl);
2360		}
2361		NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
2362		if (*tl == newnfs_true) {
2363			NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
2364			nvap->na_uid = fxdr_unsigned(uid_t, *tl);
2365		}
2366		NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
2367		if (*tl == newnfs_true) {
2368			NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
2369			nvap->na_gid = fxdr_unsigned(gid_t, *tl);
2370		}
2371		NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
2372		if (*tl == newnfs_true) {
2373			NFSM_DISSECT(tl, u_int32_t *, 2 * NFSX_UNSIGNED);
2374			nvap->na_size = fxdr_hyper(tl);
2375		}
2376		NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
2377		switch (fxdr_unsigned(int, *tl)) {
2378		case NFSV3SATTRTIME_TOCLIENT:
2379			NFSM_DISSECT(tl, u_int32_t *, 2 * NFSX_UNSIGNED);
2380			fxdr_nfsv3time(tl, &nvap->na_atime);
2381			toclient = 1;
2382			break;
2383		case NFSV3SATTRTIME_TOSERVER:
2384			vfs_timestamp(&nvap->na_atime);
2385			nvap->na_vaflags |= VA_UTIMES_NULL;
2386			break;
2387		};
2388		NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
2389		switch (fxdr_unsigned(int, *tl)) {
2390		case NFSV3SATTRTIME_TOCLIENT:
2391			NFSM_DISSECT(tl, u_int32_t *, 2 * NFSX_UNSIGNED);
2392			fxdr_nfsv3time(tl, &nvap->na_mtime);
2393			nvap->na_vaflags &= ~VA_UTIMES_NULL;
2394			break;
2395		case NFSV3SATTRTIME_TOSERVER:
2396			vfs_timestamp(&nvap->na_mtime);
2397			if (!toclient)
2398				nvap->na_vaflags |= VA_UTIMES_NULL;
2399			break;
2400		};
2401		break;
2402	case ND_NFSV4:
2403		error = nfsv4_sattr(nd, nvap, attrbitp, aclp, p);
2404	};
2405nfsmout:
2406	NFSEXITCODE2(error, nd);
2407	return (error);
2408}
2409
2410/*
2411 * Handle the setable attributes for V4.
2412 * Returns NFSERR_BADXDR if it can't be parsed, 0 otherwise.
2413 */
2414int
2415nfsv4_sattr(struct nfsrv_descript *nd, struct nfsvattr *nvap,
2416    nfsattrbit_t *attrbitp, NFSACL_T *aclp, struct thread *p)
2417{
2418	u_int32_t *tl;
2419	int attrsum = 0;
2420	int i, j;
2421	int error, attrsize, bitpos, aclsize, aceerr, retnotsup = 0;
2422	int toclient = 0;
2423	u_char *cp, namestr[NFSV4_SMALLSTR + 1];
2424	uid_t uid;
2425	gid_t gid;
2426
2427	error = nfsrv_getattrbits(nd, attrbitp, NULL, &retnotsup);
2428	if (error)
2429		goto nfsmout;
2430	NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
2431	attrsize = fxdr_unsigned(int, *tl);
2432
2433	/*
2434	 * Loop around getting the setable attributes. If an unsupported
2435	 * one is found, set nd_repstat == NFSERR_ATTRNOTSUPP and return.
2436	 */
2437	if (retnotsup) {
2438		nd->nd_repstat = NFSERR_ATTRNOTSUPP;
2439		bitpos = NFSATTRBIT_MAX;
2440	} else {
2441		bitpos = 0;
2442	}
2443	for (; bitpos < NFSATTRBIT_MAX; bitpos++) {
2444	    if (attrsum > attrsize) {
2445		error = NFSERR_BADXDR;
2446		goto nfsmout;
2447	    }
2448	    if (NFSISSET_ATTRBIT(attrbitp, bitpos))
2449		switch (bitpos) {
2450		case NFSATTRBIT_SIZE:
2451			NFSM_DISSECT(tl, u_int32_t *, NFSX_HYPER);
2452			nvap->na_size = fxdr_hyper(tl);
2453			attrsum += NFSX_HYPER;
2454			break;
2455		case NFSATTRBIT_ACL:
2456			error = nfsrv_dissectacl(nd, aclp, &aceerr, &aclsize,
2457			    p);
2458			if (error)
2459				goto nfsmout;
2460			if (aceerr && !nd->nd_repstat)
2461				nd->nd_repstat = aceerr;
2462			attrsum += aclsize;
2463			break;
2464		case NFSATTRBIT_ARCHIVE:
2465			NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
2466			if (!nd->nd_repstat)
2467				nd->nd_repstat = NFSERR_ATTRNOTSUPP;
2468			attrsum += NFSX_UNSIGNED;
2469			break;
2470		case NFSATTRBIT_HIDDEN:
2471			NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
2472			if (!nd->nd_repstat)
2473				nd->nd_repstat = NFSERR_ATTRNOTSUPP;
2474			attrsum += NFSX_UNSIGNED;
2475			break;
2476		case NFSATTRBIT_MIMETYPE:
2477			NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
2478			i = fxdr_unsigned(int, *tl);
2479			error = nfsm_advance(nd, NFSM_RNDUP(i), -1);
2480			if (error)
2481				goto nfsmout;
2482			if (!nd->nd_repstat)
2483				nd->nd_repstat = NFSERR_ATTRNOTSUPP;
2484			attrsum += (NFSX_UNSIGNED + NFSM_RNDUP(i));
2485			break;
2486		case NFSATTRBIT_MODE:
2487			NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
2488			nvap->na_mode = nfstov_mode(*tl);
2489			attrsum += NFSX_UNSIGNED;
2490			break;
2491		case NFSATTRBIT_OWNER:
2492			NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
2493			j = fxdr_unsigned(int, *tl);
2494			if (j < 0) {
2495				error = NFSERR_BADXDR;
2496				goto nfsmout;
2497			}
2498			if (j > NFSV4_SMALLSTR)
2499				cp = malloc(j + 1, M_NFSSTRING, M_WAITOK);
2500			else
2501				cp = namestr;
2502			error = nfsrv_mtostr(nd, cp, j);
2503			if (error) {
2504				if (j > NFSV4_SMALLSTR)
2505					free(cp, M_NFSSTRING);
2506				goto nfsmout;
2507			}
2508			if (!nd->nd_repstat) {
2509				nd->nd_repstat = nfsv4_strtouid(nd, cp, j, &uid,
2510				    p);
2511				if (!nd->nd_repstat)
2512					nvap->na_uid = uid;
2513			}
2514			if (j > NFSV4_SMALLSTR)
2515				free(cp, M_NFSSTRING);
2516			attrsum += (NFSX_UNSIGNED + NFSM_RNDUP(j));
2517			break;
2518		case NFSATTRBIT_OWNERGROUP:
2519			NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
2520			j = fxdr_unsigned(int, *tl);
2521			if (j < 0) {
2522				error = NFSERR_BADXDR;
2523				goto nfsmout;
2524			}
2525			if (j > NFSV4_SMALLSTR)
2526				cp = malloc(j + 1, M_NFSSTRING, M_WAITOK);
2527			else
2528				cp = namestr;
2529			error = nfsrv_mtostr(nd, cp, j);
2530			if (error) {
2531				if (j > NFSV4_SMALLSTR)
2532					free(cp, M_NFSSTRING);
2533				goto nfsmout;
2534			}
2535			if (!nd->nd_repstat) {
2536				nd->nd_repstat = nfsv4_strtogid(nd, cp, j, &gid,
2537				    p);
2538				if (!nd->nd_repstat)
2539					nvap->na_gid = gid;
2540			}
2541			if (j > NFSV4_SMALLSTR)
2542				free(cp, M_NFSSTRING);
2543			attrsum += (NFSX_UNSIGNED + NFSM_RNDUP(j));
2544			break;
2545		case NFSATTRBIT_SYSTEM:
2546			NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
2547			if (!nd->nd_repstat)
2548				nd->nd_repstat = NFSERR_ATTRNOTSUPP;
2549			attrsum += NFSX_UNSIGNED;
2550			break;
2551		case NFSATTRBIT_TIMEACCESSSET:
2552			NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
2553			attrsum += NFSX_UNSIGNED;
2554			if (fxdr_unsigned(int, *tl)==NFSV4SATTRTIME_TOCLIENT) {
2555			    NFSM_DISSECT(tl, u_int32_t *, NFSX_V4TIME);
2556			    fxdr_nfsv4time(tl, &nvap->na_atime);
2557			    toclient = 1;
2558			    attrsum += NFSX_V4TIME;
2559			} else {
2560			    vfs_timestamp(&nvap->na_atime);
2561			    nvap->na_vaflags |= VA_UTIMES_NULL;
2562			}
2563			break;
2564		case NFSATTRBIT_TIMEBACKUP:
2565			NFSM_DISSECT(tl, u_int32_t *, NFSX_V4TIME);
2566			if (!nd->nd_repstat)
2567				nd->nd_repstat = NFSERR_ATTRNOTSUPP;
2568			attrsum += NFSX_V4TIME;
2569			break;
2570		case NFSATTRBIT_TIMECREATE:
2571			NFSM_DISSECT(tl, u_int32_t *, NFSX_V4TIME);
2572			if (!nd->nd_repstat)
2573				nd->nd_repstat = NFSERR_ATTRNOTSUPP;
2574			attrsum += NFSX_V4TIME;
2575			break;
2576		case NFSATTRBIT_TIMEMODIFYSET:
2577			NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
2578			attrsum += NFSX_UNSIGNED;
2579			if (fxdr_unsigned(int, *tl)==NFSV4SATTRTIME_TOCLIENT) {
2580			    NFSM_DISSECT(tl, u_int32_t *, NFSX_V4TIME);
2581			    fxdr_nfsv4time(tl, &nvap->na_mtime);
2582			    nvap->na_vaflags &= ~VA_UTIMES_NULL;
2583			    attrsum += NFSX_V4TIME;
2584			} else {
2585			    vfs_timestamp(&nvap->na_mtime);
2586			    if (!toclient)
2587				nvap->na_vaflags |= VA_UTIMES_NULL;
2588			}
2589			break;
2590		default:
2591			nd->nd_repstat = NFSERR_ATTRNOTSUPP;
2592			/*
2593			 * set bitpos so we drop out of the loop.
2594			 */
2595			bitpos = NFSATTRBIT_MAX;
2596			break;
2597		};
2598	}
2599
2600	/*
2601	 * some clients pad the attrlist, so we need to skip over the
2602	 * padding.
2603	 */
2604	if (attrsum > attrsize) {
2605		error = NFSERR_BADXDR;
2606	} else {
2607		attrsize = NFSM_RNDUP(attrsize);
2608		if (attrsum < attrsize)
2609			error = nfsm_advance(nd, attrsize - attrsum, -1);
2610	}
2611nfsmout:
2612	NFSEXITCODE2(error, nd);
2613	return (error);
2614}
2615
2616/*
2617 * Check/setup export credentials.
2618 */
2619int
2620nfsd_excred(struct nfsrv_descript *nd, struct nfsexstuff *exp,
2621    struct ucred *credanon)
2622{
2623	int error = 0;
2624
2625	/*
2626	 * Check/setup credentials.
2627	 */
2628	if (nd->nd_flag & ND_GSS)
2629		exp->nes_exflag &= ~MNT_EXPORTANON;
2630
2631	/*
2632	 * Check to see if the operation is allowed for this security flavor.
2633	 * RFC2623 suggests that the NFSv3 Fsinfo RPC be allowed to
2634	 * AUTH_NONE or AUTH_SYS for file systems requiring RPCSEC_GSS.
2635	 * Also, allow Secinfo, so that it can acquire the correct flavor(s).
2636	 */
2637	if (nfsvno_testexp(nd, exp) &&
2638	    nd->nd_procnum != NFSV4OP_SECINFO &&
2639	    nd->nd_procnum != NFSPROC_FSINFO) {
2640		if (nd->nd_flag & ND_NFSV4)
2641			error = NFSERR_WRONGSEC;
2642		else
2643			error = (NFSERR_AUTHERR | AUTH_TOOWEAK);
2644		goto out;
2645	}
2646
2647	/*
2648	 * Check to see if the file system is exported V4 only.
2649	 */
2650	if (NFSVNO_EXV4ONLY(exp) && !(nd->nd_flag & ND_NFSV4)) {
2651		error = NFSERR_PROGNOTV4;
2652		goto out;
2653	}
2654
2655	/*
2656	 * Now, map the user credentials.
2657	 * (Note that ND_AUTHNONE will only be set for an NFSv3
2658	 *  Fsinfo RPC. If set for anything else, this code might need
2659	 *  to change.)
2660	 */
2661	if (NFSVNO_EXPORTED(exp)) {
2662		if (((nd->nd_flag & ND_GSS) == 0 && nd->nd_cred->cr_uid == 0) ||
2663		     NFSVNO_EXPORTANON(exp) ||
2664		     (nd->nd_flag & ND_AUTHNONE) != 0) {
2665			nd->nd_cred->cr_uid = credanon->cr_uid;
2666			nd->nd_cred->cr_gid = credanon->cr_gid;
2667			crsetgroups(nd->nd_cred, credanon->cr_ngroups,
2668			    credanon->cr_groups);
2669		} else if ((nd->nd_flag & ND_GSS) == 0) {
2670			/*
2671			 * If using AUTH_SYS, call nfsrv_getgrpscred() to see
2672			 * if there is a replacement credential with a group
2673			 * list set up by "nfsuserd -manage-gids".
2674			 * If there is no replacement, nfsrv_getgrpscred()
2675			 * simply returns its argument.
2676			 */
2677			nd->nd_cred = nfsrv_getgrpscred(nd->nd_cred);
2678		}
2679	}
2680
2681out:
2682	NFSEXITCODE2(error, nd);
2683	return (error);
2684}
2685
2686/*
2687 * Check exports.
2688 */
2689int
2690nfsvno_checkexp(struct mount *mp, struct sockaddr *nam, struct nfsexstuff *exp,
2691    struct ucred **credp)
2692{
2693	int i, error, *secflavors;
2694
2695	error = VFS_CHECKEXP(mp, nam, &exp->nes_exflag, credp,
2696	    &exp->nes_numsecflavor, &secflavors);
2697	if (error) {
2698		if (nfs_rootfhset) {
2699			exp->nes_exflag = 0;
2700			exp->nes_numsecflavor = 0;
2701			error = 0;
2702		}
2703	} else {
2704		/* Copy the security flavors. */
2705		for (i = 0; i < exp->nes_numsecflavor; i++)
2706			exp->nes_secflavors[i] = secflavors[i];
2707	}
2708	NFSEXITCODE(error);
2709	return (error);
2710}
2711
2712/*
2713 * Get a vnode for a file handle and export stuff.
2714 */
2715int
2716nfsvno_fhtovp(struct mount *mp, fhandle_t *fhp, struct sockaddr *nam,
2717    int lktype, struct vnode **vpp, struct nfsexstuff *exp,
2718    struct ucred **credp)
2719{
2720	int i, error, *secflavors;
2721
2722	*credp = NULL;
2723	exp->nes_numsecflavor = 0;
2724	error = VFS_FHTOVP(mp, &fhp->fh_fid, lktype, vpp);
2725	if (error != 0)
2726		/* Make sure the server replies ESTALE to the client. */
2727		error = ESTALE;
2728	if (nam && !error) {
2729		error = VFS_CHECKEXP(mp, nam, &exp->nes_exflag, credp,
2730		    &exp->nes_numsecflavor, &secflavors);
2731		if (error) {
2732			if (nfs_rootfhset) {
2733				exp->nes_exflag = 0;
2734				exp->nes_numsecflavor = 0;
2735				error = 0;
2736			} else {
2737				vput(*vpp);
2738			}
2739		} else {
2740			/* Copy the security flavors. */
2741			for (i = 0; i < exp->nes_numsecflavor; i++)
2742				exp->nes_secflavors[i] = secflavors[i];
2743		}
2744	}
2745	NFSEXITCODE(error);
2746	return (error);
2747}
2748
2749/*
2750 * nfsd_fhtovp() - convert a fh to a vnode ptr
2751 * 	- look up fsid in mount list (if not found ret error)
2752 *	- get vp and export rights by calling nfsvno_fhtovp()
2753 *	- if cred->cr_uid == 0 or MNT_EXPORTANON set it to credanon
2754 *	  for AUTH_SYS
2755 *	- if mpp != NULL, return the mount point so that it can
2756 *	  be used for vn_finished_write() by the caller
2757 */
2758void
2759nfsd_fhtovp(struct nfsrv_descript *nd, struct nfsrvfh *nfp, int lktype,
2760    struct vnode **vpp, struct nfsexstuff *exp,
2761    struct mount **mpp, int startwrite, struct thread *p)
2762{
2763	struct mount *mp;
2764	struct ucred *credanon;
2765	fhandle_t *fhp;
2766
2767	fhp = (fhandle_t *)nfp->nfsrvfh_data;
2768	/*
2769	 * Check for the special case of the nfsv4root_fh.
2770	 */
2771	mp = vfs_busyfs(&fhp->fh_fsid);
2772	if (mpp != NULL)
2773		*mpp = mp;
2774	if (mp == NULL) {
2775		*vpp = NULL;
2776		nd->nd_repstat = ESTALE;
2777		goto out;
2778	}
2779
2780	if (startwrite) {
2781		vn_start_write(NULL, mpp, V_WAIT);
2782		if (lktype == LK_SHARED && !(MNT_SHARED_WRITES(mp)))
2783			lktype = LK_EXCLUSIVE;
2784	}
2785	nd->nd_repstat = nfsvno_fhtovp(mp, fhp, nd->nd_nam, lktype, vpp, exp,
2786	    &credanon);
2787	vfs_unbusy(mp);
2788
2789	/*
2790	 * For NFSv4 without a pseudo root fs, unexported file handles
2791	 * can be returned, so that Lookup works everywhere.
2792	 */
2793	if (!nd->nd_repstat && exp->nes_exflag == 0 &&
2794	    !(nd->nd_flag & ND_NFSV4)) {
2795		vput(*vpp);
2796		nd->nd_repstat = EACCES;
2797	}
2798
2799	/*
2800	 * Personally, I've never seen any point in requiring a
2801	 * reserved port#, since only in the rare case where the
2802	 * clients are all boxes with secure system priviledges,
2803	 * does it provide any enhanced security, but... some people
2804	 * believe it to be useful and keep putting this code back in.
2805	 * (There is also some "security checker" out there that
2806	 *  complains if the nfs server doesn't enforce this.)
2807	 * However, note the following:
2808	 * RFC3530 (NFSv4) specifies that a reserved port# not be
2809	 *	required.
2810	 * RFC2623 recommends that, if a reserved port# is checked for,
2811	 *	that there be a way to turn that off--> ifdef'd.
2812	 */
2813#ifdef NFS_REQRSVPORT
2814	if (!nd->nd_repstat) {
2815		struct sockaddr_in *saddr;
2816		struct sockaddr_in6 *saddr6;
2817
2818		saddr = NFSSOCKADDR(nd->nd_nam, struct sockaddr_in *);
2819		saddr6 = NFSSOCKADDR(nd->nd_nam, struct sockaddr_in6 *);
2820		if (!(nd->nd_flag & ND_NFSV4) &&
2821		    ((saddr->sin_family == AF_INET &&
2822		      ntohs(saddr->sin_port) >= IPPORT_RESERVED) ||
2823		     (saddr6->sin6_family == AF_INET6 &&
2824		      ntohs(saddr6->sin6_port) >= IPPORT_RESERVED))) {
2825			vput(*vpp);
2826			nd->nd_repstat = (NFSERR_AUTHERR | AUTH_TOOWEAK);
2827		}
2828	}
2829#endif	/* NFS_REQRSVPORT */
2830
2831	/*
2832	 * Check/setup credentials.
2833	 */
2834	if (!nd->nd_repstat) {
2835		nd->nd_saveduid = nd->nd_cred->cr_uid;
2836		nd->nd_repstat = nfsd_excred(nd, exp, credanon);
2837		if (nd->nd_repstat)
2838			vput(*vpp);
2839	}
2840	if (credanon != NULL)
2841		crfree(credanon);
2842	if (nd->nd_repstat) {
2843		if (startwrite)
2844			vn_finished_write(mp);
2845		*vpp = NULL;
2846		if (mpp != NULL)
2847			*mpp = NULL;
2848	}
2849
2850out:
2851	NFSEXITCODE2(0, nd);
2852}
2853
2854/*
2855 * glue for fp.
2856 */
2857static int
2858fp_getfvp(struct thread *p, int fd, struct file **fpp, struct vnode **vpp)
2859{
2860	struct filedesc *fdp;
2861	struct file *fp;
2862	int error = 0;
2863
2864	fdp = p->td_proc->p_fd;
2865	if (fd < 0 || fd >= fdp->fd_nfiles ||
2866	    (fp = fdp->fd_ofiles[fd].fde_file) == NULL) {
2867		error = EBADF;
2868		goto out;
2869	}
2870	*fpp = fp;
2871
2872out:
2873	NFSEXITCODE(error);
2874	return (error);
2875}
2876
2877/*
2878 * Called from nfssvc() to update the exports list. Just call
2879 * vfs_export(). This has to be done, since the v4 root fake fs isn't
2880 * in the mount list.
2881 */
2882int
2883nfsrv_v4rootexport(void *argp, struct ucred *cred, struct thread *p)
2884{
2885	struct nfsex_args *nfsexargp = (struct nfsex_args *)argp;
2886	int error = 0;
2887	struct nameidata nd;
2888	fhandle_t fh;
2889
2890	error = vfs_export(&nfsv4root_mnt, &nfsexargp->export);
2891	if ((nfsexargp->export.ex_flags & MNT_DELEXPORT) != 0)
2892		nfs_rootfhset = 0;
2893	else if (error == 0) {
2894		if (nfsexargp->fspec == NULL) {
2895			error = EPERM;
2896			goto out;
2897		}
2898		/*
2899		 * If fspec != NULL, this is the v4root path.
2900		 */
2901		NDINIT(&nd, LOOKUP, FOLLOW, UIO_USERSPACE,
2902		    nfsexargp->fspec, p);
2903		if ((error = namei(&nd)) != 0)
2904			goto out;
2905		error = nfsvno_getfh(nd.ni_vp, &fh, p);
2906		vrele(nd.ni_vp);
2907		if (!error) {
2908			nfs_rootfh.nfsrvfh_len = NFSX_MYFH;
2909			NFSBCOPY((caddr_t)&fh,
2910			    nfs_rootfh.nfsrvfh_data,
2911			    sizeof (fhandle_t));
2912			nfs_rootfhset = 1;
2913		}
2914	}
2915
2916out:
2917	NFSEXITCODE(error);
2918	return (error);
2919}
2920
2921/*
2922 * This function needs to test to see if the system is near its limit
2923 * for memory allocation via malloc() or mget() and return True iff
2924 * either of these resources are near their limit.
2925 * XXX (For now, this is just a stub.)
2926 */
2927int nfsrv_testmalloclimit = 0;
2928int
2929nfsrv_mallocmget_limit(void)
2930{
2931	static int printmesg = 0;
2932	static int testval = 1;
2933
2934	if (nfsrv_testmalloclimit && (testval++ % 1000) == 0) {
2935		if ((printmesg++ % 100) == 0)
2936			printf("nfsd: malloc/mget near limit\n");
2937		return (1);
2938	}
2939	return (0);
2940}
2941
2942/*
2943 * BSD specific initialization of a mount point.
2944 */
2945void
2946nfsd_mntinit(void)
2947{
2948	static int inited = 0;
2949
2950	if (inited)
2951		return;
2952	inited = 1;
2953	nfsv4root_mnt.mnt_flag = (MNT_RDONLY | MNT_EXPORTED);
2954	TAILQ_INIT(&nfsv4root_mnt.mnt_nvnodelist);
2955	TAILQ_INIT(&nfsv4root_mnt.mnt_activevnodelist);
2956	nfsv4root_mnt.mnt_export = NULL;
2957	TAILQ_INIT(&nfsv4root_opt);
2958	TAILQ_INIT(&nfsv4root_newopt);
2959	nfsv4root_mnt.mnt_opt = &nfsv4root_opt;
2960	nfsv4root_mnt.mnt_optnew = &nfsv4root_newopt;
2961	nfsv4root_mnt.mnt_nvnodelistsize = 0;
2962	nfsv4root_mnt.mnt_activevnodelistsize = 0;
2963}
2964
2965/*
2966 * Get a vnode for a file handle, without checking exports, etc.
2967 */
2968struct vnode *
2969nfsvno_getvp(fhandle_t *fhp)
2970{
2971	struct mount *mp;
2972	struct vnode *vp;
2973	int error;
2974
2975	mp = vfs_busyfs(&fhp->fh_fsid);
2976	if (mp == NULL)
2977		return (NULL);
2978	error = VFS_FHTOVP(mp, &fhp->fh_fid, LK_EXCLUSIVE, &vp);
2979	vfs_unbusy(mp);
2980	if (error)
2981		return (NULL);
2982	return (vp);
2983}
2984
2985/*
2986 * Do a local VOP_ADVLOCK().
2987 */
2988int
2989nfsvno_advlock(struct vnode *vp, int ftype, u_int64_t first,
2990    u_int64_t end, struct thread *td)
2991{
2992	int error = 0;
2993	struct flock fl;
2994	u_int64_t tlen;
2995
2996	if (nfsrv_dolocallocks == 0)
2997		goto out;
2998	ASSERT_VOP_UNLOCKED(vp, "nfsvno_advlock: vp locked");
2999
3000	fl.l_whence = SEEK_SET;
3001	fl.l_type = ftype;
3002	fl.l_start = (off_t)first;
3003	if (end == NFS64BITSSET) {
3004		fl.l_len = 0;
3005	} else {
3006		tlen = end - first;
3007		fl.l_len = (off_t)tlen;
3008	}
3009	/*
3010	 * For FreeBSD8, the l_pid and l_sysid must be set to the same
3011	 * values for all calls, so that all locks will be held by the
3012	 * nfsd server. (The nfsd server handles conflicts between the
3013	 * various clients.)
3014	 * Since an NFSv4 lockowner is a ClientID plus an array of up to 1024
3015	 * bytes, so it can't be put in l_sysid.
3016	 */
3017	if (nfsv4_sysid == 0)
3018		nfsv4_sysid = nlm_acquire_next_sysid();
3019	fl.l_pid = (pid_t)0;
3020	fl.l_sysid = (int)nfsv4_sysid;
3021
3022	if (ftype == F_UNLCK)
3023		error = VOP_ADVLOCK(vp, (caddr_t)td->td_proc, F_UNLCK, &fl,
3024		    (F_POSIX | F_REMOTE));
3025	else
3026		error = VOP_ADVLOCK(vp, (caddr_t)td->td_proc, F_SETLK, &fl,
3027		    (F_POSIX | F_REMOTE));
3028
3029out:
3030	NFSEXITCODE(error);
3031	return (error);
3032}
3033
3034/*
3035 * Check the nfsv4 root exports.
3036 */
3037int
3038nfsvno_v4rootexport(struct nfsrv_descript *nd)
3039{
3040	struct ucred *credanon;
3041	int exflags, error = 0, numsecflavor, *secflavors, i;
3042
3043	error = vfs_stdcheckexp(&nfsv4root_mnt, nd->nd_nam, &exflags,
3044	    &credanon, &numsecflavor, &secflavors);
3045	if (error) {
3046		error = NFSERR_PROGUNAVAIL;
3047		goto out;
3048	}
3049	if (credanon != NULL)
3050		crfree(credanon);
3051	for (i = 0; i < numsecflavor; i++) {
3052		if (secflavors[i] == AUTH_SYS)
3053			nd->nd_flag |= ND_EXAUTHSYS;
3054		else if (secflavors[i] == RPCSEC_GSS_KRB5)
3055			nd->nd_flag |= ND_EXGSS;
3056		else if (secflavors[i] == RPCSEC_GSS_KRB5I)
3057			nd->nd_flag |= ND_EXGSSINTEGRITY;
3058		else if (secflavors[i] == RPCSEC_GSS_KRB5P)
3059			nd->nd_flag |= ND_EXGSSPRIVACY;
3060	}
3061
3062out:
3063	NFSEXITCODE(error);
3064	return (error);
3065}
3066
3067/*
3068 * Nfs server psuedo system call for the nfsd's
3069 */
3070/*
3071 * MPSAFE
3072 */
3073static int
3074nfssvc_nfsd(struct thread *td, struct nfssvc_args *uap)
3075{
3076	struct file *fp;
3077	struct nfsd_addsock_args sockarg;
3078	struct nfsd_nfsd_args nfsdarg;
3079	cap_rights_t rights;
3080	int error;
3081
3082	if (uap->flag & NFSSVC_NFSDADDSOCK) {
3083		error = copyin(uap->argp, (caddr_t)&sockarg, sizeof (sockarg));
3084		if (error)
3085			goto out;
3086		/*
3087		 * Since we don't know what rights might be required,
3088		 * pretend that we need them all. It is better to be too
3089		 * careful than too reckless.
3090		 */
3091		error = fget(td, sockarg.sock,
3092		    cap_rights_init(&rights, CAP_SOCK_SERVER), &fp);
3093		if (error != 0)
3094			goto out;
3095		if (fp->f_type != DTYPE_SOCKET) {
3096			fdrop(fp, td);
3097			error = EPERM;
3098			goto out;
3099		}
3100		error = nfsrvd_addsock(fp);
3101		fdrop(fp, td);
3102	} else if (uap->flag & NFSSVC_NFSDNFSD) {
3103		if (uap->argp == NULL) {
3104			error = EINVAL;
3105			goto out;
3106		}
3107		error = copyin(uap->argp, (caddr_t)&nfsdarg,
3108		    sizeof (nfsdarg));
3109		if (error)
3110			goto out;
3111		error = nfsrvd_nfsd(td, &nfsdarg);
3112	} else {
3113		error = nfssvc_srvcall(td, uap, td->td_ucred);
3114	}
3115
3116out:
3117	NFSEXITCODE(error);
3118	return (error);
3119}
3120
3121static int
3122nfssvc_srvcall(struct thread *p, struct nfssvc_args *uap, struct ucred *cred)
3123{
3124	struct nfsex_args export;
3125	struct file *fp = NULL;
3126	int stablefd, len;
3127	struct nfsd_clid adminrevoke;
3128	struct nfsd_dumplist dumplist;
3129	struct nfsd_dumpclients *dumpclients;
3130	struct nfsd_dumplocklist dumplocklist;
3131	struct nfsd_dumplocks *dumplocks;
3132	struct nameidata nd;
3133	vnode_t vp;
3134	int error = EINVAL, igotlock;
3135	struct proc *procp;
3136	static int suspend_nfsd = 0;
3137
3138	if (uap->flag & NFSSVC_PUBLICFH) {
3139		NFSBZERO((caddr_t)&nfs_pubfh.nfsrvfh_data,
3140		    sizeof (fhandle_t));
3141		error = copyin(uap->argp,
3142		    &nfs_pubfh.nfsrvfh_data, sizeof (fhandle_t));
3143		if (!error)
3144			nfs_pubfhset = 1;
3145	} else if (uap->flag & NFSSVC_V4ROOTEXPORT) {
3146		error = copyin(uap->argp,(caddr_t)&export,
3147		    sizeof (struct nfsex_args));
3148		if (!error)
3149			error = nfsrv_v4rootexport(&export, cred, p);
3150	} else if (uap->flag & NFSSVC_NOPUBLICFH) {
3151		nfs_pubfhset = 0;
3152		error = 0;
3153	} else if (uap->flag & NFSSVC_STABLERESTART) {
3154		error = copyin(uap->argp, (caddr_t)&stablefd,
3155		    sizeof (int));
3156		if (!error)
3157			error = fp_getfvp(p, stablefd, &fp, &vp);
3158		if (!error && (NFSFPFLAG(fp) & (FREAD | FWRITE)) != (FREAD | FWRITE))
3159			error = EBADF;
3160		if (!error && newnfs_numnfsd != 0)
3161			error = EPERM;
3162		if (!error) {
3163			nfsrv_stablefirst.nsf_fp = fp;
3164			nfsrv_setupstable(p);
3165		}
3166	} else if (uap->flag & NFSSVC_ADMINREVOKE) {
3167		error = copyin(uap->argp, (caddr_t)&adminrevoke,
3168		    sizeof (struct nfsd_clid));
3169		if (!error)
3170			error = nfsrv_adminrevoke(&adminrevoke, p);
3171	} else if (uap->flag & NFSSVC_DUMPCLIENTS) {
3172		error = copyin(uap->argp, (caddr_t)&dumplist,
3173		    sizeof (struct nfsd_dumplist));
3174		if (!error && (dumplist.ndl_size < 1 ||
3175			dumplist.ndl_size > NFSRV_MAXDUMPLIST))
3176			error = EPERM;
3177		if (!error) {
3178		    len = sizeof (struct nfsd_dumpclients) * dumplist.ndl_size;
3179		    dumpclients = (struct nfsd_dumpclients *)malloc(len,
3180			M_TEMP, M_WAITOK);
3181		    nfsrv_dumpclients(dumpclients, dumplist.ndl_size);
3182		    error = copyout(dumpclients,
3183			CAST_USER_ADDR_T(dumplist.ndl_list), len);
3184		    free((caddr_t)dumpclients, M_TEMP);
3185		}
3186	} else if (uap->flag & NFSSVC_DUMPLOCKS) {
3187		error = copyin(uap->argp, (caddr_t)&dumplocklist,
3188		    sizeof (struct nfsd_dumplocklist));
3189		if (!error && (dumplocklist.ndllck_size < 1 ||
3190			dumplocklist.ndllck_size > NFSRV_MAXDUMPLIST))
3191			error = EPERM;
3192		if (!error)
3193			error = nfsrv_lookupfilename(&nd,
3194				dumplocklist.ndllck_fname, p);
3195		if (!error) {
3196			len = sizeof (struct nfsd_dumplocks) *
3197				dumplocklist.ndllck_size;
3198			dumplocks = (struct nfsd_dumplocks *)malloc(len,
3199				M_TEMP, M_WAITOK);
3200			nfsrv_dumplocks(nd.ni_vp, dumplocks,
3201			    dumplocklist.ndllck_size, p);
3202			vput(nd.ni_vp);
3203			error = copyout(dumplocks,
3204			    CAST_USER_ADDR_T(dumplocklist.ndllck_list), len);
3205			free((caddr_t)dumplocks, M_TEMP);
3206		}
3207	} else if (uap->flag & NFSSVC_BACKUPSTABLE) {
3208		procp = p->td_proc;
3209		PROC_LOCK(procp);
3210		nfsd_master_pid = procp->p_pid;
3211		bcopy(procp->p_comm, nfsd_master_comm, MAXCOMLEN + 1);
3212		nfsd_master_start = procp->p_stats->p_start;
3213		nfsd_master_proc = procp;
3214		PROC_UNLOCK(procp);
3215	} else if ((uap->flag & NFSSVC_SUSPENDNFSD) != 0) {
3216		NFSLOCKV4ROOTMUTEX();
3217		if (suspend_nfsd == 0) {
3218			/* Lock out all nfsd threads */
3219			do {
3220				igotlock = nfsv4_lock(&nfsd_suspend_lock, 1,
3221				    NULL, NFSV4ROOTLOCKMUTEXPTR, NULL);
3222			} while (igotlock == 0 && suspend_nfsd == 0);
3223			suspend_nfsd = 1;
3224		}
3225		NFSUNLOCKV4ROOTMUTEX();
3226		error = 0;
3227	} else if ((uap->flag & NFSSVC_RESUMENFSD) != 0) {
3228		NFSLOCKV4ROOTMUTEX();
3229		if (suspend_nfsd != 0) {
3230			nfsv4_unlock(&nfsd_suspend_lock, 0);
3231			suspend_nfsd = 0;
3232		}
3233		NFSUNLOCKV4ROOTMUTEX();
3234		error = 0;
3235	}
3236
3237	NFSEXITCODE(error);
3238	return (error);
3239}
3240
3241/*
3242 * Check exports.
3243 * Returns 0 if ok, 1 otherwise.
3244 */
3245int
3246nfsvno_testexp(struct nfsrv_descript *nd, struct nfsexstuff *exp)
3247{
3248	int i;
3249
3250	/*
3251	 * This seems odd, but allow the case where the security flavor
3252	 * list is empty. This happens when NFSv4 is traversing non-exported
3253	 * file systems. Exported file systems should always have a non-empty
3254	 * security flavor list.
3255	 */
3256	if (exp->nes_numsecflavor == 0)
3257		return (0);
3258
3259	for (i = 0; i < exp->nes_numsecflavor; i++) {
3260		/*
3261		 * The tests for privacy and integrity must be first,
3262		 * since ND_GSS is set for everything but AUTH_SYS.
3263		 */
3264		if (exp->nes_secflavors[i] == RPCSEC_GSS_KRB5P &&
3265		    (nd->nd_flag & ND_GSSPRIVACY))
3266			return (0);
3267		if (exp->nes_secflavors[i] == RPCSEC_GSS_KRB5I &&
3268		    (nd->nd_flag & ND_GSSINTEGRITY))
3269			return (0);
3270		if (exp->nes_secflavors[i] == RPCSEC_GSS_KRB5 &&
3271		    (nd->nd_flag & ND_GSS))
3272			return (0);
3273		if (exp->nes_secflavors[i] == AUTH_SYS &&
3274		    (nd->nd_flag & ND_GSS) == 0)
3275			return (0);
3276	}
3277	return (1);
3278}
3279
3280/*
3281 * Calculate a hash value for the fid in a file handle.
3282 */
3283uint32_t
3284nfsrv_hashfh(fhandle_t *fhp)
3285{
3286	uint32_t hashval;
3287
3288	hashval = hash32_buf(&fhp->fh_fid, sizeof(struct fid), 0);
3289	return (hashval);
3290}
3291
3292/*
3293 * Calculate a hash value for the sessionid.
3294 */
3295uint32_t
3296nfsrv_hashsessionid(uint8_t *sessionid)
3297{
3298	uint32_t hashval;
3299
3300	hashval = hash32_buf(sessionid, NFSX_V4SESSIONID, 0);
3301	return (hashval);
3302}
3303
3304/*
3305 * Signal the userland master nfsd to backup the stable restart file.
3306 */
3307void
3308nfsrv_backupstable(void)
3309{
3310	struct proc *procp;
3311
3312	if (nfsd_master_proc != NULL) {
3313		procp = pfind(nfsd_master_pid);
3314		/* Try to make sure it is the correct process. */
3315		if (procp == nfsd_master_proc &&
3316		    procp->p_stats->p_start.tv_sec ==
3317		    nfsd_master_start.tv_sec &&
3318		    procp->p_stats->p_start.tv_usec ==
3319		    nfsd_master_start.tv_usec &&
3320		    strcmp(procp->p_comm, nfsd_master_comm) == 0)
3321			kern_psignal(procp, SIGUSR2);
3322		else
3323			nfsd_master_proc = NULL;
3324
3325		if (procp != NULL)
3326			PROC_UNLOCK(procp);
3327	}
3328}
3329
3330extern int (*nfsd_call_nfsd)(struct thread *, struct nfssvc_args *);
3331
3332/*
3333 * Called once to initialize data structures...
3334 */
3335static int
3336nfsd_modevent(module_t mod, int type, void *data)
3337{
3338	int error = 0, i;
3339	static int loaded = 0;
3340
3341	switch (type) {
3342	case MOD_LOAD:
3343		if (loaded)
3344			goto out;
3345		newnfs_portinit();
3346		for (i = 0; i < NFSRVCACHE_HASHSIZE; i++) {
3347			mtx_init(&nfsrchash_table[i].mtx, "nfsrtc", NULL,
3348			    MTX_DEF);
3349			mtx_init(&nfsrcahash_table[i].mtx, "nfsrtca", NULL,
3350			    MTX_DEF);
3351		}
3352		mtx_init(&nfsrc_udpmtx, "nfsuc", NULL, MTX_DEF);
3353		mtx_init(&nfs_v4root_mutex, "nfs4rt", NULL, MTX_DEF);
3354		mtx_init(&nfsv4root_mnt.mnt_mtx, "nfs4mnt", NULL, MTX_DEF);
3355		lockinit(&nfsv4root_mnt.mnt_explock, PVFS, "explock", 0, 0);
3356		nfsrvd_initcache();
3357		nfsd_init();
3358		NFSD_LOCK();
3359		nfsrvd_init(0);
3360		NFSD_UNLOCK();
3361		nfsd_mntinit();
3362#ifdef VV_DISABLEDELEG
3363		vn_deleg_ops.vndeleg_recall = nfsd_recalldelegation;
3364		vn_deleg_ops.vndeleg_disable = nfsd_disabledelegation;
3365#endif
3366		nfsd_call_servertimer = nfsrv_servertimer;
3367		nfsd_call_nfsd = nfssvc_nfsd;
3368		loaded = 1;
3369		break;
3370
3371	case MOD_UNLOAD:
3372		if (newnfs_numnfsd != 0) {
3373			error = EBUSY;
3374			break;
3375		}
3376
3377#ifdef VV_DISABLEDELEG
3378		vn_deleg_ops.vndeleg_recall = NULL;
3379		vn_deleg_ops.vndeleg_disable = NULL;
3380#endif
3381		nfsd_call_servertimer = NULL;
3382		nfsd_call_nfsd = NULL;
3383
3384		/* Clean out all NFSv4 state. */
3385		nfsrv_throwawayallstate(curthread);
3386
3387		/* Clean the NFS server reply cache */
3388		nfsrvd_cleancache();
3389
3390		/* Free up the krpc server pool. */
3391		if (nfsrvd_pool != NULL)
3392			svcpool_destroy(nfsrvd_pool);
3393
3394		/* and get rid of the locks */
3395		for (i = 0; i < NFSRVCACHE_HASHSIZE; i++) {
3396			mtx_destroy(&nfsrchash_table[i].mtx);
3397			mtx_destroy(&nfsrcahash_table[i].mtx);
3398		}
3399		mtx_destroy(&nfsrc_udpmtx);
3400		mtx_destroy(&nfs_v4root_mutex);
3401		mtx_destroy(&nfsv4root_mnt.mnt_mtx);
3402		for (i = 0; i < nfsrv_sessionhashsize; i++)
3403			mtx_destroy(&nfssessionhash[i].mtx);
3404		lockdestroy(&nfsv4root_mnt.mnt_explock);
3405		free(nfsclienthash, M_NFSDCLIENT);
3406		free(nfslockhash, M_NFSDLOCKFILE);
3407		free(nfssessionhash, M_NFSDSESSION);
3408		loaded = 0;
3409		break;
3410	default:
3411		error = EOPNOTSUPP;
3412		break;
3413	}
3414
3415out:
3416	NFSEXITCODE(error);
3417	return (error);
3418}
3419static moduledata_t nfsd_mod = {
3420	"nfsd",
3421	nfsd_modevent,
3422	NULL,
3423};
3424DECLARE_MODULE(nfsd, nfsd_mod, SI_SUB_VFS, SI_ORDER_ANY);
3425
3426/* So that loader and kldload(2) can find us, wherever we are.. */
3427MODULE_VERSION(nfsd, 1);
3428MODULE_DEPEND(nfsd, nfscommon, 1, 1, 1);
3429MODULE_DEPEND(nfsd, nfslock, 1, 1, 1);
3430MODULE_DEPEND(nfsd, nfslockd, 1, 1, 1);
3431MODULE_DEPEND(nfsd, krpc, 1, 1, 1);
3432MODULE_DEPEND(nfsd, nfssvc, 1, 1, 1);
3433
3434