xref: /freebsd/sys/fs/nfsserver/nfs_nfsdport.c (revision 81b22a98)
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 	u_long *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 				*tl++ = 0;
2262 			} else
2263 				NFSM_BUILD(tl, u_int32_t *, NFSX_UNSIGNED);
2264 			*tl = txdr_unsigned(*cookiep);
2265 		}
2266 		cpos += dp->d_reclen;
2267 		dp = (struct dirent *)cpos;
2268 		cookiep++;
2269 		ncookies--;
2270 	}
2271 	if (cpos < cend)
2272 		eofflag = 0;
2273 	NFSM_BUILD(tl, u_int32_t *, 2 * NFSX_UNSIGNED);
2274 	*tl++ = newnfs_false;
2275 	if (eofflag)
2276 		*tl = newnfs_true;
2277 	else
2278 		*tl = newnfs_false;
2279 	free(rbuf, M_TEMP);
2280 	free(cookies, M_TEMP);
2281 
2282 out:
2283 	NFSEXITCODE2(0, nd);
2284 	return (0);
2285 nfsmout:
2286 	vput(vp);
2287 	NFSEXITCODE2(error, nd);
2288 	return (error);
2289 }
2290 
2291 /*
2292  * Readdirplus for V3 and Readdir for V4.
2293  */
2294 int
2295 nfsrvd_readdirplus(struct nfsrv_descript *nd, int isdgram,
2296     struct vnode *vp, struct nfsexstuff *exp)
2297 {
2298 	struct dirent *dp;
2299 	u_int32_t *tl;
2300 	int dirlen;
2301 	char *cpos, *cend, *rbuf;
2302 	struct vnode *nvp;
2303 	fhandle_t nfh;
2304 	struct nfsvattr nva, at, *nvap = &nva;
2305 	struct mbuf *mb0, *mb1;
2306 	struct nfsreferral *refp;
2307 	int nlen, r, error = 0, getret = 1, usevget = 1;
2308 	int siz, cnt, fullsiz, eofflag, ncookies, entrycnt;
2309 	caddr_t bpos0, bpos1;
2310 	u_int64_t off, toff, verf;
2311 	u_long *cookies = NULL, *cookiep;
2312 	nfsattrbit_t attrbits, rderrbits, savbits;
2313 	struct uio io;
2314 	struct iovec iv;
2315 	struct componentname cn;
2316 	int at_root, is_ufs, is_zfs, needs_unbusy, supports_nfsv4acls;
2317 	struct mount *mp, *new_mp;
2318 	uint64_t mounted_on_fileno;
2319 	struct thread *p = curthread;
2320 	int bextpg0, bextpg1, bextpgsiz0, bextpgsiz1;
2321 
2322 	if (nd->nd_repstat) {
2323 		nfsrv_postopattr(nd, getret, &at);
2324 		goto out;
2325 	}
2326 	NFSM_DISSECT(tl, u_int32_t *, 6 * NFSX_UNSIGNED);
2327 	off = fxdr_hyper(tl);
2328 	toff = off;
2329 	tl += 2;
2330 	verf = fxdr_hyper(tl);
2331 	tl += 2;
2332 	siz = fxdr_unsigned(int, *tl++);
2333 	cnt = fxdr_unsigned(int, *tl);
2334 
2335 	/*
2336 	 * Use the server's maximum data transfer size as the upper bound
2337 	 * on reply datalen.
2338 	 */
2339 	if (cnt > NFS_SRVMAXDATA(nd) || cnt < 0)
2340 		cnt = NFS_SRVMAXDATA(nd);
2341 
2342 	/*
2343 	 * siz is a "hint" of how much directory information (name, fileid,
2344 	 * cookie) should be in the reply. At least one client "hints" 0,
2345 	 * so I set it to cnt for that case. I also round it up to the
2346 	 * next multiple of DIRBLKSIZ.
2347 	 * Since the size of a Readdirplus directory entry reply will always
2348 	 * be greater than a directory entry returned by VOP_READDIR(), it
2349 	 * does not make sense to read more than NFS_SRVMAXDATA() via
2350 	 * VOP_READDIR().
2351 	 */
2352 	if (siz <= 0)
2353 		siz = cnt;
2354 	else if (siz > NFS_SRVMAXDATA(nd))
2355 		siz = NFS_SRVMAXDATA(nd);
2356 	siz = ((siz + DIRBLKSIZ - 1) & ~(DIRBLKSIZ - 1));
2357 
2358 	if (nd->nd_flag & ND_NFSV4) {
2359 		error = nfsrv_getattrbits(nd, &attrbits, NULL, NULL);
2360 		if (error)
2361 			goto nfsmout;
2362 		NFSSET_ATTRBIT(&savbits, &attrbits);
2363 		NFSCLRNOTFILLABLE_ATTRBIT(&attrbits, nd);
2364 		NFSZERO_ATTRBIT(&rderrbits);
2365 		NFSSETBIT_ATTRBIT(&rderrbits, NFSATTRBIT_RDATTRERROR);
2366 	} else {
2367 		NFSZERO_ATTRBIT(&attrbits);
2368 	}
2369 	fullsiz = siz;
2370 	nd->nd_repstat = getret = nfsvno_getattr(vp, &at, nd, p, 1, NULL);
2371 #if 0
2372 	if (!nd->nd_repstat) {
2373 	    if (off && verf != at.na_filerev) {
2374 		/*
2375 		 * va_filerev is not sufficient as a cookie verifier,
2376 		 * since it is not supposed to change when entries are
2377 		 * removed/added unless that offset cookies returned to
2378 		 * the client are no longer valid.
2379 		 */
2380 		if (nd->nd_flag & ND_NFSV4) {
2381 			nd->nd_repstat = NFSERR_NOTSAME;
2382 		} else {
2383 			nd->nd_repstat = NFSERR_BAD_COOKIE;
2384 		}
2385 	    }
2386 	}
2387 #endif
2388 	if (!nd->nd_repstat && vp->v_type != VDIR)
2389 		nd->nd_repstat = NFSERR_NOTDIR;
2390 	if (!nd->nd_repstat && cnt == 0)
2391 		nd->nd_repstat = NFSERR_TOOSMALL;
2392 	if (!nd->nd_repstat)
2393 		nd->nd_repstat = nfsvno_accchk(vp, VEXEC,
2394 		    nd->nd_cred, exp, p, NFSACCCHK_NOOVERRIDE,
2395 		    NFSACCCHK_VPISLOCKED, NULL);
2396 	if (nd->nd_repstat) {
2397 		vput(vp);
2398 		if (nd->nd_flag & ND_NFSV3)
2399 			nfsrv_postopattr(nd, getret, &at);
2400 		goto out;
2401 	}
2402 	is_ufs = strcmp(vp->v_mount->mnt_vfc->vfc_name, "ufs") == 0;
2403 	is_zfs = strcmp(vp->v_mount->mnt_vfc->vfc_name, "zfs") == 0;
2404 
2405 	rbuf = malloc(siz, M_TEMP, M_WAITOK);
2406 again:
2407 	eofflag = 0;
2408 	if (cookies) {
2409 		free(cookies, M_TEMP);
2410 		cookies = NULL;
2411 	}
2412 
2413 	iv.iov_base = rbuf;
2414 	iv.iov_len = siz;
2415 	io.uio_iov = &iv;
2416 	io.uio_iovcnt = 1;
2417 	io.uio_offset = (off_t)off;
2418 	io.uio_resid = siz;
2419 	io.uio_segflg = UIO_SYSSPACE;
2420 	io.uio_rw = UIO_READ;
2421 	io.uio_td = NULL;
2422 	nd->nd_repstat = VOP_READDIR(vp, &io, nd->nd_cred, &eofflag, &ncookies,
2423 	    &cookies);
2424 	off = (u_int64_t)io.uio_offset;
2425 	if (io.uio_resid)
2426 		siz -= io.uio_resid;
2427 
2428 	getret = nfsvno_getattr(vp, &at, nd, p, 1, NULL);
2429 
2430 	if (!cookies && !nd->nd_repstat)
2431 		nd->nd_repstat = NFSERR_PERM;
2432 	if (!nd->nd_repstat)
2433 		nd->nd_repstat = getret;
2434 	if (nd->nd_repstat) {
2435 		vput(vp);
2436 		if (cookies)
2437 			free(cookies, M_TEMP);
2438 		free(rbuf, M_TEMP);
2439 		if (nd->nd_flag & ND_NFSV3)
2440 			nfsrv_postopattr(nd, getret, &at);
2441 		goto out;
2442 	}
2443 	/*
2444 	 * If nothing read, return eof
2445 	 * rpc reply
2446 	 */
2447 	if (siz == 0) {
2448 		vput(vp);
2449 		if (nd->nd_flag & ND_NFSV3)
2450 			nfsrv_postopattr(nd, getret, &at);
2451 		NFSM_BUILD(tl, u_int32_t *, 4 * NFSX_UNSIGNED);
2452 		txdr_hyper(at.na_filerev, tl);
2453 		tl += 2;
2454 		*tl++ = newnfs_false;
2455 		*tl = newnfs_true;
2456 		free(cookies, M_TEMP);
2457 		free(rbuf, M_TEMP);
2458 		goto out;
2459 	}
2460 
2461 	/*
2462 	 * Check for degenerate cases of nothing useful read.
2463 	 * If so go try again
2464 	 */
2465 	cpos = rbuf;
2466 	cend = rbuf + siz;
2467 	dp = (struct dirent *)cpos;
2468 	cookiep = cookies;
2469 
2470 	/*
2471 	 * For some reason FreeBSD's ufs_readdir() chooses to back the
2472 	 * directory offset up to a block boundary, so it is necessary to
2473 	 * skip over the records that precede the requested offset. This
2474 	 * requires the assumption that file offset cookies monotonically
2475 	 * increase.
2476 	 */
2477 	while (cpos < cend && ncookies > 0 &&
2478 	  (dp->d_fileno == 0 || dp->d_type == DT_WHT ||
2479 	   (is_ufs == 1 && ((u_quad_t)(*cookiep)) <= toff) ||
2480 	   ((nd->nd_flag & ND_NFSV4) &&
2481 	    ((dp->d_namlen == 1 && dp->d_name[0] == '.') ||
2482 	     (dp->d_namlen==2 && dp->d_name[0]=='.' && dp->d_name[1]=='.'))))) {
2483 		cpos += dp->d_reclen;
2484 		dp = (struct dirent *)cpos;
2485 		cookiep++;
2486 		ncookies--;
2487 	}
2488 	if (cpos >= cend || ncookies == 0) {
2489 		siz = fullsiz;
2490 		toff = off;
2491 		goto again;
2492 	}
2493 
2494 	/*
2495 	 * Busy the file system so that the mount point won't go away
2496 	 * and, as such, VFS_VGET() can be used safely.
2497 	 */
2498 	mp = vp->v_mount;
2499 	vfs_ref(mp);
2500 	NFSVOPUNLOCK(vp);
2501 	nd->nd_repstat = vfs_busy(mp, 0);
2502 	vfs_rel(mp);
2503 	if (nd->nd_repstat != 0) {
2504 		vrele(vp);
2505 		free(cookies, M_TEMP);
2506 		free(rbuf, M_TEMP);
2507 		if (nd->nd_flag & ND_NFSV3)
2508 			nfsrv_postopattr(nd, getret, &at);
2509 		goto out;
2510 	}
2511 
2512 	/*
2513 	 * Check to see if entries in this directory can be safely acquired
2514 	 * via VFS_VGET() or if a switch to VOP_LOOKUP() is required.
2515 	 * ZFS snapshot directories need VOP_LOOKUP(), so that any
2516 	 * automount of the snapshot directory that is required will
2517 	 * be done.
2518 	 * This needs to be done here for NFSv4, since NFSv4 never does
2519 	 * a VFS_VGET() for "." or "..".
2520 	 */
2521 	if (is_zfs == 1) {
2522 		r = VFS_VGET(mp, at.na_fileid, LK_SHARED, &nvp);
2523 		if (r == EOPNOTSUPP) {
2524 			usevget = 0;
2525 			cn.cn_nameiop = LOOKUP;
2526 			cn.cn_lkflags = LK_SHARED | LK_RETRY;
2527 			cn.cn_cred = nd->nd_cred;
2528 		} else if (r == 0)
2529 			vput(nvp);
2530 	}
2531 
2532 	/*
2533 	 * If the reply is likely to exceed MCLBYTES and the reply will
2534 	 * not be saved, use ext_pgs mbufs for TLS.
2535 	 * It is difficult to predict how large each entry will be and
2536 	 * how many entries have been read, so just assume the directory
2537 	 * entries grow by a factor of 4 when attributes are included.
2538 	 * For NFSv4.0, we do not know for sure if the reply will
2539 	 * be saved, so do not use ext_pgs mbufs for NFSv4.0.
2540 	 */
2541 	if (cnt > MCLBYTES && siz > MCLBYTES / 4 &&
2542 	    (nd->nd_flag & (ND_TLS | ND_EXTPG | ND_SAVEREPLY)) == ND_TLS &&
2543 	    (nd->nd_flag & (ND_NFSV4 | ND_NFSV41)) != ND_NFSV4)
2544 		nd->nd_flag |= ND_EXTPG;
2545 
2546 	/*
2547 	 * Save this position, in case there is an error before one entry
2548 	 * is created.
2549 	 */
2550 	mb0 = nd->nd_mb;
2551 	bpos0 = nd->nd_bpos;
2552 	bextpg0 = nd->nd_bextpg;
2553 	bextpgsiz0 = nd->nd_bextpgsiz;
2554 
2555 	/*
2556 	 * Fill in the first part of the reply.
2557 	 * dirlen is the reply length in bytes and cannot exceed cnt.
2558 	 * (Include the two booleans at the end of the reply in dirlen now,
2559 	 *  so we recognize when we have exceeded cnt.)
2560 	 */
2561 	if (nd->nd_flag & ND_NFSV3) {
2562 		dirlen = NFSX_V3POSTOPATTR + NFSX_VERF + 2 * NFSX_UNSIGNED;
2563 		nfsrv_postopattr(nd, getret, &at);
2564 	} else {
2565 		dirlen = NFSX_VERF + 2 * NFSX_UNSIGNED;
2566 	}
2567 	NFSM_BUILD(tl, u_int32_t *, NFSX_VERF);
2568 	txdr_hyper(at.na_filerev, tl);
2569 
2570 	/*
2571 	 * Save this position, in case there is an empty reply needed.
2572 	 */
2573 	mb1 = nd->nd_mb;
2574 	bpos1 = nd->nd_bpos;
2575 	bextpg1 = nd->nd_bextpg;
2576 	bextpgsiz1 = nd->nd_bextpgsiz;
2577 
2578 	/* Loop through the records and build reply */
2579 	entrycnt = 0;
2580 	while (cpos < cend && ncookies > 0 && dirlen < cnt) {
2581 		nlen = dp->d_namlen;
2582 		if (dp->d_fileno != 0 && dp->d_type != DT_WHT &&
2583 		    nlen <= NFS_MAXNAMLEN &&
2584 		    ((nd->nd_flag & ND_NFSV3) || nlen > 2 ||
2585 		     (nlen==2 && (dp->d_name[0]!='.' || dp->d_name[1]!='.'))
2586 		      || (nlen == 1 && dp->d_name[0] != '.'))) {
2587 			/*
2588 			 * Save the current position in the reply, in case
2589 			 * this entry exceeds cnt.
2590 			 */
2591 			mb1 = nd->nd_mb;
2592 			bpos1 = nd->nd_bpos;
2593 			bextpg1 = nd->nd_bextpg;
2594 			bextpgsiz1 = nd->nd_bextpgsiz;
2595 
2596 			/*
2597 			 * For readdir_and_lookup get the vnode using
2598 			 * the file number.
2599 			 */
2600 			nvp = NULL;
2601 			refp = NULL;
2602 			r = 0;
2603 			at_root = 0;
2604 			needs_unbusy = 0;
2605 			new_mp = mp;
2606 			mounted_on_fileno = (uint64_t)dp->d_fileno;
2607 			if ((nd->nd_flag & ND_NFSV3) ||
2608 			    NFSNONZERO_ATTRBIT(&savbits)) {
2609 				if (nd->nd_flag & ND_NFSV4)
2610 					refp = nfsv4root_getreferral(NULL,
2611 					    vp, dp->d_fileno);
2612 				if (refp == NULL) {
2613 					if (usevget)
2614 						r = VFS_VGET(mp, dp->d_fileno,
2615 						    LK_SHARED, &nvp);
2616 					else
2617 						r = EOPNOTSUPP;
2618 					if (r == EOPNOTSUPP) {
2619 						if (usevget) {
2620 							usevget = 0;
2621 							cn.cn_nameiop = LOOKUP;
2622 							cn.cn_lkflags =
2623 							    LK_SHARED |
2624 							    LK_RETRY;
2625 							cn.cn_cred =
2626 							    nd->nd_cred;
2627 						}
2628 						cn.cn_nameptr = dp->d_name;
2629 						cn.cn_namelen = nlen;
2630 						cn.cn_flags = ISLASTCN |
2631 						    NOFOLLOW | LOCKLEAF;
2632 						if (nlen == 2 &&
2633 						    dp->d_name[0] == '.' &&
2634 						    dp->d_name[1] == '.')
2635 							cn.cn_flags |=
2636 							    ISDOTDOT;
2637 						if (NFSVOPLOCK(vp, LK_SHARED)
2638 						    != 0) {
2639 							nd->nd_repstat = EPERM;
2640 							break;
2641 						}
2642 						if ((vp->v_vflag & VV_ROOT) != 0
2643 						    && (cn.cn_flags & ISDOTDOT)
2644 						    != 0) {
2645 							vref(vp);
2646 							nvp = vp;
2647 							r = 0;
2648 						} else {
2649 							r = VOP_LOOKUP(vp, &nvp,
2650 							    &cn);
2651 							if (vp != nvp)
2652 								NFSVOPUNLOCK(vp);
2653 						}
2654 					}
2655 
2656 					/*
2657 					 * For NFSv4, check to see if nvp is
2658 					 * a mount point and get the mount
2659 					 * point vnode, as required.
2660 					 */
2661 					if (r == 0 &&
2662 					    nfsrv_enable_crossmntpt != 0 &&
2663 					    (nd->nd_flag & ND_NFSV4) != 0 &&
2664 					    nvp->v_type == VDIR &&
2665 					    nvp->v_mountedhere != NULL) {
2666 						new_mp = nvp->v_mountedhere;
2667 						r = vfs_busy(new_mp, 0);
2668 						vput(nvp);
2669 						nvp = NULL;
2670 						if (r == 0) {
2671 							r = VFS_ROOT(new_mp,
2672 							    LK_SHARED, &nvp);
2673 							needs_unbusy = 1;
2674 							if (r == 0)
2675 								at_root = 1;
2676 						}
2677 					}
2678 				}
2679 
2680 				/*
2681 				 * If we failed to look up the entry, then it
2682 				 * has become invalid, most likely removed.
2683 				 */
2684 				if (r != 0) {
2685 					if (needs_unbusy)
2686 						vfs_unbusy(new_mp);
2687 					goto invalid;
2688 				}
2689 				KASSERT(refp != NULL || nvp != NULL,
2690 				    ("%s: undetected lookup error", __func__));
2691 
2692 				if (refp == NULL &&
2693 				    ((nd->nd_flag & ND_NFSV3) ||
2694 				     NFSNONZERO_ATTRBIT(&attrbits))) {
2695 					r = nfsvno_getfh(nvp, &nfh, p);
2696 					if (!r)
2697 					    r = nfsvno_getattr(nvp, nvap, nd, p,
2698 						1, &attrbits);
2699 					if (r == 0 && is_zfs == 1 &&
2700 					    nfsrv_enable_crossmntpt != 0 &&
2701 					    (nd->nd_flag & ND_NFSV4) != 0 &&
2702 					    nvp->v_type == VDIR &&
2703 					    vp->v_mount != nvp->v_mount) {
2704 					    /*
2705 					     * For a ZFS snapshot, there is a
2706 					     * pseudo mount that does not set
2707 					     * v_mountedhere, so it needs to
2708 					     * be detected via a different
2709 					     * mount structure.
2710 					     */
2711 					    at_root = 1;
2712 					    if (new_mp == mp)
2713 						new_mp = nvp->v_mount;
2714 					}
2715 				}
2716 
2717 				/*
2718 				 * If we failed to get attributes of the entry,
2719 				 * then just skip it for NFSv3 (the traditional
2720 				 * behavior in the old NFS server).
2721 				 * For NFSv4 the behavior is controlled by
2722 				 * RDATTRERROR: we either ignore the error or
2723 				 * fail the request.
2724 				 * Note that RDATTRERROR is never set for NFSv3.
2725 				 */
2726 				if (r != 0) {
2727 					if (!NFSISSET_ATTRBIT(&attrbits,
2728 					    NFSATTRBIT_RDATTRERROR)) {
2729 						vput(nvp);
2730 						if (needs_unbusy != 0)
2731 							vfs_unbusy(new_mp);
2732 						if ((nd->nd_flag & ND_NFSV3))
2733 							goto invalid;
2734 						nd->nd_repstat = r;
2735 						break;
2736 					}
2737 				}
2738 			}
2739 
2740 			/*
2741 			 * Build the directory record xdr
2742 			 */
2743 			if (nd->nd_flag & ND_NFSV3) {
2744 				NFSM_BUILD(tl, u_int32_t *, 3 * NFSX_UNSIGNED);
2745 				*tl++ = newnfs_true;
2746 				*tl++ = 0;
2747 				*tl = txdr_unsigned(dp->d_fileno);
2748 				dirlen += nfsm_strtom(nd, dp->d_name, nlen);
2749 				NFSM_BUILD(tl, u_int32_t *, 2 * NFSX_UNSIGNED);
2750 				*tl++ = 0;
2751 				*tl = txdr_unsigned(*cookiep);
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 				*tl++ = 0;
2761 				*tl = txdr_unsigned(*cookiep);
2762 				dirlen += nfsm_strtom(nd, dp->d_name, nlen);
2763 				if (nvp != NULL) {
2764 					supports_nfsv4acls =
2765 					    nfs_supportsnfsv4acls(nvp);
2766 					NFSVOPUNLOCK(nvp);
2767 				} else
2768 					supports_nfsv4acls = 0;
2769 				if (refp != NULL) {
2770 					dirlen += nfsrv_putreferralattr(nd,
2771 					    &savbits, refp, 0,
2772 					    &nd->nd_repstat);
2773 					if (nd->nd_repstat) {
2774 						if (nvp != NULL)
2775 							vrele(nvp);
2776 						if (needs_unbusy != 0)
2777 							vfs_unbusy(new_mp);
2778 						break;
2779 					}
2780 				} else if (r) {
2781 					dirlen += nfsvno_fillattr(nd, new_mp,
2782 					    nvp, nvap, &nfh, r, &rderrbits,
2783 					    nd->nd_cred, p, isdgram, 0,
2784 					    supports_nfsv4acls, at_root,
2785 					    mounted_on_fileno);
2786 				} else {
2787 					dirlen += nfsvno_fillattr(nd, new_mp,
2788 					    nvp, nvap, &nfh, r, &attrbits,
2789 					    nd->nd_cred, p, isdgram, 0,
2790 					    supports_nfsv4acls, at_root,
2791 					    mounted_on_fileno);
2792 				}
2793 				if (nvp != NULL)
2794 					vrele(nvp);
2795 				dirlen += (3 * NFSX_UNSIGNED);
2796 			}
2797 			if (needs_unbusy != 0)
2798 				vfs_unbusy(new_mp);
2799 			if (dirlen <= cnt)
2800 				entrycnt++;
2801 		}
2802 invalid:
2803 		cpos += dp->d_reclen;
2804 		dp = (struct dirent *)cpos;
2805 		cookiep++;
2806 		ncookies--;
2807 	}
2808 	vrele(vp);
2809 	vfs_unbusy(mp);
2810 
2811 	/*
2812 	 * If dirlen > cnt, we must strip off the last entry. If that
2813 	 * results in an empty reply, report NFSERR_TOOSMALL.
2814 	 */
2815 	if (dirlen > cnt || nd->nd_repstat) {
2816 		if (!nd->nd_repstat && entrycnt == 0)
2817 			nd->nd_repstat = NFSERR_TOOSMALL;
2818 		if (nd->nd_repstat) {
2819 			nfsm_trimtrailing(nd, mb0, bpos0, bextpg0, bextpgsiz0);
2820 			if (nd->nd_flag & ND_NFSV3)
2821 				nfsrv_postopattr(nd, getret, &at);
2822 		} else
2823 			nfsm_trimtrailing(nd, mb1, bpos1, bextpg1, bextpgsiz1);
2824 		eofflag = 0;
2825 	} else if (cpos < cend)
2826 		eofflag = 0;
2827 	if (!nd->nd_repstat) {
2828 		NFSM_BUILD(tl, u_int32_t *, 2 * NFSX_UNSIGNED);
2829 		*tl++ = newnfs_false;
2830 		if (eofflag)
2831 			*tl = newnfs_true;
2832 		else
2833 			*tl = newnfs_false;
2834 	}
2835 	free(cookies, M_TEMP);
2836 	free(rbuf, M_TEMP);
2837 
2838 out:
2839 	NFSEXITCODE2(0, nd);
2840 	return (0);
2841 nfsmout:
2842 	vput(vp);
2843 	NFSEXITCODE2(error, nd);
2844 	return (error);
2845 }
2846 
2847 /*
2848  * Get the settable attributes out of the mbuf list.
2849  * (Return 0 or EBADRPC)
2850  */
2851 int
2852 nfsrv_sattr(struct nfsrv_descript *nd, vnode_t vp, struct nfsvattr *nvap,
2853     nfsattrbit_t *attrbitp, NFSACL_T *aclp, struct thread *p)
2854 {
2855 	u_int32_t *tl;
2856 	struct nfsv2_sattr *sp;
2857 	int error = 0, toclient = 0;
2858 
2859 	switch (nd->nd_flag & (ND_NFSV2 | ND_NFSV3 | ND_NFSV4)) {
2860 	case ND_NFSV2:
2861 		NFSM_DISSECT(sp, struct nfsv2_sattr *, NFSX_V2SATTR);
2862 		/*
2863 		 * Some old clients didn't fill in the high order 16bits.
2864 		 * --> check the low order 2 bytes for 0xffff
2865 		 */
2866 		if ((fxdr_unsigned(int, sp->sa_mode) & 0xffff) != 0xffff)
2867 			nvap->na_mode = nfstov_mode(sp->sa_mode);
2868 		if (sp->sa_uid != newnfs_xdrneg1)
2869 			nvap->na_uid = fxdr_unsigned(uid_t, sp->sa_uid);
2870 		if (sp->sa_gid != newnfs_xdrneg1)
2871 			nvap->na_gid = fxdr_unsigned(gid_t, sp->sa_gid);
2872 		if (sp->sa_size != newnfs_xdrneg1)
2873 			nvap->na_size = fxdr_unsigned(u_quad_t, sp->sa_size);
2874 		if (sp->sa_atime.nfsv2_sec != newnfs_xdrneg1) {
2875 #ifdef notyet
2876 			fxdr_nfsv2time(&sp->sa_atime, &nvap->na_atime);
2877 #else
2878 			nvap->na_atime.tv_sec =
2879 				fxdr_unsigned(u_int32_t,sp->sa_atime.nfsv2_sec);
2880 			nvap->na_atime.tv_nsec = 0;
2881 #endif
2882 		}
2883 		if (sp->sa_mtime.nfsv2_sec != newnfs_xdrneg1)
2884 			fxdr_nfsv2time(&sp->sa_mtime, &nvap->na_mtime);
2885 		break;
2886 	case ND_NFSV3:
2887 		NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
2888 		if (*tl == newnfs_true) {
2889 			NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
2890 			nvap->na_mode = nfstov_mode(*tl);
2891 		}
2892 		NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
2893 		if (*tl == newnfs_true) {
2894 			NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
2895 			nvap->na_uid = fxdr_unsigned(uid_t, *tl);
2896 		}
2897 		NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
2898 		if (*tl == newnfs_true) {
2899 			NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
2900 			nvap->na_gid = fxdr_unsigned(gid_t, *tl);
2901 		}
2902 		NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
2903 		if (*tl == newnfs_true) {
2904 			NFSM_DISSECT(tl, u_int32_t *, 2 * NFSX_UNSIGNED);
2905 			nvap->na_size = fxdr_hyper(tl);
2906 		}
2907 		NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
2908 		switch (fxdr_unsigned(int, *tl)) {
2909 		case NFSV3SATTRTIME_TOCLIENT:
2910 			NFSM_DISSECT(tl, u_int32_t *, 2 * NFSX_UNSIGNED);
2911 			fxdr_nfsv3time(tl, &nvap->na_atime);
2912 			toclient = 1;
2913 			break;
2914 		case NFSV3SATTRTIME_TOSERVER:
2915 			vfs_timestamp(&nvap->na_atime);
2916 			nvap->na_vaflags |= VA_UTIMES_NULL;
2917 			break;
2918 		}
2919 		NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
2920 		switch (fxdr_unsigned(int, *tl)) {
2921 		case NFSV3SATTRTIME_TOCLIENT:
2922 			NFSM_DISSECT(tl, u_int32_t *, 2 * NFSX_UNSIGNED);
2923 			fxdr_nfsv3time(tl, &nvap->na_mtime);
2924 			nvap->na_vaflags &= ~VA_UTIMES_NULL;
2925 			break;
2926 		case NFSV3SATTRTIME_TOSERVER:
2927 			vfs_timestamp(&nvap->na_mtime);
2928 			if (!toclient)
2929 				nvap->na_vaflags |= VA_UTIMES_NULL;
2930 			break;
2931 		}
2932 		break;
2933 	case ND_NFSV4:
2934 		error = nfsv4_sattr(nd, vp, nvap, attrbitp, aclp, p);
2935 	}
2936 nfsmout:
2937 	NFSEXITCODE2(error, nd);
2938 	return (error);
2939 }
2940 
2941 /*
2942  * Handle the setable attributes for V4.
2943  * Returns NFSERR_BADXDR if it can't be parsed, 0 otherwise.
2944  */
2945 int
2946 nfsv4_sattr(struct nfsrv_descript *nd, vnode_t vp, struct nfsvattr *nvap,
2947     nfsattrbit_t *attrbitp, NFSACL_T *aclp, struct thread *p)
2948 {
2949 	u_int32_t *tl;
2950 	int attrsum = 0;
2951 	int i, j;
2952 	int error, attrsize, bitpos, aclsize, aceerr, retnotsup = 0;
2953 	int moderet, toclient = 0;
2954 	u_char *cp, namestr[NFSV4_SMALLSTR + 1];
2955 	uid_t uid;
2956 	gid_t gid;
2957 	u_short mode, mask;		/* Same type as va_mode. */
2958 	struct vattr va;
2959 
2960 	error = nfsrv_getattrbits(nd, attrbitp, NULL, &retnotsup);
2961 	if (error)
2962 		goto nfsmout;
2963 	NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
2964 	attrsize = fxdr_unsigned(int, *tl);
2965 
2966 	/*
2967 	 * Loop around getting the setable attributes. If an unsupported
2968 	 * one is found, set nd_repstat == NFSERR_ATTRNOTSUPP and return.
2969 	 */
2970 	if (retnotsup) {
2971 		nd->nd_repstat = NFSERR_ATTRNOTSUPP;
2972 		bitpos = NFSATTRBIT_MAX;
2973 	} else {
2974 		bitpos = 0;
2975 	}
2976 	moderet = 0;
2977 	for (; bitpos < NFSATTRBIT_MAX; bitpos++) {
2978 	    if (attrsum > attrsize) {
2979 		error = NFSERR_BADXDR;
2980 		goto nfsmout;
2981 	    }
2982 	    if (NFSISSET_ATTRBIT(attrbitp, bitpos))
2983 		switch (bitpos) {
2984 		case NFSATTRBIT_SIZE:
2985 			NFSM_DISSECT(tl, u_int32_t *, NFSX_HYPER);
2986                      if (vp != NULL && vp->v_type != VREG) {
2987                             error = (vp->v_type == VDIR) ? NFSERR_ISDIR :
2988                                 NFSERR_INVAL;
2989                             goto nfsmout;
2990 			}
2991 			nvap->na_size = fxdr_hyper(tl);
2992 			attrsum += NFSX_HYPER;
2993 			break;
2994 		case NFSATTRBIT_ACL:
2995 			error = nfsrv_dissectacl(nd, aclp, &aceerr, &aclsize,
2996 			    p);
2997 			if (error)
2998 				goto nfsmout;
2999 			if (aceerr && !nd->nd_repstat)
3000 				nd->nd_repstat = aceerr;
3001 			attrsum += aclsize;
3002 			break;
3003 		case NFSATTRBIT_ARCHIVE:
3004 			NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
3005 			if (!nd->nd_repstat)
3006 				nd->nd_repstat = NFSERR_ATTRNOTSUPP;
3007 			attrsum += NFSX_UNSIGNED;
3008 			break;
3009 		case NFSATTRBIT_HIDDEN:
3010 			NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
3011 			if (!nd->nd_repstat)
3012 				nd->nd_repstat = NFSERR_ATTRNOTSUPP;
3013 			attrsum += NFSX_UNSIGNED;
3014 			break;
3015 		case NFSATTRBIT_MIMETYPE:
3016 			NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
3017 			i = fxdr_unsigned(int, *tl);
3018 			error = nfsm_advance(nd, NFSM_RNDUP(i), -1);
3019 			if (error)
3020 				goto nfsmout;
3021 			if (!nd->nd_repstat)
3022 				nd->nd_repstat = NFSERR_ATTRNOTSUPP;
3023 			attrsum += (NFSX_UNSIGNED + NFSM_RNDUP(i));
3024 			break;
3025 		case NFSATTRBIT_MODE:
3026 			moderet = NFSERR_INVAL;	/* Can't do MODESETMASKED. */
3027 			NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
3028 			nvap->na_mode = nfstov_mode(*tl);
3029 			attrsum += NFSX_UNSIGNED;
3030 			break;
3031 		case NFSATTRBIT_OWNER:
3032 			NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
3033 			j = fxdr_unsigned(int, *tl);
3034 			if (j < 0) {
3035 				error = NFSERR_BADXDR;
3036 				goto nfsmout;
3037 			}
3038 			if (j > NFSV4_SMALLSTR)
3039 				cp = malloc(j + 1, M_NFSSTRING, M_WAITOK);
3040 			else
3041 				cp = namestr;
3042 			error = nfsrv_mtostr(nd, cp, j);
3043 			if (error) {
3044 				if (j > NFSV4_SMALLSTR)
3045 					free(cp, M_NFSSTRING);
3046 				goto nfsmout;
3047 			}
3048 			if (!nd->nd_repstat) {
3049 				nd->nd_repstat = nfsv4_strtouid(nd, cp, j,
3050 				    &uid);
3051 				if (!nd->nd_repstat)
3052 					nvap->na_uid = uid;
3053 			}
3054 			if (j > NFSV4_SMALLSTR)
3055 				free(cp, M_NFSSTRING);
3056 			attrsum += (NFSX_UNSIGNED + NFSM_RNDUP(j));
3057 			break;
3058 		case NFSATTRBIT_OWNERGROUP:
3059 			NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
3060 			j = fxdr_unsigned(int, *tl);
3061 			if (j < 0) {
3062 				error = NFSERR_BADXDR;
3063 				goto nfsmout;
3064 			}
3065 			if (j > NFSV4_SMALLSTR)
3066 				cp = malloc(j + 1, M_NFSSTRING, M_WAITOK);
3067 			else
3068 				cp = namestr;
3069 			error = nfsrv_mtostr(nd, cp, j);
3070 			if (error) {
3071 				if (j > NFSV4_SMALLSTR)
3072 					free(cp, M_NFSSTRING);
3073 				goto nfsmout;
3074 			}
3075 			if (!nd->nd_repstat) {
3076 				nd->nd_repstat = nfsv4_strtogid(nd, cp, j,
3077 				    &gid);
3078 				if (!nd->nd_repstat)
3079 					nvap->na_gid = gid;
3080 			}
3081 			if (j > NFSV4_SMALLSTR)
3082 				free(cp, M_NFSSTRING);
3083 			attrsum += (NFSX_UNSIGNED + NFSM_RNDUP(j));
3084 			break;
3085 		case NFSATTRBIT_SYSTEM:
3086 			NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
3087 			if (!nd->nd_repstat)
3088 				nd->nd_repstat = NFSERR_ATTRNOTSUPP;
3089 			attrsum += NFSX_UNSIGNED;
3090 			break;
3091 		case NFSATTRBIT_TIMEACCESSSET:
3092 			NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
3093 			attrsum += NFSX_UNSIGNED;
3094 			if (fxdr_unsigned(int, *tl)==NFSV4SATTRTIME_TOCLIENT) {
3095 			    NFSM_DISSECT(tl, u_int32_t *, NFSX_V4TIME);
3096 			    fxdr_nfsv4time(tl, &nvap->na_atime);
3097 			    toclient = 1;
3098 			    attrsum += NFSX_V4TIME;
3099 			} else {
3100 			    vfs_timestamp(&nvap->na_atime);
3101 			    nvap->na_vaflags |= VA_UTIMES_NULL;
3102 			}
3103 			break;
3104 		case NFSATTRBIT_TIMEBACKUP:
3105 			NFSM_DISSECT(tl, u_int32_t *, NFSX_V4TIME);
3106 			if (!nd->nd_repstat)
3107 				nd->nd_repstat = NFSERR_ATTRNOTSUPP;
3108 			attrsum += NFSX_V4TIME;
3109 			break;
3110 		case NFSATTRBIT_TIMECREATE:
3111 			NFSM_DISSECT(tl, u_int32_t *, NFSX_V4TIME);
3112 			fxdr_nfsv4time(tl, &nvap->na_btime);
3113 			attrsum += NFSX_V4TIME;
3114 			break;
3115 		case NFSATTRBIT_TIMEMODIFYSET:
3116 			NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
3117 			attrsum += NFSX_UNSIGNED;
3118 			if (fxdr_unsigned(int, *tl)==NFSV4SATTRTIME_TOCLIENT) {
3119 			    NFSM_DISSECT(tl, u_int32_t *, NFSX_V4TIME);
3120 			    fxdr_nfsv4time(tl, &nvap->na_mtime);
3121 			    nvap->na_vaflags &= ~VA_UTIMES_NULL;
3122 			    attrsum += NFSX_V4TIME;
3123 			} else {
3124 			    vfs_timestamp(&nvap->na_mtime);
3125 			    if (!toclient)
3126 				nvap->na_vaflags |= VA_UTIMES_NULL;
3127 			}
3128 			break;
3129 		case NFSATTRBIT_MODESETMASKED:
3130 			NFSM_DISSECT(tl, uint32_t *, 2 * NFSX_UNSIGNED);
3131 			mode = fxdr_unsigned(u_short, *tl++);
3132 			mask = fxdr_unsigned(u_short, *tl);
3133 			/*
3134 			 * vp == NULL implies an Open/Create operation.
3135 			 * This attribute can only be used for Setattr and
3136 			 * only for NFSv4.1 or higher.
3137 			 * If moderet != 0, a mode attribute has also been
3138 			 * specified and this attribute cannot be done in the
3139 			 * same Setattr operation.
3140 			 */
3141 			if ((nd->nd_flag & ND_NFSV41) == 0)
3142 				nd->nd_repstat = NFSERR_ATTRNOTSUPP;
3143 			else if ((mode & ~07777) != 0 || (mask & ~07777) != 0 ||
3144 			    vp == NULL)
3145 				nd->nd_repstat = NFSERR_INVAL;
3146 			else if (moderet == 0)
3147 				moderet = VOP_GETATTR(vp, &va, nd->nd_cred);
3148 			if (moderet == 0)
3149 				nvap->na_mode = (mode & mask) |
3150 				    (va.va_mode & ~mask);
3151 			else
3152 				nd->nd_repstat = moderet;
3153 			attrsum += 2 * NFSX_UNSIGNED;
3154 			break;
3155 		default:
3156 			nd->nd_repstat = NFSERR_ATTRNOTSUPP;
3157 			/*
3158 			 * set bitpos so we drop out of the loop.
3159 			 */
3160 			bitpos = NFSATTRBIT_MAX;
3161 			break;
3162 		}
3163 	}
3164 
3165 	/*
3166 	 * some clients pad the attrlist, so we need to skip over the
3167 	 * padding.
3168 	 */
3169 	if (attrsum > attrsize) {
3170 		error = NFSERR_BADXDR;
3171 	} else {
3172 		attrsize = NFSM_RNDUP(attrsize);
3173 		if (attrsum < attrsize)
3174 			error = nfsm_advance(nd, attrsize - attrsum, -1);
3175 	}
3176 nfsmout:
3177 	NFSEXITCODE2(error, nd);
3178 	return (error);
3179 }
3180 
3181 /*
3182  * Check/setup export credentials.
3183  */
3184 int
3185 nfsd_excred(struct nfsrv_descript *nd, struct nfsexstuff *exp,
3186     struct ucred *credanon, bool testsec)
3187 {
3188 	int error;
3189 
3190 	/*
3191 	 * Check/setup credentials.
3192 	 */
3193 	if (nd->nd_flag & ND_GSS)
3194 		exp->nes_exflag &= ~MNT_EXPORTANON;
3195 
3196 	/*
3197 	 * Check to see if the operation is allowed for this security flavor.
3198 	 */
3199 	error = 0;
3200 	if (testsec) {
3201 		error = nfsvno_testexp(nd, exp);
3202 		if (error != 0)
3203 			goto out;
3204 	}
3205 
3206 	/*
3207 	 * Check to see if the file system is exported V4 only.
3208 	 */
3209 	if (NFSVNO_EXV4ONLY(exp) && !(nd->nd_flag & ND_NFSV4)) {
3210 		error = NFSERR_PROGNOTV4;
3211 		goto out;
3212 	}
3213 
3214 	/*
3215 	 * Now, map the user credentials.
3216 	 * (Note that ND_AUTHNONE will only be set for an NFSv3
3217 	 *  Fsinfo RPC. If set for anything else, this code might need
3218 	 *  to change.)
3219 	 */
3220 	if (NFSVNO_EXPORTED(exp)) {
3221 		if (((nd->nd_flag & ND_GSS) == 0 && nd->nd_cred->cr_uid == 0) ||
3222 		     NFSVNO_EXPORTANON(exp) ||
3223 		     (nd->nd_flag & ND_AUTHNONE) != 0) {
3224 			nd->nd_cred->cr_uid = credanon->cr_uid;
3225 			nd->nd_cred->cr_gid = credanon->cr_gid;
3226 			crsetgroups(nd->nd_cred, credanon->cr_ngroups,
3227 			    credanon->cr_groups);
3228 		} else if ((nd->nd_flag & ND_GSS) == 0) {
3229 			/*
3230 			 * If using AUTH_SYS, call nfsrv_getgrpscred() to see
3231 			 * if there is a replacement credential with a group
3232 			 * list set up by "nfsuserd -manage-gids".
3233 			 * If there is no replacement, nfsrv_getgrpscred()
3234 			 * simply returns its argument.
3235 			 */
3236 			nd->nd_cred = nfsrv_getgrpscred(nd->nd_cred);
3237 		}
3238 	}
3239 
3240 out:
3241 	NFSEXITCODE2(error, nd);
3242 	return (error);
3243 }
3244 
3245 /*
3246  * Check exports.
3247  */
3248 int
3249 nfsvno_checkexp(struct mount *mp, struct sockaddr *nam, struct nfsexstuff *exp,
3250     struct ucred **credp)
3251 {
3252 	int error;
3253 
3254 	error = VFS_CHECKEXP(mp, nam, &exp->nes_exflag, credp,
3255 	    &exp->nes_numsecflavor, exp->nes_secflavors);
3256 	if (error) {
3257 		if (nfs_rootfhset) {
3258 			exp->nes_exflag = 0;
3259 			exp->nes_numsecflavor = 0;
3260 			error = 0;
3261 		}
3262 	} else if (exp->nes_numsecflavor < 1 || exp->nes_numsecflavor >
3263 	    MAXSECFLAVORS) {
3264 		printf("nfsvno_checkexp: numsecflavors out of range\n");
3265 		exp->nes_numsecflavor = 0;
3266 		error = EACCES;
3267 	}
3268 	NFSEXITCODE(error);
3269 	return (error);
3270 }
3271 
3272 /*
3273  * Get a vnode for a file handle and export stuff.
3274  */
3275 int
3276 nfsvno_fhtovp(struct mount *mp, fhandle_t *fhp, struct sockaddr *nam,
3277     int lktype, struct vnode **vpp, struct nfsexstuff *exp,
3278     struct ucred **credp)
3279 {
3280 	int error;
3281 
3282 	*credp = NULL;
3283 	exp->nes_numsecflavor = 0;
3284 	error = VFS_FHTOVP(mp, &fhp->fh_fid, lktype, vpp);
3285 	if (error != 0)
3286 		/* Make sure the server replies ESTALE to the client. */
3287 		error = ESTALE;
3288 	if (nam && !error) {
3289 		error = VFS_CHECKEXP(mp, nam, &exp->nes_exflag, credp,
3290 		    &exp->nes_numsecflavor, exp->nes_secflavors);
3291 		if (error) {
3292 			if (nfs_rootfhset) {
3293 				exp->nes_exflag = 0;
3294 				exp->nes_numsecflavor = 0;
3295 				error = 0;
3296 			} else {
3297 				vput(*vpp);
3298 			}
3299 		} else if (exp->nes_numsecflavor < 1 || exp->nes_numsecflavor >
3300 		    MAXSECFLAVORS) {
3301 			printf("nfsvno_fhtovp: numsecflavors out of range\n");
3302 			exp->nes_numsecflavor = 0;
3303 			error = EACCES;
3304 			vput(*vpp);
3305 		}
3306 	}
3307 	NFSEXITCODE(error);
3308 	return (error);
3309 }
3310 
3311 /*
3312  * nfsd_fhtovp() - convert a fh to a vnode ptr
3313  * 	- look up fsid in mount list (if not found ret error)
3314  *	- get vp and export rights by calling nfsvno_fhtovp()
3315  *	- if cred->cr_uid == 0 or MNT_EXPORTANON set it to credanon
3316  *	  for AUTH_SYS
3317  *	- if mpp != NULL, return the mount point so that it can
3318  *	  be used for vn_finished_write() by the caller
3319  */
3320 void
3321 nfsd_fhtovp(struct nfsrv_descript *nd, struct nfsrvfh *nfp, int lktype,
3322     struct vnode **vpp, struct nfsexstuff *exp,
3323     struct mount **mpp, int startwrite, int nextop)
3324 {
3325 	struct mount *mp, *mpw;
3326 	struct ucred *credanon;
3327 	fhandle_t *fhp;
3328 	int error;
3329 
3330 	if (mpp != NULL)
3331 		*mpp = NULL;
3332 	*vpp = NULL;
3333 	fhp = (fhandle_t *)nfp->nfsrvfh_data;
3334 	mp = vfs_busyfs(&fhp->fh_fsid);
3335 	if (mp == NULL) {
3336 		nd->nd_repstat = ESTALE;
3337 		goto out;
3338 	}
3339 
3340 	if (startwrite) {
3341 		mpw = mp;
3342 		error = vn_start_write(NULL, &mpw, V_WAIT);
3343 		if (error != 0) {
3344 			mpw = NULL;
3345 			vfs_unbusy(mp);
3346 			nd->nd_repstat = ESTALE;
3347 			goto out;
3348 		}
3349 		if (lktype == LK_SHARED && !(MNT_SHARED_WRITES(mp)))
3350 			lktype = LK_EXCLUSIVE;
3351 	} else
3352 		mpw = NULL;
3353 
3354 	nd->nd_repstat = nfsvno_fhtovp(mp, fhp, nd->nd_nam, lktype, vpp, exp,
3355 	    &credanon);
3356 	vfs_unbusy(mp);
3357 
3358 	/*
3359 	 * For NFSv4 without a pseudo root fs, unexported file handles
3360 	 * can be returned, so that Lookup works everywhere.
3361 	 */
3362 	if (!nd->nd_repstat && exp->nes_exflag == 0 &&
3363 	    !(nd->nd_flag & ND_NFSV4)) {
3364 		vput(*vpp);
3365 		*vpp = NULL;
3366 		nd->nd_repstat = EACCES;
3367 	}
3368 
3369 	/*
3370 	 * Personally, I've never seen any point in requiring a
3371 	 * reserved port#, since only in the rare case where the
3372 	 * clients are all boxes with secure system privileges,
3373 	 * does it provide any enhanced security, but... some people
3374 	 * believe it to be useful and keep putting this code back in.
3375 	 * (There is also some "security checker" out there that
3376 	 *  complains if the nfs server doesn't enforce this.)
3377 	 * However, note the following:
3378 	 * RFC3530 (NFSv4) specifies that a reserved port# not be
3379 	 *	required.
3380 	 * RFC2623 recommends that, if a reserved port# is checked for,
3381 	 *	that there be a way to turn that off--> ifdef'd.
3382 	 */
3383 #ifdef NFS_REQRSVPORT
3384 	if (!nd->nd_repstat) {
3385 		struct sockaddr_in *saddr;
3386 		struct sockaddr_in6 *saddr6;
3387 
3388 		saddr = NFSSOCKADDR(nd->nd_nam, struct sockaddr_in *);
3389 		saddr6 = NFSSOCKADDR(nd->nd_nam, struct sockaddr_in6 *);
3390 		if (!(nd->nd_flag & ND_NFSV4) &&
3391 		    ((saddr->sin_family == AF_INET &&
3392 		      ntohs(saddr->sin_port) >= IPPORT_RESERVED) ||
3393 		     (saddr6->sin6_family == AF_INET6 &&
3394 		      ntohs(saddr6->sin6_port) >= IPPORT_RESERVED))) {
3395 			vput(*vpp);
3396 			nd->nd_repstat = (NFSERR_AUTHERR | AUTH_TOOWEAK);
3397 		}
3398 	}
3399 #endif	/* NFS_REQRSVPORT */
3400 
3401 	/*
3402 	 * Check/setup credentials.
3403 	 */
3404 	if (!nd->nd_repstat) {
3405 		nd->nd_saveduid = nd->nd_cred->cr_uid;
3406 		nd->nd_repstat = nfsd_excred(nd, exp, credanon,
3407 		    nfsrv_checkwrongsec(nd, nextop, (*vpp)->v_type));
3408 		if (nd->nd_repstat)
3409 			vput(*vpp);
3410 	}
3411 	if (credanon != NULL)
3412 		crfree(credanon);
3413 	if (nd->nd_repstat) {
3414 		vn_finished_write(mpw);
3415 		*vpp = NULL;
3416 	} else if (mpp != NULL) {
3417 		*mpp = mpw;
3418 	}
3419 
3420 out:
3421 	NFSEXITCODE2(0, nd);
3422 }
3423 
3424 /*
3425  * glue for fp.
3426  */
3427 static int
3428 fp_getfvp(struct thread *p, int fd, struct file **fpp, struct vnode **vpp)
3429 {
3430 	struct filedesc *fdp;
3431 	struct file *fp;
3432 	int error = 0;
3433 
3434 	fdp = p->td_proc->p_fd;
3435 	if (fd < 0 || fd >= fdp->fd_nfiles ||
3436 	    (fp = fdp->fd_ofiles[fd].fde_file) == NULL) {
3437 		error = EBADF;
3438 		goto out;
3439 	}
3440 	*fpp = fp;
3441 
3442 out:
3443 	NFSEXITCODE(error);
3444 	return (error);
3445 }
3446 
3447 /*
3448  * Called from nfssvc() to update the exports list. Just call
3449  * vfs_export(). This has to be done, since the v4 root fake fs isn't
3450  * in the mount list.
3451  */
3452 int
3453 nfsrv_v4rootexport(void *argp, struct ucred *cred, struct thread *p)
3454 {
3455 	struct nfsex_args *nfsexargp = (struct nfsex_args *)argp;
3456 	int error = 0;
3457 	struct nameidata nd;
3458 	fhandle_t fh;
3459 
3460 	error = vfs_export(&nfsv4root_mnt, &nfsexargp->export);
3461 	if ((nfsexargp->export.ex_flags & MNT_DELEXPORT) != 0)
3462 		nfs_rootfhset = 0;
3463 	else if (error == 0) {
3464 		if (nfsexargp->fspec == NULL) {
3465 			error = EPERM;
3466 			goto out;
3467 		}
3468 		/*
3469 		 * If fspec != NULL, this is the v4root path.
3470 		 */
3471 		NDINIT(&nd, LOOKUP, FOLLOW, UIO_USERSPACE,
3472 		    nfsexargp->fspec, p);
3473 		if ((error = namei(&nd)) != 0)
3474 			goto out;
3475 		error = nfsvno_getfh(nd.ni_vp, &fh, p);
3476 		vrele(nd.ni_vp);
3477 		if (!error) {
3478 			nfs_rootfh.nfsrvfh_len = NFSX_MYFH;
3479 			NFSBCOPY((caddr_t)&fh,
3480 			    nfs_rootfh.nfsrvfh_data,
3481 			    sizeof (fhandle_t));
3482 			nfs_rootfhset = 1;
3483 		}
3484 	}
3485 
3486 out:
3487 	NFSEXITCODE(error);
3488 	return (error);
3489 }
3490 
3491 /*
3492  * This function needs to test to see if the system is near its limit
3493  * for memory allocation via malloc() or mget() and return True iff
3494  * either of these resources are near their limit.
3495  * XXX (For now, this is just a stub.)
3496  */
3497 int nfsrv_testmalloclimit = 0;
3498 int
3499 nfsrv_mallocmget_limit(void)
3500 {
3501 	static int printmesg = 0;
3502 	static int testval = 1;
3503 
3504 	if (nfsrv_testmalloclimit && (testval++ % 1000) == 0) {
3505 		if ((printmesg++ % 100) == 0)
3506 			printf("nfsd: malloc/mget near limit\n");
3507 		return (1);
3508 	}
3509 	return (0);
3510 }
3511 
3512 /*
3513  * BSD specific initialization of a mount point.
3514  */
3515 void
3516 nfsd_mntinit(void)
3517 {
3518 	static int inited = 0;
3519 
3520 	if (inited)
3521 		return;
3522 	inited = 1;
3523 	nfsv4root_mnt.mnt_flag = (MNT_RDONLY | MNT_EXPORTED);
3524 	TAILQ_INIT(&nfsv4root_mnt.mnt_nvnodelist);
3525 	TAILQ_INIT(&nfsv4root_mnt.mnt_lazyvnodelist);
3526 	nfsv4root_mnt.mnt_export = NULL;
3527 	TAILQ_INIT(&nfsv4root_opt);
3528 	TAILQ_INIT(&nfsv4root_newopt);
3529 	nfsv4root_mnt.mnt_opt = &nfsv4root_opt;
3530 	nfsv4root_mnt.mnt_optnew = &nfsv4root_newopt;
3531 	nfsv4root_mnt.mnt_nvnodelistsize = 0;
3532 	nfsv4root_mnt.mnt_lazyvnodelistsize = 0;
3533 }
3534 
3535 /*
3536  * Get a vnode for a file handle, without checking exports, etc.
3537  */
3538 struct vnode *
3539 nfsvno_getvp(fhandle_t *fhp)
3540 {
3541 	struct mount *mp;
3542 	struct vnode *vp;
3543 	int error;
3544 
3545 	mp = vfs_busyfs(&fhp->fh_fsid);
3546 	if (mp == NULL)
3547 		return (NULL);
3548 	error = VFS_FHTOVP(mp, &fhp->fh_fid, LK_EXCLUSIVE, &vp);
3549 	vfs_unbusy(mp);
3550 	if (error)
3551 		return (NULL);
3552 	return (vp);
3553 }
3554 
3555 /*
3556  * Do a local VOP_ADVLOCK().
3557  */
3558 int
3559 nfsvno_advlock(struct vnode *vp, int ftype, u_int64_t first,
3560     u_int64_t end, struct thread *td)
3561 {
3562 	int error = 0;
3563 	struct flock fl;
3564 	u_int64_t tlen;
3565 
3566 	if (nfsrv_dolocallocks == 0)
3567 		goto out;
3568 	ASSERT_VOP_UNLOCKED(vp, "nfsvno_advlock: vp locked");
3569 
3570 	fl.l_whence = SEEK_SET;
3571 	fl.l_type = ftype;
3572 	fl.l_start = (off_t)first;
3573 	if (end == NFS64BITSSET) {
3574 		fl.l_len = 0;
3575 	} else {
3576 		tlen = end - first;
3577 		fl.l_len = (off_t)tlen;
3578 	}
3579 	/*
3580 	 * For FreeBSD8, the l_pid and l_sysid must be set to the same
3581 	 * values for all calls, so that all locks will be held by the
3582 	 * nfsd server. (The nfsd server handles conflicts between the
3583 	 * various clients.)
3584 	 * Since an NFSv4 lockowner is a ClientID plus an array of up to 1024
3585 	 * bytes, so it can't be put in l_sysid.
3586 	 */
3587 	if (nfsv4_sysid == 0)
3588 		nfsv4_sysid = nlm_acquire_next_sysid();
3589 	fl.l_pid = (pid_t)0;
3590 	fl.l_sysid = (int)nfsv4_sysid;
3591 
3592 	if (ftype == F_UNLCK)
3593 		error = VOP_ADVLOCK(vp, (caddr_t)td->td_proc, F_UNLCK, &fl,
3594 		    (F_POSIX | F_REMOTE));
3595 	else
3596 		error = VOP_ADVLOCK(vp, (caddr_t)td->td_proc, F_SETLK, &fl,
3597 		    (F_POSIX | F_REMOTE));
3598 
3599 out:
3600 	NFSEXITCODE(error);
3601 	return (error);
3602 }
3603 
3604 /*
3605  * Check the nfsv4 root exports.
3606  */
3607 int
3608 nfsvno_v4rootexport(struct nfsrv_descript *nd)
3609 {
3610 	struct ucred *credanon;
3611 	int error = 0, numsecflavor, secflavors[MAXSECFLAVORS], i;
3612 	uint64_t exflags;
3613 
3614 	error = vfs_stdcheckexp(&nfsv4root_mnt, nd->nd_nam, &exflags,
3615 	    &credanon, &numsecflavor, secflavors);
3616 	if (error) {
3617 		error = NFSERR_PROGUNAVAIL;
3618 		goto out;
3619 	}
3620 	if (credanon != NULL)
3621 		crfree(credanon);
3622 	for (i = 0; i < numsecflavor; i++) {
3623 		if (secflavors[i] == AUTH_SYS)
3624 			nd->nd_flag |= ND_EXAUTHSYS;
3625 		else if (secflavors[i] == RPCSEC_GSS_KRB5)
3626 			nd->nd_flag |= ND_EXGSS;
3627 		else if (secflavors[i] == RPCSEC_GSS_KRB5I)
3628 			nd->nd_flag |= ND_EXGSSINTEGRITY;
3629 		else if (secflavors[i] == RPCSEC_GSS_KRB5P)
3630 			nd->nd_flag |= ND_EXGSSPRIVACY;
3631 	}
3632 
3633 	/* And set ND_EXxx flags for TLS. */
3634 	if ((exflags & MNT_EXTLS) != 0) {
3635 		nd->nd_flag |= ND_EXTLS;
3636 		if ((exflags & MNT_EXTLSCERT) != 0)
3637 			nd->nd_flag |= ND_EXTLSCERT;
3638 		if ((exflags & MNT_EXTLSCERTUSER) != 0)
3639 			nd->nd_flag |= ND_EXTLSCERTUSER;
3640 	}
3641 
3642 out:
3643 	NFSEXITCODE(error);
3644 	return (error);
3645 }
3646 
3647 /*
3648  * Nfs server pseudo system call for the nfsd's
3649  */
3650 /*
3651  * MPSAFE
3652  */
3653 static int
3654 nfssvc_nfsd(struct thread *td, struct nfssvc_args *uap)
3655 {
3656 	struct file *fp;
3657 	struct nfsd_addsock_args sockarg;
3658 	struct nfsd_nfsd_args nfsdarg;
3659 	struct nfsd_nfsd_oargs onfsdarg;
3660 	struct nfsd_pnfsd_args pnfsdarg;
3661 	struct vnode *vp, *nvp, *curdvp;
3662 	struct pnfsdsfile *pf;
3663 	struct nfsdevice *ds, *fds;
3664 	cap_rights_t rights;
3665 	int buflen, error, ret;
3666 	char *buf, *cp, *cp2, *cp3;
3667 	char fname[PNFS_FILENAME_LEN + 1];
3668 
3669 	if (uap->flag & NFSSVC_NFSDADDSOCK) {
3670 		error = copyin(uap->argp, (caddr_t)&sockarg, sizeof (sockarg));
3671 		if (error)
3672 			goto out;
3673 		/*
3674 		 * Since we don't know what rights might be required,
3675 		 * pretend that we need them all. It is better to be too
3676 		 * careful than too reckless.
3677 		 */
3678 		error = fget(td, sockarg.sock,
3679 		    cap_rights_init_one(&rights, CAP_SOCK_SERVER), &fp);
3680 		if (error != 0)
3681 			goto out;
3682 		if (fp->f_type != DTYPE_SOCKET) {
3683 			fdrop(fp, td);
3684 			error = EPERM;
3685 			goto out;
3686 		}
3687 		error = nfsrvd_addsock(fp);
3688 		fdrop(fp, td);
3689 	} else if (uap->flag & NFSSVC_NFSDNFSD) {
3690 		if (uap->argp == NULL) {
3691 			error = EINVAL;
3692 			goto out;
3693 		}
3694 		if ((uap->flag & NFSSVC_NEWSTRUCT) == 0) {
3695 			error = copyin(uap->argp, &onfsdarg, sizeof(onfsdarg));
3696 			if (error == 0) {
3697 				nfsdarg.principal = onfsdarg.principal;
3698 				nfsdarg.minthreads = onfsdarg.minthreads;
3699 				nfsdarg.maxthreads = onfsdarg.maxthreads;
3700 				nfsdarg.version = 1;
3701 				nfsdarg.addr = NULL;
3702 				nfsdarg.addrlen = 0;
3703 				nfsdarg.dnshost = NULL;
3704 				nfsdarg.dnshostlen = 0;
3705 				nfsdarg.dspath = NULL;
3706 				nfsdarg.dspathlen = 0;
3707 				nfsdarg.mdspath = NULL;
3708 				nfsdarg.mdspathlen = 0;
3709 				nfsdarg.mirrorcnt = 1;
3710 			}
3711 		} else
3712 			error = copyin(uap->argp, &nfsdarg, sizeof(nfsdarg));
3713 		if (error)
3714 			goto out;
3715 		if (nfsdarg.addrlen > 0 && nfsdarg.addrlen < 10000 &&
3716 		    nfsdarg.dnshostlen > 0 && nfsdarg.dnshostlen < 10000 &&
3717 		    nfsdarg.dspathlen > 0 && nfsdarg.dspathlen < 10000 &&
3718 		    nfsdarg.mdspathlen > 0 && nfsdarg.mdspathlen < 10000 &&
3719 		    nfsdarg.mirrorcnt >= 1 &&
3720 		    nfsdarg.mirrorcnt <= NFSDEV_MAXMIRRORS &&
3721 		    nfsdarg.addr != NULL && nfsdarg.dnshost != NULL &&
3722 		    nfsdarg.dspath != NULL && nfsdarg.mdspath != NULL) {
3723 			NFSD_DEBUG(1, "addrlen=%d dspathlen=%d dnslen=%d"
3724 			    " mdspathlen=%d mirrorcnt=%d\n", nfsdarg.addrlen,
3725 			    nfsdarg.dspathlen, nfsdarg.dnshostlen,
3726 			    nfsdarg.mdspathlen, nfsdarg.mirrorcnt);
3727 			cp = malloc(nfsdarg.addrlen + 1, M_TEMP, M_WAITOK);
3728 			error = copyin(nfsdarg.addr, cp, nfsdarg.addrlen);
3729 			if (error != 0) {
3730 				free(cp, M_TEMP);
3731 				goto out;
3732 			}
3733 			cp[nfsdarg.addrlen] = '\0';	/* Ensure nul term. */
3734 			nfsdarg.addr = cp;
3735 			cp = malloc(nfsdarg.dnshostlen + 1, M_TEMP, M_WAITOK);
3736 			error = copyin(nfsdarg.dnshost, cp, nfsdarg.dnshostlen);
3737 			if (error != 0) {
3738 				free(nfsdarg.addr, M_TEMP);
3739 				free(cp, M_TEMP);
3740 				goto out;
3741 			}
3742 			cp[nfsdarg.dnshostlen] = '\0';	/* Ensure nul term. */
3743 			nfsdarg.dnshost = cp;
3744 			cp = malloc(nfsdarg.dspathlen + 1, M_TEMP, M_WAITOK);
3745 			error = copyin(nfsdarg.dspath, cp, nfsdarg.dspathlen);
3746 			if (error != 0) {
3747 				free(nfsdarg.addr, M_TEMP);
3748 				free(nfsdarg.dnshost, M_TEMP);
3749 				free(cp, M_TEMP);
3750 				goto out;
3751 			}
3752 			cp[nfsdarg.dspathlen] = '\0';	/* Ensure nul term. */
3753 			nfsdarg.dspath = cp;
3754 			cp = malloc(nfsdarg.mdspathlen + 1, M_TEMP, M_WAITOK);
3755 			error = copyin(nfsdarg.mdspath, cp, nfsdarg.mdspathlen);
3756 			if (error != 0) {
3757 				free(nfsdarg.addr, M_TEMP);
3758 				free(nfsdarg.dnshost, M_TEMP);
3759 				free(nfsdarg.dspath, M_TEMP);
3760 				free(cp, M_TEMP);
3761 				goto out;
3762 			}
3763 			cp[nfsdarg.mdspathlen] = '\0';	/* Ensure nul term. */
3764 			nfsdarg.mdspath = cp;
3765 		} else {
3766 			nfsdarg.addr = NULL;
3767 			nfsdarg.addrlen = 0;
3768 			nfsdarg.dnshost = NULL;
3769 			nfsdarg.dnshostlen = 0;
3770 			nfsdarg.dspath = NULL;
3771 			nfsdarg.dspathlen = 0;
3772 			nfsdarg.mdspath = NULL;
3773 			nfsdarg.mdspathlen = 0;
3774 			nfsdarg.mirrorcnt = 1;
3775 		}
3776 		error = nfsrvd_nfsd(td, &nfsdarg);
3777 		free(nfsdarg.addr, M_TEMP);
3778 		free(nfsdarg.dnshost, M_TEMP);
3779 		free(nfsdarg.dspath, M_TEMP);
3780 		free(nfsdarg.mdspath, M_TEMP);
3781 	} else if (uap->flag & NFSSVC_PNFSDS) {
3782 		error = copyin(uap->argp, &pnfsdarg, sizeof(pnfsdarg));
3783 		if (error == 0 && (pnfsdarg.op == PNFSDOP_DELDSSERVER ||
3784 		    pnfsdarg.op == PNFSDOP_FORCEDELDS)) {
3785 			cp = malloc(PATH_MAX + 1, M_TEMP, M_WAITOK);
3786 			error = copyinstr(pnfsdarg.dspath, cp, PATH_MAX + 1,
3787 			    NULL);
3788 			if (error == 0)
3789 				error = nfsrv_deldsserver(pnfsdarg.op, cp, td);
3790 			free(cp, M_TEMP);
3791 		} else if (error == 0 && pnfsdarg.op == PNFSDOP_COPYMR) {
3792 			cp = malloc(PATH_MAX + 1, M_TEMP, M_WAITOK);
3793 			buflen = sizeof(*pf) * NFSDEV_MAXMIRRORS;
3794 			buf = malloc(buflen, M_TEMP, M_WAITOK);
3795 			error = copyinstr(pnfsdarg.mdspath, cp, PATH_MAX + 1,
3796 			    NULL);
3797 			NFSD_DEBUG(4, "pnfsdcopymr cp mdspath=%d\n", error);
3798 			if (error == 0 && pnfsdarg.dspath != NULL) {
3799 				cp2 = malloc(PATH_MAX + 1, M_TEMP, M_WAITOK);
3800 				error = copyinstr(pnfsdarg.dspath, cp2,
3801 				    PATH_MAX + 1, NULL);
3802 				NFSD_DEBUG(4, "pnfsdcopymr cp dspath=%d\n",
3803 				    error);
3804 			} else
3805 				cp2 = NULL;
3806 			if (error == 0 && pnfsdarg.curdspath != NULL) {
3807 				cp3 = malloc(PATH_MAX + 1, M_TEMP, M_WAITOK);
3808 				error = copyinstr(pnfsdarg.curdspath, cp3,
3809 				    PATH_MAX + 1, NULL);
3810 				NFSD_DEBUG(4, "pnfsdcopymr cp curdspath=%d\n",
3811 				    error);
3812 			} else
3813 				cp3 = NULL;
3814 			curdvp = NULL;
3815 			fds = NULL;
3816 			if (error == 0)
3817 				error = nfsrv_mdscopymr(cp, cp2, cp3, buf,
3818 				    &buflen, fname, td, &vp, &nvp, &pf, &ds,
3819 				    &fds);
3820 			NFSD_DEBUG(4, "nfsrv_mdscopymr=%d\n", error);
3821 			if (error == 0) {
3822 				if (pf->dsf_dir >= nfsrv_dsdirsize) {
3823 					printf("copymr: dsdir out of range\n");
3824 					pf->dsf_dir = 0;
3825 				}
3826 				NFSD_DEBUG(4, "copymr: buflen=%d\n", buflen);
3827 				error = nfsrv_copymr(vp, nvp,
3828 				    ds->nfsdev_dsdir[pf->dsf_dir], ds, pf,
3829 				    (struct pnfsdsfile *)buf,
3830 				    buflen / sizeof(*pf), td->td_ucred, td);
3831 				vput(vp);
3832 				vput(nvp);
3833 				if (fds != NULL && error == 0) {
3834 					curdvp = fds->nfsdev_dsdir[pf->dsf_dir];
3835 					ret = vn_lock(curdvp, LK_EXCLUSIVE);
3836 					if (ret == 0) {
3837 						nfsrv_dsremove(curdvp, fname,
3838 						    td->td_ucred, td);
3839 						NFSVOPUNLOCK(curdvp);
3840 					}
3841 				}
3842 				NFSD_DEBUG(4, "nfsrv_copymr=%d\n", error);
3843 			}
3844 			free(cp, M_TEMP);
3845 			free(cp2, M_TEMP);
3846 			free(cp3, M_TEMP);
3847 			free(buf, M_TEMP);
3848 		}
3849 	} else {
3850 		error = nfssvc_srvcall(td, uap, td->td_ucred);
3851 	}
3852 
3853 out:
3854 	NFSEXITCODE(error);
3855 	return (error);
3856 }
3857 
3858 static int
3859 nfssvc_srvcall(struct thread *p, struct nfssvc_args *uap, struct ucred *cred)
3860 {
3861 	struct nfsex_args export;
3862 	struct nfsex_oldargs oexp;
3863 	struct file *fp = NULL;
3864 	int stablefd, i, len;
3865 	struct nfsd_clid adminrevoke;
3866 	struct nfsd_dumplist dumplist;
3867 	struct nfsd_dumpclients *dumpclients;
3868 	struct nfsd_dumplocklist dumplocklist;
3869 	struct nfsd_dumplocks *dumplocks;
3870 	struct nameidata nd;
3871 	vnode_t vp;
3872 	int error = EINVAL, igotlock;
3873 	struct proc *procp;
3874 	gid_t *grps;
3875 	static int suspend_nfsd = 0;
3876 
3877 	if (uap->flag & NFSSVC_PUBLICFH) {
3878 		NFSBZERO((caddr_t)&nfs_pubfh.nfsrvfh_data,
3879 		    sizeof (fhandle_t));
3880 		error = copyin(uap->argp,
3881 		    &nfs_pubfh.nfsrvfh_data, sizeof (fhandle_t));
3882 		if (!error)
3883 			nfs_pubfhset = 1;
3884 	} else if ((uap->flag & (NFSSVC_V4ROOTEXPORT | NFSSVC_NEWSTRUCT)) ==
3885 	    (NFSSVC_V4ROOTEXPORT | NFSSVC_NEWSTRUCT)) {
3886 		error = copyin(uap->argp,(caddr_t)&export,
3887 		    sizeof (struct nfsex_args));
3888 		if (!error) {
3889 			grps = NULL;
3890 			if (export.export.ex_ngroups > NGROUPS_MAX ||
3891 			    export.export.ex_ngroups < 0)
3892 				error = EINVAL;
3893 			else if (export.export.ex_ngroups > 0) {
3894 				grps = malloc(export.export.ex_ngroups *
3895 				    sizeof(gid_t), M_TEMP, M_WAITOK);
3896 				error = copyin(export.export.ex_groups, grps,
3897 				    export.export.ex_ngroups * sizeof(gid_t));
3898 				export.export.ex_groups = grps;
3899 			} else
3900 				export.export.ex_groups = NULL;
3901 			if (!error)
3902 				error = nfsrv_v4rootexport(&export, cred, p);
3903 			free(grps, M_TEMP);
3904 		}
3905 	} else if ((uap->flag & (NFSSVC_V4ROOTEXPORT | NFSSVC_NEWSTRUCT)) ==
3906 	    NFSSVC_V4ROOTEXPORT) {
3907 		error = copyin(uap->argp,(caddr_t)&oexp,
3908 		    sizeof (struct nfsex_oldargs));
3909 		if (!error) {
3910 			memset(&export.export, 0, sizeof(export.export));
3911 			export.export.ex_flags = (uint64_t)oexp.export.ex_flags;
3912 			export.export.ex_root = oexp.export.ex_root;
3913 			export.export.ex_uid = oexp.export.ex_anon.cr_uid;
3914 			export.export.ex_ngroups =
3915 			    oexp.export.ex_anon.cr_ngroups;
3916 			export.export.ex_groups = NULL;
3917 			if (export.export.ex_ngroups > XU_NGROUPS ||
3918 			    export.export.ex_ngroups < 0)
3919 				error = EINVAL;
3920 			else if (export.export.ex_ngroups > 0) {
3921 				export.export.ex_groups = malloc(
3922 				    export.export.ex_ngroups * sizeof(gid_t),
3923 				    M_TEMP, M_WAITOK);
3924 				for (i = 0; i < export.export.ex_ngroups; i++)
3925 					export.export.ex_groups[i] =
3926 					    oexp.export.ex_anon.cr_groups[i];
3927 			}
3928 			export.export.ex_addr = oexp.export.ex_addr;
3929 			export.export.ex_addrlen = oexp.export.ex_addrlen;
3930 			export.export.ex_mask = oexp.export.ex_mask;
3931 			export.export.ex_masklen = oexp.export.ex_masklen;
3932 			export.export.ex_indexfile = oexp.export.ex_indexfile;
3933 			export.export.ex_numsecflavors =
3934 			    oexp.export.ex_numsecflavors;
3935 			if (export.export.ex_numsecflavors >= MAXSECFLAVORS ||
3936 			    export.export.ex_numsecflavors < 0)
3937 				error = EINVAL;
3938 			else {
3939 				for (i = 0; i < export.export.ex_numsecflavors;
3940 				    i++)
3941 					export.export.ex_secflavors[i] =
3942 					    oexp.export.ex_secflavors[i];
3943 			}
3944 			export.fspec = oexp.fspec;
3945 			if (error == 0)
3946 				error = nfsrv_v4rootexport(&export, cred, p);
3947 			free(export.export.ex_groups, M_TEMP);
3948 		}
3949 	} else if (uap->flag & NFSSVC_NOPUBLICFH) {
3950 		nfs_pubfhset = 0;
3951 		error = 0;
3952 	} else if (uap->flag & NFSSVC_STABLERESTART) {
3953 		error = copyin(uap->argp, (caddr_t)&stablefd,
3954 		    sizeof (int));
3955 		if (!error)
3956 			error = fp_getfvp(p, stablefd, &fp, &vp);
3957 		if (!error && (NFSFPFLAG(fp) & (FREAD | FWRITE)) != (FREAD | FWRITE))
3958 			error = EBADF;
3959 		if (!error && newnfs_numnfsd != 0)
3960 			error = EPERM;
3961 		if (!error) {
3962 			nfsrv_stablefirst.nsf_fp = fp;
3963 			nfsrv_setupstable(p);
3964 		}
3965 	} else if (uap->flag & NFSSVC_ADMINREVOKE) {
3966 		error = copyin(uap->argp, (caddr_t)&adminrevoke,
3967 		    sizeof (struct nfsd_clid));
3968 		if (!error)
3969 			error = nfsrv_adminrevoke(&adminrevoke, p);
3970 	} else if (uap->flag & NFSSVC_DUMPCLIENTS) {
3971 		error = copyin(uap->argp, (caddr_t)&dumplist,
3972 		    sizeof (struct nfsd_dumplist));
3973 		if (!error && (dumplist.ndl_size < 1 ||
3974 			dumplist.ndl_size > NFSRV_MAXDUMPLIST))
3975 			error = EPERM;
3976 		if (!error) {
3977 		    len = sizeof (struct nfsd_dumpclients) * dumplist.ndl_size;
3978 		    dumpclients = malloc(len, M_TEMP, M_WAITOK | M_ZERO);
3979 		    nfsrv_dumpclients(dumpclients, dumplist.ndl_size);
3980 		    error = copyout(dumpclients, dumplist.ndl_list, len);
3981 		    free(dumpclients, M_TEMP);
3982 		}
3983 	} else if (uap->flag & NFSSVC_DUMPLOCKS) {
3984 		error = copyin(uap->argp, (caddr_t)&dumplocklist,
3985 		    sizeof (struct nfsd_dumplocklist));
3986 		if (!error && (dumplocklist.ndllck_size < 1 ||
3987 			dumplocklist.ndllck_size > NFSRV_MAXDUMPLIST))
3988 			error = EPERM;
3989 		if (!error)
3990 			error = nfsrv_lookupfilename(&nd,
3991 				dumplocklist.ndllck_fname, p);
3992 		if (!error) {
3993 			len = sizeof (struct nfsd_dumplocks) *
3994 				dumplocklist.ndllck_size;
3995 			dumplocks = malloc(len, M_TEMP, M_WAITOK | M_ZERO);
3996 			nfsrv_dumplocks(nd.ni_vp, dumplocks,
3997 			    dumplocklist.ndllck_size, p);
3998 			vput(nd.ni_vp);
3999 			error = copyout(dumplocks, dumplocklist.ndllck_list,
4000 			    len);
4001 			free(dumplocks, M_TEMP);
4002 		}
4003 	} else if (uap->flag & NFSSVC_BACKUPSTABLE) {
4004 		procp = p->td_proc;
4005 		PROC_LOCK(procp);
4006 		nfsd_master_pid = procp->p_pid;
4007 		bcopy(procp->p_comm, nfsd_master_comm, MAXCOMLEN + 1);
4008 		nfsd_master_start = procp->p_stats->p_start;
4009 		nfsd_master_proc = procp;
4010 		PROC_UNLOCK(procp);
4011 	} else if ((uap->flag & NFSSVC_SUSPENDNFSD) != 0) {
4012 		NFSLOCKV4ROOTMUTEX();
4013 		if (suspend_nfsd == 0) {
4014 			/* Lock out all nfsd threads */
4015 			do {
4016 				igotlock = nfsv4_lock(&nfsd_suspend_lock, 1,
4017 				    NULL, NFSV4ROOTLOCKMUTEXPTR, NULL);
4018 			} while (igotlock == 0 && suspend_nfsd == 0);
4019 			suspend_nfsd = 1;
4020 		}
4021 		NFSUNLOCKV4ROOTMUTEX();
4022 		error = 0;
4023 	} else if ((uap->flag & NFSSVC_RESUMENFSD) != 0) {
4024 		NFSLOCKV4ROOTMUTEX();
4025 		if (suspend_nfsd != 0) {
4026 			nfsv4_unlock(&nfsd_suspend_lock, 0);
4027 			suspend_nfsd = 0;
4028 		}
4029 		NFSUNLOCKV4ROOTMUTEX();
4030 		error = 0;
4031 	}
4032 
4033 	NFSEXITCODE(error);
4034 	return (error);
4035 }
4036 
4037 /*
4038  * Check exports.
4039  * Returns 0 if ok, 1 otherwise.
4040  */
4041 int
4042 nfsvno_testexp(struct nfsrv_descript *nd, struct nfsexstuff *exp)
4043 {
4044 	int i;
4045 
4046 	/*
4047 	 * Allow NFSv3 Fsinfo per RFC2623.
4048 	 */
4049 	if (((nd->nd_flag & ND_NFSV4) != 0 ||
4050 	     nd->nd_procnum != NFSPROC_FSINFO) &&
4051 	    ((NFSVNO_EXTLS(exp) && (nd->nd_flag & ND_TLS) == 0) ||
4052 	     (NFSVNO_EXTLSCERT(exp) &&
4053 	      (nd->nd_flag & ND_TLSCERT) == 0) ||
4054 	     (NFSVNO_EXTLSCERTUSER(exp) &&
4055 	      (nd->nd_flag & ND_TLSCERTUSER) == 0))) {
4056 		if ((nd->nd_flag & ND_NFSV4) != 0)
4057 			return (NFSERR_WRONGSEC);
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 	}
4063 
4064 	/*
4065 	 * This seems odd, but allow the case where the security flavor
4066 	 * list is empty. This happens when NFSv4 is traversing non-exported
4067 	 * file systems. Exported file systems should always have a non-empty
4068 	 * security flavor list.
4069 	 */
4070 	if (exp->nes_numsecflavor == 0)
4071 		return (0);
4072 
4073 	for (i = 0; i < exp->nes_numsecflavor; i++) {
4074 		/*
4075 		 * The tests for privacy and integrity must be first,
4076 		 * since ND_GSS is set for everything but AUTH_SYS.
4077 		 */
4078 		if (exp->nes_secflavors[i] == RPCSEC_GSS_KRB5P &&
4079 		    (nd->nd_flag & ND_GSSPRIVACY))
4080 			return (0);
4081 		if (exp->nes_secflavors[i] == RPCSEC_GSS_KRB5I &&
4082 		    (nd->nd_flag & ND_GSSINTEGRITY))
4083 			return (0);
4084 		if (exp->nes_secflavors[i] == RPCSEC_GSS_KRB5 &&
4085 		    (nd->nd_flag & ND_GSS))
4086 			return (0);
4087 		if (exp->nes_secflavors[i] == AUTH_SYS &&
4088 		    (nd->nd_flag & ND_GSS) == 0)
4089 			return (0);
4090 	}
4091 	if ((nd->nd_flag & ND_NFSV4) != 0)
4092 		return (NFSERR_WRONGSEC);
4093 	return (NFSERR_AUTHERR | AUTH_TOOWEAK);
4094 }
4095 
4096 /*
4097  * Calculate a hash value for the fid in a file handle.
4098  */
4099 uint32_t
4100 nfsrv_hashfh(fhandle_t *fhp)
4101 {
4102 	uint32_t hashval;
4103 
4104 	hashval = hash32_buf(&fhp->fh_fid, sizeof(struct fid), 0);
4105 	return (hashval);
4106 }
4107 
4108 /*
4109  * Calculate a hash value for the sessionid.
4110  */
4111 uint32_t
4112 nfsrv_hashsessionid(uint8_t *sessionid)
4113 {
4114 	uint32_t hashval;
4115 
4116 	hashval = hash32_buf(sessionid, NFSX_V4SESSIONID, 0);
4117 	return (hashval);
4118 }
4119 
4120 /*
4121  * Signal the userland master nfsd to backup the stable restart file.
4122  */
4123 void
4124 nfsrv_backupstable(void)
4125 {
4126 	struct proc *procp;
4127 
4128 	if (nfsd_master_proc != NULL) {
4129 		procp = pfind(nfsd_master_pid);
4130 		/* Try to make sure it is the correct process. */
4131 		if (procp == nfsd_master_proc &&
4132 		    procp->p_stats->p_start.tv_sec ==
4133 		    nfsd_master_start.tv_sec &&
4134 		    procp->p_stats->p_start.tv_usec ==
4135 		    nfsd_master_start.tv_usec &&
4136 		    strcmp(procp->p_comm, nfsd_master_comm) == 0)
4137 			kern_psignal(procp, SIGUSR2);
4138 		else
4139 			nfsd_master_proc = NULL;
4140 
4141 		if (procp != NULL)
4142 			PROC_UNLOCK(procp);
4143 	}
4144 }
4145 
4146 /*
4147  * Create a DS data file for nfsrv_pnfscreate(). Called for each mirror.
4148  * The arguments are in a structure, so that they can be passed through
4149  * taskqueue for a kernel process to execute this function.
4150  */
4151 struct nfsrvdscreate {
4152 	int			done;
4153 	int			inprog;
4154 	struct task		tsk;
4155 	struct ucred		*tcred;
4156 	struct vnode		*dvp;
4157 	NFSPROC_T		*p;
4158 	struct pnfsdsfile	*pf;
4159 	int			err;
4160 	fhandle_t		fh;
4161 	struct vattr		va;
4162 	struct vattr		createva;
4163 };
4164 
4165 int
4166 nfsrv_dscreate(struct vnode *dvp, struct vattr *vap, struct vattr *nvap,
4167     fhandle_t *fhp, struct pnfsdsfile *pf, struct pnfsdsattr *dsa,
4168     char *fnamep, struct ucred *tcred, NFSPROC_T *p, struct vnode **nvpp)
4169 {
4170 	struct vnode *nvp;
4171 	struct nameidata named;
4172 	struct vattr va;
4173 	char *bufp;
4174 	u_long *hashp;
4175 	struct nfsnode *np;
4176 	struct nfsmount *nmp;
4177 	int error;
4178 
4179 	NFSNAMEICNDSET(&named.ni_cnd, tcred, CREATE,
4180 	    LOCKPARENT | LOCKLEAF | SAVESTART | NOCACHE);
4181 	nfsvno_setpathbuf(&named, &bufp, &hashp);
4182 	named.ni_cnd.cn_lkflags = LK_EXCLUSIVE;
4183 	named.ni_cnd.cn_nameptr = bufp;
4184 	if (fnamep != NULL) {
4185 		strlcpy(bufp, fnamep, PNFS_FILENAME_LEN + 1);
4186 		named.ni_cnd.cn_namelen = strlen(bufp);
4187 	} else
4188 		named.ni_cnd.cn_namelen = nfsrv_putfhname(fhp, bufp);
4189 	NFSD_DEBUG(4, "nfsrv_dscreate: dvp=%p fname=%s\n", dvp, bufp);
4190 
4191 	/* Create the date file in the DS mount. */
4192 	error = NFSVOPLOCK(dvp, LK_EXCLUSIVE);
4193 	if (error == 0) {
4194 		error = VOP_CREATE(dvp, &nvp, &named.ni_cnd, vap);
4195 		vref(dvp);
4196 		VOP_VPUT_PAIR(dvp, error == 0 ? &nvp : NULL, false);
4197 		if (error == 0) {
4198 			/* Set the ownership of the file. */
4199 			error = VOP_SETATTR(nvp, nvap, tcred);
4200 			NFSD_DEBUG(4, "nfsrv_dscreate:"
4201 			    " setattr-uid=%d\n", error);
4202 			if (error != 0)
4203 				vput(nvp);
4204 		}
4205 		if (error != 0)
4206 			printf("pNFS: pnfscreate failed=%d\n", error);
4207 	} else
4208 		printf("pNFS: pnfscreate vnlock=%d\n", error);
4209 	if (error == 0) {
4210 		np = VTONFS(nvp);
4211 		nmp = VFSTONFS(nvp->v_mount);
4212 		if (strcmp(nvp->v_mount->mnt_vfc->vfc_name, "nfs")
4213 		    != 0 || nmp->nm_nam->sa_len > sizeof(
4214 		    struct sockaddr_in6) ||
4215 		    np->n_fhp->nfh_len != NFSX_MYFH) {
4216 			printf("Bad DS file: fstype=%s salen=%d"
4217 			    " fhlen=%d\n",
4218 			    nvp->v_mount->mnt_vfc->vfc_name,
4219 			    nmp->nm_nam->sa_len, np->n_fhp->nfh_len);
4220 			error = ENOENT;
4221 		}
4222 
4223 		/* Set extattrs for the DS on the MDS file. */
4224 		if (error == 0) {
4225 			if (dsa != NULL) {
4226 				error = VOP_GETATTR(nvp, &va, tcred);
4227 				if (error == 0) {
4228 					dsa->dsa_filerev = va.va_filerev;
4229 					dsa->dsa_size = va.va_size;
4230 					dsa->dsa_atime = va.va_atime;
4231 					dsa->dsa_mtime = va.va_mtime;
4232 					dsa->dsa_bytes = va.va_bytes;
4233 				}
4234 			}
4235 			if (error == 0) {
4236 				NFSBCOPY(np->n_fhp->nfh_fh, &pf->dsf_fh,
4237 				    NFSX_MYFH);
4238 				NFSBCOPY(nmp->nm_nam, &pf->dsf_sin,
4239 				    nmp->nm_nam->sa_len);
4240 				NFSBCOPY(named.ni_cnd.cn_nameptr,
4241 				    pf->dsf_filename,
4242 				    sizeof(pf->dsf_filename));
4243 			}
4244 		} else
4245 			printf("pNFS: pnfscreate can't get DS"
4246 			    " attr=%d\n", error);
4247 		if (nvpp != NULL && error == 0)
4248 			*nvpp = nvp;
4249 		else
4250 			vput(nvp);
4251 	}
4252 	nfsvno_relpathbuf(&named);
4253 	return (error);
4254 }
4255 
4256 /*
4257  * Start up the thread that will execute nfsrv_dscreate().
4258  */
4259 static void
4260 start_dscreate(void *arg, int pending)
4261 {
4262 	struct nfsrvdscreate *dsc;
4263 
4264 	dsc = (struct nfsrvdscreate *)arg;
4265 	dsc->err = nfsrv_dscreate(dsc->dvp, &dsc->createva, &dsc->va, &dsc->fh,
4266 	    dsc->pf, NULL, NULL, dsc->tcred, dsc->p, NULL);
4267 	dsc->done = 1;
4268 	NFSD_DEBUG(4, "start_dscreate: err=%d\n", dsc->err);
4269 }
4270 
4271 /*
4272  * Create a pNFS data file on the Data Server(s).
4273  */
4274 static void
4275 nfsrv_pnfscreate(struct vnode *vp, struct vattr *vap, struct ucred *cred,
4276     NFSPROC_T *p)
4277 {
4278 	struct nfsrvdscreate *dsc, *tdsc = NULL;
4279 	struct nfsdevice *ds, *tds, *fds;
4280 	struct mount *mp;
4281 	struct pnfsdsfile *pf, *tpf;
4282 	struct pnfsdsattr dsattr;
4283 	struct vattr va;
4284 	struct vnode *dvp[NFSDEV_MAXMIRRORS];
4285 	struct nfsmount *nmp;
4286 	fhandle_t fh;
4287 	uid_t vauid;
4288 	gid_t vagid;
4289 	u_short vamode;
4290 	struct ucred *tcred;
4291 	int dsdir[NFSDEV_MAXMIRRORS], error, i, mirrorcnt, ret;
4292 	int failpos, timo;
4293 
4294 	/* Get a DS server directory in a round-robin order. */
4295 	mirrorcnt = 1;
4296 	mp = vp->v_mount;
4297 	ds = fds = NULL;
4298 	NFSDDSLOCK();
4299 	/*
4300 	 * Search for the first entry that handles this MDS fs, but use the
4301 	 * first entry for all MDS fs's otherwise.
4302 	 */
4303 	TAILQ_FOREACH(tds, &nfsrv_devidhead, nfsdev_list) {
4304 		if (tds->nfsdev_nmp != NULL) {
4305 			if (tds->nfsdev_mdsisset == 0 && ds == NULL)
4306 				ds = tds;
4307 			else if (tds->nfsdev_mdsisset != 0 && fsidcmp(
4308 			    &mp->mnt_stat.f_fsid, &tds->nfsdev_mdsfsid) == 0) {
4309 				ds = fds = tds;
4310 				break;
4311 			}
4312 		}
4313 	}
4314 	if (ds == NULL) {
4315 		NFSDDSUNLOCK();
4316 		NFSD_DEBUG(4, "nfsrv_pnfscreate: no srv\n");
4317 		return;
4318 	}
4319 	i = dsdir[0] = ds->nfsdev_nextdir;
4320 	ds->nfsdev_nextdir = (ds->nfsdev_nextdir + 1) % nfsrv_dsdirsize;
4321 	dvp[0] = ds->nfsdev_dsdir[i];
4322 	tds = TAILQ_NEXT(ds, nfsdev_list);
4323 	if (nfsrv_maxpnfsmirror > 1 && tds != NULL) {
4324 		TAILQ_FOREACH_FROM(tds, &nfsrv_devidhead, nfsdev_list) {
4325 			if (tds->nfsdev_nmp != NULL &&
4326 			    ((tds->nfsdev_mdsisset == 0 && fds == NULL) ||
4327 			     (tds->nfsdev_mdsisset != 0 && fds != NULL &&
4328 			      fsidcmp(&mp->mnt_stat.f_fsid,
4329 			      &tds->nfsdev_mdsfsid) == 0))) {
4330 				dsdir[mirrorcnt] = i;
4331 				dvp[mirrorcnt] = tds->nfsdev_dsdir[i];
4332 				mirrorcnt++;
4333 				if (mirrorcnt >= nfsrv_maxpnfsmirror)
4334 					break;
4335 			}
4336 		}
4337 	}
4338 	/* Put at end of list to implement round-robin usage. */
4339 	TAILQ_REMOVE(&nfsrv_devidhead, ds, nfsdev_list);
4340 	TAILQ_INSERT_TAIL(&nfsrv_devidhead, ds, nfsdev_list);
4341 	NFSDDSUNLOCK();
4342 	dsc = NULL;
4343 	if (mirrorcnt > 1)
4344 		tdsc = dsc = malloc(sizeof(*dsc) * (mirrorcnt - 1), M_TEMP,
4345 		    M_WAITOK | M_ZERO);
4346 	tpf = pf = malloc(sizeof(*pf) * nfsrv_maxpnfsmirror, M_TEMP, M_WAITOK |
4347 	    M_ZERO);
4348 
4349 	error = nfsvno_getfh(vp, &fh, p);
4350 	if (error == 0)
4351 		error = VOP_GETATTR(vp, &va, cred);
4352 	if (error == 0) {
4353 		/* Set the attributes for "vp" to Setattr the DS vp. */
4354 		vauid = va.va_uid;
4355 		vagid = va.va_gid;
4356 		vamode = va.va_mode;
4357 		VATTR_NULL(&va);
4358 		va.va_uid = vauid;
4359 		va.va_gid = vagid;
4360 		va.va_mode = vamode;
4361 		va.va_size = 0;
4362 	} else
4363 		printf("pNFS: pnfscreate getfh+attr=%d\n", error);
4364 
4365 	NFSD_DEBUG(4, "nfsrv_pnfscreate: cruid=%d crgid=%d\n", cred->cr_uid,
4366 	    cred->cr_gid);
4367 	/* Make data file name based on FH. */
4368 	tcred = newnfs_getcred();
4369 
4370 	/*
4371 	 * Create the file on each DS mirror, using kernel process(es) for the
4372 	 * additional mirrors.
4373 	 */
4374 	failpos = -1;
4375 	for (i = 0; i < mirrorcnt - 1 && error == 0; i++, tpf++, tdsc++) {
4376 		tpf->dsf_dir = dsdir[i];
4377 		tdsc->tcred = tcred;
4378 		tdsc->p = p;
4379 		tdsc->pf = tpf;
4380 		tdsc->createva = *vap;
4381 		NFSBCOPY(&fh, &tdsc->fh, sizeof(fh));
4382 		tdsc->va = va;
4383 		tdsc->dvp = dvp[i];
4384 		tdsc->done = 0;
4385 		tdsc->inprog = 0;
4386 		tdsc->err = 0;
4387 		ret = EIO;
4388 		if (nfs_pnfsiothreads != 0) {
4389 			ret = nfs_pnfsio(start_dscreate, tdsc);
4390 			NFSD_DEBUG(4, "nfsrv_pnfscreate: nfs_pnfsio=%d\n", ret);
4391 		}
4392 		if (ret != 0) {
4393 			ret = nfsrv_dscreate(dvp[i], vap, &va, &fh, tpf, NULL,
4394 			    NULL, tcred, p, NULL);
4395 			if (ret != 0) {
4396 				KASSERT(error == 0, ("nfsrv_dscreate err=%d",
4397 				    error));
4398 				if (failpos == -1 && nfsds_failerr(ret))
4399 					failpos = i;
4400 				else
4401 					error = ret;
4402 			}
4403 		}
4404 	}
4405 	if (error == 0) {
4406 		tpf->dsf_dir = dsdir[mirrorcnt - 1];
4407 		error = nfsrv_dscreate(dvp[mirrorcnt - 1], vap, &va, &fh, tpf,
4408 		    &dsattr, NULL, tcred, p, NULL);
4409 		if (failpos == -1 && mirrorcnt > 1 && nfsds_failerr(error)) {
4410 			failpos = mirrorcnt - 1;
4411 			error = 0;
4412 		}
4413 	}
4414 	timo = hz / 50;		/* Wait for 20msec. */
4415 	if (timo < 1)
4416 		timo = 1;
4417 	/* Wait for kernel task(s) to complete. */
4418 	for (tdsc = dsc, i = 0; i < mirrorcnt - 1; i++, tdsc++) {
4419 		while (tdsc->inprog != 0 && tdsc->done == 0)
4420 			tsleep(&tdsc->tsk, PVFS, "srvdcr", timo);
4421 		if (tdsc->err != 0) {
4422 			if (failpos == -1 && nfsds_failerr(tdsc->err))
4423 				failpos = i;
4424 			else if (error == 0)
4425 				error = tdsc->err;
4426 		}
4427 	}
4428 
4429 	/*
4430 	 * If failpos has been set, that mirror has failed, so it needs
4431 	 * to be disabled.
4432 	 */
4433 	if (failpos >= 0) {
4434 		nmp = VFSTONFS(dvp[failpos]->v_mount);
4435 		NFSLOCKMNT(nmp);
4436 		if ((nmp->nm_privflag & (NFSMNTP_FORCEDISM |
4437 		     NFSMNTP_CANCELRPCS)) == 0) {
4438 			nmp->nm_privflag |= NFSMNTP_CANCELRPCS;
4439 			NFSUNLOCKMNT(nmp);
4440 			ds = nfsrv_deldsnmp(PNFSDOP_DELDSSERVER, nmp, p);
4441 			NFSD_DEBUG(4, "dscreatfail fail=%d ds=%p\n", failpos,
4442 			    ds);
4443 			if (ds != NULL)
4444 				nfsrv_killrpcs(nmp);
4445 			NFSLOCKMNT(nmp);
4446 			nmp->nm_privflag &= ~NFSMNTP_CANCELRPCS;
4447 			wakeup(nmp);
4448 		}
4449 		NFSUNLOCKMNT(nmp);
4450 	}
4451 
4452 	NFSFREECRED(tcred);
4453 	if (error == 0) {
4454 		ASSERT_VOP_ELOCKED(vp, "nfsrv_pnfscreate vp");
4455 
4456 		NFSD_DEBUG(4, "nfsrv_pnfscreate: mirrorcnt=%d maxmirror=%d\n",
4457 		    mirrorcnt, nfsrv_maxpnfsmirror);
4458 		/*
4459 		 * For all mirrors that couldn't be created, fill in the
4460 		 * *pf structure, but with an IP address == 0.0.0.0.
4461 		 */
4462 		tpf = pf + mirrorcnt;
4463 		for (i = mirrorcnt; i < nfsrv_maxpnfsmirror; i++, tpf++) {
4464 			*tpf = *pf;
4465 			tpf->dsf_sin.sin_family = AF_INET;
4466 			tpf->dsf_sin.sin_len = sizeof(struct sockaddr_in);
4467 			tpf->dsf_sin.sin_addr.s_addr = 0;
4468 			tpf->dsf_sin.sin_port = 0;
4469 		}
4470 
4471 		error = vn_extattr_set(vp, IO_NODELOCKED,
4472 		    EXTATTR_NAMESPACE_SYSTEM, "pnfsd.dsfile",
4473 		    sizeof(*pf) * nfsrv_maxpnfsmirror, (char *)pf, p);
4474 		if (error == 0)
4475 			error = vn_extattr_set(vp, IO_NODELOCKED,
4476 			    EXTATTR_NAMESPACE_SYSTEM, "pnfsd.dsattr",
4477 			    sizeof(dsattr), (char *)&dsattr, p);
4478 		if (error != 0)
4479 			printf("pNFS: pnfscreate setextattr=%d\n",
4480 			    error);
4481 	} else
4482 		printf("pNFS: pnfscreate=%d\n", error);
4483 	free(pf, M_TEMP);
4484 	free(dsc, M_TEMP);
4485 }
4486 
4487 /*
4488  * Get the information needed to remove the pNFS Data Server file from the
4489  * Metadata file.  Upon success, ddvp is set non-NULL to the locked
4490  * DS directory vnode.  The caller must unlock *ddvp when done with it.
4491  */
4492 static void
4493 nfsrv_pnfsremovesetup(struct vnode *vp, NFSPROC_T *p, struct vnode **dvpp,
4494     int *mirrorcntp, char *fname, fhandle_t *fhp)
4495 {
4496 	struct vattr va;
4497 	struct ucred *tcred;
4498 	char *buf;
4499 	int buflen, error;
4500 
4501 	dvpp[0] = NULL;
4502 	/* If not an exported regular file or not a pNFS server, just return. */
4503 	if (vp->v_type != VREG || (vp->v_mount->mnt_flag & MNT_EXPORTED) == 0 ||
4504 	    nfsrv_devidcnt == 0)
4505 		return;
4506 
4507 	/* Check to see if this is the last hard link. */
4508 	tcred = newnfs_getcred();
4509 	error = VOP_GETATTR(vp, &va, tcred);
4510 	NFSFREECRED(tcred);
4511 	if (error != 0) {
4512 		printf("pNFS: nfsrv_pnfsremovesetup getattr=%d\n", error);
4513 		return;
4514 	}
4515 	if (va.va_nlink > 1)
4516 		return;
4517 
4518 	error = nfsvno_getfh(vp, fhp, p);
4519 	if (error != 0) {
4520 		printf("pNFS: nfsrv_pnfsremovesetup getfh=%d\n", error);
4521 		return;
4522 	}
4523 
4524 	buflen = 1024;
4525 	buf = malloc(buflen, M_TEMP, M_WAITOK);
4526 	/* Get the directory vnode for the DS mount and the file handle. */
4527 	error = nfsrv_dsgetsockmnt(vp, 0, buf, &buflen, mirrorcntp, p, dvpp,
4528 	    NULL, NULL, fname, NULL, NULL, NULL, NULL, NULL);
4529 	free(buf, M_TEMP);
4530 	if (error != 0)
4531 		printf("pNFS: nfsrv_pnfsremovesetup getsockmnt=%d\n", error);
4532 }
4533 
4534 /*
4535  * Remove a DS data file for nfsrv_pnfsremove(). Called for each mirror.
4536  * The arguments are in a structure, so that they can be passed through
4537  * taskqueue for a kernel process to execute this function.
4538  */
4539 struct nfsrvdsremove {
4540 	int			done;
4541 	int			inprog;
4542 	struct task		tsk;
4543 	struct ucred		*tcred;
4544 	struct vnode		*dvp;
4545 	NFSPROC_T		*p;
4546 	int			err;
4547 	char			fname[PNFS_FILENAME_LEN + 1];
4548 };
4549 
4550 static int
4551 nfsrv_dsremove(struct vnode *dvp, char *fname, struct ucred *tcred,
4552     NFSPROC_T *p)
4553 {
4554 	struct nameidata named;
4555 	struct vnode *nvp;
4556 	char *bufp;
4557 	u_long *hashp;
4558 	int error;
4559 
4560 	error = NFSVOPLOCK(dvp, LK_EXCLUSIVE);
4561 	if (error != 0)
4562 		return (error);
4563 	named.ni_cnd.cn_nameiop = DELETE;
4564 	named.ni_cnd.cn_lkflags = LK_EXCLUSIVE | LK_RETRY;
4565 	named.ni_cnd.cn_cred = tcred;
4566 	named.ni_cnd.cn_flags = ISLASTCN | LOCKPARENT | LOCKLEAF | SAVENAME;
4567 	nfsvno_setpathbuf(&named, &bufp, &hashp);
4568 	named.ni_cnd.cn_nameptr = bufp;
4569 	named.ni_cnd.cn_namelen = strlen(fname);
4570 	strlcpy(bufp, fname, NAME_MAX);
4571 	NFSD_DEBUG(4, "nfsrv_pnfsremove: filename=%s\n", bufp);
4572 	error = VOP_LOOKUP(dvp, &nvp, &named.ni_cnd);
4573 	NFSD_DEBUG(4, "nfsrv_pnfsremove: aft LOOKUP=%d\n", error);
4574 	if (error == 0) {
4575 		error = VOP_REMOVE(dvp, nvp, &named.ni_cnd);
4576 		vput(nvp);
4577 	}
4578 	NFSVOPUNLOCK(dvp);
4579 	nfsvno_relpathbuf(&named);
4580 	if (error != 0)
4581 		printf("pNFS: nfsrv_pnfsremove failed=%d\n", error);
4582 	return (error);
4583 }
4584 
4585 /*
4586  * Start up the thread that will execute nfsrv_dsremove().
4587  */
4588 static void
4589 start_dsremove(void *arg, int pending)
4590 {
4591 	struct nfsrvdsremove *dsrm;
4592 
4593 	dsrm = (struct nfsrvdsremove *)arg;
4594 	dsrm->err = nfsrv_dsremove(dsrm->dvp, dsrm->fname, dsrm->tcred,
4595 	    dsrm->p);
4596 	dsrm->done = 1;
4597 	NFSD_DEBUG(4, "start_dsremove: err=%d\n", dsrm->err);
4598 }
4599 
4600 /*
4601  * Remove a pNFS data file from a Data Server.
4602  * nfsrv_pnfsremovesetup() must have been called before the MDS file was
4603  * removed to set up the dvp and fill in the FH.
4604  */
4605 static void
4606 nfsrv_pnfsremove(struct vnode **dvp, int mirrorcnt, char *fname, fhandle_t *fhp,
4607     NFSPROC_T *p)
4608 {
4609 	struct ucred *tcred;
4610 	struct nfsrvdsremove *dsrm, *tdsrm;
4611 	struct nfsdevice *ds;
4612 	struct nfsmount *nmp;
4613 	int failpos, i, ret, timo;
4614 
4615 	tcred = newnfs_getcred();
4616 	dsrm = NULL;
4617 	if (mirrorcnt > 1)
4618 		dsrm = malloc(sizeof(*dsrm) * mirrorcnt - 1, M_TEMP, M_WAITOK);
4619 	/*
4620 	 * Remove the file on each DS mirror, using kernel process(es) for the
4621 	 * additional mirrors.
4622 	 */
4623 	failpos = -1;
4624 	for (tdsrm = dsrm, i = 0; i < mirrorcnt - 1; i++, tdsrm++) {
4625 		tdsrm->tcred = tcred;
4626 		tdsrm->p = p;
4627 		tdsrm->dvp = dvp[i];
4628 		strlcpy(tdsrm->fname, fname, PNFS_FILENAME_LEN + 1);
4629 		tdsrm->inprog = 0;
4630 		tdsrm->done = 0;
4631 		tdsrm->err = 0;
4632 		ret = EIO;
4633 		if (nfs_pnfsiothreads != 0) {
4634 			ret = nfs_pnfsio(start_dsremove, tdsrm);
4635 			NFSD_DEBUG(4, "nfsrv_pnfsremove: nfs_pnfsio=%d\n", ret);
4636 		}
4637 		if (ret != 0) {
4638 			ret = nfsrv_dsremove(dvp[i], fname, tcred, p);
4639 			if (failpos == -1 && nfsds_failerr(ret))
4640 				failpos = i;
4641 		}
4642 	}
4643 	ret = nfsrv_dsremove(dvp[mirrorcnt - 1], fname, tcred, p);
4644 	if (failpos == -1 && mirrorcnt > 1 && nfsds_failerr(ret))
4645 		failpos = mirrorcnt - 1;
4646 	timo = hz / 50;		/* Wait for 20msec. */
4647 	if (timo < 1)
4648 		timo = 1;
4649 	/* Wait for kernel task(s) to complete. */
4650 	for (tdsrm = dsrm, i = 0; i < mirrorcnt - 1; i++, tdsrm++) {
4651 		while (tdsrm->inprog != 0 && tdsrm->done == 0)
4652 			tsleep(&tdsrm->tsk, PVFS, "srvdsrm", timo);
4653 		if (failpos == -1 && nfsds_failerr(tdsrm->err))
4654 			failpos = i;
4655 	}
4656 
4657 	/*
4658 	 * If failpos has been set, that mirror has failed, so it needs
4659 	 * to be disabled.
4660 	 */
4661 	if (failpos >= 0) {
4662 		nmp = VFSTONFS(dvp[failpos]->v_mount);
4663 		NFSLOCKMNT(nmp);
4664 		if ((nmp->nm_privflag & (NFSMNTP_FORCEDISM |
4665 		     NFSMNTP_CANCELRPCS)) == 0) {
4666 			nmp->nm_privflag |= NFSMNTP_CANCELRPCS;
4667 			NFSUNLOCKMNT(nmp);
4668 			ds = nfsrv_deldsnmp(PNFSDOP_DELDSSERVER, nmp, p);
4669 			NFSD_DEBUG(4, "dsremovefail fail=%d ds=%p\n", failpos,
4670 			    ds);
4671 			if (ds != NULL)
4672 				nfsrv_killrpcs(nmp);
4673 			NFSLOCKMNT(nmp);
4674 			nmp->nm_privflag &= ~NFSMNTP_CANCELRPCS;
4675 			wakeup(nmp);
4676 		}
4677 		NFSUNLOCKMNT(nmp);
4678 	}
4679 
4680 	/* Get rid all layouts for the file. */
4681 	nfsrv_freefilelayouts(fhp);
4682 
4683 	NFSFREECRED(tcred);
4684 	free(dsrm, M_TEMP);
4685 }
4686 
4687 /*
4688  * Generate a file name based on the file handle and put it in *bufp.
4689  * Return the number of bytes generated.
4690  */
4691 static int
4692 nfsrv_putfhname(fhandle_t *fhp, char *bufp)
4693 {
4694 	int i;
4695 	uint8_t *cp;
4696 	const uint8_t *hexdigits = "0123456789abcdef";
4697 
4698 	cp = (uint8_t *)fhp;
4699 	for (i = 0; i < sizeof(*fhp); i++) {
4700 		bufp[2 * i] = hexdigits[(*cp >> 4) & 0xf];
4701 		bufp[2 * i + 1] = hexdigits[*cp++ & 0xf];
4702 	}
4703 	bufp[2 * i] = '\0';
4704 	return (2 * i);
4705 }
4706 
4707 /*
4708  * Update the Metadata file's attributes from the DS file when a Read/Write
4709  * layout is returned.
4710  * Basically just call nfsrv_proxyds() with procedure == NFSPROC_LAYOUTRETURN
4711  * so that it does a nfsrv_getattrdsrpc() and nfsrv_setextattr() on the DS file.
4712  */
4713 int
4714 nfsrv_updatemdsattr(struct vnode *vp, struct nfsvattr *nap, NFSPROC_T *p)
4715 {
4716 	struct ucred *tcred;
4717 	int error;
4718 
4719 	/* Do this as root so that it won't fail with EACCES. */
4720 	tcred = newnfs_getcred();
4721 	error = nfsrv_proxyds(vp, 0, 0, tcred, p, NFSPROC_LAYOUTRETURN,
4722 	    NULL, NULL, NULL, nap, NULL, NULL, 0, NULL);
4723 	NFSFREECRED(tcred);
4724 	return (error);
4725 }
4726 
4727 /*
4728  * Set the NFSv4 ACL on the DS file to the same ACL as the MDS file.
4729  */
4730 static int
4731 nfsrv_dssetacl(struct vnode *vp, struct acl *aclp, struct ucred *cred,
4732     NFSPROC_T *p)
4733 {
4734 	int error;
4735 
4736 	error = nfsrv_proxyds(vp, 0, 0, cred, p, NFSPROC_SETACL,
4737 	    NULL, NULL, NULL, NULL, aclp, NULL, 0, NULL);
4738 	return (error);
4739 }
4740 
4741 static int
4742 nfsrv_proxyds(struct vnode *vp, off_t off, int cnt, struct ucred *cred,
4743     struct thread *p, int ioproc, struct mbuf **mpp, char *cp,
4744     struct mbuf **mpp2, struct nfsvattr *nap, struct acl *aclp,
4745     off_t *offp, int content, bool *eofp)
4746 {
4747 	struct nfsmount *nmp[NFSDEV_MAXMIRRORS], *failnmp;
4748 	fhandle_t fh[NFSDEV_MAXMIRRORS];
4749 	struct vnode *dvp[NFSDEV_MAXMIRRORS];
4750 	struct nfsdevice *ds;
4751 	struct pnfsdsattr dsattr;
4752 	struct opnfsdsattr odsattr;
4753 	char *buf;
4754 	int buflen, error, failpos, i, mirrorcnt, origmircnt, trycnt;
4755 
4756 	NFSD_DEBUG(4, "in nfsrv_proxyds\n");
4757 	/*
4758 	 * If not a regular file, not exported or not a pNFS server,
4759 	 * just return ENOENT.
4760 	 */
4761 	if (vp->v_type != VREG || (vp->v_mount->mnt_flag & MNT_EXPORTED) == 0 ||
4762 	    nfsrv_devidcnt == 0)
4763 		return (ENOENT);
4764 
4765 	buflen = 1024;
4766 	buf = malloc(buflen, M_TEMP, M_WAITOK);
4767 	error = 0;
4768 
4769 	/*
4770 	 * For Getattr, get the Change attribute (va_filerev) and size (va_size)
4771 	 * from the MetaData file's extended attribute.
4772 	 */
4773 	if (ioproc == NFSPROC_GETATTR) {
4774 		error = vn_extattr_get(vp, IO_NODELOCKED,
4775 		    EXTATTR_NAMESPACE_SYSTEM, "pnfsd.dsattr", &buflen, buf,
4776 		    p);
4777 		if (error == 0) {
4778 			if (buflen == sizeof(odsattr)) {
4779 				NFSBCOPY(buf, &odsattr, buflen);
4780 				nap->na_filerev = odsattr.dsa_filerev;
4781 				nap->na_size = odsattr.dsa_size;
4782 				nap->na_atime = odsattr.dsa_atime;
4783 				nap->na_mtime = odsattr.dsa_mtime;
4784 				/*
4785 				 * Fake na_bytes by rounding up na_size.
4786 				 * Since we don't know the block size, just
4787 				 * use BLKDEV_IOSIZE.
4788 				 */
4789 				nap->na_bytes = (odsattr.dsa_size +
4790 				    BLKDEV_IOSIZE - 1) & ~(BLKDEV_IOSIZE - 1);
4791 			} else if (buflen == sizeof(dsattr)) {
4792 				NFSBCOPY(buf, &dsattr, buflen);
4793 				nap->na_filerev = dsattr.dsa_filerev;
4794 				nap->na_size = dsattr.dsa_size;
4795 				nap->na_atime = dsattr.dsa_atime;
4796 				nap->na_mtime = dsattr.dsa_mtime;
4797 				nap->na_bytes = dsattr.dsa_bytes;
4798 			} else
4799 				error = ENXIO;
4800 		}
4801 		if (error == 0) {
4802 			/*
4803 			 * If nfsrv_pnfsgetdsattr is 0 or nfsrv_checkdsattr()
4804 			 * returns 0, just return now.  nfsrv_checkdsattr()
4805 			 * returns 0 if there is no Read/Write layout
4806 			 * plus either an Open/Write_access or Write
4807 			 * delegation issued to a client for the file.
4808 			 */
4809 			if (nfsrv_pnfsgetdsattr == 0 ||
4810 			    nfsrv_checkdsattr(vp, p) == 0) {
4811 				free(buf, M_TEMP);
4812 				return (error);
4813 			}
4814 		}
4815 
4816 		/*
4817 		 * Clear ENOATTR so the code below will attempt to do a
4818 		 * nfsrv_getattrdsrpc() to get the attributes and (re)create
4819 		 * the extended attribute.
4820 		 */
4821 		if (error == ENOATTR)
4822 			error = 0;
4823 	}
4824 
4825 	origmircnt = -1;
4826 	trycnt = 0;
4827 tryagain:
4828 	if (error == 0) {
4829 		buflen = 1024;
4830 		if (ioproc == NFSPROC_READDS && NFSVOPISLOCKED(vp) ==
4831 		    LK_EXCLUSIVE)
4832 			printf("nfsrv_proxyds: Readds vp exclusively locked\n");
4833 		error = nfsrv_dsgetsockmnt(vp, LK_SHARED, buf, &buflen,
4834 		    &mirrorcnt, p, dvp, fh, NULL, NULL, NULL, NULL, NULL,
4835 		    NULL, NULL);
4836 		if (error == 0) {
4837 			for (i = 0; i < mirrorcnt; i++)
4838 				nmp[i] = VFSTONFS(dvp[i]->v_mount);
4839 		} else
4840 			printf("pNFS: proxy getextattr sockaddr=%d\n", error);
4841 	} else
4842 		printf("pNFS: nfsrv_dsgetsockmnt=%d\n", error);
4843 	if (error == 0) {
4844 		failpos = -1;
4845 		if (origmircnt == -1)
4846 			origmircnt = mirrorcnt;
4847 		/*
4848 		 * If failpos is set to a mirror#, then that mirror has
4849 		 * failed and will be disabled. For Read, Getattr and Seek, the
4850 		 * function only tries one mirror, so if that mirror has
4851 		 * failed, it will need to be retried. As such, increment
4852 		 * tryitagain for these cases.
4853 		 * For Write, Setattr and Setacl, the function tries all
4854 		 * mirrors and will not return an error for the case where
4855 		 * one mirror has failed. For these cases, the functioning
4856 		 * mirror(s) will have been modified, so a retry isn't
4857 		 * necessary. These functions will set failpos for the
4858 		 * failed mirror#.
4859 		 */
4860 		if (ioproc == NFSPROC_READDS) {
4861 			error = nfsrv_readdsrpc(fh, off, cnt, cred, p, nmp[0],
4862 			    mpp, mpp2);
4863 			if (nfsds_failerr(error) && mirrorcnt > 1) {
4864 				/*
4865 				 * Setting failpos will cause the mirror
4866 				 * to be disabled and then a retry of this
4867 				 * read is required.
4868 				 */
4869 				failpos = 0;
4870 				error = 0;
4871 				trycnt++;
4872 			}
4873 		} else if (ioproc == NFSPROC_WRITEDS)
4874 			error = nfsrv_writedsrpc(fh, off, cnt, cred, p, vp,
4875 			    &nmp[0], mirrorcnt, mpp, cp, &failpos);
4876 		else if (ioproc == NFSPROC_SETATTR)
4877 			error = nfsrv_setattrdsrpc(fh, cred, p, vp, &nmp[0],
4878 			    mirrorcnt, nap, &failpos);
4879 		else if (ioproc == NFSPROC_SETACL)
4880 			error = nfsrv_setacldsrpc(fh, cred, p, vp, &nmp[0],
4881 			    mirrorcnt, aclp, &failpos);
4882 		else if (ioproc == NFSPROC_SEEKDS) {
4883 			error = nfsrv_seekdsrpc(fh, offp, content, eofp, cred,
4884 			    p, nmp[0]);
4885 			if (nfsds_failerr(error) && mirrorcnt > 1) {
4886 				/*
4887 				 * Setting failpos will cause the mirror
4888 				 * to be disabled and then a retry of this
4889 				 * read is required.
4890 				 */
4891 				failpos = 0;
4892 				error = 0;
4893 				trycnt++;
4894 			}
4895 		} else if (ioproc == NFSPROC_ALLOCATE)
4896 			error = nfsrv_allocatedsrpc(fh, off, *offp, cred, p, vp,
4897 			    &nmp[0], mirrorcnt, &failpos);
4898 		else if (ioproc == NFSPROC_DEALLOCATE)
4899 			error = nfsrv_deallocatedsrpc(fh, off, *offp, cred, p,
4900 			    vp, &nmp[0], mirrorcnt, &failpos);
4901 		else {
4902 			error = nfsrv_getattrdsrpc(&fh[mirrorcnt - 1], cred, p,
4903 			    vp, nmp[mirrorcnt - 1], nap);
4904 			if (nfsds_failerr(error) && mirrorcnt > 1) {
4905 				/*
4906 				 * Setting failpos will cause the mirror
4907 				 * to be disabled and then a retry of this
4908 				 * getattr is required.
4909 				 */
4910 				failpos = mirrorcnt - 1;
4911 				error = 0;
4912 				trycnt++;
4913 			}
4914 		}
4915 		ds = NULL;
4916 		if (failpos >= 0) {
4917 			failnmp = nmp[failpos];
4918 			NFSLOCKMNT(failnmp);
4919 			if ((failnmp->nm_privflag & (NFSMNTP_FORCEDISM |
4920 			     NFSMNTP_CANCELRPCS)) == 0) {
4921 				failnmp->nm_privflag |= NFSMNTP_CANCELRPCS;
4922 				NFSUNLOCKMNT(failnmp);
4923 				ds = nfsrv_deldsnmp(PNFSDOP_DELDSSERVER,
4924 				    failnmp, p);
4925 				NFSD_DEBUG(4, "dsldsnmp fail=%d ds=%p\n",
4926 				    failpos, ds);
4927 				if (ds != NULL)
4928 					nfsrv_killrpcs(failnmp);
4929 				NFSLOCKMNT(failnmp);
4930 				failnmp->nm_privflag &= ~NFSMNTP_CANCELRPCS;
4931 				wakeup(failnmp);
4932 			}
4933 			NFSUNLOCKMNT(failnmp);
4934 		}
4935 		for (i = 0; i < mirrorcnt; i++)
4936 			NFSVOPUNLOCK(dvp[i]);
4937 		NFSD_DEBUG(4, "nfsrv_proxyds: aft RPC=%d trya=%d\n", error,
4938 		    trycnt);
4939 		/* Try the Read/Getattr again if a mirror was deleted. */
4940 		if (ds != NULL && trycnt > 0 && trycnt < origmircnt)
4941 			goto tryagain;
4942 	} else {
4943 		/* Return ENOENT for any Extended Attribute error. */
4944 		error = ENOENT;
4945 	}
4946 	free(buf, M_TEMP);
4947 	NFSD_DEBUG(4, "nfsrv_proxyds: error=%d\n", error);
4948 	return (error);
4949 }
4950 
4951 /*
4952  * Get the DS mount point, fh and directory from the "pnfsd.dsfile" extended
4953  * attribute.
4954  * newnmpp - If it points to a non-NULL nmp, that is the destination and needs
4955  *           to be checked.  If it points to a NULL nmp, then it returns
4956  *           a suitable destination.
4957  * curnmp - If non-NULL, it is the source mount for the copy.
4958  */
4959 int
4960 nfsrv_dsgetsockmnt(struct vnode *vp, int lktype, char *buf, int *buflenp,
4961     int *mirrorcntp, NFSPROC_T *p, struct vnode **dvpp, fhandle_t *fhp,
4962     char *devid, char *fnamep, struct vnode **nvpp, struct nfsmount **newnmpp,
4963     struct nfsmount *curnmp, int *ippos, int *dsdirp)
4964 {
4965 	struct vnode *dvp, *nvp = NULL, **tdvpp;
4966 	struct mount *mp;
4967 	struct nfsmount *nmp, *newnmp;
4968 	struct sockaddr *sad;
4969 	struct sockaddr_in *sin;
4970 	struct nfsdevice *ds, *tds, *fndds;
4971 	struct pnfsdsfile *pf;
4972 	uint32_t dsdir;
4973 	int error, fhiszero, fnd, gotone, i, mirrorcnt;
4974 
4975 	ASSERT_VOP_LOCKED(vp, "nfsrv_dsgetsockmnt vp");
4976 	*mirrorcntp = 1;
4977 	tdvpp = dvpp;
4978 	if (nvpp != NULL)
4979 		*nvpp = NULL;
4980 	if (dvpp != NULL)
4981 		*dvpp = NULL;
4982 	if (ippos != NULL)
4983 		*ippos = -1;
4984 	if (newnmpp != NULL)
4985 		newnmp = *newnmpp;
4986 	else
4987 		newnmp = NULL;
4988 	mp = vp->v_mount;
4989 	error = vn_extattr_get(vp, IO_NODELOCKED, EXTATTR_NAMESPACE_SYSTEM,
4990 	    "pnfsd.dsfile", buflenp, buf, p);
4991 	mirrorcnt = *buflenp / sizeof(*pf);
4992 	if (error == 0 && (mirrorcnt < 1 || mirrorcnt > NFSDEV_MAXMIRRORS ||
4993 	    *buflenp != sizeof(*pf) * mirrorcnt))
4994 		error = ENOATTR;
4995 
4996 	pf = (struct pnfsdsfile *)buf;
4997 	/* If curnmp != NULL, check for a match in the mirror list. */
4998 	if (curnmp != NULL && error == 0) {
4999 		fnd = 0;
5000 		for (i = 0; i < mirrorcnt; i++, pf++) {
5001 			sad = (struct sockaddr *)&pf->dsf_sin;
5002 			if (nfsaddr2_match(sad, curnmp->nm_nam)) {
5003 				if (ippos != NULL)
5004 					*ippos = i;
5005 				fnd = 1;
5006 				break;
5007 			}
5008 		}
5009 		if (fnd == 0)
5010 			error = ENXIO;
5011 	}
5012 
5013 	gotone = 0;
5014 	pf = (struct pnfsdsfile *)buf;
5015 	NFSD_DEBUG(4, "nfsrv_dsgetsockmnt: mirrorcnt=%d err=%d\n", mirrorcnt,
5016 	    error);
5017 	for (i = 0; i < mirrorcnt && error == 0; i++, pf++) {
5018 		fhiszero = 0;
5019 		sad = (struct sockaddr *)&pf->dsf_sin;
5020 		sin = &pf->dsf_sin;
5021 		dsdir = pf->dsf_dir;
5022 		if (dsdir >= nfsrv_dsdirsize) {
5023 			printf("nfsrv_dsgetsockmnt: dsdir=%d\n", dsdir);
5024 			error = ENOATTR;
5025 		} else if (nvpp != NULL && newnmp != NULL &&
5026 		    nfsaddr2_match(sad, newnmp->nm_nam))
5027 			error = EEXIST;
5028 		if (error == 0) {
5029 			if (ippos != NULL && curnmp == NULL &&
5030 			    sad->sa_family == AF_INET &&
5031 			    sin->sin_addr.s_addr == 0)
5032 				*ippos = i;
5033 			if (NFSBCMP(&zerofh, &pf->dsf_fh, sizeof(zerofh)) == 0)
5034 				fhiszero = 1;
5035 			/* Use the socket address to find the mount point. */
5036 			fndds = NULL;
5037 			NFSDDSLOCK();
5038 			/* Find a match for the IP address. */
5039 			TAILQ_FOREACH(ds, &nfsrv_devidhead, nfsdev_list) {
5040 				if (ds->nfsdev_nmp != NULL) {
5041 					dvp = ds->nfsdev_dvp;
5042 					nmp = VFSTONFS(dvp->v_mount);
5043 					if (nmp != ds->nfsdev_nmp)
5044 						printf("different2 nmp %p %p\n",
5045 						    nmp, ds->nfsdev_nmp);
5046 					if (nfsaddr2_match(sad, nmp->nm_nam)) {
5047 						fndds = ds;
5048 						break;
5049 					}
5050 				}
5051 			}
5052 			if (fndds != NULL && newnmpp != NULL &&
5053 			    newnmp == NULL) {
5054 				/* Search for a place to make a mirror copy. */
5055 				TAILQ_FOREACH(tds, &nfsrv_devidhead,
5056 				    nfsdev_list) {
5057 					if (tds->nfsdev_nmp != NULL &&
5058 					    fndds != tds &&
5059 					    ((tds->nfsdev_mdsisset == 0 &&
5060 					      fndds->nfsdev_mdsisset == 0) ||
5061 					     (tds->nfsdev_mdsisset != 0 &&
5062 					      fndds->nfsdev_mdsisset != 0 &&
5063 					      fsidcmp(&tds->nfsdev_mdsfsid,
5064 					      &mp->mnt_stat.f_fsid) == 0))) {
5065 						*newnmpp = tds->nfsdev_nmp;
5066 						break;
5067 					}
5068 				}
5069 				if (tds != NULL) {
5070 					/*
5071 					 * Move this entry to the end of the
5072 					 * list, so it won't be selected as
5073 					 * easily the next time.
5074 					 */
5075 					TAILQ_REMOVE(&nfsrv_devidhead, tds,
5076 					    nfsdev_list);
5077 					TAILQ_INSERT_TAIL(&nfsrv_devidhead, tds,
5078 					    nfsdev_list);
5079 				}
5080 			}
5081 			NFSDDSUNLOCK();
5082 			if (fndds != NULL) {
5083 				dvp = fndds->nfsdev_dsdir[dsdir];
5084 				if (lktype != 0 || fhiszero != 0 ||
5085 				    (nvpp != NULL && *nvpp == NULL)) {
5086 					if (fhiszero != 0)
5087 						error = vn_lock(dvp,
5088 						    LK_EXCLUSIVE);
5089 					else if (lktype != 0)
5090 						error = vn_lock(dvp, lktype);
5091 					else
5092 						error = vn_lock(dvp, LK_SHARED);
5093 					/*
5094 					 * If the file handle is all 0's, try to
5095 					 * do a Lookup against the DS to acquire
5096 					 * it.
5097 					 * If dvpp == NULL or the Lookup fails,
5098 					 * unlock dvp after the call.
5099 					 */
5100 					if (error == 0 && (fhiszero != 0 ||
5101 					    (nvpp != NULL && *nvpp == NULL))) {
5102 						error = nfsrv_pnfslookupds(vp,
5103 						    dvp, pf, &nvp, p);
5104 						if (error == 0) {
5105 							if (fhiszero != 0)
5106 								nfsrv_pnfssetfh(
5107 								    vp, pf,
5108 								    devid,
5109 								    fnamep,
5110 								    nvp, p);
5111 							if (nvpp != NULL &&
5112 							    *nvpp == NULL) {
5113 								*nvpp = nvp;
5114 								*dsdirp = dsdir;
5115 							} else
5116 								vput(nvp);
5117 						}
5118 						if (error != 0 || lktype == 0)
5119 							NFSVOPUNLOCK(dvp);
5120 					}
5121 				}
5122 				if (error == 0) {
5123 					gotone++;
5124 					NFSD_DEBUG(4, "gotone=%d\n", gotone);
5125 					if (devid != NULL) {
5126 						NFSBCOPY(fndds->nfsdev_deviceid,
5127 						    devid, NFSX_V4DEVICEID);
5128 						devid += NFSX_V4DEVICEID;
5129 					}
5130 					if (dvpp != NULL)
5131 						*tdvpp++ = dvp;
5132 					if (fhp != NULL)
5133 						NFSBCOPY(&pf->dsf_fh, fhp++,
5134 						    NFSX_MYFH);
5135 					if (fnamep != NULL && gotone == 1)
5136 						strlcpy(fnamep,
5137 						    pf->dsf_filename,
5138 						    sizeof(pf->dsf_filename));
5139 				} else
5140 					NFSD_DEBUG(4, "nfsrv_dsgetsockmnt "
5141 					    "err=%d\n", error);
5142 			}
5143 		}
5144 	}
5145 	if (error == 0 && gotone == 0)
5146 		error = ENOENT;
5147 
5148 	NFSD_DEBUG(4, "eo nfsrv_dsgetsockmnt: gotone=%d err=%d\n", gotone,
5149 	    error);
5150 	if (error == 0)
5151 		*mirrorcntp = gotone;
5152 	else {
5153 		if (gotone > 0 && dvpp != NULL) {
5154 			/*
5155 			 * If the error didn't occur on the first one and
5156 			 * dvpp != NULL, the one(s) prior to the failure will
5157 			 * have locked dvp's that need to be unlocked.
5158 			 */
5159 			for (i = 0; i < gotone; i++) {
5160 				NFSVOPUNLOCK(*dvpp);
5161 				*dvpp++ = NULL;
5162 			}
5163 		}
5164 		/*
5165 		 * If it found the vnode to be copied from before a failure,
5166 		 * it needs to be vput()'d.
5167 		 */
5168 		if (nvpp != NULL && *nvpp != NULL) {
5169 			vput(*nvpp);
5170 			*nvpp = NULL;
5171 		}
5172 	}
5173 	return (error);
5174 }
5175 
5176 /*
5177  * Set the extended attribute for the Change attribute.
5178  */
5179 static int
5180 nfsrv_setextattr(struct vnode *vp, struct nfsvattr *nap, NFSPROC_T *p)
5181 {
5182 	struct pnfsdsattr dsattr;
5183 	int error;
5184 
5185 	ASSERT_VOP_ELOCKED(vp, "nfsrv_setextattr vp");
5186 	dsattr.dsa_filerev = nap->na_filerev;
5187 	dsattr.dsa_size = nap->na_size;
5188 	dsattr.dsa_atime = nap->na_atime;
5189 	dsattr.dsa_mtime = nap->na_mtime;
5190 	dsattr.dsa_bytes = nap->na_bytes;
5191 	error = vn_extattr_set(vp, IO_NODELOCKED, EXTATTR_NAMESPACE_SYSTEM,
5192 	    "pnfsd.dsattr", sizeof(dsattr), (char *)&dsattr, p);
5193 	if (error != 0)
5194 		printf("pNFS: setextattr=%d\n", error);
5195 	return (error);
5196 }
5197 
5198 static int
5199 nfsrv_readdsrpc(fhandle_t *fhp, off_t off, int len, struct ucred *cred,
5200     NFSPROC_T *p, struct nfsmount *nmp, struct mbuf **mpp, struct mbuf **mpendp)
5201 {
5202 	uint32_t *tl;
5203 	struct nfsrv_descript *nd;
5204 	nfsv4stateid_t st;
5205 	struct mbuf *m, *m2;
5206 	int error = 0, retlen, tlen, trimlen;
5207 
5208 	NFSD_DEBUG(4, "in nfsrv_readdsrpc\n");
5209 	nd = malloc(sizeof(*nd), M_TEMP, M_WAITOK | M_ZERO);
5210 	*mpp = NULL;
5211 	/*
5212 	 * Use a stateid where other is an alternating 01010 pattern and
5213 	 * seqid is 0xffffffff.  This value is not defined as special by
5214 	 * the RFC and is used by the FreeBSD NFS server to indicate an
5215 	 * MDS->DS proxy operation.
5216 	 */
5217 	st.other[0] = 0x55555555;
5218 	st.other[1] = 0x55555555;
5219 	st.other[2] = 0x55555555;
5220 	st.seqid = 0xffffffff;
5221 	nfscl_reqstart(nd, NFSPROC_READDS, nmp, (u_int8_t *)fhp, sizeof(*fhp),
5222 	    NULL, NULL, 0, 0);
5223 	nfsm_stateidtom(nd, &st, NFSSTATEID_PUTSTATEID);
5224 	NFSM_BUILD(tl, uint32_t *, NFSX_UNSIGNED * 3);
5225 	txdr_hyper(off, tl);
5226 	*(tl + 2) = txdr_unsigned(len);
5227 	error = newnfs_request(nd, nmp, NULL, &nmp->nm_sockreq, NULL, p, cred,
5228 	    NFS_PROG, NFS_VER4, NULL, 1, NULL, NULL);
5229 	if (error != 0) {
5230 		free(nd, M_TEMP);
5231 		return (error);
5232 	}
5233 	if (nd->nd_repstat == 0) {
5234 		NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
5235 		NFSM_STRSIZ(retlen, len);
5236 		if (retlen > 0) {
5237 			/* Trim off the pre-data XDR from the mbuf chain. */
5238 			m = nd->nd_mrep;
5239 			while (m != NULL && m != nd->nd_md) {
5240 				if (m->m_next == nd->nd_md) {
5241 					m->m_next = NULL;
5242 					m_freem(nd->nd_mrep);
5243 					nd->nd_mrep = m = nd->nd_md;
5244 				} else
5245 					m = m->m_next;
5246 			}
5247 			if (m == NULL) {
5248 				printf("nfsrv_readdsrpc: busted mbuf list\n");
5249 				error = ENOENT;
5250 				goto nfsmout;
5251 			}
5252 
5253 			/*
5254 			 * Now, adjust first mbuf so that any XDR before the
5255 			 * read data is skipped over.
5256 			 */
5257 			trimlen = nd->nd_dpos - mtod(m, char *);
5258 			if (trimlen > 0) {
5259 				m->m_len -= trimlen;
5260 				NFSM_DATAP(m, trimlen);
5261 			}
5262 
5263 			/*
5264 			 * Truncate the mbuf chain at retlen bytes of data,
5265 			 * plus XDR padding that brings the length up to a
5266 			 * multiple of 4.
5267 			 */
5268 			tlen = NFSM_RNDUP(retlen);
5269 			do {
5270 				if (m->m_len >= tlen) {
5271 					m->m_len = tlen;
5272 					tlen = 0;
5273 					m2 = m->m_next;
5274 					m->m_next = NULL;
5275 					m_freem(m2);
5276 					break;
5277 				}
5278 				tlen -= m->m_len;
5279 				m = m->m_next;
5280 			} while (m != NULL);
5281 			if (tlen > 0) {
5282 				printf("nfsrv_readdsrpc: busted mbuf list\n");
5283 				error = ENOENT;
5284 				goto nfsmout;
5285 			}
5286 			*mpp = nd->nd_mrep;
5287 			*mpendp = m;
5288 			nd->nd_mrep = NULL;
5289 		}
5290 	} else
5291 		error = nd->nd_repstat;
5292 nfsmout:
5293 	/* If nd->nd_mrep is already NULL, this is a no-op. */
5294 	m_freem(nd->nd_mrep);
5295 	free(nd, M_TEMP);
5296 	NFSD_DEBUG(4, "nfsrv_readdsrpc error=%d\n", error);
5297 	return (error);
5298 }
5299 
5300 /*
5301  * Do a write RPC on a DS data file, using this structure for the arguments,
5302  * so that this function can be executed by a separate kernel process.
5303  */
5304 struct nfsrvwritedsdorpc {
5305 	int			done;
5306 	int			inprog;
5307 	struct task		tsk;
5308 	fhandle_t		fh;
5309 	off_t			off;
5310 	int			len;
5311 	struct nfsmount		*nmp;
5312 	struct ucred		*cred;
5313 	NFSPROC_T		*p;
5314 	struct mbuf		*m;
5315 	int			err;
5316 };
5317 
5318 static int
5319 nfsrv_writedsdorpc(struct nfsmount *nmp, fhandle_t *fhp, off_t off, int len,
5320     struct nfsvattr *nap, struct mbuf *m, struct ucred *cred, NFSPROC_T *p)
5321 {
5322 	uint32_t *tl;
5323 	struct nfsrv_descript *nd;
5324 	nfsattrbit_t attrbits;
5325 	nfsv4stateid_t st;
5326 	int commit, error, retlen;
5327 
5328 	nd = malloc(sizeof(*nd), M_TEMP, M_WAITOK | M_ZERO);
5329 	nfscl_reqstart(nd, NFSPROC_WRITE, nmp, (u_int8_t *)fhp,
5330 	    sizeof(fhandle_t), NULL, NULL, 0, 0);
5331 
5332 	/*
5333 	 * Use a stateid where other is an alternating 01010 pattern and
5334 	 * seqid is 0xffffffff.  This value is not defined as special by
5335 	 * the RFC and is used by the FreeBSD NFS server to indicate an
5336 	 * MDS->DS proxy operation.
5337 	 */
5338 	st.other[0] = 0x55555555;
5339 	st.other[1] = 0x55555555;
5340 	st.other[2] = 0x55555555;
5341 	st.seqid = 0xffffffff;
5342 	nfsm_stateidtom(nd, &st, NFSSTATEID_PUTSTATEID);
5343 	NFSM_BUILD(tl, u_int32_t *, NFSX_HYPER + 2 * NFSX_UNSIGNED);
5344 	txdr_hyper(off, tl);
5345 	tl += 2;
5346 	/*
5347 	 * Do all writes FileSync, since the server doesn't hold onto dirty
5348 	 * buffers.  Since clients should be accessing the DS servers directly
5349 	 * using the pNFS layouts, this just needs to work correctly as a
5350 	 * fallback.
5351 	 */
5352 	*tl++ = txdr_unsigned(NFSWRITE_FILESYNC);
5353 	*tl = txdr_unsigned(len);
5354 	NFSD_DEBUG(4, "nfsrv_writedsdorpc: len=%d\n", len);
5355 
5356 	/* Put data in mbuf chain. */
5357 	nd->nd_mb->m_next = m;
5358 
5359 	/* Set nd_mb and nd_bpos to end of data. */
5360 	while (m->m_next != NULL)
5361 		m = m->m_next;
5362 	nd->nd_mb = m;
5363 	nfsm_set(nd, m->m_len);
5364 	NFSD_DEBUG(4, "nfsrv_writedsdorpc: lastmb len=%d\n", m->m_len);
5365 
5366 	/* Do a Getattr for the attributes that change upon writing. */
5367 	NFSZERO_ATTRBIT(&attrbits);
5368 	NFSSETBIT_ATTRBIT(&attrbits, NFSATTRBIT_SIZE);
5369 	NFSSETBIT_ATTRBIT(&attrbits, NFSATTRBIT_CHANGE);
5370 	NFSSETBIT_ATTRBIT(&attrbits, NFSATTRBIT_TIMEACCESS);
5371 	NFSSETBIT_ATTRBIT(&attrbits, NFSATTRBIT_TIMEMODIFY);
5372 	NFSSETBIT_ATTRBIT(&attrbits, NFSATTRBIT_SPACEUSED);
5373 	NFSM_BUILD(tl, u_int32_t *, NFSX_UNSIGNED);
5374 	*tl = txdr_unsigned(NFSV4OP_GETATTR);
5375 	(void) nfsrv_putattrbit(nd, &attrbits);
5376 	error = newnfs_request(nd, nmp, NULL, &nmp->nm_sockreq, NULL, p,
5377 	    cred, NFS_PROG, NFS_VER4, NULL, 1, NULL, NULL);
5378 	if (error != 0) {
5379 		free(nd, M_TEMP);
5380 		return (error);
5381 	}
5382 	NFSD_DEBUG(4, "nfsrv_writedsdorpc: aft writerpc=%d\n", nd->nd_repstat);
5383 	/* Get rid of weak cache consistency data for now. */
5384 	if ((nd->nd_flag & (ND_NOMOREDATA | ND_NFSV4 | ND_V4WCCATTR)) ==
5385 	    (ND_NFSV4 | ND_V4WCCATTR)) {
5386 		error = nfsv4_loadattr(nd, NULL, nap, NULL, NULL, 0, NULL, NULL,
5387 		    NULL, NULL, NULL, 0, NULL, NULL, NULL, NULL, NULL);
5388 		NFSD_DEBUG(4, "nfsrv_writedsdorpc: wcc attr=%d\n", error);
5389 		if (error != 0)
5390 			goto nfsmout;
5391 		/*
5392 		 * Get rid of Op# and status for next op.
5393 		 */
5394 		NFSM_DISSECT(tl, uint32_t *, 2 * NFSX_UNSIGNED);
5395 		if (*++tl != 0)
5396 			nd->nd_flag |= ND_NOMOREDATA;
5397 	}
5398 	if (nd->nd_repstat == 0) {
5399 		NFSM_DISSECT(tl, uint32_t *, 2 * NFSX_UNSIGNED + NFSX_VERF);
5400 		retlen = fxdr_unsigned(int, *tl++);
5401 		commit = fxdr_unsigned(int, *tl);
5402 		if (commit != NFSWRITE_FILESYNC)
5403 			error = NFSERR_IO;
5404 		NFSD_DEBUG(4, "nfsrv_writedsdorpc:retlen=%d commit=%d err=%d\n",
5405 		    retlen, commit, error);
5406 	} else
5407 		error = nd->nd_repstat;
5408 	/* We have no use for the Write Verifier since we use FileSync. */
5409 
5410 	/*
5411 	 * Get the Change, Size, Access Time and Modify Time attributes and set
5412 	 * on the Metadata file, so its attributes will be what the file's
5413 	 * would be if it had been written.
5414 	 */
5415 	if (error == 0) {
5416 		NFSM_DISSECT(tl, uint32_t *, 2 * NFSX_UNSIGNED);
5417 		error = nfsv4_loadattr(nd, NULL, nap, NULL, NULL, 0, NULL, NULL,
5418 		    NULL, NULL, NULL, 0, NULL, NULL, NULL, NULL, NULL);
5419 	}
5420 	NFSD_DEBUG(4, "nfsrv_writedsdorpc: aft loadattr=%d\n", error);
5421 nfsmout:
5422 	m_freem(nd->nd_mrep);
5423 	free(nd, M_TEMP);
5424 	NFSD_DEBUG(4, "nfsrv_writedsdorpc error=%d\n", error);
5425 	return (error);
5426 }
5427 
5428 /*
5429  * Start up the thread that will execute nfsrv_writedsdorpc().
5430  */
5431 static void
5432 start_writedsdorpc(void *arg, int pending)
5433 {
5434 	struct nfsrvwritedsdorpc *drpc;
5435 
5436 	drpc = (struct nfsrvwritedsdorpc *)arg;
5437 	drpc->err = nfsrv_writedsdorpc(drpc->nmp, &drpc->fh, drpc->off,
5438 	    drpc->len, NULL, drpc->m, drpc->cred, drpc->p);
5439 	drpc->done = 1;
5440 	NFSD_DEBUG(4, "start_writedsdorpc: err=%d\n", drpc->err);
5441 }
5442 
5443 static int
5444 nfsrv_writedsrpc(fhandle_t *fhp, off_t off, int len, struct ucred *cred,
5445     NFSPROC_T *p, struct vnode *vp, struct nfsmount **nmpp, int mirrorcnt,
5446     struct mbuf **mpp, char *cp, int *failposp)
5447 {
5448 	struct nfsrvwritedsdorpc *drpc, *tdrpc = NULL;
5449 	struct nfsvattr na;
5450 	struct mbuf *m;
5451 	int error, i, offs, ret, timo;
5452 
5453 	NFSD_DEBUG(4, "in nfsrv_writedsrpc\n");
5454 	KASSERT(*mpp != NULL, ("nfsrv_writedsrpc: NULL mbuf chain"));
5455 	drpc = NULL;
5456 	if (mirrorcnt > 1)
5457 		tdrpc = drpc = malloc(sizeof(*drpc) * (mirrorcnt - 1), M_TEMP,
5458 		    M_WAITOK);
5459 
5460 	/* Calculate offset in mbuf chain that data starts. */
5461 	offs = cp - mtod(*mpp, char *);
5462 	NFSD_DEBUG(4, "nfsrv_writedsrpc: mcopy offs=%d len=%d\n", offs, len);
5463 
5464 	/*
5465 	 * Do the write RPC for every DS, using a separate kernel process
5466 	 * for every DS except the last one.
5467 	 */
5468 	error = 0;
5469 	for (i = 0; i < mirrorcnt - 1; i++, tdrpc++) {
5470 		tdrpc->done = 0;
5471 		NFSBCOPY(fhp, &tdrpc->fh, sizeof(*fhp));
5472 		tdrpc->off = off;
5473 		tdrpc->len = len;
5474 		tdrpc->nmp = *nmpp;
5475 		tdrpc->cred = cred;
5476 		tdrpc->p = p;
5477 		tdrpc->inprog = 0;
5478 		tdrpc->err = 0;
5479 		tdrpc->m = m_copym(*mpp, offs, NFSM_RNDUP(len), M_WAITOK);
5480 		ret = EIO;
5481 		if (nfs_pnfsiothreads != 0) {
5482 			ret = nfs_pnfsio(start_writedsdorpc, tdrpc);
5483 			NFSD_DEBUG(4, "nfsrv_writedsrpc: nfs_pnfsio=%d\n",
5484 			    ret);
5485 		}
5486 		if (ret != 0) {
5487 			ret = nfsrv_writedsdorpc(*nmpp, fhp, off, len, NULL,
5488 			    tdrpc->m, cred, p);
5489 			if (nfsds_failerr(ret) && *failposp == -1)
5490 				*failposp = i;
5491 			else if (error == 0 && ret != 0)
5492 				error = ret;
5493 		}
5494 		nmpp++;
5495 		fhp++;
5496 	}
5497 	m = m_copym(*mpp, offs, NFSM_RNDUP(len), M_WAITOK);
5498 	ret = nfsrv_writedsdorpc(*nmpp, fhp, off, len, &na, m, cred, p);
5499 	if (nfsds_failerr(ret) && *failposp == -1 && mirrorcnt > 1)
5500 		*failposp = mirrorcnt - 1;
5501 	else if (error == 0 && ret != 0)
5502 		error = ret;
5503 	if (error == 0)
5504 		error = nfsrv_setextattr(vp, &na, p);
5505 	NFSD_DEBUG(4, "nfsrv_writedsrpc: aft setextat=%d\n", error);
5506 	tdrpc = drpc;
5507 	timo = hz / 50;		/* Wait for 20msec. */
5508 	if (timo < 1)
5509 		timo = 1;
5510 	for (i = 0; i < mirrorcnt - 1; i++, tdrpc++) {
5511 		/* Wait for RPCs on separate threads to complete. */
5512 		while (tdrpc->inprog != 0 && tdrpc->done == 0)
5513 			tsleep(&tdrpc->tsk, PVFS, "srvwrds", timo);
5514 		if (nfsds_failerr(tdrpc->err) && *failposp == -1)
5515 			*failposp = i;
5516 		else if (error == 0 && tdrpc->err != 0)
5517 			error = tdrpc->err;
5518 	}
5519 	free(drpc, M_TEMP);
5520 	return (error);
5521 }
5522 
5523 /*
5524  * Do a allocate RPC on a DS data file, using this structure for the arguments,
5525  * so that this function can be executed by a separate kernel process.
5526  */
5527 struct nfsrvallocatedsdorpc {
5528 	int			done;
5529 	int			inprog;
5530 	struct task		tsk;
5531 	fhandle_t		fh;
5532 	off_t			off;
5533 	off_t			len;
5534 	struct nfsmount		*nmp;
5535 	struct ucred		*cred;
5536 	NFSPROC_T		*p;
5537 	int			err;
5538 };
5539 
5540 static int
5541 nfsrv_allocatedsdorpc(struct nfsmount *nmp, fhandle_t *fhp, off_t off,
5542     off_t len, struct nfsvattr *nap, struct ucred *cred, NFSPROC_T *p)
5543 {
5544 	uint32_t *tl;
5545 	struct nfsrv_descript *nd;
5546 	nfsattrbit_t attrbits;
5547 	nfsv4stateid_t st;
5548 	int error;
5549 
5550 	nd = malloc(sizeof(*nd), M_TEMP, M_WAITOK | M_ZERO);
5551 	nfscl_reqstart(nd, NFSPROC_ALLOCATE, nmp, (u_int8_t *)fhp,
5552 	    sizeof(fhandle_t), NULL, NULL, 0, 0);
5553 
5554 	/*
5555 	 * Use a stateid where other is an alternating 01010 pattern and
5556 	 * seqid is 0xffffffff.  This value is not defined as special by
5557 	 * the RFC and is used by the FreeBSD NFS server to indicate an
5558 	 * MDS->DS proxy operation.
5559 	 */
5560 	st.other[0] = 0x55555555;
5561 	st.other[1] = 0x55555555;
5562 	st.other[2] = 0x55555555;
5563 	st.seqid = 0xffffffff;
5564 	nfsm_stateidtom(nd, &st, NFSSTATEID_PUTSTATEID);
5565 	NFSM_BUILD(tl, uint32_t *, 2 * NFSX_HYPER + NFSX_UNSIGNED);
5566 	txdr_hyper(off, tl); tl += 2;
5567 	txdr_hyper(len, tl); tl += 2;
5568 	NFSD_DEBUG(4, "nfsrv_allocatedsdorpc: len=%jd\n", (intmax_t)len);
5569 
5570 	*tl = txdr_unsigned(NFSV4OP_GETATTR);
5571 	NFSGETATTR_ATTRBIT(&attrbits);
5572 	nfsrv_putattrbit(nd, &attrbits);
5573 	error = newnfs_request(nd, nmp, NULL, &nmp->nm_sockreq, NULL, p,
5574 	    cred, NFS_PROG, NFS_VER4, NULL, 1, NULL, NULL);
5575 	if (error != 0) {
5576 		free(nd, M_TEMP);
5577 		return (error);
5578 	}
5579 	NFSD_DEBUG(4, "nfsrv_allocatedsdorpc: aft allocaterpc=%d\n",
5580 	    nd->nd_repstat);
5581 	if (nd->nd_repstat == 0) {
5582 		NFSM_DISSECT(tl, uint32_t *, 2 * NFSX_UNSIGNED);
5583 		error = nfsv4_loadattr(nd, NULL, nap, NULL, NULL, 0, NULL, NULL,
5584 		    NULL, NULL, NULL, 0, NULL, NULL, NULL, NULL, NULL);
5585 	} else
5586 		error = nd->nd_repstat;
5587 	NFSD_DEBUG(4, "nfsrv_allocatedsdorpc: aft loadattr=%d\n", error);
5588 nfsmout:
5589 	m_freem(nd->nd_mrep);
5590 	free(nd, M_TEMP);
5591 	NFSD_DEBUG(4, "nfsrv_allocatedsdorpc error=%d\n", error);
5592 	return (error);
5593 }
5594 
5595 /*
5596  * Start up the thread that will execute nfsrv_allocatedsdorpc().
5597  */
5598 static void
5599 start_allocatedsdorpc(void *arg, int pending)
5600 {
5601 	struct nfsrvallocatedsdorpc *drpc;
5602 
5603 	drpc = (struct nfsrvallocatedsdorpc *)arg;
5604 	drpc->err = nfsrv_allocatedsdorpc(drpc->nmp, &drpc->fh, drpc->off,
5605 	    drpc->len, NULL, drpc->cred, drpc->p);
5606 	drpc->done = 1;
5607 	NFSD_DEBUG(4, "start_allocatedsdorpc: err=%d\n", drpc->err);
5608 }
5609 
5610 static int
5611 nfsrv_allocatedsrpc(fhandle_t *fhp, off_t off, off_t len, struct ucred *cred,
5612     NFSPROC_T *p, struct vnode *vp, struct nfsmount **nmpp, int mirrorcnt,
5613     int *failposp)
5614 {
5615 	struct nfsrvallocatedsdorpc *drpc, *tdrpc = NULL;
5616 	struct nfsvattr na;
5617 	int error, i, ret, timo;
5618 
5619 	NFSD_DEBUG(4, "in nfsrv_allocatedsrpc\n");
5620 	drpc = NULL;
5621 	if (mirrorcnt > 1)
5622 		tdrpc = drpc = malloc(sizeof(*drpc) * (mirrorcnt - 1), M_TEMP,
5623 		    M_WAITOK);
5624 
5625 	/*
5626 	 * Do the allocate RPC for every DS, using a separate kernel process
5627 	 * for every DS except the last one.
5628 	 */
5629 	error = 0;
5630 	for (i = 0; i < mirrorcnt - 1; i++, tdrpc++) {
5631 		tdrpc->done = 0;
5632 		NFSBCOPY(fhp, &tdrpc->fh, sizeof(*fhp));
5633 		tdrpc->off = off;
5634 		tdrpc->len = len;
5635 		tdrpc->nmp = *nmpp;
5636 		tdrpc->cred = cred;
5637 		tdrpc->p = p;
5638 		tdrpc->inprog = 0;
5639 		tdrpc->err = 0;
5640 		ret = EIO;
5641 		if (nfs_pnfsiothreads != 0) {
5642 			ret = nfs_pnfsio(start_allocatedsdorpc, tdrpc);
5643 			NFSD_DEBUG(4, "nfsrv_allocatedsrpc: nfs_pnfsio=%d\n",
5644 			    ret);
5645 		}
5646 		if (ret != 0) {
5647 			ret = nfsrv_allocatedsdorpc(*nmpp, fhp, off, len, NULL,
5648 			    cred, p);
5649 			if (nfsds_failerr(ret) && *failposp == -1)
5650 				*failposp = i;
5651 			else if (error == 0 && ret != 0)
5652 				error = ret;
5653 		}
5654 		nmpp++;
5655 		fhp++;
5656 	}
5657 	ret = nfsrv_allocatedsdorpc(*nmpp, fhp, off, len, &na, cred, p);
5658 	if (nfsds_failerr(ret) && *failposp == -1 && mirrorcnt > 1)
5659 		*failposp = mirrorcnt - 1;
5660 	else if (error == 0 && ret != 0)
5661 		error = ret;
5662 	if (error == 0)
5663 		error = nfsrv_setextattr(vp, &na, p);
5664 	NFSD_DEBUG(4, "nfsrv_allocatedsrpc: aft setextat=%d\n", error);
5665 	tdrpc = drpc;
5666 	timo = hz / 50;		/* Wait for 20msec. */
5667 	if (timo < 1)
5668 		timo = 1;
5669 	for (i = 0; i < mirrorcnt - 1; i++, tdrpc++) {
5670 		/* Wait for RPCs on separate threads to complete. */
5671 		while (tdrpc->inprog != 0 && tdrpc->done == 0)
5672 			tsleep(&tdrpc->tsk, PVFS, "srvalds", timo);
5673 		if (nfsds_failerr(tdrpc->err) && *failposp == -1)
5674 			*failposp = i;
5675 		else if (error == 0 && tdrpc->err != 0)
5676 			error = tdrpc->err;
5677 	}
5678 	free(drpc, M_TEMP);
5679 	return (error);
5680 }
5681 
5682 /*
5683  * Do a deallocate RPC on a DS data file, using this structure for the
5684  * arguments, so that this function can be executed by a separate kernel
5685  * process.
5686  */
5687 struct nfsrvdeallocatedsdorpc {
5688 	int			done;
5689 	int			inprog;
5690 	struct task		tsk;
5691 	fhandle_t		fh;
5692 	off_t			off;
5693 	off_t			len;
5694 	struct nfsmount		*nmp;
5695 	struct ucred		*cred;
5696 	NFSPROC_T		*p;
5697 	int			err;
5698 };
5699 
5700 static int
5701 nfsrv_deallocatedsdorpc(struct nfsmount *nmp, fhandle_t *fhp, off_t off,
5702     off_t len, struct nfsvattr *nap, struct ucred *cred, NFSPROC_T *p)
5703 {
5704 	uint32_t *tl;
5705 	struct nfsrv_descript *nd;
5706 	nfsattrbit_t attrbits;
5707 	nfsv4stateid_t st;
5708 	int error;
5709 
5710 	nd = malloc(sizeof(*nd), M_TEMP, M_WAITOK | M_ZERO);
5711 	nfscl_reqstart(nd, NFSPROC_DEALLOCATE, nmp, (u_int8_t *)fhp,
5712 	    sizeof(fhandle_t), NULL, NULL, 0, 0);
5713 
5714 	/*
5715 	 * Use a stateid where other is an alternating 01010 pattern and
5716 	 * seqid is 0xffffffff.  This value is not defined as special by
5717 	 * the RFC and is used by the FreeBSD NFS server to indicate an
5718 	 * MDS->DS proxy operation.
5719 	 */
5720 	st.other[0] = 0x55555555;
5721 	st.other[1] = 0x55555555;
5722 	st.other[2] = 0x55555555;
5723 	st.seqid = 0xffffffff;
5724 	nfsm_stateidtom(nd, &st, NFSSTATEID_PUTSTATEID);
5725 	NFSM_BUILD(tl, uint32_t *, 2 * NFSX_HYPER + NFSX_UNSIGNED);
5726 	txdr_hyper(off, tl); tl += 2;
5727 	txdr_hyper(len, tl); tl += 2;
5728 	NFSD_DEBUG(4, "nfsrv_deallocatedsdorpc: len=%jd\n", (intmax_t)len);
5729 
5730 	/* Do a Getattr for the attributes that change upon writing. */
5731 	NFSZERO_ATTRBIT(&attrbits);
5732 	NFSSETBIT_ATTRBIT(&attrbits, NFSATTRBIT_SIZE);
5733 	NFSSETBIT_ATTRBIT(&attrbits, NFSATTRBIT_CHANGE);
5734 	NFSSETBIT_ATTRBIT(&attrbits, NFSATTRBIT_TIMEACCESS);
5735 	NFSSETBIT_ATTRBIT(&attrbits, NFSATTRBIT_TIMEMODIFY);
5736 	NFSSETBIT_ATTRBIT(&attrbits, NFSATTRBIT_SPACEUSED);
5737 	*tl = txdr_unsigned(NFSV4OP_GETATTR);
5738 	nfsrv_putattrbit(nd, &attrbits);
5739 	error = newnfs_request(nd, nmp, NULL, &nmp->nm_sockreq, NULL, p,
5740 	    cred, NFS_PROG, NFS_VER4, NULL, 1, NULL, NULL);
5741 	if (error != 0) {
5742 		free(nd, M_TEMP);
5743 		return (error);
5744 	}
5745 	NFSD_DEBUG(4, "nfsrv_deallocatedsdorpc: aft deallocaterpc=%d\n",
5746 	    nd->nd_repstat);
5747 	/* Get rid of weak cache consistency data for now. */
5748 	if ((nd->nd_flag & (ND_NOMOREDATA | ND_NFSV4 | ND_V4WCCATTR)) ==
5749 	    (ND_NFSV4 | ND_V4WCCATTR)) {
5750 		error = nfsv4_loadattr(nd, NULL, nap, NULL, NULL, 0, NULL, NULL,
5751 		    NULL, NULL, NULL, 0, NULL, NULL, NULL, NULL, NULL);
5752 		NFSD_DEBUG(4, "nfsrv_deallocatedsdorpc: wcc attr=%d\n", error);
5753 		if (error != 0)
5754 			goto nfsmout;
5755 		/*
5756 		 * Get rid of Op# and status for next op.
5757 		 */
5758 		NFSM_DISSECT(tl, uint32_t *, 2 * NFSX_UNSIGNED);
5759 		if (*++tl != 0)
5760 			nd->nd_flag |= ND_NOMOREDATA;
5761 	}
5762 	if (nd->nd_repstat == 0) {
5763 		NFSM_DISSECT(tl, uint32_t *, 2 * NFSX_UNSIGNED);
5764 		error = nfsv4_loadattr(nd, NULL, nap, NULL, NULL, 0, NULL, NULL,
5765 		    NULL, NULL, NULL, 0, NULL, NULL, NULL, NULL, NULL);
5766 	} else
5767 		error = nd->nd_repstat;
5768 	NFSD_DEBUG(4, "nfsrv_deallocatedsdorpc: aft loadattr=%d\n", error);
5769 nfsmout:
5770 	m_freem(nd->nd_mrep);
5771 	free(nd, M_TEMP);
5772 	NFSD_DEBUG(4, "nfsrv_deallocatedsdorpc error=%d\n", error);
5773 	return (error);
5774 }
5775 
5776 /*
5777  * Start up the thread that will execute nfsrv_deallocatedsdorpc().
5778  */
5779 static void
5780 start_deallocatedsdorpc(void *arg, int pending)
5781 {
5782 	struct nfsrvdeallocatedsdorpc *drpc;
5783 
5784 	drpc = (struct nfsrvdeallocatedsdorpc *)arg;
5785 	drpc->err = nfsrv_deallocatedsdorpc(drpc->nmp, &drpc->fh, drpc->off,
5786 	    drpc->len, NULL, drpc->cred, drpc->p);
5787 	drpc->done = 1;
5788 	NFSD_DEBUG(4, "start_deallocatedsdorpc: err=%d\n", drpc->err);
5789 }
5790 
5791 static int
5792 nfsrv_deallocatedsrpc(fhandle_t *fhp, off_t off, off_t len, struct ucred *cred,
5793     NFSPROC_T *p, struct vnode *vp, struct nfsmount **nmpp, int mirrorcnt,
5794     int *failposp)
5795 {
5796 	struct nfsrvdeallocatedsdorpc *drpc, *tdrpc = NULL;
5797 	struct nfsvattr na;
5798 	int error, i, ret, timo;
5799 
5800 	NFSD_DEBUG(4, "in nfsrv_deallocatedsrpc\n");
5801 	drpc = NULL;
5802 	if (mirrorcnt > 1)
5803 		tdrpc = drpc = malloc(sizeof(*drpc) * (mirrorcnt - 1), M_TEMP,
5804 		    M_WAITOK);
5805 
5806 	/*
5807 	 * Do the deallocate RPC for every DS, using a separate kernel process
5808 	 * for every DS except the last one.
5809 	 */
5810 	error = 0;
5811 	for (i = 0; i < mirrorcnt - 1; i++, tdrpc++) {
5812 		tdrpc->done = 0;
5813 		NFSBCOPY(fhp, &tdrpc->fh, sizeof(*fhp));
5814 		tdrpc->off = off;
5815 		tdrpc->len = len;
5816 		tdrpc->nmp = *nmpp;
5817 		tdrpc->cred = cred;
5818 		tdrpc->p = p;
5819 		tdrpc->inprog = 0;
5820 		tdrpc->err = 0;
5821 		ret = EIO;
5822 		if (nfs_pnfsiothreads != 0) {
5823 			ret = nfs_pnfsio(start_deallocatedsdorpc, tdrpc);
5824 			NFSD_DEBUG(4, "nfsrv_deallocatedsrpc: nfs_pnfsio=%d\n",
5825 			    ret);
5826 		}
5827 		if (ret != 0) {
5828 			ret = nfsrv_deallocatedsdorpc(*nmpp, fhp, off, len,
5829 			    NULL, cred, p);
5830 			if (nfsds_failerr(ret) && *failposp == -1)
5831 				*failposp = i;
5832 			else if (error == 0 && ret != 0)
5833 				error = ret;
5834 		}
5835 		nmpp++;
5836 		fhp++;
5837 	}
5838 	ret = nfsrv_deallocatedsdorpc(*nmpp, fhp, off, len, &na, cred, p);
5839 	if (nfsds_failerr(ret) && *failposp == -1 && mirrorcnt > 1)
5840 		*failposp = mirrorcnt - 1;
5841 	else if (error == 0 && ret != 0)
5842 		error = ret;
5843 	if (error == 0)
5844 		error = nfsrv_setextattr(vp, &na, p);
5845 	NFSD_DEBUG(4, "nfsrv_deallocatedsrpc: aft setextat=%d\n", error);
5846 	tdrpc = drpc;
5847 	timo = hz / 50;		/* Wait for 20msec. */
5848 	if (timo < 1)
5849 		timo = 1;
5850 	for (i = 0; i < mirrorcnt - 1; i++, tdrpc++) {
5851 		/* Wait for RPCs on separate threads to complete. */
5852 		while (tdrpc->inprog != 0 && tdrpc->done == 0)
5853 			tsleep(&tdrpc->tsk, PVFS, "srvalds", timo);
5854 		if (nfsds_failerr(tdrpc->err) && *failposp == -1)
5855 			*failposp = i;
5856 		else if (error == 0 && tdrpc->err != 0)
5857 			error = tdrpc->err;
5858 	}
5859 	free(drpc, M_TEMP);
5860 	return (error);
5861 }
5862 
5863 static int
5864 nfsrv_setattrdsdorpc(fhandle_t *fhp, struct ucred *cred, NFSPROC_T *p,
5865     struct vnode *vp, struct nfsmount *nmp, struct nfsvattr *nap,
5866     struct nfsvattr *dsnap)
5867 {
5868 	uint32_t *tl;
5869 	struct nfsrv_descript *nd;
5870 	nfsv4stateid_t st;
5871 	nfsattrbit_t attrbits;
5872 	int error;
5873 
5874 	NFSD_DEBUG(4, "in nfsrv_setattrdsdorpc\n");
5875 	nd = malloc(sizeof(*nd), M_TEMP, M_WAITOK | M_ZERO);
5876 	/*
5877 	 * Use a stateid where other is an alternating 01010 pattern and
5878 	 * seqid is 0xffffffff.  This value is not defined as special by
5879 	 * the RFC and is used by the FreeBSD NFS server to indicate an
5880 	 * MDS->DS proxy operation.
5881 	 */
5882 	st.other[0] = 0x55555555;
5883 	st.other[1] = 0x55555555;
5884 	st.other[2] = 0x55555555;
5885 	st.seqid = 0xffffffff;
5886 	nfscl_reqstart(nd, NFSPROC_SETATTR, nmp, (u_int8_t *)fhp, sizeof(*fhp),
5887 	    NULL, NULL, 0, 0);
5888 	nfsm_stateidtom(nd, &st, NFSSTATEID_PUTSTATEID);
5889 	nfscl_fillsattr(nd, &nap->na_vattr, vp, NFSSATTR_FULL, 0);
5890 
5891 	/* Do a Getattr for the attributes that change due to writing. */
5892 	NFSZERO_ATTRBIT(&attrbits);
5893 	NFSSETBIT_ATTRBIT(&attrbits, NFSATTRBIT_SIZE);
5894 	NFSSETBIT_ATTRBIT(&attrbits, NFSATTRBIT_CHANGE);
5895 	NFSSETBIT_ATTRBIT(&attrbits, NFSATTRBIT_TIMEACCESS);
5896 	NFSSETBIT_ATTRBIT(&attrbits, NFSATTRBIT_TIMEMODIFY);
5897 	NFSSETBIT_ATTRBIT(&attrbits, NFSATTRBIT_SPACEUSED);
5898 	NFSM_BUILD(tl, u_int32_t *, NFSX_UNSIGNED);
5899 	*tl = txdr_unsigned(NFSV4OP_GETATTR);
5900 	(void) nfsrv_putattrbit(nd, &attrbits);
5901 	error = newnfs_request(nd, nmp, NULL, &nmp->nm_sockreq, NULL, p, cred,
5902 	    NFS_PROG, NFS_VER4, NULL, 1, NULL, NULL);
5903 	if (error != 0) {
5904 		free(nd, M_TEMP);
5905 		return (error);
5906 	}
5907 	NFSD_DEBUG(4, "nfsrv_setattrdsdorpc: aft setattrrpc=%d\n",
5908 	    nd->nd_repstat);
5909 	/* Get rid of weak cache consistency data for now. */
5910 	if ((nd->nd_flag & (ND_NOMOREDATA | ND_NFSV4 | ND_V4WCCATTR)) ==
5911 	    (ND_NFSV4 | ND_V4WCCATTR)) {
5912 		error = nfsv4_loadattr(nd, NULL, dsnap, NULL, NULL, 0, NULL,
5913 		    NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL, NULL, NULL);
5914 		NFSD_DEBUG(4, "nfsrv_setattrdsdorpc: wcc attr=%d\n", error);
5915 		if (error != 0)
5916 			goto nfsmout;
5917 		/*
5918 		 * Get rid of Op# and status for next op.
5919 		 */
5920 		NFSM_DISSECT(tl, uint32_t *, 2 * NFSX_UNSIGNED);
5921 		if (*++tl != 0)
5922 			nd->nd_flag |= ND_NOMOREDATA;
5923 	}
5924 	error = nfsrv_getattrbits(nd, &attrbits, NULL, NULL);
5925 	if (error != 0)
5926 		goto nfsmout;
5927 	if (nd->nd_repstat != 0)
5928 		error = nd->nd_repstat;
5929 	/*
5930 	 * Get the Change, Size, Access Time and Modify Time attributes and set
5931 	 * on the Metadata file, so its attributes will be what the file's
5932 	 * would be if it had been written.
5933 	 */
5934 	if (error == 0) {
5935 		NFSM_DISSECT(tl, uint32_t *, 2 * NFSX_UNSIGNED);
5936 		error = nfsv4_loadattr(nd, NULL, dsnap, NULL, NULL, 0, NULL,
5937 		    NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL, NULL, NULL);
5938 	}
5939 	NFSD_DEBUG(4, "nfsrv_setattrdsdorpc: aft setattr loadattr=%d\n", error);
5940 nfsmout:
5941 	m_freem(nd->nd_mrep);
5942 	free(nd, M_TEMP);
5943 	NFSD_DEBUG(4, "nfsrv_setattrdsdorpc error=%d\n", error);
5944 	return (error);
5945 }
5946 
5947 struct nfsrvsetattrdsdorpc {
5948 	int			done;
5949 	int			inprog;
5950 	struct task		tsk;
5951 	fhandle_t		fh;
5952 	struct nfsmount		*nmp;
5953 	struct vnode		*vp;
5954 	struct ucred		*cred;
5955 	NFSPROC_T		*p;
5956 	struct nfsvattr		na;
5957 	struct nfsvattr		dsna;
5958 	int			err;
5959 };
5960 
5961 /*
5962  * Start up the thread that will execute nfsrv_setattrdsdorpc().
5963  */
5964 static void
5965 start_setattrdsdorpc(void *arg, int pending)
5966 {
5967 	struct nfsrvsetattrdsdorpc *drpc;
5968 
5969 	drpc = (struct nfsrvsetattrdsdorpc *)arg;
5970 	drpc->err = nfsrv_setattrdsdorpc(&drpc->fh, drpc->cred, drpc->p,
5971 	    drpc->vp, drpc->nmp, &drpc->na, &drpc->dsna);
5972 	drpc->done = 1;
5973 }
5974 
5975 static int
5976 nfsrv_setattrdsrpc(fhandle_t *fhp, struct ucred *cred, NFSPROC_T *p,
5977     struct vnode *vp, struct nfsmount **nmpp, int mirrorcnt,
5978     struct nfsvattr *nap, int *failposp)
5979 {
5980 	struct nfsrvsetattrdsdorpc *drpc, *tdrpc = NULL;
5981 	struct nfsvattr na;
5982 	int error, i, ret, timo;
5983 
5984 	NFSD_DEBUG(4, "in nfsrv_setattrdsrpc\n");
5985 	drpc = NULL;
5986 	if (mirrorcnt > 1)
5987 		tdrpc = drpc = malloc(sizeof(*drpc) * (mirrorcnt - 1), M_TEMP,
5988 		    M_WAITOK);
5989 
5990 	/*
5991 	 * Do the setattr RPC for every DS, using a separate kernel process
5992 	 * for every DS except the last one.
5993 	 */
5994 	error = 0;
5995 	for (i = 0; i < mirrorcnt - 1; i++, tdrpc++) {
5996 		tdrpc->done = 0;
5997 		tdrpc->inprog = 0;
5998 		NFSBCOPY(fhp, &tdrpc->fh, sizeof(*fhp));
5999 		tdrpc->nmp = *nmpp;
6000 		tdrpc->vp = vp;
6001 		tdrpc->cred = cred;
6002 		tdrpc->p = p;
6003 		tdrpc->na = *nap;
6004 		tdrpc->err = 0;
6005 		ret = EIO;
6006 		if (nfs_pnfsiothreads != 0) {
6007 			ret = nfs_pnfsio(start_setattrdsdorpc, tdrpc);
6008 			NFSD_DEBUG(4, "nfsrv_setattrdsrpc: nfs_pnfsio=%d\n",
6009 			    ret);
6010 		}
6011 		if (ret != 0) {
6012 			ret = nfsrv_setattrdsdorpc(fhp, cred, p, vp, *nmpp, nap,
6013 			    &na);
6014 			if (nfsds_failerr(ret) && *failposp == -1)
6015 				*failposp = i;
6016 			else if (error == 0 && ret != 0)
6017 				error = ret;
6018 		}
6019 		nmpp++;
6020 		fhp++;
6021 	}
6022 	ret = nfsrv_setattrdsdorpc(fhp, cred, p, vp, *nmpp, nap, &na);
6023 	if (nfsds_failerr(ret) && *failposp == -1 && mirrorcnt > 1)
6024 		*failposp = mirrorcnt - 1;
6025 	else if (error == 0 && ret != 0)
6026 		error = ret;
6027 	if (error == 0)
6028 		error = nfsrv_setextattr(vp, &na, p);
6029 	NFSD_DEBUG(4, "nfsrv_setattrdsrpc: aft setextat=%d\n", error);
6030 	tdrpc = drpc;
6031 	timo = hz / 50;		/* Wait for 20msec. */
6032 	if (timo < 1)
6033 		timo = 1;
6034 	for (i = 0; i < mirrorcnt - 1; i++, tdrpc++) {
6035 		/* Wait for RPCs on separate threads to complete. */
6036 		while (tdrpc->inprog != 0 && tdrpc->done == 0)
6037 			tsleep(&tdrpc->tsk, PVFS, "srvsads", timo);
6038 		if (nfsds_failerr(tdrpc->err) && *failposp == -1)
6039 			*failposp = i;
6040 		else if (error == 0 && tdrpc->err != 0)
6041 			error = tdrpc->err;
6042 	}
6043 	free(drpc, M_TEMP);
6044 	return (error);
6045 }
6046 
6047 /*
6048  * Do a Setattr of an NFSv4 ACL on the DS file.
6049  */
6050 static int
6051 nfsrv_setacldsdorpc(fhandle_t *fhp, struct ucred *cred, NFSPROC_T *p,
6052     struct vnode *vp, struct nfsmount *nmp, struct acl *aclp)
6053 {
6054 	struct nfsrv_descript *nd;
6055 	nfsv4stateid_t st;
6056 	nfsattrbit_t attrbits;
6057 	int error;
6058 
6059 	NFSD_DEBUG(4, "in nfsrv_setacldsdorpc\n");
6060 	nd = malloc(sizeof(*nd), M_TEMP, M_WAITOK | M_ZERO);
6061 	/*
6062 	 * Use a stateid where other is an alternating 01010 pattern and
6063 	 * seqid is 0xffffffff.  This value is not defined as special by
6064 	 * the RFC and is used by the FreeBSD NFS server to indicate an
6065 	 * MDS->DS proxy operation.
6066 	 */
6067 	st.other[0] = 0x55555555;
6068 	st.other[1] = 0x55555555;
6069 	st.other[2] = 0x55555555;
6070 	st.seqid = 0xffffffff;
6071 	nfscl_reqstart(nd, NFSPROC_SETACL, nmp, (u_int8_t *)fhp, sizeof(*fhp),
6072 	    NULL, NULL, 0, 0);
6073 	nfsm_stateidtom(nd, &st, NFSSTATEID_PUTSTATEID);
6074 	NFSZERO_ATTRBIT(&attrbits);
6075 	NFSSETBIT_ATTRBIT(&attrbits, NFSATTRBIT_ACL);
6076 	/*
6077 	 * The "vp" argument to nfsv4_fillattr() is only used for vnode_type(),
6078 	 * so passing in the metadata "vp" will be ok, since it is of
6079 	 * the same type (VREG).
6080 	 */
6081 	nfsv4_fillattr(nd, NULL, vp, aclp, NULL, NULL, 0, &attrbits, NULL,
6082 	    NULL, 0, 0, 0, 0, 0, NULL);
6083 	error = newnfs_request(nd, nmp, NULL, &nmp->nm_sockreq, NULL, p, cred,
6084 	    NFS_PROG, NFS_VER4, NULL, 1, NULL, NULL);
6085 	if (error != 0) {
6086 		free(nd, M_TEMP);
6087 		return (error);
6088 	}
6089 	NFSD_DEBUG(4, "nfsrv_setacldsdorpc: aft setaclrpc=%d\n",
6090 	    nd->nd_repstat);
6091 	error = nd->nd_repstat;
6092 	m_freem(nd->nd_mrep);
6093 	free(nd, M_TEMP);
6094 	return (error);
6095 }
6096 
6097 struct nfsrvsetacldsdorpc {
6098 	int			done;
6099 	int			inprog;
6100 	struct task		tsk;
6101 	fhandle_t		fh;
6102 	struct nfsmount		*nmp;
6103 	struct vnode		*vp;
6104 	struct ucred		*cred;
6105 	NFSPROC_T		*p;
6106 	struct acl		*aclp;
6107 	int			err;
6108 };
6109 
6110 /*
6111  * Start up the thread that will execute nfsrv_setacldsdorpc().
6112  */
6113 static void
6114 start_setacldsdorpc(void *arg, int pending)
6115 {
6116 	struct nfsrvsetacldsdorpc *drpc;
6117 
6118 	drpc = (struct nfsrvsetacldsdorpc *)arg;
6119 	drpc->err = nfsrv_setacldsdorpc(&drpc->fh, drpc->cred, drpc->p,
6120 	    drpc->vp, drpc->nmp, drpc->aclp);
6121 	drpc->done = 1;
6122 }
6123 
6124 static int
6125 nfsrv_setacldsrpc(fhandle_t *fhp, struct ucred *cred, NFSPROC_T *p,
6126     struct vnode *vp, struct nfsmount **nmpp, int mirrorcnt, struct acl *aclp,
6127     int *failposp)
6128 {
6129 	struct nfsrvsetacldsdorpc *drpc, *tdrpc = NULL;
6130 	int error, i, ret, timo;
6131 
6132 	NFSD_DEBUG(4, "in nfsrv_setacldsrpc\n");
6133 	drpc = NULL;
6134 	if (mirrorcnt > 1)
6135 		tdrpc = drpc = malloc(sizeof(*drpc) * (mirrorcnt - 1), M_TEMP,
6136 		    M_WAITOK);
6137 
6138 	/*
6139 	 * Do the setattr RPC for every DS, using a separate kernel process
6140 	 * for every DS except the last one.
6141 	 */
6142 	error = 0;
6143 	for (i = 0; i < mirrorcnt - 1; i++, tdrpc++) {
6144 		tdrpc->done = 0;
6145 		tdrpc->inprog = 0;
6146 		NFSBCOPY(fhp, &tdrpc->fh, sizeof(*fhp));
6147 		tdrpc->nmp = *nmpp;
6148 		tdrpc->vp = vp;
6149 		tdrpc->cred = cred;
6150 		tdrpc->p = p;
6151 		tdrpc->aclp = aclp;
6152 		tdrpc->err = 0;
6153 		ret = EIO;
6154 		if (nfs_pnfsiothreads != 0) {
6155 			ret = nfs_pnfsio(start_setacldsdorpc, tdrpc);
6156 			NFSD_DEBUG(4, "nfsrv_setacldsrpc: nfs_pnfsio=%d\n",
6157 			    ret);
6158 		}
6159 		if (ret != 0) {
6160 			ret = nfsrv_setacldsdorpc(fhp, cred, p, vp, *nmpp,
6161 			    aclp);
6162 			if (nfsds_failerr(ret) && *failposp == -1)
6163 				*failposp = i;
6164 			else if (error == 0 && ret != 0)
6165 				error = ret;
6166 		}
6167 		nmpp++;
6168 		fhp++;
6169 	}
6170 	ret = nfsrv_setacldsdorpc(fhp, cred, p, vp, *nmpp, aclp);
6171 	if (nfsds_failerr(ret) && *failposp == -1 && mirrorcnt > 1)
6172 		*failposp = mirrorcnt - 1;
6173 	else if (error == 0 && ret != 0)
6174 		error = ret;
6175 	NFSD_DEBUG(4, "nfsrv_setacldsrpc: aft setextat=%d\n", error);
6176 	tdrpc = drpc;
6177 	timo = hz / 50;		/* Wait for 20msec. */
6178 	if (timo < 1)
6179 		timo = 1;
6180 	for (i = 0; i < mirrorcnt - 1; i++, tdrpc++) {
6181 		/* Wait for RPCs on separate threads to complete. */
6182 		while (tdrpc->inprog != 0 && tdrpc->done == 0)
6183 			tsleep(&tdrpc->tsk, PVFS, "srvacds", timo);
6184 		if (nfsds_failerr(tdrpc->err) && *failposp == -1)
6185 			*failposp = i;
6186 		else if (error == 0 && tdrpc->err != 0)
6187 			error = tdrpc->err;
6188 	}
6189 	free(drpc, M_TEMP);
6190 	return (error);
6191 }
6192 
6193 /*
6194  * Getattr call to the DS for the attributes that change due to writing.
6195  */
6196 static int
6197 nfsrv_getattrdsrpc(fhandle_t *fhp, struct ucred *cred, NFSPROC_T *p,
6198     struct vnode *vp, struct nfsmount *nmp, struct nfsvattr *nap)
6199 {
6200 	struct nfsrv_descript *nd;
6201 	int error;
6202 	nfsattrbit_t attrbits;
6203 
6204 	NFSD_DEBUG(4, "in nfsrv_getattrdsrpc\n");
6205 	nd = malloc(sizeof(*nd), M_TEMP, M_WAITOK | M_ZERO);
6206 	nfscl_reqstart(nd, NFSPROC_GETATTR, nmp, (u_int8_t *)fhp,
6207 	    sizeof(fhandle_t), NULL, NULL, 0, 0);
6208 	NFSZERO_ATTRBIT(&attrbits);
6209 	NFSSETBIT_ATTRBIT(&attrbits, NFSATTRBIT_SIZE);
6210 	NFSSETBIT_ATTRBIT(&attrbits, NFSATTRBIT_CHANGE);
6211 	NFSSETBIT_ATTRBIT(&attrbits, NFSATTRBIT_TIMEACCESS);
6212 	NFSSETBIT_ATTRBIT(&attrbits, NFSATTRBIT_TIMEMODIFY);
6213 	NFSSETBIT_ATTRBIT(&attrbits, NFSATTRBIT_SPACEUSED);
6214 	(void) nfsrv_putattrbit(nd, &attrbits);
6215 	error = newnfs_request(nd, nmp, NULL, &nmp->nm_sockreq, NULL, p, cred,
6216 	    NFS_PROG, NFS_VER4, NULL, 1, NULL, NULL);
6217 	if (error != 0) {
6218 		free(nd, M_TEMP);
6219 		return (error);
6220 	}
6221 	NFSD_DEBUG(4, "nfsrv_getattrdsrpc: aft getattrrpc=%d\n",
6222 	    nd->nd_repstat);
6223 	if (nd->nd_repstat == 0) {
6224 		error = nfsv4_loadattr(nd, NULL, nap, NULL, NULL, 0,
6225 		    NULL, NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL,
6226 		    NULL, NULL);
6227 		/*
6228 		 * We can only save the updated values in the extended
6229 		 * attribute if the vp is exclusively locked.
6230 		 * This should happen when any of the following operations
6231 		 * occur on the vnode:
6232 		 *    Close, Delegreturn, LayoutCommit, LayoutReturn
6233 		 * As such, the updated extended attribute should get saved
6234 		 * before nfsrv_checkdsattr() returns 0 and allows the cached
6235 		 * attributes to be returned without calling this function.
6236 		 */
6237 		if (error == 0 && VOP_ISLOCKED(vp) == LK_EXCLUSIVE) {
6238 			error = nfsrv_setextattr(vp, nap, p);
6239 			NFSD_DEBUG(4, "nfsrv_getattrdsrpc: aft setextat=%d\n",
6240 			    error);
6241 		}
6242 	} else
6243 		error = nd->nd_repstat;
6244 	m_freem(nd->nd_mrep);
6245 	free(nd, M_TEMP);
6246 	NFSD_DEBUG(4, "nfsrv_getattrdsrpc error=%d\n", error);
6247 	return (error);
6248 }
6249 
6250 /*
6251  * Seek call to a DS.
6252  */
6253 static int
6254 nfsrv_seekdsrpc(fhandle_t *fhp, off_t *offp, int content, bool *eofp,
6255     struct ucred *cred, NFSPROC_T *p, struct nfsmount *nmp)
6256 {
6257 	uint32_t *tl;
6258 	struct nfsrv_descript *nd;
6259 	nfsv4stateid_t st;
6260 	int error;
6261 
6262 	NFSD_DEBUG(4, "in nfsrv_seekdsrpc\n");
6263 	/*
6264 	 * Use a stateid where other is an alternating 01010 pattern and
6265 	 * seqid is 0xffffffff.  This value is not defined as special by
6266 	 * the RFC and is used by the FreeBSD NFS server to indicate an
6267 	 * MDS->DS proxy operation.
6268 	 */
6269 	st.other[0] = 0x55555555;
6270 	st.other[1] = 0x55555555;
6271 	st.other[2] = 0x55555555;
6272 	st.seqid = 0xffffffff;
6273 	nd = malloc(sizeof(*nd), M_TEMP, M_WAITOK | M_ZERO);
6274 	nfscl_reqstart(nd, NFSPROC_SEEKDS, nmp, (u_int8_t *)fhp,
6275 	    sizeof(fhandle_t), NULL, NULL, 0, 0);
6276 	nfsm_stateidtom(nd, &st, NFSSTATEID_PUTSTATEID);
6277 	NFSM_BUILD(tl, uint32_t *, NFSX_HYPER + NFSX_UNSIGNED);
6278 	txdr_hyper(*offp, tl); tl += 2;
6279 	*tl = txdr_unsigned(content);
6280 	error = newnfs_request(nd, nmp, NULL, &nmp->nm_sockreq, NULL, p, cred,
6281 	    NFS_PROG, NFS_VER4, NULL, 1, NULL, NULL);
6282 	if (error != 0) {
6283 		free(nd, M_TEMP);
6284 		return (error);
6285 	}
6286 	NFSD_DEBUG(4, "nfsrv_seekdsrpc: aft seekrpc=%d\n", nd->nd_repstat);
6287 	if (nd->nd_repstat == 0) {
6288 		NFSM_DISSECT(tl, uint32_t *, NFSX_UNSIGNED + NFSX_HYPER);
6289 		if (*tl++ == newnfs_true)
6290 			*eofp = true;
6291 		else
6292 			*eofp = false;
6293 		*offp = fxdr_hyper(tl);
6294 	} else
6295 		error = nd->nd_repstat;
6296 nfsmout:
6297 	m_freem(nd->nd_mrep);
6298 	free(nd, M_TEMP);
6299 	NFSD_DEBUG(4, "nfsrv_seekdsrpc error=%d\n", error);
6300 	return (error);
6301 }
6302 
6303 /*
6304  * Get the device id and file handle for a DS file.
6305  */
6306 int
6307 nfsrv_dsgetdevandfh(struct vnode *vp, NFSPROC_T *p, int *mirrorcntp,
6308     fhandle_t *fhp, char *devid)
6309 {
6310 	int buflen, error;
6311 	char *buf;
6312 
6313 	buflen = 1024;
6314 	buf = malloc(buflen, M_TEMP, M_WAITOK);
6315 	error = nfsrv_dsgetsockmnt(vp, 0, buf, &buflen, mirrorcntp, p, NULL,
6316 	    fhp, devid, NULL, NULL, NULL, NULL, NULL, NULL);
6317 	free(buf, M_TEMP);
6318 	return (error);
6319 }
6320 
6321 /*
6322  * Do a Lookup against the DS for the filename.
6323  */
6324 static int
6325 nfsrv_pnfslookupds(struct vnode *vp, struct vnode *dvp, struct pnfsdsfile *pf,
6326     struct vnode **nvpp, NFSPROC_T *p)
6327 {
6328 	struct nameidata named;
6329 	struct ucred *tcred;
6330 	char *bufp;
6331 	u_long *hashp;
6332 	struct vnode *nvp;
6333 	int error;
6334 
6335 	tcred = newnfs_getcred();
6336 	named.ni_cnd.cn_nameiop = LOOKUP;
6337 	named.ni_cnd.cn_lkflags = LK_SHARED | LK_RETRY;
6338 	named.ni_cnd.cn_cred = tcred;
6339 	named.ni_cnd.cn_flags = ISLASTCN | LOCKPARENT | LOCKLEAF | SAVENAME;
6340 	nfsvno_setpathbuf(&named, &bufp, &hashp);
6341 	named.ni_cnd.cn_nameptr = bufp;
6342 	named.ni_cnd.cn_namelen = strlen(pf->dsf_filename);
6343 	strlcpy(bufp, pf->dsf_filename, NAME_MAX);
6344 	NFSD_DEBUG(4, "nfsrv_pnfslookupds: filename=%s\n", bufp);
6345 	error = VOP_LOOKUP(dvp, &nvp, &named.ni_cnd);
6346 	NFSD_DEBUG(4, "nfsrv_pnfslookupds: aft LOOKUP=%d\n", error);
6347 	NFSFREECRED(tcred);
6348 	nfsvno_relpathbuf(&named);
6349 	if (error == 0)
6350 		*nvpp = nvp;
6351 	NFSD_DEBUG(4, "eo nfsrv_pnfslookupds=%d\n", error);
6352 	return (error);
6353 }
6354 
6355 /*
6356  * Set the file handle to the correct one.
6357  */
6358 static void
6359 nfsrv_pnfssetfh(struct vnode *vp, struct pnfsdsfile *pf, char *devid,
6360     char *fnamep, struct vnode *nvp, NFSPROC_T *p)
6361 {
6362 	struct nfsnode *np;
6363 	int ret = 0;
6364 
6365 	np = VTONFS(nvp);
6366 	NFSBCOPY(np->n_fhp->nfh_fh, &pf->dsf_fh, NFSX_MYFH);
6367 	/*
6368 	 * We can only do a vn_set_extattr() if the vnode is exclusively
6369 	 * locked and vn_start_write() has been done.  If devid != NULL or
6370 	 * fnamep != NULL or the vnode is shared locked, vn_start_write()
6371 	 * may not have been done.
6372 	 * If not done now, it will be done on a future call.
6373 	 */
6374 	if (devid == NULL && fnamep == NULL && NFSVOPISLOCKED(vp) ==
6375 	    LK_EXCLUSIVE)
6376 		ret = vn_extattr_set(vp, IO_NODELOCKED,
6377 		    EXTATTR_NAMESPACE_SYSTEM, "pnfsd.dsfile", sizeof(*pf),
6378 		    (char *)pf, p);
6379 	NFSD_DEBUG(4, "eo nfsrv_pnfssetfh=%d\n", ret);
6380 }
6381 
6382 /*
6383  * Cause RPCs waiting on "nmp" to fail.  This is called for a DS mount point
6384  * when the DS has failed.
6385  */
6386 void
6387 nfsrv_killrpcs(struct nfsmount *nmp)
6388 {
6389 
6390 	/*
6391 	 * Call newnfs_nmcancelreqs() to cause
6392 	 * any RPCs in progress on the mount point to
6393 	 * fail.
6394 	 * This will cause any process waiting for an
6395 	 * RPC to complete while holding a vnode lock
6396 	 * on the mounted-on vnode (such as "df" or
6397 	 * a non-forced "umount") to fail.
6398 	 * This will unlock the mounted-on vnode so
6399 	 * a forced dismount can succeed.
6400 	 * The NFSMNTP_CANCELRPCS flag should be set when this function is
6401 	 * called.
6402 	 */
6403 	newnfs_nmcancelreqs(nmp);
6404 }
6405 
6406 /*
6407  * Sum up the statfs info for each of the DSs, so that the client will
6408  * receive the total for all DSs.
6409  */
6410 static int
6411 nfsrv_pnfsstatfs(struct statfs *sf, struct mount *mp)
6412 {
6413 	struct statfs *tsf;
6414 	struct nfsdevice *ds;
6415 	struct vnode **dvpp, **tdvpp, *dvp;
6416 	uint64_t tot;
6417 	int cnt, error = 0, i;
6418 
6419 	if (nfsrv_devidcnt <= 0)
6420 		return (ENXIO);
6421 	dvpp = mallocarray(nfsrv_devidcnt, sizeof(*dvpp), M_TEMP, M_WAITOK);
6422 	tsf = malloc(sizeof(*tsf), M_TEMP, M_WAITOK);
6423 
6424 	/* Get an array of the dvps for the DSs. */
6425 	tdvpp = dvpp;
6426 	i = 0;
6427 	NFSDDSLOCK();
6428 	/* First, search for matches for same file system. */
6429 	TAILQ_FOREACH(ds, &nfsrv_devidhead, nfsdev_list) {
6430 		if (ds->nfsdev_nmp != NULL && ds->nfsdev_mdsisset != 0 &&
6431 		    fsidcmp(&ds->nfsdev_mdsfsid, &mp->mnt_stat.f_fsid) == 0) {
6432 			if (++i > nfsrv_devidcnt)
6433 				break;
6434 			*tdvpp++ = ds->nfsdev_dvp;
6435 		}
6436 	}
6437 	/*
6438 	 * If no matches for same file system, total all servers not assigned
6439 	 * to a file system.
6440 	 */
6441 	if (i == 0) {
6442 		TAILQ_FOREACH(ds, &nfsrv_devidhead, nfsdev_list) {
6443 			if (ds->nfsdev_nmp != NULL &&
6444 			    ds->nfsdev_mdsisset == 0) {
6445 				if (++i > nfsrv_devidcnt)
6446 					break;
6447 				*tdvpp++ = ds->nfsdev_dvp;
6448 			}
6449 		}
6450 	}
6451 	NFSDDSUNLOCK();
6452 	cnt = i;
6453 
6454 	/* Do a VFS_STATFS() for each of the DSs and sum them up. */
6455 	tdvpp = dvpp;
6456 	for (i = 0; i < cnt && error == 0; i++) {
6457 		dvp = *tdvpp++;
6458 		error = VFS_STATFS(dvp->v_mount, tsf);
6459 		if (error == 0) {
6460 			if (sf->f_bsize == 0) {
6461 				if (tsf->f_bsize > 0)
6462 					sf->f_bsize = tsf->f_bsize;
6463 				else
6464 					sf->f_bsize = 8192;
6465 			}
6466 			if (tsf->f_blocks > 0) {
6467 				if (sf->f_bsize != tsf->f_bsize) {
6468 					tot = tsf->f_blocks * tsf->f_bsize;
6469 					sf->f_blocks += (tot / sf->f_bsize);
6470 				} else
6471 					sf->f_blocks += tsf->f_blocks;
6472 			}
6473 			if (tsf->f_bfree > 0) {
6474 				if (sf->f_bsize != tsf->f_bsize) {
6475 					tot = tsf->f_bfree * tsf->f_bsize;
6476 					sf->f_bfree += (tot / sf->f_bsize);
6477 				} else
6478 					sf->f_bfree += tsf->f_bfree;
6479 			}
6480 			if (tsf->f_bavail > 0) {
6481 				if (sf->f_bsize != tsf->f_bsize) {
6482 					tot = tsf->f_bavail * tsf->f_bsize;
6483 					sf->f_bavail += (tot / sf->f_bsize);
6484 				} else
6485 					sf->f_bavail += tsf->f_bavail;
6486 			}
6487 		}
6488 	}
6489 	free(tsf, M_TEMP);
6490 	free(dvpp, M_TEMP);
6491 	return (error);
6492 }
6493 
6494 /*
6495  * Set an NFSv4 acl.
6496  */
6497 int
6498 nfsrv_setacl(struct vnode *vp, NFSACL_T *aclp, struct ucred *cred, NFSPROC_T *p)
6499 {
6500 	int error;
6501 
6502 	if (nfsrv_useacl == 0 || nfs_supportsnfsv4acls(vp) == 0) {
6503 		error = NFSERR_ATTRNOTSUPP;
6504 		goto out;
6505 	}
6506 	/*
6507 	 * With NFSv4 ACLs, chmod(2) may need to add additional entries.
6508 	 * Make sure it has enough room for that - splitting every entry
6509 	 * into two and appending "canonical six" entries at the end.
6510 	 * Cribbed out of kern/vfs_acl.c - Rick M.
6511 	 */
6512 	if (aclp->acl_cnt > (ACL_MAX_ENTRIES - 6) / 2) {
6513 		error = NFSERR_ATTRNOTSUPP;
6514 		goto out;
6515 	}
6516 	error = VOP_SETACL(vp, ACL_TYPE_NFS4, aclp, cred, p);
6517 	if (error == 0) {
6518 		error = nfsrv_dssetacl(vp, aclp, cred, p);
6519 		if (error == ENOENT)
6520 			error = 0;
6521 	}
6522 
6523 out:
6524 	NFSEXITCODE(error);
6525 	return (error);
6526 }
6527 
6528 /*
6529  * Seek vnode op call (actually it is a VOP_IOCTL()).
6530  * This function is called with the vnode locked, but unlocks and vrele()s
6531  * the vp before returning.
6532  */
6533 int
6534 nfsvno_seek(struct nfsrv_descript *nd, struct vnode *vp, u_long cmd,
6535     off_t *offp, int content, bool *eofp, struct ucred *cred, NFSPROC_T *p)
6536 {
6537 	struct nfsvattr at;
6538 	int error, ret;
6539 
6540 	ASSERT_VOP_LOCKED(vp, "nfsvno_seek vp");
6541 	/*
6542 	 * Attempt to seek on a DS file. A return of ENOENT implies
6543 	 * there is no DS file to seek on.
6544 	 */
6545 	error = nfsrv_proxyds(vp, 0, 0, cred, p, NFSPROC_SEEKDS, NULL,
6546 	    NULL, NULL, NULL, NULL, offp, content, eofp);
6547 	if (error != ENOENT) {
6548 		vput(vp);
6549 		return (error);
6550 	}
6551 
6552 	/*
6553 	 * Do the VOP_IOCTL() call.  For the case where *offp == file_size,
6554 	 * VOP_IOCTL() will return ENXIO.  However, the correct reply for
6555 	 * NFSv4.2 is *eofp == true and error == 0 for this case.
6556 	 */
6557 	NFSVOPUNLOCK(vp);
6558 	error = VOP_IOCTL(vp, cmd, offp, 0, cred, p);
6559 	*eofp = false;
6560 	if (error == ENXIO || (error == 0 && cmd == FIOSEEKHOLE)) {
6561 		/* Handle the cases where we might be at EOF. */
6562 		ret = nfsvno_getattr(vp, &at, nd, p, 0, NULL);
6563 		if (ret == 0 && *offp == at.na_size) {
6564 			*eofp = true;
6565 			error = 0;
6566 		}
6567 		if (ret != 0 && error == 0)
6568 			error = ret;
6569 	}
6570 	vrele(vp);
6571 	NFSEXITCODE(error);
6572 	return (error);
6573 }
6574 
6575 /*
6576  * Allocate vnode op call.
6577  */
6578 int
6579 nfsvno_allocate(struct vnode *vp, off_t off, off_t len, struct ucred *cred,
6580     NFSPROC_T *p)
6581 {
6582 	int error;
6583 	off_t olen;
6584 
6585 	ASSERT_VOP_ELOCKED(vp, "nfsvno_allocate vp");
6586 	/*
6587 	 * Attempt to allocate on a DS file. A return of ENOENT implies
6588 	 * there is no DS file to allocate on.
6589 	 */
6590 	error = nfsrv_proxyds(vp, off, 0, cred, p, NFSPROC_ALLOCATE, NULL,
6591 	    NULL, NULL, NULL, NULL, &len, 0, NULL);
6592 	if (error != ENOENT)
6593 		return (error);
6594 
6595 	/*
6596 	 * Do the actual VOP_ALLOCATE(), looping so long as
6597 	 * progress is being made, to achieve completion.
6598 	 */
6599 	do {
6600 		olen = len;
6601 		error = VOP_ALLOCATE(vp, &off, &len, IO_SYNC, cred);
6602 		if (error == 0 && len > 0 && olen > len)
6603 			maybe_yield();
6604 	} while (error == 0 && len > 0 && olen > len);
6605 	if (error == 0 && len > 0)
6606 		error = NFSERR_IO;
6607 	NFSEXITCODE(error);
6608 	return (error);
6609 }
6610 
6611 /*
6612  * Deallocate vnode op call.
6613  */
6614 int
6615 nfsvno_deallocate(struct vnode *vp, off_t off, off_t len, struct ucred *cred,
6616     NFSPROC_T *p)
6617 {
6618 	int error;
6619 	off_t olen;
6620 
6621 	ASSERT_VOP_ELOCKED(vp, "nfsvno_deallocate vp");
6622 	/*
6623 	 * Attempt to deallocate on a DS file. A return of ENOENT implies
6624 	 * there is no DS file to deallocate on.
6625 	 */
6626 	error = nfsrv_proxyds(vp, off, 0, cred, p, NFSPROC_DEALLOCATE, NULL,
6627 	    NULL, NULL, NULL, NULL, &len, 0, NULL);
6628 	if (error != ENOENT)
6629 		return (error);
6630 
6631 	/*
6632 	 * Do the actual VOP_DEALLOCATE(), looping so long as
6633 	 * progress is being made, to achieve completion.
6634 	 */
6635 	do {
6636 		olen = len;
6637 		error = VOP_DEALLOCATE(vp, &off, &len, 0, IO_SYNC, cred);
6638 		if (error == 0 && len > 0 && olen > len)
6639 			maybe_yield();
6640 	} while (error == 0 && len > 0 && olen > len);
6641 	if (error == 0 && len > 0)
6642 		error = NFSERR_IO;
6643 	NFSEXITCODE(error);
6644 	return (error);
6645 }
6646 
6647 /*
6648  * Get Extended Atribute vnode op into an mbuf list.
6649  */
6650 int
6651 nfsvno_getxattr(struct vnode *vp, char *name, uint32_t maxresp,
6652     struct ucred *cred, uint64_t flag, int maxextsiz, struct thread *p,
6653     struct mbuf **mpp, struct mbuf **mpendp, int *lenp)
6654 {
6655 	struct iovec *iv;
6656 	struct uio io, *uiop = &io;
6657 	struct mbuf *m, *m2;
6658 	int alen, error, len, tlen;
6659 	size_t siz;
6660 
6661 	/* First, find out the size of the extended attribute. */
6662 	error = VOP_GETEXTATTR(vp, EXTATTR_NAMESPACE_USER, name, NULL,
6663 	    &siz, cred, p);
6664 	if (error != 0)
6665 		return (NFSERR_NOXATTR);
6666 	if (siz > maxresp - NFS_MAXXDR)
6667 		return (NFSERR_XATTR2BIG);
6668 	len = siz;
6669 	tlen = NFSM_RNDUP(len);
6670 	if (tlen > 0) {
6671 		/*
6672 		 * If cnt > MCLBYTES and the reply will not be saved, use
6673 		 * ext_pgs mbufs for TLS.
6674 		 * For NFSv4.0, we do not know for sure if the reply will
6675 		 * be saved, so do not use ext_pgs mbufs for NFSv4.0.
6676 		 * Always use ext_pgs mbufs if ND_EXTPG is set.
6677 		 */
6678 		if ((flag & ND_EXTPG) != 0 || (tlen > MCLBYTES &&
6679 		    (flag & (ND_TLS | ND_SAVEREPLY)) == ND_TLS &&
6680 		    (flag & (ND_NFSV4 | ND_NFSV41)) != ND_NFSV4))
6681 			uiop->uio_iovcnt = nfsrv_createiovec_extpgs(tlen,
6682 			    maxextsiz, &m, &m2, &iv);
6683 		else
6684 			uiop->uio_iovcnt = nfsrv_createiovec(tlen, &m, &m2,
6685 			    &iv);
6686 		uiop->uio_iov = iv;
6687 	} else {
6688 		uiop->uio_iovcnt = 0;
6689 		uiop->uio_iov = iv = NULL;
6690 		m = m2 = NULL;
6691 	}
6692 	uiop->uio_offset = 0;
6693 	uiop->uio_resid = tlen;
6694 	uiop->uio_rw = UIO_READ;
6695 	uiop->uio_segflg = UIO_SYSSPACE;
6696 	uiop->uio_td = p;
6697 #ifdef MAC
6698 	error = mac_vnode_check_getextattr(cred, vp, EXTATTR_NAMESPACE_USER,
6699 	    name);
6700 	if (error != 0)
6701 		goto out;
6702 #endif
6703 
6704 	if (tlen > 0)
6705 		error = VOP_GETEXTATTR(vp, EXTATTR_NAMESPACE_USER, name, uiop,
6706 		    NULL, cred, p);
6707 	if (error != 0)
6708 		goto out;
6709 	if (uiop->uio_resid > 0) {
6710 		alen = tlen;
6711 		len = tlen - uiop->uio_resid;
6712 		tlen = NFSM_RNDUP(len);
6713 		if (alen != tlen)
6714 			printf("nfsvno_getxattr: weird size read\n");
6715 		if (tlen == 0) {
6716 			m_freem(m);
6717 			m = m2 = NULL;
6718 		} else if (alen != tlen || tlen != len)
6719 			m2 = nfsrv_adj(m, alen - tlen, tlen - len);
6720 	}
6721 	*lenp = len;
6722 	*mpp = m;
6723 	*mpendp = m2;
6724 
6725 out:
6726 	if (error != 0) {
6727 		if (m != NULL)
6728 			m_freem(m);
6729 		*lenp = 0;
6730 	}
6731 	free(iv, M_TEMP);
6732 	NFSEXITCODE(error);
6733 	return (error);
6734 }
6735 
6736 /*
6737  * Set Extended attribute vnode op from an mbuf list.
6738  */
6739 int
6740 nfsvno_setxattr(struct vnode *vp, char *name, int len, struct mbuf *m,
6741     char *cp, struct ucred *cred, struct thread *p)
6742 {
6743 	struct iovec *iv;
6744 	struct uio uio, *uiop = &uio;
6745 	int cnt, error;
6746 
6747 	error = 0;
6748 #ifdef MAC
6749 	error = mac_vnode_check_setextattr(cred, vp, EXTATTR_NAMESPACE_USER,
6750 	    name);
6751 #endif
6752 	if (error != 0)
6753 		goto out;
6754 
6755 	uiop->uio_rw = UIO_WRITE;
6756 	uiop->uio_segflg = UIO_SYSSPACE;
6757 	uiop->uio_td = p;
6758 	uiop->uio_offset = 0;
6759 	uiop->uio_resid = len;
6760 	if (len > 0) {
6761 		error = nfsrv_createiovecw(len, m, cp, &iv, &cnt);
6762 		uiop->uio_iov = iv;
6763 		uiop->uio_iovcnt = cnt;
6764 	} else {
6765 		uiop->uio_iov = iv = NULL;
6766 		uiop->uio_iovcnt = 0;
6767 	}
6768 	if (error == 0) {
6769 		error = VOP_SETEXTATTR(vp, EXTATTR_NAMESPACE_USER, name, uiop,
6770 		    cred, p);
6771 		free(iv, M_TEMP);
6772 	}
6773 
6774 out:
6775 	NFSEXITCODE(error);
6776 	return (error);
6777 }
6778 
6779 /*
6780  * Remove Extended attribute vnode op.
6781  */
6782 int
6783 nfsvno_rmxattr(struct nfsrv_descript *nd, struct vnode *vp, char *name,
6784     struct ucred *cred, struct thread *p)
6785 {
6786 	int error;
6787 
6788 	/*
6789 	 * Get rid of any delegations.  I am not sure why this is required,
6790 	 * but RFC-8276 says so.
6791 	 */
6792 	error = nfsrv_checkremove(vp, 0, nd, nd->nd_clientid, p);
6793 	if (error != 0)
6794 		goto out;
6795 #ifdef MAC
6796 	error = mac_vnode_check_deleteextattr(cred, vp, EXTATTR_NAMESPACE_USER,
6797 	    name);
6798 	if (error != 0)
6799 		goto out;
6800 #endif
6801 
6802 	error = VOP_DELETEEXTATTR(vp, EXTATTR_NAMESPACE_USER, name, cred, p);
6803 	if (error == EOPNOTSUPP)
6804 		error = VOP_SETEXTATTR(vp, EXTATTR_NAMESPACE_USER, name, NULL,
6805 		    cred, p);
6806 out:
6807 	NFSEXITCODE(error);
6808 	return (error);
6809 }
6810 
6811 /*
6812  * List Extended Atribute vnode op into an mbuf list.
6813  */
6814 int
6815 nfsvno_listxattr(struct vnode *vp, uint64_t cookie, struct ucred *cred,
6816     struct thread *p, u_char **bufp, uint32_t *lenp, bool *eofp)
6817 {
6818 	struct iovec iv;
6819 	struct uio io;
6820 	int error;
6821 	size_t siz;
6822 
6823 	*bufp = NULL;
6824 	/* First, find out the size of the extended attribute. */
6825 	error = VOP_LISTEXTATTR(vp, EXTATTR_NAMESPACE_USER, NULL, &siz, cred,
6826 	    p);
6827 	if (error != 0)
6828 		return (NFSERR_NOXATTR);
6829 	if (siz <= cookie) {
6830 		*lenp = 0;
6831 		*eofp = true;
6832 		goto out;
6833 	}
6834 	if (siz > cookie + *lenp) {
6835 		siz = cookie + *lenp;
6836 		*eofp = false;
6837 	} else
6838 		*eofp = true;
6839 	/* Just choose a sanity limit of 10Mbytes for malloc(M_TEMP). */
6840 	if (siz > 10 * 1024 * 1024) {
6841 		error = NFSERR_XATTR2BIG;
6842 		goto out;
6843 	}
6844 	*bufp = malloc(siz, M_TEMP, M_WAITOK);
6845 	iv.iov_base = *bufp;
6846 	iv.iov_len = siz;
6847 	io.uio_iovcnt = 1;
6848 	io.uio_iov = &iv;
6849 	io.uio_offset = 0;
6850 	io.uio_resid = siz;
6851 	io.uio_rw = UIO_READ;
6852 	io.uio_segflg = UIO_SYSSPACE;
6853 	io.uio_td = p;
6854 #ifdef MAC
6855 	error = mac_vnode_check_listextattr(cred, vp, EXTATTR_NAMESPACE_USER);
6856 	if (error != 0)
6857 		goto out;
6858 #endif
6859 
6860 	error = VOP_LISTEXTATTR(vp, EXTATTR_NAMESPACE_USER, &io, NULL, cred,
6861 	    p);
6862 	if (error != 0)
6863 		goto out;
6864 	if (io.uio_resid > 0)
6865 		siz -= io.uio_resid;
6866 	*lenp = siz;
6867 
6868 out:
6869 	if (error != 0) {
6870 		free(*bufp, M_TEMP);
6871 		*bufp = NULL;
6872 	}
6873 	NFSEXITCODE(error);
6874 	return (error);
6875 }
6876 
6877 /*
6878  * Trim trailing data off the mbuf list being built.
6879  */
6880 void
6881 nfsm_trimtrailing(struct nfsrv_descript *nd, struct mbuf *mb, char *bpos,
6882     int bextpg, int bextpgsiz)
6883 {
6884 	vm_page_t pg;
6885 	int fullpgsiz, i;
6886 
6887 	if (mb->m_next != NULL) {
6888 		m_freem(mb->m_next);
6889 		mb->m_next = NULL;
6890 	}
6891 	if ((mb->m_flags & M_EXTPG) != 0) {
6892 		KASSERT(bextpg >= 0 && bextpg < mb->m_epg_npgs,
6893 		    ("nfsm_trimtrailing: bextpg out of range"));
6894 		KASSERT(bpos == (char *)(void *)
6895 		    PHYS_TO_DMAP(mb->m_epg_pa[bextpg]) + PAGE_SIZE - bextpgsiz,
6896 		    ("nfsm_trimtrailing: bextpgsiz bad!"));
6897 
6898 		/* First, get rid of any pages after this position. */
6899 		for (i = mb->m_epg_npgs - 1; i > bextpg; i--) {
6900 			pg = PHYS_TO_VM_PAGE(mb->m_epg_pa[i]);
6901 			vm_page_unwire_noq(pg);
6902 			vm_page_free(pg);
6903 		}
6904 		mb->m_epg_npgs = bextpg + 1;
6905 		if (bextpg == 0)
6906 			fullpgsiz = PAGE_SIZE - mb->m_epg_1st_off;
6907 		else
6908 			fullpgsiz = PAGE_SIZE;
6909 		mb->m_epg_last_len = fullpgsiz - bextpgsiz;
6910 		mb->m_len = m_epg_pagelen(mb, 0, mb->m_epg_1st_off);
6911 		for (i = 1; i < mb->m_epg_npgs; i++)
6912 			mb->m_len += m_epg_pagelen(mb, i, 0);
6913 		nd->nd_bextpgsiz = bextpgsiz;
6914 		nd->nd_bextpg = bextpg;
6915 	} else
6916 		mb->m_len = bpos - mtod(mb, char *);
6917 	nd->nd_mb = mb;
6918 	nd->nd_bpos = bpos;
6919 }
6920 
6921 
6922 /*
6923  * Check to see if a put file handle operation should test for
6924  * NFSERR_WRONGSEC, although NFSv3 actually returns NFSERR_AUTHERR.
6925  * When Open is the next operation, NFSERR_WRONGSEC cannot be
6926  * replied for the Open cases that use a component.  Thia can
6927  * be identified by the fact that the file handle's type is VDIR.
6928  */
6929 bool
6930 nfsrv_checkwrongsec(struct nfsrv_descript *nd, int nextop, enum vtype vtyp)
6931 {
6932 
6933 	if ((nd->nd_flag & ND_NFSV4) == 0) {
6934 		if (nd->nd_procnum == NFSPROC_FSINFO)
6935 			return (false);
6936 		return (true);
6937 	}
6938 
6939 	if ((nd->nd_flag & ND_LASTOP) != 0)
6940 		return (false);
6941 
6942 	if (nextop == NFSV4OP_PUTROOTFH || nextop == NFSV4OP_PUTFH ||
6943 	    nextop == NFSV4OP_PUTPUBFH || nextop == NFSV4OP_RESTOREFH ||
6944 	    nextop == NFSV4OP_LOOKUP || nextop == NFSV4OP_LOOKUPP ||
6945 	    nextop == NFSV4OP_SECINFO || nextop == NFSV4OP_SECINFONONAME)
6946 		return (false);
6947 	if (nextop == NFSV4OP_OPEN && vtyp == VDIR)
6948 		return (false);
6949 	return (true);
6950 }
6951 
6952 /*
6953  * Check DSs marked no space.
6954  */
6955 void
6956 nfsrv_checknospc(void)
6957 {
6958 	struct statfs *tsf;
6959 	struct nfsdevice *ds;
6960 	struct vnode **dvpp, **tdvpp, *dvp;
6961 	char *devid, *tdevid;
6962 	int cnt, error = 0, i;
6963 
6964 	if (nfsrv_devidcnt <= 0)
6965 		return;
6966 	dvpp = mallocarray(nfsrv_devidcnt, sizeof(*dvpp), M_TEMP, M_WAITOK);
6967 	devid = malloc(nfsrv_devidcnt * NFSX_V4DEVICEID, M_TEMP, M_WAITOK);
6968 	tsf = malloc(sizeof(*tsf), M_TEMP, M_WAITOK);
6969 
6970 	/* Get an array of the dvps for the DSs. */
6971 	tdvpp = dvpp;
6972 	tdevid = devid;
6973 	i = 0;
6974 	NFSDDSLOCK();
6975 	/* First, search for matches for same file system. */
6976 	TAILQ_FOREACH(ds, &nfsrv_devidhead, nfsdev_list) {
6977 		if (ds->nfsdev_nmp != NULL && ds->nfsdev_nospc) {
6978 			if (++i > nfsrv_devidcnt)
6979 				break;
6980 			*tdvpp++ = ds->nfsdev_dvp;
6981 			NFSBCOPY(ds->nfsdev_deviceid, tdevid, NFSX_V4DEVICEID);
6982 			tdevid += NFSX_V4DEVICEID;
6983 		}
6984 	}
6985 	NFSDDSUNLOCK();
6986 
6987 	/* Do a VFS_STATFS() for each of the DSs and clear no space. */
6988 	cnt = i;
6989 	tdvpp = dvpp;
6990 	tdevid = devid;
6991 	for (i = 0; i < cnt && error == 0; i++) {
6992 		dvp = *tdvpp++;
6993 		error = VFS_STATFS(dvp->v_mount, tsf);
6994 		if (error == 0 && tsf->f_bavail > 0) {
6995 			NFSD_DEBUG(1, "nfsrv_checknospc: reset nospc\n");
6996 			nfsrv_marknospc(tdevid, false);
6997 		}
6998 		tdevid += NFSX_V4DEVICEID;
6999 	}
7000 	free(tsf, M_TEMP);
7001 	free(dvpp, M_TEMP);
7002 	free(devid, M_TEMP);
7003 }
7004 
7005 extern int (*nfsd_call_nfsd)(struct thread *, struct nfssvc_args *);
7006 
7007 /*
7008  * Called once to initialize data structures...
7009  */
7010 static int
7011 nfsd_modevent(module_t mod, int type, void *data)
7012 {
7013 	int error = 0, i;
7014 	static int loaded = 0;
7015 
7016 	switch (type) {
7017 	case MOD_LOAD:
7018 		if (loaded)
7019 			goto out;
7020 		newnfs_portinit();
7021 		for (i = 0; i < NFSRVCACHE_HASHSIZE; i++) {
7022 			mtx_init(&nfsrchash_table[i].mtx, "nfsrtc", NULL,
7023 			    MTX_DEF);
7024 			mtx_init(&nfsrcahash_table[i].mtx, "nfsrtca", NULL,
7025 			    MTX_DEF);
7026 		}
7027 		mtx_init(&nfsrc_udpmtx, "nfsuc", NULL, MTX_DEF);
7028 		mtx_init(&nfs_v4root_mutex, "nfs4rt", NULL, MTX_DEF);
7029 		mtx_init(&nfsv4root_mnt.mnt_mtx, "nfs4mnt", NULL, MTX_DEF);
7030 		mtx_init(&nfsrv_dontlistlock_mtx, "nfs4dnl", NULL, MTX_DEF);
7031 		mtx_init(&nfsrv_recalllock_mtx, "nfs4rec", NULL, MTX_DEF);
7032 		lockinit(&nfsv4root_mnt.mnt_explock, PVFS, "explock", 0, 0);
7033 		nfsrvd_initcache();
7034 		nfsd_init();
7035 		NFSD_LOCK();
7036 		nfsrvd_init(0);
7037 		NFSD_UNLOCK();
7038 		nfsd_mntinit();
7039 #ifdef VV_DISABLEDELEG
7040 		vn_deleg_ops.vndeleg_recall = nfsd_recalldelegation;
7041 		vn_deleg_ops.vndeleg_disable = nfsd_disabledelegation;
7042 #endif
7043 		nfsd_call_servertimer = nfsrv_servertimer;
7044 		nfsd_call_nfsd = nfssvc_nfsd;
7045 		loaded = 1;
7046 		break;
7047 
7048 	case MOD_UNLOAD:
7049 		if (newnfs_numnfsd != 0) {
7050 			error = EBUSY;
7051 			break;
7052 		}
7053 
7054 #ifdef VV_DISABLEDELEG
7055 		vn_deleg_ops.vndeleg_recall = NULL;
7056 		vn_deleg_ops.vndeleg_disable = NULL;
7057 #endif
7058 		nfsd_call_servertimer = NULL;
7059 		nfsd_call_nfsd = NULL;
7060 
7061 		/* Clean out all NFSv4 state. */
7062 		nfsrv_throwawayallstate(curthread);
7063 
7064 		/* Clean the NFS server reply cache */
7065 		nfsrvd_cleancache();
7066 
7067 		/* Free up the krpc server pool. */
7068 		if (nfsrvd_pool != NULL)
7069 			svcpool_destroy(nfsrvd_pool);
7070 
7071 		/* and get rid of the locks */
7072 		for (i = 0; i < NFSRVCACHE_HASHSIZE; i++) {
7073 			mtx_destroy(&nfsrchash_table[i].mtx);
7074 			mtx_destroy(&nfsrcahash_table[i].mtx);
7075 		}
7076 		mtx_destroy(&nfsrc_udpmtx);
7077 		mtx_destroy(&nfs_v4root_mutex);
7078 		mtx_destroy(&nfsv4root_mnt.mnt_mtx);
7079 		mtx_destroy(&nfsrv_dontlistlock_mtx);
7080 		mtx_destroy(&nfsrv_recalllock_mtx);
7081 		for (i = 0; i < nfsrv_sessionhashsize; i++)
7082 			mtx_destroy(&nfssessionhash[i].mtx);
7083 		if (nfslayouthash != NULL) {
7084 			for (i = 0; i < nfsrv_layouthashsize; i++)
7085 				mtx_destroy(&nfslayouthash[i].mtx);
7086 			free(nfslayouthash, M_NFSDSESSION);
7087 		}
7088 		lockdestroy(&nfsv4root_mnt.mnt_explock);
7089 		free(nfsclienthash, M_NFSDCLIENT);
7090 		free(nfslockhash, M_NFSDLOCKFILE);
7091 		free(nfssessionhash, M_NFSDSESSION);
7092 		loaded = 0;
7093 		break;
7094 	default:
7095 		error = EOPNOTSUPP;
7096 		break;
7097 	}
7098 
7099 out:
7100 	NFSEXITCODE(error);
7101 	return (error);
7102 }
7103 static moduledata_t nfsd_mod = {
7104 	"nfsd",
7105 	nfsd_modevent,
7106 	NULL,
7107 };
7108 DECLARE_MODULE(nfsd, nfsd_mod, SI_SUB_VFS, SI_ORDER_ANY);
7109 
7110 /* So that loader and kldload(2) can find us, wherever we are.. */
7111 MODULE_VERSION(nfsd, 1);
7112 MODULE_DEPEND(nfsd, nfscommon, 1, 1, 1);
7113 MODULE_DEPEND(nfsd, nfslockd, 1, 1, 1);
7114 MODULE_DEPEND(nfsd, krpc, 1, 1, 1);
7115 MODULE_DEPEND(nfsd, nfssvc, 1, 1, 1);
7116