nfs_nfsdport.c revision 261067
1183724Ssos/*-
2230132Suqs * Copyright (c) 1989, 1993
3183724Ssos *	The Regents of the University of California.  All rights reserved.
4183724Ssos *
5183724Ssos * This code is derived from software contributed to Berkeley by
6183724Ssos * Rick Macklem at The University of Guelph.
7183724Ssos *
8183724Ssos * Redistribution and use in source and binary forms, with or without
9183724Ssos * modification, are permitted provided that the following conditions
10183724Ssos * are met:
11183724Ssos * 1. Redistributions of source code must retain the above copyright
12183724Ssos *    notice, this list of conditions and the following disclaimer.
13183724Ssos * 2. Redistributions in binary form must reproduce the above copyright
14183724Ssos *    notice, this list of conditions and the following disclaimer in the
15183724Ssos *    documentation and/or other materials provided with the distribution.
16183724Ssos * 4. Neither the name of the University nor the names of its contributors
17183724Ssos *    may be used to endorse or promote products derived from this software
18183724Ssos *    without specific prior written permission.
19183724Ssos *
20183724Ssos * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21183724Ssos * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22183724Ssos * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23183724Ssos * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24183724Ssos * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25183724Ssos * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26183724Ssos * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27183724Ssos * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28183724Ssos * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29183724Ssos * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30183724Ssos * SUCH DAMAGE.
31183724Ssos *
32183724Ssos */
33183724Ssos
34183724Ssos#include <sys/cdefs.h>
35183724Ssos__FBSDID("$FreeBSD: stable/9/sys/fs/nfsserver/nfs_nfsdport.c 261067 2014-01-23 00:46:29Z mav $");
36183724Ssos
37183724Ssos#include <sys/capability.h>
38183724Ssos
39183724Ssos/*
40183724Ssos * Functions that perform the vfs operations required by the routines in
41183724Ssos * nfsd_serv.c. It is hoped that this change will make the server more
42183724Ssos * portable.
43183724Ssos */
44183724Ssos
45183724Ssos#include <fs/nfs/nfsport.h>
46183724Ssos#include <sys/hash.h>
47183724Ssos#include <sys/sysctl.h>
48183724Ssos#include <nlm/nlm_prot.h>
49183724Ssos#include <nlm/nlm.h>
50183724Ssos
51183724SsosFEATURE(nfsd, "NFSv4 server");
52183724Ssos
53183724Ssosextern u_int32_t newnfs_true, newnfs_false, newnfs_xdrneg1;
54183724Ssosextern int nfsrv_useacl;
55188765Smavextern int newnfs_numnfsd;
56188769Smavextern struct mount nfsv4root_mnt;
57183724Ssosextern struct nfsrv_stablefirst nfsrv_stablefirst;
58214016Smavextern void (*nfsd_call_servertimer)(void);
59200171Smavextern SVCPOOL	*nfsrvd_pool;
60183724Ssosextern struct nfsv4lock nfsd_suspend_lock;
61200171Smavstruct vfsoptlist nfsv4root_opt, nfsv4root_newopt;
62200754SmavNFSDLOCKMUTEX;
63200754Smavstruct nfsrchash_bucket nfsrchash_table[NFSRVCACHE_HASHSIZE];
64200754Smavstruct nfsrchash_bucket nfsrcahash_table[NFSRVCACHE_HASHSIZE];
65215449Smavstruct mtx nfsrc_udpmtx;
66215449Smavstruct mtx nfs_v4root_mutex;
67215449Smavstruct nfsrvfh nfs_rootfh, nfs_pubfh;
68215449Smavint nfs_pubfhset = 0, nfs_rootfhset = 0;
69215449Smavstruct proc *nfsd_master_proc = NULL;
70215449Smavstatic pid_t nfsd_master_pid = (pid_t)-1;
71183724Ssosstatic char nfsd_master_comm[MAXCOMLEN + 1];
72183724Ssosstatic struct timeval nfsd_master_start;
73183724Ssosstatic uint32_t nfsv4_sysid = 0;
74183724Ssos
75183724Ssosstatic int nfssvc_srvcall(struct thread *, struct nfssvc_args *,
76183724Ssos    struct ucred *);
77183724Ssos
78183724Ssosint nfsrv_enable_crossmntpt = 1;
79183724Ssosstatic int nfs_commit_blks;
80183724Ssosstatic int nfs_commit_miss;
81183724Ssosextern int nfsrv_issuedelegs;
82200754Smavextern int nfsrv_dolocallocks;
83183724Ssos
84183724SsosSYSCTL_NODE(_vfs, OID_AUTO, nfsd, CTLFLAG_RW, 0, "New NFS server");
85183724SsosSYSCTL_INT(_vfs_nfsd, OID_AUTO, mirrormnt, CTLFLAG_RW,
86183724Ssos    &nfsrv_enable_crossmntpt, 0, "Enable nfsd to cross mount points");
87183724SsosSYSCTL_INT(_vfs_nfsd, OID_AUTO, commit_blks, CTLFLAG_RW, &nfs_commit_blks,
88183724Ssos    0, "");
89183724SsosSYSCTL_INT(_vfs_nfsd, OID_AUTO, commit_miss, CTLFLAG_RW, &nfs_commit_miss,
90183724Ssos    0, "");
91242625SdimSYSCTL_INT(_vfs_nfsd, OID_AUTO, issue_delegations, CTLFLAG_RW,
92183724Ssos    &nfsrv_issuedelegs, 0, "Enable nfsd to issue delegations");
93183724SsosSYSCTL_INT(_vfs_nfsd, OID_AUTO, enable_locallocks, CTLFLAG_RW,
94183724Ssos    &nfsrv_dolocallocks, 0, "Enable nfsd to acquire local locks on files");
95183724Ssos
96183724Ssos#define	MAX_REORDERED_RPC	16
97183724Ssos#define	NUM_HEURISTIC		1031
98183724Ssos#define	NHUSE_INIT		64
99183724Ssos#define	NHUSE_INC		16
100183724Ssos#define	NHUSE_MAX		2048
101183724Ssos
102183724Ssosstatic struct nfsheur {
103183724Ssos	struct vnode *nh_vp;	/* vp to match (unreferenced pointer) */
104183724Ssos	off_t nh_nextoff;	/* next offset for sequential detection */
105183724Ssos	int nh_use;		/* use count for selection */
106183724Ssos	int nh_seqcount;	/* heuristic */
107198482Smav} nfsheur[NUM_HEURISTIC];
108198482Smav
109183724Ssos
110200754Smav/*
111200754Smav * Heuristic to detect sequential operation.
112200754Smav */
113215428Smavstatic struct nfsheur *
114183724Ssosnfsrv_sequential_heuristic(struct uio *uio, struct vnode *vp)
115242625Sdim{
116183724Ssos	struct nfsheur *nh;
117183724Ssos	int hi, try;
118183724Ssos
119183724Ssos	/* Locate best candidate. */
120183724Ssos	try = 32;
121198481Smav	hi = ((int)(vm_offset_t)vp / sizeof(struct vnode)) % NUM_HEURISTIC;
122198481Smav	nh = &nfsheur[hi];
123183724Ssos	while (try--) {
124183724Ssos		if (nfsheur[hi].nh_vp == vp) {
125183724Ssos			nh = &nfsheur[hi];
126183724Ssos			break;
127183724Ssos		}
128183724Ssos		if (nfsheur[hi].nh_use > 0)
129200754Smav			--nfsheur[hi].nh_use;
130200754Smav		hi = (hi + 1) % NUM_HEURISTIC;
131215428Smav		if (nfsheur[hi].nh_use < nh->nh_use)
132215428Smav			nh = &nfsheur[hi];
133215428Smav	}
134183724Ssos
135183724Ssos	/* Initialize hint if this is a new file. */
136183724Ssos	if (nh->nh_vp != vp) {
137183724Ssos		nh->nh_vp = vp;
138183724Ssos		nh->nh_nextoff = uio->uio_offset;
139183724Ssos		nh->nh_use = NHUSE_INIT;
140183724Ssos		if (uio->uio_offset == 0)
141183724Ssos			nh->nh_seqcount = 4;
142183724Ssos		else
143183724Ssos			nh->nh_seqcount = 1;
144194893Smav	}
145183724Ssos
146183724Ssos	/* Calculate heuristic. */
147183724Ssos	if ((uio->uio_offset == 0 && nh->nh_seqcount > 0) ||
148183724Ssos	    uio->uio_offset == nh->nh_nextoff) {
149183724Ssos		/* See comments in vfs_vnops.c:sequential_heuristic(). */
150183724Ssos		nh->nh_seqcount += howmany(uio->uio_resid, 16384);
151183724Ssos		if (nh->nh_seqcount > IO_SEQMAX)
152183724Ssos			nh->nh_seqcount = IO_SEQMAX;
153183724Ssos	} else if (qabs(uio->uio_offset - nh->nh_nextoff) <= MAX_REORDERED_RPC *
154200754Smav	    imax(vp->v_mount->mnt_stat.f_iosize, uio->uio_resid)) {
155200754Smav		/* Probably a reordered RPC, leave seqcount alone. */
156200754Smav	} else if (nh->nh_seqcount > 1) {
157200754Smav		nh->nh_seqcount /= 2;
158200754Smav	} else {
159200754Smav		nh->nh_seqcount = 0;
160215449Smav	}
161200754Smav	nh->nh_use += NHUSE_INC;
162200754Smav	if (nh->nh_use > NHUSE_MAX)
163200754Smav		nh->nh_use = NHUSE_MAX;
164200754Smav	return (nh);
165215449Smav}
166200754Smav
167200754Smav/*
168200754Smav * Get attributes into nfsvattr structure.
169183724Ssos */
170183724Ssosint
171183724Ssosnfsvno_getattr(struct vnode *vp, struct nfsvattr *nvap, struct ucred *cred,
172183724Ssos    struct thread *p, int vpislocked)
173183724Ssos{
174188765Smav	int error, lockedit = 0;
175188769Smav
176183724Ssos	if (vpislocked == 0) {
177183724Ssos		/*
178183724Ssos		 * When vpislocked == 0, the vnode is either exclusively
179183724Ssos		 * locked by this thread or not locked by this thread.
180183724Ssos		 * As such, shared lock it, if not exclusively locked.
181200171Smav		 */
182183724Ssos		if (NFSVOPISLOCKED(vp) != LK_EXCLUSIVE) {
183200171Smav			lockedit = 1;
184183724Ssos			NFSVOPLOCK(vp, LK_SHARED | LK_RETRY);
185183724Ssos		}
186183724Ssos	}
187183724Ssos	error = VOP_GETATTR(vp, &nvap->na_vattr, cred);
188183724Ssos	if (lockedit != 0)
189183724Ssos		NFSVOPUNLOCK(vp, 0);
190183724Ssos
191183724Ssos	NFSEXITCODE(error);
192183724Ssos	return (error);
193183724Ssos}
194183724Ssos
195183724Ssos/*
196183724Ssos * Get a file handle for a vnode.
197183724Ssos */
198183724Ssosint
199183724Ssosnfsvno_getfh(struct vnode *vp, fhandle_t *fhp, struct thread *p)
200183724Ssos{
201183724Ssos	int error;
202183724Ssos
203183724Ssos	NFSBZERO((caddr_t)fhp, sizeof(fhandle_t));
204183724Ssos	fhp->fh_fsid = vp->v_mount->mnt_stat.f_fsid;
205183724Ssos	error = VOP_VPTOFH(vp, &fhp->fh_fid);
206183724Ssos
207183724Ssos	NFSEXITCODE(error);
208183724Ssos	return (error);
209183724Ssos}
210183724Ssos
211183724Ssos/*
212183724Ssos * Perform access checking for vnodes obtained from file handles that would
213183724Ssos * refer to files already opened by a Unix client. You cannot just use
214183724Ssos * vn_writechk() and VOP_ACCESSX() for two reasons.
215188765Smav * 1 - You must check for exported rdonly as well as MNT_RDONLY for the write
216183724Ssos *     case.
217183724Ssos * 2 - The owner is to be given access irrespective of mode bits for some
218183724Ssos *     operations, so that processes that chmod after opening a file don't
219183724Ssos *     break.
220183724Ssos */
221183724Ssosint
222183724Ssosnfsvno_accchk(struct vnode *vp, accmode_t accmode, struct ucred *cred,
223183724Ssos    struct nfsexstuff *exp, struct thread *p, int override, int vpislocked,
224183724Ssos    u_int32_t *supportedtypep)
225188769Smav{
226188769Smav	struct vattr vattr;
227183724Ssos	int error = 0, getret = 0;
228183724Ssos
229183724Ssos	if (vpislocked == 0) {
230183724Ssos		if (NFSVOPLOCK(vp, LK_SHARED) != 0) {
231183724Ssos			error = EPERM;
232183724Ssos			goto out;
233183724Ssos		}
234183724Ssos	}
235183724Ssos	if (accmode & VWRITE) {
236183724Ssos		/* Just vn_writechk() changed to check rdonly */
237183724Ssos		/*
238183724Ssos		 * Disallow write attempts on read-only file systems;
239183724Ssos		 * unless the file is a socket or a block or character
240183724Ssos		 * device resident on the file system.
241183724Ssos		 */
242183724Ssos		if (NFSVNO_EXRDONLY(exp) ||
243183724Ssos		    (vp->v_mount->mnt_flag & MNT_RDONLY)) {
244183724Ssos			switch (vp->v_type) {
245183724Ssos			case VREG:
246183724Ssos			case VDIR:
247183724Ssos			case VLNK:
248183724Ssos				error = EROFS;
249183724Ssos			default:
250183724Ssos				break;
251188765Smav			}
252183724Ssos		}
253183724Ssos		/*
254183724Ssos		 * If there's shared text associated with
255183724Ssos		 * the inode, try to free it up once.  If
256183724Ssos		 * we fail, we can't allow writing.
257183724Ssos		 */
258183724Ssos		if (VOP_IS_TEXT(vp) && error == 0)
259183724Ssos			error = ETXTBSY;
260183724Ssos	}
261214016Smav	if (error != 0) {
262183724Ssos		if (vpislocked == 0)
263200171Smav			NFSVOPUNLOCK(vp, 0);
264214016Smav		goto out;
265183724Ssos	}
266214016Smav
267214016Smav	/*
268183724Ssos	 * Should the override still be applied when ACLs are enabled?
269183724Ssos	 */
270183724Ssos	error = VOP_ACCESSX(vp, accmode, cred, p);
271188769Smav	if (error != 0 && (accmode & (VDELETE | VDELETE_CHILD))) {
272188769Smav		/*
273188769Smav		 * Try again with VEXPLICIT_DENY, to see if the test for
274188769Smav		 * deletion is supported.
275188769Smav		 */
276188769Smav		error = VOP_ACCESSX(vp, accmode | VEXPLICIT_DENY, cred, p);
277188769Smav		if (error == 0) {
278188769Smav			if (vp->v_type == VDIR) {
279188769Smav				accmode &= ~(VDELETE | VDELETE_CHILD);
280188769Smav				accmode |= VWRITE;
281188769Smav				error = VOP_ACCESSX(vp, accmode, cred, p);
282188769Smav			} else if (supportedtypep != NULL) {
283188769Smav				*supportedtypep &= ~NFSACCESS_DELETE;
284188769Smav			}
285188769Smav		}
286188769Smav	}
287188769Smav
288188769Smav	/*
289188769Smav	 * Allow certain operations for the owner (reads and writes
290188769Smav	 * on files that are already open).
291188769Smav	 */
292188769Smav	if (override != NFSACCCHK_NOOVERRIDE &&
293188769Smav	    (error == EPERM || error == EACCES)) {
294188769Smav		if (cred->cr_uid == 0 && (override & NFSACCCHK_ALLOWROOT))
295188769Smav			error = 0;
296183724Ssos		else if (override & NFSACCCHK_ALLOWOWNER) {
297183724Ssos			getret = VOP_GETATTR(vp, &vattr, cred);
298183724Ssos			if (getret == 0 && cred->cr_uid == vattr.va_uid)
299183724Ssos				error = 0;
300183724Ssos		}
301183724Ssos	}
302183724Ssos	if (vpislocked == 0)
303183724Ssos		NFSVOPUNLOCK(vp, 0);
304209884Smav
305190581Smavout:
306183724Ssos	NFSEXITCODE(error);
307209884Smav	return (error);
308209884Smav}
309209884Smav
310183724Ssos/*
311183724Ssos * Set attribute(s) vnop.
312200171Smav */
313214016Smavint
314214016Smavnfsvno_setattr(struct vnode *vp, struct nfsvattr *nvap, struct ucred *cred,
315214016Smav    struct thread *p, struct nfsexstuff *exp)
316214016Smav{
317214016Smav	int error;
318214016Smav
319214016Smav	error = VOP_SETATTR(vp, &nvap->na_vattr, cred);
320214016Smav	NFSEXITCODE(error);
321200171Smav	return (error);
322183724Ssos}
323200171Smav
324200171Smav/*
325200171Smav * Set up nameidata for a lookup() call and do it.
326183724Ssos */
327200171Smavint
328200171Smavnfsvno_namei(struct nfsrv_descript *nd, struct nameidata *ndp,
329233282Smarius    struct vnode *dp, int islocked, struct nfsexstuff *exp, struct thread *p,
330233282Smarius    struct vnode **retdirp)
331233282Smarius{
332233282Smarius	struct componentname *cnp = &ndp->ni_cnd;
333183724Ssos	int i;
334200171Smav	struct iovec aiov;
335200171Smav	struct uio auio;
336200171Smav	int lockleaf = (cnp->cn_flags & LOCKLEAF) != 0, linklen;
337200171Smav	int error = 0, crossmnt;
338200171Smav	char *cp;
339183724Ssos
340200171Smav	*retdirp = NULL;
341200171Smav	cnp->cn_nameptr = cnp->cn_pnbuf;
342200171Smav	ndp->ni_strictrelative = 0;
343200171Smav	/*
344200171Smav	 * Extract and set starting directory.
345200171Smav	 */
346200171Smav	if (dp->v_type != VDIR) {
347183724Ssos		if (islocked)
348183724Ssos			vput(dp);
349200171Smav		else
350200171Smav			vrele(dp);
351183724Ssos		nfsvno_relpathbuf(ndp);
352200171Smav		error = ENOTDIR;
353200171Smav		goto out1;
354200171Smav	}
355200171Smav	if (islocked)
356200171Smav		NFSVOPUNLOCK(dp, 0);
357200171Smav	VREF(dp);
358233282Smarius	*retdirp = dp;
359233282Smarius	if (NFSVNO_EXRDONLY(exp))
360233282Smarius		cnp->cn_flags |= RDONLY;
361200171Smav	ndp->ni_segflg = UIO_SYSSPACE;
362200171Smav	crossmnt = 1;
363200171Smav
364200171Smav	if (nd->nd_flag & ND_PUBLOOKUP) {
365183724Ssos		ndp->ni_loopcnt = 0;
366200171Smav		if (cnp->cn_pnbuf[0] == '/') {
367200171Smav			vrele(dp);
368200171Smav			/*
369200171Smav			 * Check for degenerate pathnames here, since lookup()
370200171Smav			 * panics on them.
371200171Smav			 */
372200171Smav			for (i = 1; i < ndp->ni_pathlen; i++)
373200171Smav				if (cnp->cn_pnbuf[i] != '/')
374200171Smav					break;
375200171Smav			if (i == ndp->ni_pathlen) {
376200171Smav				error = NFSERR_ACCES;
377213301Smav				goto out;
378200171Smav			}
379183724Ssos			dp = rootvnode;
380183724Ssos			VREF(dp);
381183724Ssos		}
382183724Ssos	} else if ((nfsrv_enable_crossmntpt == 0 && NFSVNO_EXPORTED(exp)) ||
383183724Ssos	    (nd->nd_flag & ND_NFSV4) == 0) {
384183724Ssos		/*
385183724Ssos		 * Only cross mount points for NFSv4 when doing a
386183724Ssos		 * mount while traversing the file system above
387183724Ssos		 * the mount point, unless nfsrv_enable_crossmntpt is set.
388183724Ssos		 */
389183724Ssos		cnp->cn_flags |= NOCROSSMOUNT;
390183724Ssos		crossmnt = 0;
391183724Ssos	}
392183724Ssos
393183724Ssos	/*
394183724Ssos	 * Initialize for scan, set ni_startdir and bump ref on dp again
395183724Ssos	 * becuase lookup() will dereference ni_startdir.
396183724Ssos	 */
397183724Ssos
398183724Ssos	cnp->cn_thread = p;
399183724Ssos	ndp->ni_startdir = dp;
400183724Ssos	ndp->ni_rootdir = rootvnode;
401183724Ssos	ndp->ni_topdir = NULL;
402183724Ssos
403183724Ssos	if (!lockleaf)
404183724Ssos		cnp->cn_flags |= LOCKLEAF;
405183724Ssos	for (;;) {
406183724Ssos		cnp->cn_nameptr = cnp->cn_pnbuf;
407183724Ssos		/*
408183724Ssos		 * Call lookup() to do the real work.  If an error occurs,
409200754Smav		 * ndp->ni_vp and ni_dvp are left uninitialized or NULL and
410200754Smav		 * we do not have to dereference anything before returning.
411200754Smav		 * In either case ni_startdir will be dereferenced and NULLed
412200754Smav		 * out.
413200754Smav		 */
414200754Smav		error = lookup(ndp);
415200754Smav		if (error)
416215449Smav			break;
417215449Smav
418215449Smav		/*
419215449Smav		 * Check for encountering a symbolic link.  Trivial
420215449Smav		 * termination occurs if no symlink encountered.
421200754Smav		 */
422215449Smav		if ((cnp->cn_flags & ISSYMLINK) == 0) {
423215449Smav			if ((cnp->cn_flags & (SAVENAME | SAVESTART)) == 0)
424215449Smav				nfsvno_relpathbuf(ndp);
425200754Smav			if (ndp->ni_vp && !lockleaf)
426200754Smav				NFSVOPUNLOCK(ndp->ni_vp, 0);
427200754Smav			break;
428200754Smav		}
429200754Smav
430200754Smav		/*
431215449Smav		 * Validate symlink
432200754Smav		 */
433200754Smav		if ((cnp->cn_flags & LOCKPARENT) && ndp->ni_pathlen == 1)
434215449Smav			NFSVOPUNLOCK(ndp->ni_dvp, 0);
435215449Smav		if (!(nd->nd_flag & ND_PUBLOOKUP)) {
436215449Smav			error = EINVAL;
437215449Smav			goto badlink2;
438215449Smav		}
439215449Smav
440200754Smav		if (ndp->ni_loopcnt++ >= MAXSYMLINKS) {
441200754Smav			error = ELOOP;
442200754Smav			goto badlink2;
443200754Smav		}
444200754Smav		if (ndp->ni_pathlen > 1)
445200754Smav			cp = uma_zalloc(namei_zone, M_WAITOK);
446200754Smav		else
447200754Smav			cp = cnp->cn_pnbuf;
448200754Smav		aiov.iov_base = cp;
449200754Smav		aiov.iov_len = MAXPATHLEN;
450200754Smav		auio.uio_iov = &aiov;
451200754Smav		auio.uio_iovcnt = 1;
452200754Smav		auio.uio_offset = 0;
453215449Smav		auio.uio_rw = UIO_READ;
454215449Smav		auio.uio_segflg = UIO_SYSSPACE;
455215449Smav		auio.uio_td = NULL;
456215449Smav		auio.uio_resid = MAXPATHLEN;
457215449Smav		error = VOP_READLINK(ndp->ni_vp, &auio, cnp->cn_cred);
458215449Smav		if (error) {
459215449Smav		badlink1:
460215449Smav			if (ndp->ni_pathlen > 1)
461215449Smav				uma_zfree(namei_zone, cp);
462215449Smav		badlink2:
463215449Smav			vrele(ndp->ni_dvp);
464215449Smav			vput(ndp->ni_vp);
465215449Smav			break;
466215449Smav		}
467215451Smav		linklen = MAXPATHLEN - auio.uio_resid;
468215451Smav		if (linklen == 0) {
469215449Smav			error = ENOENT;
470215449Smav			goto badlink1;
471215449Smav		}
472215449Smav		if (linklen + ndp->ni_pathlen >= MAXPATHLEN) {
473215449Smav			error = ENAMETOOLONG;
474215449Smav			goto badlink1;
475215449Smav		}
476215449Smav
477215449Smav		/*
478215449Smav		 * Adjust or replace path
479215449Smav		 */
480215449Smav		if (ndp->ni_pathlen > 1) {
481215449Smav			NFSBCOPY(ndp->ni_next, cp + linklen, ndp->ni_pathlen);
482215449Smav			uma_zfree(namei_zone, cnp->cn_pnbuf);
483215449Smav			cnp->cn_pnbuf = cp;
484215449Smav		} else
485215449Smav			cnp->cn_pnbuf[linklen] = '\0';
486215449Smav		ndp->ni_pathlen += linklen;
487215449Smav
488215449Smav		/*
489215449Smav		 * Cleanup refs for next loop and check if root directory
490215449Smav		 * should replace current directory.  Normally ni_dvp
491215449Smav		 * becomes the new base directory and is cleaned up when
492215449Smav		 * we loop.  Explicitly null pointers after invalidation
493215449Smav		 * to clarify operation.
494215449Smav		 */
495215449Smav		vput(ndp->ni_vp);
496215449Smav		ndp->ni_vp = NULL;
497215449Smav
498215449Smav		if (cnp->cn_pnbuf[0] == '/') {
499215449Smav			vrele(ndp->ni_dvp);
500215449Smav			ndp->ni_dvp = ndp->ni_rootdir;
501215449Smav			VREF(ndp->ni_dvp);
502215449Smav		}
503215449Smav		ndp->ni_startdir = ndp->ni_dvp;
504215449Smav		ndp->ni_dvp = NULL;
505215449Smav	}
506215449Smav	if (!lockleaf)
507215449Smav		cnp->cn_flags &= ~LOCKLEAF;
508215449Smav
509215449Smavout:
510215449Smav	if (error) {
511215449Smav		uma_zfree(namei_zone, cnp->cn_pnbuf);
512215449Smav		ndp->ni_vp = NULL;
513215449Smav		ndp->ni_dvp = NULL;
514215449Smav		ndp->ni_startdir = NULL;
515215449Smav		cnp->cn_flags &= ~HASBUF;
516215449Smav	} else if ((ndp->ni_cnd.cn_flags & (WANTPARENT|LOCKPARENT)) == 0) {
517215449Smav		ndp->ni_dvp = NULL;
518215449Smav	}
519215449Smav
520215449Smavout1:
521215449Smav	NFSEXITCODE2(error, nd);
522215449Smav	return (error);
523215449Smav}
524215449Smav
525215449Smav/*
526215449Smav * Set up a pathname buffer and return a pointer to it and, optionally
527215449Smav * set a hash pointer.
528215449Smav */
529215449Smavvoid
530215449Smavnfsvno_setpathbuf(struct nameidata *ndp, char **bufpp, u_long **hashpp)
531215449Smav{
532215449Smav	struct componentname *cnp = &ndp->ni_cnd;
533215449Smav
534215449Smav	cnp->cn_flags |= (NOMACCHECK | HASBUF);
535215449Smav	cnp->cn_pnbuf = uma_zalloc(namei_zone, M_WAITOK);
536215449Smav	if (hashpp != NULL)
537215449Smav		*hashpp = NULL;
538215449Smav	*bufpp = cnp->cn_pnbuf;
539215449Smav}
540215449Smav
541215449Smav/*
542215449Smav * Release the above path buffer, if not released by nfsvno_namei().
543215449Smav */
544215449Smavvoid
545215449Smavnfsvno_relpathbuf(struct nameidata *ndp)
546215449Smav{
547215449Smav
548215449Smav	if ((ndp->ni_cnd.cn_flags & HASBUF) == 0)
549215449Smav		panic("nfsrelpath");
550215449Smav	uma_zfree(namei_zone, ndp->ni_cnd.cn_pnbuf);
551215449Smav	ndp->ni_cnd.cn_flags &= ~HASBUF;
552215449Smav}
553215449Smav
554215449Smav/*
555215449Smav * Readlink vnode op into an mbuf list.
556183724Ssos */
557183724Ssosint
558nfsvno_readlink(struct vnode *vp, struct ucred *cred, struct thread *p,
559    struct mbuf **mpp, struct mbuf **mpendp, int *lenp)
560{
561	struct iovec iv[(NFS_MAXPATHLEN+MLEN-1)/MLEN];
562	struct iovec *ivp = iv;
563	struct uio io, *uiop = &io;
564	struct mbuf *mp, *mp2 = NULL, *mp3 = NULL;
565	int i, len, tlen, error = 0;
566
567	len = 0;
568	i = 0;
569	while (len < NFS_MAXPATHLEN) {
570		NFSMGET(mp);
571		MCLGET(mp, M_WAIT);
572		mp->m_len = NFSMSIZ(mp);
573		if (len == 0) {
574			mp3 = mp2 = mp;
575		} else {
576			mp2->m_next = mp;
577			mp2 = mp;
578		}
579		if ((len + mp->m_len) > NFS_MAXPATHLEN) {
580			mp->m_len = NFS_MAXPATHLEN - len;
581			len = NFS_MAXPATHLEN;
582		} else {
583			len += mp->m_len;
584		}
585		ivp->iov_base = mtod(mp, caddr_t);
586		ivp->iov_len = mp->m_len;
587		i++;
588		ivp++;
589	}
590	uiop->uio_iov = iv;
591	uiop->uio_iovcnt = i;
592	uiop->uio_offset = 0;
593	uiop->uio_resid = len;
594	uiop->uio_rw = UIO_READ;
595	uiop->uio_segflg = UIO_SYSSPACE;
596	uiop->uio_td = NULL;
597	error = VOP_READLINK(vp, uiop, cred);
598	if (error) {
599		m_freem(mp3);
600		*lenp = 0;
601		goto out;
602	}
603	if (uiop->uio_resid > 0) {
604		len -= uiop->uio_resid;
605		tlen = NFSM_RNDUP(len);
606		nfsrv_adj(mp3, NFS_MAXPATHLEN - tlen, tlen - len);
607	}
608	*lenp = len;
609	*mpp = mp3;
610	*mpendp = mp;
611
612out:
613	NFSEXITCODE(error);
614	return (error);
615}
616
617/*
618 * Read vnode op call into mbuf list.
619 */
620int
621nfsvno_read(struct vnode *vp, off_t off, int cnt, struct ucred *cred,
622    struct thread *p, struct mbuf **mpp, struct mbuf **mpendp)
623{
624	struct mbuf *m;
625	int i;
626	struct iovec *iv;
627	struct iovec *iv2;
628	int error = 0, len, left, siz, tlen, ioflag = 0;
629	struct mbuf *m2 = NULL, *m3;
630	struct uio io, *uiop = &io;
631	struct nfsheur *nh;
632
633	len = left = NFSM_RNDUP(cnt);
634	m3 = NULL;
635	/*
636	 * Generate the mbuf list with the uio_iov ref. to it.
637	 */
638	i = 0;
639	while (left > 0) {
640		NFSMGET(m);
641		MCLGET(m, M_WAIT);
642		m->m_len = 0;
643		siz = min(M_TRAILINGSPACE(m), left);
644		left -= siz;
645		i++;
646		if (m3)
647			m2->m_next = m;
648		else
649			m3 = m;
650		m2 = m;
651	}
652	MALLOC(iv, struct iovec *, i * sizeof (struct iovec),
653	    M_TEMP, M_WAITOK);
654	uiop->uio_iov = iv2 = iv;
655	m = m3;
656	left = len;
657	i = 0;
658	while (left > 0) {
659		if (m == NULL)
660			panic("nfsvno_read iov");
661		siz = min(M_TRAILINGSPACE(m), left);
662		if (siz > 0) {
663			iv->iov_base = mtod(m, caddr_t) + m->m_len;
664			iv->iov_len = siz;
665			m->m_len += siz;
666			left -= siz;
667			iv++;
668			i++;
669		}
670		m = m->m_next;
671	}
672	uiop->uio_iovcnt = i;
673	uiop->uio_offset = off;
674	uiop->uio_resid = len;
675	uiop->uio_rw = UIO_READ;
676	uiop->uio_segflg = UIO_SYSSPACE;
677	nh = nfsrv_sequential_heuristic(uiop, vp);
678	ioflag |= nh->nh_seqcount << IO_SEQSHIFT;
679	error = VOP_READ(vp, uiop, IO_NODELOCKED | ioflag, cred);
680	FREE((caddr_t)iv2, M_TEMP);
681	if (error) {
682		m_freem(m3);
683		*mpp = NULL;
684		goto out;
685	}
686	nh->nh_nextoff = uiop->uio_offset;
687	tlen = len - uiop->uio_resid;
688	cnt = cnt < tlen ? cnt : tlen;
689	tlen = NFSM_RNDUP(cnt);
690	if (tlen == 0) {
691		m_freem(m3);
692		m3 = NULL;
693	} else if (len != tlen || tlen != cnt)
694		nfsrv_adj(m3, len - tlen, tlen - cnt);
695	*mpp = m3;
696	*mpendp = m2;
697
698out:
699	NFSEXITCODE(error);
700	return (error);
701}
702
703/*
704 * Write vnode op from an mbuf list.
705 */
706int
707nfsvno_write(struct vnode *vp, off_t off, int retlen, int cnt, int stable,
708    struct mbuf *mp, char *cp, struct ucred *cred, struct thread *p)
709{
710	struct iovec *ivp;
711	int i, len;
712	struct iovec *iv;
713	int ioflags, error;
714	struct uio io, *uiop = &io;
715	struct nfsheur *nh;
716
717	MALLOC(ivp, struct iovec *, cnt * sizeof (struct iovec), M_TEMP,
718	    M_WAITOK);
719	uiop->uio_iov = iv = ivp;
720	uiop->uio_iovcnt = cnt;
721	i = mtod(mp, caddr_t) + mp->m_len - cp;
722	len = retlen;
723	while (len > 0) {
724		if (mp == NULL)
725			panic("nfsvno_write");
726		if (i > 0) {
727			i = min(i, len);
728			ivp->iov_base = cp;
729			ivp->iov_len = i;
730			ivp++;
731			len -= i;
732		}
733		mp = mp->m_next;
734		if (mp) {
735			i = mp->m_len;
736			cp = mtod(mp, caddr_t);
737		}
738	}
739
740	if (stable == NFSWRITE_UNSTABLE)
741		ioflags = IO_NODELOCKED;
742	else
743		ioflags = (IO_SYNC | IO_NODELOCKED);
744	uiop->uio_resid = retlen;
745	uiop->uio_rw = UIO_WRITE;
746	uiop->uio_segflg = UIO_SYSSPACE;
747	NFSUIOPROC(uiop, p);
748	uiop->uio_offset = off;
749	nh = nfsrv_sequential_heuristic(uiop, vp);
750	ioflags |= nh->nh_seqcount << IO_SEQSHIFT;
751	error = VOP_WRITE(vp, uiop, ioflags, cred);
752	if (error == 0)
753		nh->nh_nextoff = uiop->uio_offset;
754	FREE((caddr_t)iv, M_TEMP);
755
756	NFSEXITCODE(error);
757	return (error);
758}
759
760/*
761 * Common code for creating a regular file (plus special files for V2).
762 */
763int
764nfsvno_createsub(struct nfsrv_descript *nd, struct nameidata *ndp,
765    struct vnode **vpp, struct nfsvattr *nvap, int *exclusive_flagp,
766    int32_t *cverf, NFSDEV_T rdev, struct thread *p, struct nfsexstuff *exp)
767{
768	u_quad_t tempsize;
769	int error;
770
771	error = nd->nd_repstat;
772	if (!error && ndp->ni_vp == NULL) {
773		if (nvap->na_type == VREG || nvap->na_type == VSOCK) {
774			vrele(ndp->ni_startdir);
775			error = VOP_CREATE(ndp->ni_dvp,
776			    &ndp->ni_vp, &ndp->ni_cnd, &nvap->na_vattr);
777			vput(ndp->ni_dvp);
778			nfsvno_relpathbuf(ndp);
779			if (!error) {
780				if (*exclusive_flagp) {
781					*exclusive_flagp = 0;
782					NFSVNO_ATTRINIT(nvap);
783					nvap->na_atime.tv_sec = cverf[0];
784					nvap->na_atime.tv_nsec = cverf[1];
785					error = VOP_SETATTR(ndp->ni_vp,
786					    &nvap->na_vattr, nd->nd_cred);
787				}
788			}
789		/*
790		 * NFS V2 Only. nfsrvd_mknod() does this for V3.
791		 * (This implies, just get out on an error.)
792		 */
793		} else if (nvap->na_type == VCHR || nvap->na_type == VBLK ||
794			nvap->na_type == VFIFO) {
795			if (nvap->na_type == VCHR && rdev == 0xffffffff)
796				nvap->na_type = VFIFO;
797                        if (nvap->na_type != VFIFO &&
798			    (error = priv_check_cred(nd->nd_cred,
799			     PRIV_VFS_MKNOD_DEV, 0))) {
800				vrele(ndp->ni_startdir);
801				nfsvno_relpathbuf(ndp);
802				vput(ndp->ni_dvp);
803				goto out;
804			}
805			nvap->na_rdev = rdev;
806			error = VOP_MKNOD(ndp->ni_dvp, &ndp->ni_vp,
807			    &ndp->ni_cnd, &nvap->na_vattr);
808			vput(ndp->ni_dvp);
809			nfsvno_relpathbuf(ndp);
810			vrele(ndp->ni_startdir);
811			if (error)
812				goto out;
813		} else {
814			vrele(ndp->ni_startdir);
815			nfsvno_relpathbuf(ndp);
816			vput(ndp->ni_dvp);
817			error = ENXIO;
818			goto out;
819		}
820		*vpp = ndp->ni_vp;
821	} else {
822		/*
823		 * Handle cases where error is already set and/or
824		 * the file exists.
825		 * 1 - clean up the lookup
826		 * 2 - iff !error and na_size set, truncate it
827		 */
828		vrele(ndp->ni_startdir);
829		nfsvno_relpathbuf(ndp);
830		*vpp = ndp->ni_vp;
831		if (ndp->ni_dvp == *vpp)
832			vrele(ndp->ni_dvp);
833		else
834			vput(ndp->ni_dvp);
835		if (!error && nvap->na_size != VNOVAL) {
836			error = nfsvno_accchk(*vpp, VWRITE,
837			    nd->nd_cred, exp, p, NFSACCCHK_NOOVERRIDE,
838			    NFSACCCHK_VPISLOCKED, NULL);
839			if (!error) {
840				tempsize = nvap->na_size;
841				NFSVNO_ATTRINIT(nvap);
842				nvap->na_size = tempsize;
843				error = VOP_SETATTR(*vpp,
844				    &nvap->na_vattr, nd->nd_cred);
845			}
846		}
847		if (error)
848			vput(*vpp);
849	}
850
851out:
852	NFSEXITCODE(error);
853	return (error);
854}
855
856/*
857 * Do a mknod vnode op.
858 */
859int
860nfsvno_mknod(struct nameidata *ndp, struct nfsvattr *nvap, struct ucred *cred,
861    struct thread *p)
862{
863	int error = 0;
864	enum vtype vtyp;
865
866	vtyp = nvap->na_type;
867	/*
868	 * Iff doesn't exist, create it.
869	 */
870	if (ndp->ni_vp) {
871		vrele(ndp->ni_startdir);
872		nfsvno_relpathbuf(ndp);
873		vput(ndp->ni_dvp);
874		vrele(ndp->ni_vp);
875		error = EEXIST;
876		goto out;
877	}
878	if (vtyp != VCHR && vtyp != VBLK && vtyp != VSOCK && vtyp != VFIFO) {
879		vrele(ndp->ni_startdir);
880		nfsvno_relpathbuf(ndp);
881		vput(ndp->ni_dvp);
882		error = NFSERR_BADTYPE;
883		goto out;
884	}
885	if (vtyp == VSOCK) {
886		vrele(ndp->ni_startdir);
887		error = VOP_CREATE(ndp->ni_dvp, &ndp->ni_vp,
888		    &ndp->ni_cnd, &nvap->na_vattr);
889		vput(ndp->ni_dvp);
890		nfsvno_relpathbuf(ndp);
891	} else {
892		if (nvap->na_type != VFIFO &&
893		    (error = priv_check_cred(cred, PRIV_VFS_MKNOD_DEV, 0))) {
894			vrele(ndp->ni_startdir);
895			nfsvno_relpathbuf(ndp);
896			vput(ndp->ni_dvp);
897			goto out;
898		}
899		error = VOP_MKNOD(ndp->ni_dvp, &ndp->ni_vp,
900		    &ndp->ni_cnd, &nvap->na_vattr);
901		vput(ndp->ni_dvp);
902		nfsvno_relpathbuf(ndp);
903		vrele(ndp->ni_startdir);
904		/*
905		 * Since VOP_MKNOD returns the ni_vp, I can't
906		 * see any reason to do the lookup.
907		 */
908	}
909
910out:
911	NFSEXITCODE(error);
912	return (error);
913}
914
915/*
916 * Mkdir vnode op.
917 */
918int
919nfsvno_mkdir(struct nameidata *ndp, struct nfsvattr *nvap, uid_t saved_uid,
920    struct ucred *cred, struct thread *p, struct nfsexstuff *exp)
921{
922	int error = 0;
923
924	if (ndp->ni_vp != NULL) {
925		if (ndp->ni_dvp == ndp->ni_vp)
926			vrele(ndp->ni_dvp);
927		else
928			vput(ndp->ni_dvp);
929		vrele(ndp->ni_vp);
930		nfsvno_relpathbuf(ndp);
931		error = EEXIST;
932		goto out;
933	}
934	error = VOP_MKDIR(ndp->ni_dvp, &ndp->ni_vp, &ndp->ni_cnd,
935	    &nvap->na_vattr);
936	vput(ndp->ni_dvp);
937	nfsvno_relpathbuf(ndp);
938
939out:
940	NFSEXITCODE(error);
941	return (error);
942}
943
944/*
945 * symlink vnode op.
946 */
947int
948nfsvno_symlink(struct nameidata *ndp, struct nfsvattr *nvap, char *pathcp,
949    int pathlen, int not_v2, uid_t saved_uid, struct ucred *cred, struct thread *p,
950    struct nfsexstuff *exp)
951{
952	int error = 0;
953
954	if (ndp->ni_vp) {
955		vrele(ndp->ni_startdir);
956		nfsvno_relpathbuf(ndp);
957		if (ndp->ni_dvp == ndp->ni_vp)
958			vrele(ndp->ni_dvp);
959		else
960			vput(ndp->ni_dvp);
961		vrele(ndp->ni_vp);
962		error = EEXIST;
963		goto out;
964	}
965
966	error = VOP_SYMLINK(ndp->ni_dvp, &ndp->ni_vp, &ndp->ni_cnd,
967	    &nvap->na_vattr, pathcp);
968	vput(ndp->ni_dvp);
969	vrele(ndp->ni_startdir);
970	nfsvno_relpathbuf(ndp);
971	/*
972	 * Although FreeBSD still had the lookup code in
973	 * it for 7/current, there doesn't seem to be any
974	 * point, since VOP_SYMLINK() returns the ni_vp.
975	 * Just vput it for v2.
976	 */
977	if (!not_v2 && !error)
978		vput(ndp->ni_vp);
979
980out:
981	NFSEXITCODE(error);
982	return (error);
983}
984
985/*
986 * Parse symbolic link arguments.
987 * This function has an ugly side effect. It will MALLOC() an area for
988 * the symlink and set iov_base to point to it, only if it succeeds.
989 * So, if it returns with uiop->uio_iov->iov_base != NULL, that must
990 * be FREE'd later.
991 */
992int
993nfsvno_getsymlink(struct nfsrv_descript *nd, struct nfsvattr *nvap,
994    struct thread *p, char **pathcpp, int *lenp)
995{
996	u_int32_t *tl;
997	char *pathcp = NULL;
998	int error = 0, len;
999	struct nfsv2_sattr *sp;
1000
1001	*pathcpp = NULL;
1002	*lenp = 0;
1003	if ((nd->nd_flag & ND_NFSV3) &&
1004	    (error = nfsrv_sattr(nd, nvap, NULL, NULL, p)))
1005		goto nfsmout;
1006	NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
1007	len = fxdr_unsigned(int, *tl);
1008	if (len > NFS_MAXPATHLEN || len <= 0) {
1009		error = EBADRPC;
1010		goto nfsmout;
1011	}
1012	MALLOC(pathcp, caddr_t, len + 1, M_TEMP, M_WAITOK);
1013	error = nfsrv_mtostr(nd, pathcp, len);
1014	if (error)
1015		goto nfsmout;
1016	if (nd->nd_flag & ND_NFSV2) {
1017		NFSM_DISSECT(sp, struct nfsv2_sattr *, NFSX_V2SATTR);
1018		nvap->na_mode = fxdr_unsigned(u_int16_t, sp->sa_mode);
1019	}
1020	*pathcpp = pathcp;
1021	*lenp = len;
1022	NFSEXITCODE2(0, nd);
1023	return (0);
1024nfsmout:
1025	if (pathcp)
1026		free(pathcp, M_TEMP);
1027	NFSEXITCODE2(error, nd);
1028	return (error);
1029}
1030
1031/*
1032 * Remove a non-directory object.
1033 */
1034int
1035nfsvno_removesub(struct nameidata *ndp, int is_v4, struct ucred *cred,
1036    struct thread *p, struct nfsexstuff *exp)
1037{
1038	struct vnode *vp;
1039	int error = 0;
1040
1041	vp = ndp->ni_vp;
1042	if (vp->v_type == VDIR)
1043		error = NFSERR_ISDIR;
1044	else if (is_v4)
1045		error = nfsrv_checkremove(vp, 1, p);
1046	if (!error)
1047		error = VOP_REMOVE(ndp->ni_dvp, vp, &ndp->ni_cnd);
1048	if (ndp->ni_dvp == vp)
1049		vrele(ndp->ni_dvp);
1050	else
1051		vput(ndp->ni_dvp);
1052	vput(vp);
1053	if ((ndp->ni_cnd.cn_flags & SAVENAME) != 0)
1054		nfsvno_relpathbuf(ndp);
1055	NFSEXITCODE(error);
1056	return (error);
1057}
1058
1059/*
1060 * Remove a directory.
1061 */
1062int
1063nfsvno_rmdirsub(struct nameidata *ndp, int is_v4, struct ucred *cred,
1064    struct thread *p, struct nfsexstuff *exp)
1065{
1066	struct vnode *vp;
1067	int error = 0;
1068
1069	vp = ndp->ni_vp;
1070	if (vp->v_type != VDIR) {
1071		error = ENOTDIR;
1072		goto out;
1073	}
1074	/*
1075	 * No rmdir "." please.
1076	 */
1077	if (ndp->ni_dvp == vp) {
1078		error = EINVAL;
1079		goto out;
1080	}
1081	/*
1082	 * The root of a mounted filesystem cannot be deleted.
1083	 */
1084	if (vp->v_vflag & VV_ROOT)
1085		error = EBUSY;
1086out:
1087	if (!error)
1088		error = VOP_RMDIR(ndp->ni_dvp, vp, &ndp->ni_cnd);
1089	if (ndp->ni_dvp == vp)
1090		vrele(ndp->ni_dvp);
1091	else
1092		vput(ndp->ni_dvp);
1093	vput(vp);
1094	if ((ndp->ni_cnd.cn_flags & SAVENAME) != 0)
1095		nfsvno_relpathbuf(ndp);
1096	NFSEXITCODE(error);
1097	return (error);
1098}
1099
1100/*
1101 * Rename vnode op.
1102 */
1103int
1104nfsvno_rename(struct nameidata *fromndp, struct nameidata *tondp,
1105    u_int32_t ndstat, u_int32_t ndflag, struct ucred *cred, struct thread *p)
1106{
1107	struct vnode *fvp, *tvp, *tdvp;
1108	int error = 0;
1109
1110	fvp = fromndp->ni_vp;
1111	if (ndstat) {
1112		vrele(fromndp->ni_dvp);
1113		vrele(fvp);
1114		error = ndstat;
1115		goto out1;
1116	}
1117	tdvp = tondp->ni_dvp;
1118	tvp = tondp->ni_vp;
1119	if (tvp != NULL) {
1120		if (fvp->v_type == VDIR && tvp->v_type != VDIR) {
1121			error = (ndflag & ND_NFSV2) ? EISDIR : EEXIST;
1122			goto out;
1123		} else if (fvp->v_type != VDIR && tvp->v_type == VDIR) {
1124			error = (ndflag & ND_NFSV2) ? ENOTDIR : EEXIST;
1125			goto out;
1126		}
1127		if (tvp->v_type == VDIR && tvp->v_mountedhere) {
1128			error = (ndflag & ND_NFSV2) ? ENOTEMPTY : EXDEV;
1129			goto out;
1130		}
1131
1132		/*
1133		 * A rename to '.' or '..' results in a prematurely
1134		 * unlocked vnode on FreeBSD5, so I'm just going to fail that
1135		 * here.
1136		 */
1137		if ((tondp->ni_cnd.cn_namelen == 1 &&
1138		     tondp->ni_cnd.cn_nameptr[0] == '.') ||
1139		    (tondp->ni_cnd.cn_namelen == 2 &&
1140		     tondp->ni_cnd.cn_nameptr[0] == '.' &&
1141		     tondp->ni_cnd.cn_nameptr[1] == '.')) {
1142			error = EINVAL;
1143			goto out;
1144		}
1145	}
1146	if (fvp->v_type == VDIR && fvp->v_mountedhere) {
1147		error = (ndflag & ND_NFSV2) ? ENOTEMPTY : EXDEV;
1148		goto out;
1149	}
1150	if (fvp->v_mount != tdvp->v_mount) {
1151		error = (ndflag & ND_NFSV2) ? ENOTEMPTY : EXDEV;
1152		goto out;
1153	}
1154	if (fvp == tdvp) {
1155		error = (ndflag & ND_NFSV2) ? ENOTEMPTY : EINVAL;
1156		goto out;
1157	}
1158	if (fvp == tvp) {
1159		/*
1160		 * If source and destination are the same, there is nothing to
1161		 * do. Set error to -1 to indicate this.
1162		 */
1163		error = -1;
1164		goto out;
1165	}
1166	if (ndflag & ND_NFSV4) {
1167		if (NFSVOPLOCK(fvp, LK_EXCLUSIVE) == 0) {
1168			error = nfsrv_checkremove(fvp, 0, p);
1169			NFSVOPUNLOCK(fvp, 0);
1170		} else
1171			error = EPERM;
1172		if (tvp && !error)
1173			error = nfsrv_checkremove(tvp, 1, p);
1174	} else {
1175		/*
1176		 * For NFSv2 and NFSv3, try to get rid of the delegation, so
1177		 * that the NFSv4 client won't be confused by the rename.
1178		 * Since nfsd_recalldelegation() can only be called on an
1179		 * unlocked vnode at this point and fvp is the file that will
1180		 * still exist after the rename, just do fvp.
1181		 */
1182		nfsd_recalldelegation(fvp, p);
1183	}
1184out:
1185	if (!error) {
1186		error = VOP_RENAME(fromndp->ni_dvp, fromndp->ni_vp,
1187		    &fromndp->ni_cnd, tondp->ni_dvp, tondp->ni_vp,
1188		    &tondp->ni_cnd);
1189	} else {
1190		if (tdvp == tvp)
1191			vrele(tdvp);
1192		else
1193			vput(tdvp);
1194		if (tvp)
1195			vput(tvp);
1196		vrele(fromndp->ni_dvp);
1197		vrele(fvp);
1198		if (error == -1)
1199			error = 0;
1200	}
1201	vrele(tondp->ni_startdir);
1202	nfsvno_relpathbuf(tondp);
1203out1:
1204	vrele(fromndp->ni_startdir);
1205	nfsvno_relpathbuf(fromndp);
1206	NFSEXITCODE(error);
1207	return (error);
1208}
1209
1210/*
1211 * Link vnode op.
1212 */
1213int
1214nfsvno_link(struct nameidata *ndp, struct vnode *vp, struct ucred *cred,
1215    struct thread *p, struct nfsexstuff *exp)
1216{
1217	struct vnode *xp;
1218	int error = 0;
1219
1220	xp = ndp->ni_vp;
1221	if (xp != NULL) {
1222		error = EEXIST;
1223	} else {
1224		xp = ndp->ni_dvp;
1225		if (vp->v_mount != xp->v_mount)
1226			error = EXDEV;
1227	}
1228	if (!error) {
1229		NFSVOPLOCK(vp, LK_EXCLUSIVE | LK_RETRY);
1230		if ((vp->v_iflag & VI_DOOMED) == 0)
1231			error = VOP_LINK(ndp->ni_dvp, vp, &ndp->ni_cnd);
1232		else
1233			error = EPERM;
1234		if (ndp->ni_dvp == vp)
1235			vrele(ndp->ni_dvp);
1236		else
1237			vput(ndp->ni_dvp);
1238		NFSVOPUNLOCK(vp, 0);
1239	} else {
1240		if (ndp->ni_dvp == ndp->ni_vp)
1241			vrele(ndp->ni_dvp);
1242		else
1243			vput(ndp->ni_dvp);
1244		if (ndp->ni_vp)
1245			vrele(ndp->ni_vp);
1246	}
1247	nfsvno_relpathbuf(ndp);
1248	NFSEXITCODE(error);
1249	return (error);
1250}
1251
1252/*
1253 * Do the fsync() appropriate for the commit.
1254 */
1255int
1256nfsvno_fsync(struct vnode *vp, u_int64_t off, int cnt, struct ucred *cred,
1257    struct thread *td)
1258{
1259	int error = 0;
1260
1261	/*
1262	 * RFC 1813 3.3.21: if count is 0, a flush from offset to the end of
1263	 * file is done.  At this time VOP_FSYNC does not accept offset and
1264	 * byte count parameters so call VOP_FSYNC the whole file for now.
1265	 * The same is true for NFSv4: RFC 3530 Sec. 14.2.3.
1266	 */
1267	if (cnt == 0 || cnt > MAX_COMMIT_COUNT) {
1268		/*
1269		 * Give up and do the whole thing
1270		 */
1271		if (vp->v_object &&
1272		   (vp->v_object->flags & OBJ_MIGHTBEDIRTY)) {
1273			VM_OBJECT_LOCK(vp->v_object);
1274			vm_object_page_clean(vp->v_object, 0, 0, OBJPC_SYNC);
1275			VM_OBJECT_UNLOCK(vp->v_object);
1276		}
1277		error = VOP_FSYNC(vp, MNT_WAIT, td);
1278	} else {
1279		/*
1280		 * Locate and synchronously write any buffers that fall
1281		 * into the requested range.  Note:  we are assuming that
1282		 * f_iosize is a power of 2.
1283		 */
1284		int iosize = vp->v_mount->mnt_stat.f_iosize;
1285		int iomask = iosize - 1;
1286		struct bufobj *bo;
1287		daddr_t lblkno;
1288
1289		/*
1290		 * Align to iosize boundry, super-align to page boundry.
1291		 */
1292		if (off & iomask) {
1293			cnt += off & iomask;
1294			off &= ~(u_quad_t)iomask;
1295		}
1296		if (off & PAGE_MASK) {
1297			cnt += off & PAGE_MASK;
1298			off &= ~(u_quad_t)PAGE_MASK;
1299		}
1300		lblkno = off / iosize;
1301
1302		if (vp->v_object &&
1303		   (vp->v_object->flags & OBJ_MIGHTBEDIRTY)) {
1304			VM_OBJECT_LOCK(vp->v_object);
1305			vm_object_page_clean(vp->v_object, off, off + cnt,
1306			    OBJPC_SYNC);
1307			VM_OBJECT_UNLOCK(vp->v_object);
1308		}
1309
1310		bo = &vp->v_bufobj;
1311		BO_LOCK(bo);
1312		while (cnt > 0) {
1313			struct buf *bp;
1314
1315			/*
1316			 * If we have a buffer and it is marked B_DELWRI we
1317			 * have to lock and write it.  Otherwise the prior
1318			 * write is assumed to have already been committed.
1319			 *
1320			 * gbincore() can return invalid buffers now so we
1321			 * have to check that bit as well (though B_DELWRI
1322			 * should not be set if B_INVAL is set there could be
1323			 * a race here since we haven't locked the buffer).
1324			 */
1325			if ((bp = gbincore(&vp->v_bufobj, lblkno)) != NULL) {
1326				if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_SLEEPFAIL |
1327				    LK_INTERLOCK, BO_MTX(bo)) == ENOLCK) {
1328					BO_LOCK(bo);
1329					continue; /* retry */
1330				}
1331			    	if ((bp->b_flags & (B_DELWRI|B_INVAL)) ==
1332				    B_DELWRI) {
1333					bremfree(bp);
1334					bp->b_flags &= ~B_ASYNC;
1335					bwrite(bp);
1336					++nfs_commit_miss;
1337				} else
1338					BUF_UNLOCK(bp);
1339				BO_LOCK(bo);
1340			}
1341			++nfs_commit_blks;
1342			if (cnt < iosize)
1343				break;
1344			cnt -= iosize;
1345			++lblkno;
1346		}
1347		BO_UNLOCK(bo);
1348	}
1349	NFSEXITCODE(error);
1350	return (error);
1351}
1352
1353/*
1354 * Statfs vnode op.
1355 */
1356int
1357nfsvno_statfs(struct vnode *vp, struct statfs *sf)
1358{
1359	int error;
1360
1361	error = VFS_STATFS(vp->v_mount, sf);
1362	if (error == 0) {
1363		/*
1364		 * Since NFS handles these values as unsigned on the
1365		 * wire, there is no way to represent negative values,
1366		 * so set them to 0. Without this, they will appear
1367		 * to be very large positive values for clients like
1368		 * Solaris10.
1369		 */
1370		if (sf->f_bavail < 0)
1371			sf->f_bavail = 0;
1372		if (sf->f_ffree < 0)
1373			sf->f_ffree = 0;
1374	}
1375	NFSEXITCODE(error);
1376	return (error);
1377}
1378
1379/*
1380 * Do the vnode op stuff for Open. Similar to nfsvno_createsub(), but
1381 * must handle nfsrv_opencheck() calls after any other access checks.
1382 */
1383void
1384nfsvno_open(struct nfsrv_descript *nd, struct nameidata *ndp,
1385    nfsquad_t clientid, nfsv4stateid_t *stateidp, struct nfsstate *stp,
1386    int *exclusive_flagp, struct nfsvattr *nvap, int32_t *cverf, int create,
1387    NFSACL_T *aclp, nfsattrbit_t *attrbitp, struct ucred *cred, struct thread *p,
1388    struct nfsexstuff *exp, struct vnode **vpp)
1389{
1390	struct vnode *vp = NULL;
1391	u_quad_t tempsize;
1392	struct nfsexstuff nes;
1393
1394	if (ndp->ni_vp == NULL)
1395		nd->nd_repstat = nfsrv_opencheck(clientid,
1396		    stateidp, stp, NULL, nd, p, nd->nd_repstat);
1397	if (!nd->nd_repstat) {
1398		if (ndp->ni_vp == NULL) {
1399			vrele(ndp->ni_startdir);
1400			nd->nd_repstat = VOP_CREATE(ndp->ni_dvp,
1401			    &ndp->ni_vp, &ndp->ni_cnd, &nvap->na_vattr);
1402			vput(ndp->ni_dvp);
1403			nfsvno_relpathbuf(ndp);
1404			if (!nd->nd_repstat) {
1405				if (*exclusive_flagp) {
1406					*exclusive_flagp = 0;
1407					NFSVNO_ATTRINIT(nvap);
1408					nvap->na_atime.tv_sec = cverf[0];
1409					nvap->na_atime.tv_nsec = cverf[1];
1410					nd->nd_repstat = VOP_SETATTR(ndp->ni_vp,
1411					    &nvap->na_vattr, cred);
1412				} else {
1413					nfsrv_fixattr(nd, ndp->ni_vp, nvap,
1414					    aclp, p, attrbitp, exp);
1415				}
1416			}
1417			vp = ndp->ni_vp;
1418		} else {
1419			if (ndp->ni_startdir)
1420				vrele(ndp->ni_startdir);
1421			nfsvno_relpathbuf(ndp);
1422			vp = ndp->ni_vp;
1423			if (create == NFSV4OPEN_CREATE) {
1424				if (ndp->ni_dvp == vp)
1425					vrele(ndp->ni_dvp);
1426				else
1427					vput(ndp->ni_dvp);
1428			}
1429			if (NFSVNO_ISSETSIZE(nvap) && vp->v_type == VREG) {
1430				if (ndp->ni_cnd.cn_flags & RDONLY)
1431					NFSVNO_SETEXRDONLY(&nes);
1432				else
1433					NFSVNO_EXINIT(&nes);
1434				nd->nd_repstat = nfsvno_accchk(vp,
1435				    VWRITE, cred, &nes, p,
1436				    NFSACCCHK_NOOVERRIDE,
1437				    NFSACCCHK_VPISLOCKED, NULL);
1438				nd->nd_repstat = nfsrv_opencheck(clientid,
1439				    stateidp, stp, vp, nd, p, nd->nd_repstat);
1440				if (!nd->nd_repstat) {
1441					tempsize = nvap->na_size;
1442					NFSVNO_ATTRINIT(nvap);
1443					nvap->na_size = tempsize;
1444					nd->nd_repstat = VOP_SETATTR(vp,
1445					    &nvap->na_vattr, cred);
1446				}
1447			} else if (vp->v_type == VREG) {
1448				nd->nd_repstat = nfsrv_opencheck(clientid,
1449				    stateidp, stp, vp, nd, p, nd->nd_repstat);
1450			}
1451		}
1452	} else {
1453		if (ndp->ni_cnd.cn_flags & HASBUF)
1454			nfsvno_relpathbuf(ndp);
1455		if (ndp->ni_startdir && create == NFSV4OPEN_CREATE) {
1456			vrele(ndp->ni_startdir);
1457			if (ndp->ni_dvp == ndp->ni_vp)
1458				vrele(ndp->ni_dvp);
1459			else
1460				vput(ndp->ni_dvp);
1461			if (ndp->ni_vp)
1462				vput(ndp->ni_vp);
1463		}
1464	}
1465	*vpp = vp;
1466
1467	NFSEXITCODE2(0, nd);
1468}
1469
1470/*
1471 * Updates the file rev and sets the mtime and ctime
1472 * to the current clock time, returning the va_filerev and va_Xtime
1473 * values.
1474 * Return ESTALE to indicate the vnode is VI_DOOMED.
1475 */
1476int
1477nfsvno_updfilerev(struct vnode *vp, struct nfsvattr *nvap,
1478    struct ucred *cred, struct thread *p)
1479{
1480	struct vattr va;
1481
1482	VATTR_NULL(&va);
1483	vfs_timestamp(&va.va_mtime);
1484	if (NFSVOPISLOCKED(vp) != LK_EXCLUSIVE) {
1485		NFSVOPLOCK(vp, LK_UPGRADE | LK_RETRY);
1486		if ((vp->v_iflag & VI_DOOMED) != 0)
1487			return (ESTALE);
1488	}
1489	(void) VOP_SETATTR(vp, &va, cred);
1490	(void) nfsvno_getattr(vp, nvap, cred, p, 1);
1491	return (0);
1492}
1493
1494/*
1495 * Glue routine to nfsv4_fillattr().
1496 */
1497int
1498nfsvno_fillattr(struct nfsrv_descript *nd, struct mount *mp, struct vnode *vp,
1499    struct nfsvattr *nvap, fhandle_t *fhp, int rderror, nfsattrbit_t *attrbitp,
1500    struct ucred *cred, struct thread *p, int isdgram, int reterr,
1501    int supports_nfsv4acls, int at_root, uint64_t mounted_on_fileno)
1502{
1503	int error;
1504
1505	error = nfsv4_fillattr(nd, mp, vp, NULL, &nvap->na_vattr, fhp, rderror,
1506	    attrbitp, cred, p, isdgram, reterr, supports_nfsv4acls, at_root,
1507	    mounted_on_fileno);
1508	NFSEXITCODE2(0, nd);
1509	return (error);
1510}
1511
1512/* Since the Readdir vnode ops vary, put the entire functions in here. */
1513/*
1514 * nfs readdir service
1515 * - mallocs what it thinks is enough to read
1516 *	count rounded up to a multiple of DIRBLKSIZ <= NFS_MAXREADDIR
1517 * - calls VOP_READDIR()
1518 * - loops around building the reply
1519 *	if the output generated exceeds count break out of loop
1520 *	The NFSM_CLGET macro is used here so that the reply will be packed
1521 *	tightly in mbuf clusters.
1522 * - it trims out records with d_fileno == 0
1523 *	this doesn't matter for Unix clients, but they might confuse clients
1524 *	for other os'.
1525 * - it trims out records with d_type == DT_WHT
1526 *	these cannot be seen through NFS (unless we extend the protocol)
1527 *     The alternate call nfsrvd_readdirplus() does lookups as well.
1528 * PS: The NFS protocol spec. does not clarify what the "count" byte
1529 *	argument is a count of.. just name strings and file id's or the
1530 *	entire reply rpc or ...
1531 *	I tried just file name and id sizes and it confused the Sun client,
1532 *	so I am using the full rpc size now. The "paranoia.." comment refers
1533 *	to including the status longwords that are not a part of the dir.
1534 *	"entry" structures, but are in the rpc.
1535 */
1536int
1537nfsrvd_readdir(struct nfsrv_descript *nd, int isdgram,
1538    struct vnode *vp, struct thread *p, struct nfsexstuff *exp)
1539{
1540	struct dirent *dp;
1541	u_int32_t *tl;
1542	int dirlen;
1543	char *cpos, *cend, *rbuf;
1544	struct nfsvattr at;
1545	int nlen, error = 0, getret = 1;
1546	int siz, cnt, fullsiz, eofflag, ncookies;
1547	u_int64_t off, toff, verf;
1548	u_long *cookies = NULL, *cookiep;
1549	struct uio io;
1550	struct iovec iv;
1551	int not_zfs;
1552
1553	if (nd->nd_repstat) {
1554		nfsrv_postopattr(nd, getret, &at);
1555		goto out;
1556	}
1557	if (nd->nd_flag & ND_NFSV2) {
1558		NFSM_DISSECT(tl, u_int32_t *, 2 * NFSX_UNSIGNED);
1559		off = fxdr_unsigned(u_quad_t, *tl++);
1560	} else {
1561		NFSM_DISSECT(tl, u_int32_t *, 5 * NFSX_UNSIGNED);
1562		off = fxdr_hyper(tl);
1563		tl += 2;
1564		verf = fxdr_hyper(tl);
1565		tl += 2;
1566	}
1567	toff = off;
1568	cnt = fxdr_unsigned(int, *tl);
1569	if (cnt > NFS_SRVMAXDATA(nd) || cnt < 0)
1570		cnt = NFS_SRVMAXDATA(nd);
1571	siz = ((cnt + DIRBLKSIZ - 1) & ~(DIRBLKSIZ - 1));
1572	fullsiz = siz;
1573	if (nd->nd_flag & ND_NFSV3) {
1574		nd->nd_repstat = getret = nfsvno_getattr(vp, &at, nd->nd_cred,
1575		    p, 1);
1576#if 0
1577		/*
1578		 * va_filerev is not sufficient as a cookie verifier,
1579		 * since it is not supposed to change when entries are
1580		 * removed/added unless that offset cookies returned to
1581		 * the client are no longer valid.
1582		 */
1583		if (!nd->nd_repstat && toff && verf != at.na_filerev)
1584			nd->nd_repstat = NFSERR_BAD_COOKIE;
1585#endif
1586	}
1587	if (!nd->nd_repstat && vp->v_type != VDIR)
1588		nd->nd_repstat = NFSERR_NOTDIR;
1589	if (nd->nd_repstat == 0 && cnt == 0) {
1590		if (nd->nd_flag & ND_NFSV2)
1591			/* NFSv2 does not have NFSERR_TOOSMALL */
1592			nd->nd_repstat = EPERM;
1593		else
1594			nd->nd_repstat = NFSERR_TOOSMALL;
1595	}
1596	if (!nd->nd_repstat)
1597		nd->nd_repstat = nfsvno_accchk(vp, VEXEC,
1598		    nd->nd_cred, exp, p, NFSACCCHK_NOOVERRIDE,
1599		    NFSACCCHK_VPISLOCKED, NULL);
1600	if (nd->nd_repstat) {
1601		vput(vp);
1602		if (nd->nd_flag & ND_NFSV3)
1603			nfsrv_postopattr(nd, getret, &at);
1604		goto out;
1605	}
1606	not_zfs = strcmp(vp->v_mount->mnt_vfc->vfc_name, "zfs");
1607	MALLOC(rbuf, caddr_t, siz, M_TEMP, M_WAITOK);
1608again:
1609	eofflag = 0;
1610	if (cookies) {
1611		free((caddr_t)cookies, M_TEMP);
1612		cookies = NULL;
1613	}
1614
1615	iv.iov_base = rbuf;
1616	iv.iov_len = siz;
1617	io.uio_iov = &iv;
1618	io.uio_iovcnt = 1;
1619	io.uio_offset = (off_t)off;
1620	io.uio_resid = siz;
1621	io.uio_segflg = UIO_SYSSPACE;
1622	io.uio_rw = UIO_READ;
1623	io.uio_td = NULL;
1624	nd->nd_repstat = VOP_READDIR(vp, &io, nd->nd_cred, &eofflag, &ncookies,
1625	    &cookies);
1626	off = (u_int64_t)io.uio_offset;
1627	if (io.uio_resid)
1628		siz -= io.uio_resid;
1629
1630	if (!cookies && !nd->nd_repstat)
1631		nd->nd_repstat = NFSERR_PERM;
1632	if (nd->nd_flag & ND_NFSV3) {
1633		getret = nfsvno_getattr(vp, &at, nd->nd_cred, p, 1);
1634		if (!nd->nd_repstat)
1635			nd->nd_repstat = getret;
1636	}
1637
1638	/*
1639	 * Handles the failed cases. nd->nd_repstat == 0 past here.
1640	 */
1641	if (nd->nd_repstat) {
1642		vput(vp);
1643		free((caddr_t)rbuf, M_TEMP);
1644		if (cookies)
1645			free((caddr_t)cookies, M_TEMP);
1646		if (nd->nd_flag & ND_NFSV3)
1647			nfsrv_postopattr(nd, getret, &at);
1648		goto out;
1649	}
1650	/*
1651	 * If nothing read, return eof
1652	 * rpc reply
1653	 */
1654	if (siz == 0) {
1655		vput(vp);
1656		if (nd->nd_flag & ND_NFSV2) {
1657			NFSM_BUILD(tl, u_int32_t *, 2 * NFSX_UNSIGNED);
1658		} else {
1659			nfsrv_postopattr(nd, getret, &at);
1660			NFSM_BUILD(tl, u_int32_t *, 4 * NFSX_UNSIGNED);
1661			txdr_hyper(at.na_filerev, tl);
1662			tl += 2;
1663		}
1664		*tl++ = newnfs_false;
1665		*tl = newnfs_true;
1666		FREE((caddr_t)rbuf, M_TEMP);
1667		FREE((caddr_t)cookies, M_TEMP);
1668		goto out;
1669	}
1670
1671	/*
1672	 * Check for degenerate cases of nothing useful read.
1673	 * If so go try again
1674	 */
1675	cpos = rbuf;
1676	cend = rbuf + siz;
1677	dp = (struct dirent *)cpos;
1678	cookiep = cookies;
1679
1680	/*
1681	 * For some reason FreeBSD's ufs_readdir() chooses to back the
1682	 * directory offset up to a block boundary, so it is necessary to
1683	 * skip over the records that precede the requested offset. This
1684	 * requires the assumption that file offset cookies monotonically
1685	 * increase.
1686	 * Since the offset cookies don't monotonically increase for ZFS,
1687	 * this is not done when ZFS is the file system.
1688	 */
1689	while (cpos < cend && ncookies > 0 &&
1690	    (dp->d_fileno == 0 || dp->d_type == DT_WHT ||
1691	     (not_zfs != 0 && ((u_quad_t)(*cookiep)) <= toff))) {
1692		cpos += dp->d_reclen;
1693		dp = (struct dirent *)cpos;
1694		cookiep++;
1695		ncookies--;
1696	}
1697	if (cpos >= cend || ncookies == 0) {
1698		siz = fullsiz;
1699		toff = off;
1700		goto again;
1701	}
1702	vput(vp);
1703
1704	/*
1705	 * dirlen is the size of the reply, including all XDR and must
1706	 * not exceed cnt. For NFSv2, RFC1094 didn't clearly indicate
1707	 * if the XDR should be included in "count", but to be safe, we do.
1708	 * (Include the two booleans at the end of the reply in dirlen now.)
1709	 */
1710	if (nd->nd_flag & ND_NFSV3) {
1711		nfsrv_postopattr(nd, getret, &at);
1712		NFSM_BUILD(tl, u_int32_t *, 2 * NFSX_UNSIGNED);
1713		txdr_hyper(at.na_filerev, tl);
1714		dirlen = NFSX_V3POSTOPATTR + NFSX_VERF + 2 * NFSX_UNSIGNED;
1715	} else {
1716		dirlen = 2 * NFSX_UNSIGNED;
1717	}
1718
1719	/* Loop through the records and build reply */
1720	while (cpos < cend && ncookies > 0) {
1721		nlen = dp->d_namlen;
1722		if (dp->d_fileno != 0 && dp->d_type != DT_WHT &&
1723			nlen <= NFS_MAXNAMLEN) {
1724			if (nd->nd_flag & ND_NFSV3)
1725				dirlen += (6*NFSX_UNSIGNED + NFSM_RNDUP(nlen));
1726			else
1727				dirlen += (4*NFSX_UNSIGNED + NFSM_RNDUP(nlen));
1728			if (dirlen > cnt) {
1729				eofflag = 0;
1730				break;
1731			}
1732
1733			/*
1734			 * Build the directory record xdr from
1735			 * the dirent entry.
1736			 */
1737			if (nd->nd_flag & ND_NFSV3) {
1738				NFSM_BUILD(tl, u_int32_t *, 3 * NFSX_UNSIGNED);
1739				*tl++ = newnfs_true;
1740				*tl++ = 0;
1741			} else {
1742				NFSM_BUILD(tl, u_int32_t *, 2 * NFSX_UNSIGNED);
1743				*tl++ = newnfs_true;
1744			}
1745			*tl = txdr_unsigned(dp->d_fileno);
1746			(void) nfsm_strtom(nd, dp->d_name, nlen);
1747			if (nd->nd_flag & ND_NFSV3) {
1748				NFSM_BUILD(tl, u_int32_t *, 2 * NFSX_UNSIGNED);
1749				*tl++ = 0;
1750			} else
1751				NFSM_BUILD(tl, u_int32_t *, NFSX_UNSIGNED);
1752			*tl = txdr_unsigned(*cookiep);
1753		}
1754		cpos += dp->d_reclen;
1755		dp = (struct dirent *)cpos;
1756		cookiep++;
1757		ncookies--;
1758	}
1759	if (cpos < cend)
1760		eofflag = 0;
1761	NFSM_BUILD(tl, u_int32_t *, 2 * NFSX_UNSIGNED);
1762	*tl++ = newnfs_false;
1763	if (eofflag)
1764		*tl = newnfs_true;
1765	else
1766		*tl = newnfs_false;
1767	FREE((caddr_t)rbuf, M_TEMP);
1768	FREE((caddr_t)cookies, M_TEMP);
1769
1770out:
1771	NFSEXITCODE2(0, nd);
1772	return (0);
1773nfsmout:
1774	vput(vp);
1775	NFSEXITCODE2(error, nd);
1776	return (error);
1777}
1778
1779/*
1780 * Readdirplus for V3 and Readdir for V4.
1781 */
1782int
1783nfsrvd_readdirplus(struct nfsrv_descript *nd, int isdgram,
1784    struct vnode *vp, struct thread *p, struct nfsexstuff *exp)
1785{
1786	struct dirent *dp;
1787	u_int32_t *tl;
1788	int dirlen;
1789	char *cpos, *cend, *rbuf;
1790	struct vnode *nvp;
1791	fhandle_t nfh;
1792	struct nfsvattr nva, at, *nvap = &nva;
1793	struct mbuf *mb0, *mb1;
1794	struct nfsreferral *refp;
1795	int nlen, r, error = 0, getret = 1, usevget = 1;
1796	int siz, cnt, fullsiz, eofflag, ncookies, entrycnt;
1797	caddr_t bpos0, bpos1;
1798	u_int64_t off, toff, verf;
1799	u_long *cookies = NULL, *cookiep;
1800	nfsattrbit_t attrbits, rderrbits, savbits;
1801	struct uio io;
1802	struct iovec iv;
1803	struct componentname cn;
1804	int at_root, needs_unbusy, not_zfs, supports_nfsv4acls;
1805	struct mount *mp, *new_mp;
1806	uint64_t mounted_on_fileno;
1807
1808	if (nd->nd_repstat) {
1809		nfsrv_postopattr(nd, getret, &at);
1810		goto out;
1811	}
1812	NFSM_DISSECT(tl, u_int32_t *, 6 * NFSX_UNSIGNED);
1813	off = fxdr_hyper(tl);
1814	toff = off;
1815	tl += 2;
1816	verf = fxdr_hyper(tl);
1817	tl += 2;
1818	siz = fxdr_unsigned(int, *tl++);
1819	cnt = fxdr_unsigned(int, *tl);
1820
1821	/*
1822	 * Use the server's maximum data transfer size as the upper bound
1823	 * on reply datalen.
1824	 */
1825	if (cnt > NFS_SRVMAXDATA(nd) || cnt < 0)
1826		cnt = NFS_SRVMAXDATA(nd);
1827
1828	/*
1829	 * siz is a "hint" of how much directory information (name, fileid,
1830	 * cookie) should be in the reply. At least one client "hints" 0,
1831	 * so I set it to cnt for that case. I also round it up to the
1832	 * next multiple of DIRBLKSIZ.
1833	 */
1834	if (siz <= 0)
1835		siz = cnt;
1836	siz = ((siz + DIRBLKSIZ - 1) & ~(DIRBLKSIZ - 1));
1837
1838	if (nd->nd_flag & ND_NFSV4) {
1839		error = nfsrv_getattrbits(nd, &attrbits, NULL, NULL);
1840		if (error)
1841			goto nfsmout;
1842		NFSSET_ATTRBIT(&savbits, &attrbits);
1843		NFSCLRNOTFILLABLE_ATTRBIT(&attrbits);
1844		NFSZERO_ATTRBIT(&rderrbits);
1845		NFSSETBIT_ATTRBIT(&rderrbits, NFSATTRBIT_RDATTRERROR);
1846	} else {
1847		NFSZERO_ATTRBIT(&attrbits);
1848	}
1849	fullsiz = siz;
1850	nd->nd_repstat = getret = nfsvno_getattr(vp, &at, nd->nd_cred, p, 1);
1851	if (!nd->nd_repstat) {
1852	    if (off && verf != at.na_filerev) {
1853		/*
1854		 * va_filerev is not sufficient as a cookie verifier,
1855		 * since it is not supposed to change when entries are
1856		 * removed/added unless that offset cookies returned to
1857		 * the client are no longer valid.
1858		 */
1859#if 0
1860		if (nd->nd_flag & ND_NFSV4) {
1861			nd->nd_repstat = NFSERR_NOTSAME;
1862		} else {
1863			nd->nd_repstat = NFSERR_BAD_COOKIE;
1864		}
1865#endif
1866	    } else if ((nd->nd_flag & ND_NFSV4) && off == 0 && verf != 0) {
1867		nd->nd_repstat = NFSERR_BAD_COOKIE;
1868	    }
1869	}
1870	if (!nd->nd_repstat && vp->v_type != VDIR)
1871		nd->nd_repstat = NFSERR_NOTDIR;
1872	if (!nd->nd_repstat && cnt == 0)
1873		nd->nd_repstat = NFSERR_TOOSMALL;
1874	if (!nd->nd_repstat)
1875		nd->nd_repstat = nfsvno_accchk(vp, VEXEC,
1876		    nd->nd_cred, exp, p, NFSACCCHK_NOOVERRIDE,
1877		    NFSACCCHK_VPISLOCKED, NULL);
1878	if (nd->nd_repstat) {
1879		vput(vp);
1880		if (nd->nd_flag & ND_NFSV3)
1881			nfsrv_postopattr(nd, getret, &at);
1882		goto out;
1883	}
1884	not_zfs = strcmp(vp->v_mount->mnt_vfc->vfc_name, "zfs");
1885
1886	MALLOC(rbuf, caddr_t, siz, M_TEMP, M_WAITOK);
1887again:
1888	eofflag = 0;
1889	if (cookies) {
1890		free((caddr_t)cookies, M_TEMP);
1891		cookies = NULL;
1892	}
1893
1894	iv.iov_base = rbuf;
1895	iv.iov_len = siz;
1896	io.uio_iov = &iv;
1897	io.uio_iovcnt = 1;
1898	io.uio_offset = (off_t)off;
1899	io.uio_resid = siz;
1900	io.uio_segflg = UIO_SYSSPACE;
1901	io.uio_rw = UIO_READ;
1902	io.uio_td = NULL;
1903	nd->nd_repstat = VOP_READDIR(vp, &io, nd->nd_cred, &eofflag, &ncookies,
1904	    &cookies);
1905	off = (u_int64_t)io.uio_offset;
1906	if (io.uio_resid)
1907		siz -= io.uio_resid;
1908
1909	getret = nfsvno_getattr(vp, &at, nd->nd_cred, p, 1);
1910
1911	if (!cookies && !nd->nd_repstat)
1912		nd->nd_repstat = NFSERR_PERM;
1913	if (!nd->nd_repstat)
1914		nd->nd_repstat = getret;
1915	if (nd->nd_repstat) {
1916		vput(vp);
1917		if (cookies)
1918			free((caddr_t)cookies, M_TEMP);
1919		free((caddr_t)rbuf, M_TEMP);
1920		if (nd->nd_flag & ND_NFSV3)
1921			nfsrv_postopattr(nd, getret, &at);
1922		goto out;
1923	}
1924	/*
1925	 * If nothing read, return eof
1926	 * rpc reply
1927	 */
1928	if (siz == 0) {
1929		vput(vp);
1930		if (nd->nd_flag & ND_NFSV3)
1931			nfsrv_postopattr(nd, getret, &at);
1932		NFSM_BUILD(tl, u_int32_t *, 4 * NFSX_UNSIGNED);
1933		txdr_hyper(at.na_filerev, tl);
1934		tl += 2;
1935		*tl++ = newnfs_false;
1936		*tl = newnfs_true;
1937		free((caddr_t)cookies, M_TEMP);
1938		free((caddr_t)rbuf, M_TEMP);
1939		goto out;
1940	}
1941
1942	/*
1943	 * Check for degenerate cases of nothing useful read.
1944	 * If so go try again
1945	 */
1946	cpos = rbuf;
1947	cend = rbuf + siz;
1948	dp = (struct dirent *)cpos;
1949	cookiep = cookies;
1950
1951	/*
1952	 * For some reason FreeBSD's ufs_readdir() chooses to back the
1953	 * directory offset up to a block boundary, so it is necessary to
1954	 * skip over the records that precede the requested offset. This
1955	 * requires the assumption that file offset cookies monotonically
1956	 * increase.
1957	 * Since the offset cookies don't monotonically increase for ZFS,
1958	 * this is not done when ZFS is the file system.
1959	 */
1960	while (cpos < cend && ncookies > 0 &&
1961	  (dp->d_fileno == 0 || dp->d_type == DT_WHT ||
1962	   (not_zfs != 0 && ((u_quad_t)(*cookiep)) <= toff) ||
1963	   ((nd->nd_flag & ND_NFSV4) &&
1964	    ((dp->d_namlen == 1 && dp->d_name[0] == '.') ||
1965	     (dp->d_namlen==2 && dp->d_name[0]=='.' && dp->d_name[1]=='.'))))) {
1966		cpos += dp->d_reclen;
1967		dp = (struct dirent *)cpos;
1968		cookiep++;
1969		ncookies--;
1970	}
1971	if (cpos >= cend || ncookies == 0) {
1972		siz = fullsiz;
1973		toff = off;
1974		goto again;
1975	}
1976
1977	/*
1978	 * Busy the file system so that the mount point won't go away
1979	 * and, as such, VFS_VGET() can be used safely.
1980	 */
1981	mp = vp->v_mount;
1982	vfs_ref(mp);
1983	NFSVOPUNLOCK(vp, 0);
1984	nd->nd_repstat = vfs_busy(mp, 0);
1985	vfs_rel(mp);
1986	if (nd->nd_repstat != 0) {
1987		vrele(vp);
1988		free(cookies, M_TEMP);
1989		free(rbuf, M_TEMP);
1990		if (nd->nd_flag & ND_NFSV3)
1991			nfsrv_postopattr(nd, getret, &at);
1992		goto out;
1993	}
1994
1995	/*
1996	 * Check to see if entries in this directory can be safely acquired
1997	 * via VFS_VGET() or if a switch to VOP_LOOKUP() is required.
1998	 * ZFS snapshot directories need VOP_LOOKUP(), so that any
1999	 * automount of the snapshot directory that is required will
2000	 * be done.
2001	 * This needs to be done here for NFSv4, since NFSv4 never does
2002	 * a VFS_VGET() for "." or "..".
2003	 */
2004	if (not_zfs == 0) {
2005		r = VFS_VGET(mp, at.na_fileid, LK_SHARED, &nvp);
2006		if (r == EOPNOTSUPP) {
2007			usevget = 0;
2008			cn.cn_nameiop = LOOKUP;
2009			cn.cn_lkflags = LK_SHARED | LK_RETRY;
2010			cn.cn_cred = nd->nd_cred;
2011			cn.cn_thread = p;
2012		} else if (r == 0)
2013			vput(nvp);
2014	}
2015
2016	/*
2017	 * Save this position, in case there is an error before one entry
2018	 * is created.
2019	 */
2020	mb0 = nd->nd_mb;
2021	bpos0 = nd->nd_bpos;
2022
2023	/*
2024	 * Fill in the first part of the reply.
2025	 * dirlen is the reply length in bytes and cannot exceed cnt.
2026	 * (Include the two booleans at the end of the reply in dirlen now,
2027	 *  so we recognize when we have exceeded cnt.)
2028	 */
2029	if (nd->nd_flag & ND_NFSV3) {
2030		dirlen = NFSX_V3POSTOPATTR + NFSX_VERF + 2 * NFSX_UNSIGNED;
2031		nfsrv_postopattr(nd, getret, &at);
2032	} else {
2033		dirlen = NFSX_VERF + 2 * NFSX_UNSIGNED;
2034	}
2035	NFSM_BUILD(tl, u_int32_t *, NFSX_VERF);
2036	txdr_hyper(at.na_filerev, tl);
2037
2038	/*
2039	 * Save this position, in case there is an empty reply needed.
2040	 */
2041	mb1 = nd->nd_mb;
2042	bpos1 = nd->nd_bpos;
2043
2044	/* Loop through the records and build reply */
2045	entrycnt = 0;
2046	while (cpos < cend && ncookies > 0 && dirlen < cnt) {
2047		nlen = dp->d_namlen;
2048		if (dp->d_fileno != 0 && dp->d_type != DT_WHT &&
2049		    nlen <= NFS_MAXNAMLEN &&
2050		    ((nd->nd_flag & ND_NFSV3) || nlen > 2 ||
2051		     (nlen==2 && (dp->d_name[0]!='.' || dp->d_name[1]!='.'))
2052		      || (nlen == 1 && dp->d_name[0] != '.'))) {
2053			/*
2054			 * Save the current position in the reply, in case
2055			 * this entry exceeds cnt.
2056			 */
2057			mb1 = nd->nd_mb;
2058			bpos1 = nd->nd_bpos;
2059
2060			/*
2061			 * For readdir_and_lookup get the vnode using
2062			 * the file number.
2063			 */
2064			nvp = NULL;
2065			refp = NULL;
2066			r = 0;
2067			at_root = 0;
2068			needs_unbusy = 0;
2069			new_mp = mp;
2070			mounted_on_fileno = (uint64_t)dp->d_fileno;
2071			if ((nd->nd_flag & ND_NFSV3) ||
2072			    NFSNONZERO_ATTRBIT(&savbits)) {
2073				if (nd->nd_flag & ND_NFSV4)
2074					refp = nfsv4root_getreferral(NULL,
2075					    vp, dp->d_fileno);
2076				if (refp == NULL) {
2077					if (usevget)
2078						r = VFS_VGET(mp, dp->d_fileno,
2079						    LK_SHARED, &nvp);
2080					else
2081						r = EOPNOTSUPP;
2082					if (r == EOPNOTSUPP) {
2083						if (usevget) {
2084							usevget = 0;
2085							cn.cn_nameiop = LOOKUP;
2086							cn.cn_lkflags =
2087							    LK_SHARED |
2088							    LK_RETRY;
2089							cn.cn_cred =
2090							    nd->nd_cred;
2091							cn.cn_thread = p;
2092						}
2093						cn.cn_nameptr = dp->d_name;
2094						cn.cn_namelen = nlen;
2095						cn.cn_flags = ISLASTCN |
2096						    NOFOLLOW | LOCKLEAF |
2097						    MPSAFE;
2098						if (nlen == 2 &&
2099						    dp->d_name[0] == '.' &&
2100						    dp->d_name[1] == '.')
2101							cn.cn_flags |=
2102							    ISDOTDOT;
2103						if (NFSVOPLOCK(vp, LK_SHARED)
2104						    != 0) {
2105							nd->nd_repstat = EPERM;
2106							break;
2107						}
2108						if ((vp->v_vflag & VV_ROOT) != 0
2109						    && (cn.cn_flags & ISDOTDOT)
2110						    != 0) {
2111							vref(vp);
2112							nvp = vp;
2113							r = 0;
2114						} else {
2115							r = VOP_LOOKUP(vp, &nvp,
2116							    &cn);
2117							if (vp != nvp)
2118								NFSVOPUNLOCK(vp,
2119								    0);
2120						}
2121					}
2122
2123					/*
2124					 * For NFSv4, check to see if nvp is
2125					 * a mount point and get the mount
2126					 * point vnode, as required.
2127					 */
2128					if (r == 0 &&
2129					    nfsrv_enable_crossmntpt != 0 &&
2130					    (nd->nd_flag & ND_NFSV4) != 0 &&
2131					    nvp->v_type == VDIR &&
2132					    nvp->v_mountedhere != NULL) {
2133						new_mp = nvp->v_mountedhere;
2134						r = vfs_busy(new_mp, 0);
2135						vput(nvp);
2136						nvp = NULL;
2137						if (r == 0) {
2138							r = VFS_ROOT(new_mp,
2139							    LK_SHARED, &nvp);
2140							needs_unbusy = 1;
2141							if (r == 0)
2142								at_root = 1;
2143						}
2144					}
2145				}
2146				if (!r) {
2147				    if (refp == NULL &&
2148					((nd->nd_flag & ND_NFSV3) ||
2149					 NFSNONZERO_ATTRBIT(&attrbits))) {
2150					r = nfsvno_getfh(nvp, &nfh, p);
2151					if (!r)
2152					    r = nfsvno_getattr(nvp, nvap,
2153						nd->nd_cred, p, 1);
2154					if (r == 0 && not_zfs == 0 &&
2155					    nfsrv_enable_crossmntpt != 0 &&
2156					    (nd->nd_flag & ND_NFSV4) != 0 &&
2157					    nvp->v_type == VDIR &&
2158					    vp->v_mount != nvp->v_mount) {
2159					    /*
2160					     * For a ZFS snapshot, there is a
2161					     * pseudo mount that does not set
2162					     * v_mountedhere, so it needs to
2163					     * be detected via a different
2164					     * mount structure.
2165					     */
2166					    at_root = 1;
2167					    if (new_mp == mp)
2168						new_mp = nvp->v_mount;
2169					}
2170				    }
2171				} else {
2172				    nvp = NULL;
2173				}
2174				if (r) {
2175					if (!NFSISSET_ATTRBIT(&attrbits,
2176					    NFSATTRBIT_RDATTRERROR)) {
2177						if (nvp != NULL)
2178							vput(nvp);
2179						if (needs_unbusy != 0)
2180							vfs_unbusy(new_mp);
2181						nd->nd_repstat = r;
2182						break;
2183					}
2184				}
2185			}
2186
2187			/*
2188			 * Build the directory record xdr
2189			 */
2190			if (nd->nd_flag & ND_NFSV3) {
2191				NFSM_BUILD(tl, u_int32_t *, 3 * NFSX_UNSIGNED);
2192				*tl++ = newnfs_true;
2193				*tl++ = 0;
2194				*tl = txdr_unsigned(dp->d_fileno);
2195				dirlen += nfsm_strtom(nd, dp->d_name, nlen);
2196				NFSM_BUILD(tl, u_int32_t *, 2 * NFSX_UNSIGNED);
2197				*tl++ = 0;
2198				*tl = txdr_unsigned(*cookiep);
2199				nfsrv_postopattr(nd, 0, nvap);
2200				dirlen += nfsm_fhtom(nd,(u_int8_t *)&nfh,0,1);
2201				dirlen += (5*NFSX_UNSIGNED+NFSX_V3POSTOPATTR);
2202				if (nvp != NULL)
2203					vput(nvp);
2204			} else {
2205				NFSM_BUILD(tl, u_int32_t *, 3 * NFSX_UNSIGNED);
2206				*tl++ = newnfs_true;
2207				*tl++ = 0;
2208				*tl = txdr_unsigned(*cookiep);
2209				dirlen += nfsm_strtom(nd, dp->d_name, nlen);
2210				if (nvp != NULL) {
2211					supports_nfsv4acls =
2212					    nfs_supportsnfsv4acls(nvp);
2213					NFSVOPUNLOCK(nvp, 0);
2214				} else
2215					supports_nfsv4acls = 0;
2216				if (refp != NULL) {
2217					dirlen += nfsrv_putreferralattr(nd,
2218					    &savbits, refp, 0,
2219					    &nd->nd_repstat);
2220					if (nd->nd_repstat) {
2221						if (nvp != NULL)
2222							vrele(nvp);
2223						if (needs_unbusy != 0)
2224							vfs_unbusy(new_mp);
2225						break;
2226					}
2227				} else if (r) {
2228					dirlen += nfsvno_fillattr(nd, new_mp,
2229					    nvp, nvap, &nfh, r, &rderrbits,
2230					    nd->nd_cred, p, isdgram, 0,
2231					    supports_nfsv4acls, at_root,
2232					    mounted_on_fileno);
2233				} else {
2234					dirlen += nfsvno_fillattr(nd, new_mp,
2235					    nvp, nvap, &nfh, r, &attrbits,
2236					    nd->nd_cred, p, isdgram, 0,
2237					    supports_nfsv4acls, at_root,
2238					    mounted_on_fileno);
2239				}
2240				if (nvp != NULL)
2241					vrele(nvp);
2242				dirlen += (3 * NFSX_UNSIGNED);
2243			}
2244			if (needs_unbusy != 0)
2245				vfs_unbusy(new_mp);
2246			if (dirlen <= cnt)
2247				entrycnt++;
2248		}
2249		cpos += dp->d_reclen;
2250		dp = (struct dirent *)cpos;
2251		cookiep++;
2252		ncookies--;
2253	}
2254	vrele(vp);
2255	vfs_unbusy(mp);
2256
2257	/*
2258	 * If dirlen > cnt, we must strip off the last entry. If that
2259	 * results in an empty reply, report NFSERR_TOOSMALL.
2260	 */
2261	if (dirlen > cnt || nd->nd_repstat) {
2262		if (!nd->nd_repstat && entrycnt == 0)
2263			nd->nd_repstat = NFSERR_TOOSMALL;
2264		if (nd->nd_repstat)
2265			newnfs_trimtrailing(nd, mb0, bpos0);
2266		else
2267			newnfs_trimtrailing(nd, mb1, bpos1);
2268		eofflag = 0;
2269	} else if (cpos < cend)
2270		eofflag = 0;
2271	if (!nd->nd_repstat) {
2272		NFSM_BUILD(tl, u_int32_t *, 2 * NFSX_UNSIGNED);
2273		*tl++ = newnfs_false;
2274		if (eofflag)
2275			*tl = newnfs_true;
2276		else
2277			*tl = newnfs_false;
2278	}
2279	FREE((caddr_t)cookies, M_TEMP);
2280	FREE((caddr_t)rbuf, M_TEMP);
2281
2282out:
2283	NFSEXITCODE2(0, nd);
2284	return (0);
2285nfsmout:
2286	vput(vp);
2287	NFSEXITCODE2(error, nd);
2288	return (error);
2289}
2290
2291/*
2292 * Get the settable attributes out of the mbuf list.
2293 * (Return 0 or EBADRPC)
2294 */
2295int
2296nfsrv_sattr(struct nfsrv_descript *nd, struct nfsvattr *nvap,
2297    nfsattrbit_t *attrbitp, NFSACL_T *aclp, struct thread *p)
2298{
2299	u_int32_t *tl;
2300	struct nfsv2_sattr *sp;
2301	int error = 0, toclient = 0;
2302
2303	switch (nd->nd_flag & (ND_NFSV2 | ND_NFSV3 | ND_NFSV4)) {
2304	case ND_NFSV2:
2305		NFSM_DISSECT(sp, struct nfsv2_sattr *, NFSX_V2SATTR);
2306		/*
2307		 * Some old clients didn't fill in the high order 16bits.
2308		 * --> check the low order 2 bytes for 0xffff
2309		 */
2310		if ((fxdr_unsigned(int, sp->sa_mode) & 0xffff) != 0xffff)
2311			nvap->na_mode = nfstov_mode(sp->sa_mode);
2312		if (sp->sa_uid != newnfs_xdrneg1)
2313			nvap->na_uid = fxdr_unsigned(uid_t, sp->sa_uid);
2314		if (sp->sa_gid != newnfs_xdrneg1)
2315			nvap->na_gid = fxdr_unsigned(gid_t, sp->sa_gid);
2316		if (sp->sa_size != newnfs_xdrneg1)
2317			nvap->na_size = fxdr_unsigned(u_quad_t, sp->sa_size);
2318		if (sp->sa_atime.nfsv2_sec != newnfs_xdrneg1) {
2319#ifdef notyet
2320			fxdr_nfsv2time(&sp->sa_atime, &nvap->na_atime);
2321#else
2322			nvap->na_atime.tv_sec =
2323				fxdr_unsigned(u_int32_t,sp->sa_atime.nfsv2_sec);
2324			nvap->na_atime.tv_nsec = 0;
2325#endif
2326		}
2327		if (sp->sa_mtime.nfsv2_sec != newnfs_xdrneg1)
2328			fxdr_nfsv2time(&sp->sa_mtime, &nvap->na_mtime);
2329		break;
2330	case ND_NFSV3:
2331		NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
2332		if (*tl == newnfs_true) {
2333			NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
2334			nvap->na_mode = nfstov_mode(*tl);
2335		}
2336		NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
2337		if (*tl == newnfs_true) {
2338			NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
2339			nvap->na_uid = fxdr_unsigned(uid_t, *tl);
2340		}
2341		NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
2342		if (*tl == newnfs_true) {
2343			NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
2344			nvap->na_gid = fxdr_unsigned(gid_t, *tl);
2345		}
2346		NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
2347		if (*tl == newnfs_true) {
2348			NFSM_DISSECT(tl, u_int32_t *, 2 * NFSX_UNSIGNED);
2349			nvap->na_size = fxdr_hyper(tl);
2350		}
2351		NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
2352		switch (fxdr_unsigned(int, *tl)) {
2353		case NFSV3SATTRTIME_TOCLIENT:
2354			NFSM_DISSECT(tl, u_int32_t *, 2 * NFSX_UNSIGNED);
2355			fxdr_nfsv3time(tl, &nvap->na_atime);
2356			toclient = 1;
2357			break;
2358		case NFSV3SATTRTIME_TOSERVER:
2359			vfs_timestamp(&nvap->na_atime);
2360			nvap->na_vaflags |= VA_UTIMES_NULL;
2361			break;
2362		};
2363		NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
2364		switch (fxdr_unsigned(int, *tl)) {
2365		case NFSV3SATTRTIME_TOCLIENT:
2366			NFSM_DISSECT(tl, u_int32_t *, 2 * NFSX_UNSIGNED);
2367			fxdr_nfsv3time(tl, &nvap->na_mtime);
2368			nvap->na_vaflags &= ~VA_UTIMES_NULL;
2369			break;
2370		case NFSV3SATTRTIME_TOSERVER:
2371			vfs_timestamp(&nvap->na_mtime);
2372			if (!toclient)
2373				nvap->na_vaflags |= VA_UTIMES_NULL;
2374			break;
2375		};
2376		break;
2377	case ND_NFSV4:
2378		error = nfsv4_sattr(nd, nvap, attrbitp, aclp, p);
2379	};
2380nfsmout:
2381	NFSEXITCODE2(error, nd);
2382	return (error);
2383}
2384
2385/*
2386 * Handle the setable attributes for V4.
2387 * Returns NFSERR_BADXDR if it can't be parsed, 0 otherwise.
2388 */
2389int
2390nfsv4_sattr(struct nfsrv_descript *nd, struct nfsvattr *nvap,
2391    nfsattrbit_t *attrbitp, NFSACL_T *aclp, struct thread *p)
2392{
2393	u_int32_t *tl;
2394	int attrsum = 0;
2395	int i, j;
2396	int error, attrsize, bitpos, aclsize, aceerr, retnotsup = 0;
2397	int toclient = 0;
2398	u_char *cp, namestr[NFSV4_SMALLSTR + 1];
2399	uid_t uid;
2400	gid_t gid;
2401
2402	error = nfsrv_getattrbits(nd, attrbitp, NULL, &retnotsup);
2403	if (error)
2404		goto nfsmout;
2405	NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
2406	attrsize = fxdr_unsigned(int, *tl);
2407
2408	/*
2409	 * Loop around getting the setable attributes. If an unsupported
2410	 * one is found, set nd_repstat == NFSERR_ATTRNOTSUPP and return.
2411	 */
2412	if (retnotsup) {
2413		nd->nd_repstat = NFSERR_ATTRNOTSUPP;
2414		bitpos = NFSATTRBIT_MAX;
2415	} else {
2416		bitpos = 0;
2417	}
2418	for (; bitpos < NFSATTRBIT_MAX; bitpos++) {
2419	    if (attrsum > attrsize) {
2420		error = NFSERR_BADXDR;
2421		goto nfsmout;
2422	    }
2423	    if (NFSISSET_ATTRBIT(attrbitp, bitpos))
2424		switch (bitpos) {
2425		case NFSATTRBIT_SIZE:
2426			NFSM_DISSECT(tl, u_int32_t *, NFSX_HYPER);
2427			nvap->na_size = fxdr_hyper(tl);
2428			attrsum += NFSX_HYPER;
2429			break;
2430		case NFSATTRBIT_ACL:
2431			error = nfsrv_dissectacl(nd, aclp, &aceerr, &aclsize,
2432			    p);
2433			if (error)
2434				goto nfsmout;
2435			if (aceerr && !nd->nd_repstat)
2436				nd->nd_repstat = aceerr;
2437			attrsum += aclsize;
2438			break;
2439		case NFSATTRBIT_ARCHIVE:
2440			NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
2441			if (!nd->nd_repstat)
2442				nd->nd_repstat = NFSERR_ATTRNOTSUPP;
2443			attrsum += NFSX_UNSIGNED;
2444			break;
2445		case NFSATTRBIT_HIDDEN:
2446			NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
2447			if (!nd->nd_repstat)
2448				nd->nd_repstat = NFSERR_ATTRNOTSUPP;
2449			attrsum += NFSX_UNSIGNED;
2450			break;
2451		case NFSATTRBIT_MIMETYPE:
2452			NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
2453			i = fxdr_unsigned(int, *tl);
2454			error = nfsm_advance(nd, NFSM_RNDUP(i), -1);
2455			if (error)
2456				goto nfsmout;
2457			if (!nd->nd_repstat)
2458				nd->nd_repstat = NFSERR_ATTRNOTSUPP;
2459			attrsum += (NFSX_UNSIGNED + NFSM_RNDUP(i));
2460			break;
2461		case NFSATTRBIT_MODE:
2462			NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
2463			nvap->na_mode = nfstov_mode(*tl);
2464			attrsum += NFSX_UNSIGNED;
2465			break;
2466		case NFSATTRBIT_OWNER:
2467			NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
2468			j = fxdr_unsigned(int, *tl);
2469			if (j < 0) {
2470				error = NFSERR_BADXDR;
2471				goto nfsmout;
2472			}
2473			if (j > NFSV4_SMALLSTR)
2474				cp = malloc(j + 1, M_NFSSTRING, M_WAITOK);
2475			else
2476				cp = namestr;
2477			error = nfsrv_mtostr(nd, cp, j);
2478			if (error) {
2479				if (j > NFSV4_SMALLSTR)
2480					free(cp, M_NFSSTRING);
2481				goto nfsmout;
2482			}
2483			if (!nd->nd_repstat) {
2484				nd->nd_repstat = nfsv4_strtouid(nd, cp, j, &uid,
2485				    p);
2486				if (!nd->nd_repstat)
2487					nvap->na_uid = uid;
2488			}
2489			if (j > NFSV4_SMALLSTR)
2490				free(cp, M_NFSSTRING);
2491			attrsum += (NFSX_UNSIGNED + NFSM_RNDUP(j));
2492			break;
2493		case NFSATTRBIT_OWNERGROUP:
2494			NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
2495			j = fxdr_unsigned(int, *tl);
2496			if (j < 0) {
2497				error = NFSERR_BADXDR;
2498				goto nfsmout;
2499			}
2500			if (j > NFSV4_SMALLSTR)
2501				cp = malloc(j + 1, M_NFSSTRING, M_WAITOK);
2502			else
2503				cp = namestr;
2504			error = nfsrv_mtostr(nd, cp, j);
2505			if (error) {
2506				if (j > NFSV4_SMALLSTR)
2507					free(cp, M_NFSSTRING);
2508				goto nfsmout;
2509			}
2510			if (!nd->nd_repstat) {
2511				nd->nd_repstat = nfsv4_strtogid(nd, cp, j, &gid,
2512				    p);
2513				if (!nd->nd_repstat)
2514					nvap->na_gid = gid;
2515			}
2516			if (j > NFSV4_SMALLSTR)
2517				free(cp, M_NFSSTRING);
2518			attrsum += (NFSX_UNSIGNED + NFSM_RNDUP(j));
2519			break;
2520		case NFSATTRBIT_SYSTEM:
2521			NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
2522			if (!nd->nd_repstat)
2523				nd->nd_repstat = NFSERR_ATTRNOTSUPP;
2524			attrsum += NFSX_UNSIGNED;
2525			break;
2526		case NFSATTRBIT_TIMEACCESSSET:
2527			NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
2528			attrsum += NFSX_UNSIGNED;
2529			if (fxdr_unsigned(int, *tl)==NFSV4SATTRTIME_TOCLIENT) {
2530			    NFSM_DISSECT(tl, u_int32_t *, NFSX_V4TIME);
2531			    fxdr_nfsv4time(tl, &nvap->na_atime);
2532			    toclient = 1;
2533			    attrsum += NFSX_V4TIME;
2534			} else {
2535			    vfs_timestamp(&nvap->na_atime);
2536			    nvap->na_vaflags |= VA_UTIMES_NULL;
2537			}
2538			break;
2539		case NFSATTRBIT_TIMEBACKUP:
2540			NFSM_DISSECT(tl, u_int32_t *, NFSX_V4TIME);
2541			if (!nd->nd_repstat)
2542				nd->nd_repstat = NFSERR_ATTRNOTSUPP;
2543			attrsum += NFSX_V4TIME;
2544			break;
2545		case NFSATTRBIT_TIMECREATE:
2546			NFSM_DISSECT(tl, u_int32_t *, NFSX_V4TIME);
2547			if (!nd->nd_repstat)
2548				nd->nd_repstat = NFSERR_ATTRNOTSUPP;
2549			attrsum += NFSX_V4TIME;
2550			break;
2551		case NFSATTRBIT_TIMEMODIFYSET:
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_mtime);
2557			    nvap->na_vaflags &= ~VA_UTIMES_NULL;
2558			    attrsum += NFSX_V4TIME;
2559			} else {
2560			    vfs_timestamp(&nvap->na_mtime);
2561			    if (!toclient)
2562				nvap->na_vaflags |= VA_UTIMES_NULL;
2563			}
2564			break;
2565		default:
2566			nd->nd_repstat = NFSERR_ATTRNOTSUPP;
2567			/*
2568			 * set bitpos so we drop out of the loop.
2569			 */
2570			bitpos = NFSATTRBIT_MAX;
2571			break;
2572		};
2573	}
2574
2575	/*
2576	 * some clients pad the attrlist, so we need to skip over the
2577	 * padding.
2578	 */
2579	if (attrsum > attrsize) {
2580		error = NFSERR_BADXDR;
2581	} else {
2582		attrsize = NFSM_RNDUP(attrsize);
2583		if (attrsum < attrsize)
2584			error = nfsm_advance(nd, attrsize - attrsum, -1);
2585	}
2586nfsmout:
2587	NFSEXITCODE2(error, nd);
2588	return (error);
2589}
2590
2591/*
2592 * Check/setup export credentials.
2593 */
2594int
2595nfsd_excred(struct nfsrv_descript *nd, struct nfsexstuff *exp,
2596    struct ucred *credanon)
2597{
2598	int error = 0;
2599
2600	/*
2601	 * Check/setup credentials.
2602	 */
2603	if (nd->nd_flag & ND_GSS)
2604		exp->nes_exflag &= ~MNT_EXPORTANON;
2605
2606	/*
2607	 * Check to see if the operation is allowed for this security flavor.
2608	 * RFC2623 suggests that the NFSv3 Fsinfo RPC be allowed to
2609	 * AUTH_NONE or AUTH_SYS for file systems requiring RPCSEC_GSS.
2610	 * Also, allow Secinfo, so that it can acquire the correct flavor(s).
2611	 */
2612	if (nfsvno_testexp(nd, exp) &&
2613	    nd->nd_procnum != NFSV4OP_SECINFO &&
2614	    nd->nd_procnum != NFSPROC_FSINFO) {
2615		if (nd->nd_flag & ND_NFSV4)
2616			error = NFSERR_WRONGSEC;
2617		else
2618			error = (NFSERR_AUTHERR | AUTH_TOOWEAK);
2619		goto out;
2620	}
2621
2622	/*
2623	 * Check to see if the file system is exported V4 only.
2624	 */
2625	if (NFSVNO_EXV4ONLY(exp) && !(nd->nd_flag & ND_NFSV4)) {
2626		error = NFSERR_PROGNOTV4;
2627		goto out;
2628	}
2629
2630	/*
2631	 * Now, map the user credentials.
2632	 * (Note that ND_AUTHNONE will only be set for an NFSv3
2633	 *  Fsinfo RPC. If set for anything else, this code might need
2634	 *  to change.)
2635	 */
2636	if (NFSVNO_EXPORTED(exp) &&
2637	    ((!(nd->nd_flag & ND_GSS) && nd->nd_cred->cr_uid == 0) ||
2638	     NFSVNO_EXPORTANON(exp) ||
2639	     (nd->nd_flag & ND_AUTHNONE))) {
2640		nd->nd_cred->cr_uid = credanon->cr_uid;
2641		nd->nd_cred->cr_gid = credanon->cr_gid;
2642		crsetgroups(nd->nd_cred, credanon->cr_ngroups,
2643		    credanon->cr_groups);
2644	}
2645
2646out:
2647	NFSEXITCODE2(error, nd);
2648	return (error);
2649}
2650
2651/*
2652 * Check exports.
2653 */
2654int
2655nfsvno_checkexp(struct mount *mp, struct sockaddr *nam, struct nfsexstuff *exp,
2656    struct ucred **credp)
2657{
2658	int i, error, *secflavors;
2659
2660	error = VFS_CHECKEXP(mp, nam, &exp->nes_exflag, credp,
2661	    &exp->nes_numsecflavor, &secflavors);
2662	if (error) {
2663		if (nfs_rootfhset) {
2664			exp->nes_exflag = 0;
2665			exp->nes_numsecflavor = 0;
2666			error = 0;
2667		}
2668	} else {
2669		/* Copy the security flavors. */
2670		for (i = 0; i < exp->nes_numsecflavor; i++)
2671			exp->nes_secflavors[i] = secflavors[i];
2672	}
2673	NFSEXITCODE(error);
2674	return (error);
2675}
2676
2677/*
2678 * Get a vnode for a file handle and export stuff.
2679 */
2680int
2681nfsvno_fhtovp(struct mount *mp, fhandle_t *fhp, struct sockaddr *nam,
2682    int lktype, struct vnode **vpp, struct nfsexstuff *exp,
2683    struct ucred **credp)
2684{
2685	int i, error, *secflavors;
2686
2687	*credp = NULL;
2688	exp->nes_numsecflavor = 0;
2689	if (VFS_NEEDSGIANT(mp))
2690		error = ESTALE;
2691	else
2692		error = VFS_FHTOVP(mp, &fhp->fh_fid, LK_EXCLUSIVE, vpp);
2693	if (error != 0)
2694		/* Make sure the server replies ESTALE to the client. */
2695		error = ESTALE;
2696	if (nam && !error) {
2697		error = VFS_CHECKEXP(mp, nam, &exp->nes_exflag, credp,
2698		    &exp->nes_numsecflavor, &secflavors);
2699		if (error) {
2700			if (nfs_rootfhset) {
2701				exp->nes_exflag = 0;
2702				exp->nes_numsecflavor = 0;
2703				error = 0;
2704			} else {
2705				vput(*vpp);
2706			}
2707		} else {
2708			/* Copy the security flavors. */
2709			for (i = 0; i < exp->nes_numsecflavor; i++)
2710				exp->nes_secflavors[i] = secflavors[i];
2711		}
2712	}
2713	if (error == 0 && lktype == LK_SHARED)
2714		/*
2715		 * It would be much better to pass lktype to VFS_FHTOVP(),
2716		 * but this will have to do until VFS_FHTOVP() has a lock
2717		 * type argument like VFS_VGET().
2718		 */
2719		NFSVOPLOCK(*vpp, LK_DOWNGRADE | LK_RETRY);
2720
2721	NFSEXITCODE(error);
2722	return (error);
2723}
2724
2725/*
2726 * nfsd_fhtovp() - convert a fh to a vnode ptr
2727 * 	- look up fsid in mount list (if not found ret error)
2728 *	- get vp and export rights by calling nfsvno_fhtovp()
2729 *	- if cred->cr_uid == 0 or MNT_EXPORTANON set it to credanon
2730 *	  for AUTH_SYS
2731 *	- if mpp != NULL, return the mount point so that it can
2732 *	  be used for vn_finished_write() by the caller
2733 */
2734void
2735nfsd_fhtovp(struct nfsrv_descript *nd, struct nfsrvfh *nfp, int lktype,
2736    struct vnode **vpp, struct nfsexstuff *exp,
2737    struct mount **mpp, int startwrite, struct thread *p)
2738{
2739	struct mount *mp;
2740	struct ucred *credanon;
2741	fhandle_t *fhp;
2742
2743	fhp = (fhandle_t *)nfp->nfsrvfh_data;
2744	/*
2745	 * Check for the special case of the nfsv4root_fh.
2746	 */
2747	mp = vfs_busyfs(&fhp->fh_fsid);
2748	if (mpp != NULL)
2749		*mpp = mp;
2750	if (mp == NULL) {
2751		*vpp = NULL;
2752		nd->nd_repstat = ESTALE;
2753		goto out;
2754	}
2755
2756	if (startwrite) {
2757		vn_start_write(NULL, mpp, V_WAIT);
2758		if (lktype == LK_SHARED && !(MNT_SHARED_WRITES(mp)))
2759			lktype = LK_EXCLUSIVE;
2760	}
2761	nd->nd_repstat = nfsvno_fhtovp(mp, fhp, nd->nd_nam, lktype, vpp, exp,
2762	    &credanon);
2763	vfs_unbusy(mp);
2764
2765	/*
2766	 * For NFSv4 without a pseudo root fs, unexported file handles
2767	 * can be returned, so that Lookup works everywhere.
2768	 */
2769	if (!nd->nd_repstat && exp->nes_exflag == 0 &&
2770	    !(nd->nd_flag & ND_NFSV4)) {
2771		vput(*vpp);
2772		nd->nd_repstat = EACCES;
2773	}
2774
2775	/*
2776	 * Personally, I've never seen any point in requiring a
2777	 * reserved port#, since only in the rare case where the
2778	 * clients are all boxes with secure system priviledges,
2779	 * does it provide any enhanced security, but... some people
2780	 * believe it to be useful and keep putting this code back in.
2781	 * (There is also some "security checker" out there that
2782	 *  complains if the nfs server doesn't enforce this.)
2783	 * However, note the following:
2784	 * RFC3530 (NFSv4) specifies that a reserved port# not be
2785	 *	required.
2786	 * RFC2623 recommends that, if a reserved port# is checked for,
2787	 *	that there be a way to turn that off--> ifdef'd.
2788	 */
2789#ifdef NFS_REQRSVPORT
2790	if (!nd->nd_repstat) {
2791		struct sockaddr_in *saddr;
2792		struct sockaddr_in6 *saddr6;
2793
2794		saddr = NFSSOCKADDR(nd->nd_nam, struct sockaddr_in *);
2795		saddr6 = NFSSOCKADDR(nd->nd_nam, struct sockaddr_in6 *);
2796		if (!(nd->nd_flag & ND_NFSV4) &&
2797		    ((saddr->sin_family == AF_INET &&
2798		      ntohs(saddr->sin_port) >= IPPORT_RESERVED) ||
2799		     (saddr6->sin6_family == AF_INET6 &&
2800		      ntohs(saddr6->sin6_port) >= IPPORT_RESERVED))) {
2801			vput(*vpp);
2802			nd->nd_repstat = (NFSERR_AUTHERR | AUTH_TOOWEAK);
2803		}
2804	}
2805#endif	/* NFS_REQRSVPORT */
2806
2807	/*
2808	 * Check/setup credentials.
2809	 */
2810	if (!nd->nd_repstat) {
2811		nd->nd_saveduid = nd->nd_cred->cr_uid;
2812		nd->nd_repstat = nfsd_excred(nd, exp, credanon);
2813		if (nd->nd_repstat)
2814			vput(*vpp);
2815	}
2816	if (credanon != NULL)
2817		crfree(credanon);
2818	if (nd->nd_repstat) {
2819		if (startwrite)
2820			vn_finished_write(mp);
2821		*vpp = NULL;
2822		if (mpp != NULL)
2823			*mpp = NULL;
2824	}
2825
2826out:
2827	NFSEXITCODE2(0, nd);
2828}
2829
2830/*
2831 * glue for fp.
2832 */
2833int
2834fp_getfvp(struct thread *p, int fd, struct file **fpp, struct vnode **vpp)
2835{
2836	struct filedesc *fdp;
2837	struct file *fp;
2838	int error = 0;
2839
2840	fdp = p->td_proc->p_fd;
2841	if (fd >= fdp->fd_nfiles ||
2842	    (fp = fdp->fd_ofiles[fd]) == NULL) {
2843		error = EBADF;
2844		goto out;
2845	}
2846	*fpp = fp;
2847
2848out:
2849	NFSEXITCODE(error);
2850	return (error);
2851}
2852
2853/*
2854 * Called from nfssvc() to update the exports list. Just call
2855 * vfs_export(). This has to be done, since the v4 root fake fs isn't
2856 * in the mount list.
2857 */
2858int
2859nfsrv_v4rootexport(void *argp, struct ucred *cred, struct thread *p)
2860{
2861	struct nfsex_args *nfsexargp = (struct nfsex_args *)argp;
2862	int error = 0;
2863	struct nameidata nd;
2864	fhandle_t fh;
2865
2866	error = vfs_export(&nfsv4root_mnt, &nfsexargp->export);
2867	if ((nfsexargp->export.ex_flags & MNT_DELEXPORT) != 0)
2868		nfs_rootfhset = 0;
2869	else if (error == 0) {
2870		if (nfsexargp->fspec == NULL) {
2871			error = EPERM;
2872			goto out;
2873		}
2874		/*
2875		 * If fspec != NULL, this is the v4root path.
2876		 */
2877		NDINIT(&nd, LOOKUP, FOLLOW | MPSAFE, UIO_USERSPACE,
2878		    nfsexargp->fspec, p);
2879		if ((error = namei(&nd)) != 0)
2880			goto out;
2881		error = nfsvno_getfh(nd.ni_vp, &fh, p);
2882		vrele(nd.ni_vp);
2883		if (!error) {
2884			nfs_rootfh.nfsrvfh_len = NFSX_MYFH;
2885			NFSBCOPY((caddr_t)&fh,
2886			    nfs_rootfh.nfsrvfh_data,
2887			    sizeof (fhandle_t));
2888			nfs_rootfhset = 1;
2889		}
2890	}
2891
2892out:
2893	NFSEXITCODE(error);
2894	return (error);
2895}
2896
2897/*
2898 * This function needs to test to see if the system is near its limit
2899 * for memory allocation via malloc() or mget() and return True iff
2900 * either of these resources are near their limit.
2901 * XXX (For now, this is just a stub.)
2902 */
2903int nfsrv_testmalloclimit = 0;
2904int
2905nfsrv_mallocmget_limit(void)
2906{
2907	static int printmesg = 0;
2908	static int testval = 1;
2909
2910	if (nfsrv_testmalloclimit && (testval++ % 1000) == 0) {
2911		if ((printmesg++ % 100) == 0)
2912			printf("nfsd: malloc/mget near limit\n");
2913		return (1);
2914	}
2915	return (0);
2916}
2917
2918/*
2919 * BSD specific initialization of a mount point.
2920 */
2921void
2922nfsd_mntinit(void)
2923{
2924	static int inited = 0;
2925
2926	if (inited)
2927		return;
2928	inited = 1;
2929	nfsv4root_mnt.mnt_flag = (MNT_RDONLY | MNT_EXPORTED);
2930	TAILQ_INIT(&nfsv4root_mnt.mnt_nvnodelist);
2931	TAILQ_INIT(&nfsv4root_mnt.mnt_activevnodelist);
2932	nfsv4root_mnt.mnt_export = NULL;
2933	TAILQ_INIT(&nfsv4root_opt);
2934	TAILQ_INIT(&nfsv4root_newopt);
2935	nfsv4root_mnt.mnt_opt = &nfsv4root_opt;
2936	nfsv4root_mnt.mnt_optnew = &nfsv4root_newopt;
2937	nfsv4root_mnt.mnt_nvnodelistsize = 0;
2938	nfsv4root_mnt.mnt_activevnodelistsize = 0;
2939}
2940
2941/*
2942 * Get a vnode for a file handle, without checking exports, etc.
2943 */
2944struct vnode *
2945nfsvno_getvp(fhandle_t *fhp)
2946{
2947	struct mount *mp;
2948	struct vnode *vp;
2949	int error;
2950
2951	mp = vfs_busyfs(&fhp->fh_fsid);
2952	if (mp == NULL)
2953		return (NULL);
2954	error = VFS_FHTOVP(mp, &fhp->fh_fid, LK_EXCLUSIVE, &vp);
2955	vfs_unbusy(mp);
2956	if (error)
2957		return (NULL);
2958	return (vp);
2959}
2960
2961/*
2962 * Do a local VOP_ADVLOCK().
2963 */
2964int
2965nfsvno_advlock(struct vnode *vp, int ftype, u_int64_t first,
2966    u_int64_t end, struct thread *td)
2967{
2968	int error = 0;
2969	struct flock fl;
2970	u_int64_t tlen;
2971
2972	if (nfsrv_dolocallocks == 0)
2973		goto out;
2974
2975	/* Check for VI_DOOMED here, so that VOP_ADVLOCK() isn't performed. */
2976	if ((vp->v_iflag & VI_DOOMED) != 0) {
2977		error = EPERM;
2978		goto out;
2979	}
2980
2981	fl.l_whence = SEEK_SET;
2982	fl.l_type = ftype;
2983	fl.l_start = (off_t)first;
2984	if (end == NFS64BITSSET) {
2985		fl.l_len = 0;
2986	} else {
2987		tlen = end - first;
2988		fl.l_len = (off_t)tlen;
2989	}
2990	/*
2991	 * For FreeBSD8, the l_pid and l_sysid must be set to the same
2992	 * values for all calls, so that all locks will be held by the
2993	 * nfsd server. (The nfsd server handles conflicts between the
2994	 * various clients.)
2995	 * Since an NFSv4 lockowner is a ClientID plus an array of up to 1024
2996	 * bytes, so it can't be put in l_sysid.
2997	 */
2998	if (nfsv4_sysid == 0)
2999		nfsv4_sysid = nlm_acquire_next_sysid();
3000	fl.l_pid = (pid_t)0;
3001	fl.l_sysid = (int)nfsv4_sysid;
3002
3003	NFSVOPUNLOCK(vp, 0);
3004	if (ftype == F_UNLCK)
3005		error = VOP_ADVLOCK(vp, (caddr_t)td->td_proc, F_UNLCK, &fl,
3006		    (F_POSIX | F_REMOTE));
3007	else
3008		error = VOP_ADVLOCK(vp, (caddr_t)td->td_proc, F_SETLK, &fl,
3009		    (F_POSIX | F_REMOTE));
3010	NFSVOPLOCK(vp, LK_EXCLUSIVE | LK_RETRY);
3011
3012out:
3013	NFSEXITCODE(error);
3014	return (error);
3015}
3016
3017/*
3018 * Check the nfsv4 root exports.
3019 */
3020int
3021nfsvno_v4rootexport(struct nfsrv_descript *nd)
3022{
3023	struct ucred *credanon;
3024	int exflags, error = 0, numsecflavor, *secflavors, i;
3025
3026	error = vfs_stdcheckexp(&nfsv4root_mnt, nd->nd_nam, &exflags,
3027	    &credanon, &numsecflavor, &secflavors);
3028	if (error) {
3029		error = NFSERR_PROGUNAVAIL;
3030		goto out;
3031	}
3032	if (credanon != NULL)
3033		crfree(credanon);
3034	for (i = 0; i < numsecflavor; i++) {
3035		if (secflavors[i] == AUTH_SYS)
3036			nd->nd_flag |= ND_EXAUTHSYS;
3037		else if (secflavors[i] == RPCSEC_GSS_KRB5)
3038			nd->nd_flag |= ND_EXGSS;
3039		else if (secflavors[i] == RPCSEC_GSS_KRB5I)
3040			nd->nd_flag |= ND_EXGSSINTEGRITY;
3041		else if (secflavors[i] == RPCSEC_GSS_KRB5P)
3042			nd->nd_flag |= ND_EXGSSPRIVACY;
3043	}
3044
3045out:
3046	NFSEXITCODE(error);
3047	return (error);
3048}
3049
3050/*
3051 * Nfs server psuedo system call for the nfsd's
3052 */
3053/*
3054 * MPSAFE
3055 */
3056static int
3057nfssvc_nfsd(struct thread *td, struct nfssvc_args *uap)
3058{
3059	struct file *fp;
3060	struct nfsd_addsock_args sockarg;
3061	struct nfsd_nfsd_args nfsdarg;
3062	int error;
3063
3064	if (uap->flag & NFSSVC_NFSDADDSOCK) {
3065		error = copyin(uap->argp, (caddr_t)&sockarg, sizeof (sockarg));
3066		if (error)
3067			goto out;
3068		/*
3069		 * Since we don't know what rights might be required,
3070		 * pretend that we need them all. It is better to be too
3071		 * careful than too reckless.
3072		 */
3073		if ((error = fget(td, sockarg.sock, CAP_SOCK_ALL, &fp)) != 0)
3074			goto out;
3075		if (fp->f_type != DTYPE_SOCKET) {
3076			fdrop(fp, td);
3077			error = EPERM;
3078			goto out;
3079		}
3080		error = nfsrvd_addsock(fp);
3081		fdrop(fp, td);
3082	} else if (uap->flag & NFSSVC_NFSDNFSD) {
3083		if (uap->argp == NULL) {
3084			error = EINVAL;
3085			goto out;
3086		}
3087		error = copyin(uap->argp, (caddr_t)&nfsdarg,
3088		    sizeof (nfsdarg));
3089		if (error)
3090			goto out;
3091		error = nfsrvd_nfsd(td, &nfsdarg);
3092	} else {
3093		error = nfssvc_srvcall(td, uap, td->td_ucred);
3094	}
3095
3096out:
3097	NFSEXITCODE(error);
3098	return (error);
3099}
3100
3101static int
3102nfssvc_srvcall(struct thread *p, struct nfssvc_args *uap, struct ucred *cred)
3103{
3104	struct nfsex_args export;
3105	struct file *fp = NULL;
3106	int stablefd, len;
3107	struct nfsd_clid adminrevoke;
3108	struct nfsd_dumplist dumplist;
3109	struct nfsd_dumpclients *dumpclients;
3110	struct nfsd_dumplocklist dumplocklist;
3111	struct nfsd_dumplocks *dumplocks;
3112	struct nameidata nd;
3113	vnode_t vp;
3114	int error = EINVAL, igotlock;
3115	struct proc *procp;
3116	static int suspend_nfsd = 0;
3117
3118	if (uap->flag & NFSSVC_PUBLICFH) {
3119		NFSBZERO((caddr_t)&nfs_pubfh.nfsrvfh_data,
3120		    sizeof (fhandle_t));
3121		error = copyin(uap->argp,
3122		    &nfs_pubfh.nfsrvfh_data, sizeof (fhandle_t));
3123		if (!error)
3124			nfs_pubfhset = 1;
3125	} else if (uap->flag & NFSSVC_V4ROOTEXPORT) {
3126		error = copyin(uap->argp,(caddr_t)&export,
3127		    sizeof (struct nfsex_args));
3128		if (!error)
3129			error = nfsrv_v4rootexport(&export, cred, p);
3130	} else if (uap->flag & NFSSVC_NOPUBLICFH) {
3131		nfs_pubfhset = 0;
3132		error = 0;
3133	} else if (uap->flag & NFSSVC_STABLERESTART) {
3134		error = copyin(uap->argp, (caddr_t)&stablefd,
3135		    sizeof (int));
3136		if (!error)
3137			error = fp_getfvp(p, stablefd, &fp, &vp);
3138		if (!error && (NFSFPFLAG(fp) & (FREAD | FWRITE)) != (FREAD | FWRITE))
3139			error = EBADF;
3140		if (!error && newnfs_numnfsd != 0)
3141			error = EPERM;
3142		if (!error) {
3143			nfsrv_stablefirst.nsf_fp = fp;
3144			nfsrv_setupstable(p);
3145		}
3146	} else if (uap->flag & NFSSVC_ADMINREVOKE) {
3147		error = copyin(uap->argp, (caddr_t)&adminrevoke,
3148		    sizeof (struct nfsd_clid));
3149		if (!error)
3150			error = nfsrv_adminrevoke(&adminrevoke, p);
3151	} else if (uap->flag & NFSSVC_DUMPCLIENTS) {
3152		error = copyin(uap->argp, (caddr_t)&dumplist,
3153		    sizeof (struct nfsd_dumplist));
3154		if (!error && (dumplist.ndl_size < 1 ||
3155			dumplist.ndl_size > NFSRV_MAXDUMPLIST))
3156			error = EPERM;
3157		if (!error) {
3158		    len = sizeof (struct nfsd_dumpclients) * dumplist.ndl_size;
3159		    dumpclients = (struct nfsd_dumpclients *)malloc(len,
3160			M_TEMP, M_WAITOK);
3161		    nfsrv_dumpclients(dumpclients, dumplist.ndl_size);
3162		    error = copyout(dumpclients,
3163			CAST_USER_ADDR_T(dumplist.ndl_list), len);
3164		    free((caddr_t)dumpclients, M_TEMP);
3165		}
3166	} else if (uap->flag & NFSSVC_DUMPLOCKS) {
3167		error = copyin(uap->argp, (caddr_t)&dumplocklist,
3168		    sizeof (struct nfsd_dumplocklist));
3169		if (!error && (dumplocklist.ndllck_size < 1 ||
3170			dumplocklist.ndllck_size > NFSRV_MAXDUMPLIST))
3171			error = EPERM;
3172		if (!error)
3173			error = nfsrv_lookupfilename(&nd,
3174				dumplocklist.ndllck_fname, p);
3175		if (!error) {
3176			len = sizeof (struct nfsd_dumplocks) *
3177				dumplocklist.ndllck_size;
3178			dumplocks = (struct nfsd_dumplocks *)malloc(len,
3179				M_TEMP, M_WAITOK);
3180			nfsrv_dumplocks(nd.ni_vp, dumplocks,
3181			    dumplocklist.ndllck_size, p);
3182			vput(nd.ni_vp);
3183			error = copyout(dumplocks,
3184			    CAST_USER_ADDR_T(dumplocklist.ndllck_list), len);
3185			free((caddr_t)dumplocks, M_TEMP);
3186		}
3187	} else if (uap->flag & NFSSVC_BACKUPSTABLE) {
3188		procp = p->td_proc;
3189		PROC_LOCK(procp);
3190		nfsd_master_pid = procp->p_pid;
3191		bcopy(procp->p_comm, nfsd_master_comm, MAXCOMLEN + 1);
3192		nfsd_master_start = procp->p_stats->p_start;
3193		nfsd_master_proc = procp;
3194		PROC_UNLOCK(procp);
3195	} else if ((uap->flag & NFSSVC_SUSPENDNFSD) != 0) {
3196		NFSLOCKV4ROOTMUTEX();
3197		if (suspend_nfsd == 0) {
3198			/* Lock out all nfsd threads */
3199			do {
3200				igotlock = nfsv4_lock(&nfsd_suspend_lock, 1,
3201				    NULL, NFSV4ROOTLOCKMUTEXPTR, NULL);
3202			} while (igotlock == 0 && suspend_nfsd == 0);
3203			suspend_nfsd = 1;
3204		}
3205		NFSUNLOCKV4ROOTMUTEX();
3206		error = 0;
3207	} else if ((uap->flag & NFSSVC_RESUMENFSD) != 0) {
3208		NFSLOCKV4ROOTMUTEX();
3209		if (suspend_nfsd != 0) {
3210			nfsv4_unlock(&nfsd_suspend_lock, 0);
3211			suspend_nfsd = 0;
3212		}
3213		NFSUNLOCKV4ROOTMUTEX();
3214		error = 0;
3215	}
3216
3217	NFSEXITCODE(error);
3218	return (error);
3219}
3220
3221/*
3222 * Check exports.
3223 * Returns 0 if ok, 1 otherwise.
3224 */
3225int
3226nfsvno_testexp(struct nfsrv_descript *nd, struct nfsexstuff *exp)
3227{
3228	int i;
3229
3230	/*
3231	 * This seems odd, but allow the case where the security flavor
3232	 * list is empty. This happens when NFSv4 is traversing non-exported
3233	 * file systems. Exported file systems should always have a non-empty
3234	 * security flavor list.
3235	 */
3236	if (exp->nes_numsecflavor == 0)
3237		return (0);
3238
3239	for (i = 0; i < exp->nes_numsecflavor; i++) {
3240		/*
3241		 * The tests for privacy and integrity must be first,
3242		 * since ND_GSS is set for everything but AUTH_SYS.
3243		 */
3244		if (exp->nes_secflavors[i] == RPCSEC_GSS_KRB5P &&
3245		    (nd->nd_flag & ND_GSSPRIVACY))
3246			return (0);
3247		if (exp->nes_secflavors[i] == RPCSEC_GSS_KRB5I &&
3248		    (nd->nd_flag & ND_GSSINTEGRITY))
3249			return (0);
3250		if (exp->nes_secflavors[i] == RPCSEC_GSS_KRB5 &&
3251		    (nd->nd_flag & ND_GSS))
3252			return (0);
3253		if (exp->nes_secflavors[i] == AUTH_SYS &&
3254		    (nd->nd_flag & ND_GSS) == 0)
3255			return (0);
3256	}
3257	return (1);
3258}
3259
3260/*
3261 * Calculate a hash value for the fid in a file handle.
3262 */
3263uint32_t
3264nfsrv_hashfh(fhandle_t *fhp)
3265{
3266	uint32_t hashval;
3267
3268	hashval = hash32_buf(&fhp->fh_fid, sizeof(struct fid), 0);
3269	return (hashval);
3270}
3271
3272/*
3273 * Signal the userland master nfsd to backup the stable restart file.
3274 */
3275void
3276nfsrv_backupstable(void)
3277{
3278	struct proc *procp;
3279
3280	if (nfsd_master_proc != NULL) {
3281		procp = pfind(nfsd_master_pid);
3282		/* Try to make sure it is the correct process. */
3283		if (procp == nfsd_master_proc &&
3284		    procp->p_stats->p_start.tv_sec ==
3285		    nfsd_master_start.tv_sec &&
3286		    procp->p_stats->p_start.tv_usec ==
3287		    nfsd_master_start.tv_usec &&
3288		    strcmp(procp->p_comm, nfsd_master_comm) == 0)
3289			kern_psignal(procp, SIGUSR2);
3290		else
3291			nfsd_master_proc = NULL;
3292
3293		if (procp != NULL)
3294			PROC_UNLOCK(procp);
3295	}
3296}
3297
3298extern int (*nfsd_call_nfsd)(struct thread *, struct nfssvc_args *);
3299
3300/*
3301 * Called once to initialize data structures...
3302 */
3303static int
3304nfsd_modevent(module_t mod, int type, void *data)
3305{
3306	int error = 0, i;
3307	static int loaded = 0;
3308
3309	switch (type) {
3310	case MOD_LOAD:
3311		if (loaded)
3312			goto out;
3313		newnfs_portinit();
3314		for (i = 0; i < NFSRVCACHE_HASHSIZE; i++) {
3315			snprintf(nfsrchash_table[i].lock_name,
3316			    sizeof(nfsrchash_table[i].lock_name), "nfsrc_tcp%d",
3317			    i);
3318			mtx_init(&nfsrchash_table[i].mtx,
3319			    nfsrchash_table[i].lock_name, NULL, MTX_DEF);
3320			snprintf(nfsrcahash_table[i].lock_name,
3321			    sizeof(nfsrcahash_table[i].lock_name), "nfsrc_tcpa%d",
3322			    i);
3323			mtx_init(&nfsrcahash_table[i].mtx,
3324			    nfsrcahash_table[i].lock_name, NULL, MTX_DEF);
3325		}
3326		mtx_init(&nfsrc_udpmtx, "nfs_udpcache_mutex", NULL, MTX_DEF);
3327		mtx_init(&nfs_v4root_mutex, "nfs_v4root_mutex", NULL, MTX_DEF);
3328		mtx_init(&nfsv4root_mnt.mnt_mtx, "struct mount mtx", NULL,
3329		    MTX_DEF);
3330		lockinit(&nfsv4root_mnt.mnt_explock, PVFS, "explock", 0, 0);
3331		nfsrvd_initcache();
3332		nfsd_init();
3333		NFSD_LOCK();
3334		nfsrvd_init(0);
3335		NFSD_UNLOCK();
3336		nfsd_mntinit();
3337#ifdef VV_DISABLEDELEG
3338		vn_deleg_ops.vndeleg_recall = nfsd_recalldelegation;
3339		vn_deleg_ops.vndeleg_disable = nfsd_disabledelegation;
3340#endif
3341		nfsd_call_servertimer = nfsrv_servertimer;
3342		nfsd_call_nfsd = nfssvc_nfsd;
3343		loaded = 1;
3344		break;
3345
3346	case MOD_UNLOAD:
3347		if (newnfs_numnfsd != 0) {
3348			error = EBUSY;
3349			break;
3350		}
3351
3352#ifdef VV_DISABLEDELEG
3353		vn_deleg_ops.vndeleg_recall = NULL;
3354		vn_deleg_ops.vndeleg_disable = NULL;
3355#endif
3356		nfsd_call_servertimer = NULL;
3357		nfsd_call_nfsd = NULL;
3358
3359		/* Clean out all NFSv4 state. */
3360		nfsrv_throwawayallstate(curthread);
3361
3362		/* Clean the NFS server reply cache */
3363		nfsrvd_cleancache();
3364
3365		/* Free up the krpc server pool. */
3366		if (nfsrvd_pool != NULL)
3367			svcpool_destroy(nfsrvd_pool);
3368
3369		/* and get rid of the locks */
3370		for (i = 0; i < NFSRVCACHE_HASHSIZE; i++) {
3371			mtx_destroy(&nfsrchash_table[i].mtx);
3372			mtx_destroy(&nfsrcahash_table[i].mtx);
3373		}
3374		mtx_destroy(&nfsrc_udpmtx);
3375		mtx_destroy(&nfs_v4root_mutex);
3376		mtx_destroy(&nfsv4root_mnt.mnt_mtx);
3377		lockdestroy(&nfsv4root_mnt.mnt_explock);
3378		loaded = 0;
3379		break;
3380	default:
3381		error = EOPNOTSUPP;
3382		break;
3383	}
3384
3385out:
3386	NFSEXITCODE(error);
3387	return (error);
3388}
3389static moduledata_t nfsd_mod = {
3390	"nfsd",
3391	nfsd_modevent,
3392	NULL,
3393};
3394DECLARE_MODULE(nfsd, nfsd_mod, SI_SUB_VFS, SI_ORDER_ANY);
3395
3396/* So that loader and kldload(2) can find us, wherever we are.. */
3397MODULE_VERSION(nfsd, 1);
3398MODULE_DEPEND(nfsd, nfscommon, 1, 1, 1);
3399MODULE_DEPEND(nfsd, nfslock, 1, 1, 1);
3400MODULE_DEPEND(nfsd, nfslockd, 1, 1, 1);
3401MODULE_DEPEND(nfsd, krpc, 1, 1, 1);
3402MODULE_DEPEND(nfsd, nfssvc, 1, 1, 1);
3403
3404