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