xref: /freebsd/sys/fs/nfsserver/nfs_nfsdport.c (revision d3d381b2b194b4d24853e92eecef55f262688d1a)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1989, 1993
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * This code is derived from software contributed to Berkeley by
8  * Rick Macklem at The University of Guelph.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. Neither the name of the University nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  *
34  */
35 
36 #include <sys/cdefs.h>
37 __FBSDID("$FreeBSD$");
38 
39 #include <sys/capsicum.h>
40 #include <sys/extattr.h>
41 
42 /*
43  * Functions that perform the vfs operations required by the routines in
44  * nfsd_serv.c. It is hoped that this change will make the server more
45  * portable.
46  */
47 
48 #include <fs/nfs/nfsport.h>
49 #include <sys/hash.h>
50 #include <sys/sysctl.h>
51 #include <nlm/nlm_prot.h>
52 #include <nlm/nlm.h>
53 
54 FEATURE(nfsd, "NFSv4 server");
55 
56 extern u_int32_t newnfs_true, newnfs_false, newnfs_xdrneg1;
57 extern int nfsrv_useacl;
58 extern int newnfs_numnfsd;
59 extern struct mount nfsv4root_mnt;
60 extern struct nfsrv_stablefirst nfsrv_stablefirst;
61 extern void (*nfsd_call_servertimer)(void);
62 extern SVCPOOL	*nfsrvd_pool;
63 extern struct nfsv4lock nfsd_suspend_lock;
64 extern struct nfsclienthashhead *nfsclienthash;
65 extern struct nfslockhashhead *nfslockhash;
66 extern struct nfssessionhash *nfssessionhash;
67 extern int nfsrv_sessionhashsize;
68 extern struct nfsstatsv1 nfsstatsv1;
69 extern struct nfslayouthash *nfslayouthash;
70 extern int nfsrv_layouthashsize;
71 extern struct mtx nfsrv_dslock_mtx;
72 extern int nfs_pnfsiothreads;
73 extern struct nfsdontlisthead nfsrv_dontlisthead;
74 extern volatile int nfsrv_dontlistlen;
75 extern volatile int nfsrv_devidcnt;
76 extern int nfsrv_maxpnfsmirror;
77 struct vfsoptlist nfsv4root_opt, nfsv4root_newopt;
78 NFSDLOCKMUTEX;
79 NFSSTATESPINLOCK;
80 struct nfsrchash_bucket nfsrchash_table[NFSRVCACHE_HASHSIZE];
81 struct nfsrchash_bucket nfsrcahash_table[NFSRVCACHE_HASHSIZE];
82 struct mtx nfsrc_udpmtx;
83 struct mtx nfs_v4root_mutex;
84 struct mtx nfsrv_dontlistlock_mtx;
85 struct mtx nfsrv_recalllock_mtx;
86 struct nfsrvfh nfs_rootfh, nfs_pubfh;
87 int nfs_pubfhset = 0, nfs_rootfhset = 0;
88 struct proc *nfsd_master_proc = NULL;
89 int nfsd_debuglevel = 0;
90 static pid_t nfsd_master_pid = (pid_t)-1;
91 static char nfsd_master_comm[MAXCOMLEN + 1];
92 static struct timeval nfsd_master_start;
93 static uint32_t nfsv4_sysid = 0;
94 static fhandle_t zerofh;
95 
96 static int nfssvc_srvcall(struct thread *, struct nfssvc_args *,
97     struct ucred *);
98 
99 int nfsrv_enable_crossmntpt = 1;
100 static int nfs_commit_blks;
101 static int nfs_commit_miss;
102 extern int nfsrv_issuedelegs;
103 extern int nfsrv_dolocallocks;
104 extern int nfsd_enable_stringtouid;
105 extern struct nfsdevicehead nfsrv_devidhead;
106 
107 static void nfsrv_pnfscreate(struct vnode *, struct vattr *, struct ucred *,
108     NFSPROC_T *);
109 static void nfsrv_pnfsremovesetup(struct vnode *, NFSPROC_T *, struct vnode **,
110     int *, char *, fhandle_t *);
111 static void nfsrv_pnfsremove(struct vnode **, int, char *, fhandle_t *,
112     NFSPROC_T *);
113 static int nfsrv_proxyds(struct nfsrv_descript *, struct vnode *, off_t, int,
114     struct ucred *, struct thread *, int, struct mbuf **, char *,
115     struct mbuf **, struct nfsvattr *, struct acl *);
116 static int nfsrv_setextattr(struct vnode *, struct nfsvattr *, NFSPROC_T *);
117 static int nfsrv_readdsrpc(fhandle_t *, off_t, int, struct ucred *,
118     NFSPROC_T *, struct nfsmount *, struct mbuf **, struct mbuf **);
119 static int nfsrv_writedsrpc(fhandle_t *, off_t, int, struct ucred *,
120     NFSPROC_T *, struct vnode *, struct nfsmount **, int, struct mbuf **,
121     char *, int *);
122 static int nfsrv_setacldsrpc(fhandle_t *, struct ucred *, NFSPROC_T *,
123     struct vnode *, struct nfsmount **, int, struct acl *, int *);
124 static int nfsrv_setattrdsrpc(fhandle_t *, struct ucred *, NFSPROC_T *,
125     struct vnode *, struct nfsmount **, int, struct nfsvattr *, int *);
126 static int nfsrv_getattrdsrpc(fhandle_t *, struct ucred *, NFSPROC_T *,
127     struct vnode *, struct nfsmount *, struct nfsvattr *);
128 static int nfsrv_putfhname(fhandle_t *, char *);
129 static int nfsrv_pnfslookupds(struct vnode *, struct vnode *,
130     struct pnfsdsfile *, struct vnode **, NFSPROC_T *);
131 static void nfsrv_pnfssetfh(struct vnode *, struct pnfsdsfile *, char *, char *,
132     struct vnode *, NFSPROC_T *);
133 static int nfsrv_dsremove(struct vnode *, char *, struct ucred *, NFSPROC_T *);
134 static int nfsrv_dssetacl(struct vnode *, struct acl *, struct ucred *,
135     NFSPROC_T *);
136 static int nfsrv_pnfsstatfs(struct statfs *);
137 
138 int nfs_pnfsio(task_fn_t *, void *);
139 
140 SYSCTL_NODE(_vfs, OID_AUTO, nfsd, CTLFLAG_RW, 0, "NFS server");
141 SYSCTL_INT(_vfs_nfsd, OID_AUTO, mirrormnt, CTLFLAG_RW,
142     &nfsrv_enable_crossmntpt, 0, "Enable nfsd to cross mount points");
143 SYSCTL_INT(_vfs_nfsd, OID_AUTO, commit_blks, CTLFLAG_RW, &nfs_commit_blks,
144     0, "");
145 SYSCTL_INT(_vfs_nfsd, OID_AUTO, commit_miss, CTLFLAG_RW, &nfs_commit_miss,
146     0, "");
147 SYSCTL_INT(_vfs_nfsd, OID_AUTO, issue_delegations, CTLFLAG_RW,
148     &nfsrv_issuedelegs, 0, "Enable nfsd to issue delegations");
149 SYSCTL_INT(_vfs_nfsd, OID_AUTO, enable_locallocks, CTLFLAG_RW,
150     &nfsrv_dolocallocks, 0, "Enable nfsd to acquire local locks on files");
151 SYSCTL_INT(_vfs_nfsd, OID_AUTO, debuglevel, CTLFLAG_RW, &nfsd_debuglevel,
152     0, "Debug level for NFS server");
153 SYSCTL_INT(_vfs_nfsd, OID_AUTO, enable_stringtouid, CTLFLAG_RW,
154     &nfsd_enable_stringtouid, 0, "Enable nfsd to accept numeric owner_names");
155 static int nfsrv_pnfsgetdsattr = 1;
156 SYSCTL_INT(_vfs_nfsd, OID_AUTO, pnfsgetdsattr, CTLFLAG_RW,
157     &nfsrv_pnfsgetdsattr, 0, "When set getattr gets DS attributes via RPC");
158 
159 /*
160  * nfsrv_dsdirsize can only be increased and only when the nfsd threads are
161  * not running.
162  * The dsN subdirectories for the increased values must have been created
163  * on all DS servers before this increase is done.
164  */
165 u_int	nfsrv_dsdirsize = 20;
166 static int
167 sysctl_dsdirsize(SYSCTL_HANDLER_ARGS)
168 {
169 	int error, newdsdirsize;
170 
171 	newdsdirsize = nfsrv_dsdirsize;
172 	error = sysctl_handle_int(oidp, &newdsdirsize, 0, req);
173 	if (error != 0 || req->newptr == NULL)
174 		return (error);
175 	if (newdsdirsize <= nfsrv_dsdirsize || newdsdirsize > 10000 ||
176 	    newnfs_numnfsd != 0)
177 		return (EINVAL);
178 	nfsrv_dsdirsize = newdsdirsize;
179 	return (0);
180 }
181 SYSCTL_PROC(_vfs_nfsd, OID_AUTO, dsdirsize, CTLTYPE_UINT | CTLFLAG_RW, 0,
182     sizeof(nfsrv_dsdirsize), sysctl_dsdirsize, "IU",
183     "Number of dsN subdirs on the DS servers");
184 
185 #define	MAX_REORDERED_RPC	16
186 #define	NUM_HEURISTIC		1031
187 #define	NHUSE_INIT		64
188 #define	NHUSE_INC		16
189 #define	NHUSE_MAX		2048
190 
191 static struct nfsheur {
192 	struct vnode *nh_vp;	/* vp to match (unreferenced pointer) */
193 	off_t nh_nextoff;	/* next offset for sequential detection */
194 	int nh_use;		/* use count for selection */
195 	int nh_seqcount;	/* heuristic */
196 } nfsheur[NUM_HEURISTIC];
197 
198 
199 /*
200  * Heuristic to detect sequential operation.
201  */
202 static struct nfsheur *
203 nfsrv_sequential_heuristic(struct uio *uio, struct vnode *vp)
204 {
205 	struct nfsheur *nh;
206 	int hi, try;
207 
208 	/* Locate best candidate. */
209 	try = 32;
210 	hi = ((int)(vm_offset_t)vp / sizeof(struct vnode)) % NUM_HEURISTIC;
211 	nh = &nfsheur[hi];
212 	while (try--) {
213 		if (nfsheur[hi].nh_vp == vp) {
214 			nh = &nfsheur[hi];
215 			break;
216 		}
217 		if (nfsheur[hi].nh_use > 0)
218 			--nfsheur[hi].nh_use;
219 		hi = (hi + 1) % NUM_HEURISTIC;
220 		if (nfsheur[hi].nh_use < nh->nh_use)
221 			nh = &nfsheur[hi];
222 	}
223 
224 	/* Initialize hint if this is a new file. */
225 	if (nh->nh_vp != vp) {
226 		nh->nh_vp = vp;
227 		nh->nh_nextoff = uio->uio_offset;
228 		nh->nh_use = NHUSE_INIT;
229 		if (uio->uio_offset == 0)
230 			nh->nh_seqcount = 4;
231 		else
232 			nh->nh_seqcount = 1;
233 	}
234 
235 	/* Calculate heuristic. */
236 	if ((uio->uio_offset == 0 && nh->nh_seqcount > 0) ||
237 	    uio->uio_offset == nh->nh_nextoff) {
238 		/* See comments in vfs_vnops.c:sequential_heuristic(). */
239 		nh->nh_seqcount += howmany(uio->uio_resid, 16384);
240 		if (nh->nh_seqcount > IO_SEQMAX)
241 			nh->nh_seqcount = IO_SEQMAX;
242 	} else if (qabs(uio->uio_offset - nh->nh_nextoff) <= MAX_REORDERED_RPC *
243 	    imax(vp->v_mount->mnt_stat.f_iosize, uio->uio_resid)) {
244 		/* Probably a reordered RPC, leave seqcount alone. */
245 	} else if (nh->nh_seqcount > 1) {
246 		nh->nh_seqcount /= 2;
247 	} else {
248 		nh->nh_seqcount = 0;
249 	}
250 	nh->nh_use += NHUSE_INC;
251 	if (nh->nh_use > NHUSE_MAX)
252 		nh->nh_use = NHUSE_MAX;
253 	return (nh);
254 }
255 
256 /*
257  * Get attributes into nfsvattr structure.
258  */
259 int
260 nfsvno_getattr(struct vnode *vp, struct nfsvattr *nvap,
261     struct nfsrv_descript *nd, struct thread *p, int vpislocked,
262     nfsattrbit_t *attrbitp)
263 {
264 	int error, gotattr, lockedit = 0;
265 	struct nfsvattr na;
266 
267 	if (vpislocked == 0) {
268 		/*
269 		 * When vpislocked == 0, the vnode is either exclusively
270 		 * locked by this thread or not locked by this thread.
271 		 * As such, shared lock it, if not exclusively locked.
272 		 */
273 		if (NFSVOPISLOCKED(vp) != LK_EXCLUSIVE) {
274 			lockedit = 1;
275 			NFSVOPLOCK(vp, LK_SHARED | LK_RETRY);
276 		}
277 	}
278 
279 	/*
280 	 * Acquire the Change, Size and TimeModify attributes, as required.
281 	 * This needs to be done for regular files if:
282 	 * - non-NFSv4 RPCs or
283 	 * - when attrbitp == NULL or
284 	 * - an NFSv4 RPC with any of the above attributes in attrbitp.
285 	 * A return of 0 for nfsrv_proxyds() indicates that it has acquired
286 	 * these attributes.  nfsrv_proxyds() will return an error if the
287 	 * server is not a pNFS one.
288 	 */
289 	gotattr = 0;
290 	if (vp->v_type == VREG && nfsrv_devidcnt > 0 && (attrbitp == NULL ||
291 	    (nd->nd_flag & ND_NFSV4) == 0 ||
292 	    NFSISSET_ATTRBIT(attrbitp, NFSATTRBIT_CHANGE) ||
293 	    NFSISSET_ATTRBIT(attrbitp, NFSATTRBIT_SIZE) ||
294 	    NFSISSET_ATTRBIT(attrbitp, NFSATTRBIT_TIMEACCESS) ||
295 	    NFSISSET_ATTRBIT(attrbitp, NFSATTRBIT_TIMEMODIFY))) {
296 		error = nfsrv_proxyds(nd, vp, 0, 0, nd->nd_cred, p,
297 		    NFSPROC_GETATTR, NULL, NULL, NULL, &na, NULL);
298 		if (error == 0)
299 			gotattr = 1;
300 	}
301 
302 	error = VOP_GETATTR(vp, &nvap->na_vattr, nd->nd_cred);
303 	if (lockedit != 0)
304 		NFSVOPUNLOCK(vp, 0);
305 
306 	/*
307 	 * If we got the Change, Size and Modify Time from the DS,
308 	 * replace them.
309 	 */
310 	if (gotattr != 0) {
311 		nvap->na_atime = na.na_atime;
312 		nvap->na_mtime = na.na_mtime;
313 		nvap->na_filerev = na.na_filerev;
314 		nvap->na_size = na.na_size;
315 	}
316 	NFSD_DEBUG(4, "nfsvno_getattr: gotattr=%d err=%d chg=%ju\n", gotattr,
317 	    error, (uintmax_t)na.na_filerev);
318 
319 	NFSEXITCODE(error);
320 	return (error);
321 }
322 
323 /*
324  * Get a file handle for a vnode.
325  */
326 int
327 nfsvno_getfh(struct vnode *vp, fhandle_t *fhp, struct thread *p)
328 {
329 	int error;
330 
331 	NFSBZERO((caddr_t)fhp, sizeof(fhandle_t));
332 	fhp->fh_fsid = vp->v_mount->mnt_stat.f_fsid;
333 	error = VOP_VPTOFH(vp, &fhp->fh_fid);
334 
335 	NFSEXITCODE(error);
336 	return (error);
337 }
338 
339 /*
340  * Perform access checking for vnodes obtained from file handles that would
341  * refer to files already opened by a Unix client. You cannot just use
342  * vn_writechk() and VOP_ACCESSX() for two reasons.
343  * 1 - You must check for exported rdonly as well as MNT_RDONLY for the write
344  *     case.
345  * 2 - The owner is to be given access irrespective of mode bits for some
346  *     operations, so that processes that chmod after opening a file don't
347  *     break.
348  */
349 int
350 nfsvno_accchk(struct vnode *vp, accmode_t accmode, struct ucred *cred,
351     struct nfsexstuff *exp, struct thread *p, int override, int vpislocked,
352     u_int32_t *supportedtypep)
353 {
354 	struct vattr vattr;
355 	int error = 0, getret = 0;
356 
357 	if (vpislocked == 0) {
358 		if (NFSVOPLOCK(vp, LK_SHARED) != 0) {
359 			error = EPERM;
360 			goto out;
361 		}
362 	}
363 	if (accmode & VWRITE) {
364 		/* Just vn_writechk() changed to check rdonly */
365 		/*
366 		 * Disallow write attempts on read-only file systems;
367 		 * unless the file is a socket or a block or character
368 		 * device resident on the file system.
369 		 */
370 		if (NFSVNO_EXRDONLY(exp) ||
371 		    (vp->v_mount->mnt_flag & MNT_RDONLY)) {
372 			switch (vp->v_type) {
373 			case VREG:
374 			case VDIR:
375 			case VLNK:
376 				error = EROFS;
377 			default:
378 				break;
379 			}
380 		}
381 		/*
382 		 * If there's shared text associated with
383 		 * the inode, try to free it up once.  If
384 		 * we fail, we can't allow writing.
385 		 */
386 		if (VOP_IS_TEXT(vp) && error == 0)
387 			error = ETXTBSY;
388 	}
389 	if (error != 0) {
390 		if (vpislocked == 0)
391 			NFSVOPUNLOCK(vp, 0);
392 		goto out;
393 	}
394 
395 	/*
396 	 * Should the override still be applied when ACLs are enabled?
397 	 */
398 	error = VOP_ACCESSX(vp, accmode, cred, p);
399 	if (error != 0 && (accmode & (VDELETE | VDELETE_CHILD))) {
400 		/*
401 		 * Try again with VEXPLICIT_DENY, to see if the test for
402 		 * deletion is supported.
403 		 */
404 		error = VOP_ACCESSX(vp, accmode | VEXPLICIT_DENY, cred, p);
405 		if (error == 0) {
406 			if (vp->v_type == VDIR) {
407 				accmode &= ~(VDELETE | VDELETE_CHILD);
408 				accmode |= VWRITE;
409 				error = VOP_ACCESSX(vp, accmode, cred, p);
410 			} else if (supportedtypep != NULL) {
411 				*supportedtypep &= ~NFSACCESS_DELETE;
412 			}
413 		}
414 	}
415 
416 	/*
417 	 * Allow certain operations for the owner (reads and writes
418 	 * on files that are already open).
419 	 */
420 	if (override != NFSACCCHK_NOOVERRIDE &&
421 	    (error == EPERM || error == EACCES)) {
422 		if (cred->cr_uid == 0 && (override & NFSACCCHK_ALLOWROOT))
423 			error = 0;
424 		else if (override & NFSACCCHK_ALLOWOWNER) {
425 			getret = VOP_GETATTR(vp, &vattr, cred);
426 			if (getret == 0 && cred->cr_uid == vattr.va_uid)
427 				error = 0;
428 		}
429 	}
430 	if (vpislocked == 0)
431 		NFSVOPUNLOCK(vp, 0);
432 
433 out:
434 	NFSEXITCODE(error);
435 	return (error);
436 }
437 
438 /*
439  * Set attribute(s) vnop.
440  */
441 int
442 nfsvno_setattr(struct vnode *vp, struct nfsvattr *nvap, struct ucred *cred,
443     struct thread *p, struct nfsexstuff *exp)
444 {
445 	u_quad_t savsize = 0;
446 	int error, savedit;
447 
448 	/*
449 	 * If this is an exported file system and a pNFS service is running,
450 	 * don't VOP_SETATTR() of size for the MDS file system.
451 	 */
452 	savedit = 0;
453 	error = 0;
454 	if (vp->v_type == VREG && (vp->v_mount->mnt_flag & MNT_EXPORTED) != 0 &&
455 	    nfsrv_devidcnt != 0 && nvap->na_vattr.va_size != VNOVAL &&
456 	    nvap->na_vattr.va_size > 0) {
457 		savsize = nvap->na_vattr.va_size;
458 		nvap->na_vattr.va_size = VNOVAL;
459 		if (nvap->na_vattr.va_uid != (uid_t)VNOVAL ||
460 		    nvap->na_vattr.va_gid != (gid_t)VNOVAL ||
461 		    nvap->na_vattr.va_mode != (mode_t)VNOVAL ||
462 		    nvap->na_vattr.va_atime.tv_sec != VNOVAL ||
463 		    nvap->na_vattr.va_mtime.tv_sec != VNOVAL)
464 			savedit = 1;
465 		else
466 			savedit = 2;
467 	}
468 	if (savedit != 2)
469 		error = VOP_SETATTR(vp, &nvap->na_vattr, cred);
470 	if (savedit != 0)
471 		nvap->na_vattr.va_size = savsize;
472 	if (error == 0 && (nvap->na_vattr.va_uid != (uid_t)VNOVAL ||
473 	    nvap->na_vattr.va_gid != (gid_t)VNOVAL ||
474 	    nvap->na_vattr.va_size != VNOVAL ||
475 	    nvap->na_vattr.va_mode != (mode_t)VNOVAL ||
476 	    nvap->na_vattr.va_atime.tv_sec != VNOVAL ||
477 	    nvap->na_vattr.va_mtime.tv_sec != VNOVAL)) {
478 		/* For a pNFS server, set the attributes on the DS file. */
479 		error = nfsrv_proxyds(NULL, vp, 0, 0, cred, p, NFSPROC_SETATTR,
480 		    NULL, NULL, NULL, nvap, NULL);
481 		if (error == ENOENT)
482 			error = 0;
483 	}
484 	NFSEXITCODE(error);
485 	return (error);
486 }
487 
488 /*
489  * Set up nameidata for a lookup() call and do it.
490  */
491 int
492 nfsvno_namei(struct nfsrv_descript *nd, struct nameidata *ndp,
493     struct vnode *dp, int islocked, struct nfsexstuff *exp, struct thread *p,
494     struct vnode **retdirp)
495 {
496 	struct componentname *cnp = &ndp->ni_cnd;
497 	int i;
498 	struct iovec aiov;
499 	struct uio auio;
500 	int lockleaf = (cnp->cn_flags & LOCKLEAF) != 0, linklen;
501 	int error = 0;
502 	char *cp;
503 
504 	*retdirp = NULL;
505 	cnp->cn_nameptr = cnp->cn_pnbuf;
506 	ndp->ni_lcf = 0;
507 	/*
508 	 * Extract and set starting directory.
509 	 */
510 	if (dp->v_type != VDIR) {
511 		if (islocked)
512 			vput(dp);
513 		else
514 			vrele(dp);
515 		nfsvno_relpathbuf(ndp);
516 		error = ENOTDIR;
517 		goto out1;
518 	}
519 	if (islocked)
520 		NFSVOPUNLOCK(dp, 0);
521 	VREF(dp);
522 	*retdirp = dp;
523 	if (NFSVNO_EXRDONLY(exp))
524 		cnp->cn_flags |= RDONLY;
525 	ndp->ni_segflg = UIO_SYSSPACE;
526 
527 	if (nd->nd_flag & ND_PUBLOOKUP) {
528 		ndp->ni_loopcnt = 0;
529 		if (cnp->cn_pnbuf[0] == '/') {
530 			vrele(dp);
531 			/*
532 			 * Check for degenerate pathnames here, since lookup()
533 			 * panics on them.
534 			 */
535 			for (i = 1; i < ndp->ni_pathlen; i++)
536 				if (cnp->cn_pnbuf[i] != '/')
537 					break;
538 			if (i == ndp->ni_pathlen) {
539 				error = NFSERR_ACCES;
540 				goto out;
541 			}
542 			dp = rootvnode;
543 			VREF(dp);
544 		}
545 	} else if ((nfsrv_enable_crossmntpt == 0 && NFSVNO_EXPORTED(exp)) ||
546 	    (nd->nd_flag & ND_NFSV4) == 0) {
547 		/*
548 		 * Only cross mount points for NFSv4 when doing a
549 		 * mount while traversing the file system above
550 		 * the mount point, unless nfsrv_enable_crossmntpt is set.
551 		 */
552 		cnp->cn_flags |= NOCROSSMOUNT;
553 	}
554 
555 	/*
556 	 * Initialize for scan, set ni_startdir and bump ref on dp again
557 	 * because lookup() will dereference ni_startdir.
558 	 */
559 
560 	cnp->cn_thread = p;
561 	ndp->ni_startdir = dp;
562 	ndp->ni_rootdir = rootvnode;
563 	ndp->ni_topdir = NULL;
564 
565 	if (!lockleaf)
566 		cnp->cn_flags |= LOCKLEAF;
567 	for (;;) {
568 		cnp->cn_nameptr = cnp->cn_pnbuf;
569 		/*
570 		 * Call lookup() to do the real work.  If an error occurs,
571 		 * ndp->ni_vp and ni_dvp are left uninitialized or NULL and
572 		 * we do not have to dereference anything before returning.
573 		 * In either case ni_startdir will be dereferenced and NULLed
574 		 * out.
575 		 */
576 		error = lookup(ndp);
577 		if (error)
578 			break;
579 
580 		/*
581 		 * Check for encountering a symbolic link.  Trivial
582 		 * termination occurs if no symlink encountered.
583 		 */
584 		if ((cnp->cn_flags & ISSYMLINK) == 0) {
585 			if ((cnp->cn_flags & (SAVENAME | SAVESTART)) == 0)
586 				nfsvno_relpathbuf(ndp);
587 			if (ndp->ni_vp && !lockleaf)
588 				NFSVOPUNLOCK(ndp->ni_vp, 0);
589 			break;
590 		}
591 
592 		/*
593 		 * Validate symlink
594 		 */
595 		if ((cnp->cn_flags & LOCKPARENT) && ndp->ni_pathlen == 1)
596 			NFSVOPUNLOCK(ndp->ni_dvp, 0);
597 		if (!(nd->nd_flag & ND_PUBLOOKUP)) {
598 			error = EINVAL;
599 			goto badlink2;
600 		}
601 
602 		if (ndp->ni_loopcnt++ >= MAXSYMLINKS) {
603 			error = ELOOP;
604 			goto badlink2;
605 		}
606 		if (ndp->ni_pathlen > 1)
607 			cp = uma_zalloc(namei_zone, M_WAITOK);
608 		else
609 			cp = cnp->cn_pnbuf;
610 		aiov.iov_base = cp;
611 		aiov.iov_len = MAXPATHLEN;
612 		auio.uio_iov = &aiov;
613 		auio.uio_iovcnt = 1;
614 		auio.uio_offset = 0;
615 		auio.uio_rw = UIO_READ;
616 		auio.uio_segflg = UIO_SYSSPACE;
617 		auio.uio_td = NULL;
618 		auio.uio_resid = MAXPATHLEN;
619 		error = VOP_READLINK(ndp->ni_vp, &auio, cnp->cn_cred);
620 		if (error) {
621 		badlink1:
622 			if (ndp->ni_pathlen > 1)
623 				uma_zfree(namei_zone, cp);
624 		badlink2:
625 			vrele(ndp->ni_dvp);
626 			vput(ndp->ni_vp);
627 			break;
628 		}
629 		linklen = MAXPATHLEN - auio.uio_resid;
630 		if (linklen == 0) {
631 			error = ENOENT;
632 			goto badlink1;
633 		}
634 		if (linklen + ndp->ni_pathlen >= MAXPATHLEN) {
635 			error = ENAMETOOLONG;
636 			goto badlink1;
637 		}
638 
639 		/*
640 		 * Adjust or replace path
641 		 */
642 		if (ndp->ni_pathlen > 1) {
643 			NFSBCOPY(ndp->ni_next, cp + linklen, ndp->ni_pathlen);
644 			uma_zfree(namei_zone, cnp->cn_pnbuf);
645 			cnp->cn_pnbuf = cp;
646 		} else
647 			cnp->cn_pnbuf[linklen] = '\0';
648 		ndp->ni_pathlen += linklen;
649 
650 		/*
651 		 * Cleanup refs for next loop and check if root directory
652 		 * should replace current directory.  Normally ni_dvp
653 		 * becomes the new base directory and is cleaned up when
654 		 * we loop.  Explicitly null pointers after invalidation
655 		 * to clarify operation.
656 		 */
657 		vput(ndp->ni_vp);
658 		ndp->ni_vp = NULL;
659 
660 		if (cnp->cn_pnbuf[0] == '/') {
661 			vrele(ndp->ni_dvp);
662 			ndp->ni_dvp = ndp->ni_rootdir;
663 			VREF(ndp->ni_dvp);
664 		}
665 		ndp->ni_startdir = ndp->ni_dvp;
666 		ndp->ni_dvp = NULL;
667 	}
668 	if (!lockleaf)
669 		cnp->cn_flags &= ~LOCKLEAF;
670 
671 out:
672 	if (error) {
673 		nfsvno_relpathbuf(ndp);
674 		ndp->ni_vp = NULL;
675 		ndp->ni_dvp = NULL;
676 		ndp->ni_startdir = NULL;
677 	} else if ((ndp->ni_cnd.cn_flags & (WANTPARENT|LOCKPARENT)) == 0) {
678 		ndp->ni_dvp = NULL;
679 	}
680 
681 out1:
682 	NFSEXITCODE2(error, nd);
683 	return (error);
684 }
685 
686 /*
687  * Set up a pathname buffer and return a pointer to it and, optionally
688  * set a hash pointer.
689  */
690 void
691 nfsvno_setpathbuf(struct nameidata *ndp, char **bufpp, u_long **hashpp)
692 {
693 	struct componentname *cnp = &ndp->ni_cnd;
694 
695 	cnp->cn_flags |= (NOMACCHECK | HASBUF);
696 	cnp->cn_pnbuf = uma_zalloc(namei_zone, M_WAITOK);
697 	if (hashpp != NULL)
698 		*hashpp = NULL;
699 	*bufpp = cnp->cn_pnbuf;
700 }
701 
702 /*
703  * Release the above path buffer, if not released by nfsvno_namei().
704  */
705 void
706 nfsvno_relpathbuf(struct nameidata *ndp)
707 {
708 
709 	if ((ndp->ni_cnd.cn_flags & HASBUF) == 0)
710 		panic("nfsrelpath");
711 	uma_zfree(namei_zone, ndp->ni_cnd.cn_pnbuf);
712 	ndp->ni_cnd.cn_flags &= ~HASBUF;
713 }
714 
715 /*
716  * Readlink vnode op into an mbuf list.
717  */
718 int
719 nfsvno_readlink(struct vnode *vp, struct ucred *cred, struct thread *p,
720     struct mbuf **mpp, struct mbuf **mpendp, int *lenp)
721 {
722 	struct iovec iv[(NFS_MAXPATHLEN+MLEN-1)/MLEN];
723 	struct iovec *ivp = iv;
724 	struct uio io, *uiop = &io;
725 	struct mbuf *mp, *mp2 = NULL, *mp3 = NULL;
726 	int i, len, tlen, error = 0;
727 
728 	len = 0;
729 	i = 0;
730 	while (len < NFS_MAXPATHLEN) {
731 		NFSMGET(mp);
732 		MCLGET(mp, M_WAITOK);
733 		mp->m_len = M_SIZE(mp);
734 		if (len == 0) {
735 			mp3 = mp2 = mp;
736 		} else {
737 			mp2->m_next = mp;
738 			mp2 = mp;
739 		}
740 		if ((len + mp->m_len) > NFS_MAXPATHLEN) {
741 			mp->m_len = NFS_MAXPATHLEN - len;
742 			len = NFS_MAXPATHLEN;
743 		} else {
744 			len += mp->m_len;
745 		}
746 		ivp->iov_base = mtod(mp, caddr_t);
747 		ivp->iov_len = mp->m_len;
748 		i++;
749 		ivp++;
750 	}
751 	uiop->uio_iov = iv;
752 	uiop->uio_iovcnt = i;
753 	uiop->uio_offset = 0;
754 	uiop->uio_resid = len;
755 	uiop->uio_rw = UIO_READ;
756 	uiop->uio_segflg = UIO_SYSSPACE;
757 	uiop->uio_td = NULL;
758 	error = VOP_READLINK(vp, uiop, cred);
759 	if (error) {
760 		m_freem(mp3);
761 		*lenp = 0;
762 		goto out;
763 	}
764 	if (uiop->uio_resid > 0) {
765 		len -= uiop->uio_resid;
766 		tlen = NFSM_RNDUP(len);
767 		nfsrv_adj(mp3, NFS_MAXPATHLEN - tlen, tlen - len);
768 	}
769 	*lenp = len;
770 	*mpp = mp3;
771 	*mpendp = mp;
772 
773 out:
774 	NFSEXITCODE(error);
775 	return (error);
776 }
777 
778 /*
779  * Read vnode op call into mbuf list.
780  */
781 int
782 nfsvno_read(struct vnode *vp, off_t off, int cnt, struct ucred *cred,
783     struct thread *p, struct mbuf **mpp, struct mbuf **mpendp)
784 {
785 	struct mbuf *m;
786 	int i;
787 	struct iovec *iv;
788 	struct iovec *iv2;
789 	int error = 0, len, left, siz, tlen, ioflag = 0;
790 	struct mbuf *m2 = NULL, *m3;
791 	struct uio io, *uiop = &io;
792 	struct nfsheur *nh;
793 
794 	/*
795 	 * Attempt to read from a DS file. A return of ENOENT implies
796 	 * there is no DS file to read.
797 	 */
798 	error = nfsrv_proxyds(NULL, vp, off, cnt, cred, p, NFSPROC_READDS, mpp,
799 	    NULL, mpendp, NULL, NULL);
800 	if (error != ENOENT)
801 		return (error);
802 
803 	len = left = NFSM_RNDUP(cnt);
804 	m3 = NULL;
805 	/*
806 	 * Generate the mbuf list with the uio_iov ref. to it.
807 	 */
808 	i = 0;
809 	while (left > 0) {
810 		NFSMGET(m);
811 		MCLGET(m, M_WAITOK);
812 		m->m_len = 0;
813 		siz = min(M_TRAILINGSPACE(m), left);
814 		left -= siz;
815 		i++;
816 		if (m3)
817 			m2->m_next = m;
818 		else
819 			m3 = m;
820 		m2 = m;
821 	}
822 	iv = malloc(i * sizeof (struct iovec),
823 	    M_TEMP, M_WAITOK);
824 	uiop->uio_iov = iv2 = iv;
825 	m = m3;
826 	left = len;
827 	i = 0;
828 	while (left > 0) {
829 		if (m == NULL)
830 			panic("nfsvno_read iov");
831 		siz = min(M_TRAILINGSPACE(m), left);
832 		if (siz > 0) {
833 			iv->iov_base = mtod(m, caddr_t) + m->m_len;
834 			iv->iov_len = siz;
835 			m->m_len += siz;
836 			left -= siz;
837 			iv++;
838 			i++;
839 		}
840 		m = m->m_next;
841 	}
842 	uiop->uio_iovcnt = i;
843 	uiop->uio_offset = off;
844 	uiop->uio_resid = len;
845 	uiop->uio_rw = UIO_READ;
846 	uiop->uio_segflg = UIO_SYSSPACE;
847 	uiop->uio_td = NULL;
848 	nh = nfsrv_sequential_heuristic(uiop, vp);
849 	ioflag |= nh->nh_seqcount << IO_SEQSHIFT;
850 	/* XXX KDM make this more systematic? */
851 	nfsstatsv1.srvbytes[NFSV4OP_READ] += uiop->uio_resid;
852 	error = VOP_READ(vp, uiop, IO_NODELOCKED | ioflag, cred);
853 	free(iv2, M_TEMP);
854 	if (error) {
855 		m_freem(m3);
856 		*mpp = NULL;
857 		goto out;
858 	}
859 	nh->nh_nextoff = uiop->uio_offset;
860 	tlen = len - uiop->uio_resid;
861 	cnt = cnt < tlen ? cnt : tlen;
862 	tlen = NFSM_RNDUP(cnt);
863 	if (tlen == 0) {
864 		m_freem(m3);
865 		m3 = NULL;
866 	} else if (len != tlen || tlen != cnt)
867 		nfsrv_adj(m3, len - tlen, tlen - cnt);
868 	*mpp = m3;
869 	*mpendp = m2;
870 
871 out:
872 	NFSEXITCODE(error);
873 	return (error);
874 }
875 
876 /*
877  * Write vnode op from an mbuf list.
878  */
879 int
880 nfsvno_write(struct vnode *vp, off_t off, int retlen, int cnt, int *stable,
881     struct mbuf *mp, char *cp, struct ucred *cred, struct thread *p)
882 {
883 	struct iovec *ivp;
884 	int i, len;
885 	struct iovec *iv;
886 	int ioflags, error;
887 	struct uio io, *uiop = &io;
888 	struct nfsheur *nh;
889 
890 	/*
891 	 * Attempt to write to a DS file. A return of ENOENT implies
892 	 * there is no DS file to write.
893 	 */
894 	error = nfsrv_proxyds(NULL, vp, off, retlen, cred, p, NFSPROC_WRITEDS,
895 	    &mp, cp, NULL, NULL, NULL);
896 	if (error != ENOENT) {
897 		*stable = NFSWRITE_FILESYNC;
898 		return (error);
899 	}
900 
901 	ivp = malloc(cnt * sizeof (struct iovec), M_TEMP,
902 	    M_WAITOK);
903 	uiop->uio_iov = iv = ivp;
904 	uiop->uio_iovcnt = cnt;
905 	i = mtod(mp, caddr_t) + mp->m_len - cp;
906 	len = retlen;
907 	while (len > 0) {
908 		if (mp == NULL)
909 			panic("nfsvno_write");
910 		if (i > 0) {
911 			i = min(i, len);
912 			ivp->iov_base = cp;
913 			ivp->iov_len = i;
914 			ivp++;
915 			len -= i;
916 		}
917 		mp = mp->m_next;
918 		if (mp) {
919 			i = mp->m_len;
920 			cp = mtod(mp, caddr_t);
921 		}
922 	}
923 
924 	if (*stable == NFSWRITE_UNSTABLE)
925 		ioflags = IO_NODELOCKED;
926 	else
927 		ioflags = (IO_SYNC | IO_NODELOCKED);
928 	uiop->uio_resid = retlen;
929 	uiop->uio_rw = UIO_WRITE;
930 	uiop->uio_segflg = UIO_SYSSPACE;
931 	NFSUIOPROC(uiop, p);
932 	uiop->uio_offset = off;
933 	nh = nfsrv_sequential_heuristic(uiop, vp);
934 	ioflags |= nh->nh_seqcount << IO_SEQSHIFT;
935 	/* XXX KDM make this more systematic? */
936 	nfsstatsv1.srvbytes[NFSV4OP_WRITE] += uiop->uio_resid;
937 	error = VOP_WRITE(vp, uiop, ioflags, cred);
938 	if (error == 0)
939 		nh->nh_nextoff = uiop->uio_offset;
940 	free(iv, M_TEMP);
941 
942 	NFSEXITCODE(error);
943 	return (error);
944 }
945 
946 /*
947  * Common code for creating a regular file (plus special files for V2).
948  */
949 int
950 nfsvno_createsub(struct nfsrv_descript *nd, struct nameidata *ndp,
951     struct vnode **vpp, struct nfsvattr *nvap, int *exclusive_flagp,
952     int32_t *cverf, NFSDEV_T rdev, struct thread *p, struct nfsexstuff *exp)
953 {
954 	u_quad_t tempsize;
955 	int error;
956 
957 	error = nd->nd_repstat;
958 	if (!error && ndp->ni_vp == NULL) {
959 		if (nvap->na_type == VREG || nvap->na_type == VSOCK) {
960 			vrele(ndp->ni_startdir);
961 			error = VOP_CREATE(ndp->ni_dvp,
962 			    &ndp->ni_vp, &ndp->ni_cnd, &nvap->na_vattr);
963 			/* For a pNFS server, create the data file on a DS. */
964 			if (error == 0 && nvap->na_type == VREG) {
965 				/*
966 				 * Create a data file on a DS for a pNFS server.
967 				 * This function just returns if not
968 				 * running a pNFS DS or the creation fails.
969 				 */
970 				nfsrv_pnfscreate(ndp->ni_vp, &nvap->na_vattr,
971 				    nd->nd_cred, p);
972 			}
973 			vput(ndp->ni_dvp);
974 			nfsvno_relpathbuf(ndp);
975 			if (!error) {
976 				if (*exclusive_flagp) {
977 					*exclusive_flagp = 0;
978 					NFSVNO_ATTRINIT(nvap);
979 					nvap->na_atime.tv_sec = cverf[0];
980 					nvap->na_atime.tv_nsec = cverf[1];
981 					error = VOP_SETATTR(ndp->ni_vp,
982 					    &nvap->na_vattr, nd->nd_cred);
983 					if (error != 0) {
984 						vput(ndp->ni_vp);
985 						ndp->ni_vp = NULL;
986 						error = NFSERR_NOTSUPP;
987 					}
988 				}
989 			}
990 		/*
991 		 * NFS V2 Only. nfsrvd_mknod() does this for V3.
992 		 * (This implies, just get out on an error.)
993 		 */
994 		} else if (nvap->na_type == VCHR || nvap->na_type == VBLK ||
995 			nvap->na_type == VFIFO) {
996 			if (nvap->na_type == VCHR && rdev == 0xffffffff)
997 				nvap->na_type = VFIFO;
998                         if (nvap->na_type != VFIFO &&
999 			    (error = priv_check_cred(nd->nd_cred,
1000 			     PRIV_VFS_MKNOD_DEV, 0))) {
1001 				vrele(ndp->ni_startdir);
1002 				nfsvno_relpathbuf(ndp);
1003 				vput(ndp->ni_dvp);
1004 				goto out;
1005 			}
1006 			nvap->na_rdev = rdev;
1007 			error = VOP_MKNOD(ndp->ni_dvp, &ndp->ni_vp,
1008 			    &ndp->ni_cnd, &nvap->na_vattr);
1009 			vput(ndp->ni_dvp);
1010 			nfsvno_relpathbuf(ndp);
1011 			vrele(ndp->ni_startdir);
1012 			if (error)
1013 				goto out;
1014 		} else {
1015 			vrele(ndp->ni_startdir);
1016 			nfsvno_relpathbuf(ndp);
1017 			vput(ndp->ni_dvp);
1018 			error = ENXIO;
1019 			goto out;
1020 		}
1021 		*vpp = ndp->ni_vp;
1022 	} else {
1023 		/*
1024 		 * Handle cases where error is already set and/or
1025 		 * the file exists.
1026 		 * 1 - clean up the lookup
1027 		 * 2 - iff !error and na_size set, truncate it
1028 		 */
1029 		vrele(ndp->ni_startdir);
1030 		nfsvno_relpathbuf(ndp);
1031 		*vpp = ndp->ni_vp;
1032 		if (ndp->ni_dvp == *vpp)
1033 			vrele(ndp->ni_dvp);
1034 		else
1035 			vput(ndp->ni_dvp);
1036 		if (!error && nvap->na_size != VNOVAL) {
1037 			error = nfsvno_accchk(*vpp, VWRITE,
1038 			    nd->nd_cred, exp, p, NFSACCCHK_NOOVERRIDE,
1039 			    NFSACCCHK_VPISLOCKED, NULL);
1040 			if (!error) {
1041 				tempsize = nvap->na_size;
1042 				NFSVNO_ATTRINIT(nvap);
1043 				nvap->na_size = tempsize;
1044 				error = VOP_SETATTR(*vpp,
1045 				    &nvap->na_vattr, nd->nd_cred);
1046 			}
1047 		}
1048 		if (error)
1049 			vput(*vpp);
1050 	}
1051 
1052 out:
1053 	NFSEXITCODE(error);
1054 	return (error);
1055 }
1056 
1057 /*
1058  * Do a mknod vnode op.
1059  */
1060 int
1061 nfsvno_mknod(struct nameidata *ndp, struct nfsvattr *nvap, struct ucred *cred,
1062     struct thread *p)
1063 {
1064 	int error = 0;
1065 	enum vtype vtyp;
1066 
1067 	vtyp = nvap->na_type;
1068 	/*
1069 	 * Iff doesn't exist, create it.
1070 	 */
1071 	if (ndp->ni_vp) {
1072 		vrele(ndp->ni_startdir);
1073 		nfsvno_relpathbuf(ndp);
1074 		vput(ndp->ni_dvp);
1075 		vrele(ndp->ni_vp);
1076 		error = EEXIST;
1077 		goto out;
1078 	}
1079 	if (vtyp != VCHR && vtyp != VBLK && vtyp != VSOCK && vtyp != VFIFO) {
1080 		vrele(ndp->ni_startdir);
1081 		nfsvno_relpathbuf(ndp);
1082 		vput(ndp->ni_dvp);
1083 		error = NFSERR_BADTYPE;
1084 		goto out;
1085 	}
1086 	if (vtyp == VSOCK) {
1087 		vrele(ndp->ni_startdir);
1088 		error = VOP_CREATE(ndp->ni_dvp, &ndp->ni_vp,
1089 		    &ndp->ni_cnd, &nvap->na_vattr);
1090 		vput(ndp->ni_dvp);
1091 		nfsvno_relpathbuf(ndp);
1092 	} else {
1093 		if (nvap->na_type != VFIFO &&
1094 		    (error = priv_check_cred(cred, PRIV_VFS_MKNOD_DEV, 0))) {
1095 			vrele(ndp->ni_startdir);
1096 			nfsvno_relpathbuf(ndp);
1097 			vput(ndp->ni_dvp);
1098 			goto out;
1099 		}
1100 		error = VOP_MKNOD(ndp->ni_dvp, &ndp->ni_vp,
1101 		    &ndp->ni_cnd, &nvap->na_vattr);
1102 		vput(ndp->ni_dvp);
1103 		nfsvno_relpathbuf(ndp);
1104 		vrele(ndp->ni_startdir);
1105 		/*
1106 		 * Since VOP_MKNOD returns the ni_vp, I can't
1107 		 * see any reason to do the lookup.
1108 		 */
1109 	}
1110 
1111 out:
1112 	NFSEXITCODE(error);
1113 	return (error);
1114 }
1115 
1116 /*
1117  * Mkdir vnode op.
1118  */
1119 int
1120 nfsvno_mkdir(struct nameidata *ndp, struct nfsvattr *nvap, uid_t saved_uid,
1121     struct ucred *cred, struct thread *p, struct nfsexstuff *exp)
1122 {
1123 	int error = 0;
1124 
1125 	if (ndp->ni_vp != NULL) {
1126 		if (ndp->ni_dvp == ndp->ni_vp)
1127 			vrele(ndp->ni_dvp);
1128 		else
1129 			vput(ndp->ni_dvp);
1130 		vrele(ndp->ni_vp);
1131 		nfsvno_relpathbuf(ndp);
1132 		error = EEXIST;
1133 		goto out;
1134 	}
1135 	error = VOP_MKDIR(ndp->ni_dvp, &ndp->ni_vp, &ndp->ni_cnd,
1136 	    &nvap->na_vattr);
1137 	vput(ndp->ni_dvp);
1138 	nfsvno_relpathbuf(ndp);
1139 
1140 out:
1141 	NFSEXITCODE(error);
1142 	return (error);
1143 }
1144 
1145 /*
1146  * symlink vnode op.
1147  */
1148 int
1149 nfsvno_symlink(struct nameidata *ndp, struct nfsvattr *nvap, char *pathcp,
1150     int pathlen, int not_v2, uid_t saved_uid, struct ucred *cred, struct thread *p,
1151     struct nfsexstuff *exp)
1152 {
1153 	int error = 0;
1154 
1155 	if (ndp->ni_vp) {
1156 		vrele(ndp->ni_startdir);
1157 		nfsvno_relpathbuf(ndp);
1158 		if (ndp->ni_dvp == ndp->ni_vp)
1159 			vrele(ndp->ni_dvp);
1160 		else
1161 			vput(ndp->ni_dvp);
1162 		vrele(ndp->ni_vp);
1163 		error = EEXIST;
1164 		goto out;
1165 	}
1166 
1167 	error = VOP_SYMLINK(ndp->ni_dvp, &ndp->ni_vp, &ndp->ni_cnd,
1168 	    &nvap->na_vattr, pathcp);
1169 	vput(ndp->ni_dvp);
1170 	vrele(ndp->ni_startdir);
1171 	nfsvno_relpathbuf(ndp);
1172 	/*
1173 	 * Although FreeBSD still had the lookup code in
1174 	 * it for 7/current, there doesn't seem to be any
1175 	 * point, since VOP_SYMLINK() returns the ni_vp.
1176 	 * Just vput it for v2.
1177 	 */
1178 	if (!not_v2 && !error)
1179 		vput(ndp->ni_vp);
1180 
1181 out:
1182 	NFSEXITCODE(error);
1183 	return (error);
1184 }
1185 
1186 /*
1187  * Parse symbolic link arguments.
1188  * This function has an ugly side effect. It will malloc() an area for
1189  * the symlink and set iov_base to point to it, only if it succeeds.
1190  * So, if it returns with uiop->uio_iov->iov_base != NULL, that must
1191  * be FREE'd later.
1192  */
1193 int
1194 nfsvno_getsymlink(struct nfsrv_descript *nd, struct nfsvattr *nvap,
1195     struct thread *p, char **pathcpp, int *lenp)
1196 {
1197 	u_int32_t *tl;
1198 	char *pathcp = NULL;
1199 	int error = 0, len;
1200 	struct nfsv2_sattr *sp;
1201 
1202 	*pathcpp = NULL;
1203 	*lenp = 0;
1204 	if ((nd->nd_flag & ND_NFSV3) &&
1205 	    (error = nfsrv_sattr(nd, NULL, nvap, NULL, NULL, p)))
1206 		goto nfsmout;
1207 	NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
1208 	len = fxdr_unsigned(int, *tl);
1209 	if (len > NFS_MAXPATHLEN || len <= 0) {
1210 		error = EBADRPC;
1211 		goto nfsmout;
1212 	}
1213 	pathcp = malloc(len + 1, M_TEMP, M_WAITOK);
1214 	error = nfsrv_mtostr(nd, pathcp, len);
1215 	if (error)
1216 		goto nfsmout;
1217 	if (nd->nd_flag & ND_NFSV2) {
1218 		NFSM_DISSECT(sp, struct nfsv2_sattr *, NFSX_V2SATTR);
1219 		nvap->na_mode = fxdr_unsigned(u_int16_t, sp->sa_mode);
1220 	}
1221 	*pathcpp = pathcp;
1222 	*lenp = len;
1223 	NFSEXITCODE2(0, nd);
1224 	return (0);
1225 nfsmout:
1226 	if (pathcp)
1227 		free(pathcp, M_TEMP);
1228 	NFSEXITCODE2(error, nd);
1229 	return (error);
1230 }
1231 
1232 /*
1233  * Remove a non-directory object.
1234  */
1235 int
1236 nfsvno_removesub(struct nameidata *ndp, int is_v4, struct ucred *cred,
1237     struct thread *p, struct nfsexstuff *exp)
1238 {
1239 	struct vnode *vp, *dsdvp[NFSDEV_MAXMIRRORS];
1240 	int error = 0, mirrorcnt;
1241 	char fname[PNFS_FILENAME_LEN + 1];
1242 	fhandle_t fh;
1243 
1244 	vp = ndp->ni_vp;
1245 	dsdvp[0] = NULL;
1246 	if (vp->v_type == VDIR)
1247 		error = NFSERR_ISDIR;
1248 	else if (is_v4)
1249 		error = nfsrv_checkremove(vp, 1, p);
1250 	if (error == 0)
1251 		nfsrv_pnfsremovesetup(vp, p, dsdvp, &mirrorcnt, fname, &fh);
1252 	if (!error)
1253 		error = VOP_REMOVE(ndp->ni_dvp, vp, &ndp->ni_cnd);
1254 	if (error == 0 && dsdvp[0] != NULL)
1255 		nfsrv_pnfsremove(dsdvp, mirrorcnt, fname, &fh, p);
1256 	if (ndp->ni_dvp == vp)
1257 		vrele(ndp->ni_dvp);
1258 	else
1259 		vput(ndp->ni_dvp);
1260 	vput(vp);
1261 	if ((ndp->ni_cnd.cn_flags & SAVENAME) != 0)
1262 		nfsvno_relpathbuf(ndp);
1263 	NFSEXITCODE(error);
1264 	return (error);
1265 }
1266 
1267 /*
1268  * Remove a directory.
1269  */
1270 int
1271 nfsvno_rmdirsub(struct nameidata *ndp, int is_v4, struct ucred *cred,
1272     struct thread *p, struct nfsexstuff *exp)
1273 {
1274 	struct vnode *vp;
1275 	int error = 0;
1276 
1277 	vp = ndp->ni_vp;
1278 	if (vp->v_type != VDIR) {
1279 		error = ENOTDIR;
1280 		goto out;
1281 	}
1282 	/*
1283 	 * No rmdir "." please.
1284 	 */
1285 	if (ndp->ni_dvp == vp) {
1286 		error = EINVAL;
1287 		goto out;
1288 	}
1289 	/*
1290 	 * The root of a mounted filesystem cannot be deleted.
1291 	 */
1292 	if (vp->v_vflag & VV_ROOT)
1293 		error = EBUSY;
1294 out:
1295 	if (!error)
1296 		error = VOP_RMDIR(ndp->ni_dvp, vp, &ndp->ni_cnd);
1297 	if (ndp->ni_dvp == vp)
1298 		vrele(ndp->ni_dvp);
1299 	else
1300 		vput(ndp->ni_dvp);
1301 	vput(vp);
1302 	if ((ndp->ni_cnd.cn_flags & SAVENAME) != 0)
1303 		nfsvno_relpathbuf(ndp);
1304 	NFSEXITCODE(error);
1305 	return (error);
1306 }
1307 
1308 /*
1309  * Rename vnode op.
1310  */
1311 int
1312 nfsvno_rename(struct nameidata *fromndp, struct nameidata *tondp,
1313     u_int32_t ndstat, u_int32_t ndflag, struct ucred *cred, struct thread *p)
1314 {
1315 	struct vnode *fvp, *tvp, *tdvp, *dsdvp[NFSDEV_MAXMIRRORS];
1316 	int error = 0, mirrorcnt;
1317 	char fname[PNFS_FILENAME_LEN + 1];
1318 	fhandle_t fh;
1319 
1320 	dsdvp[0] = NULL;
1321 	fvp = fromndp->ni_vp;
1322 	if (ndstat) {
1323 		vrele(fromndp->ni_dvp);
1324 		vrele(fvp);
1325 		error = ndstat;
1326 		goto out1;
1327 	}
1328 	tdvp = tondp->ni_dvp;
1329 	tvp = tondp->ni_vp;
1330 	if (tvp != NULL) {
1331 		if (fvp->v_type == VDIR && tvp->v_type != VDIR) {
1332 			error = (ndflag & ND_NFSV2) ? EISDIR : EEXIST;
1333 			goto out;
1334 		} else if (fvp->v_type != VDIR && tvp->v_type == VDIR) {
1335 			error = (ndflag & ND_NFSV2) ? ENOTDIR : EEXIST;
1336 			goto out;
1337 		}
1338 		if (tvp->v_type == VDIR && tvp->v_mountedhere) {
1339 			error = (ndflag & ND_NFSV2) ? ENOTEMPTY : EXDEV;
1340 			goto out;
1341 		}
1342 
1343 		/*
1344 		 * A rename to '.' or '..' results in a prematurely
1345 		 * unlocked vnode on FreeBSD5, so I'm just going to fail that
1346 		 * here.
1347 		 */
1348 		if ((tondp->ni_cnd.cn_namelen == 1 &&
1349 		     tondp->ni_cnd.cn_nameptr[0] == '.') ||
1350 		    (tondp->ni_cnd.cn_namelen == 2 &&
1351 		     tondp->ni_cnd.cn_nameptr[0] == '.' &&
1352 		     tondp->ni_cnd.cn_nameptr[1] == '.')) {
1353 			error = EINVAL;
1354 			goto out;
1355 		}
1356 	}
1357 	if (fvp->v_type == VDIR && fvp->v_mountedhere) {
1358 		error = (ndflag & ND_NFSV2) ? ENOTEMPTY : EXDEV;
1359 		goto out;
1360 	}
1361 	if (fvp->v_mount != tdvp->v_mount) {
1362 		error = (ndflag & ND_NFSV2) ? ENOTEMPTY : EXDEV;
1363 		goto out;
1364 	}
1365 	if (fvp == tdvp) {
1366 		error = (ndflag & ND_NFSV2) ? ENOTEMPTY : EINVAL;
1367 		goto out;
1368 	}
1369 	if (fvp == tvp) {
1370 		/*
1371 		 * If source and destination are the same, there is nothing to
1372 		 * do. Set error to -1 to indicate this.
1373 		 */
1374 		error = -1;
1375 		goto out;
1376 	}
1377 	if (ndflag & ND_NFSV4) {
1378 		if (NFSVOPLOCK(fvp, LK_EXCLUSIVE) == 0) {
1379 			error = nfsrv_checkremove(fvp, 0, p);
1380 			NFSVOPUNLOCK(fvp, 0);
1381 		} else
1382 			error = EPERM;
1383 		if (tvp && !error)
1384 			error = nfsrv_checkremove(tvp, 1, p);
1385 	} else {
1386 		/*
1387 		 * For NFSv2 and NFSv3, try to get rid of the delegation, so
1388 		 * that the NFSv4 client won't be confused by the rename.
1389 		 * Since nfsd_recalldelegation() can only be called on an
1390 		 * unlocked vnode at this point and fvp is the file that will
1391 		 * still exist after the rename, just do fvp.
1392 		 */
1393 		nfsd_recalldelegation(fvp, p);
1394 	}
1395 	if (error == 0 && tvp != NULL) {
1396 		nfsrv_pnfsremovesetup(tvp, p, dsdvp, &mirrorcnt, fname, &fh);
1397 		NFSD_DEBUG(4, "nfsvno_rename: pnfsremovesetup"
1398 		    " dsdvp=%p\n", dsdvp[0]);
1399 	}
1400 out:
1401 	if (!error) {
1402 		error = VOP_RENAME(fromndp->ni_dvp, fromndp->ni_vp,
1403 		    &fromndp->ni_cnd, tondp->ni_dvp, tondp->ni_vp,
1404 		    &tondp->ni_cnd);
1405 	} else {
1406 		if (tdvp == tvp)
1407 			vrele(tdvp);
1408 		else
1409 			vput(tdvp);
1410 		if (tvp)
1411 			vput(tvp);
1412 		vrele(fromndp->ni_dvp);
1413 		vrele(fvp);
1414 		if (error == -1)
1415 			error = 0;
1416 	}
1417 
1418 	/*
1419 	 * If dsdvp[0] != NULL, it was set up by nfsrv_pnfsremovesetup() and
1420 	 * if the rename succeeded, the DS file for the tvp needs to be
1421 	 * removed.
1422 	 */
1423 	if (error == 0 && dsdvp[0] != NULL) {
1424 		nfsrv_pnfsremove(dsdvp, mirrorcnt, fname, &fh, p);
1425 		NFSD_DEBUG(4, "nfsvno_rename: pnfsremove\n");
1426 	}
1427 
1428 	vrele(tondp->ni_startdir);
1429 	nfsvno_relpathbuf(tondp);
1430 out1:
1431 	vrele(fromndp->ni_startdir);
1432 	nfsvno_relpathbuf(fromndp);
1433 	NFSEXITCODE(error);
1434 	return (error);
1435 }
1436 
1437 /*
1438  * Link vnode op.
1439  */
1440 int
1441 nfsvno_link(struct nameidata *ndp, struct vnode *vp, struct ucred *cred,
1442     struct thread *p, struct nfsexstuff *exp)
1443 {
1444 	struct vnode *xp;
1445 	int error = 0;
1446 
1447 	xp = ndp->ni_vp;
1448 	if (xp != NULL) {
1449 		error = EEXIST;
1450 	} else {
1451 		xp = ndp->ni_dvp;
1452 		if (vp->v_mount != xp->v_mount)
1453 			error = EXDEV;
1454 	}
1455 	if (!error) {
1456 		NFSVOPLOCK(vp, LK_EXCLUSIVE | LK_RETRY);
1457 		if ((vp->v_iflag & VI_DOOMED) == 0)
1458 			error = VOP_LINK(ndp->ni_dvp, vp, &ndp->ni_cnd);
1459 		else
1460 			error = EPERM;
1461 		if (ndp->ni_dvp == vp)
1462 			vrele(ndp->ni_dvp);
1463 		else
1464 			vput(ndp->ni_dvp);
1465 		NFSVOPUNLOCK(vp, 0);
1466 	} else {
1467 		if (ndp->ni_dvp == ndp->ni_vp)
1468 			vrele(ndp->ni_dvp);
1469 		else
1470 			vput(ndp->ni_dvp);
1471 		if (ndp->ni_vp)
1472 			vrele(ndp->ni_vp);
1473 	}
1474 	nfsvno_relpathbuf(ndp);
1475 	NFSEXITCODE(error);
1476 	return (error);
1477 }
1478 
1479 /*
1480  * Do the fsync() appropriate for the commit.
1481  */
1482 int
1483 nfsvno_fsync(struct vnode *vp, u_int64_t off, int cnt, struct ucred *cred,
1484     struct thread *td)
1485 {
1486 	int error = 0;
1487 
1488 	/*
1489 	 * RFC 1813 3.3.21: if count is 0, a flush from offset to the end of
1490 	 * file is done.  At this time VOP_FSYNC does not accept offset and
1491 	 * byte count parameters so call VOP_FSYNC the whole file for now.
1492 	 * The same is true for NFSv4: RFC 3530 Sec. 14.2.3.
1493 	 * File systems that do not use the buffer cache (as indicated
1494 	 * by MNTK_USES_BCACHE not being set) must use VOP_FSYNC().
1495 	 */
1496 	if (cnt == 0 || cnt > MAX_COMMIT_COUNT ||
1497 	    (vp->v_mount->mnt_kern_flag & MNTK_USES_BCACHE) == 0) {
1498 		/*
1499 		 * Give up and do the whole thing
1500 		 */
1501 		if (vp->v_object &&
1502 		   (vp->v_object->flags & OBJ_MIGHTBEDIRTY)) {
1503 			VM_OBJECT_WLOCK(vp->v_object);
1504 			vm_object_page_clean(vp->v_object, 0, 0, OBJPC_SYNC);
1505 			VM_OBJECT_WUNLOCK(vp->v_object);
1506 		}
1507 		error = VOP_FSYNC(vp, MNT_WAIT, td);
1508 	} else {
1509 		/*
1510 		 * Locate and synchronously write any buffers that fall
1511 		 * into the requested range.  Note:  we are assuming that
1512 		 * f_iosize is a power of 2.
1513 		 */
1514 		int iosize = vp->v_mount->mnt_stat.f_iosize;
1515 		int iomask = iosize - 1;
1516 		struct bufobj *bo;
1517 		daddr_t lblkno;
1518 
1519 		/*
1520 		 * Align to iosize boundary, super-align to page boundary.
1521 		 */
1522 		if (off & iomask) {
1523 			cnt += off & iomask;
1524 			off &= ~(u_quad_t)iomask;
1525 		}
1526 		if (off & PAGE_MASK) {
1527 			cnt += off & PAGE_MASK;
1528 			off &= ~(u_quad_t)PAGE_MASK;
1529 		}
1530 		lblkno = off / iosize;
1531 
1532 		if (vp->v_object &&
1533 		   (vp->v_object->flags & OBJ_MIGHTBEDIRTY)) {
1534 			VM_OBJECT_WLOCK(vp->v_object);
1535 			vm_object_page_clean(vp->v_object, off, off + cnt,
1536 			    OBJPC_SYNC);
1537 			VM_OBJECT_WUNLOCK(vp->v_object);
1538 		}
1539 
1540 		bo = &vp->v_bufobj;
1541 		BO_LOCK(bo);
1542 		while (cnt > 0) {
1543 			struct buf *bp;
1544 
1545 			/*
1546 			 * If we have a buffer and it is marked B_DELWRI we
1547 			 * have to lock and write it.  Otherwise the prior
1548 			 * write is assumed to have already been committed.
1549 			 *
1550 			 * gbincore() can return invalid buffers now so we
1551 			 * have to check that bit as well (though B_DELWRI
1552 			 * should not be set if B_INVAL is set there could be
1553 			 * a race here since we haven't locked the buffer).
1554 			 */
1555 			if ((bp = gbincore(&vp->v_bufobj, lblkno)) != NULL) {
1556 				if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_SLEEPFAIL |
1557 				    LK_INTERLOCK, BO_LOCKPTR(bo)) == ENOLCK) {
1558 					BO_LOCK(bo);
1559 					continue; /* retry */
1560 				}
1561 			    	if ((bp->b_flags & (B_DELWRI|B_INVAL)) ==
1562 				    B_DELWRI) {
1563 					bremfree(bp);
1564 					bp->b_flags &= ~B_ASYNC;
1565 					bwrite(bp);
1566 					++nfs_commit_miss;
1567 				} else
1568 					BUF_UNLOCK(bp);
1569 				BO_LOCK(bo);
1570 			}
1571 			++nfs_commit_blks;
1572 			if (cnt < iosize)
1573 				break;
1574 			cnt -= iosize;
1575 			++lblkno;
1576 		}
1577 		BO_UNLOCK(bo);
1578 	}
1579 	NFSEXITCODE(error);
1580 	return (error);
1581 }
1582 
1583 /*
1584  * Statfs vnode op.
1585  */
1586 int
1587 nfsvno_statfs(struct vnode *vp, struct statfs *sf)
1588 {
1589 	struct statfs *tsf;
1590 	int error;
1591 
1592 	tsf = NULL;
1593 	if (nfsrv_devidcnt > 0) {
1594 		/* For a pNFS service, get the DS numbers. */
1595 		tsf = malloc(sizeof(*tsf), M_TEMP, M_WAITOK | M_ZERO);
1596 		error = nfsrv_pnfsstatfs(tsf);
1597 		if (error != 0) {
1598 			free(tsf, M_TEMP);
1599 			tsf = NULL;
1600 		}
1601 	}
1602 	error = VFS_STATFS(vp->v_mount, sf);
1603 	if (error == 0) {
1604 		if (tsf != NULL) {
1605 			sf->f_blocks = tsf->f_blocks;
1606 			sf->f_bavail = tsf->f_bavail;
1607 			sf->f_bfree = tsf->f_bfree;
1608 			sf->f_bsize = tsf->f_bsize;
1609 		}
1610 		/*
1611 		 * Since NFS handles these values as unsigned on the
1612 		 * wire, there is no way to represent negative values,
1613 		 * so set them to 0. Without this, they will appear
1614 		 * to be very large positive values for clients like
1615 		 * Solaris10.
1616 		 */
1617 		if (sf->f_bavail < 0)
1618 			sf->f_bavail = 0;
1619 		if (sf->f_ffree < 0)
1620 			sf->f_ffree = 0;
1621 	}
1622 	free(tsf, M_TEMP);
1623 	NFSEXITCODE(error);
1624 	return (error);
1625 }
1626 
1627 /*
1628  * Do the vnode op stuff for Open. Similar to nfsvno_createsub(), but
1629  * must handle nfsrv_opencheck() calls after any other access checks.
1630  */
1631 void
1632 nfsvno_open(struct nfsrv_descript *nd, struct nameidata *ndp,
1633     nfsquad_t clientid, nfsv4stateid_t *stateidp, struct nfsstate *stp,
1634     int *exclusive_flagp, struct nfsvattr *nvap, int32_t *cverf, int create,
1635     NFSACL_T *aclp, nfsattrbit_t *attrbitp, struct ucred *cred, struct thread *p,
1636     struct nfsexstuff *exp, struct vnode **vpp)
1637 {
1638 	struct vnode *vp = NULL;
1639 	u_quad_t tempsize;
1640 	struct nfsexstuff nes;
1641 
1642 	if (ndp->ni_vp == NULL)
1643 		nd->nd_repstat = nfsrv_opencheck(clientid,
1644 		    stateidp, stp, NULL, nd, p, nd->nd_repstat);
1645 	if (!nd->nd_repstat) {
1646 		if (ndp->ni_vp == NULL) {
1647 			vrele(ndp->ni_startdir);
1648 			nd->nd_repstat = VOP_CREATE(ndp->ni_dvp,
1649 			    &ndp->ni_vp, &ndp->ni_cnd, &nvap->na_vattr);
1650 			/* For a pNFS server, create the data file on a DS. */
1651 			if (nd->nd_repstat == 0) {
1652 				/*
1653 				 * Create a data file on a DS for a pNFS server.
1654 				 * This function just returns if not
1655 				 * running a pNFS DS or the creation fails.
1656 				 */
1657 				nfsrv_pnfscreate(ndp->ni_vp, &nvap->na_vattr,
1658 				    cred, p);
1659 			}
1660 			vput(ndp->ni_dvp);
1661 			nfsvno_relpathbuf(ndp);
1662 			if (!nd->nd_repstat) {
1663 				if (*exclusive_flagp) {
1664 					*exclusive_flagp = 0;
1665 					NFSVNO_ATTRINIT(nvap);
1666 					nvap->na_atime.tv_sec = cverf[0];
1667 					nvap->na_atime.tv_nsec = cverf[1];
1668 					nd->nd_repstat = VOP_SETATTR(ndp->ni_vp,
1669 					    &nvap->na_vattr, cred);
1670 					if (nd->nd_repstat != 0) {
1671 						vput(ndp->ni_vp);
1672 						ndp->ni_vp = NULL;
1673 						nd->nd_repstat = NFSERR_NOTSUPP;
1674 					} else
1675 						NFSSETBIT_ATTRBIT(attrbitp,
1676 						    NFSATTRBIT_TIMEACCESS);
1677 				} else {
1678 					nfsrv_fixattr(nd, ndp->ni_vp, nvap,
1679 					    aclp, p, attrbitp, exp);
1680 				}
1681 			}
1682 			vp = ndp->ni_vp;
1683 		} else {
1684 			if (ndp->ni_startdir)
1685 				vrele(ndp->ni_startdir);
1686 			nfsvno_relpathbuf(ndp);
1687 			vp = ndp->ni_vp;
1688 			if (create == NFSV4OPEN_CREATE) {
1689 				if (ndp->ni_dvp == vp)
1690 					vrele(ndp->ni_dvp);
1691 				else
1692 					vput(ndp->ni_dvp);
1693 			}
1694 			if (NFSVNO_ISSETSIZE(nvap) && vp->v_type == VREG) {
1695 				if (ndp->ni_cnd.cn_flags & RDONLY)
1696 					NFSVNO_SETEXRDONLY(&nes);
1697 				else
1698 					NFSVNO_EXINIT(&nes);
1699 				nd->nd_repstat = nfsvno_accchk(vp,
1700 				    VWRITE, cred, &nes, p,
1701 				    NFSACCCHK_NOOVERRIDE,
1702 				    NFSACCCHK_VPISLOCKED, NULL);
1703 				nd->nd_repstat = nfsrv_opencheck(clientid,
1704 				    stateidp, stp, vp, nd, p, nd->nd_repstat);
1705 				if (!nd->nd_repstat) {
1706 					tempsize = nvap->na_size;
1707 					NFSVNO_ATTRINIT(nvap);
1708 					nvap->na_size = tempsize;
1709 					nd->nd_repstat = VOP_SETATTR(vp,
1710 					    &nvap->na_vattr, cred);
1711 				}
1712 			} else if (vp->v_type == VREG) {
1713 				nd->nd_repstat = nfsrv_opencheck(clientid,
1714 				    stateidp, stp, vp, nd, p, nd->nd_repstat);
1715 			}
1716 		}
1717 	} else {
1718 		if (ndp->ni_cnd.cn_flags & HASBUF)
1719 			nfsvno_relpathbuf(ndp);
1720 		if (ndp->ni_startdir && create == NFSV4OPEN_CREATE) {
1721 			vrele(ndp->ni_startdir);
1722 			if (ndp->ni_dvp == ndp->ni_vp)
1723 				vrele(ndp->ni_dvp);
1724 			else
1725 				vput(ndp->ni_dvp);
1726 			if (ndp->ni_vp)
1727 				vput(ndp->ni_vp);
1728 		}
1729 	}
1730 	*vpp = vp;
1731 
1732 	NFSEXITCODE2(0, nd);
1733 }
1734 
1735 /*
1736  * Updates the file rev and sets the mtime and ctime
1737  * to the current clock time, returning the va_filerev and va_Xtime
1738  * values.
1739  * Return ESTALE to indicate the vnode is VI_DOOMED.
1740  */
1741 int
1742 nfsvno_updfilerev(struct vnode *vp, struct nfsvattr *nvap,
1743     struct nfsrv_descript *nd, struct thread *p)
1744 {
1745 	struct vattr va;
1746 
1747 	VATTR_NULL(&va);
1748 	vfs_timestamp(&va.va_mtime);
1749 	if (NFSVOPISLOCKED(vp) != LK_EXCLUSIVE) {
1750 		NFSVOPLOCK(vp, LK_UPGRADE | LK_RETRY);
1751 		if ((vp->v_iflag & VI_DOOMED) != 0)
1752 			return (ESTALE);
1753 	}
1754 	(void) VOP_SETATTR(vp, &va, nd->nd_cred);
1755 	(void) nfsvno_getattr(vp, nvap, nd, p, 1, NULL);
1756 	return (0);
1757 }
1758 
1759 /*
1760  * Glue routine to nfsv4_fillattr().
1761  */
1762 int
1763 nfsvno_fillattr(struct nfsrv_descript *nd, struct mount *mp, struct vnode *vp,
1764     struct nfsvattr *nvap, fhandle_t *fhp, int rderror, nfsattrbit_t *attrbitp,
1765     struct ucred *cred, struct thread *p, int isdgram, int reterr,
1766     int supports_nfsv4acls, int at_root, uint64_t mounted_on_fileno)
1767 {
1768 	struct statfs *sf;
1769 	int error;
1770 
1771 	sf = NULL;
1772 	if (nfsrv_devidcnt > 0 &&
1773 	    (NFSISSET_ATTRBIT(attrbitp, NFSATTRBIT_SPACEAVAIL) ||
1774 	     NFSISSET_ATTRBIT(attrbitp, NFSATTRBIT_SPACEFREE) ||
1775 	     NFSISSET_ATTRBIT(attrbitp, NFSATTRBIT_SPACETOTAL))) {
1776 		sf = malloc(sizeof(*sf), M_TEMP, M_WAITOK | M_ZERO);
1777 		error = nfsrv_pnfsstatfs(sf);
1778 		if (error != 0) {
1779 			free(sf, M_TEMP);
1780 			sf = NULL;
1781 		}
1782 	}
1783 	error = nfsv4_fillattr(nd, mp, vp, NULL, &nvap->na_vattr, fhp, rderror,
1784 	    attrbitp, cred, p, isdgram, reterr, supports_nfsv4acls, at_root,
1785 	    mounted_on_fileno, sf);
1786 	free(sf, M_TEMP);
1787 	NFSEXITCODE2(0, nd);
1788 	return (error);
1789 }
1790 
1791 /* Since the Readdir vnode ops vary, put the entire functions in here. */
1792 /*
1793  * nfs readdir service
1794  * - mallocs what it thinks is enough to read
1795  *	count rounded up to a multiple of DIRBLKSIZ <= NFS_MAXREADDIR
1796  * - calls VOP_READDIR()
1797  * - loops around building the reply
1798  *	if the output generated exceeds count break out of loop
1799  *	The NFSM_CLGET macro is used here so that the reply will be packed
1800  *	tightly in mbuf clusters.
1801  * - it trims out records with d_fileno == 0
1802  *	this doesn't matter for Unix clients, but they might confuse clients
1803  *	for other os'.
1804  * - it trims out records with d_type == DT_WHT
1805  *	these cannot be seen through NFS (unless we extend the protocol)
1806  *     The alternate call nfsrvd_readdirplus() does lookups as well.
1807  * PS: The NFS protocol spec. does not clarify what the "count" byte
1808  *	argument is a count of.. just name strings and file id's or the
1809  *	entire reply rpc or ...
1810  *	I tried just file name and id sizes and it confused the Sun client,
1811  *	so I am using the full rpc size now. The "paranoia.." comment refers
1812  *	to including the status longwords that are not a part of the dir.
1813  *	"entry" structures, but are in the rpc.
1814  */
1815 int
1816 nfsrvd_readdir(struct nfsrv_descript *nd, int isdgram,
1817     struct vnode *vp, struct thread *p, struct nfsexstuff *exp)
1818 {
1819 	struct dirent *dp;
1820 	u_int32_t *tl;
1821 	int dirlen;
1822 	char *cpos, *cend, *rbuf;
1823 	struct nfsvattr at;
1824 	int nlen, error = 0, getret = 1;
1825 	int siz, cnt, fullsiz, eofflag, ncookies;
1826 	u_int64_t off, toff, verf __unused;
1827 	u_long *cookies = NULL, *cookiep;
1828 	struct uio io;
1829 	struct iovec iv;
1830 	int is_ufs;
1831 
1832 	if (nd->nd_repstat) {
1833 		nfsrv_postopattr(nd, getret, &at);
1834 		goto out;
1835 	}
1836 	if (nd->nd_flag & ND_NFSV2) {
1837 		NFSM_DISSECT(tl, u_int32_t *, 2 * NFSX_UNSIGNED);
1838 		off = fxdr_unsigned(u_quad_t, *tl++);
1839 	} else {
1840 		NFSM_DISSECT(tl, u_int32_t *, 5 * NFSX_UNSIGNED);
1841 		off = fxdr_hyper(tl);
1842 		tl += 2;
1843 		verf = fxdr_hyper(tl);
1844 		tl += 2;
1845 	}
1846 	toff = off;
1847 	cnt = fxdr_unsigned(int, *tl);
1848 	if (cnt > NFS_SRVMAXDATA(nd) || cnt < 0)
1849 		cnt = NFS_SRVMAXDATA(nd);
1850 	siz = ((cnt + DIRBLKSIZ - 1) & ~(DIRBLKSIZ - 1));
1851 	fullsiz = siz;
1852 	if (nd->nd_flag & ND_NFSV3) {
1853 		nd->nd_repstat = getret = nfsvno_getattr(vp, &at, nd, p, 1,
1854 		    NULL);
1855 #if 0
1856 		/*
1857 		 * va_filerev is not sufficient as a cookie verifier,
1858 		 * since it is not supposed to change when entries are
1859 		 * removed/added unless that offset cookies returned to
1860 		 * the client are no longer valid.
1861 		 */
1862 		if (!nd->nd_repstat && toff && verf != at.na_filerev)
1863 			nd->nd_repstat = NFSERR_BAD_COOKIE;
1864 #endif
1865 	}
1866 	if (!nd->nd_repstat && vp->v_type != VDIR)
1867 		nd->nd_repstat = NFSERR_NOTDIR;
1868 	if (nd->nd_repstat == 0 && cnt == 0) {
1869 		if (nd->nd_flag & ND_NFSV2)
1870 			/* NFSv2 does not have NFSERR_TOOSMALL */
1871 			nd->nd_repstat = EPERM;
1872 		else
1873 			nd->nd_repstat = NFSERR_TOOSMALL;
1874 	}
1875 	if (!nd->nd_repstat)
1876 		nd->nd_repstat = nfsvno_accchk(vp, VEXEC,
1877 		    nd->nd_cred, exp, p, NFSACCCHK_NOOVERRIDE,
1878 		    NFSACCCHK_VPISLOCKED, NULL);
1879 	if (nd->nd_repstat) {
1880 		vput(vp);
1881 		if (nd->nd_flag & ND_NFSV3)
1882 			nfsrv_postopattr(nd, getret, &at);
1883 		goto out;
1884 	}
1885 	is_ufs = strcmp(vp->v_mount->mnt_vfc->vfc_name, "ufs") == 0;
1886 	rbuf = malloc(siz, M_TEMP, M_WAITOK);
1887 again:
1888 	eofflag = 0;
1889 	if (cookies) {
1890 		free(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 	if (!cookies && !nd->nd_repstat)
1910 		nd->nd_repstat = NFSERR_PERM;
1911 	if (nd->nd_flag & ND_NFSV3) {
1912 		getret = nfsvno_getattr(vp, &at, nd, p, 1, NULL);
1913 		if (!nd->nd_repstat)
1914 			nd->nd_repstat = getret;
1915 	}
1916 
1917 	/*
1918 	 * Handles the failed cases. nd->nd_repstat == 0 past here.
1919 	 */
1920 	if (nd->nd_repstat) {
1921 		vput(vp);
1922 		free(rbuf, M_TEMP);
1923 		if (cookies)
1924 			free(cookies, M_TEMP);
1925 		if (nd->nd_flag & ND_NFSV3)
1926 			nfsrv_postopattr(nd, getret, &at);
1927 		goto out;
1928 	}
1929 	/*
1930 	 * If nothing read, return eof
1931 	 * rpc reply
1932 	 */
1933 	if (siz == 0) {
1934 		vput(vp);
1935 		if (nd->nd_flag & ND_NFSV2) {
1936 			NFSM_BUILD(tl, u_int32_t *, 2 * NFSX_UNSIGNED);
1937 		} else {
1938 			nfsrv_postopattr(nd, getret, &at);
1939 			NFSM_BUILD(tl, u_int32_t *, 4 * NFSX_UNSIGNED);
1940 			txdr_hyper(at.na_filerev, tl);
1941 			tl += 2;
1942 		}
1943 		*tl++ = newnfs_false;
1944 		*tl = newnfs_true;
1945 		free(rbuf, M_TEMP);
1946 		free(cookies, M_TEMP);
1947 		goto out;
1948 	}
1949 
1950 	/*
1951 	 * Check for degenerate cases of nothing useful read.
1952 	 * If so go try again
1953 	 */
1954 	cpos = rbuf;
1955 	cend = rbuf + siz;
1956 	dp = (struct dirent *)cpos;
1957 	cookiep = cookies;
1958 
1959 	/*
1960 	 * For some reason FreeBSD's ufs_readdir() chooses to back the
1961 	 * directory offset up to a block boundary, so it is necessary to
1962 	 * skip over the records that precede the requested offset. This
1963 	 * requires the assumption that file offset cookies monotonically
1964 	 * increase.
1965 	 */
1966 	while (cpos < cend && ncookies > 0 &&
1967 	    (dp->d_fileno == 0 || dp->d_type == DT_WHT ||
1968 	     (is_ufs == 1 && ((u_quad_t)(*cookiep)) <= toff))) {
1969 		cpos += dp->d_reclen;
1970 		dp = (struct dirent *)cpos;
1971 		cookiep++;
1972 		ncookies--;
1973 	}
1974 	if (cpos >= cend || ncookies == 0) {
1975 		siz = fullsiz;
1976 		toff = off;
1977 		goto again;
1978 	}
1979 	vput(vp);
1980 
1981 	/*
1982 	 * dirlen is the size of the reply, including all XDR and must
1983 	 * not exceed cnt. For NFSv2, RFC1094 didn't clearly indicate
1984 	 * if the XDR should be included in "count", but to be safe, we do.
1985 	 * (Include the two booleans at the end of the reply in dirlen now.)
1986 	 */
1987 	if (nd->nd_flag & ND_NFSV3) {
1988 		nfsrv_postopattr(nd, getret, &at);
1989 		NFSM_BUILD(tl, u_int32_t *, 2 * NFSX_UNSIGNED);
1990 		txdr_hyper(at.na_filerev, tl);
1991 		dirlen = NFSX_V3POSTOPATTR + NFSX_VERF + 2 * NFSX_UNSIGNED;
1992 	} else {
1993 		dirlen = 2 * NFSX_UNSIGNED;
1994 	}
1995 
1996 	/* Loop through the records and build reply */
1997 	while (cpos < cend && ncookies > 0) {
1998 		nlen = dp->d_namlen;
1999 		if (dp->d_fileno != 0 && dp->d_type != DT_WHT &&
2000 			nlen <= NFS_MAXNAMLEN) {
2001 			if (nd->nd_flag & ND_NFSV3)
2002 				dirlen += (6*NFSX_UNSIGNED + NFSM_RNDUP(nlen));
2003 			else
2004 				dirlen += (4*NFSX_UNSIGNED + NFSM_RNDUP(nlen));
2005 			if (dirlen > cnt) {
2006 				eofflag = 0;
2007 				break;
2008 			}
2009 
2010 			/*
2011 			 * Build the directory record xdr from
2012 			 * the dirent entry.
2013 			 */
2014 			if (nd->nd_flag & ND_NFSV3) {
2015 				NFSM_BUILD(tl, u_int32_t *, 3 * NFSX_UNSIGNED);
2016 				*tl++ = newnfs_true;
2017 				*tl++ = 0;
2018 			} else {
2019 				NFSM_BUILD(tl, u_int32_t *, 2 * NFSX_UNSIGNED);
2020 				*tl++ = newnfs_true;
2021 			}
2022 			*tl = txdr_unsigned(dp->d_fileno);
2023 			(void) nfsm_strtom(nd, dp->d_name, nlen);
2024 			if (nd->nd_flag & ND_NFSV3) {
2025 				NFSM_BUILD(tl, u_int32_t *, 2 * NFSX_UNSIGNED);
2026 				*tl++ = 0;
2027 			} else
2028 				NFSM_BUILD(tl, u_int32_t *, NFSX_UNSIGNED);
2029 			*tl = txdr_unsigned(*cookiep);
2030 		}
2031 		cpos += dp->d_reclen;
2032 		dp = (struct dirent *)cpos;
2033 		cookiep++;
2034 		ncookies--;
2035 	}
2036 	if (cpos < cend)
2037 		eofflag = 0;
2038 	NFSM_BUILD(tl, u_int32_t *, 2 * NFSX_UNSIGNED);
2039 	*tl++ = newnfs_false;
2040 	if (eofflag)
2041 		*tl = newnfs_true;
2042 	else
2043 		*tl = newnfs_false;
2044 	free(rbuf, M_TEMP);
2045 	free(cookies, M_TEMP);
2046 
2047 out:
2048 	NFSEXITCODE2(0, nd);
2049 	return (0);
2050 nfsmout:
2051 	vput(vp);
2052 	NFSEXITCODE2(error, nd);
2053 	return (error);
2054 }
2055 
2056 /*
2057  * Readdirplus for V3 and Readdir for V4.
2058  */
2059 int
2060 nfsrvd_readdirplus(struct nfsrv_descript *nd, int isdgram,
2061     struct vnode *vp, struct thread *p, struct nfsexstuff *exp)
2062 {
2063 	struct dirent *dp;
2064 	u_int32_t *tl;
2065 	int dirlen;
2066 	char *cpos, *cend, *rbuf;
2067 	struct vnode *nvp;
2068 	fhandle_t nfh;
2069 	struct nfsvattr nva, at, *nvap = &nva;
2070 	struct mbuf *mb0, *mb1;
2071 	struct nfsreferral *refp;
2072 	int nlen, r, error = 0, getret = 1, usevget = 1;
2073 	int siz, cnt, fullsiz, eofflag, ncookies, entrycnt;
2074 	caddr_t bpos0, bpos1;
2075 	u_int64_t off, toff, verf;
2076 	u_long *cookies = NULL, *cookiep;
2077 	nfsattrbit_t attrbits, rderrbits, savbits;
2078 	struct uio io;
2079 	struct iovec iv;
2080 	struct componentname cn;
2081 	int at_root, is_ufs, is_zfs, needs_unbusy, supports_nfsv4acls;
2082 	struct mount *mp, *new_mp;
2083 	uint64_t mounted_on_fileno;
2084 
2085 	if (nd->nd_repstat) {
2086 		nfsrv_postopattr(nd, getret, &at);
2087 		goto out;
2088 	}
2089 	NFSM_DISSECT(tl, u_int32_t *, 6 * NFSX_UNSIGNED);
2090 	off = fxdr_hyper(tl);
2091 	toff = off;
2092 	tl += 2;
2093 	verf = fxdr_hyper(tl);
2094 	tl += 2;
2095 	siz = fxdr_unsigned(int, *tl++);
2096 	cnt = fxdr_unsigned(int, *tl);
2097 
2098 	/*
2099 	 * Use the server's maximum data transfer size as the upper bound
2100 	 * on reply datalen.
2101 	 */
2102 	if (cnt > NFS_SRVMAXDATA(nd) || cnt < 0)
2103 		cnt = NFS_SRVMAXDATA(nd);
2104 
2105 	/*
2106 	 * siz is a "hint" of how much directory information (name, fileid,
2107 	 * cookie) should be in the reply. At least one client "hints" 0,
2108 	 * so I set it to cnt for that case. I also round it up to the
2109 	 * next multiple of DIRBLKSIZ.
2110 	 */
2111 	if (siz <= 0)
2112 		siz = cnt;
2113 	siz = ((siz + DIRBLKSIZ - 1) & ~(DIRBLKSIZ - 1));
2114 
2115 	if (nd->nd_flag & ND_NFSV4) {
2116 		error = nfsrv_getattrbits(nd, &attrbits, NULL, NULL);
2117 		if (error)
2118 			goto nfsmout;
2119 		NFSSET_ATTRBIT(&savbits, &attrbits);
2120 		NFSCLRNOTFILLABLE_ATTRBIT(&attrbits);
2121 		NFSZERO_ATTRBIT(&rderrbits);
2122 		NFSSETBIT_ATTRBIT(&rderrbits, NFSATTRBIT_RDATTRERROR);
2123 	} else {
2124 		NFSZERO_ATTRBIT(&attrbits);
2125 	}
2126 	fullsiz = siz;
2127 	nd->nd_repstat = getret = nfsvno_getattr(vp, &at, nd, p, 1, NULL);
2128 #if 0
2129 	if (!nd->nd_repstat) {
2130 	    if (off && verf != at.na_filerev) {
2131 		/*
2132 		 * va_filerev is not sufficient as a cookie verifier,
2133 		 * since it is not supposed to change when entries are
2134 		 * removed/added unless that offset cookies returned to
2135 		 * the client are no longer valid.
2136 		 */
2137 		if (nd->nd_flag & ND_NFSV4) {
2138 			nd->nd_repstat = NFSERR_NOTSAME;
2139 		} else {
2140 			nd->nd_repstat = NFSERR_BAD_COOKIE;
2141 		}
2142 	    }
2143 	}
2144 #endif
2145 	if (!nd->nd_repstat && vp->v_type != VDIR)
2146 		nd->nd_repstat = NFSERR_NOTDIR;
2147 	if (!nd->nd_repstat && cnt == 0)
2148 		nd->nd_repstat = NFSERR_TOOSMALL;
2149 	if (!nd->nd_repstat)
2150 		nd->nd_repstat = nfsvno_accchk(vp, VEXEC,
2151 		    nd->nd_cred, exp, p, NFSACCCHK_NOOVERRIDE,
2152 		    NFSACCCHK_VPISLOCKED, NULL);
2153 	if (nd->nd_repstat) {
2154 		vput(vp);
2155 		if (nd->nd_flag & ND_NFSV3)
2156 			nfsrv_postopattr(nd, getret, &at);
2157 		goto out;
2158 	}
2159 	is_ufs = strcmp(vp->v_mount->mnt_vfc->vfc_name, "ufs") == 0;
2160 	is_zfs = strcmp(vp->v_mount->mnt_vfc->vfc_name, "zfs") == 0;
2161 
2162 	rbuf = malloc(siz, M_TEMP, M_WAITOK);
2163 again:
2164 	eofflag = 0;
2165 	if (cookies) {
2166 		free(cookies, M_TEMP);
2167 		cookies = NULL;
2168 	}
2169 
2170 	iv.iov_base = rbuf;
2171 	iv.iov_len = siz;
2172 	io.uio_iov = &iv;
2173 	io.uio_iovcnt = 1;
2174 	io.uio_offset = (off_t)off;
2175 	io.uio_resid = siz;
2176 	io.uio_segflg = UIO_SYSSPACE;
2177 	io.uio_rw = UIO_READ;
2178 	io.uio_td = NULL;
2179 	nd->nd_repstat = VOP_READDIR(vp, &io, nd->nd_cred, &eofflag, &ncookies,
2180 	    &cookies);
2181 	off = (u_int64_t)io.uio_offset;
2182 	if (io.uio_resid)
2183 		siz -= io.uio_resid;
2184 
2185 	getret = nfsvno_getattr(vp, &at, nd, p, 1, NULL);
2186 
2187 	if (!cookies && !nd->nd_repstat)
2188 		nd->nd_repstat = NFSERR_PERM;
2189 	if (!nd->nd_repstat)
2190 		nd->nd_repstat = getret;
2191 	if (nd->nd_repstat) {
2192 		vput(vp);
2193 		if (cookies)
2194 			free(cookies, M_TEMP);
2195 		free(rbuf, M_TEMP);
2196 		if (nd->nd_flag & ND_NFSV3)
2197 			nfsrv_postopattr(nd, getret, &at);
2198 		goto out;
2199 	}
2200 	/*
2201 	 * If nothing read, return eof
2202 	 * rpc reply
2203 	 */
2204 	if (siz == 0) {
2205 		vput(vp);
2206 		if (nd->nd_flag & ND_NFSV3)
2207 			nfsrv_postopattr(nd, getret, &at);
2208 		NFSM_BUILD(tl, u_int32_t *, 4 * NFSX_UNSIGNED);
2209 		txdr_hyper(at.na_filerev, tl);
2210 		tl += 2;
2211 		*tl++ = newnfs_false;
2212 		*tl = newnfs_true;
2213 		free(cookies, M_TEMP);
2214 		free(rbuf, M_TEMP);
2215 		goto out;
2216 	}
2217 
2218 	/*
2219 	 * Check for degenerate cases of nothing useful read.
2220 	 * If so go try again
2221 	 */
2222 	cpos = rbuf;
2223 	cend = rbuf + siz;
2224 	dp = (struct dirent *)cpos;
2225 	cookiep = cookies;
2226 
2227 	/*
2228 	 * For some reason FreeBSD's ufs_readdir() chooses to back the
2229 	 * directory offset up to a block boundary, so it is necessary to
2230 	 * skip over the records that precede the requested offset. This
2231 	 * requires the assumption that file offset cookies monotonically
2232 	 * increase.
2233 	 */
2234 	while (cpos < cend && ncookies > 0 &&
2235 	  (dp->d_fileno == 0 || dp->d_type == DT_WHT ||
2236 	   (is_ufs == 1 && ((u_quad_t)(*cookiep)) <= toff) ||
2237 	   ((nd->nd_flag & ND_NFSV4) &&
2238 	    ((dp->d_namlen == 1 && dp->d_name[0] == '.') ||
2239 	     (dp->d_namlen==2 && dp->d_name[0]=='.' && dp->d_name[1]=='.'))))) {
2240 		cpos += dp->d_reclen;
2241 		dp = (struct dirent *)cpos;
2242 		cookiep++;
2243 		ncookies--;
2244 	}
2245 	if (cpos >= cend || ncookies == 0) {
2246 		siz = fullsiz;
2247 		toff = off;
2248 		goto again;
2249 	}
2250 
2251 	/*
2252 	 * Busy the file system so that the mount point won't go away
2253 	 * and, as such, VFS_VGET() can be used safely.
2254 	 */
2255 	mp = vp->v_mount;
2256 	vfs_ref(mp);
2257 	NFSVOPUNLOCK(vp, 0);
2258 	nd->nd_repstat = vfs_busy(mp, 0);
2259 	vfs_rel(mp);
2260 	if (nd->nd_repstat != 0) {
2261 		vrele(vp);
2262 		free(cookies, M_TEMP);
2263 		free(rbuf, M_TEMP);
2264 		if (nd->nd_flag & ND_NFSV3)
2265 			nfsrv_postopattr(nd, getret, &at);
2266 		goto out;
2267 	}
2268 
2269 	/*
2270 	 * Check to see if entries in this directory can be safely acquired
2271 	 * via VFS_VGET() or if a switch to VOP_LOOKUP() is required.
2272 	 * ZFS snapshot directories need VOP_LOOKUP(), so that any
2273 	 * automount of the snapshot directory that is required will
2274 	 * be done.
2275 	 * This needs to be done here for NFSv4, since NFSv4 never does
2276 	 * a VFS_VGET() for "." or "..".
2277 	 */
2278 	if (is_zfs == 1) {
2279 		r = VFS_VGET(mp, at.na_fileid, LK_SHARED, &nvp);
2280 		if (r == EOPNOTSUPP) {
2281 			usevget = 0;
2282 			cn.cn_nameiop = LOOKUP;
2283 			cn.cn_lkflags = LK_SHARED | LK_RETRY;
2284 			cn.cn_cred = nd->nd_cred;
2285 			cn.cn_thread = p;
2286 		} else if (r == 0)
2287 			vput(nvp);
2288 	}
2289 
2290 	/*
2291 	 * Save this position, in case there is an error before one entry
2292 	 * is created.
2293 	 */
2294 	mb0 = nd->nd_mb;
2295 	bpos0 = nd->nd_bpos;
2296 
2297 	/*
2298 	 * Fill in the first part of the reply.
2299 	 * dirlen is the reply length in bytes and cannot exceed cnt.
2300 	 * (Include the two booleans at the end of the reply in dirlen now,
2301 	 *  so we recognize when we have exceeded cnt.)
2302 	 */
2303 	if (nd->nd_flag & ND_NFSV3) {
2304 		dirlen = NFSX_V3POSTOPATTR + NFSX_VERF + 2 * NFSX_UNSIGNED;
2305 		nfsrv_postopattr(nd, getret, &at);
2306 	} else {
2307 		dirlen = NFSX_VERF + 2 * NFSX_UNSIGNED;
2308 	}
2309 	NFSM_BUILD(tl, u_int32_t *, NFSX_VERF);
2310 	txdr_hyper(at.na_filerev, tl);
2311 
2312 	/*
2313 	 * Save this position, in case there is an empty reply needed.
2314 	 */
2315 	mb1 = nd->nd_mb;
2316 	bpos1 = nd->nd_bpos;
2317 
2318 	/* Loop through the records and build reply */
2319 	entrycnt = 0;
2320 	while (cpos < cend && ncookies > 0 && dirlen < cnt) {
2321 		nlen = dp->d_namlen;
2322 		if (dp->d_fileno != 0 && dp->d_type != DT_WHT &&
2323 		    nlen <= NFS_MAXNAMLEN &&
2324 		    ((nd->nd_flag & ND_NFSV3) || nlen > 2 ||
2325 		     (nlen==2 && (dp->d_name[0]!='.' || dp->d_name[1]!='.'))
2326 		      || (nlen == 1 && dp->d_name[0] != '.'))) {
2327 			/*
2328 			 * Save the current position in the reply, in case
2329 			 * this entry exceeds cnt.
2330 			 */
2331 			mb1 = nd->nd_mb;
2332 			bpos1 = nd->nd_bpos;
2333 
2334 			/*
2335 			 * For readdir_and_lookup get the vnode using
2336 			 * the file number.
2337 			 */
2338 			nvp = NULL;
2339 			refp = NULL;
2340 			r = 0;
2341 			at_root = 0;
2342 			needs_unbusy = 0;
2343 			new_mp = mp;
2344 			mounted_on_fileno = (uint64_t)dp->d_fileno;
2345 			if ((nd->nd_flag & ND_NFSV3) ||
2346 			    NFSNONZERO_ATTRBIT(&savbits)) {
2347 				if (nd->nd_flag & ND_NFSV4)
2348 					refp = nfsv4root_getreferral(NULL,
2349 					    vp, dp->d_fileno);
2350 				if (refp == NULL) {
2351 					if (usevget)
2352 						r = VFS_VGET(mp, dp->d_fileno,
2353 						    LK_SHARED, &nvp);
2354 					else
2355 						r = EOPNOTSUPP;
2356 					if (r == EOPNOTSUPP) {
2357 						if (usevget) {
2358 							usevget = 0;
2359 							cn.cn_nameiop = LOOKUP;
2360 							cn.cn_lkflags =
2361 							    LK_SHARED |
2362 							    LK_RETRY;
2363 							cn.cn_cred =
2364 							    nd->nd_cred;
2365 							cn.cn_thread = p;
2366 						}
2367 						cn.cn_nameptr = dp->d_name;
2368 						cn.cn_namelen = nlen;
2369 						cn.cn_flags = ISLASTCN |
2370 						    NOFOLLOW | LOCKLEAF;
2371 						if (nlen == 2 &&
2372 						    dp->d_name[0] == '.' &&
2373 						    dp->d_name[1] == '.')
2374 							cn.cn_flags |=
2375 							    ISDOTDOT;
2376 						if (NFSVOPLOCK(vp, LK_SHARED)
2377 						    != 0) {
2378 							nd->nd_repstat = EPERM;
2379 							break;
2380 						}
2381 						if ((vp->v_vflag & VV_ROOT) != 0
2382 						    && (cn.cn_flags & ISDOTDOT)
2383 						    != 0) {
2384 							vref(vp);
2385 							nvp = vp;
2386 							r = 0;
2387 						} else {
2388 							r = VOP_LOOKUP(vp, &nvp,
2389 							    &cn);
2390 							if (vp != nvp)
2391 								NFSVOPUNLOCK(vp,
2392 								    0);
2393 						}
2394 					}
2395 
2396 					/*
2397 					 * For NFSv4, check to see if nvp is
2398 					 * a mount point and get the mount
2399 					 * point vnode, as required.
2400 					 */
2401 					if (r == 0 &&
2402 					    nfsrv_enable_crossmntpt != 0 &&
2403 					    (nd->nd_flag & ND_NFSV4) != 0 &&
2404 					    nvp->v_type == VDIR &&
2405 					    nvp->v_mountedhere != NULL) {
2406 						new_mp = nvp->v_mountedhere;
2407 						r = vfs_busy(new_mp, 0);
2408 						vput(nvp);
2409 						nvp = NULL;
2410 						if (r == 0) {
2411 							r = VFS_ROOT(new_mp,
2412 							    LK_SHARED, &nvp);
2413 							needs_unbusy = 1;
2414 							if (r == 0)
2415 								at_root = 1;
2416 						}
2417 					}
2418 				}
2419 				if (!r) {
2420 				    if (refp == NULL &&
2421 					((nd->nd_flag & ND_NFSV3) ||
2422 					 NFSNONZERO_ATTRBIT(&attrbits))) {
2423 					r = nfsvno_getfh(nvp, &nfh, p);
2424 					if (!r)
2425 					    r = nfsvno_getattr(nvp, nvap, nd, p,
2426 						1, &attrbits);
2427 					if (r == 0 && is_zfs == 1 &&
2428 					    nfsrv_enable_crossmntpt != 0 &&
2429 					    (nd->nd_flag & ND_NFSV4) != 0 &&
2430 					    nvp->v_type == VDIR &&
2431 					    vp->v_mount != nvp->v_mount) {
2432 					    /*
2433 					     * For a ZFS snapshot, there is a
2434 					     * pseudo mount that does not set
2435 					     * v_mountedhere, so it needs to
2436 					     * be detected via a different
2437 					     * mount structure.
2438 					     */
2439 					    at_root = 1;
2440 					    if (new_mp == mp)
2441 						new_mp = nvp->v_mount;
2442 					}
2443 				    }
2444 				} else {
2445 				    nvp = NULL;
2446 				}
2447 				if (r) {
2448 					if (!NFSISSET_ATTRBIT(&attrbits,
2449 					    NFSATTRBIT_RDATTRERROR)) {
2450 						if (nvp != NULL)
2451 							vput(nvp);
2452 						if (needs_unbusy != 0)
2453 							vfs_unbusy(new_mp);
2454 						nd->nd_repstat = r;
2455 						break;
2456 					}
2457 				}
2458 			}
2459 
2460 			/*
2461 			 * Build the directory record xdr
2462 			 */
2463 			if (nd->nd_flag & ND_NFSV3) {
2464 				NFSM_BUILD(tl, u_int32_t *, 3 * NFSX_UNSIGNED);
2465 				*tl++ = newnfs_true;
2466 				*tl++ = 0;
2467 				*tl = txdr_unsigned(dp->d_fileno);
2468 				dirlen += nfsm_strtom(nd, dp->d_name, nlen);
2469 				NFSM_BUILD(tl, u_int32_t *, 2 * NFSX_UNSIGNED);
2470 				*tl++ = 0;
2471 				*tl = txdr_unsigned(*cookiep);
2472 				nfsrv_postopattr(nd, 0, nvap);
2473 				dirlen += nfsm_fhtom(nd,(u_int8_t *)&nfh,0,1);
2474 				dirlen += (5*NFSX_UNSIGNED+NFSX_V3POSTOPATTR);
2475 				if (nvp != NULL)
2476 					vput(nvp);
2477 			} else {
2478 				NFSM_BUILD(tl, u_int32_t *, 3 * NFSX_UNSIGNED);
2479 				*tl++ = newnfs_true;
2480 				*tl++ = 0;
2481 				*tl = txdr_unsigned(*cookiep);
2482 				dirlen += nfsm_strtom(nd, dp->d_name, nlen);
2483 				if (nvp != NULL) {
2484 					supports_nfsv4acls =
2485 					    nfs_supportsnfsv4acls(nvp);
2486 					NFSVOPUNLOCK(nvp, 0);
2487 				} else
2488 					supports_nfsv4acls = 0;
2489 				if (refp != NULL) {
2490 					dirlen += nfsrv_putreferralattr(nd,
2491 					    &savbits, refp, 0,
2492 					    &nd->nd_repstat);
2493 					if (nd->nd_repstat) {
2494 						if (nvp != NULL)
2495 							vrele(nvp);
2496 						if (needs_unbusy != 0)
2497 							vfs_unbusy(new_mp);
2498 						break;
2499 					}
2500 				} else if (r) {
2501 					dirlen += nfsvno_fillattr(nd, new_mp,
2502 					    nvp, nvap, &nfh, r, &rderrbits,
2503 					    nd->nd_cred, p, isdgram, 0,
2504 					    supports_nfsv4acls, at_root,
2505 					    mounted_on_fileno);
2506 				} else {
2507 					dirlen += nfsvno_fillattr(nd, new_mp,
2508 					    nvp, nvap, &nfh, r, &attrbits,
2509 					    nd->nd_cred, p, isdgram, 0,
2510 					    supports_nfsv4acls, at_root,
2511 					    mounted_on_fileno);
2512 				}
2513 				if (nvp != NULL)
2514 					vrele(nvp);
2515 				dirlen += (3 * NFSX_UNSIGNED);
2516 			}
2517 			if (needs_unbusy != 0)
2518 				vfs_unbusy(new_mp);
2519 			if (dirlen <= cnt)
2520 				entrycnt++;
2521 		}
2522 		cpos += dp->d_reclen;
2523 		dp = (struct dirent *)cpos;
2524 		cookiep++;
2525 		ncookies--;
2526 	}
2527 	vrele(vp);
2528 	vfs_unbusy(mp);
2529 
2530 	/*
2531 	 * If dirlen > cnt, we must strip off the last entry. If that
2532 	 * results in an empty reply, report NFSERR_TOOSMALL.
2533 	 */
2534 	if (dirlen > cnt || nd->nd_repstat) {
2535 		if (!nd->nd_repstat && entrycnt == 0)
2536 			nd->nd_repstat = NFSERR_TOOSMALL;
2537 		if (nd->nd_repstat) {
2538 			newnfs_trimtrailing(nd, mb0, bpos0);
2539 			if (nd->nd_flag & ND_NFSV3)
2540 				nfsrv_postopattr(nd, getret, &at);
2541 		} else
2542 			newnfs_trimtrailing(nd, mb1, bpos1);
2543 		eofflag = 0;
2544 	} else if (cpos < cend)
2545 		eofflag = 0;
2546 	if (!nd->nd_repstat) {
2547 		NFSM_BUILD(tl, u_int32_t *, 2 * NFSX_UNSIGNED);
2548 		*tl++ = newnfs_false;
2549 		if (eofflag)
2550 			*tl = newnfs_true;
2551 		else
2552 			*tl = newnfs_false;
2553 	}
2554 	free(cookies, M_TEMP);
2555 	free(rbuf, M_TEMP);
2556 
2557 out:
2558 	NFSEXITCODE2(0, nd);
2559 	return (0);
2560 nfsmout:
2561 	vput(vp);
2562 	NFSEXITCODE2(error, nd);
2563 	return (error);
2564 }
2565 
2566 /*
2567  * Get the settable attributes out of the mbuf list.
2568  * (Return 0 or EBADRPC)
2569  */
2570 int
2571 nfsrv_sattr(struct nfsrv_descript *nd, vnode_t vp, struct nfsvattr *nvap,
2572     nfsattrbit_t *attrbitp, NFSACL_T *aclp, struct thread *p)
2573 {
2574 	u_int32_t *tl;
2575 	struct nfsv2_sattr *sp;
2576 	int error = 0, toclient = 0;
2577 
2578 	switch (nd->nd_flag & (ND_NFSV2 | ND_NFSV3 | ND_NFSV4)) {
2579 	case ND_NFSV2:
2580 		NFSM_DISSECT(sp, struct nfsv2_sattr *, NFSX_V2SATTR);
2581 		/*
2582 		 * Some old clients didn't fill in the high order 16bits.
2583 		 * --> check the low order 2 bytes for 0xffff
2584 		 */
2585 		if ((fxdr_unsigned(int, sp->sa_mode) & 0xffff) != 0xffff)
2586 			nvap->na_mode = nfstov_mode(sp->sa_mode);
2587 		if (sp->sa_uid != newnfs_xdrneg1)
2588 			nvap->na_uid = fxdr_unsigned(uid_t, sp->sa_uid);
2589 		if (sp->sa_gid != newnfs_xdrneg1)
2590 			nvap->na_gid = fxdr_unsigned(gid_t, sp->sa_gid);
2591 		if (sp->sa_size != newnfs_xdrneg1)
2592 			nvap->na_size = fxdr_unsigned(u_quad_t, sp->sa_size);
2593 		if (sp->sa_atime.nfsv2_sec != newnfs_xdrneg1) {
2594 #ifdef notyet
2595 			fxdr_nfsv2time(&sp->sa_atime, &nvap->na_atime);
2596 #else
2597 			nvap->na_atime.tv_sec =
2598 				fxdr_unsigned(u_int32_t,sp->sa_atime.nfsv2_sec);
2599 			nvap->na_atime.tv_nsec = 0;
2600 #endif
2601 		}
2602 		if (sp->sa_mtime.nfsv2_sec != newnfs_xdrneg1)
2603 			fxdr_nfsv2time(&sp->sa_mtime, &nvap->na_mtime);
2604 		break;
2605 	case ND_NFSV3:
2606 		NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
2607 		if (*tl == newnfs_true) {
2608 			NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
2609 			nvap->na_mode = nfstov_mode(*tl);
2610 		}
2611 		NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
2612 		if (*tl == newnfs_true) {
2613 			NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
2614 			nvap->na_uid = fxdr_unsigned(uid_t, *tl);
2615 		}
2616 		NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
2617 		if (*tl == newnfs_true) {
2618 			NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
2619 			nvap->na_gid = fxdr_unsigned(gid_t, *tl);
2620 		}
2621 		NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
2622 		if (*tl == newnfs_true) {
2623 			NFSM_DISSECT(tl, u_int32_t *, 2 * NFSX_UNSIGNED);
2624 			nvap->na_size = fxdr_hyper(tl);
2625 		}
2626 		NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
2627 		switch (fxdr_unsigned(int, *tl)) {
2628 		case NFSV3SATTRTIME_TOCLIENT:
2629 			NFSM_DISSECT(tl, u_int32_t *, 2 * NFSX_UNSIGNED);
2630 			fxdr_nfsv3time(tl, &nvap->na_atime);
2631 			toclient = 1;
2632 			break;
2633 		case NFSV3SATTRTIME_TOSERVER:
2634 			vfs_timestamp(&nvap->na_atime);
2635 			nvap->na_vaflags |= VA_UTIMES_NULL;
2636 			break;
2637 		}
2638 		NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
2639 		switch (fxdr_unsigned(int, *tl)) {
2640 		case NFSV3SATTRTIME_TOCLIENT:
2641 			NFSM_DISSECT(tl, u_int32_t *, 2 * NFSX_UNSIGNED);
2642 			fxdr_nfsv3time(tl, &nvap->na_mtime);
2643 			nvap->na_vaflags &= ~VA_UTIMES_NULL;
2644 			break;
2645 		case NFSV3SATTRTIME_TOSERVER:
2646 			vfs_timestamp(&nvap->na_mtime);
2647 			if (!toclient)
2648 				nvap->na_vaflags |= VA_UTIMES_NULL;
2649 			break;
2650 		}
2651 		break;
2652 	case ND_NFSV4:
2653 		error = nfsv4_sattr(nd, vp, nvap, attrbitp, aclp, p);
2654 	}
2655 nfsmout:
2656 	NFSEXITCODE2(error, nd);
2657 	return (error);
2658 }
2659 
2660 /*
2661  * Handle the setable attributes for V4.
2662  * Returns NFSERR_BADXDR if it can't be parsed, 0 otherwise.
2663  */
2664 int
2665 nfsv4_sattr(struct nfsrv_descript *nd, vnode_t vp, struct nfsvattr *nvap,
2666     nfsattrbit_t *attrbitp, NFSACL_T *aclp, struct thread *p)
2667 {
2668 	u_int32_t *tl;
2669 	int attrsum = 0;
2670 	int i, j;
2671 	int error, attrsize, bitpos, aclsize, aceerr, retnotsup = 0;
2672 	int toclient = 0;
2673 	u_char *cp, namestr[NFSV4_SMALLSTR + 1];
2674 	uid_t uid;
2675 	gid_t gid;
2676 
2677 	error = nfsrv_getattrbits(nd, attrbitp, NULL, &retnotsup);
2678 	if (error)
2679 		goto nfsmout;
2680 	NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
2681 	attrsize = fxdr_unsigned(int, *tl);
2682 
2683 	/*
2684 	 * Loop around getting the setable attributes. If an unsupported
2685 	 * one is found, set nd_repstat == NFSERR_ATTRNOTSUPP and return.
2686 	 */
2687 	if (retnotsup) {
2688 		nd->nd_repstat = NFSERR_ATTRNOTSUPP;
2689 		bitpos = NFSATTRBIT_MAX;
2690 	} else {
2691 		bitpos = 0;
2692 	}
2693 	for (; bitpos < NFSATTRBIT_MAX; bitpos++) {
2694 	    if (attrsum > attrsize) {
2695 		error = NFSERR_BADXDR;
2696 		goto nfsmout;
2697 	    }
2698 	    if (NFSISSET_ATTRBIT(attrbitp, bitpos))
2699 		switch (bitpos) {
2700 		case NFSATTRBIT_SIZE:
2701 			NFSM_DISSECT(tl, u_int32_t *, NFSX_HYPER);
2702                      if (vp != NULL && vp->v_type != VREG) {
2703                             error = (vp->v_type == VDIR) ? NFSERR_ISDIR :
2704                                 NFSERR_INVAL;
2705                             goto nfsmout;
2706 			}
2707 			nvap->na_size = fxdr_hyper(tl);
2708 			attrsum += NFSX_HYPER;
2709 			break;
2710 		case NFSATTRBIT_ACL:
2711 			error = nfsrv_dissectacl(nd, aclp, &aceerr, &aclsize,
2712 			    p);
2713 			if (error)
2714 				goto nfsmout;
2715 			if (aceerr && !nd->nd_repstat)
2716 				nd->nd_repstat = aceerr;
2717 			attrsum += aclsize;
2718 			break;
2719 		case NFSATTRBIT_ARCHIVE:
2720 			NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
2721 			if (!nd->nd_repstat)
2722 				nd->nd_repstat = NFSERR_ATTRNOTSUPP;
2723 			attrsum += NFSX_UNSIGNED;
2724 			break;
2725 		case NFSATTRBIT_HIDDEN:
2726 			NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
2727 			if (!nd->nd_repstat)
2728 				nd->nd_repstat = NFSERR_ATTRNOTSUPP;
2729 			attrsum += NFSX_UNSIGNED;
2730 			break;
2731 		case NFSATTRBIT_MIMETYPE:
2732 			NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
2733 			i = fxdr_unsigned(int, *tl);
2734 			error = nfsm_advance(nd, NFSM_RNDUP(i), -1);
2735 			if (error)
2736 				goto nfsmout;
2737 			if (!nd->nd_repstat)
2738 				nd->nd_repstat = NFSERR_ATTRNOTSUPP;
2739 			attrsum += (NFSX_UNSIGNED + NFSM_RNDUP(i));
2740 			break;
2741 		case NFSATTRBIT_MODE:
2742 			NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
2743 			nvap->na_mode = nfstov_mode(*tl);
2744 			attrsum += NFSX_UNSIGNED;
2745 			break;
2746 		case NFSATTRBIT_OWNER:
2747 			NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
2748 			j = fxdr_unsigned(int, *tl);
2749 			if (j < 0) {
2750 				error = NFSERR_BADXDR;
2751 				goto nfsmout;
2752 			}
2753 			if (j > NFSV4_SMALLSTR)
2754 				cp = malloc(j + 1, M_NFSSTRING, M_WAITOK);
2755 			else
2756 				cp = namestr;
2757 			error = nfsrv_mtostr(nd, cp, j);
2758 			if (error) {
2759 				if (j > NFSV4_SMALLSTR)
2760 					free(cp, M_NFSSTRING);
2761 				goto nfsmout;
2762 			}
2763 			if (!nd->nd_repstat) {
2764 				nd->nd_repstat = nfsv4_strtouid(nd, cp, j, &uid,
2765 				    p);
2766 				if (!nd->nd_repstat)
2767 					nvap->na_uid = uid;
2768 			}
2769 			if (j > NFSV4_SMALLSTR)
2770 				free(cp, M_NFSSTRING);
2771 			attrsum += (NFSX_UNSIGNED + NFSM_RNDUP(j));
2772 			break;
2773 		case NFSATTRBIT_OWNERGROUP:
2774 			NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
2775 			j = fxdr_unsigned(int, *tl);
2776 			if (j < 0) {
2777 				error = NFSERR_BADXDR;
2778 				goto nfsmout;
2779 			}
2780 			if (j > NFSV4_SMALLSTR)
2781 				cp = malloc(j + 1, M_NFSSTRING, M_WAITOK);
2782 			else
2783 				cp = namestr;
2784 			error = nfsrv_mtostr(nd, cp, j);
2785 			if (error) {
2786 				if (j > NFSV4_SMALLSTR)
2787 					free(cp, M_NFSSTRING);
2788 				goto nfsmout;
2789 			}
2790 			if (!nd->nd_repstat) {
2791 				nd->nd_repstat = nfsv4_strtogid(nd, cp, j, &gid,
2792 				    p);
2793 				if (!nd->nd_repstat)
2794 					nvap->na_gid = gid;
2795 			}
2796 			if (j > NFSV4_SMALLSTR)
2797 				free(cp, M_NFSSTRING);
2798 			attrsum += (NFSX_UNSIGNED + NFSM_RNDUP(j));
2799 			break;
2800 		case NFSATTRBIT_SYSTEM:
2801 			NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
2802 			if (!nd->nd_repstat)
2803 				nd->nd_repstat = NFSERR_ATTRNOTSUPP;
2804 			attrsum += NFSX_UNSIGNED;
2805 			break;
2806 		case NFSATTRBIT_TIMEACCESSSET:
2807 			NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
2808 			attrsum += NFSX_UNSIGNED;
2809 			if (fxdr_unsigned(int, *tl)==NFSV4SATTRTIME_TOCLIENT) {
2810 			    NFSM_DISSECT(tl, u_int32_t *, NFSX_V4TIME);
2811 			    fxdr_nfsv4time(tl, &nvap->na_atime);
2812 			    toclient = 1;
2813 			    attrsum += NFSX_V4TIME;
2814 			} else {
2815 			    vfs_timestamp(&nvap->na_atime);
2816 			    nvap->na_vaflags |= VA_UTIMES_NULL;
2817 			}
2818 			break;
2819 		case NFSATTRBIT_TIMEBACKUP:
2820 			NFSM_DISSECT(tl, u_int32_t *, NFSX_V4TIME);
2821 			if (!nd->nd_repstat)
2822 				nd->nd_repstat = NFSERR_ATTRNOTSUPP;
2823 			attrsum += NFSX_V4TIME;
2824 			break;
2825 		case NFSATTRBIT_TIMECREATE:
2826 			NFSM_DISSECT(tl, u_int32_t *, NFSX_V4TIME);
2827 			if (!nd->nd_repstat)
2828 				nd->nd_repstat = NFSERR_ATTRNOTSUPP;
2829 			attrsum += NFSX_V4TIME;
2830 			break;
2831 		case NFSATTRBIT_TIMEMODIFYSET:
2832 			NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
2833 			attrsum += NFSX_UNSIGNED;
2834 			if (fxdr_unsigned(int, *tl)==NFSV4SATTRTIME_TOCLIENT) {
2835 			    NFSM_DISSECT(tl, u_int32_t *, NFSX_V4TIME);
2836 			    fxdr_nfsv4time(tl, &nvap->na_mtime);
2837 			    nvap->na_vaflags &= ~VA_UTIMES_NULL;
2838 			    attrsum += NFSX_V4TIME;
2839 			} else {
2840 			    vfs_timestamp(&nvap->na_mtime);
2841 			    if (!toclient)
2842 				nvap->na_vaflags |= VA_UTIMES_NULL;
2843 			}
2844 			break;
2845 		default:
2846 			nd->nd_repstat = NFSERR_ATTRNOTSUPP;
2847 			/*
2848 			 * set bitpos so we drop out of the loop.
2849 			 */
2850 			bitpos = NFSATTRBIT_MAX;
2851 			break;
2852 		}
2853 	}
2854 
2855 	/*
2856 	 * some clients pad the attrlist, so we need to skip over the
2857 	 * padding.
2858 	 */
2859 	if (attrsum > attrsize) {
2860 		error = NFSERR_BADXDR;
2861 	} else {
2862 		attrsize = NFSM_RNDUP(attrsize);
2863 		if (attrsum < attrsize)
2864 			error = nfsm_advance(nd, attrsize - attrsum, -1);
2865 	}
2866 nfsmout:
2867 	NFSEXITCODE2(error, nd);
2868 	return (error);
2869 }
2870 
2871 /*
2872  * Check/setup export credentials.
2873  */
2874 int
2875 nfsd_excred(struct nfsrv_descript *nd, struct nfsexstuff *exp,
2876     struct ucred *credanon)
2877 {
2878 	int error = 0;
2879 
2880 	/*
2881 	 * Check/setup credentials.
2882 	 */
2883 	if (nd->nd_flag & ND_GSS)
2884 		exp->nes_exflag &= ~MNT_EXPORTANON;
2885 
2886 	/*
2887 	 * Check to see if the operation is allowed for this security flavor.
2888 	 * RFC2623 suggests that the NFSv3 Fsinfo RPC be allowed to
2889 	 * AUTH_NONE or AUTH_SYS for file systems requiring RPCSEC_GSS.
2890 	 * Also, allow Secinfo, so that it can acquire the correct flavor(s).
2891 	 */
2892 	if (nfsvno_testexp(nd, exp) &&
2893 	    nd->nd_procnum != NFSV4OP_SECINFO &&
2894 	    nd->nd_procnum != NFSPROC_FSINFO) {
2895 		if (nd->nd_flag & ND_NFSV4)
2896 			error = NFSERR_WRONGSEC;
2897 		else
2898 			error = (NFSERR_AUTHERR | AUTH_TOOWEAK);
2899 		goto out;
2900 	}
2901 
2902 	/*
2903 	 * Check to see if the file system is exported V4 only.
2904 	 */
2905 	if (NFSVNO_EXV4ONLY(exp) && !(nd->nd_flag & ND_NFSV4)) {
2906 		error = NFSERR_PROGNOTV4;
2907 		goto out;
2908 	}
2909 
2910 	/*
2911 	 * Now, map the user credentials.
2912 	 * (Note that ND_AUTHNONE will only be set for an NFSv3
2913 	 *  Fsinfo RPC. If set for anything else, this code might need
2914 	 *  to change.)
2915 	 */
2916 	if (NFSVNO_EXPORTED(exp)) {
2917 		if (((nd->nd_flag & ND_GSS) == 0 && nd->nd_cred->cr_uid == 0) ||
2918 		     NFSVNO_EXPORTANON(exp) ||
2919 		     (nd->nd_flag & ND_AUTHNONE) != 0) {
2920 			nd->nd_cred->cr_uid = credanon->cr_uid;
2921 			nd->nd_cred->cr_gid = credanon->cr_gid;
2922 			crsetgroups(nd->nd_cred, credanon->cr_ngroups,
2923 			    credanon->cr_groups);
2924 		} else if ((nd->nd_flag & ND_GSS) == 0) {
2925 			/*
2926 			 * If using AUTH_SYS, call nfsrv_getgrpscred() to see
2927 			 * if there is a replacement credential with a group
2928 			 * list set up by "nfsuserd -manage-gids".
2929 			 * If there is no replacement, nfsrv_getgrpscred()
2930 			 * simply returns its argument.
2931 			 */
2932 			nd->nd_cred = nfsrv_getgrpscred(nd->nd_cred);
2933 		}
2934 	}
2935 
2936 out:
2937 	NFSEXITCODE2(error, nd);
2938 	return (error);
2939 }
2940 
2941 /*
2942  * Check exports.
2943  */
2944 int
2945 nfsvno_checkexp(struct mount *mp, struct sockaddr *nam, struct nfsexstuff *exp,
2946     struct ucred **credp)
2947 {
2948 	int i, error, *secflavors;
2949 
2950 	error = VFS_CHECKEXP(mp, nam, &exp->nes_exflag, credp,
2951 	    &exp->nes_numsecflavor, &secflavors);
2952 	if (error) {
2953 		if (nfs_rootfhset) {
2954 			exp->nes_exflag = 0;
2955 			exp->nes_numsecflavor = 0;
2956 			error = 0;
2957 		}
2958 	} else {
2959 		/* Copy the security flavors. */
2960 		for (i = 0; i < exp->nes_numsecflavor; i++)
2961 			exp->nes_secflavors[i] = secflavors[i];
2962 	}
2963 	NFSEXITCODE(error);
2964 	return (error);
2965 }
2966 
2967 /*
2968  * Get a vnode for a file handle and export stuff.
2969  */
2970 int
2971 nfsvno_fhtovp(struct mount *mp, fhandle_t *fhp, struct sockaddr *nam,
2972     int lktype, struct vnode **vpp, struct nfsexstuff *exp,
2973     struct ucred **credp)
2974 {
2975 	int i, error, *secflavors;
2976 
2977 	*credp = NULL;
2978 	exp->nes_numsecflavor = 0;
2979 	error = VFS_FHTOVP(mp, &fhp->fh_fid, lktype, vpp);
2980 	if (error != 0)
2981 		/* Make sure the server replies ESTALE to the client. */
2982 		error = ESTALE;
2983 	if (nam && !error) {
2984 		error = VFS_CHECKEXP(mp, nam, &exp->nes_exflag, credp,
2985 		    &exp->nes_numsecflavor, &secflavors);
2986 		if (error) {
2987 			if (nfs_rootfhset) {
2988 				exp->nes_exflag = 0;
2989 				exp->nes_numsecflavor = 0;
2990 				error = 0;
2991 			} else {
2992 				vput(*vpp);
2993 			}
2994 		} else {
2995 			/* Copy the security flavors. */
2996 			for (i = 0; i < exp->nes_numsecflavor; i++)
2997 				exp->nes_secflavors[i] = secflavors[i];
2998 		}
2999 	}
3000 	NFSEXITCODE(error);
3001 	return (error);
3002 }
3003 
3004 /*
3005  * nfsd_fhtovp() - convert a fh to a vnode ptr
3006  * 	- look up fsid in mount list (if not found ret error)
3007  *	- get vp and export rights by calling nfsvno_fhtovp()
3008  *	- if cred->cr_uid == 0 or MNT_EXPORTANON set it to credanon
3009  *	  for AUTH_SYS
3010  *	- if mpp != NULL, return the mount point so that it can
3011  *	  be used for vn_finished_write() by the caller
3012  */
3013 void
3014 nfsd_fhtovp(struct nfsrv_descript *nd, struct nfsrvfh *nfp, int lktype,
3015     struct vnode **vpp, struct nfsexstuff *exp,
3016     struct mount **mpp, int startwrite, struct thread *p)
3017 {
3018 	struct mount *mp;
3019 	struct ucred *credanon;
3020 	fhandle_t *fhp;
3021 
3022 	fhp = (fhandle_t *)nfp->nfsrvfh_data;
3023 	/*
3024 	 * Check for the special case of the nfsv4root_fh.
3025 	 */
3026 	mp = vfs_busyfs(&fhp->fh_fsid);
3027 	if (mpp != NULL)
3028 		*mpp = mp;
3029 	if (mp == NULL) {
3030 		*vpp = NULL;
3031 		nd->nd_repstat = ESTALE;
3032 		goto out;
3033 	}
3034 
3035 	if (startwrite) {
3036 		vn_start_write(NULL, mpp, V_WAIT);
3037 		if (lktype == LK_SHARED && !(MNT_SHARED_WRITES(mp)))
3038 			lktype = LK_EXCLUSIVE;
3039 	}
3040 	nd->nd_repstat = nfsvno_fhtovp(mp, fhp, nd->nd_nam, lktype, vpp, exp,
3041 	    &credanon);
3042 	vfs_unbusy(mp);
3043 
3044 	/*
3045 	 * For NFSv4 without a pseudo root fs, unexported file handles
3046 	 * can be returned, so that Lookup works everywhere.
3047 	 */
3048 	if (!nd->nd_repstat && exp->nes_exflag == 0 &&
3049 	    !(nd->nd_flag & ND_NFSV4)) {
3050 		vput(*vpp);
3051 		nd->nd_repstat = EACCES;
3052 	}
3053 
3054 	/*
3055 	 * Personally, I've never seen any point in requiring a
3056 	 * reserved port#, since only in the rare case where the
3057 	 * clients are all boxes with secure system privileges,
3058 	 * does it provide any enhanced security, but... some people
3059 	 * believe it to be useful and keep putting this code back in.
3060 	 * (There is also some "security checker" out there that
3061 	 *  complains if the nfs server doesn't enforce this.)
3062 	 * However, note the following:
3063 	 * RFC3530 (NFSv4) specifies that a reserved port# not be
3064 	 *	required.
3065 	 * RFC2623 recommends that, if a reserved port# is checked for,
3066 	 *	that there be a way to turn that off--> ifdef'd.
3067 	 */
3068 #ifdef NFS_REQRSVPORT
3069 	if (!nd->nd_repstat) {
3070 		struct sockaddr_in *saddr;
3071 		struct sockaddr_in6 *saddr6;
3072 
3073 		saddr = NFSSOCKADDR(nd->nd_nam, struct sockaddr_in *);
3074 		saddr6 = NFSSOCKADDR(nd->nd_nam, struct sockaddr_in6 *);
3075 		if (!(nd->nd_flag & ND_NFSV4) &&
3076 		    ((saddr->sin_family == AF_INET &&
3077 		      ntohs(saddr->sin_port) >= IPPORT_RESERVED) ||
3078 		     (saddr6->sin6_family == AF_INET6 &&
3079 		      ntohs(saddr6->sin6_port) >= IPPORT_RESERVED))) {
3080 			vput(*vpp);
3081 			nd->nd_repstat = (NFSERR_AUTHERR | AUTH_TOOWEAK);
3082 		}
3083 	}
3084 #endif	/* NFS_REQRSVPORT */
3085 
3086 	/*
3087 	 * Check/setup credentials.
3088 	 */
3089 	if (!nd->nd_repstat) {
3090 		nd->nd_saveduid = nd->nd_cred->cr_uid;
3091 		nd->nd_repstat = nfsd_excred(nd, exp, credanon);
3092 		if (nd->nd_repstat)
3093 			vput(*vpp);
3094 	}
3095 	if (credanon != NULL)
3096 		crfree(credanon);
3097 	if (nd->nd_repstat) {
3098 		if (startwrite)
3099 			vn_finished_write(mp);
3100 		*vpp = NULL;
3101 		if (mpp != NULL)
3102 			*mpp = NULL;
3103 	}
3104 
3105 out:
3106 	NFSEXITCODE2(0, nd);
3107 }
3108 
3109 /*
3110  * glue for fp.
3111  */
3112 static int
3113 fp_getfvp(struct thread *p, int fd, struct file **fpp, struct vnode **vpp)
3114 {
3115 	struct filedesc *fdp;
3116 	struct file *fp;
3117 	int error = 0;
3118 
3119 	fdp = p->td_proc->p_fd;
3120 	if (fd < 0 || fd >= fdp->fd_nfiles ||
3121 	    (fp = fdp->fd_ofiles[fd].fde_file) == NULL) {
3122 		error = EBADF;
3123 		goto out;
3124 	}
3125 	*fpp = fp;
3126 
3127 out:
3128 	NFSEXITCODE(error);
3129 	return (error);
3130 }
3131 
3132 /*
3133  * Called from nfssvc() to update the exports list. Just call
3134  * vfs_export(). This has to be done, since the v4 root fake fs isn't
3135  * in the mount list.
3136  */
3137 int
3138 nfsrv_v4rootexport(void *argp, struct ucred *cred, struct thread *p)
3139 {
3140 	struct nfsex_args *nfsexargp = (struct nfsex_args *)argp;
3141 	int error = 0;
3142 	struct nameidata nd;
3143 	fhandle_t fh;
3144 
3145 	error = vfs_export(&nfsv4root_mnt, &nfsexargp->export);
3146 	if ((nfsexargp->export.ex_flags & MNT_DELEXPORT) != 0)
3147 		nfs_rootfhset = 0;
3148 	else if (error == 0) {
3149 		if (nfsexargp->fspec == NULL) {
3150 			error = EPERM;
3151 			goto out;
3152 		}
3153 		/*
3154 		 * If fspec != NULL, this is the v4root path.
3155 		 */
3156 		NDINIT(&nd, LOOKUP, FOLLOW, UIO_USERSPACE,
3157 		    nfsexargp->fspec, p);
3158 		if ((error = namei(&nd)) != 0)
3159 			goto out;
3160 		error = nfsvno_getfh(nd.ni_vp, &fh, p);
3161 		vrele(nd.ni_vp);
3162 		if (!error) {
3163 			nfs_rootfh.nfsrvfh_len = NFSX_MYFH;
3164 			NFSBCOPY((caddr_t)&fh,
3165 			    nfs_rootfh.nfsrvfh_data,
3166 			    sizeof (fhandle_t));
3167 			nfs_rootfhset = 1;
3168 		}
3169 	}
3170 
3171 out:
3172 	NFSEXITCODE(error);
3173 	return (error);
3174 }
3175 
3176 /*
3177  * This function needs to test to see if the system is near its limit
3178  * for memory allocation via malloc() or mget() and return True iff
3179  * either of these resources are near their limit.
3180  * XXX (For now, this is just a stub.)
3181  */
3182 int nfsrv_testmalloclimit = 0;
3183 int
3184 nfsrv_mallocmget_limit(void)
3185 {
3186 	static int printmesg = 0;
3187 	static int testval = 1;
3188 
3189 	if (nfsrv_testmalloclimit && (testval++ % 1000) == 0) {
3190 		if ((printmesg++ % 100) == 0)
3191 			printf("nfsd: malloc/mget near limit\n");
3192 		return (1);
3193 	}
3194 	return (0);
3195 }
3196 
3197 /*
3198  * BSD specific initialization of a mount point.
3199  */
3200 void
3201 nfsd_mntinit(void)
3202 {
3203 	static int inited = 0;
3204 
3205 	if (inited)
3206 		return;
3207 	inited = 1;
3208 	nfsv4root_mnt.mnt_flag = (MNT_RDONLY | MNT_EXPORTED);
3209 	TAILQ_INIT(&nfsv4root_mnt.mnt_nvnodelist);
3210 	TAILQ_INIT(&nfsv4root_mnt.mnt_activevnodelist);
3211 	nfsv4root_mnt.mnt_export = NULL;
3212 	TAILQ_INIT(&nfsv4root_opt);
3213 	TAILQ_INIT(&nfsv4root_newopt);
3214 	nfsv4root_mnt.mnt_opt = &nfsv4root_opt;
3215 	nfsv4root_mnt.mnt_optnew = &nfsv4root_newopt;
3216 	nfsv4root_mnt.mnt_nvnodelistsize = 0;
3217 	nfsv4root_mnt.mnt_activevnodelistsize = 0;
3218 }
3219 
3220 /*
3221  * Get a vnode for a file handle, without checking exports, etc.
3222  */
3223 struct vnode *
3224 nfsvno_getvp(fhandle_t *fhp)
3225 {
3226 	struct mount *mp;
3227 	struct vnode *vp;
3228 	int error;
3229 
3230 	mp = vfs_busyfs(&fhp->fh_fsid);
3231 	if (mp == NULL)
3232 		return (NULL);
3233 	error = VFS_FHTOVP(mp, &fhp->fh_fid, LK_EXCLUSIVE, &vp);
3234 	vfs_unbusy(mp);
3235 	if (error)
3236 		return (NULL);
3237 	return (vp);
3238 }
3239 
3240 /*
3241  * Do a local VOP_ADVLOCK().
3242  */
3243 int
3244 nfsvno_advlock(struct vnode *vp, int ftype, u_int64_t first,
3245     u_int64_t end, struct thread *td)
3246 {
3247 	int error = 0;
3248 	struct flock fl;
3249 	u_int64_t tlen;
3250 
3251 	if (nfsrv_dolocallocks == 0)
3252 		goto out;
3253 	ASSERT_VOP_UNLOCKED(vp, "nfsvno_advlock: vp locked");
3254 
3255 	fl.l_whence = SEEK_SET;
3256 	fl.l_type = ftype;
3257 	fl.l_start = (off_t)first;
3258 	if (end == NFS64BITSSET) {
3259 		fl.l_len = 0;
3260 	} else {
3261 		tlen = end - first;
3262 		fl.l_len = (off_t)tlen;
3263 	}
3264 	/*
3265 	 * For FreeBSD8, the l_pid and l_sysid must be set to the same
3266 	 * values for all calls, so that all locks will be held by the
3267 	 * nfsd server. (The nfsd server handles conflicts between the
3268 	 * various clients.)
3269 	 * Since an NFSv4 lockowner is a ClientID plus an array of up to 1024
3270 	 * bytes, so it can't be put in l_sysid.
3271 	 */
3272 	if (nfsv4_sysid == 0)
3273 		nfsv4_sysid = nlm_acquire_next_sysid();
3274 	fl.l_pid = (pid_t)0;
3275 	fl.l_sysid = (int)nfsv4_sysid;
3276 
3277 	if (ftype == F_UNLCK)
3278 		error = VOP_ADVLOCK(vp, (caddr_t)td->td_proc, F_UNLCK, &fl,
3279 		    (F_POSIX | F_REMOTE));
3280 	else
3281 		error = VOP_ADVLOCK(vp, (caddr_t)td->td_proc, F_SETLK, &fl,
3282 		    (F_POSIX | F_REMOTE));
3283 
3284 out:
3285 	NFSEXITCODE(error);
3286 	return (error);
3287 }
3288 
3289 /*
3290  * Check the nfsv4 root exports.
3291  */
3292 int
3293 nfsvno_v4rootexport(struct nfsrv_descript *nd)
3294 {
3295 	struct ucred *credanon;
3296 	int exflags, error = 0, numsecflavor, *secflavors, i;
3297 
3298 	error = vfs_stdcheckexp(&nfsv4root_mnt, nd->nd_nam, &exflags,
3299 	    &credanon, &numsecflavor, &secflavors);
3300 	if (error) {
3301 		error = NFSERR_PROGUNAVAIL;
3302 		goto out;
3303 	}
3304 	if (credanon != NULL)
3305 		crfree(credanon);
3306 	for (i = 0; i < numsecflavor; i++) {
3307 		if (secflavors[i] == AUTH_SYS)
3308 			nd->nd_flag |= ND_EXAUTHSYS;
3309 		else if (secflavors[i] == RPCSEC_GSS_KRB5)
3310 			nd->nd_flag |= ND_EXGSS;
3311 		else if (secflavors[i] == RPCSEC_GSS_KRB5I)
3312 			nd->nd_flag |= ND_EXGSSINTEGRITY;
3313 		else if (secflavors[i] == RPCSEC_GSS_KRB5P)
3314 			nd->nd_flag |= ND_EXGSSPRIVACY;
3315 	}
3316 
3317 out:
3318 	NFSEXITCODE(error);
3319 	return (error);
3320 }
3321 
3322 /*
3323  * Nfs server pseudo system call for the nfsd's
3324  */
3325 /*
3326  * MPSAFE
3327  */
3328 static int
3329 nfssvc_nfsd(struct thread *td, struct nfssvc_args *uap)
3330 {
3331 	struct file *fp;
3332 	struct nfsd_addsock_args sockarg;
3333 	struct nfsd_nfsd_args nfsdarg;
3334 	struct nfsd_nfsd_oargs onfsdarg;
3335 	struct nfsd_pnfsd_args pnfsdarg;
3336 	struct vnode *vp, *nvp, *curdvp;
3337 	struct pnfsdsfile *pf;
3338 	struct nfsdevice *ds, *fds;
3339 	cap_rights_t rights;
3340 	int buflen, error, ret;
3341 	char *buf, *cp, *cp2, *cp3;
3342 	char fname[PNFS_FILENAME_LEN + 1];
3343 
3344 	if (uap->flag & NFSSVC_NFSDADDSOCK) {
3345 		error = copyin(uap->argp, (caddr_t)&sockarg, sizeof (sockarg));
3346 		if (error)
3347 			goto out;
3348 		/*
3349 		 * Since we don't know what rights might be required,
3350 		 * pretend that we need them all. It is better to be too
3351 		 * careful than too reckless.
3352 		 */
3353 		error = fget(td, sockarg.sock,
3354 		    cap_rights_init(&rights, CAP_SOCK_SERVER), &fp);
3355 		if (error != 0)
3356 			goto out;
3357 		if (fp->f_type != DTYPE_SOCKET) {
3358 			fdrop(fp, td);
3359 			error = EPERM;
3360 			goto out;
3361 		}
3362 		error = nfsrvd_addsock(fp);
3363 		fdrop(fp, td);
3364 	} else if (uap->flag & NFSSVC_NFSDNFSD) {
3365 		if (uap->argp == NULL) {
3366 			error = EINVAL;
3367 			goto out;
3368 		}
3369 		if ((uap->flag & NFSSVC_NEWSTRUCT) == 0) {
3370 			error = copyin(uap->argp, &onfsdarg, sizeof(onfsdarg));
3371 			if (error == 0) {
3372 				nfsdarg.principal = onfsdarg.principal;
3373 				nfsdarg.minthreads = onfsdarg.minthreads;
3374 				nfsdarg.maxthreads = onfsdarg.maxthreads;
3375 				nfsdarg.version = 1;
3376 				nfsdarg.addr = NULL;
3377 				nfsdarg.addrlen = 0;
3378 				nfsdarg.dnshost = NULL;
3379 				nfsdarg.dnshostlen = 0;
3380 				nfsdarg.dspath = NULL;
3381 				nfsdarg.dspathlen = 0;
3382 				nfsdarg.mdspath = NULL;
3383 				nfsdarg.mdspathlen = 0;
3384 				nfsdarg.mirrorcnt = 1;
3385 			}
3386 		} else
3387 			error = copyin(uap->argp, &nfsdarg, sizeof(nfsdarg));
3388 		if (error)
3389 			goto out;
3390 		if (nfsdarg.addrlen > 0 && nfsdarg.addrlen < 10000 &&
3391 		    nfsdarg.dnshostlen > 0 && nfsdarg.dnshostlen < 10000 &&
3392 		    nfsdarg.dspathlen > 0 && nfsdarg.dspathlen < 10000 &&
3393 		    nfsdarg.mdspathlen > 0 && nfsdarg.mdspathlen < 10000 &&
3394 		    nfsdarg.mirrorcnt >= 1 &&
3395 		    nfsdarg.mirrorcnt <= NFSDEV_MAXMIRRORS &&
3396 		    nfsdarg.addr != NULL && nfsdarg.dnshost != NULL &&
3397 		    nfsdarg.dspath != NULL && nfsdarg.mdspath != NULL) {
3398 			NFSD_DEBUG(1, "addrlen=%d dspathlen=%d dnslen=%d"
3399 			    " mdspathlen=%d mirrorcnt=%d\n", nfsdarg.addrlen,
3400 			    nfsdarg.dspathlen, nfsdarg.dnshostlen,
3401 			    nfsdarg.mdspathlen, nfsdarg.mirrorcnt);
3402 			cp = malloc(nfsdarg.addrlen + 1, M_TEMP, M_WAITOK);
3403 			error = copyin(nfsdarg.addr, cp, nfsdarg.addrlen);
3404 			if (error != 0) {
3405 				free(cp, M_TEMP);
3406 				goto out;
3407 			}
3408 			cp[nfsdarg.addrlen] = '\0';	/* Ensure nul term. */
3409 			nfsdarg.addr = cp;
3410 			cp = malloc(nfsdarg.dnshostlen + 1, M_TEMP, M_WAITOK);
3411 			error = copyin(nfsdarg.dnshost, cp, nfsdarg.dnshostlen);
3412 			if (error != 0) {
3413 				free(nfsdarg.addr, M_TEMP);
3414 				free(cp, M_TEMP);
3415 				goto out;
3416 			}
3417 			cp[nfsdarg.dnshostlen] = '\0';	/* Ensure nul term. */
3418 			nfsdarg.dnshost = cp;
3419 			cp = malloc(nfsdarg.dspathlen + 1, M_TEMP, M_WAITOK);
3420 			error = copyin(nfsdarg.dspath, cp, nfsdarg.dspathlen);
3421 			if (error != 0) {
3422 				free(nfsdarg.addr, M_TEMP);
3423 				free(nfsdarg.dnshost, M_TEMP);
3424 				free(cp, M_TEMP);
3425 				goto out;
3426 			}
3427 			cp[nfsdarg.dspathlen] = '\0';	/* Ensure nul term. */
3428 			nfsdarg.dspath = cp;
3429 			cp = malloc(nfsdarg.mdspathlen + 1, M_TEMP, M_WAITOK);
3430 			error = copyin(nfsdarg.mdspath, cp, nfsdarg.mdspathlen);
3431 			if (error != 0) {
3432 				free(nfsdarg.addr, M_TEMP);
3433 				free(nfsdarg.dnshost, M_TEMP);
3434 				free(nfsdarg.dspath, M_TEMP);
3435 				free(cp, M_TEMP);
3436 				goto out;
3437 			}
3438 			cp[nfsdarg.mdspathlen] = '\0';	/* Ensure nul term. */
3439 			nfsdarg.mdspath = cp;
3440 		} else {
3441 			nfsdarg.addr = NULL;
3442 			nfsdarg.addrlen = 0;
3443 			nfsdarg.dnshost = NULL;
3444 			nfsdarg.dnshostlen = 0;
3445 			nfsdarg.dspath = NULL;
3446 			nfsdarg.dspathlen = 0;
3447 			nfsdarg.mdspath = NULL;
3448 			nfsdarg.mdspathlen = 0;
3449 			nfsdarg.mirrorcnt = 1;
3450 		}
3451 		error = nfsrvd_nfsd(td, &nfsdarg);
3452 		free(nfsdarg.addr, M_TEMP);
3453 		free(nfsdarg.dnshost, M_TEMP);
3454 		free(nfsdarg.dspath, M_TEMP);
3455 		free(nfsdarg.mdspath, M_TEMP);
3456 	} else if (uap->flag & NFSSVC_PNFSDS) {
3457 		error = copyin(uap->argp, &pnfsdarg, sizeof(pnfsdarg));
3458 		if (error == 0 && (pnfsdarg.op == PNFSDOP_DELDSSERVER ||
3459 		    pnfsdarg.op == PNFSDOP_FORCEDELDS)) {
3460 			cp = malloc(PATH_MAX + 1, M_TEMP, M_WAITOK);
3461 			error = copyinstr(pnfsdarg.dspath, cp, PATH_MAX + 1,
3462 			    NULL);
3463 			if (error == 0)
3464 				error = nfsrv_deldsserver(pnfsdarg.op, cp, td);
3465 			free(cp, M_TEMP);
3466 		} else if (error == 0 && pnfsdarg.op == PNFSDOP_COPYMR) {
3467 			cp = malloc(PATH_MAX + 1, M_TEMP, M_WAITOK);
3468 			buflen = sizeof(*pf) * NFSDEV_MAXMIRRORS;
3469 			buf = malloc(buflen, M_TEMP, M_WAITOK);
3470 			error = copyinstr(pnfsdarg.mdspath, cp, PATH_MAX + 1,
3471 			    NULL);
3472 			NFSD_DEBUG(4, "pnfsdcopymr cp mdspath=%d\n", error);
3473 			if (error == 0 && pnfsdarg.dspath != NULL) {
3474 				cp2 = malloc(PATH_MAX + 1, M_TEMP, M_WAITOK);
3475 				error = copyinstr(pnfsdarg.dspath, cp2,
3476 				    PATH_MAX + 1, NULL);
3477 				NFSD_DEBUG(4, "pnfsdcopymr cp dspath=%d\n",
3478 				    error);
3479 			} else
3480 				cp2 = NULL;
3481 			if (error == 0 && pnfsdarg.curdspath != NULL) {
3482 				cp3 = malloc(PATH_MAX + 1, M_TEMP, M_WAITOK);
3483 				error = copyinstr(pnfsdarg.curdspath, cp3,
3484 				    PATH_MAX + 1, NULL);
3485 				NFSD_DEBUG(4, "pnfsdcopymr cp curdspath=%d\n",
3486 				    error);
3487 			} else
3488 				cp3 = NULL;
3489 			curdvp = NULL;
3490 			fds = NULL;
3491 			if (error == 0)
3492 				error = nfsrv_mdscopymr(cp, cp2, cp3, buf,
3493 				    &buflen, fname, td, &vp, &nvp, &pf, &ds,
3494 				    &fds);
3495 			NFSD_DEBUG(4, "nfsrv_mdscopymr=%d\n", error);
3496 			if (error == 0) {
3497 				if (pf->dsf_dir >= nfsrv_dsdirsize) {
3498 					printf("copymr: dsdir out of range\n");
3499 					pf->dsf_dir = 0;
3500 				}
3501 				NFSD_DEBUG(4, "copymr: buflen=%d\n", buflen);
3502 				error = nfsrv_copymr(vp, nvp,
3503 				    ds->nfsdev_dsdir[pf->dsf_dir], ds, pf,
3504 				    (struct pnfsdsfile *)buf,
3505 				    buflen / sizeof(*pf), td->td_ucred, td);
3506 				vput(vp);
3507 				vput(nvp);
3508 				if (fds != NULL && error == 0) {
3509 					curdvp = fds->nfsdev_dsdir[pf->dsf_dir];
3510 					ret = vn_lock(curdvp, LK_EXCLUSIVE);
3511 					if (ret == 0) {
3512 						nfsrv_dsremove(curdvp, fname,
3513 						    td->td_ucred, td);
3514 						NFSVOPUNLOCK(curdvp, 0);
3515 					}
3516 				}
3517 				NFSD_DEBUG(4, "nfsrv_copymr=%d\n", error);
3518 			}
3519 			free(cp, M_TEMP);
3520 			free(cp2, M_TEMP);
3521 			free(cp3, M_TEMP);
3522 			free(buf, M_TEMP);
3523 		}
3524 	} else {
3525 		error = nfssvc_srvcall(td, uap, td->td_ucred);
3526 	}
3527 
3528 out:
3529 	NFSEXITCODE(error);
3530 	return (error);
3531 }
3532 
3533 static int
3534 nfssvc_srvcall(struct thread *p, struct nfssvc_args *uap, struct ucred *cred)
3535 {
3536 	struct nfsex_args export;
3537 	struct file *fp = NULL;
3538 	int stablefd, len;
3539 	struct nfsd_clid adminrevoke;
3540 	struct nfsd_dumplist dumplist;
3541 	struct nfsd_dumpclients *dumpclients;
3542 	struct nfsd_dumplocklist dumplocklist;
3543 	struct nfsd_dumplocks *dumplocks;
3544 	struct nameidata nd;
3545 	vnode_t vp;
3546 	int error = EINVAL, igotlock;
3547 	struct proc *procp;
3548 	static int suspend_nfsd = 0;
3549 
3550 	if (uap->flag & NFSSVC_PUBLICFH) {
3551 		NFSBZERO((caddr_t)&nfs_pubfh.nfsrvfh_data,
3552 		    sizeof (fhandle_t));
3553 		error = copyin(uap->argp,
3554 		    &nfs_pubfh.nfsrvfh_data, sizeof (fhandle_t));
3555 		if (!error)
3556 			nfs_pubfhset = 1;
3557 	} else if (uap->flag & NFSSVC_V4ROOTEXPORT) {
3558 		error = copyin(uap->argp,(caddr_t)&export,
3559 		    sizeof (struct nfsex_args));
3560 		if (!error)
3561 			error = nfsrv_v4rootexport(&export, cred, p);
3562 	} else if (uap->flag & NFSSVC_NOPUBLICFH) {
3563 		nfs_pubfhset = 0;
3564 		error = 0;
3565 	} else if (uap->flag & NFSSVC_STABLERESTART) {
3566 		error = copyin(uap->argp, (caddr_t)&stablefd,
3567 		    sizeof (int));
3568 		if (!error)
3569 			error = fp_getfvp(p, stablefd, &fp, &vp);
3570 		if (!error && (NFSFPFLAG(fp) & (FREAD | FWRITE)) != (FREAD | FWRITE))
3571 			error = EBADF;
3572 		if (!error && newnfs_numnfsd != 0)
3573 			error = EPERM;
3574 		if (!error) {
3575 			nfsrv_stablefirst.nsf_fp = fp;
3576 			nfsrv_setupstable(p);
3577 		}
3578 	} else if (uap->flag & NFSSVC_ADMINREVOKE) {
3579 		error = copyin(uap->argp, (caddr_t)&adminrevoke,
3580 		    sizeof (struct nfsd_clid));
3581 		if (!error)
3582 			error = nfsrv_adminrevoke(&adminrevoke, p);
3583 	} else if (uap->flag & NFSSVC_DUMPCLIENTS) {
3584 		error = copyin(uap->argp, (caddr_t)&dumplist,
3585 		    sizeof (struct nfsd_dumplist));
3586 		if (!error && (dumplist.ndl_size < 1 ||
3587 			dumplist.ndl_size > NFSRV_MAXDUMPLIST))
3588 			error = EPERM;
3589 		if (!error) {
3590 		    len = sizeof (struct nfsd_dumpclients) * dumplist.ndl_size;
3591 		    dumpclients = (struct nfsd_dumpclients *)malloc(len,
3592 			M_TEMP, M_WAITOK);
3593 		    nfsrv_dumpclients(dumpclients, dumplist.ndl_size);
3594 		    error = copyout(dumpclients,
3595 			CAST_USER_ADDR_T(dumplist.ndl_list), len);
3596 		    free(dumpclients, M_TEMP);
3597 		}
3598 	} else if (uap->flag & NFSSVC_DUMPLOCKS) {
3599 		error = copyin(uap->argp, (caddr_t)&dumplocklist,
3600 		    sizeof (struct nfsd_dumplocklist));
3601 		if (!error && (dumplocklist.ndllck_size < 1 ||
3602 			dumplocklist.ndllck_size > NFSRV_MAXDUMPLIST))
3603 			error = EPERM;
3604 		if (!error)
3605 			error = nfsrv_lookupfilename(&nd,
3606 				dumplocklist.ndllck_fname, p);
3607 		if (!error) {
3608 			len = sizeof (struct nfsd_dumplocks) *
3609 				dumplocklist.ndllck_size;
3610 			dumplocks = (struct nfsd_dumplocks *)malloc(len,
3611 				M_TEMP, M_WAITOK);
3612 			nfsrv_dumplocks(nd.ni_vp, dumplocks,
3613 			    dumplocklist.ndllck_size, p);
3614 			vput(nd.ni_vp);
3615 			error = copyout(dumplocks,
3616 			    CAST_USER_ADDR_T(dumplocklist.ndllck_list), len);
3617 			free(dumplocks, M_TEMP);
3618 		}
3619 	} else if (uap->flag & NFSSVC_BACKUPSTABLE) {
3620 		procp = p->td_proc;
3621 		PROC_LOCK(procp);
3622 		nfsd_master_pid = procp->p_pid;
3623 		bcopy(procp->p_comm, nfsd_master_comm, MAXCOMLEN + 1);
3624 		nfsd_master_start = procp->p_stats->p_start;
3625 		nfsd_master_proc = procp;
3626 		PROC_UNLOCK(procp);
3627 	} else if ((uap->flag & NFSSVC_SUSPENDNFSD) != 0) {
3628 		NFSLOCKV4ROOTMUTEX();
3629 		if (suspend_nfsd == 0) {
3630 			/* Lock out all nfsd threads */
3631 			do {
3632 				igotlock = nfsv4_lock(&nfsd_suspend_lock, 1,
3633 				    NULL, NFSV4ROOTLOCKMUTEXPTR, NULL);
3634 			} while (igotlock == 0 && suspend_nfsd == 0);
3635 			suspend_nfsd = 1;
3636 		}
3637 		NFSUNLOCKV4ROOTMUTEX();
3638 		error = 0;
3639 	} else if ((uap->flag & NFSSVC_RESUMENFSD) != 0) {
3640 		NFSLOCKV4ROOTMUTEX();
3641 		if (suspend_nfsd != 0) {
3642 			nfsv4_unlock(&nfsd_suspend_lock, 0);
3643 			suspend_nfsd = 0;
3644 		}
3645 		NFSUNLOCKV4ROOTMUTEX();
3646 		error = 0;
3647 	}
3648 
3649 	NFSEXITCODE(error);
3650 	return (error);
3651 }
3652 
3653 /*
3654  * Check exports.
3655  * Returns 0 if ok, 1 otherwise.
3656  */
3657 int
3658 nfsvno_testexp(struct nfsrv_descript *nd, struct nfsexstuff *exp)
3659 {
3660 	int i;
3661 
3662 	/*
3663 	 * This seems odd, but allow the case where the security flavor
3664 	 * list is empty. This happens when NFSv4 is traversing non-exported
3665 	 * file systems. Exported file systems should always have a non-empty
3666 	 * security flavor list.
3667 	 */
3668 	if (exp->nes_numsecflavor == 0)
3669 		return (0);
3670 
3671 	for (i = 0; i < exp->nes_numsecflavor; i++) {
3672 		/*
3673 		 * The tests for privacy and integrity must be first,
3674 		 * since ND_GSS is set for everything but AUTH_SYS.
3675 		 */
3676 		if (exp->nes_secflavors[i] == RPCSEC_GSS_KRB5P &&
3677 		    (nd->nd_flag & ND_GSSPRIVACY))
3678 			return (0);
3679 		if (exp->nes_secflavors[i] == RPCSEC_GSS_KRB5I &&
3680 		    (nd->nd_flag & ND_GSSINTEGRITY))
3681 			return (0);
3682 		if (exp->nes_secflavors[i] == RPCSEC_GSS_KRB5 &&
3683 		    (nd->nd_flag & ND_GSS))
3684 			return (0);
3685 		if (exp->nes_secflavors[i] == AUTH_SYS &&
3686 		    (nd->nd_flag & ND_GSS) == 0)
3687 			return (0);
3688 	}
3689 	return (1);
3690 }
3691 
3692 /*
3693  * Calculate a hash value for the fid in a file handle.
3694  */
3695 uint32_t
3696 nfsrv_hashfh(fhandle_t *fhp)
3697 {
3698 	uint32_t hashval;
3699 
3700 	hashval = hash32_buf(&fhp->fh_fid, sizeof(struct fid), 0);
3701 	return (hashval);
3702 }
3703 
3704 /*
3705  * Calculate a hash value for the sessionid.
3706  */
3707 uint32_t
3708 nfsrv_hashsessionid(uint8_t *sessionid)
3709 {
3710 	uint32_t hashval;
3711 
3712 	hashval = hash32_buf(sessionid, NFSX_V4SESSIONID, 0);
3713 	return (hashval);
3714 }
3715 
3716 /*
3717  * Signal the userland master nfsd to backup the stable restart file.
3718  */
3719 void
3720 nfsrv_backupstable(void)
3721 {
3722 	struct proc *procp;
3723 
3724 	if (nfsd_master_proc != NULL) {
3725 		procp = pfind(nfsd_master_pid);
3726 		/* Try to make sure it is the correct process. */
3727 		if (procp == nfsd_master_proc &&
3728 		    procp->p_stats->p_start.tv_sec ==
3729 		    nfsd_master_start.tv_sec &&
3730 		    procp->p_stats->p_start.tv_usec ==
3731 		    nfsd_master_start.tv_usec &&
3732 		    strcmp(procp->p_comm, nfsd_master_comm) == 0)
3733 			kern_psignal(procp, SIGUSR2);
3734 		else
3735 			nfsd_master_proc = NULL;
3736 
3737 		if (procp != NULL)
3738 			PROC_UNLOCK(procp);
3739 	}
3740 }
3741 
3742 /*
3743  * Create a DS data file for nfsrv_pnfscreate(). Called for each mirror.
3744  * The arguments are in a structure, so that they can be passed through
3745  * taskqueue for a kernel process to execute this function.
3746  */
3747 struct nfsrvdscreate {
3748 	int			done;
3749 	int			inprog;
3750 	struct task		tsk;
3751 	struct ucred		*tcred;
3752 	struct vnode		*dvp;
3753 	NFSPROC_T		*p;
3754 	struct pnfsdsfile	*pf;
3755 	int			err;
3756 	fhandle_t		fh;
3757 	struct vattr		va;
3758 	struct vattr		createva;
3759 };
3760 
3761 int
3762 nfsrv_dscreate(struct vnode *dvp, struct vattr *vap, struct vattr *nvap,
3763     fhandle_t *fhp, struct pnfsdsfile *pf, struct pnfsdsattr *dsa,
3764     char *fnamep, struct ucred *tcred, NFSPROC_T *p, struct vnode **nvpp)
3765 {
3766 	struct vnode *nvp;
3767 	struct nameidata named;
3768 	struct vattr va;
3769 	char *bufp;
3770 	u_long *hashp;
3771 	struct nfsnode *np;
3772 	struct nfsmount *nmp;
3773 	int error;
3774 
3775 	NFSNAMEICNDSET(&named.ni_cnd, tcred, CREATE,
3776 	    LOCKPARENT | LOCKLEAF | SAVESTART | NOCACHE);
3777 	nfsvno_setpathbuf(&named, &bufp, &hashp);
3778 	named.ni_cnd.cn_lkflags = LK_EXCLUSIVE;
3779 	named.ni_cnd.cn_thread = p;
3780 	named.ni_cnd.cn_nameptr = bufp;
3781 	if (fnamep != NULL) {
3782 		strlcpy(bufp, fnamep, PNFS_FILENAME_LEN + 1);
3783 		named.ni_cnd.cn_namelen = strlen(bufp);
3784 	} else
3785 		named.ni_cnd.cn_namelen = nfsrv_putfhname(fhp, bufp);
3786 	NFSD_DEBUG(4, "nfsrv_dscreate: dvp=%p fname=%s\n", dvp, bufp);
3787 
3788 	/* Create the date file in the DS mount. */
3789 	error = NFSVOPLOCK(dvp, LK_EXCLUSIVE);
3790 	if (error == 0) {
3791 		error = VOP_CREATE(dvp, &nvp, &named.ni_cnd, vap);
3792 		NFSVOPUNLOCK(dvp, 0);
3793 		if (error == 0) {
3794 			/* Set the ownership of the file. */
3795 			error = VOP_SETATTR(nvp, nvap, tcred);
3796 			NFSD_DEBUG(4, "nfsrv_dscreate:"
3797 			    " setattr-uid=%d\n", error);
3798 			if (error != 0)
3799 				vput(nvp);
3800 		}
3801 		if (error != 0)
3802 			printf("pNFS: pnfscreate failed=%d\n", error);
3803 	} else
3804 		printf("pNFS: pnfscreate vnlock=%d\n", error);
3805 	if (error == 0) {
3806 		np = VTONFS(nvp);
3807 		nmp = VFSTONFS(nvp->v_mount);
3808 		if (strcmp(nvp->v_mount->mnt_vfc->vfc_name, "nfs")
3809 		    != 0 || nmp->nm_nam->sa_len > sizeof(
3810 		    struct sockaddr_in6) ||
3811 		    np->n_fhp->nfh_len != NFSX_MYFH) {
3812 			printf("Bad DS file: fstype=%s salen=%d"
3813 			    " fhlen=%d\n",
3814 			    nvp->v_mount->mnt_vfc->vfc_name,
3815 			    nmp->nm_nam->sa_len, np->n_fhp->nfh_len);
3816 			error = ENOENT;
3817 		}
3818 
3819 		/* Set extattrs for the DS on the MDS file. */
3820 		if (error == 0) {
3821 			if (dsa != NULL) {
3822 				error = VOP_GETATTR(nvp, &va, tcred);
3823 				if (error == 0) {
3824 					dsa->dsa_filerev = va.va_filerev;
3825 					dsa->dsa_size = va.va_size;
3826 					dsa->dsa_atime = va.va_atime;
3827 					dsa->dsa_mtime = va.va_mtime;
3828 				}
3829 			}
3830 			if (error == 0) {
3831 				NFSBCOPY(np->n_fhp->nfh_fh, &pf->dsf_fh,
3832 				    NFSX_MYFH);
3833 				NFSBCOPY(nmp->nm_nam, &pf->dsf_sin,
3834 				    nmp->nm_nam->sa_len);
3835 				NFSBCOPY(named.ni_cnd.cn_nameptr,
3836 				    pf->dsf_filename,
3837 				    sizeof(pf->dsf_filename));
3838 			}
3839 		} else
3840 			printf("pNFS: pnfscreate can't get DS"
3841 			    " attr=%d\n", error);
3842 		if (nvpp != NULL && error == 0)
3843 			*nvpp = nvp;
3844 		else
3845 			vput(nvp);
3846 	}
3847 	nfsvno_relpathbuf(&named);
3848 	return (error);
3849 }
3850 
3851 /*
3852  * Start up the thread that will execute nfsrv_dscreate().
3853  */
3854 static void
3855 start_dscreate(void *arg, int pending)
3856 {
3857 	struct nfsrvdscreate *dsc;
3858 
3859 	dsc = (struct nfsrvdscreate *)arg;
3860 	dsc->err = nfsrv_dscreate(dsc->dvp, &dsc->createva, &dsc->va, &dsc->fh,
3861 	    dsc->pf, NULL, NULL, dsc->tcred, dsc->p, NULL);
3862 	dsc->done = 1;
3863 	NFSD_DEBUG(4, "start_dscreate: err=%d\n", dsc->err);
3864 }
3865 
3866 /*
3867  * Create a pNFS data file on the Data Server(s).
3868  */
3869 static void
3870 nfsrv_pnfscreate(struct vnode *vp, struct vattr *vap, struct ucred *cred,
3871     NFSPROC_T *p)
3872 {
3873 	struct nfsrvdscreate *dsc, *tdsc;
3874 	struct nfsdevice *ds, *tds, *fds;
3875 	struct mount *mp;
3876 	struct pnfsdsfile *pf, *tpf;
3877 	struct pnfsdsattr dsattr;
3878 	struct vattr va;
3879 	struct vnode *dvp[NFSDEV_MAXMIRRORS];
3880 	struct nfsmount *nmp;
3881 	fhandle_t fh;
3882 	uid_t vauid;
3883 	gid_t vagid;
3884 	u_short vamode;
3885 	struct ucred *tcred;
3886 	int dsdir[NFSDEV_MAXMIRRORS], error, i, mirrorcnt, ret;
3887 	int failpos, timo;
3888 
3889 	/* Get a DS server directory in a round-robin order. */
3890 	mirrorcnt = 1;
3891 	mp = vp->v_mount;
3892 	ds = fds = NULL;
3893 	NFSDDSLOCK();
3894 	/*
3895 	 * Search for the first entry that handles this MDS fs, but use the
3896 	 * first entry for all MDS fs's otherwise.
3897 	 */
3898 	TAILQ_FOREACH(tds, &nfsrv_devidhead, nfsdev_list) {
3899 		if (tds->nfsdev_nmp != NULL) {
3900 			if (tds->nfsdev_mdsisset == 0 && ds == NULL)
3901 				ds = tds;
3902 			else if (tds->nfsdev_mdsisset != 0 &&
3903 			    mp->mnt_stat.f_fsid.val[0] ==
3904 			    tds->nfsdev_mdsfsid.val[0] &&
3905 			    mp->mnt_stat.f_fsid.val[1] ==
3906 			    tds->nfsdev_mdsfsid.val[1]) {
3907 				ds = fds = tds;
3908 				break;
3909 			}
3910 		}
3911 	}
3912 	if (ds == NULL) {
3913 		NFSDDSUNLOCK();
3914 		NFSD_DEBUG(4, "nfsrv_pnfscreate: no srv\n");
3915 		return;
3916 	}
3917 	i = dsdir[0] = ds->nfsdev_nextdir;
3918 	ds->nfsdev_nextdir = (ds->nfsdev_nextdir + 1) % nfsrv_dsdirsize;
3919 	dvp[0] = ds->nfsdev_dsdir[i];
3920 	tds = TAILQ_NEXT(ds, nfsdev_list);
3921 	if (nfsrv_maxpnfsmirror > 1 && tds != NULL) {
3922 		TAILQ_FOREACH_FROM(tds, &nfsrv_devidhead, nfsdev_list) {
3923 			if (tds->nfsdev_nmp != NULL &&
3924 			    ((tds->nfsdev_mdsisset == 0 && fds == NULL) ||
3925 			     (tds->nfsdev_mdsisset != 0 && fds != NULL &&
3926 			      mp->mnt_stat.f_fsid.val[0] ==
3927 			      tds->nfsdev_mdsfsid.val[0] &&
3928 			      mp->mnt_stat.f_fsid.val[1] ==
3929 			      tds->nfsdev_mdsfsid.val[1]))) {
3930 				dsdir[mirrorcnt] = i;
3931 				dvp[mirrorcnt] = tds->nfsdev_dsdir[i];
3932 				mirrorcnt++;
3933 				if (mirrorcnt >= nfsrv_maxpnfsmirror)
3934 					break;
3935 			}
3936 		}
3937 	}
3938 	/* Put at end of list to implement round-robin usage. */
3939 	TAILQ_REMOVE(&nfsrv_devidhead, ds, nfsdev_list);
3940 	TAILQ_INSERT_TAIL(&nfsrv_devidhead, ds, nfsdev_list);
3941 	NFSDDSUNLOCK();
3942 	dsc = NULL;
3943 	if (mirrorcnt > 1)
3944 		tdsc = dsc = malloc(sizeof(*dsc) * (mirrorcnt - 1), M_TEMP,
3945 		    M_WAITOK | M_ZERO);
3946 	tpf = pf = malloc(sizeof(*pf) * nfsrv_maxpnfsmirror, M_TEMP, M_WAITOK |
3947 	    M_ZERO);
3948 
3949 	error = nfsvno_getfh(vp, &fh, p);
3950 	if (error == 0)
3951 		error = VOP_GETATTR(vp, &va, cred);
3952 	if (error == 0) {
3953 		/* Set the attributes for "vp" to Setattr the DS vp. */
3954 		vauid = va.va_uid;
3955 		vagid = va.va_gid;
3956 		vamode = va.va_mode;
3957 		VATTR_NULL(&va);
3958 		va.va_uid = vauid;
3959 		va.va_gid = vagid;
3960 		va.va_mode = vamode;
3961 		va.va_size = 0;
3962 	} else
3963 		printf("pNFS: pnfscreate getfh+attr=%d\n", error);
3964 
3965 	NFSD_DEBUG(4, "nfsrv_pnfscreate: cruid=%d crgid=%d\n", cred->cr_uid,
3966 	    cred->cr_gid);
3967 	/* Make data file name based on FH. */
3968 	tcred = newnfs_getcred();
3969 
3970 	/*
3971 	 * Create the file on each DS mirror, using kernel process(es) for the
3972 	 * additional mirrors.
3973 	 */
3974 	failpos = -1;
3975 	for (i = 0; i < mirrorcnt - 1 && error == 0; i++, tpf++, tdsc++) {
3976 		tpf->dsf_dir = dsdir[i];
3977 		tdsc->tcred = tcred;
3978 		tdsc->p = p;
3979 		tdsc->pf = tpf;
3980 		tdsc->createva = *vap;
3981 		NFSBCOPY(&fh, &tdsc->fh, sizeof(fh));
3982 		tdsc->va = va;
3983 		tdsc->dvp = dvp[i];
3984 		tdsc->done = 0;
3985 		tdsc->inprog = 0;
3986 		tdsc->err = 0;
3987 		ret = EIO;
3988 		if (nfs_pnfsiothreads != 0) {
3989 			ret = nfs_pnfsio(start_dscreate, tdsc);
3990 			NFSD_DEBUG(4, "nfsrv_pnfscreate: nfs_pnfsio=%d\n", ret);
3991 		}
3992 		if (ret != 0) {
3993 			ret = nfsrv_dscreate(dvp[i], vap, &va, &fh, tpf, NULL,
3994 			    NULL, tcred, p, NULL);
3995 			if (ret != 0) {
3996 				KASSERT(error == 0, ("nfsrv_dscreate err=%d",
3997 				    error));
3998 				if (failpos == -1 && nfsds_failerr(ret))
3999 					failpos = i;
4000 				else
4001 					error = ret;
4002 			}
4003 		}
4004 	}
4005 	if (error == 0) {
4006 		tpf->dsf_dir = dsdir[mirrorcnt - 1];
4007 		error = nfsrv_dscreate(dvp[mirrorcnt - 1], vap, &va, &fh, tpf,
4008 		    &dsattr, NULL, tcred, p, NULL);
4009 		if (failpos == -1 && mirrorcnt > 1 && nfsds_failerr(error)) {
4010 			failpos = mirrorcnt - 1;
4011 			error = 0;
4012 		}
4013 	}
4014 	timo = hz / 50;		/* Wait for 20msec. */
4015 	if (timo < 1)
4016 		timo = 1;
4017 	/* Wait for kernel task(s) to complete. */
4018 	for (tdsc = dsc, i = 0; i < mirrorcnt - 1; i++, tdsc++) {
4019 		while (tdsc->inprog != 0 && tdsc->done == 0)
4020 			tsleep(&tdsc->tsk, PVFS, "srvdcr", timo);
4021 		if (tdsc->err != 0) {
4022 			if (failpos == -1 && nfsds_failerr(tdsc->err))
4023 				failpos = i;
4024 			else if (error == 0)
4025 				error = tdsc->err;
4026 		}
4027 	}
4028 
4029 	/*
4030 	 * If failpos has been set, that mirror has failed, so it needs
4031 	 * to be disabled.
4032 	 */
4033 	if (failpos >= 0) {
4034 		nmp = VFSTONFS(dvp[failpos]->v_mount);
4035 		NFSLOCKMNT(nmp);
4036 		if ((nmp->nm_privflag & (NFSMNTP_FORCEDISM |
4037 		     NFSMNTP_CANCELRPCS)) == 0) {
4038 			nmp->nm_privflag |= NFSMNTP_CANCELRPCS;
4039 			NFSUNLOCKMNT(nmp);
4040 			ds = nfsrv_deldsnmp(PNFSDOP_DELDSSERVER, nmp, p);
4041 			NFSD_DEBUG(4, "dscreatfail fail=%d ds=%p\n", failpos,
4042 			    ds);
4043 			if (ds != NULL)
4044 				nfsrv_killrpcs(nmp);
4045 			NFSLOCKMNT(nmp);
4046 			nmp->nm_privflag &= ~NFSMNTP_CANCELRPCS;
4047 			wakeup(nmp);
4048 		}
4049 		NFSUNLOCKMNT(nmp);
4050 	}
4051 
4052 	NFSFREECRED(tcred);
4053 	if (error == 0) {
4054 		ASSERT_VOP_ELOCKED(vp, "nfsrv_pnfscreate vp");
4055 
4056 		NFSD_DEBUG(4, "nfsrv_pnfscreate: mirrorcnt=%d maxmirror=%d\n",
4057 		    mirrorcnt, nfsrv_maxpnfsmirror);
4058 		/*
4059 		 * For all mirrors that couldn't be created, fill in the
4060 		 * *pf structure, but with an IP address == 0.0.0.0.
4061 		 */
4062 		tpf = pf + mirrorcnt;
4063 		for (i = mirrorcnt; i < nfsrv_maxpnfsmirror; i++, tpf++) {
4064 			*tpf = *pf;
4065 			tpf->dsf_sin.sin_family = AF_INET;
4066 			tpf->dsf_sin.sin_len = sizeof(struct sockaddr_in);
4067 			tpf->dsf_sin.sin_addr.s_addr = 0;
4068 			tpf->dsf_sin.sin_port = 0;
4069 		}
4070 
4071 		error = vn_extattr_set(vp, IO_NODELOCKED,
4072 		    EXTATTR_NAMESPACE_SYSTEM, "pnfsd.dsfile",
4073 		    sizeof(*pf) * nfsrv_maxpnfsmirror, (char *)pf, p);
4074 		if (error == 0)
4075 			error = vn_extattr_set(vp, IO_NODELOCKED,
4076 			    EXTATTR_NAMESPACE_SYSTEM, "pnfsd.dsattr",
4077 			    sizeof(dsattr), (char *)&dsattr, p);
4078 		if (error != 0)
4079 			printf("pNFS: pnfscreate setextattr=%d\n",
4080 			    error);
4081 	} else
4082 		printf("pNFS: pnfscreate=%d\n", error);
4083 	free(pf, M_TEMP);
4084 	free(dsc, M_TEMP);
4085 }
4086 
4087 /*
4088  * Get the information needed to remove the pNFS Data Server file from the
4089  * Metadata file.  Upon success, ddvp is set non-NULL to the locked
4090  * DS directory vnode.  The caller must unlock *ddvp when done with it.
4091  */
4092 static void
4093 nfsrv_pnfsremovesetup(struct vnode *vp, NFSPROC_T *p, struct vnode **dvpp,
4094     int *mirrorcntp, char *fname, fhandle_t *fhp)
4095 {
4096 	struct vattr va;
4097 	struct ucred *tcred;
4098 	char *buf;
4099 	int buflen, error;
4100 
4101 	dvpp[0] = NULL;
4102 	/* If not an exported regular file or not a pNFS server, just return. */
4103 	if (vp->v_type != VREG || (vp->v_mount->mnt_flag & MNT_EXPORTED) == 0 ||
4104 	    nfsrv_devidcnt == 0)
4105 		return;
4106 
4107 	/* Check to see if this is the last hard link. */
4108 	tcred = newnfs_getcred();
4109 	error = VOP_GETATTR(vp, &va, tcred);
4110 	NFSFREECRED(tcred);
4111 	if (error != 0) {
4112 		printf("pNFS: nfsrv_pnfsremovesetup getattr=%d\n", error);
4113 		return;
4114 	}
4115 	if (va.va_nlink > 1)
4116 		return;
4117 
4118 	error = nfsvno_getfh(vp, fhp, p);
4119 	if (error != 0) {
4120 		printf("pNFS: nfsrv_pnfsremovesetup getfh=%d\n", error);
4121 		return;
4122 	}
4123 
4124 	buflen = 1024;
4125 	buf = malloc(buflen, M_TEMP, M_WAITOK);
4126 	/* Get the directory vnode for the DS mount and the file handle. */
4127 	error = nfsrv_dsgetsockmnt(vp, 0, buf, &buflen, mirrorcntp, p, dvpp,
4128 	    NULL, NULL, fname, NULL, NULL, NULL, NULL, NULL);
4129 	free(buf, M_TEMP);
4130 	if (error != 0)
4131 		printf("pNFS: nfsrv_pnfsremovesetup getsockmnt=%d\n", error);
4132 }
4133 
4134 /*
4135  * Remove a DS data file for nfsrv_pnfsremove(). Called for each mirror.
4136  * The arguments are in a structure, so that they can be passed through
4137  * taskqueue for a kernel process to execute this function.
4138  */
4139 struct nfsrvdsremove {
4140 	int			done;
4141 	int			inprog;
4142 	struct task		tsk;
4143 	struct ucred		*tcred;
4144 	struct vnode		*dvp;
4145 	NFSPROC_T		*p;
4146 	int			err;
4147 	char			fname[PNFS_FILENAME_LEN + 1];
4148 };
4149 
4150 static int
4151 nfsrv_dsremove(struct vnode *dvp, char *fname, struct ucred *tcred,
4152     NFSPROC_T *p)
4153 {
4154 	struct nameidata named;
4155 	struct vnode *nvp;
4156 	char *bufp;
4157 	u_long *hashp;
4158 	int error;
4159 
4160 	error = NFSVOPLOCK(dvp, LK_EXCLUSIVE);
4161 	if (error != 0)
4162 		return (error);
4163 	named.ni_cnd.cn_nameiop = DELETE;
4164 	named.ni_cnd.cn_lkflags = LK_EXCLUSIVE | LK_RETRY;
4165 	named.ni_cnd.cn_cred = tcred;
4166 	named.ni_cnd.cn_thread = p;
4167 	named.ni_cnd.cn_flags = ISLASTCN | LOCKPARENT | LOCKLEAF | SAVENAME;
4168 	nfsvno_setpathbuf(&named, &bufp, &hashp);
4169 	named.ni_cnd.cn_nameptr = bufp;
4170 	named.ni_cnd.cn_namelen = strlen(fname);
4171 	strlcpy(bufp, fname, NAME_MAX);
4172 	NFSD_DEBUG(4, "nfsrv_pnfsremove: filename=%s\n", bufp);
4173 	error = VOP_LOOKUP(dvp, &nvp, &named.ni_cnd);
4174 	NFSD_DEBUG(4, "nfsrv_pnfsremove: aft LOOKUP=%d\n", error);
4175 	if (error == 0) {
4176 		error = VOP_REMOVE(dvp, nvp, &named.ni_cnd);
4177 		vput(nvp);
4178 	}
4179 	NFSVOPUNLOCK(dvp, 0);
4180 	nfsvno_relpathbuf(&named);
4181 	if (error != 0)
4182 		printf("pNFS: nfsrv_pnfsremove failed=%d\n", error);
4183 	return (error);
4184 }
4185 
4186 /*
4187  * Start up the thread that will execute nfsrv_dsremove().
4188  */
4189 static void
4190 start_dsremove(void *arg, int pending)
4191 {
4192 	struct nfsrvdsremove *dsrm;
4193 
4194 	dsrm = (struct nfsrvdsremove *)arg;
4195 	dsrm->err = nfsrv_dsremove(dsrm->dvp, dsrm->fname, dsrm->tcred,
4196 	    dsrm->p);
4197 	dsrm->done = 1;
4198 	NFSD_DEBUG(4, "start_dsremove: err=%d\n", dsrm->err);
4199 }
4200 
4201 /*
4202  * Remove a pNFS data file from a Data Server.
4203  * nfsrv_pnfsremovesetup() must have been called before the MDS file was
4204  * removed to set up the dvp and fill in the FH.
4205  */
4206 static void
4207 nfsrv_pnfsremove(struct vnode **dvp, int mirrorcnt, char *fname, fhandle_t *fhp,
4208     NFSPROC_T *p)
4209 {
4210 	struct ucred *tcred;
4211 	struct nfsrvdsremove *dsrm, *tdsrm;
4212 	struct nfsdevice *ds;
4213 	struct nfsmount *nmp;
4214 	int failpos, i, ret, timo;
4215 
4216 	tcred = newnfs_getcred();
4217 	dsrm = NULL;
4218 	if (mirrorcnt > 1)
4219 		dsrm = malloc(sizeof(*dsrm) * mirrorcnt - 1, M_TEMP, M_WAITOK);
4220 	/*
4221 	 * Remove the file on each DS mirror, using kernel process(es) for the
4222 	 * additional mirrors.
4223 	 */
4224 	failpos = -1;
4225 	for (tdsrm = dsrm, i = 0; i < mirrorcnt - 1; i++, tdsrm++) {
4226 		tdsrm->tcred = tcred;
4227 		tdsrm->p = p;
4228 		tdsrm->dvp = dvp[i];
4229 		strlcpy(tdsrm->fname, fname, PNFS_FILENAME_LEN + 1);
4230 		tdsrm->inprog = 0;
4231 		tdsrm->done = 0;
4232 		tdsrm->err = 0;
4233 		ret = EIO;
4234 		if (nfs_pnfsiothreads != 0) {
4235 			ret = nfs_pnfsio(start_dsremove, tdsrm);
4236 			NFSD_DEBUG(4, "nfsrv_pnfsremove: nfs_pnfsio=%d\n", ret);
4237 		}
4238 		if (ret != 0) {
4239 			ret = nfsrv_dsremove(dvp[i], fname, tcred, p);
4240 			if (failpos == -1 && nfsds_failerr(ret))
4241 				failpos = i;
4242 		}
4243 	}
4244 	ret = nfsrv_dsremove(dvp[mirrorcnt - 1], fname, tcred, p);
4245 	if (failpos == -1 && mirrorcnt > 1 && nfsds_failerr(ret))
4246 		failpos = mirrorcnt - 1;
4247 	timo = hz / 50;		/* Wait for 20msec. */
4248 	if (timo < 1)
4249 		timo = 1;
4250 	/* Wait for kernel task(s) to complete. */
4251 	for (tdsrm = dsrm, i = 0; i < mirrorcnt - 1; i++, tdsrm++) {
4252 		while (tdsrm->inprog != 0 && tdsrm->done == 0)
4253 			tsleep(&tdsrm->tsk, PVFS, "srvdsrm", timo);
4254 		if (failpos == -1 && nfsds_failerr(tdsrm->err))
4255 			failpos = i;
4256 	}
4257 
4258 	/*
4259 	 * If failpos has been set, that mirror has failed, so it needs
4260 	 * to be disabled.
4261 	 */
4262 	if (failpos >= 0) {
4263 		nmp = VFSTONFS(dvp[failpos]->v_mount);
4264 		NFSLOCKMNT(nmp);
4265 		if ((nmp->nm_privflag & (NFSMNTP_FORCEDISM |
4266 		     NFSMNTP_CANCELRPCS)) == 0) {
4267 			nmp->nm_privflag |= NFSMNTP_CANCELRPCS;
4268 			NFSUNLOCKMNT(nmp);
4269 			ds = nfsrv_deldsnmp(PNFSDOP_DELDSSERVER, nmp, p);
4270 			NFSD_DEBUG(4, "dsremovefail fail=%d ds=%p\n", failpos,
4271 			    ds);
4272 			if (ds != NULL)
4273 				nfsrv_killrpcs(nmp);
4274 			NFSLOCKMNT(nmp);
4275 			nmp->nm_privflag &= ~NFSMNTP_CANCELRPCS;
4276 			wakeup(nmp);
4277 		}
4278 		NFSUNLOCKMNT(nmp);
4279 	}
4280 
4281 	/* Get rid all layouts for the file. */
4282 	nfsrv_freefilelayouts(fhp);
4283 
4284 	NFSFREECRED(tcred);
4285 	free(dsrm, M_TEMP);
4286 }
4287 
4288 /*
4289  * Generate a file name based on the file handle and put it in *bufp.
4290  * Return the number of bytes generated.
4291  */
4292 static int
4293 nfsrv_putfhname(fhandle_t *fhp, char *bufp)
4294 {
4295 	int i;
4296 	uint8_t *cp;
4297 	const uint8_t *hexdigits = "0123456789abcdef";
4298 
4299 	cp = (uint8_t *)fhp;
4300 	for (i = 0; i < sizeof(*fhp); i++) {
4301 		bufp[2 * i] = hexdigits[(*cp >> 4) & 0xf];
4302 		bufp[2 * i + 1] = hexdigits[*cp++ & 0xf];
4303 	}
4304 	bufp[2 * i] = '\0';
4305 	return (2 * i);
4306 }
4307 
4308 /*
4309  * Update the Metadata file's attributes from the DS file when a Read/Write
4310  * layout is returned.
4311  * Basically just call nfsrv_proxyds() with procedure == NFSPROC_LAYOUTRETURN
4312  * so that it does a nfsrv_getattrdsrpc() and nfsrv_setextattr() on the DS file.
4313  */
4314 int
4315 nfsrv_updatemdsattr(struct vnode *vp, struct nfsvattr *nap, NFSPROC_T *p)
4316 {
4317 	struct ucred *tcred;
4318 	int error;
4319 
4320 	/* Do this as root so that it won't fail with EACCES. */
4321 	tcred = newnfs_getcred();
4322 	error = nfsrv_proxyds(NULL, vp, 0, 0, tcred, p, NFSPROC_LAYOUTRETURN,
4323 	    NULL, NULL, NULL, nap, NULL);
4324 	NFSFREECRED(tcred);
4325 	return (error);
4326 }
4327 
4328 /*
4329  * Set the NFSv4 ACL on the DS file to the same ACL as the MDS file.
4330  */
4331 static int
4332 nfsrv_dssetacl(struct vnode *vp, struct acl *aclp, struct ucred *cred,
4333     NFSPROC_T *p)
4334 {
4335 	int error;
4336 
4337 	error = nfsrv_proxyds(NULL, vp, 0, 0, cred, p, NFSPROC_SETACL,
4338 	    NULL, NULL, NULL, NULL, aclp);
4339 	return (error);
4340 }
4341 
4342 static int
4343 nfsrv_proxyds(struct nfsrv_descript *nd, struct vnode *vp, off_t off, int cnt,
4344     struct ucred *cred, struct thread *p, int ioproc, struct mbuf **mpp,
4345     char *cp, struct mbuf **mpp2, struct nfsvattr *nap, struct acl *aclp)
4346 {
4347 	struct nfsmount *nmp[NFSDEV_MAXMIRRORS], *failnmp;
4348 	fhandle_t fh[NFSDEV_MAXMIRRORS];
4349 	struct vnode *dvp[NFSDEV_MAXMIRRORS];
4350 	struct nfsdevice *ds;
4351 	struct pnfsdsattr dsattr;
4352 	char *buf;
4353 	int buflen, error, failpos, i, mirrorcnt, origmircnt, trycnt;
4354 
4355 	NFSD_DEBUG(4, "in nfsrv_proxyds\n");
4356 	/*
4357 	 * If not a regular file, not exported or not a pNFS server,
4358 	 * just return ENOENT.
4359 	 */
4360 	if (vp->v_type != VREG || (vp->v_mount->mnt_flag & MNT_EXPORTED) == 0 ||
4361 	    nfsrv_devidcnt == 0)
4362 		return (ENOENT);
4363 
4364 	buflen = 1024;
4365 	buf = malloc(buflen, M_TEMP, M_WAITOK);
4366 	error = 0;
4367 
4368 	/*
4369 	 * For Getattr, get the Change attribute (va_filerev) and size (va_size)
4370 	 * from the MetaData file's extended attribute.
4371 	 */
4372 	if (ioproc == NFSPROC_GETATTR) {
4373 		error = vn_extattr_get(vp, IO_NODELOCKED,
4374 		    EXTATTR_NAMESPACE_SYSTEM, "pnfsd.dsattr", &buflen, buf,
4375 		    p);
4376 		if (error == 0 && buflen != sizeof(dsattr))
4377 			error = ENXIO;
4378 		if (error == 0) {
4379 			NFSBCOPY(buf, &dsattr, buflen);
4380 			nap->na_filerev = dsattr.dsa_filerev;
4381 			nap->na_size = dsattr.dsa_size;
4382 			nap->na_atime = dsattr.dsa_atime;
4383 			nap->na_mtime = dsattr.dsa_mtime;
4384 
4385 			/*
4386 			 * If nfsrv_pnfsgetdsattr is 0 or nfsrv_checkdsattr()
4387 			 * returns 0, just return now.  nfsrv_checkdsattr()
4388 			 * returns 0 if there is no Read/Write layout
4389 			 * plus either an Open/Write_access or Write
4390 			 * delegation issued to a client for the file.
4391 			 */
4392 			if (nfsrv_pnfsgetdsattr == 0 ||
4393 			    nfsrv_checkdsattr(nd, vp, p) == 0) {
4394 				free(buf, M_TEMP);
4395 				return (error);
4396 			}
4397 		}
4398 
4399 		/*
4400 		 * Clear ENOATTR so the code below will attempt to do a
4401 		 * nfsrv_getattrdsrpc() to get the attributes and (re)create
4402 		 * the extended attribute.
4403 		 */
4404 		if (error == ENOATTR)
4405 			error = 0;
4406 	}
4407 
4408 	origmircnt = -1;
4409 	trycnt = 0;
4410 tryagain:
4411 	if (error == 0) {
4412 		buflen = 1024;
4413 		if (ioproc == NFSPROC_READDS && NFSVOPISLOCKED(vp) ==
4414 		    LK_EXCLUSIVE)
4415 			printf("nfsrv_proxyds: Readds vp exclusively locked\n");
4416 		error = nfsrv_dsgetsockmnt(vp, LK_SHARED, buf, &buflen,
4417 		    &mirrorcnt, p, dvp, fh, NULL, NULL, NULL, NULL, NULL,
4418 		    NULL, NULL);
4419 		if (error == 0) {
4420 			for (i = 0; i < mirrorcnt; i++)
4421 				nmp[i] = VFSTONFS(dvp[i]->v_mount);
4422 		} else
4423 			printf("pNFS: proxy getextattr sockaddr=%d\n", error);
4424 	} else
4425 		printf("pNFS: nfsrv_dsgetsockmnt=%d\n", error);
4426 	if (error == 0) {
4427 		failpos = -1;
4428 		if (origmircnt == -1)
4429 			origmircnt = mirrorcnt;
4430 		/*
4431 		 * If failpos is set to a mirror#, then that mirror has
4432 		 * failed and will be disabled. For Read and Getattr, the
4433 		 * function only tries one mirror, so if that mirror has
4434 		 * failed, it will need to be retried. As such, increment
4435 		 * tryitagain for these cases.
4436 		 * For Write, Setattr and Setacl, the function tries all
4437 		 * mirrors and will not return an error for the case where
4438 		 * one mirror has failed. For these cases, the functioning
4439 		 * mirror(s) will have been modified, so a retry isn't
4440 		 * necessary. These functions will set failpos for the
4441 		 * failed mirror#.
4442 		 */
4443 		if (ioproc == NFSPROC_READDS) {
4444 			error = nfsrv_readdsrpc(fh, off, cnt, cred, p, nmp[0],
4445 			    mpp, mpp2);
4446 			if (nfsds_failerr(error) && mirrorcnt > 1) {
4447 				/*
4448 				 * Setting failpos will cause the mirror
4449 				 * to be disabled and then a retry of this
4450 				 * read is required.
4451 				 */
4452 				failpos = 0;
4453 				error = 0;
4454 				trycnt++;
4455 			}
4456 		} else if (ioproc == NFSPROC_WRITEDS)
4457 			error = nfsrv_writedsrpc(fh, off, cnt, cred, p, vp,
4458 			    &nmp[0], mirrorcnt, mpp, cp, &failpos);
4459 		else if (ioproc == NFSPROC_SETATTR)
4460 			error = nfsrv_setattrdsrpc(fh, cred, p, vp, &nmp[0],
4461 			    mirrorcnt, nap, &failpos);
4462 		else if (ioproc == NFSPROC_SETACL)
4463 			error = nfsrv_setacldsrpc(fh, cred, p, vp, &nmp[0],
4464 			    mirrorcnt, aclp, &failpos);
4465 		else {
4466 			error = nfsrv_getattrdsrpc(&fh[mirrorcnt - 1], cred, p,
4467 			    vp, nmp[mirrorcnt - 1], nap);
4468 			if (nfsds_failerr(error) && mirrorcnt > 1) {
4469 				/*
4470 				 * Setting failpos will cause the mirror
4471 				 * to be disabled and then a retry of this
4472 				 * getattr is required.
4473 				 */
4474 				failpos = mirrorcnt - 1;
4475 				error = 0;
4476 				trycnt++;
4477 			}
4478 		}
4479 		ds = NULL;
4480 		if (failpos >= 0) {
4481 			failnmp = nmp[failpos];
4482 			NFSLOCKMNT(failnmp);
4483 			if ((failnmp->nm_privflag & (NFSMNTP_FORCEDISM |
4484 			     NFSMNTP_CANCELRPCS)) == 0) {
4485 				failnmp->nm_privflag |= NFSMNTP_CANCELRPCS;
4486 				NFSUNLOCKMNT(failnmp);
4487 				ds = nfsrv_deldsnmp(PNFSDOP_DELDSSERVER,
4488 				    failnmp, p);
4489 				NFSD_DEBUG(4, "dsldsnmp fail=%d ds=%p\n",
4490 				    failpos, ds);
4491 				if (ds != NULL)
4492 					nfsrv_killrpcs(failnmp);
4493 				NFSLOCKMNT(failnmp);
4494 				failnmp->nm_privflag &= ~NFSMNTP_CANCELRPCS;
4495 				wakeup(failnmp);
4496 			}
4497 			NFSUNLOCKMNT(failnmp);
4498 		}
4499 		for (i = 0; i < mirrorcnt; i++)
4500 			NFSVOPUNLOCK(dvp[i], 0);
4501 		NFSD_DEBUG(4, "nfsrv_proxyds: aft RPC=%d trya=%d\n", error,
4502 		    trycnt);
4503 		/* Try the Read/Getattr again if a mirror was deleted. */
4504 		if (ds != NULL && trycnt > 0 && trycnt < origmircnt)
4505 			goto tryagain;
4506 	} else {
4507 		/* Return ENOENT for any Extended Attribute error. */
4508 		error = ENOENT;
4509 	}
4510 	free(buf, M_TEMP);
4511 	NFSD_DEBUG(4, "nfsrv_proxyds: error=%d\n", error);
4512 	return (error);
4513 }
4514 
4515 /*
4516  * Get the DS mount point, fh and directory from the "pnfsd.dsfile" extended
4517  * attribute.
4518  * newnmpp - If it points to a non-NULL nmp, that is the destination and needs
4519  *           to be checked.  If it points to a NULL nmp, then it returns
4520  *           a suitable destination.
4521  * curnmp - If non-NULL, it is the source mount for the copy.
4522  */
4523 int
4524 nfsrv_dsgetsockmnt(struct vnode *vp, int lktype, char *buf, int *buflenp,
4525     int *mirrorcntp, NFSPROC_T *p, struct vnode **dvpp, fhandle_t *fhp,
4526     char *devid, char *fnamep, struct vnode **nvpp, struct nfsmount **newnmpp,
4527     struct nfsmount *curnmp, int *ippos, int *dsdirp)
4528 {
4529 	struct vnode *dvp, *nvp, **tdvpp;
4530 	struct mount *mp;
4531 	struct nfsmount *nmp, *newnmp;
4532 	struct sockaddr *sad;
4533 	struct sockaddr_in *sin;
4534 	struct nfsdevice *ds, *tds, *fndds;
4535 	struct pnfsdsfile *pf;
4536 	uint32_t dsdir;
4537 	int error, fhiszero, fnd, gotone, i, mirrorcnt;
4538 
4539 	ASSERT_VOP_LOCKED(vp, "nfsrv_dsgetsockmnt vp");
4540 	*mirrorcntp = 1;
4541 	tdvpp = dvpp;
4542 	if (nvpp != NULL)
4543 		*nvpp = NULL;
4544 	if (dvpp != NULL)
4545 		*dvpp = NULL;
4546 	if (ippos != NULL)
4547 		*ippos = -1;
4548 	if (newnmpp != NULL)
4549 		newnmp = *newnmpp;
4550 	else
4551 		newnmp = NULL;
4552 	mp = vp->v_mount;
4553 	error = vn_extattr_get(vp, IO_NODELOCKED, EXTATTR_NAMESPACE_SYSTEM,
4554 	    "pnfsd.dsfile", buflenp, buf, p);
4555 	mirrorcnt = *buflenp / sizeof(*pf);
4556 	if (error == 0 && (mirrorcnt < 1 || mirrorcnt > NFSDEV_MAXMIRRORS ||
4557 	    *buflenp != sizeof(*pf) * mirrorcnt))
4558 		error = ENOATTR;
4559 
4560 	pf = (struct pnfsdsfile *)buf;
4561 	/* If curnmp != NULL, check for a match in the mirror list. */
4562 	if (curnmp != NULL && error == 0) {
4563 		fnd = 0;
4564 		for (i = 0; i < mirrorcnt; i++, pf++) {
4565 			sad = (struct sockaddr *)&pf->dsf_sin;
4566 			if (nfsaddr2_match(sad, curnmp->nm_nam)) {
4567 				if (ippos != NULL)
4568 					*ippos = i;
4569 				fnd = 1;
4570 				break;
4571 			}
4572 		}
4573 		if (fnd == 0)
4574 			error = ENXIO;
4575 	}
4576 
4577 	gotone = 0;
4578 	pf = (struct pnfsdsfile *)buf;
4579 	NFSD_DEBUG(4, "nfsrv_dsgetsockmnt: mirrorcnt=%d err=%d\n", mirrorcnt,
4580 	    error);
4581 	for (i = 0; i < mirrorcnt && error == 0; i++, pf++) {
4582 		fhiszero = 0;
4583 		sad = (struct sockaddr *)&pf->dsf_sin;
4584 		sin = &pf->dsf_sin;
4585 		dsdir = pf->dsf_dir;
4586 		if (dsdir >= nfsrv_dsdirsize) {
4587 			printf("nfsrv_dsgetsockmnt: dsdir=%d\n", dsdir);
4588 			error = ENOATTR;
4589 		} else if (nvpp != NULL && newnmp != NULL &&
4590 		    nfsaddr2_match(sad, newnmp->nm_nam))
4591 			error = EEXIST;
4592 		if (error == 0) {
4593 			if (ippos != NULL && curnmp == NULL &&
4594 			    sad->sa_family == AF_INET &&
4595 			    sin->sin_addr.s_addr == 0)
4596 				*ippos = i;
4597 			if (NFSBCMP(&zerofh, &pf->dsf_fh, sizeof(zerofh)) == 0)
4598 				fhiszero = 1;
4599 			/* Use the socket address to find the mount point. */
4600 			fndds = NULL;
4601 			NFSDDSLOCK();
4602 			/* Find a match for the IP address. */
4603 			TAILQ_FOREACH(ds, &nfsrv_devidhead, nfsdev_list) {
4604 				if (ds->nfsdev_nmp != NULL) {
4605 					dvp = ds->nfsdev_dvp;
4606 					nmp = VFSTONFS(dvp->v_mount);
4607 					if (nmp != ds->nfsdev_nmp)
4608 						printf("different2 nmp %p %p\n",
4609 						    nmp, ds->nfsdev_nmp);
4610 					if (nfsaddr2_match(sad, nmp->nm_nam)) {
4611 						fndds = ds;
4612 						break;
4613 					}
4614 				}
4615 			}
4616 			if (fndds != NULL && newnmpp != NULL &&
4617 			    newnmp == NULL) {
4618 				/* Search for a place to make a mirror copy. */
4619 				TAILQ_FOREACH(tds, &nfsrv_devidhead,
4620 				    nfsdev_list) {
4621 					if (tds->nfsdev_nmp != NULL &&
4622 					    fndds != tds &&
4623 					    ((tds->nfsdev_mdsisset == 0 &&
4624 					      fndds->nfsdev_mdsisset == 0) ||
4625 					     (tds->nfsdev_mdsisset != 0 &&
4626 					      fndds->nfsdev_mdsisset != 0 &&
4627 					      tds->nfsdev_mdsfsid.val[0] ==
4628 					      mp->mnt_stat.f_fsid.val[0] &&
4629 					      tds->nfsdev_mdsfsid.val[1] ==
4630 					      mp->mnt_stat.f_fsid.val[1]))) {
4631 						*newnmpp = tds->nfsdev_nmp;
4632 						break;
4633 					}
4634 				}
4635 				if (tds != NULL) {
4636 					/*
4637 					 * Move this entry to the end of the
4638 					 * list, so it won't be selected as
4639 					 * easily the next time.
4640 					 */
4641 					TAILQ_REMOVE(&nfsrv_devidhead, tds,
4642 					    nfsdev_list);
4643 					TAILQ_INSERT_TAIL(&nfsrv_devidhead, tds,
4644 					    nfsdev_list);
4645 				}
4646 			}
4647 			NFSDDSUNLOCK();
4648 			if (fndds != NULL) {
4649 				dvp = fndds->nfsdev_dsdir[dsdir];
4650 				if (lktype != 0 || fhiszero != 0 ||
4651 				    (nvpp != NULL && *nvpp == NULL)) {
4652 					if (fhiszero != 0)
4653 						error = vn_lock(dvp,
4654 						    LK_EXCLUSIVE);
4655 					else if (lktype != 0)
4656 						error = vn_lock(dvp, lktype);
4657 					else
4658 						error = vn_lock(dvp, LK_SHARED);
4659 					/*
4660 					 * If the file handle is all 0's, try to
4661 					 * do a Lookup against the DS to acquire
4662 					 * it.
4663 					 * If dvpp == NULL or the Lookup fails,
4664 					 * unlock dvp after the call.
4665 					 */
4666 					if (error == 0 && (fhiszero != 0 ||
4667 					    (nvpp != NULL && *nvpp == NULL))) {
4668 						error = nfsrv_pnfslookupds(vp,
4669 						    dvp, pf, &nvp, p);
4670 						if (error == 0) {
4671 							if (fhiszero != 0)
4672 								nfsrv_pnfssetfh(
4673 								    vp, pf,
4674 								    devid,
4675 								    fnamep,
4676 								    nvp, p);
4677 							if (nvpp != NULL &&
4678 							    *nvpp == NULL) {
4679 								*nvpp = nvp;
4680 								*dsdirp = dsdir;
4681 							} else
4682 								vput(nvp);
4683 						}
4684 						if (error != 0 || lktype == 0)
4685 							NFSVOPUNLOCK(dvp, 0);
4686 					}
4687 				}
4688 				if (error == 0) {
4689 					gotone++;
4690 					NFSD_DEBUG(4, "gotone=%d\n", gotone);
4691 					if (devid != NULL) {
4692 						NFSBCOPY(fndds->nfsdev_deviceid,
4693 						    devid, NFSX_V4DEVICEID);
4694 						devid += NFSX_V4DEVICEID;
4695 					}
4696 					if (dvpp != NULL)
4697 						*tdvpp++ = dvp;
4698 					if (fhp != NULL)
4699 						NFSBCOPY(&pf->dsf_fh, fhp++,
4700 						    NFSX_MYFH);
4701 					if (fnamep != NULL && gotone == 1)
4702 						strlcpy(fnamep,
4703 						    pf->dsf_filename,
4704 						    sizeof(pf->dsf_filename));
4705 				} else
4706 					NFSD_DEBUG(4, "nfsrv_dsgetsockmnt "
4707 					    "err=%d\n", error);
4708 			}
4709 		}
4710 	}
4711 	if (error == 0 && gotone == 0)
4712 		error = ENOENT;
4713 
4714 	NFSD_DEBUG(4, "eo nfsrv_dsgetsockmnt: gotone=%d err=%d\n", gotone,
4715 	    error);
4716 	if (error == 0)
4717 		*mirrorcntp = gotone;
4718 	else {
4719 		if (gotone > 0 && dvpp != NULL) {
4720 			/*
4721 			 * If the error didn't occur on the first one and
4722 			 * dvpp != NULL, the one(s) prior to the failure will
4723 			 * have locked dvp's that need to be unlocked.
4724 			 */
4725 			for (i = 0; i < gotone; i++) {
4726 				NFSVOPUNLOCK(*dvpp, 0);
4727 				*dvpp++ = NULL;
4728 			}
4729 		}
4730 		/*
4731 		 * If it found the vnode to be copied from before a failure,
4732 		 * it needs to be vput()'d.
4733 		 */
4734 		if (nvpp != NULL && *nvpp != NULL) {
4735 			vput(*nvpp);
4736 			*nvpp = NULL;
4737 		}
4738 	}
4739 	return (error);
4740 }
4741 
4742 /*
4743  * Set the extended attribute for the Change attribute.
4744  */
4745 static int
4746 nfsrv_setextattr(struct vnode *vp, struct nfsvattr *nap, NFSPROC_T *p)
4747 {
4748 	struct pnfsdsattr dsattr;
4749 	int error;
4750 
4751 	ASSERT_VOP_ELOCKED(vp, "nfsrv_setextattr vp");
4752 	dsattr.dsa_filerev = nap->na_filerev;
4753 	dsattr.dsa_size = nap->na_size;
4754 	dsattr.dsa_atime = nap->na_atime;
4755 	dsattr.dsa_mtime = nap->na_mtime;
4756 	error = vn_extattr_set(vp, IO_NODELOCKED, EXTATTR_NAMESPACE_SYSTEM,
4757 	    "pnfsd.dsattr", sizeof(dsattr), (char *)&dsattr, p);
4758 	if (error != 0)
4759 		printf("pNFS: setextattr=%d\n", error);
4760 	return (error);
4761 }
4762 
4763 static int
4764 nfsrv_readdsrpc(fhandle_t *fhp, off_t off, int len, struct ucred *cred,
4765     NFSPROC_T *p, struct nfsmount *nmp, struct mbuf **mpp, struct mbuf **mpendp)
4766 {
4767 	uint32_t *tl;
4768 	struct nfsrv_descript *nd;
4769 	nfsv4stateid_t st;
4770 	struct mbuf *m, *m2;
4771 	int error = 0, retlen, tlen, trimlen;
4772 
4773 	NFSD_DEBUG(4, "in nfsrv_readdsrpc\n");
4774 	nd = malloc(sizeof(*nd), M_TEMP, M_WAITOK | M_ZERO);
4775 	*mpp = NULL;
4776 	/*
4777 	 * Use a stateid where other is an alternating 01010 pattern and
4778 	 * seqid is 0xffffffff.  This value is not defined as special by
4779 	 * the RFC and is used by the FreeBSD NFS server to indicate an
4780 	 * MDS->DS proxy operation.
4781 	 */
4782 	st.other[0] = 0x55555555;
4783 	st.other[1] = 0x55555555;
4784 	st.other[2] = 0x55555555;
4785 	st.seqid = 0xffffffff;
4786 	nfscl_reqstart(nd, NFSPROC_READDS, nmp, (u_int8_t *)fhp, sizeof(*fhp),
4787 	    NULL, NULL, 0, 0);
4788 	nfsm_stateidtom(nd, &st, NFSSTATEID_PUTSTATEID);
4789 	NFSM_BUILD(tl, uint32_t *, NFSX_UNSIGNED * 3);
4790 	txdr_hyper(off, tl);
4791 	*(tl + 2) = txdr_unsigned(len);
4792 	error = newnfs_request(nd, nmp, NULL, &nmp->nm_sockreq, NULL, p, cred,
4793 	    NFS_PROG, NFS_VER4, NULL, 1, NULL, NULL);
4794 	if (error != 0) {
4795 		free(nd, M_TEMP);
4796 		return (error);
4797 	}
4798 	if (nd->nd_repstat == 0) {
4799 		NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
4800 		NFSM_STRSIZ(retlen, len);
4801 		if (retlen > 0) {
4802 			/* Trim off the pre-data XDR from the mbuf chain. */
4803 			m = nd->nd_mrep;
4804 			while (m != NULL && m != nd->nd_md) {
4805 				if (m->m_next == nd->nd_md) {
4806 					m->m_next = NULL;
4807 					m_freem(nd->nd_mrep);
4808 					nd->nd_mrep = m = nd->nd_md;
4809 				} else
4810 					m = m->m_next;
4811 			}
4812 			if (m == NULL) {
4813 				printf("nfsrv_readdsrpc: busted mbuf list\n");
4814 				error = ENOENT;
4815 				goto nfsmout;
4816 			}
4817 
4818 			/*
4819 			 * Now, adjust first mbuf so that any XDR before the
4820 			 * read data is skipped over.
4821 			 */
4822 			trimlen = nd->nd_dpos - mtod(m, char *);
4823 			if (trimlen > 0) {
4824 				m->m_len -= trimlen;
4825 				NFSM_DATAP(m, trimlen);
4826 			}
4827 
4828 			/*
4829 			 * Truncate the mbuf chain at retlen bytes of data,
4830 			 * plus XDR padding that brings the length up to a
4831 			 * multiple of 4.
4832 			 */
4833 			tlen = NFSM_RNDUP(retlen);
4834 			do {
4835 				if (m->m_len >= tlen) {
4836 					m->m_len = tlen;
4837 					tlen = 0;
4838 					m2 = m->m_next;
4839 					m->m_next = NULL;
4840 					m_freem(m2);
4841 					break;
4842 				}
4843 				tlen -= m->m_len;
4844 				m = m->m_next;
4845 			} while (m != NULL);
4846 			if (tlen > 0) {
4847 				printf("nfsrv_readdsrpc: busted mbuf list\n");
4848 				error = ENOENT;
4849 				goto nfsmout;
4850 			}
4851 			*mpp = nd->nd_mrep;
4852 			*mpendp = m;
4853 			nd->nd_mrep = NULL;
4854 		}
4855 	} else
4856 		error = nd->nd_repstat;
4857 nfsmout:
4858 	/* If nd->nd_mrep is already NULL, this is a no-op. */
4859 	m_freem(nd->nd_mrep);
4860 	free(nd, M_TEMP);
4861 	NFSD_DEBUG(4, "nfsrv_readdsrpc error=%d\n", error);
4862 	return (error);
4863 }
4864 
4865 /*
4866  * Do a write RPC on a DS data file, using this structure for the arguments,
4867  * so that this function can be executed by a separate kernel process.
4868  */
4869 struct nfsrvwritedsdorpc {
4870 	int			done;
4871 	int			inprog;
4872 	struct task		tsk;
4873 	fhandle_t		fh;
4874 	off_t			off;
4875 	int			len;
4876 	struct nfsmount		*nmp;
4877 	struct ucred		*cred;
4878 	NFSPROC_T		*p;
4879 	struct mbuf		*m;
4880 	int			err;
4881 };
4882 
4883 static int
4884 nfsrv_writedsdorpc(struct nfsmount *nmp, fhandle_t *fhp, off_t off, int len,
4885     struct nfsvattr *nap, struct mbuf *m, struct ucred *cred, NFSPROC_T *p)
4886 {
4887 	uint32_t *tl;
4888 	struct nfsrv_descript *nd;
4889 	nfsattrbit_t attrbits;
4890 	nfsv4stateid_t st;
4891 	int commit, error, retlen;
4892 
4893 	nd = malloc(sizeof(*nd), M_TEMP, M_WAITOK | M_ZERO);
4894 	nfscl_reqstart(nd, NFSPROC_WRITE, nmp, (u_int8_t *)fhp,
4895 	    sizeof(fhandle_t), NULL, NULL, 0, 0);
4896 
4897 	/*
4898 	 * Use a stateid where other is an alternating 01010 pattern and
4899 	 * seqid is 0xffffffff.  This value is not defined as special by
4900 	 * the RFC and is used by the FreeBSD NFS server to indicate an
4901 	 * MDS->DS proxy operation.
4902 	 */
4903 	st.other[0] = 0x55555555;
4904 	st.other[1] = 0x55555555;
4905 	st.other[2] = 0x55555555;
4906 	st.seqid = 0xffffffff;
4907 	nfsm_stateidtom(nd, &st, NFSSTATEID_PUTSTATEID);
4908 	NFSM_BUILD(tl, u_int32_t *, NFSX_HYPER + 2 * NFSX_UNSIGNED);
4909 	txdr_hyper(off, tl);
4910 	tl += 2;
4911 	/*
4912 	 * Do all writes FileSync, since the server doesn't hold onto dirty
4913 	 * buffers.  Since clients should be accessing the DS servers directly
4914 	 * using the pNFS layouts, this just needs to work correctly as a
4915 	 * fallback.
4916 	 */
4917 	*tl++ = txdr_unsigned(NFSWRITE_FILESYNC);
4918 	*tl = txdr_unsigned(len);
4919 	NFSD_DEBUG(4, "nfsrv_writedsdorpc: len=%d\n", len);
4920 
4921 	/* Put data in mbuf chain. */
4922 	nd->nd_mb->m_next = m;
4923 
4924 	/* Set nd_mb and nd_bpos to end of data. */
4925 	while (m->m_next != NULL)
4926 		m = m->m_next;
4927 	nd->nd_mb = m;
4928 	nd->nd_bpos = mtod(m, char *) + m->m_len;
4929 	NFSD_DEBUG(4, "nfsrv_writedsdorpc: lastmb len=%d\n", m->m_len);
4930 
4931 	/* Do a Getattr for Size, Change and Modify Time. */
4932 	NFSZERO_ATTRBIT(&attrbits);
4933 	NFSSETBIT_ATTRBIT(&attrbits, NFSATTRBIT_SIZE);
4934 	NFSSETBIT_ATTRBIT(&attrbits, NFSATTRBIT_CHANGE);
4935 	NFSSETBIT_ATTRBIT(&attrbits, NFSATTRBIT_TIMEACCESS);
4936 	NFSSETBIT_ATTRBIT(&attrbits, NFSATTRBIT_TIMEMODIFY);
4937 	NFSM_BUILD(tl, u_int32_t *, NFSX_UNSIGNED);
4938 	*tl = txdr_unsigned(NFSV4OP_GETATTR);
4939 	(void) nfsrv_putattrbit(nd, &attrbits);
4940 	error = newnfs_request(nd, nmp, NULL, &nmp->nm_sockreq, NULL, p,
4941 	    cred, NFS_PROG, NFS_VER4, NULL, 1, NULL, NULL);
4942 	if (error != 0) {
4943 		free(nd, M_TEMP);
4944 		return (error);
4945 	}
4946 	NFSD_DEBUG(4, "nfsrv_writedsdorpc: aft writerpc=%d\n", nd->nd_repstat);
4947 	/* Get rid of weak cache consistency data for now. */
4948 	if ((nd->nd_flag & (ND_NOMOREDATA | ND_NFSV4 | ND_V4WCCATTR)) ==
4949 	    (ND_NFSV4 | ND_V4WCCATTR)) {
4950 		error = nfsv4_loadattr(nd, NULL, nap, NULL, NULL, 0, NULL, NULL,
4951 		    NULL, NULL, NULL, 0, NULL, NULL, NULL, NULL, NULL);
4952 		NFSD_DEBUG(4, "nfsrv_writedsdorpc: wcc attr=%d\n", error);
4953 		if (error != 0)
4954 			goto nfsmout;
4955 		/*
4956 		 * Get rid of Op# and status for next op.
4957 		 */
4958 		NFSM_DISSECT(tl, uint32_t *, 2 * NFSX_UNSIGNED);
4959 		if (*++tl != 0)
4960 			nd->nd_flag |= ND_NOMOREDATA;
4961 	}
4962 	if (nd->nd_repstat == 0) {
4963 		NFSM_DISSECT(tl, uint32_t *, 2 * NFSX_UNSIGNED + NFSX_VERF);
4964 		retlen = fxdr_unsigned(int, *tl++);
4965 		commit = fxdr_unsigned(int, *tl);
4966 		if (commit != NFSWRITE_FILESYNC)
4967 			error = NFSERR_IO;
4968 		NFSD_DEBUG(4, "nfsrv_writedsdorpc:retlen=%d commit=%d err=%d\n",
4969 		    retlen, commit, error);
4970 	} else
4971 		error = nd->nd_repstat;
4972 	/* We have no use for the Write Verifier since we use FileSync. */
4973 
4974 	/*
4975 	 * Get the Change, Size, Access Time and Modify Time attributes and set
4976 	 * on the Metadata file, so its attributes will be what the file's
4977 	 * would be if it had been written.
4978 	 */
4979 	if (error == 0) {
4980 		NFSM_DISSECT(tl, uint32_t *, 2 * NFSX_UNSIGNED);
4981 		error = nfsv4_loadattr(nd, NULL, nap, NULL, NULL, 0, NULL, NULL,
4982 		    NULL, NULL, NULL, 0, NULL, NULL, NULL, NULL, NULL);
4983 	}
4984 	NFSD_DEBUG(4, "nfsrv_writedsdorpc: aft loadattr=%d\n", error);
4985 nfsmout:
4986 	m_freem(nd->nd_mrep);
4987 	free(nd, M_TEMP);
4988 	NFSD_DEBUG(4, "nfsrv_writedsdorpc error=%d\n", error);
4989 	return (error);
4990 }
4991 
4992 /*
4993  * Start up the thread that will execute nfsrv_writedsdorpc().
4994  */
4995 static void
4996 start_writedsdorpc(void *arg, int pending)
4997 {
4998 	struct nfsrvwritedsdorpc *drpc;
4999 
5000 	drpc = (struct nfsrvwritedsdorpc *)arg;
5001 	drpc->err = nfsrv_writedsdorpc(drpc->nmp, &drpc->fh, drpc->off,
5002 	    drpc->len, NULL, drpc->m, drpc->cred, drpc->p);
5003 	drpc->done = 1;
5004 	NFSD_DEBUG(4, "start_writedsdorpc: err=%d\n", drpc->err);
5005 }
5006 
5007 static int
5008 nfsrv_writedsrpc(fhandle_t *fhp, off_t off, int len, struct ucred *cred,
5009     NFSPROC_T *p, struct vnode *vp, struct nfsmount **nmpp, int mirrorcnt,
5010     struct mbuf **mpp, char *cp, int *failposp)
5011 {
5012 	struct nfsrvwritedsdorpc *drpc, *tdrpc;
5013 	struct nfsvattr na;
5014 	struct mbuf *m;
5015 	int error, i, offs, ret, timo;
5016 
5017 	NFSD_DEBUG(4, "in nfsrv_writedsrpc\n");
5018 	KASSERT(*mpp != NULL, ("nfsrv_writedsrpc: NULL mbuf chain"));
5019 	drpc = NULL;
5020 	if (mirrorcnt > 1)
5021 		tdrpc = drpc = malloc(sizeof(*drpc) * (mirrorcnt - 1), M_TEMP,
5022 		    M_WAITOK);
5023 
5024 	/* Calculate offset in mbuf chain that data starts. */
5025 	offs = cp - mtod(*mpp, char *);
5026 	NFSD_DEBUG(4, "nfsrv_writedsrpc: mcopy offs=%d len=%d\n", offs, len);
5027 
5028 	/*
5029 	 * Do the write RPC for every DS, using a separate kernel process
5030 	 * for every DS except the last one.
5031 	 */
5032 	error = 0;
5033 	for (i = 0; i < mirrorcnt - 1; i++, tdrpc++) {
5034 		tdrpc->done = 0;
5035 		NFSBCOPY(fhp, &tdrpc->fh, sizeof(*fhp));
5036 		tdrpc->off = off;
5037 		tdrpc->len = len;
5038 		tdrpc->nmp = *nmpp;
5039 		tdrpc->cred = cred;
5040 		tdrpc->p = p;
5041 		tdrpc->inprog = 0;
5042 		tdrpc->err = 0;
5043 		tdrpc->m = m_copym(*mpp, offs, NFSM_RNDUP(len), M_WAITOK);
5044 		ret = EIO;
5045 		if (nfs_pnfsiothreads != 0) {
5046 			ret = nfs_pnfsio(start_writedsdorpc, tdrpc);
5047 			NFSD_DEBUG(4, "nfsrv_writedsrpc: nfs_pnfsio=%d\n",
5048 			    ret);
5049 		}
5050 		if (ret != 0) {
5051 			ret = nfsrv_writedsdorpc(*nmpp, fhp, off, len, NULL,
5052 			    tdrpc->m, cred, p);
5053 			if (nfsds_failerr(ret) && *failposp == -1)
5054 				*failposp = i;
5055 			else if (error == 0 && ret != 0)
5056 				error = ret;
5057 		}
5058 		nmpp++;
5059 		fhp++;
5060 	}
5061 	m = m_copym(*mpp, offs, NFSM_RNDUP(len), M_WAITOK);
5062 	ret = nfsrv_writedsdorpc(*nmpp, fhp, off, len, &na, m, cred, p);
5063 	if (nfsds_failerr(ret) && *failposp == -1 && mirrorcnt > 1)
5064 		*failposp = mirrorcnt - 1;
5065 	else if (error == 0 && ret != 0)
5066 		error = ret;
5067 	if (error == 0)
5068 		error = nfsrv_setextattr(vp, &na, p);
5069 	NFSD_DEBUG(4, "nfsrv_writedsrpc: aft setextat=%d\n", error);
5070 	tdrpc = drpc;
5071 	timo = hz / 50;		/* Wait for 20msec. */
5072 	if (timo < 1)
5073 		timo = 1;
5074 	for (i = 0; i < mirrorcnt - 1; i++, tdrpc++) {
5075 		/* Wait for RPCs on separate threads to complete. */
5076 		while (tdrpc->inprog != 0 && tdrpc->done == 0)
5077 			tsleep(&tdrpc->tsk, PVFS, "srvwrds", timo);
5078 		if (nfsds_failerr(tdrpc->err) && *failposp == -1)
5079 			*failposp = i;
5080 		else if (error == 0 && tdrpc->err != 0)
5081 			error = tdrpc->err;
5082 	}
5083 	free(drpc, M_TEMP);
5084 	return (error);
5085 }
5086 
5087 static int
5088 nfsrv_setattrdsdorpc(fhandle_t *fhp, struct ucred *cred, NFSPROC_T *p,
5089     struct vnode *vp, struct nfsmount *nmp, struct nfsvattr *nap,
5090     struct nfsvattr *dsnap)
5091 {
5092 	uint32_t *tl;
5093 	struct nfsrv_descript *nd;
5094 	nfsv4stateid_t st;
5095 	nfsattrbit_t attrbits;
5096 	int error;
5097 
5098 	NFSD_DEBUG(4, "in nfsrv_setattrdsdorpc\n");
5099 	nd = malloc(sizeof(*nd), M_TEMP, M_WAITOK | M_ZERO);
5100 	/*
5101 	 * Use a stateid where other is an alternating 01010 pattern and
5102 	 * seqid is 0xffffffff.  This value is not defined as special by
5103 	 * the RFC and is used by the FreeBSD NFS server to indicate an
5104 	 * MDS->DS proxy operation.
5105 	 */
5106 	st.other[0] = 0x55555555;
5107 	st.other[1] = 0x55555555;
5108 	st.other[2] = 0x55555555;
5109 	st.seqid = 0xffffffff;
5110 	nfscl_reqstart(nd, NFSPROC_SETATTR, nmp, (u_int8_t *)fhp, sizeof(*fhp),
5111 	    NULL, NULL, 0, 0);
5112 	nfsm_stateidtom(nd, &st, NFSSTATEID_PUTSTATEID);
5113 	nfscl_fillsattr(nd, &nap->na_vattr, vp, NFSSATTR_FULL, 0);
5114 
5115 	/* Do a Getattr for Size, Change, Access Time and Modify Time. */
5116 	NFSZERO_ATTRBIT(&attrbits);
5117 	NFSSETBIT_ATTRBIT(&attrbits, NFSATTRBIT_SIZE);
5118 	NFSSETBIT_ATTRBIT(&attrbits, NFSATTRBIT_CHANGE);
5119 	NFSSETBIT_ATTRBIT(&attrbits, NFSATTRBIT_TIMEACCESS);
5120 	NFSSETBIT_ATTRBIT(&attrbits, NFSATTRBIT_TIMEMODIFY);
5121 	NFSM_BUILD(tl, u_int32_t *, NFSX_UNSIGNED);
5122 	*tl = txdr_unsigned(NFSV4OP_GETATTR);
5123 	(void) nfsrv_putattrbit(nd, &attrbits);
5124 	error = newnfs_request(nd, nmp, NULL, &nmp->nm_sockreq, NULL, p, cred,
5125 	    NFS_PROG, NFS_VER4, NULL, 1, NULL, NULL);
5126 	if (error != 0) {
5127 		free(nd, M_TEMP);
5128 		return (error);
5129 	}
5130 	NFSD_DEBUG(4, "nfsrv_setattrdsdorpc: aft setattrrpc=%d\n",
5131 	    nd->nd_repstat);
5132 	/* Get rid of weak cache consistency data for now. */
5133 	if ((nd->nd_flag & (ND_NOMOREDATA | ND_NFSV4 | ND_V4WCCATTR)) ==
5134 	    (ND_NFSV4 | ND_V4WCCATTR)) {
5135 		error = nfsv4_loadattr(nd, NULL, dsnap, NULL, NULL, 0, NULL,
5136 		    NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL, NULL, NULL);
5137 		NFSD_DEBUG(4, "nfsrv_setattrdsdorpc: wcc attr=%d\n", error);
5138 		if (error != 0)
5139 			goto nfsmout;
5140 		/*
5141 		 * Get rid of Op# and status for next op.
5142 		 */
5143 		NFSM_DISSECT(tl, uint32_t *, 2 * NFSX_UNSIGNED);
5144 		if (*++tl != 0)
5145 			nd->nd_flag |= ND_NOMOREDATA;
5146 	}
5147 	error = nfsrv_getattrbits(nd, &attrbits, NULL, NULL);
5148 	if (error != 0)
5149 		goto nfsmout;
5150 	if (nd->nd_repstat != 0)
5151 		error = nd->nd_repstat;
5152 	/*
5153 	 * Get the Change, Size, Access Time and Modify Time attributes and set
5154 	 * on the Metadata file, so its attributes will be what the file's
5155 	 * would be if it had been written.
5156 	 */
5157 	if (error == 0) {
5158 		NFSM_DISSECT(tl, uint32_t *, 2 * NFSX_UNSIGNED);
5159 		error = nfsv4_loadattr(nd, NULL, dsnap, NULL, NULL, 0, NULL,
5160 		    NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL, NULL, NULL);
5161 	}
5162 	NFSD_DEBUG(4, "nfsrv_setattrdsdorpc: aft setattr loadattr=%d\n", error);
5163 nfsmout:
5164 	m_freem(nd->nd_mrep);
5165 	free(nd, M_TEMP);
5166 	NFSD_DEBUG(4, "nfsrv_setattrdsdorpc error=%d\n", error);
5167 	return (error);
5168 }
5169 
5170 struct nfsrvsetattrdsdorpc {
5171 	int			done;
5172 	int			inprog;
5173 	struct task		tsk;
5174 	fhandle_t		fh;
5175 	struct nfsmount		*nmp;
5176 	struct vnode		*vp;
5177 	struct ucred		*cred;
5178 	NFSPROC_T		*p;
5179 	struct nfsvattr		na;
5180 	struct nfsvattr		dsna;
5181 	int			err;
5182 };
5183 
5184 /*
5185  * Start up the thread that will execute nfsrv_setattrdsdorpc().
5186  */
5187 static void
5188 start_setattrdsdorpc(void *arg, int pending)
5189 {
5190 	struct nfsrvsetattrdsdorpc *drpc;
5191 
5192 	drpc = (struct nfsrvsetattrdsdorpc *)arg;
5193 	drpc->err = nfsrv_setattrdsdorpc(&drpc->fh, drpc->cred, drpc->p,
5194 	    drpc->vp, drpc->nmp, &drpc->na, &drpc->dsna);
5195 	drpc->done = 1;
5196 }
5197 
5198 static int
5199 nfsrv_setattrdsrpc(fhandle_t *fhp, struct ucred *cred, NFSPROC_T *p,
5200     struct vnode *vp, struct nfsmount **nmpp, int mirrorcnt,
5201     struct nfsvattr *nap, int *failposp)
5202 {
5203 	struct nfsrvsetattrdsdorpc *drpc, *tdrpc;
5204 	struct nfsvattr na;
5205 	int error, i, ret, timo;
5206 
5207 	NFSD_DEBUG(4, "in nfsrv_setattrdsrpc\n");
5208 	drpc = NULL;
5209 	if (mirrorcnt > 1)
5210 		tdrpc = drpc = malloc(sizeof(*drpc) * (mirrorcnt - 1), M_TEMP,
5211 		    M_WAITOK);
5212 
5213 	/*
5214 	 * Do the setattr RPC for every DS, using a separate kernel process
5215 	 * for every DS except the last one.
5216 	 */
5217 	error = 0;
5218 	for (i = 0; i < mirrorcnt - 1; i++, tdrpc++) {
5219 		tdrpc->done = 0;
5220 		tdrpc->inprog = 0;
5221 		NFSBCOPY(fhp, &tdrpc->fh, sizeof(*fhp));
5222 		tdrpc->nmp = *nmpp;
5223 		tdrpc->vp = vp;
5224 		tdrpc->cred = cred;
5225 		tdrpc->p = p;
5226 		tdrpc->na = *nap;
5227 		tdrpc->err = 0;
5228 		ret = EIO;
5229 		if (nfs_pnfsiothreads != 0) {
5230 			ret = nfs_pnfsio(start_setattrdsdorpc, tdrpc);
5231 			NFSD_DEBUG(4, "nfsrv_setattrdsrpc: nfs_pnfsio=%d\n",
5232 			    ret);
5233 		}
5234 		if (ret != 0) {
5235 			ret = nfsrv_setattrdsdorpc(fhp, cred, p, vp, *nmpp, nap,
5236 			    &na);
5237 			if (nfsds_failerr(ret) && *failposp == -1)
5238 				*failposp = i;
5239 			else if (error == 0 && ret != 0)
5240 				error = ret;
5241 		}
5242 		nmpp++;
5243 		fhp++;
5244 	}
5245 	ret = nfsrv_setattrdsdorpc(fhp, cred, p, vp, *nmpp, nap, &na);
5246 	if (nfsds_failerr(ret) && *failposp == -1 && mirrorcnt > 1)
5247 		*failposp = mirrorcnt - 1;
5248 	else if (error == 0 && ret != 0)
5249 		error = ret;
5250 	if (error == 0)
5251 		error = nfsrv_setextattr(vp, &na, p);
5252 	NFSD_DEBUG(4, "nfsrv_setattrdsrpc: aft setextat=%d\n", error);
5253 	tdrpc = drpc;
5254 	timo = hz / 50;		/* Wait for 20msec. */
5255 	if (timo < 1)
5256 		timo = 1;
5257 	for (i = 0; i < mirrorcnt - 1; i++, tdrpc++) {
5258 		/* Wait for RPCs on separate threads to complete. */
5259 		while (tdrpc->inprog != 0 && tdrpc->done == 0)
5260 			tsleep(&tdrpc->tsk, PVFS, "srvsads", timo);
5261 		if (nfsds_failerr(tdrpc->err) && *failposp == -1)
5262 			*failposp = i;
5263 		else if (error == 0 && tdrpc->err != 0)
5264 			error = tdrpc->err;
5265 	}
5266 	free(drpc, M_TEMP);
5267 	return (error);
5268 }
5269 
5270 /*
5271  * Do a Setattr of an NFSv4 ACL on the DS file.
5272  */
5273 static int
5274 nfsrv_setacldsdorpc(fhandle_t *fhp, struct ucred *cred, NFSPROC_T *p,
5275     struct vnode *vp, struct nfsmount *nmp, struct acl *aclp)
5276 {
5277 	struct nfsrv_descript *nd;
5278 	nfsv4stateid_t st;
5279 	nfsattrbit_t attrbits;
5280 	int error;
5281 
5282 	NFSD_DEBUG(4, "in nfsrv_setacldsdorpc\n");
5283 	nd = malloc(sizeof(*nd), M_TEMP, M_WAITOK | M_ZERO);
5284 	/*
5285 	 * Use a stateid where other is an alternating 01010 pattern and
5286 	 * seqid is 0xffffffff.  This value is not defined as special by
5287 	 * the RFC and is used by the FreeBSD NFS server to indicate an
5288 	 * MDS->DS proxy operation.
5289 	 */
5290 	st.other[0] = 0x55555555;
5291 	st.other[1] = 0x55555555;
5292 	st.other[2] = 0x55555555;
5293 	st.seqid = 0xffffffff;
5294 	nfscl_reqstart(nd, NFSPROC_SETACL, nmp, (u_int8_t *)fhp, sizeof(*fhp),
5295 	    NULL, NULL, 0, 0);
5296 	nfsm_stateidtom(nd, &st, NFSSTATEID_PUTSTATEID);
5297 	NFSZERO_ATTRBIT(&attrbits);
5298 	NFSSETBIT_ATTRBIT(&attrbits, NFSATTRBIT_ACL);
5299 	/*
5300 	 * The "vp" argument to nfsv4_fillattr() is only used for vnode_type(),
5301 	 * so passing in the metadata "vp" will be ok, since it is of
5302 	 * the same type (VREG).
5303 	 */
5304 	nfsv4_fillattr(nd, NULL, vp, aclp, NULL, NULL, 0, &attrbits, NULL,
5305 	    NULL, 0, 0, 0, 0, 0, NULL);
5306 	error = newnfs_request(nd, nmp, NULL, &nmp->nm_sockreq, NULL, p, cred,
5307 	    NFS_PROG, NFS_VER4, NULL, 1, NULL, NULL);
5308 	if (error != 0) {
5309 		free(nd, M_TEMP);
5310 		return (error);
5311 	}
5312 	NFSD_DEBUG(4, "nfsrv_setacldsdorpc: aft setaclrpc=%d\n",
5313 	    nd->nd_repstat);
5314 	error = nd->nd_repstat;
5315 	m_freem(nd->nd_mrep);
5316 	free(nd, M_TEMP);
5317 	return (error);
5318 }
5319 
5320 struct nfsrvsetacldsdorpc {
5321 	int			done;
5322 	int			inprog;
5323 	struct task		tsk;
5324 	fhandle_t		fh;
5325 	struct nfsmount		*nmp;
5326 	struct vnode		*vp;
5327 	struct ucred		*cred;
5328 	NFSPROC_T		*p;
5329 	struct acl		*aclp;
5330 	int			err;
5331 };
5332 
5333 /*
5334  * Start up the thread that will execute nfsrv_setacldsdorpc().
5335  */
5336 static void
5337 start_setacldsdorpc(void *arg, int pending)
5338 {
5339 	struct nfsrvsetacldsdorpc *drpc;
5340 
5341 	drpc = (struct nfsrvsetacldsdorpc *)arg;
5342 	drpc->err = nfsrv_setacldsdorpc(&drpc->fh, drpc->cred, drpc->p,
5343 	    drpc->vp, drpc->nmp, drpc->aclp);
5344 	drpc->done = 1;
5345 }
5346 
5347 static int
5348 nfsrv_setacldsrpc(fhandle_t *fhp, struct ucred *cred, NFSPROC_T *p,
5349     struct vnode *vp, struct nfsmount **nmpp, int mirrorcnt, struct acl *aclp,
5350     int *failposp)
5351 {
5352 	struct nfsrvsetacldsdorpc *drpc, *tdrpc;
5353 	int error, i, ret, timo;
5354 
5355 	NFSD_DEBUG(4, "in nfsrv_setacldsrpc\n");
5356 	drpc = NULL;
5357 	if (mirrorcnt > 1)
5358 		tdrpc = drpc = malloc(sizeof(*drpc) * (mirrorcnt - 1), M_TEMP,
5359 		    M_WAITOK);
5360 
5361 	/*
5362 	 * Do the setattr RPC for every DS, using a separate kernel process
5363 	 * for every DS except the last one.
5364 	 */
5365 	error = 0;
5366 	for (i = 0; i < mirrorcnt - 1; i++, tdrpc++) {
5367 		tdrpc->done = 0;
5368 		tdrpc->inprog = 0;
5369 		NFSBCOPY(fhp, &tdrpc->fh, sizeof(*fhp));
5370 		tdrpc->nmp = *nmpp;
5371 		tdrpc->vp = vp;
5372 		tdrpc->cred = cred;
5373 		tdrpc->p = p;
5374 		tdrpc->aclp = aclp;
5375 		tdrpc->err = 0;
5376 		ret = EIO;
5377 		if (nfs_pnfsiothreads != 0) {
5378 			ret = nfs_pnfsio(start_setacldsdorpc, tdrpc);
5379 			NFSD_DEBUG(4, "nfsrv_setacldsrpc: nfs_pnfsio=%d\n",
5380 			    ret);
5381 		}
5382 		if (ret != 0) {
5383 			ret = nfsrv_setacldsdorpc(fhp, cred, p, vp, *nmpp,
5384 			    aclp);
5385 			if (nfsds_failerr(ret) && *failposp == -1)
5386 				*failposp = i;
5387 			else if (error == 0 && ret != 0)
5388 				error = ret;
5389 		}
5390 		nmpp++;
5391 		fhp++;
5392 	}
5393 	ret = nfsrv_setacldsdorpc(fhp, cred, p, vp, *nmpp, aclp);
5394 	if (nfsds_failerr(ret) && *failposp == -1 && mirrorcnt > 1)
5395 		*failposp = mirrorcnt - 1;
5396 	else if (error == 0 && ret != 0)
5397 		error = ret;
5398 	NFSD_DEBUG(4, "nfsrv_setacldsrpc: aft setextat=%d\n", error);
5399 	tdrpc = drpc;
5400 	timo = hz / 50;		/* Wait for 20msec. */
5401 	if (timo < 1)
5402 		timo = 1;
5403 	for (i = 0; i < mirrorcnt - 1; i++, tdrpc++) {
5404 		/* Wait for RPCs on separate threads to complete. */
5405 		while (tdrpc->inprog != 0 && tdrpc->done == 0)
5406 			tsleep(&tdrpc->tsk, PVFS, "srvacds", timo);
5407 		if (nfsds_failerr(tdrpc->err) && *failposp == -1)
5408 			*failposp = i;
5409 		else if (error == 0 && tdrpc->err != 0)
5410 			error = tdrpc->err;
5411 	}
5412 	free(drpc, M_TEMP);
5413 	return (error);
5414 }
5415 
5416 /*
5417  * Getattr call to the DS for the Modify, Size and Change attributes.
5418  */
5419 static int
5420 nfsrv_getattrdsrpc(fhandle_t *fhp, struct ucred *cred, NFSPROC_T *p,
5421     struct vnode *vp, struct nfsmount *nmp, struct nfsvattr *nap)
5422 {
5423 	struct nfsrv_descript *nd;
5424 	int error;
5425 	nfsattrbit_t attrbits;
5426 
5427 	NFSD_DEBUG(4, "in nfsrv_getattrdsrpc\n");
5428 	nd = malloc(sizeof(*nd), M_TEMP, M_WAITOK | M_ZERO);
5429 	nfscl_reqstart(nd, NFSPROC_GETATTR, nmp, (u_int8_t *)fhp,
5430 	    sizeof(fhandle_t), NULL, NULL, 0, 0);
5431 	NFSZERO_ATTRBIT(&attrbits);
5432 	NFSSETBIT_ATTRBIT(&attrbits, NFSATTRBIT_SIZE);
5433 	NFSSETBIT_ATTRBIT(&attrbits, NFSATTRBIT_CHANGE);
5434 	NFSSETBIT_ATTRBIT(&attrbits, NFSATTRBIT_TIMEACCESS);
5435 	NFSSETBIT_ATTRBIT(&attrbits, NFSATTRBIT_TIMEMODIFY);
5436 	(void) nfsrv_putattrbit(nd, &attrbits);
5437 	error = newnfs_request(nd, nmp, NULL, &nmp->nm_sockreq, NULL, p, cred,
5438 	    NFS_PROG, NFS_VER4, NULL, 1, NULL, NULL);
5439 	if (error != 0) {
5440 		free(nd, M_TEMP);
5441 		return (error);
5442 	}
5443 	NFSD_DEBUG(4, "nfsrv_getattrdsrpc: aft getattrrpc=%d\n",
5444 	    nd->nd_repstat);
5445 	if (nd->nd_repstat == 0) {
5446 		error = nfsv4_loadattr(nd, NULL, nap, NULL, NULL, 0,
5447 		    NULL, NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL,
5448 		    NULL, NULL);
5449 		/*
5450 		 * We can only save the updated values in the extended
5451 		 * attribute if the vp is exclusively locked.
5452 		 * This should happen when any of the following operations
5453 		 * occur on the vnode:
5454 		 *    Close, Delegreturn, LayoutCommit, LayoutReturn
5455 		 * As such, the updated extended attribute should get saved
5456 		 * before nfsrv_checkdsattr() returns 0 and allows the cached
5457 		 * attributes to be returned without calling this function.
5458 		 */
5459 		if (error == 0 && VOP_ISLOCKED(vp) == LK_EXCLUSIVE) {
5460 			error = nfsrv_setextattr(vp, nap, p);
5461 			NFSD_DEBUG(4, "nfsrv_getattrdsrpc: aft setextat=%d\n",
5462 			    error);
5463 		}
5464 	} else
5465 		error = nd->nd_repstat;
5466 	m_freem(nd->nd_mrep);
5467 	free(nd, M_TEMP);
5468 	NFSD_DEBUG(4, "nfsrv_getattrdsrpc error=%d\n", error);
5469 	return (error);
5470 }
5471 
5472 /*
5473  * Get the device id and file handle for a DS file.
5474  */
5475 int
5476 nfsrv_dsgetdevandfh(struct vnode *vp, NFSPROC_T *p, int *mirrorcntp,
5477     fhandle_t *fhp, char *devid)
5478 {
5479 	int buflen, error;
5480 	char *buf;
5481 
5482 	buflen = 1024;
5483 	buf = malloc(buflen, M_TEMP, M_WAITOK);
5484 	error = nfsrv_dsgetsockmnt(vp, 0, buf, &buflen, mirrorcntp, p, NULL,
5485 	    fhp, devid, NULL, NULL, NULL, NULL, NULL, NULL);
5486 	free(buf, M_TEMP);
5487 	return (error);
5488 }
5489 
5490 /*
5491  * Do a Lookup against the DS for the filename.
5492  */
5493 static int
5494 nfsrv_pnfslookupds(struct vnode *vp, struct vnode *dvp, struct pnfsdsfile *pf,
5495     struct vnode **nvpp, NFSPROC_T *p)
5496 {
5497 	struct nameidata named;
5498 	struct ucred *tcred;
5499 	char *bufp;
5500 	u_long *hashp;
5501 	struct vnode *nvp;
5502 	int error;
5503 
5504 	tcred = newnfs_getcred();
5505 	named.ni_cnd.cn_nameiop = LOOKUP;
5506 	named.ni_cnd.cn_lkflags = LK_SHARED | LK_RETRY;
5507 	named.ni_cnd.cn_cred = tcred;
5508 	named.ni_cnd.cn_thread = p;
5509 	named.ni_cnd.cn_flags = ISLASTCN | LOCKPARENT | LOCKLEAF | SAVENAME;
5510 	nfsvno_setpathbuf(&named, &bufp, &hashp);
5511 	named.ni_cnd.cn_nameptr = bufp;
5512 	named.ni_cnd.cn_namelen = strlen(pf->dsf_filename);
5513 	strlcpy(bufp, pf->dsf_filename, NAME_MAX);
5514 	NFSD_DEBUG(4, "nfsrv_pnfslookupds: filename=%s\n", bufp);
5515 	error = VOP_LOOKUP(dvp, &nvp, &named.ni_cnd);
5516 	NFSD_DEBUG(4, "nfsrv_pnfslookupds: aft LOOKUP=%d\n", error);
5517 	NFSFREECRED(tcred);
5518 	nfsvno_relpathbuf(&named);
5519 	if (error == 0)
5520 		*nvpp = nvp;
5521 	NFSD_DEBUG(4, "eo nfsrv_pnfslookupds=%d\n", error);
5522 	return (error);
5523 }
5524 
5525 /*
5526  * Set the file handle to the correct one.
5527  */
5528 static void
5529 nfsrv_pnfssetfh(struct vnode *vp, struct pnfsdsfile *pf, char *devid,
5530     char *fnamep, struct vnode *nvp, NFSPROC_T *p)
5531 {
5532 	struct nfsnode *np;
5533 	int ret;
5534 
5535 	np = VTONFS(nvp);
5536 	NFSBCOPY(np->n_fhp->nfh_fh, &pf->dsf_fh, NFSX_MYFH);
5537 	/*
5538 	 * We can only do a vn_set_extattr() if the vnode is exclusively
5539 	 * locked and vn_start_write() has been done.  If devid != NULL or
5540 	 * fnamep != NULL or the vnode is shared locked, vn_start_write()
5541 	 * may not have been done.
5542 	 * If not done now, it will be done on a future call.
5543 	 */
5544 	if (devid == NULL && fnamep == NULL && NFSVOPISLOCKED(vp) ==
5545 	    LK_EXCLUSIVE)
5546 		ret = vn_extattr_set(vp, IO_NODELOCKED,
5547 		    EXTATTR_NAMESPACE_SYSTEM, "pnfsd.dsfile", sizeof(*pf),
5548 		    (char *)pf, p);
5549 	NFSD_DEBUG(4, "eo nfsrv_pnfssetfh=%d\n", ret);
5550 }
5551 
5552 /*
5553  * Cause RPCs waiting on "nmp" to fail.  This is called for a DS mount point
5554  * when the DS has failed.
5555  */
5556 void
5557 nfsrv_killrpcs(struct nfsmount *nmp)
5558 {
5559 
5560 	/*
5561 	 * Call newnfs_nmcancelreqs() to cause
5562 	 * any RPCs in progress on the mount point to
5563 	 * fail.
5564 	 * This will cause any process waiting for an
5565 	 * RPC to complete while holding a vnode lock
5566 	 * on the mounted-on vnode (such as "df" or
5567 	 * a non-forced "umount") to fail.
5568 	 * This will unlock the mounted-on vnode so
5569 	 * a forced dismount can succeed.
5570 	 * The NFSMNTP_CANCELRPCS flag should be set when this function is
5571 	 * called.
5572 	 */
5573 	newnfs_nmcancelreqs(nmp);
5574 }
5575 
5576 /*
5577  * Sum up the statfs info for each of the DSs, so that the client will
5578  * receive the total for all DSs.
5579  */
5580 static int
5581 nfsrv_pnfsstatfs(struct statfs *sf)
5582 {
5583 	struct statfs *tsf;
5584 	struct nfsdevice *ds;
5585 	struct vnode **dvpp, **tdvpp, *dvp;
5586 	uint64_t tot;
5587 	int cnt, error = 0, i;
5588 
5589 	if (nfsrv_devidcnt <= 0)
5590 		return (ENXIO);
5591 	dvpp = mallocarray(nfsrv_devidcnt, sizeof(*dvpp), M_TEMP, M_WAITOK);
5592 	tsf = malloc(sizeof(*tsf), M_TEMP, M_WAITOK);
5593 
5594 	/* Get an array of the dvps for the DSs. */
5595 	tdvpp = dvpp;
5596 	i = 0;
5597 	NFSDDSLOCK();
5598 	TAILQ_FOREACH(ds, &nfsrv_devidhead, nfsdev_list) {
5599 		if (ds->nfsdev_nmp != NULL) {
5600 			if (++i > nfsrv_devidcnt)
5601 				break;
5602 			*tdvpp++ = ds->nfsdev_dvp;
5603 		}
5604 	}
5605 	NFSDDSUNLOCK();
5606 	cnt = i;
5607 
5608 	/* Do a VFS_STATFS() for each of the DSs and sum them up. */
5609 	tdvpp = dvpp;
5610 	for (i = 0; i < cnt && error == 0; i++) {
5611 		dvp = *tdvpp++;
5612 		error = VFS_STATFS(dvp->v_mount, tsf);
5613 		if (error == 0) {
5614 			if (sf->f_bsize == 0) {
5615 				if (tsf->f_bsize > 0)
5616 					sf->f_bsize = tsf->f_bsize;
5617 				else
5618 					sf->f_bsize = 8192;
5619 			}
5620 			if (tsf->f_blocks > 0) {
5621 				if (sf->f_bsize != tsf->f_bsize) {
5622 					tot = tsf->f_blocks * tsf->f_bsize;
5623 					sf->f_blocks += (tot / sf->f_bsize);
5624 				} else
5625 					sf->f_blocks += tsf->f_blocks;
5626 			}
5627 			if (tsf->f_bfree > 0) {
5628 				if (sf->f_bsize != tsf->f_bsize) {
5629 					tot = tsf->f_bfree * tsf->f_bsize;
5630 					sf->f_bfree += (tot / sf->f_bsize);
5631 				} else
5632 					sf->f_bfree += tsf->f_bfree;
5633 			}
5634 			if (tsf->f_bavail > 0) {
5635 				if (sf->f_bsize != tsf->f_bsize) {
5636 					tot = tsf->f_bavail * tsf->f_bsize;
5637 					sf->f_bavail += (tot / sf->f_bsize);
5638 				} else
5639 					sf->f_bavail += tsf->f_bavail;
5640 			}
5641 		}
5642 	}
5643 	free(tsf, M_TEMP);
5644 	free(dvpp, M_TEMP);
5645 	return (error);
5646 }
5647 
5648 /*
5649  * Set an NFSv4 acl.
5650  */
5651 int
5652 nfsrv_setacl(struct vnode *vp, NFSACL_T *aclp, struct ucred *cred, NFSPROC_T *p)
5653 {
5654 	int error;
5655 
5656 	if (nfsrv_useacl == 0 || nfs_supportsnfsv4acls(vp) == 0) {
5657 		error = NFSERR_ATTRNOTSUPP;
5658 		goto out;
5659 	}
5660 	/*
5661 	 * With NFSv4 ACLs, chmod(2) may need to add additional entries.
5662 	 * Make sure it has enough room for that - splitting every entry
5663 	 * into two and appending "canonical six" entries at the end.
5664 	 * Cribbed out of kern/vfs_acl.c - Rick M.
5665 	 */
5666 	if (aclp->acl_cnt > (ACL_MAX_ENTRIES - 6) / 2) {
5667 		error = NFSERR_ATTRNOTSUPP;
5668 		goto out;
5669 	}
5670 	error = VOP_SETACL(vp, ACL_TYPE_NFS4, aclp, cred, p);
5671 	if (error == 0) {
5672 		error = nfsrv_dssetacl(vp, aclp, cred, p);
5673 		if (error == ENOENT)
5674 			error = 0;
5675 	}
5676 
5677 out:
5678 	NFSEXITCODE(error);
5679 	return (error);
5680 }
5681 
5682 extern int (*nfsd_call_nfsd)(struct thread *, struct nfssvc_args *);
5683 
5684 /*
5685  * Called once to initialize data structures...
5686  */
5687 static int
5688 nfsd_modevent(module_t mod, int type, void *data)
5689 {
5690 	int error = 0, i;
5691 	static int loaded = 0;
5692 
5693 	switch (type) {
5694 	case MOD_LOAD:
5695 		if (loaded)
5696 			goto out;
5697 		newnfs_portinit();
5698 		for (i = 0; i < NFSRVCACHE_HASHSIZE; i++) {
5699 			mtx_init(&nfsrchash_table[i].mtx, "nfsrtc", NULL,
5700 			    MTX_DEF);
5701 			mtx_init(&nfsrcahash_table[i].mtx, "nfsrtca", NULL,
5702 			    MTX_DEF);
5703 		}
5704 		mtx_init(&nfsrc_udpmtx, "nfsuc", NULL, MTX_DEF);
5705 		mtx_init(&nfs_v4root_mutex, "nfs4rt", NULL, MTX_DEF);
5706 		mtx_init(&nfsv4root_mnt.mnt_mtx, "nfs4mnt", NULL, MTX_DEF);
5707 		mtx_init(&nfsrv_dontlistlock_mtx, "nfs4dnl", NULL, MTX_DEF);
5708 		mtx_init(&nfsrv_recalllock_mtx, "nfs4rec", NULL, MTX_DEF);
5709 		lockinit(&nfsv4root_mnt.mnt_explock, PVFS, "explock", 0, 0);
5710 		nfsrvd_initcache();
5711 		nfsd_init();
5712 		NFSD_LOCK();
5713 		nfsrvd_init(0);
5714 		NFSD_UNLOCK();
5715 		nfsd_mntinit();
5716 #ifdef VV_DISABLEDELEG
5717 		vn_deleg_ops.vndeleg_recall = nfsd_recalldelegation;
5718 		vn_deleg_ops.vndeleg_disable = nfsd_disabledelegation;
5719 #endif
5720 		nfsd_call_servertimer = nfsrv_servertimer;
5721 		nfsd_call_nfsd = nfssvc_nfsd;
5722 		loaded = 1;
5723 		break;
5724 
5725 	case MOD_UNLOAD:
5726 		if (newnfs_numnfsd != 0) {
5727 			error = EBUSY;
5728 			break;
5729 		}
5730 
5731 #ifdef VV_DISABLEDELEG
5732 		vn_deleg_ops.vndeleg_recall = NULL;
5733 		vn_deleg_ops.vndeleg_disable = NULL;
5734 #endif
5735 		nfsd_call_servertimer = NULL;
5736 		nfsd_call_nfsd = NULL;
5737 
5738 		/* Clean out all NFSv4 state. */
5739 		nfsrv_throwawayallstate(curthread);
5740 
5741 		/* Clean the NFS server reply cache */
5742 		nfsrvd_cleancache();
5743 
5744 		/* Free up the krpc server pool. */
5745 		if (nfsrvd_pool != NULL)
5746 			svcpool_destroy(nfsrvd_pool);
5747 
5748 		/* and get rid of the locks */
5749 		for (i = 0; i < NFSRVCACHE_HASHSIZE; i++) {
5750 			mtx_destroy(&nfsrchash_table[i].mtx);
5751 			mtx_destroy(&nfsrcahash_table[i].mtx);
5752 		}
5753 		mtx_destroy(&nfsrc_udpmtx);
5754 		mtx_destroy(&nfs_v4root_mutex);
5755 		mtx_destroy(&nfsv4root_mnt.mnt_mtx);
5756 		mtx_destroy(&nfsrv_dontlistlock_mtx);
5757 		mtx_destroy(&nfsrv_recalllock_mtx);
5758 		for (i = 0; i < nfsrv_sessionhashsize; i++)
5759 			mtx_destroy(&nfssessionhash[i].mtx);
5760 		if (nfslayouthash != NULL) {
5761 			for (i = 0; i < nfsrv_layouthashsize; i++)
5762 				mtx_destroy(&nfslayouthash[i].mtx);
5763 			free(nfslayouthash, M_NFSDSESSION);
5764 		}
5765 		lockdestroy(&nfsv4root_mnt.mnt_explock);
5766 		free(nfsclienthash, M_NFSDCLIENT);
5767 		free(nfslockhash, M_NFSDLOCKFILE);
5768 		free(nfssessionhash, M_NFSDSESSION);
5769 		loaded = 0;
5770 		break;
5771 	default:
5772 		error = EOPNOTSUPP;
5773 		break;
5774 	}
5775 
5776 out:
5777 	NFSEXITCODE(error);
5778 	return (error);
5779 }
5780 static moduledata_t nfsd_mod = {
5781 	"nfsd",
5782 	nfsd_modevent,
5783 	NULL,
5784 };
5785 DECLARE_MODULE(nfsd, nfsd_mod, SI_SUB_VFS, SI_ORDER_ANY);
5786 
5787 /* So that loader and kldload(2) can find us, wherever we are.. */
5788 MODULE_VERSION(nfsd, 1);
5789 MODULE_DEPEND(nfsd, nfscommon, 1, 1, 1);
5790 MODULE_DEPEND(nfsd, nfslock, 1, 1, 1);
5791 MODULE_DEPEND(nfsd, nfslockd, 1, 1, 1);
5792 MODULE_DEPEND(nfsd, krpc, 1, 1, 1);
5793 MODULE_DEPEND(nfsd, nfssvc, 1, 1, 1);
5794 
5795