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