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