xref: /freebsd/sys/fs/nfsserver/nfs_nfsdport.c (revision 2477e88b8d4328535357bc62409f673a551be179)
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 		case NFSATTRBIT_MODEUMASK:
3216 			NFSM_DISSECT(tl, uint32_t *, 2 * NFSX_UNSIGNED);
3217 			mode = fxdr_unsigned(u_short, *tl++);
3218 			mask = fxdr_unsigned(u_short, *tl);
3219 			/*
3220 			 * If moderet != 0, mode has already been done.
3221 			 * If vp != NULL, this is not a file object creation.
3222 			 */
3223 			if ((nd->nd_flag & ND_NFSV42) == 0)
3224 				nd->nd_repstat = NFSERR_ATTRNOTSUPP;
3225 			else if ((mask & ~0777) != 0 || vp != NULL ||
3226 			    moderet != 0)
3227 				nd->nd_repstat = NFSERR_INVAL;
3228 			else
3229 				nvap->na_mode = (mode & ~mask);
3230 			attrsum += 2 * NFSX_UNSIGNED;
3231 			break;
3232 		default:
3233 			nd->nd_repstat = NFSERR_ATTRNOTSUPP;
3234 			/*
3235 			 * set bitpos so we drop out of the loop.
3236 			 */
3237 			bitpos = NFSATTRBIT_MAX;
3238 			break;
3239 		}
3240 	}
3241 
3242 	/*
3243 	 * some clients pad the attrlist, so we need to skip over the
3244 	 * padding.
3245 	 */
3246 	if (attrsum > attrsize) {
3247 		error = NFSERR_BADXDR;
3248 	} else {
3249 		attrsize = NFSM_RNDUP(attrsize);
3250 		if (attrsum < attrsize)
3251 			error = nfsm_advance(nd, attrsize - attrsum, -1);
3252 	}
3253 nfsmout:
3254 	NFSEXITCODE2(error, nd);
3255 	return (error);
3256 }
3257 
3258 /*
3259  * Check/setup export credentials.
3260  */
3261 int
3262 nfsd_excred(struct nfsrv_descript *nd, struct nfsexstuff *exp,
3263     struct ucred *credanon, bool testsec)
3264 {
3265 	int error;
3266 
3267 	/*
3268 	 * Check/setup credentials.
3269 	 */
3270 	if (nd->nd_flag & ND_GSS)
3271 		exp->nes_exflag &= ~MNT_EXPORTANON;
3272 
3273 	/*
3274 	 * Check to see if the operation is allowed for this security flavor.
3275 	 */
3276 	error = 0;
3277 	if (testsec) {
3278 		error = nfsvno_testexp(nd, exp);
3279 		if (error != 0)
3280 			goto out;
3281 	}
3282 
3283 	/*
3284 	 * Check to see if the file system is exported V4 only.
3285 	 */
3286 	if (NFSVNO_EXV4ONLY(exp) && !(nd->nd_flag & ND_NFSV4)) {
3287 		error = NFSERR_PROGNOTV4;
3288 		goto out;
3289 	}
3290 
3291 	/*
3292 	 * Now, map the user credentials.
3293 	 * (Note that ND_AUTHNONE will only be set for an NFSv3
3294 	 *  Fsinfo RPC. If set for anything else, this code might need
3295 	 *  to change.)
3296 	 */
3297 	if (NFSVNO_EXPORTED(exp)) {
3298 		if (((nd->nd_flag & ND_GSS) == 0 && nd->nd_cred->cr_uid == 0) ||
3299 		     NFSVNO_EXPORTANON(exp) ||
3300 		     (nd->nd_flag & ND_AUTHNONE) != 0) {
3301 			nd->nd_cred->cr_uid = credanon->cr_uid;
3302 			nd->nd_cred->cr_gid = credanon->cr_gid;
3303 			crsetgroups(nd->nd_cred, credanon->cr_ngroups,
3304 			    credanon->cr_groups);
3305 		} else if ((nd->nd_flag & ND_GSS) == 0) {
3306 			/*
3307 			 * If using AUTH_SYS, call nfsrv_getgrpscred() to see
3308 			 * if there is a replacement credential with a group
3309 			 * list set up by "nfsuserd -manage-gids".
3310 			 * If there is no replacement, nfsrv_getgrpscred()
3311 			 * simply returns its argument.
3312 			 */
3313 			nd->nd_cred = nfsrv_getgrpscred(nd->nd_cred);
3314 		}
3315 	}
3316 
3317 out:
3318 	NFSEXITCODE2(error, nd);
3319 	return (error);
3320 }
3321 
3322 /*
3323  * Check exports.
3324  */
3325 int
3326 nfsvno_checkexp(struct mount *mp, struct sockaddr *nam, struct nfsexstuff *exp,
3327     struct ucred **credp)
3328 {
3329 	int error;
3330 
3331 	error = 0;
3332 	*credp = NULL;
3333 	MNT_ILOCK(mp);
3334 	if (mp->mnt_exjail == NULL ||
3335 	    mp->mnt_exjail->cr_prison != curthread->td_ucred->cr_prison)
3336 		error = EACCES;
3337 	MNT_IUNLOCK(mp);
3338 	if (error == 0)
3339 		error = VFS_CHECKEXP(mp, nam, &exp->nes_exflag, credp,
3340 		    &exp->nes_numsecflavor, exp->nes_secflavors);
3341 	if (error) {
3342 		if (NFSD_VNET(nfs_rootfhset)) {
3343 			exp->nes_exflag = 0;
3344 			exp->nes_numsecflavor = 0;
3345 			error = 0;
3346 		}
3347 	} else if (exp->nes_numsecflavor < 1 || exp->nes_numsecflavor >
3348 	    MAXSECFLAVORS) {
3349 		printf("nfsvno_checkexp: numsecflavors out of range\n");
3350 		exp->nes_numsecflavor = 0;
3351 		error = EACCES;
3352 	}
3353 	NFSEXITCODE(error);
3354 	return (error);
3355 }
3356 
3357 /*
3358  * Get a vnode for a file handle and export stuff.
3359  */
3360 int
3361 nfsvno_fhtovp(struct mount *mp, fhandle_t *fhp, struct sockaddr *nam,
3362     int lktype, struct vnode **vpp, struct nfsexstuff *exp,
3363     struct ucred **credp)
3364 {
3365 	int error;
3366 
3367 	*credp = NULL;
3368 	exp->nes_numsecflavor = 0;
3369 	error = VFS_FHTOVP(mp, &fhp->fh_fid, lktype, vpp);
3370 	if (error != 0)
3371 		/* Make sure the server replies ESTALE to the client. */
3372 		error = ESTALE;
3373 	if (nam && !error) {
3374 		MNT_ILOCK(mp);
3375 		if (mp->mnt_exjail == NULL ||
3376 		    mp->mnt_exjail->cr_prison != curthread->td_ucred->cr_prison)
3377 			error = EACCES;
3378 		MNT_IUNLOCK(mp);
3379 		if (error == 0)
3380 			error = VFS_CHECKEXP(mp, nam, &exp->nes_exflag, credp,
3381 			    &exp->nes_numsecflavor, exp->nes_secflavors);
3382 		if (error) {
3383 			if (NFSD_VNET(nfs_rootfhset)) {
3384 				exp->nes_exflag = 0;
3385 				exp->nes_numsecflavor = 0;
3386 				error = 0;
3387 			} else {
3388 				vput(*vpp);
3389 			}
3390 		} else if (exp->nes_numsecflavor < 1 || exp->nes_numsecflavor >
3391 		    MAXSECFLAVORS) {
3392 			printf("nfsvno_fhtovp: numsecflavors out of range\n");
3393 			exp->nes_numsecflavor = 0;
3394 			error = EACCES;
3395 			vput(*vpp);
3396 		}
3397 	}
3398 	NFSEXITCODE(error);
3399 	return (error);
3400 }
3401 
3402 /*
3403  * nfsd_fhtovp() - convert a fh to a vnode ptr
3404  * 	- look up fsid in mount list (if not found ret error)
3405  *	- get vp and export rights by calling nfsvno_fhtovp()
3406  *	- if cred->cr_uid == 0 or MNT_EXPORTANON set it to credanon
3407  *	  for AUTH_SYS
3408  *	- if mpp != NULL, return the mount point so that it can
3409  *	  be used for vn_finished_write() by the caller
3410  */
3411 void
3412 nfsd_fhtovp(struct nfsrv_descript *nd, struct nfsrvfh *nfp, int lktype,
3413     struct vnode **vpp, struct nfsexstuff *exp,
3414     struct mount **mpp, int startwrite, int nextop)
3415 {
3416 	struct mount *mp, *mpw;
3417 	struct ucred *credanon;
3418 	fhandle_t *fhp;
3419 	int error;
3420 
3421 	if (mpp != NULL)
3422 		*mpp = NULL;
3423 	*vpp = NULL;
3424 	fhp = (fhandle_t *)nfp->nfsrvfh_data;
3425 	mp = vfs_busyfs(&fhp->fh_fsid);
3426 	if (mp == NULL) {
3427 		nd->nd_repstat = ESTALE;
3428 		goto out;
3429 	}
3430 
3431 	if (startwrite) {
3432 		mpw = mp;
3433 		error = vn_start_write(NULL, &mpw, V_WAIT);
3434 		if (error != 0) {
3435 			mpw = NULL;
3436 			vfs_unbusy(mp);
3437 			nd->nd_repstat = ESTALE;
3438 			goto out;
3439 		}
3440 		if (lktype == LK_SHARED && !(MNT_SHARED_WRITES(mp)))
3441 			lktype = LK_EXCLUSIVE;
3442 	} else
3443 		mpw = NULL;
3444 
3445 	nd->nd_repstat = nfsvno_fhtovp(mp, fhp, nd->nd_nam, lktype, vpp, exp,
3446 	    &credanon);
3447 	vfs_unbusy(mp);
3448 
3449 	/*
3450 	 * For NFSv4 without a pseudo root fs, unexported file handles
3451 	 * can be returned, so that Lookup works everywhere.
3452 	 */
3453 	if (!nd->nd_repstat && exp->nes_exflag == 0 &&
3454 	    !(nd->nd_flag & ND_NFSV4)) {
3455 		vput(*vpp);
3456 		*vpp = NULL;
3457 		nd->nd_repstat = EACCES;
3458 	}
3459 
3460 	/*
3461 	 * Personally, I've never seen any point in requiring a
3462 	 * reserved port#, since only in the rare case where the
3463 	 * clients are all boxes with secure system privileges,
3464 	 * does it provide any enhanced security, but... some people
3465 	 * believe it to be useful and keep putting this code back in.
3466 	 * (There is also some "security checker" out there that
3467 	 *  complains if the nfs server doesn't enforce this.)
3468 	 * However, note the following:
3469 	 * RFC3530 (NFSv4) specifies that a reserved port# not be
3470 	 *	required.
3471 	 * RFC2623 recommends that, if a reserved port# is checked for,
3472 	 *	that there be a way to turn that off--> ifdef'd.
3473 	 */
3474 #ifdef NFS_REQRSVPORT
3475 	if (!nd->nd_repstat) {
3476 		struct sockaddr_in *saddr;
3477 		struct sockaddr_in6 *saddr6;
3478 
3479 		saddr = NFSSOCKADDR(nd->nd_nam, struct sockaddr_in *);
3480 		saddr6 = NFSSOCKADDR(nd->nd_nam, struct sockaddr_in6 *);
3481 		if (!(nd->nd_flag & ND_NFSV4) &&
3482 		    ((saddr->sin_family == AF_INET &&
3483 		      ntohs(saddr->sin_port) >= IPPORT_RESERVED) ||
3484 		     (saddr6->sin6_family == AF_INET6 &&
3485 		      ntohs(saddr6->sin6_port) >= IPPORT_RESERVED))) {
3486 			vput(*vpp);
3487 			nd->nd_repstat = (NFSERR_AUTHERR | AUTH_TOOWEAK);
3488 		}
3489 	}
3490 #endif	/* NFS_REQRSVPORT */
3491 
3492 	/*
3493 	 * Check/setup credentials.
3494 	 */
3495 	if (!nd->nd_repstat) {
3496 		nd->nd_saveduid = nd->nd_cred->cr_uid;
3497 		nd->nd_repstat = nfsd_excred(nd, exp, credanon,
3498 		    nfsrv_checkwrongsec(nd, nextop, (*vpp)->v_type));
3499 		if (nd->nd_repstat)
3500 			vput(*vpp);
3501 	}
3502 	if (credanon != NULL)
3503 		crfree(credanon);
3504 	if (nd->nd_repstat) {
3505 		vn_finished_write(mpw);
3506 		*vpp = NULL;
3507 	} else if (mpp != NULL) {
3508 		*mpp = mpw;
3509 	}
3510 
3511 out:
3512 	NFSEXITCODE2(0, nd);
3513 }
3514 
3515 /*
3516  * glue for fp.
3517  */
3518 static int
3519 fp_getfvp(struct thread *p, int fd, struct file **fpp, struct vnode **vpp)
3520 {
3521 	struct filedesc *fdp;
3522 	struct file *fp;
3523 	int error = 0;
3524 
3525 	fdp = p->td_proc->p_fd;
3526 	if (fd < 0 || fd >= fdp->fd_nfiles ||
3527 	    (fp = fdp->fd_ofiles[fd].fde_file) == NULL) {
3528 		error = EBADF;
3529 		goto out;
3530 	}
3531 	*fpp = fp;
3532 
3533 out:
3534 	NFSEXITCODE(error);
3535 	return (error);
3536 }
3537 
3538 /*
3539  * Called from nfssvc() to update the exports list. Just call
3540  * vfs_export(). This has to be done, since the v4 root fake fs isn't
3541  * in the mount list.
3542  */
3543 int
3544 nfsrv_v4rootexport(void *argp, struct ucred *cred, struct thread *p)
3545 {
3546 	struct nfsex_args *nfsexargp = (struct nfsex_args *)argp;
3547 	int error = 0;
3548 	struct nameidata nd;
3549 	fhandle_t fh;
3550 
3551 	error = vfs_export(NFSD_VNET(nfsv4root_mnt), &nfsexargp->export, false);
3552 	if ((nfsexargp->export.ex_flags & MNT_DELEXPORT) != 0)
3553 		NFSD_VNET(nfs_rootfhset) = 0;
3554 	else if (error == 0) {
3555 		if (nfsexargp->fspec == NULL) {
3556 			error = EPERM;
3557 			goto out;
3558 		}
3559 		/*
3560 		 * If fspec != NULL, this is the v4root path.
3561 		 */
3562 		NDINIT(&nd, LOOKUP, FOLLOW, UIO_USERSPACE, nfsexargp->fspec);
3563 		if ((error = namei(&nd)) != 0)
3564 			goto out;
3565 		error = nfsvno_getfh(nd.ni_vp, &fh, p);
3566 		vrele(nd.ni_vp);
3567 		if (!error) {
3568 			NFSD_VNET(nfs_rootfh).nfsrvfh_len = NFSX_MYFH;
3569 			NFSBCOPY((caddr_t)&fh,
3570 			    NFSD_VNET(nfs_rootfh).nfsrvfh_data,
3571 			    sizeof (fhandle_t));
3572 			NFSD_VNET(nfs_rootfhset) = 1;
3573 		}
3574 	}
3575 
3576 out:
3577 	NFSEXITCODE(error);
3578 	return (error);
3579 }
3580 
3581 /*
3582  * This function needs to test to see if the system is near its limit
3583  * for memory allocation via malloc() or mget() and return True iff
3584  * either of these resources are near their limit.
3585  * XXX (For now, this is just a stub.)
3586  */
3587 int nfsrv_testmalloclimit = 0;
3588 int
3589 nfsrv_mallocmget_limit(void)
3590 {
3591 	static int printmesg = 0;
3592 	static int testval = 1;
3593 
3594 	if (nfsrv_testmalloclimit && (testval++ % 1000) == 0) {
3595 		if ((printmesg++ % 100) == 0)
3596 			printf("nfsd: malloc/mget near limit\n");
3597 		return (1);
3598 	}
3599 	return (0);
3600 }
3601 
3602 /*
3603  * BSD specific initialization of a mount point.
3604  */
3605 void
3606 nfsd_mntinit(void)
3607 {
3608 
3609 	NFSD_LOCK();
3610 	if (NFSD_VNET(nfsrv_mntinited)) {
3611 		NFSD_UNLOCK();
3612 		return;
3613 	}
3614 	NFSD_VNET(nfsrv_mntinited) = true;
3615 	nfsrvd_init(0);
3616 	NFSD_UNLOCK();
3617 
3618 	NFSD_VNET(nfsv4root_mnt) = malloc(sizeof(struct mount), M_TEMP,
3619 	    M_WAITOK | M_ZERO);
3620 	NFSD_VNET(nfsv4root_mnt)->mnt_flag = (MNT_RDONLY | MNT_EXPORTED);
3621 	mtx_init(&NFSD_VNET(nfsv4root_mnt)->mnt_mtx, "nfs4mnt", NULL, MTX_DEF);
3622 	lockinit(&NFSD_VNET(nfsv4root_mnt)->mnt_explock, PVFS, "explock", 0, 0);
3623 	TAILQ_INIT(&NFSD_VNET(nfsv4root_mnt)->mnt_nvnodelist);
3624 	TAILQ_INIT(&NFSD_VNET(nfsv4root_mnt)->mnt_lazyvnodelist);
3625 	NFSD_VNET(nfsv4root_mnt)->mnt_export = NULL;
3626 	TAILQ_INIT(&NFSD_VNET(nfsv4root_opt));
3627 	TAILQ_INIT(&NFSD_VNET(nfsv4root_newopt));
3628 	NFSD_VNET(nfsv4root_mnt)->mnt_opt = &NFSD_VNET(nfsv4root_opt);
3629 	NFSD_VNET(nfsv4root_mnt)->mnt_optnew = &NFSD_VNET(nfsv4root_newopt);
3630 	NFSD_VNET(nfsv4root_mnt)->mnt_nvnodelistsize = 0;
3631 	NFSD_VNET(nfsv4root_mnt)->mnt_lazyvnodelistsize = 0;
3632 	callout_init(&NFSD_VNET(nfsd_callout), 1);
3633 
3634 	nfsrvd_initcache();
3635 	nfsd_init();
3636 }
3637 
3638 static void
3639 nfsd_timer(void *arg)
3640 {
3641 	struct vnet *vnetp;
3642 
3643 	vnetp = (struct vnet *)arg;
3644 	NFSD_CURVNET_SET_QUIET(vnetp);
3645 	nfsrv_servertimer(vnetp);
3646 	callout_reset_sbt(&NFSD_VNET(nfsd_callout), SBT_1S, SBT_1S, nfsd_timer,
3647 	    arg, 0);
3648 	NFSD_CURVNET_RESTORE();
3649 }
3650 
3651 /*
3652  * Get a vnode for a file handle, without checking exports, etc.
3653  */
3654 struct vnode *
3655 nfsvno_getvp(fhandle_t *fhp)
3656 {
3657 	struct mount *mp;
3658 	struct vnode *vp;
3659 	int error;
3660 
3661 	mp = vfs_busyfs(&fhp->fh_fsid);
3662 	if (mp == NULL)
3663 		return (NULL);
3664 	error = VFS_FHTOVP(mp, &fhp->fh_fid, LK_EXCLUSIVE, &vp);
3665 	vfs_unbusy(mp);
3666 	if (error)
3667 		return (NULL);
3668 	return (vp);
3669 }
3670 
3671 /*
3672  * Do a local VOP_ADVLOCK().
3673  */
3674 int
3675 nfsvno_advlock(struct vnode *vp, int ftype, u_int64_t first,
3676     u_int64_t end, struct thread *td)
3677 {
3678 	int error = 0;
3679 	struct flock fl;
3680 	u_int64_t tlen;
3681 
3682 	if (nfsrv_dolocallocks == 0)
3683 		goto out;
3684 	ASSERT_VOP_UNLOCKED(vp, "nfsvno_advlock: vp locked");
3685 
3686 	fl.l_whence = SEEK_SET;
3687 	fl.l_type = ftype;
3688 	fl.l_start = (off_t)first;
3689 	if (end == NFS64BITSSET) {
3690 		fl.l_len = 0;
3691 	} else {
3692 		tlen = end - first;
3693 		fl.l_len = (off_t)tlen;
3694 	}
3695 	/*
3696 	 * For FreeBSD8, the l_pid and l_sysid must be set to the same
3697 	 * values for all calls, so that all locks will be held by the
3698 	 * nfsd server. (The nfsd server handles conflicts between the
3699 	 * various clients.)
3700 	 * Since an NFSv4 lockowner is a ClientID plus an array of up to 1024
3701 	 * bytes, so it can't be put in l_sysid.
3702 	 */
3703 	if (nfsv4_sysid == 0)
3704 		nfsv4_sysid = nlm_acquire_next_sysid();
3705 	fl.l_pid = (pid_t)0;
3706 	fl.l_sysid = (int)nfsv4_sysid;
3707 
3708 	if (ftype == F_UNLCK)
3709 		error = VOP_ADVLOCK(vp, (caddr_t)td->td_proc, F_UNLCK, &fl,
3710 		    (F_POSIX | F_REMOTE));
3711 	else
3712 		error = VOP_ADVLOCK(vp, (caddr_t)td->td_proc, F_SETLK, &fl,
3713 		    (F_POSIX | F_REMOTE));
3714 
3715 out:
3716 	NFSEXITCODE(error);
3717 	return (error);
3718 }
3719 
3720 /*
3721  * Check the nfsv4 root exports.
3722  */
3723 int
3724 nfsvno_v4rootexport(struct nfsrv_descript *nd)
3725 {
3726 	struct ucred *credanon;
3727 	int error = 0, numsecflavor, secflavors[MAXSECFLAVORS], i;
3728 	uint64_t exflags;
3729 
3730 	error = vfs_stdcheckexp(NFSD_VNET(nfsv4root_mnt), nd->nd_nam, &exflags,
3731 	    &credanon, &numsecflavor, secflavors);
3732 	if (error) {
3733 		error = NFSERR_PROGUNAVAIL;
3734 		goto out;
3735 	}
3736 	if (credanon != NULL)
3737 		crfree(credanon);
3738 	for (i = 0; i < numsecflavor; i++) {
3739 		if (secflavors[i] == AUTH_SYS)
3740 			nd->nd_flag |= ND_EXAUTHSYS;
3741 		else if (secflavors[i] == RPCSEC_GSS_KRB5)
3742 			nd->nd_flag |= ND_EXGSS;
3743 		else if (secflavors[i] == RPCSEC_GSS_KRB5I)
3744 			nd->nd_flag |= ND_EXGSSINTEGRITY;
3745 		else if (secflavors[i] == RPCSEC_GSS_KRB5P)
3746 			nd->nd_flag |= ND_EXGSSPRIVACY;
3747 	}
3748 
3749 	/* And set ND_EXxx flags for TLS. */
3750 	if ((exflags & MNT_EXTLS) != 0) {
3751 		nd->nd_flag |= ND_EXTLS;
3752 		if ((exflags & MNT_EXTLSCERT) != 0)
3753 			nd->nd_flag |= ND_EXTLSCERT;
3754 		if ((exflags & MNT_EXTLSCERTUSER) != 0)
3755 			nd->nd_flag |= ND_EXTLSCERTUSER;
3756 	}
3757 
3758 out:
3759 	NFSEXITCODE(error);
3760 	return (error);
3761 }
3762 
3763 /*
3764  * Nfs server pseudo system call for the nfsd's
3765  */
3766 /*
3767  * MPSAFE
3768  */
3769 static int
3770 nfssvc_nfsd(struct thread *td, struct nfssvc_args *uap)
3771 {
3772 	struct file *fp;
3773 	struct nfsd_addsock_args sockarg;
3774 	struct nfsd_nfsd_args nfsdarg;
3775 	struct nfsd_nfsd_oargs onfsdarg;
3776 	struct nfsd_pnfsd_args pnfsdarg;
3777 	struct vnode *vp, *nvp, *curdvp;
3778 	struct pnfsdsfile *pf;
3779 	struct nfsdevice *ds, *fds;
3780 	cap_rights_t rights;
3781 	int buflen, error, ret;
3782 	char *buf, *cp, *cp2, *cp3;
3783 	char fname[PNFS_FILENAME_LEN + 1];
3784 
3785 	NFSD_CURVNET_SET(NFSD_TD_TO_VNET(td));
3786 	if (uap->flag & NFSSVC_NFSDADDSOCK) {
3787 		error = copyin(uap->argp, (caddr_t)&sockarg, sizeof (sockarg));
3788 		if (error)
3789 			goto out;
3790 		/*
3791 		 * Since we don't know what rights might be required,
3792 		 * pretend that we need them all. It is better to be too
3793 		 * careful than too reckless.
3794 		 */
3795 		error = fget(td, sockarg.sock,
3796 		    cap_rights_init_one(&rights, CAP_SOCK_SERVER), &fp);
3797 		if (error != 0)
3798 			goto out;
3799 		if (fp->f_type != DTYPE_SOCKET) {
3800 			fdrop(fp, td);
3801 			error = EPERM;
3802 			goto out;
3803 		}
3804 		error = nfsrvd_addsock(fp);
3805 		fdrop(fp, td);
3806 	} else if (uap->flag & NFSSVC_NFSDNFSD) {
3807 		if (uap->argp == NULL) {
3808 			error = EINVAL;
3809 			goto out;
3810 		}
3811 		if ((uap->flag & NFSSVC_NEWSTRUCT) == 0) {
3812 			error = copyin(uap->argp, &onfsdarg, sizeof(onfsdarg));
3813 			if (error == 0) {
3814 				nfsdarg.principal = onfsdarg.principal;
3815 				nfsdarg.minthreads = onfsdarg.minthreads;
3816 				nfsdarg.maxthreads = onfsdarg.maxthreads;
3817 				nfsdarg.version = 1;
3818 				nfsdarg.addr = NULL;
3819 				nfsdarg.addrlen = 0;
3820 				nfsdarg.dnshost = NULL;
3821 				nfsdarg.dnshostlen = 0;
3822 				nfsdarg.dspath = NULL;
3823 				nfsdarg.dspathlen = 0;
3824 				nfsdarg.mdspath = NULL;
3825 				nfsdarg.mdspathlen = 0;
3826 				nfsdarg.mirrorcnt = 1;
3827 			}
3828 		} else
3829 			error = copyin(uap->argp, &nfsdarg, sizeof(nfsdarg));
3830 		if (error)
3831 			goto out;
3832 		if (nfsdarg.addrlen > 0 && nfsdarg.addrlen < 10000 &&
3833 		    nfsdarg.dnshostlen > 0 && nfsdarg.dnshostlen < 10000 &&
3834 		    nfsdarg.dspathlen > 0 && nfsdarg.dspathlen < 10000 &&
3835 		    nfsdarg.mdspathlen > 0 && nfsdarg.mdspathlen < 10000 &&
3836 		    nfsdarg.mirrorcnt >= 1 &&
3837 		    nfsdarg.mirrorcnt <= NFSDEV_MAXMIRRORS &&
3838 		    nfsdarg.addr != NULL && nfsdarg.dnshost != NULL &&
3839 		    nfsdarg.dspath != NULL && nfsdarg.mdspath != NULL) {
3840 			NFSD_DEBUG(1, "addrlen=%d dspathlen=%d dnslen=%d"
3841 			    " mdspathlen=%d mirrorcnt=%d\n", nfsdarg.addrlen,
3842 			    nfsdarg.dspathlen, nfsdarg.dnshostlen,
3843 			    nfsdarg.mdspathlen, nfsdarg.mirrorcnt);
3844 			cp = malloc(nfsdarg.addrlen + 1, M_TEMP, M_WAITOK);
3845 			error = copyin(nfsdarg.addr, cp, nfsdarg.addrlen);
3846 			if (error != 0) {
3847 				free(cp, M_TEMP);
3848 				goto out;
3849 			}
3850 			cp[nfsdarg.addrlen] = '\0';	/* Ensure nul term. */
3851 			nfsdarg.addr = cp;
3852 			cp = malloc(nfsdarg.dnshostlen + 1, M_TEMP, M_WAITOK);
3853 			error = copyin(nfsdarg.dnshost, cp, nfsdarg.dnshostlen);
3854 			if (error != 0) {
3855 				free(nfsdarg.addr, M_TEMP);
3856 				free(cp, M_TEMP);
3857 				goto out;
3858 			}
3859 			cp[nfsdarg.dnshostlen] = '\0';	/* Ensure nul term. */
3860 			nfsdarg.dnshost = cp;
3861 			cp = malloc(nfsdarg.dspathlen + 1, M_TEMP, M_WAITOK);
3862 			error = copyin(nfsdarg.dspath, cp, nfsdarg.dspathlen);
3863 			if (error != 0) {
3864 				free(nfsdarg.addr, M_TEMP);
3865 				free(nfsdarg.dnshost, M_TEMP);
3866 				free(cp, M_TEMP);
3867 				goto out;
3868 			}
3869 			cp[nfsdarg.dspathlen] = '\0';	/* Ensure nul term. */
3870 			nfsdarg.dspath = cp;
3871 			cp = malloc(nfsdarg.mdspathlen + 1, M_TEMP, M_WAITOK);
3872 			error = copyin(nfsdarg.mdspath, cp, nfsdarg.mdspathlen);
3873 			if (error != 0) {
3874 				free(nfsdarg.addr, M_TEMP);
3875 				free(nfsdarg.dnshost, M_TEMP);
3876 				free(nfsdarg.dspath, M_TEMP);
3877 				free(cp, M_TEMP);
3878 				goto out;
3879 			}
3880 			cp[nfsdarg.mdspathlen] = '\0';	/* Ensure nul term. */
3881 			nfsdarg.mdspath = cp;
3882 		} else {
3883 			nfsdarg.addr = NULL;
3884 			nfsdarg.addrlen = 0;
3885 			nfsdarg.dnshost = NULL;
3886 			nfsdarg.dnshostlen = 0;
3887 			nfsdarg.dspath = NULL;
3888 			nfsdarg.dspathlen = 0;
3889 			nfsdarg.mdspath = NULL;
3890 			nfsdarg.mdspathlen = 0;
3891 			nfsdarg.mirrorcnt = 1;
3892 		}
3893 		nfsd_timer(NFSD_TD_TO_VNET(td));
3894 		error = nfsrvd_nfsd(td, &nfsdarg);
3895 		callout_drain(&NFSD_VNET(nfsd_callout));
3896 		free(nfsdarg.addr, M_TEMP);
3897 		free(nfsdarg.dnshost, M_TEMP);
3898 		free(nfsdarg.dspath, M_TEMP);
3899 		free(nfsdarg.mdspath, M_TEMP);
3900 	} else if (uap->flag & NFSSVC_PNFSDS) {
3901 		error = copyin(uap->argp, &pnfsdarg, sizeof(pnfsdarg));
3902 		if (error == 0 && (pnfsdarg.op == PNFSDOP_DELDSSERVER ||
3903 		    pnfsdarg.op == PNFSDOP_FORCEDELDS)) {
3904 			cp = malloc(PATH_MAX + 1, M_TEMP, M_WAITOK);
3905 			error = copyinstr(pnfsdarg.dspath, cp, PATH_MAX + 1,
3906 			    NULL);
3907 			if (error == 0)
3908 				error = nfsrv_deldsserver(pnfsdarg.op, cp, td);
3909 			free(cp, M_TEMP);
3910 		} else if (error == 0 && pnfsdarg.op == PNFSDOP_COPYMR) {
3911 			cp = malloc(PATH_MAX + 1, M_TEMP, M_WAITOK);
3912 			buflen = sizeof(*pf) * NFSDEV_MAXMIRRORS;
3913 			buf = malloc(buflen, M_TEMP, M_WAITOK);
3914 			error = copyinstr(pnfsdarg.mdspath, cp, PATH_MAX + 1,
3915 			    NULL);
3916 			NFSD_DEBUG(4, "pnfsdcopymr cp mdspath=%d\n", error);
3917 			if (error == 0 && pnfsdarg.dspath != NULL) {
3918 				cp2 = malloc(PATH_MAX + 1, M_TEMP, M_WAITOK);
3919 				error = copyinstr(pnfsdarg.dspath, cp2,
3920 				    PATH_MAX + 1, NULL);
3921 				NFSD_DEBUG(4, "pnfsdcopymr cp dspath=%d\n",
3922 				    error);
3923 			} else
3924 				cp2 = NULL;
3925 			if (error == 0 && pnfsdarg.curdspath != NULL) {
3926 				cp3 = malloc(PATH_MAX + 1, M_TEMP, M_WAITOK);
3927 				error = copyinstr(pnfsdarg.curdspath, cp3,
3928 				    PATH_MAX + 1, NULL);
3929 				NFSD_DEBUG(4, "pnfsdcopymr cp curdspath=%d\n",
3930 				    error);
3931 			} else
3932 				cp3 = NULL;
3933 			curdvp = NULL;
3934 			fds = NULL;
3935 			if (error == 0)
3936 				error = nfsrv_mdscopymr(cp, cp2, cp3, buf,
3937 				    &buflen, fname, td, &vp, &nvp, &pf, &ds,
3938 				    &fds);
3939 			NFSD_DEBUG(4, "nfsrv_mdscopymr=%d\n", error);
3940 			if (error == 0) {
3941 				if (pf->dsf_dir >= nfsrv_dsdirsize) {
3942 					printf("copymr: dsdir out of range\n");
3943 					pf->dsf_dir = 0;
3944 				}
3945 				NFSD_DEBUG(4, "copymr: buflen=%d\n", buflen);
3946 				error = nfsrv_copymr(vp, nvp,
3947 				    ds->nfsdev_dsdir[pf->dsf_dir], ds, pf,
3948 				    (struct pnfsdsfile *)buf,
3949 				    buflen / sizeof(*pf), td->td_ucred, td);
3950 				vput(vp);
3951 				vput(nvp);
3952 				if (fds != NULL && error == 0) {
3953 					curdvp = fds->nfsdev_dsdir[pf->dsf_dir];
3954 					ret = vn_lock(curdvp, LK_EXCLUSIVE);
3955 					if (ret == 0) {
3956 						nfsrv_dsremove(curdvp, fname,
3957 						    td->td_ucred, td);
3958 						NFSVOPUNLOCK(curdvp);
3959 					}
3960 				}
3961 				NFSD_DEBUG(4, "nfsrv_copymr=%d\n", error);
3962 			}
3963 			free(cp, M_TEMP);
3964 			free(cp2, M_TEMP);
3965 			free(cp3, M_TEMP);
3966 			free(buf, M_TEMP);
3967 		}
3968 	} else {
3969 		error = nfssvc_srvcall(td, uap, td->td_ucred);
3970 	}
3971 
3972 out:
3973 	NFSD_CURVNET_RESTORE();
3974 	NFSEXITCODE(error);
3975 	return (error);
3976 }
3977 
3978 static int
3979 nfssvc_srvcall(struct thread *p, struct nfssvc_args *uap, struct ucred *cred)
3980 {
3981 	struct nfsex_args export;
3982 	struct nfsex_oldargs oexp;
3983 	struct file *fp = NULL;
3984 	int stablefd, i, len;
3985 	struct nfsd_clid adminrevoke;
3986 	struct nfsd_dumplist dumplist;
3987 	struct nfsd_dumpclients *dumpclients;
3988 	struct nfsd_dumplocklist dumplocklist;
3989 	struct nfsd_dumplocks *dumplocks;
3990 	struct nameidata nd;
3991 	vnode_t vp;
3992 	int error = EINVAL, igotlock;
3993 	struct proc *procp;
3994 	gid_t *grps;
3995 
3996 	if (uap->flag & NFSSVC_PUBLICFH) {
3997 		NFSBZERO((caddr_t)&nfs_pubfh.nfsrvfh_data,
3998 		    sizeof (fhandle_t));
3999 		error = copyin(uap->argp,
4000 		    &nfs_pubfh.nfsrvfh_data, sizeof (fhandle_t));
4001 		if (!error)
4002 			nfs_pubfhset = 1;
4003 	} else if ((uap->flag & (NFSSVC_V4ROOTEXPORT | NFSSVC_NEWSTRUCT)) ==
4004 	    (NFSSVC_V4ROOTEXPORT | NFSSVC_NEWSTRUCT)) {
4005 		error = copyin(uap->argp,(caddr_t)&export,
4006 		    sizeof (struct nfsex_args));
4007 		if (!error) {
4008 			grps = NULL;
4009 			if (export.export.ex_ngroups > NGROUPS_MAX ||
4010 			    export.export.ex_ngroups < 0)
4011 				error = EINVAL;
4012 			else if (export.export.ex_ngroups > 0) {
4013 				grps = malloc(export.export.ex_ngroups *
4014 				    sizeof(gid_t), M_TEMP, M_WAITOK);
4015 				error = copyin(export.export.ex_groups, grps,
4016 				    export.export.ex_ngroups * sizeof(gid_t));
4017 				export.export.ex_groups = grps;
4018 			} else
4019 				export.export.ex_groups = NULL;
4020 			if (!error)
4021 				error = nfsrv_v4rootexport(&export, cred, p);
4022 			free(grps, M_TEMP);
4023 		}
4024 	} else if ((uap->flag & (NFSSVC_V4ROOTEXPORT | NFSSVC_NEWSTRUCT)) ==
4025 	    NFSSVC_V4ROOTEXPORT) {
4026 		error = copyin(uap->argp,(caddr_t)&oexp,
4027 		    sizeof (struct nfsex_oldargs));
4028 		if (!error) {
4029 			memset(&export.export, 0, sizeof(export.export));
4030 			export.export.ex_flags = (uint64_t)oexp.export.ex_flags;
4031 			export.export.ex_root = oexp.export.ex_root;
4032 			export.export.ex_uid = oexp.export.ex_anon.cr_uid;
4033 			export.export.ex_ngroups =
4034 			    oexp.export.ex_anon.cr_ngroups;
4035 			export.export.ex_groups = NULL;
4036 			if (export.export.ex_ngroups > XU_NGROUPS ||
4037 			    export.export.ex_ngroups < 0)
4038 				error = EINVAL;
4039 			else if (export.export.ex_ngroups > 0) {
4040 				export.export.ex_groups = malloc(
4041 				    export.export.ex_ngroups * sizeof(gid_t),
4042 				    M_TEMP, M_WAITOK);
4043 				for (i = 0; i < export.export.ex_ngroups; i++)
4044 					export.export.ex_groups[i] =
4045 					    oexp.export.ex_anon.cr_groups[i];
4046 			}
4047 			export.export.ex_addr = oexp.export.ex_addr;
4048 			export.export.ex_addrlen = oexp.export.ex_addrlen;
4049 			export.export.ex_mask = oexp.export.ex_mask;
4050 			export.export.ex_masklen = oexp.export.ex_masklen;
4051 			export.export.ex_indexfile = oexp.export.ex_indexfile;
4052 			export.export.ex_numsecflavors =
4053 			    oexp.export.ex_numsecflavors;
4054 			if (export.export.ex_numsecflavors >= MAXSECFLAVORS ||
4055 			    export.export.ex_numsecflavors < 0)
4056 				error = EINVAL;
4057 			else {
4058 				for (i = 0; i < export.export.ex_numsecflavors;
4059 				    i++)
4060 					export.export.ex_secflavors[i] =
4061 					    oexp.export.ex_secflavors[i];
4062 			}
4063 			export.fspec = oexp.fspec;
4064 			if (error == 0)
4065 				error = nfsrv_v4rootexport(&export, cred, p);
4066 			free(export.export.ex_groups, M_TEMP);
4067 		}
4068 	} else if (uap->flag & NFSSVC_NOPUBLICFH) {
4069 		nfs_pubfhset = 0;
4070 		error = 0;
4071 	} else if (uap->flag & NFSSVC_STABLERESTART) {
4072 		error = copyin(uap->argp, (caddr_t)&stablefd,
4073 		    sizeof (int));
4074 		if (!error)
4075 			error = fp_getfvp(p, stablefd, &fp, &vp);
4076 		if (!error && (NFSFPFLAG(fp) & (FREAD | FWRITE)) != (FREAD | FWRITE))
4077 			error = EBADF;
4078 		if (!error && NFSD_VNET(nfsrv_numnfsd) != 0)
4079 			error = ENXIO;
4080 		if (!error) {
4081 			NFSD_VNET(nfsrv_stablefirst).nsf_fp = fp;
4082 			nfsrv_setupstable(p);
4083 		}
4084 	} else if (uap->flag & NFSSVC_ADMINREVOKE) {
4085 		error = copyin(uap->argp, (caddr_t)&adminrevoke,
4086 		    sizeof (struct nfsd_clid));
4087 		if (!error)
4088 			error = nfsrv_adminrevoke(&adminrevoke, p);
4089 	} else if (uap->flag & NFSSVC_DUMPCLIENTS) {
4090 		error = copyin(uap->argp, (caddr_t)&dumplist,
4091 		    sizeof (struct nfsd_dumplist));
4092 		if (!error && (dumplist.ndl_size < 1 ||
4093 			dumplist.ndl_size > NFSRV_MAXDUMPLIST))
4094 			error = EPERM;
4095 		if (!error) {
4096 		    len = sizeof (struct nfsd_dumpclients) * dumplist.ndl_size;
4097 		    dumpclients = malloc(len, M_TEMP, M_WAITOK | M_ZERO);
4098 		    nfsrv_dumpclients(dumpclients, dumplist.ndl_size);
4099 		    error = copyout(dumpclients, dumplist.ndl_list, len);
4100 		    free(dumpclients, M_TEMP);
4101 		}
4102 	} else if (uap->flag & NFSSVC_DUMPLOCKS) {
4103 		error = copyin(uap->argp, (caddr_t)&dumplocklist,
4104 		    sizeof (struct nfsd_dumplocklist));
4105 		if (!error && (dumplocklist.ndllck_size < 1 ||
4106 			dumplocklist.ndllck_size > NFSRV_MAXDUMPLIST))
4107 			error = EPERM;
4108 		if (!error)
4109 			error = nfsrv_lookupfilename(&nd,
4110 				dumplocklist.ndllck_fname, p);
4111 		if (!error) {
4112 			len = sizeof (struct nfsd_dumplocks) *
4113 				dumplocklist.ndllck_size;
4114 			dumplocks = malloc(len, M_TEMP, M_WAITOK | M_ZERO);
4115 			nfsrv_dumplocks(nd.ni_vp, dumplocks,
4116 			    dumplocklist.ndllck_size, p);
4117 			vput(nd.ni_vp);
4118 			error = copyout(dumplocks, dumplocklist.ndllck_list,
4119 			    len);
4120 			free(dumplocks, M_TEMP);
4121 		}
4122 	} else if (uap->flag & NFSSVC_BACKUPSTABLE) {
4123 		procp = p->td_proc;
4124 		PROC_LOCK(procp);
4125 		nfsd_master_pid = procp->p_pid;
4126 		bcopy(procp->p_comm, nfsd_master_comm, MAXCOMLEN + 1);
4127 		nfsd_master_start = procp->p_stats->p_start;
4128 		NFSD_VNET(nfsd_master_proc) = procp;
4129 		PROC_UNLOCK(procp);
4130 	} else if ((uap->flag & NFSSVC_SUSPENDNFSD) != 0) {
4131 		NFSLOCKV4ROOTMUTEX();
4132 		if (!NFSD_VNET(nfsrv_suspend_nfsd)) {
4133 			/* Lock out all nfsd threads */
4134 			do {
4135 				igotlock = nfsv4_lock(
4136 				    &NFSD_VNET(nfsd_suspend_lock), 1, NULL,
4137 				    NFSV4ROOTLOCKMUTEXPTR, NULL);
4138 			} while (igotlock == 0 &&
4139 			    !NFSD_VNET(nfsrv_suspend_nfsd));
4140 			NFSD_VNET(nfsrv_suspend_nfsd) = true;
4141 		}
4142 		NFSUNLOCKV4ROOTMUTEX();
4143 		error = 0;
4144 	} else if ((uap->flag & NFSSVC_RESUMENFSD) != 0) {
4145 		NFSLOCKV4ROOTMUTEX();
4146 		if (NFSD_VNET(nfsrv_suspend_nfsd)) {
4147 			nfsv4_unlock(&NFSD_VNET(nfsd_suspend_lock), 0);
4148 			NFSD_VNET(nfsrv_suspend_nfsd) = false;
4149 		}
4150 		NFSUNLOCKV4ROOTMUTEX();
4151 		error = 0;
4152 	}
4153 
4154 	NFSEXITCODE(error);
4155 	return (error);
4156 }
4157 
4158 /*
4159  * Check exports.
4160  * Returns 0 if ok, 1 otherwise.
4161  */
4162 int
4163 nfsvno_testexp(struct nfsrv_descript *nd, struct nfsexstuff *exp)
4164 {
4165 	int i;
4166 
4167 	if ((NFSVNO_EXTLS(exp) && (nd->nd_flag & ND_TLS) == 0) ||
4168 	    (NFSVNO_EXTLSCERT(exp) &&
4169 	     (nd->nd_flag & ND_TLSCERT) == 0) ||
4170 	    (NFSVNO_EXTLSCERTUSER(exp) &&
4171 	     (nd->nd_flag & ND_TLSCERTUSER) == 0)) {
4172 		if ((nd->nd_flag & ND_NFSV4) != 0)
4173 			return (NFSERR_WRONGSEC);
4174 #ifdef notnow
4175 		/* There is currently no auth_stat for this. */
4176 		else if ((nd->nd_flag & ND_TLS) == 0)
4177 			return (NFSERR_AUTHERR | AUTH_NEEDS_TLS);
4178 		else
4179 			return (NFSERR_AUTHERR | AUTH_NEEDS_TLS_MUTUAL_HOST);
4180 #endif
4181 		else
4182 			return (NFSERR_AUTHERR | AUTH_TOOWEAK);
4183 	}
4184 
4185 	/*
4186 	 * RFC2623 suggests that the NFSv3 Fsinfo RPC be allowed to use
4187 	 * AUTH_NONE or AUTH_SYS for file systems requiring RPCSEC_GSS.
4188 	 */
4189 	if ((nd->nd_flag & ND_NFSV3) != 0 && nd->nd_procnum == NFSPROC_FSINFO)
4190 		return (0);
4191 
4192 	/*
4193 	 * This seems odd, but allow the case where the security flavor
4194 	 * list is empty. This happens when NFSv4 is traversing non-exported
4195 	 * file systems. Exported file systems should always have a non-empty
4196 	 * security flavor list.
4197 	 */
4198 	if (exp->nes_numsecflavor == 0)
4199 		return (0);
4200 
4201 	for (i = 0; i < exp->nes_numsecflavor; i++) {
4202 		/*
4203 		 * The tests for privacy and integrity must be first,
4204 		 * since ND_GSS is set for everything but AUTH_SYS.
4205 		 */
4206 		if (exp->nes_secflavors[i] == RPCSEC_GSS_KRB5P &&
4207 		    (nd->nd_flag & ND_GSSPRIVACY))
4208 			return (0);
4209 		if (exp->nes_secflavors[i] == RPCSEC_GSS_KRB5I &&
4210 		    (nd->nd_flag & ND_GSSINTEGRITY))
4211 			return (0);
4212 		if (exp->nes_secflavors[i] == RPCSEC_GSS_KRB5 &&
4213 		    (nd->nd_flag & ND_GSS))
4214 			return (0);
4215 		if (exp->nes_secflavors[i] == AUTH_SYS &&
4216 		    (nd->nd_flag & ND_GSS) == 0)
4217 			return (0);
4218 	}
4219 	if ((nd->nd_flag & ND_NFSV4) != 0)
4220 		return (NFSERR_WRONGSEC);
4221 	return (NFSERR_AUTHERR | AUTH_TOOWEAK);
4222 }
4223 
4224 /*
4225  * Calculate a hash value for the fid in a file handle.
4226  */
4227 uint32_t
4228 nfsrv_hashfh(fhandle_t *fhp)
4229 {
4230 	uint32_t hashval;
4231 
4232 	hashval = hash32_buf(&fhp->fh_fid, sizeof(struct fid), 0);
4233 	return (hashval);
4234 }
4235 
4236 /*
4237  * Calculate a hash value for the sessionid.
4238  */
4239 uint32_t
4240 nfsrv_hashsessionid(uint8_t *sessionid)
4241 {
4242 	uint32_t hashval;
4243 
4244 	hashval = hash32_buf(sessionid, NFSX_V4SESSIONID, 0);
4245 	return (hashval);
4246 }
4247 
4248 /*
4249  * Signal the userland master nfsd to backup the stable restart file.
4250  */
4251 void
4252 nfsrv_backupstable(void)
4253 {
4254 	struct proc *procp;
4255 
4256 	if (NFSD_VNET(nfsd_master_proc) != NULL) {
4257 		procp = pfind(nfsd_master_pid);
4258 		/* Try to make sure it is the correct process. */
4259 		if (procp == NFSD_VNET(nfsd_master_proc) &&
4260 		    procp->p_stats->p_start.tv_sec ==
4261 		    nfsd_master_start.tv_sec &&
4262 		    procp->p_stats->p_start.tv_usec ==
4263 		    nfsd_master_start.tv_usec &&
4264 		    strcmp(procp->p_comm, nfsd_master_comm) == 0)
4265 			kern_psignal(procp, SIGUSR2);
4266 		else
4267 			NFSD_VNET(nfsd_master_proc) = NULL;
4268 
4269 		if (procp != NULL)
4270 			PROC_UNLOCK(procp);
4271 	}
4272 }
4273 
4274 /*
4275  * Create a DS data file for nfsrv_pnfscreate(). Called for each mirror.
4276  * The arguments are in a structure, so that they can be passed through
4277  * taskqueue for a kernel process to execute this function.
4278  */
4279 struct nfsrvdscreate {
4280 	int			done;
4281 	int			inprog;
4282 	struct task		tsk;
4283 	struct ucred		*tcred;
4284 	struct vnode		*dvp;
4285 	NFSPROC_T		*p;
4286 	struct pnfsdsfile	*pf;
4287 	int			err;
4288 	fhandle_t		fh;
4289 	struct vattr		va;
4290 	struct vattr		createva;
4291 };
4292 
4293 int
4294 nfsrv_dscreate(struct vnode *dvp, struct vattr *vap, struct vattr *nvap,
4295     fhandle_t *fhp, struct pnfsdsfile *pf, struct pnfsdsattr *dsa,
4296     char *fnamep, struct ucred *tcred, NFSPROC_T *p, struct vnode **nvpp)
4297 {
4298 	struct vnode *nvp;
4299 	struct nameidata named;
4300 	struct vattr va;
4301 	char *bufp;
4302 	u_long *hashp;
4303 	struct nfsnode *np;
4304 	struct nfsmount *nmp;
4305 	int error;
4306 
4307 	NFSNAMEICNDSET(&named.ni_cnd, tcred, CREATE,
4308 	    LOCKPARENT | LOCKLEAF | NOCACHE);
4309 	nfsvno_setpathbuf(&named, &bufp, &hashp);
4310 	named.ni_cnd.cn_lkflags = LK_EXCLUSIVE;
4311 	named.ni_cnd.cn_nameptr = bufp;
4312 	if (fnamep != NULL) {
4313 		strlcpy(bufp, fnamep, PNFS_FILENAME_LEN + 1);
4314 		named.ni_cnd.cn_namelen = strlen(bufp);
4315 	} else
4316 		named.ni_cnd.cn_namelen = nfsrv_putfhname(fhp, bufp);
4317 	NFSD_DEBUG(4, "nfsrv_dscreate: dvp=%p fname=%s\n", dvp, bufp);
4318 
4319 	/* Create the date file in the DS mount. */
4320 	error = NFSVOPLOCK(dvp, LK_EXCLUSIVE);
4321 	if (error == 0) {
4322 		error = VOP_CREATE(dvp, &nvp, &named.ni_cnd, vap);
4323 		vref(dvp);
4324 		VOP_VPUT_PAIR(dvp, error == 0 ? &nvp : NULL, false);
4325 		if (error == 0) {
4326 			/* Set the ownership of the file. */
4327 			error = VOP_SETATTR(nvp, nvap, tcred);
4328 			NFSD_DEBUG(4, "nfsrv_dscreate:"
4329 			    " setattr-uid=%d\n", error);
4330 			if (error != 0)
4331 				vput(nvp);
4332 		}
4333 		if (error != 0)
4334 			printf("pNFS: pnfscreate failed=%d\n", error);
4335 	} else
4336 		printf("pNFS: pnfscreate vnlock=%d\n", error);
4337 	if (error == 0) {
4338 		np = VTONFS(nvp);
4339 		nmp = VFSTONFS(nvp->v_mount);
4340 		if (strcmp(nvp->v_mount->mnt_vfc->vfc_name, "nfs")
4341 		    != 0 || nmp->nm_nam->sa_len > sizeof(
4342 		    struct sockaddr_in6) ||
4343 		    np->n_fhp->nfh_len != NFSX_MYFH) {
4344 			printf("Bad DS file: fstype=%s salen=%d"
4345 			    " fhlen=%d\n",
4346 			    nvp->v_mount->mnt_vfc->vfc_name,
4347 			    nmp->nm_nam->sa_len, np->n_fhp->nfh_len);
4348 			error = ENOENT;
4349 		}
4350 
4351 		/* Set extattrs for the DS on the MDS file. */
4352 		if (error == 0) {
4353 			if (dsa != NULL) {
4354 				error = VOP_GETATTR(nvp, &va, tcred);
4355 				if (error == 0) {
4356 					dsa->dsa_filerev = va.va_filerev;
4357 					dsa->dsa_size = va.va_size;
4358 					dsa->dsa_atime = va.va_atime;
4359 					dsa->dsa_mtime = va.va_mtime;
4360 					dsa->dsa_bytes = va.va_bytes;
4361 				}
4362 			}
4363 			if (error == 0) {
4364 				NFSBCOPY(np->n_fhp->nfh_fh, &pf->dsf_fh,
4365 				    NFSX_MYFH);
4366 				NFSBCOPY(nmp->nm_nam, &pf->dsf_sin,
4367 				    nmp->nm_nam->sa_len);
4368 				NFSBCOPY(named.ni_cnd.cn_nameptr,
4369 				    pf->dsf_filename,
4370 				    sizeof(pf->dsf_filename));
4371 			}
4372 		} else
4373 			printf("pNFS: pnfscreate can't get DS"
4374 			    " attr=%d\n", error);
4375 		if (nvpp != NULL && error == 0)
4376 			*nvpp = nvp;
4377 		else
4378 			vput(nvp);
4379 	}
4380 	nfsvno_relpathbuf(&named);
4381 	return (error);
4382 }
4383 
4384 /*
4385  * Start up the thread that will execute nfsrv_dscreate().
4386  */
4387 static void
4388 start_dscreate(void *arg, int pending)
4389 {
4390 	struct nfsrvdscreate *dsc;
4391 
4392 	dsc = (struct nfsrvdscreate *)arg;
4393 	dsc->err = nfsrv_dscreate(dsc->dvp, &dsc->createva, &dsc->va, &dsc->fh,
4394 	    dsc->pf, NULL, NULL, dsc->tcred, dsc->p, NULL);
4395 	dsc->done = 1;
4396 	NFSD_DEBUG(4, "start_dscreate: err=%d\n", dsc->err);
4397 }
4398 
4399 /*
4400  * Create a pNFS data file on the Data Server(s).
4401  */
4402 static void
4403 nfsrv_pnfscreate(struct vnode *vp, struct vattr *vap, struct ucred *cred,
4404     NFSPROC_T *p)
4405 {
4406 	struct nfsrvdscreate *dsc, *tdsc = NULL;
4407 	struct nfsdevice *ds, *tds, *fds;
4408 	struct mount *mp;
4409 	struct pnfsdsfile *pf, *tpf;
4410 	struct pnfsdsattr dsattr;
4411 	struct vattr va;
4412 	struct vnode *dvp[NFSDEV_MAXMIRRORS];
4413 	struct nfsmount *nmp;
4414 	fhandle_t fh;
4415 	uid_t vauid;
4416 	gid_t vagid;
4417 	u_short vamode;
4418 	struct ucred *tcred;
4419 	int dsdir[NFSDEV_MAXMIRRORS], error, i, mirrorcnt, ret;
4420 	int failpos, timo;
4421 
4422 	/* Get a DS server directory in a round-robin order. */
4423 	mirrorcnt = 1;
4424 	mp = vp->v_mount;
4425 	ds = fds = NULL;
4426 	NFSDDSLOCK();
4427 	/*
4428 	 * Search for the first entry that handles this MDS fs, but use the
4429 	 * first entry for all MDS fs's otherwise.
4430 	 */
4431 	TAILQ_FOREACH(tds, &nfsrv_devidhead, nfsdev_list) {
4432 		if (tds->nfsdev_nmp != NULL) {
4433 			if (tds->nfsdev_mdsisset == 0 && ds == NULL)
4434 				ds = tds;
4435 			else if (tds->nfsdev_mdsisset != 0 && fsidcmp(
4436 			    &mp->mnt_stat.f_fsid, &tds->nfsdev_mdsfsid) == 0) {
4437 				ds = fds = tds;
4438 				break;
4439 			}
4440 		}
4441 	}
4442 	if (ds == NULL) {
4443 		NFSDDSUNLOCK();
4444 		NFSD_DEBUG(4, "nfsrv_pnfscreate: no srv\n");
4445 		return;
4446 	}
4447 	i = dsdir[0] = ds->nfsdev_nextdir;
4448 	ds->nfsdev_nextdir = (ds->nfsdev_nextdir + 1) % nfsrv_dsdirsize;
4449 	dvp[0] = ds->nfsdev_dsdir[i];
4450 	tds = TAILQ_NEXT(ds, nfsdev_list);
4451 	if (nfsrv_maxpnfsmirror > 1 && tds != NULL) {
4452 		TAILQ_FOREACH_FROM(tds, &nfsrv_devidhead, nfsdev_list) {
4453 			if (tds->nfsdev_nmp != NULL &&
4454 			    ((tds->nfsdev_mdsisset == 0 && fds == NULL) ||
4455 			     (tds->nfsdev_mdsisset != 0 && fds != NULL &&
4456 			      fsidcmp(&mp->mnt_stat.f_fsid,
4457 			      &tds->nfsdev_mdsfsid) == 0))) {
4458 				dsdir[mirrorcnt] = i;
4459 				dvp[mirrorcnt] = tds->nfsdev_dsdir[i];
4460 				mirrorcnt++;
4461 				if (mirrorcnt >= nfsrv_maxpnfsmirror)
4462 					break;
4463 			}
4464 		}
4465 	}
4466 	/* Put at end of list to implement round-robin usage. */
4467 	TAILQ_REMOVE(&nfsrv_devidhead, ds, nfsdev_list);
4468 	TAILQ_INSERT_TAIL(&nfsrv_devidhead, ds, nfsdev_list);
4469 	NFSDDSUNLOCK();
4470 	dsc = NULL;
4471 	if (mirrorcnt > 1)
4472 		tdsc = dsc = malloc(sizeof(*dsc) * (mirrorcnt - 1), M_TEMP,
4473 		    M_WAITOK | M_ZERO);
4474 	tpf = pf = malloc(sizeof(*pf) * nfsrv_maxpnfsmirror, M_TEMP, M_WAITOK |
4475 	    M_ZERO);
4476 
4477 	error = nfsvno_getfh(vp, &fh, p);
4478 	if (error == 0)
4479 		error = VOP_GETATTR(vp, &va, cred);
4480 	if (error == 0) {
4481 		/* Set the attributes for "vp" to Setattr the DS vp. */
4482 		vauid = va.va_uid;
4483 		vagid = va.va_gid;
4484 		vamode = va.va_mode;
4485 		VATTR_NULL(&va);
4486 		va.va_uid = vauid;
4487 		va.va_gid = vagid;
4488 		va.va_mode = vamode;
4489 		va.va_size = 0;
4490 	} else
4491 		printf("pNFS: pnfscreate getfh+attr=%d\n", error);
4492 
4493 	NFSD_DEBUG(4, "nfsrv_pnfscreate: cruid=%d crgid=%d\n", cred->cr_uid,
4494 	    cred->cr_gid);
4495 	/* Make data file name based on FH. */
4496 	tcred = newnfs_getcred();
4497 
4498 	/*
4499 	 * Create the file on each DS mirror, using kernel process(es) for the
4500 	 * additional mirrors.
4501 	 */
4502 	failpos = -1;
4503 	for (i = 0; i < mirrorcnt - 1 && error == 0; i++, tpf++, tdsc++) {
4504 		tpf->dsf_dir = dsdir[i];
4505 		tdsc->tcred = tcred;
4506 		tdsc->p = p;
4507 		tdsc->pf = tpf;
4508 		tdsc->createva = *vap;
4509 		NFSBCOPY(&fh, &tdsc->fh, sizeof(fh));
4510 		tdsc->va = va;
4511 		tdsc->dvp = dvp[i];
4512 		tdsc->done = 0;
4513 		tdsc->inprog = 0;
4514 		tdsc->err = 0;
4515 		ret = EIO;
4516 		if (nfs_pnfsiothreads != 0) {
4517 			ret = nfs_pnfsio(start_dscreate, tdsc);
4518 			NFSD_DEBUG(4, "nfsrv_pnfscreate: nfs_pnfsio=%d\n", ret);
4519 		}
4520 		if (ret != 0) {
4521 			ret = nfsrv_dscreate(dvp[i], vap, &va, &fh, tpf, NULL,
4522 			    NULL, tcred, p, NULL);
4523 			if (ret != 0) {
4524 				KASSERT(error == 0, ("nfsrv_dscreate err=%d",
4525 				    error));
4526 				if (failpos == -1 && nfsds_failerr(ret))
4527 					failpos = i;
4528 				else
4529 					error = ret;
4530 			}
4531 		}
4532 	}
4533 	if (error == 0) {
4534 		tpf->dsf_dir = dsdir[mirrorcnt - 1];
4535 		error = nfsrv_dscreate(dvp[mirrorcnt - 1], vap, &va, &fh, tpf,
4536 		    &dsattr, NULL, tcred, p, NULL);
4537 		if (failpos == -1 && mirrorcnt > 1 && nfsds_failerr(error)) {
4538 			failpos = mirrorcnt - 1;
4539 			error = 0;
4540 		}
4541 	}
4542 	timo = hz / 50;		/* Wait for 20msec. */
4543 	if (timo < 1)
4544 		timo = 1;
4545 	/* Wait for kernel task(s) to complete. */
4546 	for (tdsc = dsc, i = 0; i < mirrorcnt - 1; i++, tdsc++) {
4547 		while (tdsc->inprog != 0 && tdsc->done == 0)
4548 			tsleep(&tdsc->tsk, PVFS, "srvdcr", timo);
4549 		if (tdsc->err != 0) {
4550 			if (failpos == -1 && nfsds_failerr(tdsc->err))
4551 				failpos = i;
4552 			else if (error == 0)
4553 				error = tdsc->err;
4554 		}
4555 	}
4556 
4557 	/*
4558 	 * If failpos has been set, that mirror has failed, so it needs
4559 	 * to be disabled.
4560 	 */
4561 	if (failpos >= 0) {
4562 		nmp = VFSTONFS(dvp[failpos]->v_mount);
4563 		NFSLOCKMNT(nmp);
4564 		if ((nmp->nm_privflag & (NFSMNTP_FORCEDISM |
4565 		     NFSMNTP_CANCELRPCS)) == 0) {
4566 			nmp->nm_privflag |= NFSMNTP_CANCELRPCS;
4567 			NFSUNLOCKMNT(nmp);
4568 			ds = nfsrv_deldsnmp(PNFSDOP_DELDSSERVER, nmp, p);
4569 			NFSD_DEBUG(4, "dscreatfail fail=%d ds=%p\n", failpos,
4570 			    ds);
4571 			if (ds != NULL)
4572 				nfsrv_killrpcs(nmp);
4573 			NFSLOCKMNT(nmp);
4574 			nmp->nm_privflag &= ~NFSMNTP_CANCELRPCS;
4575 			wakeup(nmp);
4576 		}
4577 		NFSUNLOCKMNT(nmp);
4578 	}
4579 
4580 	NFSFREECRED(tcred);
4581 	if (error == 0) {
4582 		ASSERT_VOP_ELOCKED(vp, "nfsrv_pnfscreate vp");
4583 
4584 		NFSD_DEBUG(4, "nfsrv_pnfscreate: mirrorcnt=%d maxmirror=%d\n",
4585 		    mirrorcnt, nfsrv_maxpnfsmirror);
4586 		/*
4587 		 * For all mirrors that couldn't be created, fill in the
4588 		 * *pf structure, but with an IP address == 0.0.0.0.
4589 		 */
4590 		tpf = pf + mirrorcnt;
4591 		for (i = mirrorcnt; i < nfsrv_maxpnfsmirror; i++, tpf++) {
4592 			*tpf = *pf;
4593 			tpf->dsf_sin.sin_family = AF_INET;
4594 			tpf->dsf_sin.sin_len = sizeof(struct sockaddr_in);
4595 			tpf->dsf_sin.sin_addr.s_addr = 0;
4596 			tpf->dsf_sin.sin_port = 0;
4597 		}
4598 
4599 		error = vn_extattr_set(vp, IO_NODELOCKED,
4600 		    EXTATTR_NAMESPACE_SYSTEM, "pnfsd.dsfile",
4601 		    sizeof(*pf) * nfsrv_maxpnfsmirror, (char *)pf, p);
4602 		if (error == 0)
4603 			error = vn_extattr_set(vp, IO_NODELOCKED,
4604 			    EXTATTR_NAMESPACE_SYSTEM, "pnfsd.dsattr",
4605 			    sizeof(dsattr), (char *)&dsattr, p);
4606 		if (error != 0)
4607 			printf("pNFS: pnfscreate setextattr=%d\n",
4608 			    error);
4609 	} else
4610 		printf("pNFS: pnfscreate=%d\n", error);
4611 	free(pf, M_TEMP);
4612 	free(dsc, M_TEMP);
4613 }
4614 
4615 /*
4616  * Get the information needed to remove the pNFS Data Server file from the
4617  * Metadata file.  Upon success, ddvp is set non-NULL to the locked
4618  * DS directory vnode.  The caller must unlock *ddvp when done with it.
4619  */
4620 static void
4621 nfsrv_pnfsremovesetup(struct vnode *vp, NFSPROC_T *p, struct vnode **dvpp,
4622     int *mirrorcntp, char *fname, fhandle_t *fhp)
4623 {
4624 	struct vattr va;
4625 	struct ucred *tcred;
4626 	char *buf;
4627 	int buflen, error;
4628 
4629 	dvpp[0] = NULL;
4630 	/* If not an exported regular file or not a pNFS server, just return. */
4631 	if (vp->v_type != VREG || (vp->v_mount->mnt_flag & MNT_EXPORTED) == 0 ||
4632 	    nfsrv_devidcnt == 0)
4633 		return;
4634 
4635 	/* Check to see if this is the last hard link. */
4636 	tcred = newnfs_getcred();
4637 	error = VOP_GETATTR(vp, &va, tcred);
4638 	NFSFREECRED(tcred);
4639 	if (error != 0) {
4640 		printf("pNFS: nfsrv_pnfsremovesetup getattr=%d\n", error);
4641 		return;
4642 	}
4643 	if (va.va_nlink > 1)
4644 		return;
4645 
4646 	error = nfsvno_getfh(vp, fhp, p);
4647 	if (error != 0) {
4648 		printf("pNFS: nfsrv_pnfsremovesetup getfh=%d\n", error);
4649 		return;
4650 	}
4651 
4652 	buflen = 1024;
4653 	buf = malloc(buflen, M_TEMP, M_WAITOK);
4654 	/* Get the directory vnode for the DS mount and the file handle. */
4655 	error = nfsrv_dsgetsockmnt(vp, 0, buf, &buflen, mirrorcntp, p, dvpp,
4656 	    NULL, NULL, fname, NULL, NULL, NULL, NULL, NULL);
4657 	free(buf, M_TEMP);
4658 	if (error != 0)
4659 		printf("pNFS: nfsrv_pnfsremovesetup getsockmnt=%d\n", error);
4660 }
4661 
4662 /*
4663  * Remove a DS data file for nfsrv_pnfsremove(). Called for each mirror.
4664  * The arguments are in a structure, so that they can be passed through
4665  * taskqueue for a kernel process to execute this function.
4666  */
4667 struct nfsrvdsremove {
4668 	int			done;
4669 	int			inprog;
4670 	struct task		tsk;
4671 	struct ucred		*tcred;
4672 	struct vnode		*dvp;
4673 	NFSPROC_T		*p;
4674 	int			err;
4675 	char			fname[PNFS_FILENAME_LEN + 1];
4676 };
4677 
4678 static int
4679 nfsrv_dsremove(struct vnode *dvp, char *fname, struct ucred *tcred,
4680     NFSPROC_T *p)
4681 {
4682 	struct nameidata named;
4683 	struct vnode *nvp;
4684 	char *bufp;
4685 	u_long *hashp;
4686 	int error;
4687 
4688 	error = NFSVOPLOCK(dvp, LK_EXCLUSIVE);
4689 	if (error != 0)
4690 		return (error);
4691 	named.ni_cnd.cn_nameiop = DELETE;
4692 	named.ni_cnd.cn_lkflags = LK_EXCLUSIVE | LK_RETRY;
4693 	named.ni_cnd.cn_cred = tcred;
4694 	named.ni_cnd.cn_flags = ISLASTCN | LOCKPARENT | LOCKLEAF;
4695 	nfsvno_setpathbuf(&named, &bufp, &hashp);
4696 	named.ni_cnd.cn_nameptr = bufp;
4697 	named.ni_cnd.cn_namelen = strlen(fname);
4698 	strlcpy(bufp, fname, NAME_MAX);
4699 	NFSD_DEBUG(4, "nfsrv_pnfsremove: filename=%s\n", bufp);
4700 	error = VOP_LOOKUP(dvp, &nvp, &named.ni_cnd);
4701 	NFSD_DEBUG(4, "nfsrv_pnfsremove: aft LOOKUP=%d\n", error);
4702 	if (error == 0) {
4703 		error = VOP_REMOVE(dvp, nvp, &named.ni_cnd);
4704 		vput(nvp);
4705 	}
4706 	NFSVOPUNLOCK(dvp);
4707 	nfsvno_relpathbuf(&named);
4708 	if (error != 0)
4709 		printf("pNFS: nfsrv_pnfsremove failed=%d\n", error);
4710 	return (error);
4711 }
4712 
4713 /*
4714  * Start up the thread that will execute nfsrv_dsremove().
4715  */
4716 static void
4717 start_dsremove(void *arg, int pending)
4718 {
4719 	struct nfsrvdsremove *dsrm;
4720 
4721 	dsrm = (struct nfsrvdsremove *)arg;
4722 	dsrm->err = nfsrv_dsremove(dsrm->dvp, dsrm->fname, dsrm->tcred,
4723 	    dsrm->p);
4724 	dsrm->done = 1;
4725 	NFSD_DEBUG(4, "start_dsremove: err=%d\n", dsrm->err);
4726 }
4727 
4728 /*
4729  * Remove a pNFS data file from a Data Server.
4730  * nfsrv_pnfsremovesetup() must have been called before the MDS file was
4731  * removed to set up the dvp and fill in the FH.
4732  */
4733 static void
4734 nfsrv_pnfsremove(struct vnode **dvp, int mirrorcnt, char *fname, fhandle_t *fhp,
4735     NFSPROC_T *p)
4736 {
4737 	struct ucred *tcred;
4738 	struct nfsrvdsremove *dsrm, *tdsrm;
4739 	struct nfsdevice *ds;
4740 	struct nfsmount *nmp;
4741 	int failpos, i, ret, timo;
4742 
4743 	tcred = newnfs_getcred();
4744 	dsrm = NULL;
4745 	if (mirrorcnt > 1)
4746 		dsrm = malloc(sizeof(*dsrm) * mirrorcnt - 1, M_TEMP, M_WAITOK);
4747 	/*
4748 	 * Remove the file on each DS mirror, using kernel process(es) for the
4749 	 * additional mirrors.
4750 	 */
4751 	failpos = -1;
4752 	for (tdsrm = dsrm, i = 0; i < mirrorcnt - 1; i++, tdsrm++) {
4753 		tdsrm->tcred = tcred;
4754 		tdsrm->p = p;
4755 		tdsrm->dvp = dvp[i];
4756 		strlcpy(tdsrm->fname, fname, PNFS_FILENAME_LEN + 1);
4757 		tdsrm->inprog = 0;
4758 		tdsrm->done = 0;
4759 		tdsrm->err = 0;
4760 		ret = EIO;
4761 		if (nfs_pnfsiothreads != 0) {
4762 			ret = nfs_pnfsio(start_dsremove, tdsrm);
4763 			NFSD_DEBUG(4, "nfsrv_pnfsremove: nfs_pnfsio=%d\n", ret);
4764 		}
4765 		if (ret != 0) {
4766 			ret = nfsrv_dsremove(dvp[i], fname, tcred, p);
4767 			if (failpos == -1 && nfsds_failerr(ret))
4768 				failpos = i;
4769 		}
4770 	}
4771 	ret = nfsrv_dsremove(dvp[mirrorcnt - 1], fname, tcred, p);
4772 	if (failpos == -1 && mirrorcnt > 1 && nfsds_failerr(ret))
4773 		failpos = mirrorcnt - 1;
4774 	timo = hz / 50;		/* Wait for 20msec. */
4775 	if (timo < 1)
4776 		timo = 1;
4777 	/* Wait for kernel task(s) to complete. */
4778 	for (tdsrm = dsrm, i = 0; i < mirrorcnt - 1; i++, tdsrm++) {
4779 		while (tdsrm->inprog != 0 && tdsrm->done == 0)
4780 			tsleep(&tdsrm->tsk, PVFS, "srvdsrm", timo);
4781 		if (failpos == -1 && nfsds_failerr(tdsrm->err))
4782 			failpos = i;
4783 	}
4784 
4785 	/*
4786 	 * If failpos has been set, that mirror has failed, so it needs
4787 	 * to be disabled.
4788 	 */
4789 	if (failpos >= 0) {
4790 		nmp = VFSTONFS(dvp[failpos]->v_mount);
4791 		NFSLOCKMNT(nmp);
4792 		if ((nmp->nm_privflag & (NFSMNTP_FORCEDISM |
4793 		     NFSMNTP_CANCELRPCS)) == 0) {
4794 			nmp->nm_privflag |= NFSMNTP_CANCELRPCS;
4795 			NFSUNLOCKMNT(nmp);
4796 			ds = nfsrv_deldsnmp(PNFSDOP_DELDSSERVER, nmp, p);
4797 			NFSD_DEBUG(4, "dsremovefail fail=%d ds=%p\n", failpos,
4798 			    ds);
4799 			if (ds != NULL)
4800 				nfsrv_killrpcs(nmp);
4801 			NFSLOCKMNT(nmp);
4802 			nmp->nm_privflag &= ~NFSMNTP_CANCELRPCS;
4803 			wakeup(nmp);
4804 		}
4805 		NFSUNLOCKMNT(nmp);
4806 	}
4807 
4808 	/* Get rid all layouts for the file. */
4809 	nfsrv_freefilelayouts(fhp);
4810 
4811 	NFSFREECRED(tcred);
4812 	free(dsrm, M_TEMP);
4813 }
4814 
4815 /*
4816  * Generate a file name based on the file handle and put it in *bufp.
4817  * Return the number of bytes generated.
4818  */
4819 static int
4820 nfsrv_putfhname(fhandle_t *fhp, char *bufp)
4821 {
4822 	int i;
4823 	uint8_t *cp;
4824 	const uint8_t *hexdigits = "0123456789abcdef";
4825 
4826 	cp = (uint8_t *)fhp;
4827 	for (i = 0; i < sizeof(*fhp); i++) {
4828 		bufp[2 * i] = hexdigits[(*cp >> 4) & 0xf];
4829 		bufp[2 * i + 1] = hexdigits[*cp++ & 0xf];
4830 	}
4831 	bufp[2 * i] = '\0';
4832 	return (2 * i);
4833 }
4834 
4835 /*
4836  * Update the Metadata file's attributes from the DS file when a Read/Write
4837  * layout is returned.
4838  * Basically just call nfsrv_proxyds() with procedure == NFSPROC_LAYOUTRETURN
4839  * so that it does a nfsrv_getattrdsrpc() and nfsrv_setextattr() on the DS file.
4840  */
4841 int
4842 nfsrv_updatemdsattr(struct vnode *vp, struct nfsvattr *nap, NFSPROC_T *p)
4843 {
4844 	struct ucred *tcred;
4845 	int error;
4846 
4847 	/* Do this as root so that it won't fail with EACCES. */
4848 	tcred = newnfs_getcred();
4849 	error = nfsrv_proxyds(vp, 0, 0, tcred, p, NFSPROC_LAYOUTRETURN,
4850 	    NULL, NULL, NULL, nap, NULL, NULL, 0, NULL);
4851 	NFSFREECRED(tcred);
4852 	return (error);
4853 }
4854 
4855 /*
4856  * Set the NFSv4 ACL on the DS file to the same ACL as the MDS file.
4857  */
4858 static int
4859 nfsrv_dssetacl(struct vnode *vp, struct acl *aclp, struct ucred *cred,
4860     NFSPROC_T *p)
4861 {
4862 	int error;
4863 
4864 	error = nfsrv_proxyds(vp, 0, 0, cred, p, NFSPROC_SETACL,
4865 	    NULL, NULL, NULL, NULL, aclp, NULL, 0, NULL);
4866 	return (error);
4867 }
4868 
4869 static int
4870 nfsrv_proxyds(struct vnode *vp, off_t off, int cnt, struct ucred *cred,
4871     struct thread *p, int ioproc, struct mbuf **mpp, char *cp,
4872     struct mbuf **mpp2, struct nfsvattr *nap, struct acl *aclp,
4873     off_t *offp, int content, bool *eofp)
4874 {
4875 	struct nfsmount *nmp[NFSDEV_MAXMIRRORS], *failnmp;
4876 	fhandle_t fh[NFSDEV_MAXMIRRORS];
4877 	struct vnode *dvp[NFSDEV_MAXMIRRORS];
4878 	struct nfsdevice *ds;
4879 	struct pnfsdsattr dsattr;
4880 	struct opnfsdsattr odsattr;
4881 	char *buf;
4882 	int buflen, error, failpos, i, mirrorcnt, origmircnt, trycnt;
4883 
4884 	NFSD_DEBUG(4, "in nfsrv_proxyds\n");
4885 	/*
4886 	 * If not a regular file, not exported or not a pNFS server,
4887 	 * just return ENOENT.
4888 	 */
4889 	if (vp->v_type != VREG || (vp->v_mount->mnt_flag & MNT_EXPORTED) == 0 ||
4890 	    nfsrv_devidcnt == 0)
4891 		return (ENOENT);
4892 
4893 	buflen = 1024;
4894 	buf = malloc(buflen, M_TEMP, M_WAITOK);
4895 	error = 0;
4896 
4897 	/*
4898 	 * For Getattr, get the Change attribute (va_filerev) and size (va_size)
4899 	 * from the MetaData file's extended attribute.
4900 	 */
4901 	if (ioproc == NFSPROC_GETATTR) {
4902 		error = vn_extattr_get(vp, IO_NODELOCKED,
4903 		    EXTATTR_NAMESPACE_SYSTEM, "pnfsd.dsattr", &buflen, buf,
4904 		    p);
4905 		if (error == 0) {
4906 			if (buflen == sizeof(odsattr)) {
4907 				NFSBCOPY(buf, &odsattr, buflen);
4908 				nap->na_filerev = odsattr.dsa_filerev;
4909 				nap->na_size = odsattr.dsa_size;
4910 				nap->na_atime = odsattr.dsa_atime;
4911 				nap->na_mtime = odsattr.dsa_mtime;
4912 				/*
4913 				 * Fake na_bytes by rounding up na_size.
4914 				 * Since we don't know the block size, just
4915 				 * use BLKDEV_IOSIZE.
4916 				 */
4917 				nap->na_bytes = (odsattr.dsa_size +
4918 				    BLKDEV_IOSIZE - 1) & ~(BLKDEV_IOSIZE - 1);
4919 			} else if (buflen == sizeof(dsattr)) {
4920 				NFSBCOPY(buf, &dsattr, buflen);
4921 				nap->na_filerev = dsattr.dsa_filerev;
4922 				nap->na_size = dsattr.dsa_size;
4923 				nap->na_atime = dsattr.dsa_atime;
4924 				nap->na_mtime = dsattr.dsa_mtime;
4925 				nap->na_bytes = dsattr.dsa_bytes;
4926 			} else
4927 				error = ENXIO;
4928 		}
4929 		if (error == 0) {
4930 			/*
4931 			 * If nfsrv_pnfsgetdsattr is 0 or nfsrv_checkdsattr()
4932 			 * returns 0, just return now.  nfsrv_checkdsattr()
4933 			 * returns 0 if there is no Read/Write layout
4934 			 * plus either an Open/Write_access or Write
4935 			 * delegation issued to a client for the file.
4936 			 */
4937 			if (nfsrv_pnfsgetdsattr == 0 ||
4938 			    nfsrv_checkdsattr(vp, p) == 0) {
4939 				free(buf, M_TEMP);
4940 				return (error);
4941 			}
4942 		}
4943 
4944 		/*
4945 		 * Clear ENOATTR so the code below will attempt to do a
4946 		 * nfsrv_getattrdsrpc() to get the attributes and (re)create
4947 		 * the extended attribute.
4948 		 */
4949 		if (error == ENOATTR)
4950 			error = 0;
4951 	}
4952 
4953 	origmircnt = -1;
4954 	trycnt = 0;
4955 tryagain:
4956 	if (error == 0) {
4957 		buflen = 1024;
4958 		if (ioproc == NFSPROC_READDS && NFSVOPISLOCKED(vp) ==
4959 		    LK_EXCLUSIVE)
4960 			printf("nfsrv_proxyds: Readds vp exclusively locked\n");
4961 		error = nfsrv_dsgetsockmnt(vp, LK_SHARED, buf, &buflen,
4962 		    &mirrorcnt, p, dvp, fh, NULL, NULL, NULL, NULL, NULL,
4963 		    NULL, NULL);
4964 		if (error == 0) {
4965 			for (i = 0; i < mirrorcnt; i++)
4966 				nmp[i] = VFSTONFS(dvp[i]->v_mount);
4967 		} else
4968 			printf("pNFS: proxy getextattr sockaddr=%d\n", error);
4969 	} else
4970 		printf("pNFS: nfsrv_dsgetsockmnt=%d\n", error);
4971 	if (error == 0) {
4972 		failpos = -1;
4973 		if (origmircnt == -1)
4974 			origmircnt = mirrorcnt;
4975 		/*
4976 		 * If failpos is set to a mirror#, then that mirror has
4977 		 * failed and will be disabled. For Read, Getattr and Seek, the
4978 		 * function only tries one mirror, so if that mirror has
4979 		 * failed, it will need to be retried. As such, increment
4980 		 * tryitagain for these cases.
4981 		 * For Write, Setattr and Setacl, the function tries all
4982 		 * mirrors and will not return an error for the case where
4983 		 * one mirror has failed. For these cases, the functioning
4984 		 * mirror(s) will have been modified, so a retry isn't
4985 		 * necessary. These functions will set failpos for the
4986 		 * failed mirror#.
4987 		 */
4988 		if (ioproc == NFSPROC_READDS) {
4989 			error = nfsrv_readdsrpc(fh, off, cnt, cred, p, nmp[0],
4990 			    mpp, mpp2);
4991 			if (nfsds_failerr(error) && mirrorcnt > 1) {
4992 				/*
4993 				 * Setting failpos will cause the mirror
4994 				 * to be disabled and then a retry of this
4995 				 * read is required.
4996 				 */
4997 				failpos = 0;
4998 				error = 0;
4999 				trycnt++;
5000 			}
5001 		} else if (ioproc == NFSPROC_WRITEDS)
5002 			error = nfsrv_writedsrpc(fh, off, cnt, cred, p, vp,
5003 			    &nmp[0], mirrorcnt, mpp, cp, &failpos);
5004 		else if (ioproc == NFSPROC_SETATTR)
5005 			error = nfsrv_setattrdsrpc(fh, cred, p, vp, &nmp[0],
5006 			    mirrorcnt, nap, &failpos);
5007 		else if (ioproc == NFSPROC_SETACL)
5008 			error = nfsrv_setacldsrpc(fh, cred, p, vp, &nmp[0],
5009 			    mirrorcnt, aclp, &failpos);
5010 		else if (ioproc == NFSPROC_SEEKDS) {
5011 			error = nfsrv_seekdsrpc(fh, offp, content, eofp, cred,
5012 			    p, nmp[0]);
5013 			if (nfsds_failerr(error) && mirrorcnt > 1) {
5014 				/*
5015 				 * Setting failpos will cause the mirror
5016 				 * to be disabled and then a retry of this
5017 				 * read is required.
5018 				 */
5019 				failpos = 0;
5020 				error = 0;
5021 				trycnt++;
5022 			}
5023 		} else if (ioproc == NFSPROC_ALLOCATE)
5024 			error = nfsrv_allocatedsrpc(fh, off, *offp, cred, p, vp,
5025 			    &nmp[0], mirrorcnt, &failpos);
5026 		else if (ioproc == NFSPROC_DEALLOCATE)
5027 			error = nfsrv_deallocatedsrpc(fh, off, *offp, cred, p,
5028 			    vp, &nmp[0], mirrorcnt, &failpos);
5029 		else {
5030 			error = nfsrv_getattrdsrpc(&fh[mirrorcnt - 1], cred, p,
5031 			    vp, nmp[mirrorcnt - 1], nap);
5032 			if (nfsds_failerr(error) && mirrorcnt > 1) {
5033 				/*
5034 				 * Setting failpos will cause the mirror
5035 				 * to be disabled and then a retry of this
5036 				 * getattr is required.
5037 				 */
5038 				failpos = mirrorcnt - 1;
5039 				error = 0;
5040 				trycnt++;
5041 			}
5042 		}
5043 		ds = NULL;
5044 		if (failpos >= 0) {
5045 			failnmp = nmp[failpos];
5046 			NFSLOCKMNT(failnmp);
5047 			if ((failnmp->nm_privflag & (NFSMNTP_FORCEDISM |
5048 			     NFSMNTP_CANCELRPCS)) == 0) {
5049 				failnmp->nm_privflag |= NFSMNTP_CANCELRPCS;
5050 				NFSUNLOCKMNT(failnmp);
5051 				ds = nfsrv_deldsnmp(PNFSDOP_DELDSSERVER,
5052 				    failnmp, p);
5053 				NFSD_DEBUG(4, "dsldsnmp fail=%d ds=%p\n",
5054 				    failpos, ds);
5055 				if (ds != NULL)
5056 					nfsrv_killrpcs(failnmp);
5057 				NFSLOCKMNT(failnmp);
5058 				failnmp->nm_privflag &= ~NFSMNTP_CANCELRPCS;
5059 				wakeup(failnmp);
5060 			}
5061 			NFSUNLOCKMNT(failnmp);
5062 		}
5063 		for (i = 0; i < mirrorcnt; i++)
5064 			NFSVOPUNLOCK(dvp[i]);
5065 		NFSD_DEBUG(4, "nfsrv_proxyds: aft RPC=%d trya=%d\n", error,
5066 		    trycnt);
5067 		/* Try the Read/Getattr again if a mirror was deleted. */
5068 		if (ds != NULL && trycnt > 0 && trycnt < origmircnt)
5069 			goto tryagain;
5070 	} else {
5071 		/* Return ENOENT for any Extended Attribute error. */
5072 		error = ENOENT;
5073 	}
5074 	free(buf, M_TEMP);
5075 	NFSD_DEBUG(4, "nfsrv_proxyds: error=%d\n", error);
5076 	return (error);
5077 }
5078 
5079 /*
5080  * Get the DS mount point, fh and directory from the "pnfsd.dsfile" extended
5081  * attribute.
5082  * newnmpp - If it points to a non-NULL nmp, that is the destination and needs
5083  *           to be checked.  If it points to a NULL nmp, then it returns
5084  *           a suitable destination.
5085  * curnmp - If non-NULL, it is the source mount for the copy.
5086  */
5087 int
5088 nfsrv_dsgetsockmnt(struct vnode *vp, int lktype, char *buf, int *buflenp,
5089     int *mirrorcntp, NFSPROC_T *p, struct vnode **dvpp, fhandle_t *fhp,
5090     char *devid, char *fnamep, struct vnode **nvpp, struct nfsmount **newnmpp,
5091     struct nfsmount *curnmp, int *ippos, int *dsdirp)
5092 {
5093 	struct vnode *dvp, *nvp = NULL, **tdvpp;
5094 	struct mount *mp;
5095 	struct nfsmount *nmp, *newnmp;
5096 	struct sockaddr *sad;
5097 	struct sockaddr_in *sin;
5098 	struct nfsdevice *ds, *tds, *fndds;
5099 	struct pnfsdsfile *pf;
5100 	uint32_t dsdir;
5101 	int error, fhiszero, fnd, gotone, i, mirrorcnt;
5102 
5103 	ASSERT_VOP_LOCKED(vp, "nfsrv_dsgetsockmnt vp");
5104 	*mirrorcntp = 1;
5105 	tdvpp = dvpp;
5106 	if (nvpp != NULL)
5107 		*nvpp = NULL;
5108 	if (dvpp != NULL)
5109 		*dvpp = NULL;
5110 	if (ippos != NULL)
5111 		*ippos = -1;
5112 	if (newnmpp != NULL)
5113 		newnmp = *newnmpp;
5114 	else
5115 		newnmp = NULL;
5116 	mp = vp->v_mount;
5117 	error = vn_extattr_get(vp, IO_NODELOCKED, EXTATTR_NAMESPACE_SYSTEM,
5118 	    "pnfsd.dsfile", buflenp, buf, p);
5119 	mirrorcnt = *buflenp / sizeof(*pf);
5120 	if (error == 0 && (mirrorcnt < 1 || mirrorcnt > NFSDEV_MAXMIRRORS ||
5121 	    *buflenp != sizeof(*pf) * mirrorcnt))
5122 		error = ENOATTR;
5123 
5124 	pf = (struct pnfsdsfile *)buf;
5125 	/* If curnmp != NULL, check for a match in the mirror list. */
5126 	if (curnmp != NULL && error == 0) {
5127 		fnd = 0;
5128 		for (i = 0; i < mirrorcnt; i++, pf++) {
5129 			sad = (struct sockaddr *)&pf->dsf_sin;
5130 			if (nfsaddr2_match(sad, curnmp->nm_nam)) {
5131 				if (ippos != NULL)
5132 					*ippos = i;
5133 				fnd = 1;
5134 				break;
5135 			}
5136 		}
5137 		if (fnd == 0)
5138 			error = ENXIO;
5139 	}
5140 
5141 	gotone = 0;
5142 	pf = (struct pnfsdsfile *)buf;
5143 	NFSD_DEBUG(4, "nfsrv_dsgetsockmnt: mirrorcnt=%d err=%d\n", mirrorcnt,
5144 	    error);
5145 	for (i = 0; i < mirrorcnt && error == 0; i++, pf++) {
5146 		fhiszero = 0;
5147 		sad = (struct sockaddr *)&pf->dsf_sin;
5148 		sin = &pf->dsf_sin;
5149 		dsdir = pf->dsf_dir;
5150 		if (dsdir >= nfsrv_dsdirsize) {
5151 			printf("nfsrv_dsgetsockmnt: dsdir=%d\n", dsdir);
5152 			error = ENOATTR;
5153 		} else if (nvpp != NULL && newnmp != NULL &&
5154 		    nfsaddr2_match(sad, newnmp->nm_nam))
5155 			error = EEXIST;
5156 		if (error == 0) {
5157 			if (ippos != NULL && curnmp == NULL &&
5158 			    sad->sa_family == AF_INET &&
5159 			    sin->sin_addr.s_addr == 0)
5160 				*ippos = i;
5161 			if (NFSBCMP(&zerofh, &pf->dsf_fh, sizeof(zerofh)) == 0)
5162 				fhiszero = 1;
5163 			/* Use the socket address to find the mount point. */
5164 			fndds = NULL;
5165 			NFSDDSLOCK();
5166 			/* Find a match for the IP address. */
5167 			TAILQ_FOREACH(ds, &nfsrv_devidhead, nfsdev_list) {
5168 				if (ds->nfsdev_nmp != NULL) {
5169 					dvp = ds->nfsdev_dvp;
5170 					nmp = VFSTONFS(dvp->v_mount);
5171 					if (nmp != ds->nfsdev_nmp)
5172 						printf("different2 nmp %p %p\n",
5173 						    nmp, ds->nfsdev_nmp);
5174 					if (nfsaddr2_match(sad, nmp->nm_nam)) {
5175 						fndds = ds;
5176 						break;
5177 					}
5178 				}
5179 			}
5180 			if (fndds != NULL && newnmpp != NULL &&
5181 			    newnmp == NULL) {
5182 				/* Search for a place to make a mirror copy. */
5183 				TAILQ_FOREACH(tds, &nfsrv_devidhead,
5184 				    nfsdev_list) {
5185 					if (tds->nfsdev_nmp != NULL &&
5186 					    fndds != tds &&
5187 					    ((tds->nfsdev_mdsisset == 0 &&
5188 					      fndds->nfsdev_mdsisset == 0) ||
5189 					     (tds->nfsdev_mdsisset != 0 &&
5190 					      fndds->nfsdev_mdsisset != 0 &&
5191 					      fsidcmp(&tds->nfsdev_mdsfsid,
5192 					      &mp->mnt_stat.f_fsid) == 0))) {
5193 						*newnmpp = tds->nfsdev_nmp;
5194 						break;
5195 					}
5196 				}
5197 				if (tds != NULL) {
5198 					/*
5199 					 * Move this entry to the end of the
5200 					 * list, so it won't be selected as
5201 					 * easily the next time.
5202 					 */
5203 					TAILQ_REMOVE(&nfsrv_devidhead, tds,
5204 					    nfsdev_list);
5205 					TAILQ_INSERT_TAIL(&nfsrv_devidhead, tds,
5206 					    nfsdev_list);
5207 				}
5208 			}
5209 			NFSDDSUNLOCK();
5210 			if (fndds != NULL) {
5211 				dvp = fndds->nfsdev_dsdir[dsdir];
5212 				if (lktype != 0 || fhiszero != 0 ||
5213 				    (nvpp != NULL && *nvpp == NULL)) {
5214 					if (fhiszero != 0)
5215 						error = vn_lock(dvp,
5216 						    LK_EXCLUSIVE);
5217 					else if (lktype != 0)
5218 						error = vn_lock(dvp, lktype);
5219 					else
5220 						error = vn_lock(dvp, LK_SHARED);
5221 					/*
5222 					 * If the file handle is all 0's, try to
5223 					 * do a Lookup against the DS to acquire
5224 					 * it.
5225 					 * If dvpp == NULL or the Lookup fails,
5226 					 * unlock dvp after the call.
5227 					 */
5228 					if (error == 0 && (fhiszero != 0 ||
5229 					    (nvpp != NULL && *nvpp == NULL))) {
5230 						error = nfsrv_pnfslookupds(vp,
5231 						    dvp, pf, &nvp, p);
5232 						if (error == 0) {
5233 							if (fhiszero != 0)
5234 								nfsrv_pnfssetfh(
5235 								    vp, pf,
5236 								    devid,
5237 								    fnamep,
5238 								    nvp, p);
5239 							if (nvpp != NULL &&
5240 							    *nvpp == NULL) {
5241 								*nvpp = nvp;
5242 								*dsdirp = dsdir;
5243 							} else
5244 								vput(nvp);
5245 						}
5246 						if (error != 0 || lktype == 0)
5247 							NFSVOPUNLOCK(dvp);
5248 					}
5249 				}
5250 				if (error == 0) {
5251 					gotone++;
5252 					NFSD_DEBUG(4, "gotone=%d\n", gotone);
5253 					if (devid != NULL) {
5254 						NFSBCOPY(fndds->nfsdev_deviceid,
5255 						    devid, NFSX_V4DEVICEID);
5256 						devid += NFSX_V4DEVICEID;
5257 					}
5258 					if (dvpp != NULL)
5259 						*tdvpp++ = dvp;
5260 					if (fhp != NULL)
5261 						NFSBCOPY(&pf->dsf_fh, fhp++,
5262 						    NFSX_MYFH);
5263 					if (fnamep != NULL && gotone == 1)
5264 						strlcpy(fnamep,
5265 						    pf->dsf_filename,
5266 						    sizeof(pf->dsf_filename));
5267 				} else
5268 					NFSD_DEBUG(4, "nfsrv_dsgetsockmnt "
5269 					    "err=%d\n", error);
5270 			}
5271 		}
5272 	}
5273 	if (error == 0 && gotone == 0)
5274 		error = ENOENT;
5275 
5276 	NFSD_DEBUG(4, "eo nfsrv_dsgetsockmnt: gotone=%d err=%d\n", gotone,
5277 	    error);
5278 	if (error == 0)
5279 		*mirrorcntp = gotone;
5280 	else {
5281 		if (gotone > 0 && dvpp != NULL) {
5282 			/*
5283 			 * If the error didn't occur on the first one and
5284 			 * dvpp != NULL, the one(s) prior to the failure will
5285 			 * have locked dvp's that need to be unlocked.
5286 			 */
5287 			for (i = 0; i < gotone; i++) {
5288 				NFSVOPUNLOCK(*dvpp);
5289 				*dvpp++ = NULL;
5290 			}
5291 		}
5292 		/*
5293 		 * If it found the vnode to be copied from before a failure,
5294 		 * it needs to be vput()'d.
5295 		 */
5296 		if (nvpp != NULL && *nvpp != NULL) {
5297 			vput(*nvpp);
5298 			*nvpp = NULL;
5299 		}
5300 	}
5301 	return (error);
5302 }
5303 
5304 /*
5305  * Set the extended attribute for the Change attribute.
5306  */
5307 static int
5308 nfsrv_setextattr(struct vnode *vp, struct nfsvattr *nap, NFSPROC_T *p)
5309 {
5310 	struct pnfsdsattr dsattr;
5311 	int error;
5312 
5313 	ASSERT_VOP_ELOCKED(vp, "nfsrv_setextattr vp");
5314 	dsattr.dsa_filerev = nap->na_filerev;
5315 	dsattr.dsa_size = nap->na_size;
5316 	dsattr.dsa_atime = nap->na_atime;
5317 	dsattr.dsa_mtime = nap->na_mtime;
5318 	dsattr.dsa_bytes = nap->na_bytes;
5319 	error = vn_extattr_set(vp, IO_NODELOCKED, EXTATTR_NAMESPACE_SYSTEM,
5320 	    "pnfsd.dsattr", sizeof(dsattr), (char *)&dsattr, p);
5321 	if (error != 0)
5322 		printf("pNFS: setextattr=%d\n", error);
5323 	return (error);
5324 }
5325 
5326 static int
5327 nfsrv_readdsrpc(fhandle_t *fhp, off_t off, int len, struct ucred *cred,
5328     NFSPROC_T *p, struct nfsmount *nmp, struct mbuf **mpp, struct mbuf **mpendp)
5329 {
5330 	uint32_t *tl;
5331 	struct nfsrv_descript *nd;
5332 	nfsv4stateid_t st;
5333 	struct mbuf *m, *m2;
5334 	int error = 0, retlen, tlen, trimlen;
5335 
5336 	NFSD_DEBUG(4, "in nfsrv_readdsrpc\n");
5337 	nd = malloc(sizeof(*nd), M_TEMP, M_WAITOK | M_ZERO);
5338 	*mpp = NULL;
5339 	/*
5340 	 * Use a stateid where other is an alternating 01010 pattern and
5341 	 * seqid is 0xffffffff.  This value is not defined as special by
5342 	 * the RFC and is used by the FreeBSD NFS server to indicate an
5343 	 * MDS->DS proxy operation.
5344 	 */
5345 	st.other[0] = 0x55555555;
5346 	st.other[1] = 0x55555555;
5347 	st.other[2] = 0x55555555;
5348 	st.seqid = 0xffffffff;
5349 	nfscl_reqstart(nd, NFSPROC_READDS, nmp, (u_int8_t *)fhp, sizeof(*fhp),
5350 	    NULL, NULL, 0, 0, cred);
5351 	nfsm_stateidtom(nd, &st, NFSSTATEID_PUTSTATEID);
5352 	NFSM_BUILD(tl, uint32_t *, NFSX_UNSIGNED * 3);
5353 	txdr_hyper(off, tl);
5354 	*(tl + 2) = txdr_unsigned(len);
5355 	error = newnfs_request(nd, nmp, NULL, &nmp->nm_sockreq, NULL, p, cred,
5356 	    NFS_PROG, NFS_VER4, NULL, 1, NULL, NULL);
5357 	if (error != 0) {
5358 		free(nd, M_TEMP);
5359 		return (error);
5360 	}
5361 	if (nd->nd_repstat == 0) {
5362 		NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
5363 		NFSM_STRSIZ(retlen, len);
5364 		if (retlen > 0) {
5365 			/* Trim off the pre-data XDR from the mbuf chain. */
5366 			m = nd->nd_mrep;
5367 			while (m != NULL && m != nd->nd_md) {
5368 				if (m->m_next == nd->nd_md) {
5369 					m->m_next = NULL;
5370 					m_freem(nd->nd_mrep);
5371 					nd->nd_mrep = m = nd->nd_md;
5372 				} else
5373 					m = m->m_next;
5374 			}
5375 			if (m == NULL) {
5376 				printf("nfsrv_readdsrpc: busted mbuf list\n");
5377 				error = ENOENT;
5378 				goto nfsmout;
5379 			}
5380 
5381 			/*
5382 			 * Now, adjust first mbuf so that any XDR before the
5383 			 * read data is skipped over.
5384 			 */
5385 			trimlen = nd->nd_dpos - mtod(m, char *);
5386 			if (trimlen > 0) {
5387 				m->m_len -= trimlen;
5388 				NFSM_DATAP(m, trimlen);
5389 			}
5390 
5391 			/*
5392 			 * Truncate the mbuf chain at retlen bytes of data,
5393 			 * plus XDR padding that brings the length up to a
5394 			 * multiple of 4.
5395 			 */
5396 			tlen = NFSM_RNDUP(retlen);
5397 			do {
5398 				if (m->m_len >= tlen) {
5399 					m->m_len = tlen;
5400 					tlen = 0;
5401 					m2 = m->m_next;
5402 					m->m_next = NULL;
5403 					m_freem(m2);
5404 					break;
5405 				}
5406 				tlen -= m->m_len;
5407 				m = m->m_next;
5408 			} while (m != NULL);
5409 			if (tlen > 0) {
5410 				printf("nfsrv_readdsrpc: busted mbuf list\n");
5411 				error = ENOENT;
5412 				goto nfsmout;
5413 			}
5414 			*mpp = nd->nd_mrep;
5415 			*mpendp = m;
5416 			nd->nd_mrep = NULL;
5417 		}
5418 	} else
5419 		error = nd->nd_repstat;
5420 nfsmout:
5421 	/* If nd->nd_mrep is already NULL, this is a no-op. */
5422 	m_freem(nd->nd_mrep);
5423 	free(nd, M_TEMP);
5424 	NFSD_DEBUG(4, "nfsrv_readdsrpc error=%d\n", error);
5425 	return (error);
5426 }
5427 
5428 /*
5429  * Do a write RPC on a DS data file, using this structure for the arguments,
5430  * so that this function can be executed by a separate kernel process.
5431  */
5432 struct nfsrvwritedsdorpc {
5433 	int			done;
5434 	int			inprog;
5435 	struct task		tsk;
5436 	fhandle_t		fh;
5437 	off_t			off;
5438 	int			len;
5439 	struct nfsmount		*nmp;
5440 	struct ucred		*cred;
5441 	NFSPROC_T		*p;
5442 	struct mbuf		*m;
5443 	int			err;
5444 };
5445 
5446 static int
5447 nfsrv_writedsdorpc(struct nfsmount *nmp, fhandle_t *fhp, off_t off, int len,
5448     struct nfsvattr *nap, struct mbuf *m, struct ucred *cred, NFSPROC_T *p)
5449 {
5450 	uint32_t *tl;
5451 	struct nfsrv_descript *nd;
5452 	nfsattrbit_t attrbits;
5453 	nfsv4stateid_t st;
5454 	int commit, error, retlen;
5455 
5456 	nd = malloc(sizeof(*nd), M_TEMP, M_WAITOK | M_ZERO);
5457 	nfscl_reqstart(nd, NFSPROC_WRITE, nmp, (u_int8_t *)fhp,
5458 	    sizeof(fhandle_t), NULL, NULL, 0, 0, cred);
5459 
5460 	/*
5461 	 * Use a stateid where other is an alternating 01010 pattern and
5462 	 * seqid is 0xffffffff.  This value is not defined as special by
5463 	 * the RFC and is used by the FreeBSD NFS server to indicate an
5464 	 * MDS->DS proxy operation.
5465 	 */
5466 	st.other[0] = 0x55555555;
5467 	st.other[1] = 0x55555555;
5468 	st.other[2] = 0x55555555;
5469 	st.seqid = 0xffffffff;
5470 	nfsm_stateidtom(nd, &st, NFSSTATEID_PUTSTATEID);
5471 	NFSM_BUILD(tl, u_int32_t *, NFSX_HYPER + 2 * NFSX_UNSIGNED);
5472 	txdr_hyper(off, tl);
5473 	tl += 2;
5474 	/*
5475 	 * Do all writes FileSync, since the server doesn't hold onto dirty
5476 	 * buffers.  Since clients should be accessing the DS servers directly
5477 	 * using the pNFS layouts, this just needs to work correctly as a
5478 	 * fallback.
5479 	 */
5480 	*tl++ = txdr_unsigned(NFSWRITE_FILESYNC);
5481 	*tl = txdr_unsigned(len);
5482 	NFSD_DEBUG(4, "nfsrv_writedsdorpc: len=%d\n", len);
5483 
5484 	/* Put data in mbuf chain. */
5485 	nd->nd_mb->m_next = m;
5486 
5487 	/* Set nd_mb and nd_bpos to end of data. */
5488 	while (m->m_next != NULL)
5489 		m = m->m_next;
5490 	nd->nd_mb = m;
5491 	nfsm_set(nd, m->m_len);
5492 	NFSD_DEBUG(4, "nfsrv_writedsdorpc: lastmb len=%d\n", m->m_len);
5493 
5494 	/* Do a Getattr for the attributes that change upon writing. */
5495 	NFSZERO_ATTRBIT(&attrbits);
5496 	NFSSETBIT_ATTRBIT(&attrbits, NFSATTRBIT_SIZE);
5497 	NFSSETBIT_ATTRBIT(&attrbits, NFSATTRBIT_CHANGE);
5498 	NFSSETBIT_ATTRBIT(&attrbits, NFSATTRBIT_TIMEACCESS);
5499 	NFSSETBIT_ATTRBIT(&attrbits, NFSATTRBIT_TIMEMODIFY);
5500 	NFSSETBIT_ATTRBIT(&attrbits, NFSATTRBIT_SPACEUSED);
5501 	NFSM_BUILD(tl, u_int32_t *, NFSX_UNSIGNED);
5502 	*tl = txdr_unsigned(NFSV4OP_GETATTR);
5503 	(void) nfsrv_putattrbit(nd, &attrbits);
5504 	error = newnfs_request(nd, nmp, NULL, &nmp->nm_sockreq, NULL, p,
5505 	    cred, NFS_PROG, NFS_VER4, NULL, 1, NULL, NULL);
5506 	if (error != 0) {
5507 		free(nd, M_TEMP);
5508 		return (error);
5509 	}
5510 	NFSD_DEBUG(4, "nfsrv_writedsdorpc: aft writerpc=%d\n", nd->nd_repstat);
5511 	/* Get rid of weak cache consistency data for now. */
5512 	if ((nd->nd_flag & (ND_NOMOREDATA | ND_NFSV4 | ND_V4WCCATTR)) ==
5513 	    (ND_NFSV4 | ND_V4WCCATTR)) {
5514 		error = nfsv4_loadattr(nd, NULL, nap, NULL, NULL, 0, NULL, NULL,
5515 		    NULL, NULL, NULL, 0, NULL, NULL, NULL, NULL, NULL);
5516 		NFSD_DEBUG(4, "nfsrv_writedsdorpc: wcc attr=%d\n", error);
5517 		if (error != 0)
5518 			goto nfsmout;
5519 		/*
5520 		 * Get rid of Op# and status for next op.
5521 		 */
5522 		NFSM_DISSECT(tl, uint32_t *, 2 * NFSX_UNSIGNED);
5523 		if (*++tl != 0)
5524 			nd->nd_flag |= ND_NOMOREDATA;
5525 	}
5526 	if (nd->nd_repstat == 0) {
5527 		NFSM_DISSECT(tl, uint32_t *, 2 * NFSX_UNSIGNED + NFSX_VERF);
5528 		retlen = fxdr_unsigned(int, *tl++);
5529 		commit = fxdr_unsigned(int, *tl);
5530 		if (commit != NFSWRITE_FILESYNC)
5531 			error = NFSERR_IO;
5532 		NFSD_DEBUG(4, "nfsrv_writedsdorpc:retlen=%d commit=%d err=%d\n",
5533 		    retlen, commit, error);
5534 	} else
5535 		error = nd->nd_repstat;
5536 	/* We have no use for the Write Verifier since we use FileSync. */
5537 
5538 	/*
5539 	 * Get the Change, Size, Access Time and Modify Time attributes and set
5540 	 * on the Metadata file, so its attributes will be what the file's
5541 	 * would be if it had been written.
5542 	 */
5543 	if (error == 0) {
5544 		NFSM_DISSECT(tl, uint32_t *, 2 * NFSX_UNSIGNED);
5545 		error = nfsv4_loadattr(nd, NULL, nap, NULL, NULL, 0, NULL, NULL,
5546 		    NULL, NULL, NULL, 0, NULL, NULL, NULL, NULL, NULL);
5547 	}
5548 	NFSD_DEBUG(4, "nfsrv_writedsdorpc: aft loadattr=%d\n", error);
5549 nfsmout:
5550 	m_freem(nd->nd_mrep);
5551 	free(nd, M_TEMP);
5552 	NFSD_DEBUG(4, "nfsrv_writedsdorpc error=%d\n", error);
5553 	return (error);
5554 }
5555 
5556 /*
5557  * Start up the thread that will execute nfsrv_writedsdorpc().
5558  */
5559 static void
5560 start_writedsdorpc(void *arg, int pending)
5561 {
5562 	struct nfsrvwritedsdorpc *drpc;
5563 
5564 	drpc = (struct nfsrvwritedsdorpc *)arg;
5565 	drpc->err = nfsrv_writedsdorpc(drpc->nmp, &drpc->fh, drpc->off,
5566 	    drpc->len, NULL, drpc->m, drpc->cred, drpc->p);
5567 	drpc->done = 1;
5568 	NFSD_DEBUG(4, "start_writedsdorpc: err=%d\n", drpc->err);
5569 }
5570 
5571 static int
5572 nfsrv_writedsrpc(fhandle_t *fhp, off_t off, int len, struct ucred *cred,
5573     NFSPROC_T *p, struct vnode *vp, struct nfsmount **nmpp, int mirrorcnt,
5574     struct mbuf **mpp, char *cp, int *failposp)
5575 {
5576 	struct nfsrvwritedsdorpc *drpc, *tdrpc = NULL;
5577 	struct nfsvattr na;
5578 	struct mbuf *m;
5579 	int error, i, offs, ret, timo;
5580 
5581 	NFSD_DEBUG(4, "in nfsrv_writedsrpc\n");
5582 	KASSERT(*mpp != NULL, ("nfsrv_writedsrpc: NULL mbuf chain"));
5583 	drpc = NULL;
5584 	if (mirrorcnt > 1)
5585 		tdrpc = drpc = malloc(sizeof(*drpc) * (mirrorcnt - 1), M_TEMP,
5586 		    M_WAITOK);
5587 
5588 	/* Calculate offset in mbuf chain that data starts. */
5589 	offs = cp - mtod(*mpp, char *);
5590 	NFSD_DEBUG(4, "nfsrv_writedsrpc: mcopy offs=%d len=%d\n", offs, len);
5591 
5592 	/*
5593 	 * Do the write RPC for every DS, using a separate kernel process
5594 	 * for every DS except the last one.
5595 	 */
5596 	error = 0;
5597 	for (i = 0; i < mirrorcnt - 1; i++, tdrpc++) {
5598 		tdrpc->done = 0;
5599 		NFSBCOPY(fhp, &tdrpc->fh, sizeof(*fhp));
5600 		tdrpc->off = off;
5601 		tdrpc->len = len;
5602 		tdrpc->nmp = *nmpp;
5603 		tdrpc->cred = cred;
5604 		tdrpc->p = p;
5605 		tdrpc->inprog = 0;
5606 		tdrpc->err = 0;
5607 		tdrpc->m = m_copym(*mpp, offs, NFSM_RNDUP(len), M_WAITOK);
5608 		ret = EIO;
5609 		if (nfs_pnfsiothreads != 0) {
5610 			ret = nfs_pnfsio(start_writedsdorpc, tdrpc);
5611 			NFSD_DEBUG(4, "nfsrv_writedsrpc: nfs_pnfsio=%d\n",
5612 			    ret);
5613 		}
5614 		if (ret != 0) {
5615 			ret = nfsrv_writedsdorpc(*nmpp, fhp, off, len, NULL,
5616 			    tdrpc->m, cred, p);
5617 			if (nfsds_failerr(ret) && *failposp == -1)
5618 				*failposp = i;
5619 			else if (error == 0 && ret != 0)
5620 				error = ret;
5621 		}
5622 		nmpp++;
5623 		fhp++;
5624 	}
5625 	m = m_copym(*mpp, offs, NFSM_RNDUP(len), M_WAITOK);
5626 	ret = nfsrv_writedsdorpc(*nmpp, fhp, off, len, &na, m, cred, p);
5627 	if (nfsds_failerr(ret) && *failposp == -1 && mirrorcnt > 1)
5628 		*failposp = mirrorcnt - 1;
5629 	else if (error == 0 && ret != 0)
5630 		error = ret;
5631 	if (error == 0)
5632 		error = nfsrv_setextattr(vp, &na, p);
5633 	NFSD_DEBUG(4, "nfsrv_writedsrpc: aft setextat=%d\n", error);
5634 	tdrpc = drpc;
5635 	timo = hz / 50;		/* Wait for 20msec. */
5636 	if (timo < 1)
5637 		timo = 1;
5638 	for (i = 0; i < mirrorcnt - 1; i++, tdrpc++) {
5639 		/* Wait for RPCs on separate threads to complete. */
5640 		while (tdrpc->inprog != 0 && tdrpc->done == 0)
5641 			tsleep(&tdrpc->tsk, PVFS, "srvwrds", timo);
5642 		if (nfsds_failerr(tdrpc->err) && *failposp == -1)
5643 			*failposp = i;
5644 		else if (error == 0 && tdrpc->err != 0)
5645 			error = tdrpc->err;
5646 	}
5647 	free(drpc, M_TEMP);
5648 	return (error);
5649 }
5650 
5651 /*
5652  * Do a allocate RPC on a DS data file, using this structure for the arguments,
5653  * so that this function can be executed by a separate kernel process.
5654  */
5655 struct nfsrvallocatedsdorpc {
5656 	int			done;
5657 	int			inprog;
5658 	struct task		tsk;
5659 	fhandle_t		fh;
5660 	off_t			off;
5661 	off_t			len;
5662 	struct nfsmount		*nmp;
5663 	struct ucred		*cred;
5664 	NFSPROC_T		*p;
5665 	int			err;
5666 };
5667 
5668 static int
5669 nfsrv_allocatedsdorpc(struct nfsmount *nmp, fhandle_t *fhp, off_t off,
5670     off_t len, struct nfsvattr *nap, struct ucred *cred, NFSPROC_T *p)
5671 {
5672 	uint32_t *tl;
5673 	struct nfsrv_descript *nd;
5674 	nfsattrbit_t attrbits;
5675 	nfsv4stateid_t st;
5676 	int error;
5677 
5678 	nd = malloc(sizeof(*nd), M_TEMP, M_WAITOK | M_ZERO);
5679 	nfscl_reqstart(nd, NFSPROC_ALLOCATE, nmp, (u_int8_t *)fhp,
5680 	    sizeof(fhandle_t), NULL, NULL, 0, 0, cred);
5681 
5682 	/*
5683 	 * Use a stateid where other is an alternating 01010 pattern and
5684 	 * seqid is 0xffffffff.  This value is not defined as special by
5685 	 * the RFC and is used by the FreeBSD NFS server to indicate an
5686 	 * MDS->DS proxy operation.
5687 	 */
5688 	st.other[0] = 0x55555555;
5689 	st.other[1] = 0x55555555;
5690 	st.other[2] = 0x55555555;
5691 	st.seqid = 0xffffffff;
5692 	nfsm_stateidtom(nd, &st, NFSSTATEID_PUTSTATEID);
5693 	NFSM_BUILD(tl, uint32_t *, 2 * NFSX_HYPER + NFSX_UNSIGNED);
5694 	txdr_hyper(off, tl); tl += 2;
5695 	txdr_hyper(len, tl); tl += 2;
5696 	NFSD_DEBUG(4, "nfsrv_allocatedsdorpc: len=%jd\n", (intmax_t)len);
5697 
5698 	*tl = txdr_unsigned(NFSV4OP_GETATTR);
5699 	NFSGETATTR_ATTRBIT(&attrbits);
5700 	nfsrv_putattrbit(nd, &attrbits);
5701 	error = newnfs_request(nd, nmp, NULL, &nmp->nm_sockreq, NULL, p,
5702 	    cred, NFS_PROG, NFS_VER4, NULL, 1, NULL, NULL);
5703 	if (error != 0) {
5704 		free(nd, M_TEMP);
5705 		return (error);
5706 	}
5707 	NFSD_DEBUG(4, "nfsrv_allocatedsdorpc: aft allocaterpc=%d\n",
5708 	    nd->nd_repstat);
5709 	if (nd->nd_repstat == 0) {
5710 		NFSM_DISSECT(tl, uint32_t *, 2 * NFSX_UNSIGNED);
5711 		error = nfsv4_loadattr(nd, NULL, nap, NULL, NULL, 0, NULL, NULL,
5712 		    NULL, NULL, NULL, 0, NULL, NULL, NULL, NULL, NULL);
5713 	} else
5714 		error = nd->nd_repstat;
5715 	NFSD_DEBUG(4, "nfsrv_allocatedsdorpc: aft loadattr=%d\n", error);
5716 nfsmout:
5717 	m_freem(nd->nd_mrep);
5718 	free(nd, M_TEMP);
5719 	NFSD_DEBUG(4, "nfsrv_allocatedsdorpc error=%d\n", error);
5720 	return (error);
5721 }
5722 
5723 /*
5724  * Start up the thread that will execute nfsrv_allocatedsdorpc().
5725  */
5726 static void
5727 start_allocatedsdorpc(void *arg, int pending)
5728 {
5729 	struct nfsrvallocatedsdorpc *drpc;
5730 
5731 	drpc = (struct nfsrvallocatedsdorpc *)arg;
5732 	drpc->err = nfsrv_allocatedsdorpc(drpc->nmp, &drpc->fh, drpc->off,
5733 	    drpc->len, NULL, drpc->cred, drpc->p);
5734 	drpc->done = 1;
5735 	NFSD_DEBUG(4, "start_allocatedsdorpc: err=%d\n", drpc->err);
5736 }
5737 
5738 static int
5739 nfsrv_allocatedsrpc(fhandle_t *fhp, off_t off, off_t len, struct ucred *cred,
5740     NFSPROC_T *p, struct vnode *vp, struct nfsmount **nmpp, int mirrorcnt,
5741     int *failposp)
5742 {
5743 	struct nfsrvallocatedsdorpc *drpc, *tdrpc = NULL;
5744 	struct nfsvattr na;
5745 	int error, i, ret, timo;
5746 
5747 	NFSD_DEBUG(4, "in nfsrv_allocatedsrpc\n");
5748 	drpc = NULL;
5749 	if (mirrorcnt > 1)
5750 		tdrpc = drpc = malloc(sizeof(*drpc) * (mirrorcnt - 1), M_TEMP,
5751 		    M_WAITOK);
5752 
5753 	/*
5754 	 * Do the allocate RPC for every DS, using a separate kernel process
5755 	 * for every DS except the last one.
5756 	 */
5757 	error = 0;
5758 	for (i = 0; i < mirrorcnt - 1; i++, tdrpc++) {
5759 		tdrpc->done = 0;
5760 		NFSBCOPY(fhp, &tdrpc->fh, sizeof(*fhp));
5761 		tdrpc->off = off;
5762 		tdrpc->len = len;
5763 		tdrpc->nmp = *nmpp;
5764 		tdrpc->cred = cred;
5765 		tdrpc->p = p;
5766 		tdrpc->inprog = 0;
5767 		tdrpc->err = 0;
5768 		ret = EIO;
5769 		if (nfs_pnfsiothreads != 0) {
5770 			ret = nfs_pnfsio(start_allocatedsdorpc, tdrpc);
5771 			NFSD_DEBUG(4, "nfsrv_allocatedsrpc: nfs_pnfsio=%d\n",
5772 			    ret);
5773 		}
5774 		if (ret != 0) {
5775 			ret = nfsrv_allocatedsdorpc(*nmpp, fhp, off, len, NULL,
5776 			    cred, p);
5777 			if (nfsds_failerr(ret) && *failposp == -1)
5778 				*failposp = i;
5779 			else if (error == 0 && ret != 0)
5780 				error = ret;
5781 		}
5782 		nmpp++;
5783 		fhp++;
5784 	}
5785 	ret = nfsrv_allocatedsdorpc(*nmpp, fhp, off, len, &na, cred, p);
5786 	if (nfsds_failerr(ret) && *failposp == -1 && mirrorcnt > 1)
5787 		*failposp = mirrorcnt - 1;
5788 	else if (error == 0 && ret != 0)
5789 		error = ret;
5790 	if (error == 0)
5791 		error = nfsrv_setextattr(vp, &na, p);
5792 	NFSD_DEBUG(4, "nfsrv_allocatedsrpc: aft setextat=%d\n", error);
5793 	tdrpc = drpc;
5794 	timo = hz / 50;		/* Wait for 20msec. */
5795 	if (timo < 1)
5796 		timo = 1;
5797 	for (i = 0; i < mirrorcnt - 1; i++, tdrpc++) {
5798 		/* Wait for RPCs on separate threads to complete. */
5799 		while (tdrpc->inprog != 0 && tdrpc->done == 0)
5800 			tsleep(&tdrpc->tsk, PVFS, "srvalds", timo);
5801 		if (nfsds_failerr(tdrpc->err) && *failposp == -1)
5802 			*failposp = i;
5803 		else if (error == 0 && tdrpc->err != 0)
5804 			error = tdrpc->err;
5805 	}
5806 	free(drpc, M_TEMP);
5807 	return (error);
5808 }
5809 
5810 /*
5811  * Do a deallocate RPC on a DS data file, using this structure for the
5812  * arguments, so that this function can be executed by a separate kernel
5813  * process.
5814  */
5815 struct nfsrvdeallocatedsdorpc {
5816 	int			done;
5817 	int			inprog;
5818 	struct task		tsk;
5819 	fhandle_t		fh;
5820 	off_t			off;
5821 	off_t			len;
5822 	struct nfsmount		*nmp;
5823 	struct ucred		*cred;
5824 	NFSPROC_T		*p;
5825 	int			err;
5826 };
5827 
5828 static int
5829 nfsrv_deallocatedsdorpc(struct nfsmount *nmp, fhandle_t *fhp, off_t off,
5830     off_t len, struct nfsvattr *nap, struct ucred *cred, NFSPROC_T *p)
5831 {
5832 	uint32_t *tl;
5833 	struct nfsrv_descript *nd;
5834 	nfsattrbit_t attrbits;
5835 	nfsv4stateid_t st;
5836 	int error;
5837 
5838 	nd = malloc(sizeof(*nd), M_TEMP, M_WAITOK | M_ZERO);
5839 	nfscl_reqstart(nd, NFSPROC_DEALLOCATE, nmp, (u_int8_t *)fhp,
5840 	    sizeof(fhandle_t), NULL, NULL, 0, 0, cred);
5841 
5842 	/*
5843 	 * Use a stateid where other is an alternating 01010 pattern and
5844 	 * seqid is 0xffffffff.  This value is not defined as special by
5845 	 * the RFC and is used by the FreeBSD NFS server to indicate an
5846 	 * MDS->DS proxy operation.
5847 	 */
5848 	st.other[0] = 0x55555555;
5849 	st.other[1] = 0x55555555;
5850 	st.other[2] = 0x55555555;
5851 	st.seqid = 0xffffffff;
5852 	nfsm_stateidtom(nd, &st, NFSSTATEID_PUTSTATEID);
5853 	NFSM_BUILD(tl, uint32_t *, 2 * NFSX_HYPER + NFSX_UNSIGNED);
5854 	txdr_hyper(off, tl); tl += 2;
5855 	txdr_hyper(len, tl); tl += 2;
5856 	NFSD_DEBUG(4, "nfsrv_deallocatedsdorpc: len=%jd\n", (intmax_t)len);
5857 
5858 	/* Do a Getattr for the attributes that change upon writing. */
5859 	NFSZERO_ATTRBIT(&attrbits);
5860 	NFSSETBIT_ATTRBIT(&attrbits, NFSATTRBIT_SIZE);
5861 	NFSSETBIT_ATTRBIT(&attrbits, NFSATTRBIT_CHANGE);
5862 	NFSSETBIT_ATTRBIT(&attrbits, NFSATTRBIT_TIMEACCESS);
5863 	NFSSETBIT_ATTRBIT(&attrbits, NFSATTRBIT_TIMEMODIFY);
5864 	NFSSETBIT_ATTRBIT(&attrbits, NFSATTRBIT_SPACEUSED);
5865 	*tl = txdr_unsigned(NFSV4OP_GETATTR);
5866 	nfsrv_putattrbit(nd, &attrbits);
5867 	error = newnfs_request(nd, nmp, NULL, &nmp->nm_sockreq, NULL, p,
5868 	    cred, NFS_PROG, NFS_VER4, NULL, 1, NULL, NULL);
5869 	if (error != 0) {
5870 		free(nd, M_TEMP);
5871 		return (error);
5872 	}
5873 	NFSD_DEBUG(4, "nfsrv_deallocatedsdorpc: aft deallocaterpc=%d\n",
5874 	    nd->nd_repstat);
5875 	/* Get rid of weak cache consistency data for now. */
5876 	if ((nd->nd_flag & (ND_NOMOREDATA | ND_NFSV4 | ND_V4WCCATTR)) ==
5877 	    (ND_NFSV4 | ND_V4WCCATTR)) {
5878 		error = nfsv4_loadattr(nd, NULL, nap, NULL, NULL, 0, NULL, NULL,
5879 		    NULL, NULL, NULL, 0, NULL, NULL, NULL, NULL, NULL);
5880 		NFSD_DEBUG(4, "nfsrv_deallocatedsdorpc: wcc attr=%d\n", error);
5881 		if (error != 0)
5882 			goto nfsmout;
5883 		/*
5884 		 * Get rid of Op# and status for next op.
5885 		 */
5886 		NFSM_DISSECT(tl, uint32_t *, 2 * NFSX_UNSIGNED);
5887 		if (*++tl != 0)
5888 			nd->nd_flag |= ND_NOMOREDATA;
5889 	}
5890 	if (nd->nd_repstat == 0) {
5891 		NFSM_DISSECT(tl, uint32_t *, 2 * NFSX_UNSIGNED);
5892 		error = nfsv4_loadattr(nd, NULL, nap, NULL, NULL, 0, NULL, NULL,
5893 		    NULL, NULL, NULL, 0, NULL, NULL, NULL, NULL, NULL);
5894 	} else
5895 		error = nd->nd_repstat;
5896 	NFSD_DEBUG(4, "nfsrv_deallocatedsdorpc: aft loadattr=%d\n", error);
5897 nfsmout:
5898 	m_freem(nd->nd_mrep);
5899 	free(nd, M_TEMP);
5900 	NFSD_DEBUG(4, "nfsrv_deallocatedsdorpc error=%d\n", error);
5901 	return (error);
5902 }
5903 
5904 /*
5905  * Start up the thread that will execute nfsrv_deallocatedsdorpc().
5906  */
5907 static void
5908 start_deallocatedsdorpc(void *arg, int pending)
5909 {
5910 	struct nfsrvdeallocatedsdorpc *drpc;
5911 
5912 	drpc = (struct nfsrvdeallocatedsdorpc *)arg;
5913 	drpc->err = nfsrv_deallocatedsdorpc(drpc->nmp, &drpc->fh, drpc->off,
5914 	    drpc->len, NULL, drpc->cred, drpc->p);
5915 	drpc->done = 1;
5916 	NFSD_DEBUG(4, "start_deallocatedsdorpc: err=%d\n", drpc->err);
5917 }
5918 
5919 static int
5920 nfsrv_deallocatedsrpc(fhandle_t *fhp, off_t off, off_t len, struct ucred *cred,
5921     NFSPROC_T *p, struct vnode *vp, struct nfsmount **nmpp, int mirrorcnt,
5922     int *failposp)
5923 {
5924 	struct nfsrvdeallocatedsdorpc *drpc, *tdrpc = NULL;
5925 	struct nfsvattr na;
5926 	int error, i, ret, timo;
5927 
5928 	NFSD_DEBUG(4, "in nfsrv_deallocatedsrpc\n");
5929 	drpc = NULL;
5930 	if (mirrorcnt > 1)
5931 		tdrpc = drpc = malloc(sizeof(*drpc) * (mirrorcnt - 1), M_TEMP,
5932 		    M_WAITOK);
5933 
5934 	/*
5935 	 * Do the deallocate RPC for every DS, using a separate kernel process
5936 	 * for every DS except the last one.
5937 	 */
5938 	error = 0;
5939 	for (i = 0; i < mirrorcnt - 1; i++, tdrpc++) {
5940 		tdrpc->done = 0;
5941 		NFSBCOPY(fhp, &tdrpc->fh, sizeof(*fhp));
5942 		tdrpc->off = off;
5943 		tdrpc->len = len;
5944 		tdrpc->nmp = *nmpp;
5945 		tdrpc->cred = cred;
5946 		tdrpc->p = p;
5947 		tdrpc->inprog = 0;
5948 		tdrpc->err = 0;
5949 		ret = EIO;
5950 		if (nfs_pnfsiothreads != 0) {
5951 			ret = nfs_pnfsio(start_deallocatedsdorpc, tdrpc);
5952 			NFSD_DEBUG(4, "nfsrv_deallocatedsrpc: nfs_pnfsio=%d\n",
5953 			    ret);
5954 		}
5955 		if (ret != 0) {
5956 			ret = nfsrv_deallocatedsdorpc(*nmpp, fhp, off, len,
5957 			    NULL, cred, p);
5958 			if (nfsds_failerr(ret) && *failposp == -1)
5959 				*failposp = i;
5960 			else if (error == 0 && ret != 0)
5961 				error = ret;
5962 		}
5963 		nmpp++;
5964 		fhp++;
5965 	}
5966 	ret = nfsrv_deallocatedsdorpc(*nmpp, fhp, off, len, &na, cred, p);
5967 	if (nfsds_failerr(ret) && *failposp == -1 && mirrorcnt > 1)
5968 		*failposp = mirrorcnt - 1;
5969 	else if (error == 0 && ret != 0)
5970 		error = ret;
5971 	if (error == 0)
5972 		error = nfsrv_setextattr(vp, &na, p);
5973 	NFSD_DEBUG(4, "nfsrv_deallocatedsrpc: aft setextat=%d\n", error);
5974 	tdrpc = drpc;
5975 	timo = hz / 50;		/* Wait for 20msec. */
5976 	if (timo < 1)
5977 		timo = 1;
5978 	for (i = 0; i < mirrorcnt - 1; i++, tdrpc++) {
5979 		/* Wait for RPCs on separate threads to complete. */
5980 		while (tdrpc->inprog != 0 && tdrpc->done == 0)
5981 			tsleep(&tdrpc->tsk, PVFS, "srvalds", timo);
5982 		if (nfsds_failerr(tdrpc->err) && *failposp == -1)
5983 			*failposp = i;
5984 		else if (error == 0 && tdrpc->err != 0)
5985 			error = tdrpc->err;
5986 	}
5987 	free(drpc, M_TEMP);
5988 	return (error);
5989 }
5990 
5991 static int
5992 nfsrv_setattrdsdorpc(fhandle_t *fhp, struct ucred *cred, NFSPROC_T *p,
5993     struct vnode *vp, struct nfsmount *nmp, struct nfsvattr *nap,
5994     struct nfsvattr *dsnap)
5995 {
5996 	uint32_t *tl;
5997 	struct nfsrv_descript *nd;
5998 	nfsv4stateid_t st;
5999 	nfsattrbit_t attrbits;
6000 	int error;
6001 
6002 	NFSD_DEBUG(4, "in nfsrv_setattrdsdorpc\n");
6003 	nd = malloc(sizeof(*nd), M_TEMP, M_WAITOK | M_ZERO);
6004 	/*
6005 	 * Use a stateid where other is an alternating 01010 pattern and
6006 	 * seqid is 0xffffffff.  This value is not defined as special by
6007 	 * the RFC and is used by the FreeBSD NFS server to indicate an
6008 	 * MDS->DS proxy operation.
6009 	 */
6010 	st.other[0] = 0x55555555;
6011 	st.other[1] = 0x55555555;
6012 	st.other[2] = 0x55555555;
6013 	st.seqid = 0xffffffff;
6014 	nfscl_reqstart(nd, NFSPROC_SETATTR, nmp, (u_int8_t *)fhp, sizeof(*fhp),
6015 	    NULL, NULL, 0, 0, cred);
6016 	nfsm_stateidtom(nd, &st, NFSSTATEID_PUTSTATEID);
6017 	nfscl_fillsattr(nd, &nap->na_vattr, vp, NFSSATTR_FULL, 0);
6018 
6019 	/* Do a Getattr for the attributes that change due to writing. */
6020 	NFSZERO_ATTRBIT(&attrbits);
6021 	NFSSETBIT_ATTRBIT(&attrbits, NFSATTRBIT_SIZE);
6022 	NFSSETBIT_ATTRBIT(&attrbits, NFSATTRBIT_CHANGE);
6023 	NFSSETBIT_ATTRBIT(&attrbits, NFSATTRBIT_TIMEACCESS);
6024 	NFSSETBIT_ATTRBIT(&attrbits, NFSATTRBIT_TIMEMODIFY);
6025 	NFSSETBIT_ATTRBIT(&attrbits, NFSATTRBIT_SPACEUSED);
6026 	NFSM_BUILD(tl, u_int32_t *, NFSX_UNSIGNED);
6027 	*tl = txdr_unsigned(NFSV4OP_GETATTR);
6028 	(void) nfsrv_putattrbit(nd, &attrbits);
6029 	error = newnfs_request(nd, nmp, NULL, &nmp->nm_sockreq, NULL, p, cred,
6030 	    NFS_PROG, NFS_VER4, NULL, 1, NULL, NULL);
6031 	if (error != 0) {
6032 		free(nd, M_TEMP);
6033 		return (error);
6034 	}
6035 	NFSD_DEBUG(4, "nfsrv_setattrdsdorpc: aft setattrrpc=%d\n",
6036 	    nd->nd_repstat);
6037 	/* Get rid of weak cache consistency data for now. */
6038 	if ((nd->nd_flag & (ND_NOMOREDATA | ND_NFSV4 | ND_V4WCCATTR)) ==
6039 	    (ND_NFSV4 | ND_V4WCCATTR)) {
6040 		error = nfsv4_loadattr(nd, NULL, dsnap, NULL, NULL, 0, NULL,
6041 		    NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL, NULL, NULL);
6042 		NFSD_DEBUG(4, "nfsrv_setattrdsdorpc: wcc attr=%d\n", error);
6043 		if (error != 0)
6044 			goto nfsmout;
6045 		/*
6046 		 * Get rid of Op# and status for next op.
6047 		 */
6048 		NFSM_DISSECT(tl, uint32_t *, 2 * NFSX_UNSIGNED);
6049 		if (*++tl != 0)
6050 			nd->nd_flag |= ND_NOMOREDATA;
6051 	}
6052 	error = nfsrv_getattrbits(nd, &attrbits, NULL, NULL);
6053 	if (error != 0)
6054 		goto nfsmout;
6055 	if (nd->nd_repstat != 0)
6056 		error = nd->nd_repstat;
6057 	/*
6058 	 * Get the Change, Size, Access Time and Modify Time attributes and set
6059 	 * on the Metadata file, so its attributes will be what the file's
6060 	 * would be if it had been written.
6061 	 */
6062 	if (error == 0) {
6063 		NFSM_DISSECT(tl, uint32_t *, 2 * NFSX_UNSIGNED);
6064 		error = nfsv4_loadattr(nd, NULL, dsnap, NULL, NULL, 0, NULL,
6065 		    NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL, NULL, NULL);
6066 	}
6067 	NFSD_DEBUG(4, "nfsrv_setattrdsdorpc: aft setattr loadattr=%d\n", error);
6068 nfsmout:
6069 	m_freem(nd->nd_mrep);
6070 	free(nd, M_TEMP);
6071 	NFSD_DEBUG(4, "nfsrv_setattrdsdorpc error=%d\n", error);
6072 	return (error);
6073 }
6074 
6075 struct nfsrvsetattrdsdorpc {
6076 	int			done;
6077 	int			inprog;
6078 	struct task		tsk;
6079 	fhandle_t		fh;
6080 	struct nfsmount		*nmp;
6081 	struct vnode		*vp;
6082 	struct ucred		*cred;
6083 	NFSPROC_T		*p;
6084 	struct nfsvattr		na;
6085 	struct nfsvattr		dsna;
6086 	int			err;
6087 };
6088 
6089 /*
6090  * Start up the thread that will execute nfsrv_setattrdsdorpc().
6091  */
6092 static void
6093 start_setattrdsdorpc(void *arg, int pending)
6094 {
6095 	struct nfsrvsetattrdsdorpc *drpc;
6096 
6097 	drpc = (struct nfsrvsetattrdsdorpc *)arg;
6098 	drpc->err = nfsrv_setattrdsdorpc(&drpc->fh, drpc->cred, drpc->p,
6099 	    drpc->vp, drpc->nmp, &drpc->na, &drpc->dsna);
6100 	drpc->done = 1;
6101 }
6102 
6103 static int
6104 nfsrv_setattrdsrpc(fhandle_t *fhp, struct ucred *cred, NFSPROC_T *p,
6105     struct vnode *vp, struct nfsmount **nmpp, int mirrorcnt,
6106     struct nfsvattr *nap, int *failposp)
6107 {
6108 	struct nfsrvsetattrdsdorpc *drpc, *tdrpc = NULL;
6109 	struct nfsvattr na;
6110 	int error, i, ret, timo;
6111 
6112 	NFSD_DEBUG(4, "in nfsrv_setattrdsrpc\n");
6113 	drpc = NULL;
6114 	if (mirrorcnt > 1)
6115 		tdrpc = drpc = malloc(sizeof(*drpc) * (mirrorcnt - 1), M_TEMP,
6116 		    M_WAITOK);
6117 
6118 	/*
6119 	 * Do the setattr RPC for every DS, using a separate kernel process
6120 	 * for every DS except the last one.
6121 	 */
6122 	error = 0;
6123 	for (i = 0; i < mirrorcnt - 1; i++, tdrpc++) {
6124 		tdrpc->done = 0;
6125 		tdrpc->inprog = 0;
6126 		NFSBCOPY(fhp, &tdrpc->fh, sizeof(*fhp));
6127 		tdrpc->nmp = *nmpp;
6128 		tdrpc->vp = vp;
6129 		tdrpc->cred = cred;
6130 		tdrpc->p = p;
6131 		tdrpc->na = *nap;
6132 		tdrpc->err = 0;
6133 		ret = EIO;
6134 		if (nfs_pnfsiothreads != 0) {
6135 			ret = nfs_pnfsio(start_setattrdsdorpc, tdrpc);
6136 			NFSD_DEBUG(4, "nfsrv_setattrdsrpc: nfs_pnfsio=%d\n",
6137 			    ret);
6138 		}
6139 		if (ret != 0) {
6140 			ret = nfsrv_setattrdsdorpc(fhp, cred, p, vp, *nmpp, nap,
6141 			    &na);
6142 			if (nfsds_failerr(ret) && *failposp == -1)
6143 				*failposp = i;
6144 			else if (error == 0 && ret != 0)
6145 				error = ret;
6146 		}
6147 		nmpp++;
6148 		fhp++;
6149 	}
6150 	ret = nfsrv_setattrdsdorpc(fhp, cred, p, vp, *nmpp, nap, &na);
6151 	if (nfsds_failerr(ret) && *failposp == -1 && mirrorcnt > 1)
6152 		*failposp = mirrorcnt - 1;
6153 	else if (error == 0 && ret != 0)
6154 		error = ret;
6155 	if (error == 0)
6156 		error = nfsrv_setextattr(vp, &na, p);
6157 	NFSD_DEBUG(4, "nfsrv_setattrdsrpc: aft setextat=%d\n", error);
6158 	tdrpc = drpc;
6159 	timo = hz / 50;		/* Wait for 20msec. */
6160 	if (timo < 1)
6161 		timo = 1;
6162 	for (i = 0; i < mirrorcnt - 1; i++, tdrpc++) {
6163 		/* Wait for RPCs on separate threads to complete. */
6164 		while (tdrpc->inprog != 0 && tdrpc->done == 0)
6165 			tsleep(&tdrpc->tsk, PVFS, "srvsads", timo);
6166 		if (nfsds_failerr(tdrpc->err) && *failposp == -1)
6167 			*failposp = i;
6168 		else if (error == 0 && tdrpc->err != 0)
6169 			error = tdrpc->err;
6170 	}
6171 	free(drpc, M_TEMP);
6172 	return (error);
6173 }
6174 
6175 /*
6176  * Do a Setattr of an NFSv4 ACL on the DS file.
6177  */
6178 static int
6179 nfsrv_setacldsdorpc(fhandle_t *fhp, struct ucred *cred, NFSPROC_T *p,
6180     struct vnode *vp, struct nfsmount *nmp, struct acl *aclp)
6181 {
6182 	struct nfsrv_descript *nd;
6183 	nfsv4stateid_t st;
6184 	nfsattrbit_t attrbits;
6185 	int error;
6186 
6187 	NFSD_DEBUG(4, "in nfsrv_setacldsdorpc\n");
6188 	nd = malloc(sizeof(*nd), M_TEMP, M_WAITOK | M_ZERO);
6189 	/*
6190 	 * Use a stateid where other is an alternating 01010 pattern and
6191 	 * seqid is 0xffffffff.  This value is not defined as special by
6192 	 * the RFC and is used by the FreeBSD NFS server to indicate an
6193 	 * MDS->DS proxy operation.
6194 	 */
6195 	st.other[0] = 0x55555555;
6196 	st.other[1] = 0x55555555;
6197 	st.other[2] = 0x55555555;
6198 	st.seqid = 0xffffffff;
6199 	nfscl_reqstart(nd, NFSPROC_SETACL, nmp, (u_int8_t *)fhp, sizeof(*fhp),
6200 	    NULL, NULL, 0, 0, cred);
6201 	nfsm_stateidtom(nd, &st, NFSSTATEID_PUTSTATEID);
6202 	NFSZERO_ATTRBIT(&attrbits);
6203 	NFSSETBIT_ATTRBIT(&attrbits, NFSATTRBIT_ACL);
6204 	/*
6205 	 * The "vp" argument to nfsv4_fillattr() is only used for vnode_type(),
6206 	 * so passing in the metadata "vp" will be ok, since it is of
6207 	 * the same type (VREG).
6208 	 */
6209 	nfsv4_fillattr(nd, NULL, vp, aclp, NULL, NULL, 0, &attrbits, NULL,
6210 	    NULL, 0, 0, 0, 0, 0, NULL);
6211 	error = newnfs_request(nd, nmp, NULL, &nmp->nm_sockreq, NULL, p, cred,
6212 	    NFS_PROG, NFS_VER4, NULL, 1, NULL, NULL);
6213 	if (error != 0) {
6214 		free(nd, M_TEMP);
6215 		return (error);
6216 	}
6217 	NFSD_DEBUG(4, "nfsrv_setacldsdorpc: aft setaclrpc=%d\n",
6218 	    nd->nd_repstat);
6219 	error = nd->nd_repstat;
6220 	m_freem(nd->nd_mrep);
6221 	free(nd, M_TEMP);
6222 	return (error);
6223 }
6224 
6225 struct nfsrvsetacldsdorpc {
6226 	int			done;
6227 	int			inprog;
6228 	struct task		tsk;
6229 	fhandle_t		fh;
6230 	struct nfsmount		*nmp;
6231 	struct vnode		*vp;
6232 	struct ucred		*cred;
6233 	NFSPROC_T		*p;
6234 	struct acl		*aclp;
6235 	int			err;
6236 };
6237 
6238 /*
6239  * Start up the thread that will execute nfsrv_setacldsdorpc().
6240  */
6241 static void
6242 start_setacldsdorpc(void *arg, int pending)
6243 {
6244 	struct nfsrvsetacldsdorpc *drpc;
6245 
6246 	drpc = (struct nfsrvsetacldsdorpc *)arg;
6247 	drpc->err = nfsrv_setacldsdorpc(&drpc->fh, drpc->cred, drpc->p,
6248 	    drpc->vp, drpc->nmp, drpc->aclp);
6249 	drpc->done = 1;
6250 }
6251 
6252 static int
6253 nfsrv_setacldsrpc(fhandle_t *fhp, struct ucred *cred, NFSPROC_T *p,
6254     struct vnode *vp, struct nfsmount **nmpp, int mirrorcnt, struct acl *aclp,
6255     int *failposp)
6256 {
6257 	struct nfsrvsetacldsdorpc *drpc, *tdrpc = NULL;
6258 	int error, i, ret, timo;
6259 
6260 	NFSD_DEBUG(4, "in nfsrv_setacldsrpc\n");
6261 	drpc = NULL;
6262 	if (mirrorcnt > 1)
6263 		tdrpc = drpc = malloc(sizeof(*drpc) * (mirrorcnt - 1), M_TEMP,
6264 		    M_WAITOK);
6265 
6266 	/*
6267 	 * Do the setattr RPC for every DS, using a separate kernel process
6268 	 * for every DS except the last one.
6269 	 */
6270 	error = 0;
6271 	for (i = 0; i < mirrorcnt - 1; i++, tdrpc++) {
6272 		tdrpc->done = 0;
6273 		tdrpc->inprog = 0;
6274 		NFSBCOPY(fhp, &tdrpc->fh, sizeof(*fhp));
6275 		tdrpc->nmp = *nmpp;
6276 		tdrpc->vp = vp;
6277 		tdrpc->cred = cred;
6278 		tdrpc->p = p;
6279 		tdrpc->aclp = aclp;
6280 		tdrpc->err = 0;
6281 		ret = EIO;
6282 		if (nfs_pnfsiothreads != 0) {
6283 			ret = nfs_pnfsio(start_setacldsdorpc, tdrpc);
6284 			NFSD_DEBUG(4, "nfsrv_setacldsrpc: nfs_pnfsio=%d\n",
6285 			    ret);
6286 		}
6287 		if (ret != 0) {
6288 			ret = nfsrv_setacldsdorpc(fhp, cred, p, vp, *nmpp,
6289 			    aclp);
6290 			if (nfsds_failerr(ret) && *failposp == -1)
6291 				*failposp = i;
6292 			else if (error == 0 && ret != 0)
6293 				error = ret;
6294 		}
6295 		nmpp++;
6296 		fhp++;
6297 	}
6298 	ret = nfsrv_setacldsdorpc(fhp, cred, p, vp, *nmpp, aclp);
6299 	if (nfsds_failerr(ret) && *failposp == -1 && mirrorcnt > 1)
6300 		*failposp = mirrorcnt - 1;
6301 	else if (error == 0 && ret != 0)
6302 		error = ret;
6303 	NFSD_DEBUG(4, "nfsrv_setacldsrpc: aft setextat=%d\n", error);
6304 	tdrpc = drpc;
6305 	timo = hz / 50;		/* Wait for 20msec. */
6306 	if (timo < 1)
6307 		timo = 1;
6308 	for (i = 0; i < mirrorcnt - 1; i++, tdrpc++) {
6309 		/* Wait for RPCs on separate threads to complete. */
6310 		while (tdrpc->inprog != 0 && tdrpc->done == 0)
6311 			tsleep(&tdrpc->tsk, PVFS, "srvacds", timo);
6312 		if (nfsds_failerr(tdrpc->err) && *failposp == -1)
6313 			*failposp = i;
6314 		else if (error == 0 && tdrpc->err != 0)
6315 			error = tdrpc->err;
6316 	}
6317 	free(drpc, M_TEMP);
6318 	return (error);
6319 }
6320 
6321 /*
6322  * Getattr call to the DS for the attributes that change due to writing.
6323  */
6324 static int
6325 nfsrv_getattrdsrpc(fhandle_t *fhp, struct ucred *cred, NFSPROC_T *p,
6326     struct vnode *vp, struct nfsmount *nmp, struct nfsvattr *nap)
6327 {
6328 	struct nfsrv_descript *nd;
6329 	int error;
6330 	nfsattrbit_t attrbits;
6331 
6332 	NFSD_DEBUG(4, "in nfsrv_getattrdsrpc\n");
6333 	nd = malloc(sizeof(*nd), M_TEMP, M_WAITOK | M_ZERO);
6334 	nfscl_reqstart(nd, NFSPROC_GETATTR, nmp, (u_int8_t *)fhp,
6335 	    sizeof(fhandle_t), NULL, NULL, 0, 0, cred);
6336 	NFSZERO_ATTRBIT(&attrbits);
6337 	NFSSETBIT_ATTRBIT(&attrbits, NFSATTRBIT_SIZE);
6338 	NFSSETBIT_ATTRBIT(&attrbits, NFSATTRBIT_CHANGE);
6339 	NFSSETBIT_ATTRBIT(&attrbits, NFSATTRBIT_TIMEACCESS);
6340 	NFSSETBIT_ATTRBIT(&attrbits, NFSATTRBIT_TIMEMODIFY);
6341 	NFSSETBIT_ATTRBIT(&attrbits, NFSATTRBIT_SPACEUSED);
6342 	(void) nfsrv_putattrbit(nd, &attrbits);
6343 	error = newnfs_request(nd, nmp, NULL, &nmp->nm_sockreq, NULL, p, cred,
6344 	    NFS_PROG, NFS_VER4, NULL, 1, NULL, NULL);
6345 	if (error != 0) {
6346 		free(nd, M_TEMP);
6347 		return (error);
6348 	}
6349 	NFSD_DEBUG(4, "nfsrv_getattrdsrpc: aft getattrrpc=%d\n",
6350 	    nd->nd_repstat);
6351 	if (nd->nd_repstat == 0) {
6352 		error = nfsv4_loadattr(nd, NULL, nap, NULL, NULL, 0,
6353 		    NULL, NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL,
6354 		    NULL, NULL);
6355 		/*
6356 		 * We can only save the updated values in the extended
6357 		 * attribute if the vp is exclusively locked.
6358 		 * This should happen when any of the following operations
6359 		 * occur on the vnode:
6360 		 *    Close, Delegreturn, LayoutCommit, LayoutReturn
6361 		 * As such, the updated extended attribute should get saved
6362 		 * before nfsrv_checkdsattr() returns 0 and allows the cached
6363 		 * attributes to be returned without calling this function.
6364 		 */
6365 		if (error == 0 && VOP_ISLOCKED(vp) == LK_EXCLUSIVE) {
6366 			error = nfsrv_setextattr(vp, nap, p);
6367 			NFSD_DEBUG(4, "nfsrv_getattrdsrpc: aft setextat=%d\n",
6368 			    error);
6369 		}
6370 	} else
6371 		error = nd->nd_repstat;
6372 	m_freem(nd->nd_mrep);
6373 	free(nd, M_TEMP);
6374 	NFSD_DEBUG(4, "nfsrv_getattrdsrpc error=%d\n", error);
6375 	return (error);
6376 }
6377 
6378 /*
6379  * Seek call to a DS.
6380  */
6381 static int
6382 nfsrv_seekdsrpc(fhandle_t *fhp, off_t *offp, int content, bool *eofp,
6383     struct ucred *cred, NFSPROC_T *p, struct nfsmount *nmp)
6384 {
6385 	uint32_t *tl;
6386 	struct nfsrv_descript *nd;
6387 	nfsv4stateid_t st;
6388 	int error;
6389 
6390 	NFSD_DEBUG(4, "in nfsrv_seekdsrpc\n");
6391 	/*
6392 	 * Use a stateid where other is an alternating 01010 pattern and
6393 	 * seqid is 0xffffffff.  This value is not defined as special by
6394 	 * the RFC and is used by the FreeBSD NFS server to indicate an
6395 	 * MDS->DS proxy operation.
6396 	 */
6397 	st.other[0] = 0x55555555;
6398 	st.other[1] = 0x55555555;
6399 	st.other[2] = 0x55555555;
6400 	st.seqid = 0xffffffff;
6401 	nd = malloc(sizeof(*nd), M_TEMP, M_WAITOK | M_ZERO);
6402 	nfscl_reqstart(nd, NFSPROC_SEEKDS, nmp, (u_int8_t *)fhp,
6403 	    sizeof(fhandle_t), NULL, NULL, 0, 0, cred);
6404 	nfsm_stateidtom(nd, &st, NFSSTATEID_PUTSTATEID);
6405 	NFSM_BUILD(tl, uint32_t *, NFSX_HYPER + NFSX_UNSIGNED);
6406 	txdr_hyper(*offp, tl); tl += 2;
6407 	*tl = txdr_unsigned(content);
6408 	error = newnfs_request(nd, nmp, NULL, &nmp->nm_sockreq, NULL, p, cred,
6409 	    NFS_PROG, NFS_VER4, NULL, 1, NULL, NULL);
6410 	if (error != 0) {
6411 		free(nd, M_TEMP);
6412 		return (error);
6413 	}
6414 	NFSD_DEBUG(4, "nfsrv_seekdsrpc: aft seekrpc=%d\n", nd->nd_repstat);
6415 	if (nd->nd_repstat == 0) {
6416 		NFSM_DISSECT(tl, uint32_t *, NFSX_UNSIGNED + NFSX_HYPER);
6417 		if (*tl++ == newnfs_true)
6418 			*eofp = true;
6419 		else
6420 			*eofp = false;
6421 		*offp = fxdr_hyper(tl);
6422 	} else
6423 		error = nd->nd_repstat;
6424 nfsmout:
6425 	m_freem(nd->nd_mrep);
6426 	free(nd, M_TEMP);
6427 	NFSD_DEBUG(4, "nfsrv_seekdsrpc error=%d\n", error);
6428 	return (error);
6429 }
6430 
6431 /*
6432  * Get the device id and file handle for a DS file.
6433  */
6434 int
6435 nfsrv_dsgetdevandfh(struct vnode *vp, NFSPROC_T *p, int *mirrorcntp,
6436     fhandle_t *fhp, char *devid)
6437 {
6438 	int buflen, error;
6439 	char *buf;
6440 
6441 	buflen = 1024;
6442 	buf = malloc(buflen, M_TEMP, M_WAITOK);
6443 	error = nfsrv_dsgetsockmnt(vp, 0, buf, &buflen, mirrorcntp, p, NULL,
6444 	    fhp, devid, NULL, NULL, NULL, NULL, NULL, NULL);
6445 	free(buf, M_TEMP);
6446 	return (error);
6447 }
6448 
6449 /*
6450  * Do a Lookup against the DS for the filename.
6451  */
6452 static int
6453 nfsrv_pnfslookupds(struct vnode *vp, struct vnode *dvp, struct pnfsdsfile *pf,
6454     struct vnode **nvpp, NFSPROC_T *p)
6455 {
6456 	struct nameidata named;
6457 	struct ucred *tcred;
6458 	char *bufp;
6459 	u_long *hashp;
6460 	struct vnode *nvp;
6461 	int error;
6462 
6463 	tcred = newnfs_getcred();
6464 	named.ni_cnd.cn_nameiop = LOOKUP;
6465 	named.ni_cnd.cn_lkflags = LK_SHARED | LK_RETRY;
6466 	named.ni_cnd.cn_cred = tcred;
6467 	named.ni_cnd.cn_flags = ISLASTCN | LOCKPARENT | LOCKLEAF;
6468 	nfsvno_setpathbuf(&named, &bufp, &hashp);
6469 	named.ni_cnd.cn_nameptr = bufp;
6470 	named.ni_cnd.cn_namelen = strlen(pf->dsf_filename);
6471 	strlcpy(bufp, pf->dsf_filename, NAME_MAX);
6472 	NFSD_DEBUG(4, "nfsrv_pnfslookupds: filename=%s\n", bufp);
6473 	error = VOP_LOOKUP(dvp, &nvp, &named.ni_cnd);
6474 	NFSD_DEBUG(4, "nfsrv_pnfslookupds: aft LOOKUP=%d\n", error);
6475 	NFSFREECRED(tcred);
6476 	nfsvno_relpathbuf(&named);
6477 	if (error == 0)
6478 		*nvpp = nvp;
6479 	NFSD_DEBUG(4, "eo nfsrv_pnfslookupds=%d\n", error);
6480 	return (error);
6481 }
6482 
6483 /*
6484  * Set the file handle to the correct one.
6485  */
6486 static void
6487 nfsrv_pnfssetfh(struct vnode *vp, struct pnfsdsfile *pf, char *devid,
6488     char *fnamep, struct vnode *nvp, NFSPROC_T *p)
6489 {
6490 	struct nfsnode *np;
6491 	int ret = 0;
6492 
6493 	np = VTONFS(nvp);
6494 	NFSBCOPY(np->n_fhp->nfh_fh, &pf->dsf_fh, NFSX_MYFH);
6495 	/*
6496 	 * We can only do a vn_set_extattr() if the vnode is exclusively
6497 	 * locked and vn_start_write() has been done.  If devid != NULL or
6498 	 * fnamep != NULL or the vnode is shared locked, vn_start_write()
6499 	 * may not have been done.
6500 	 * If not done now, it will be done on a future call.
6501 	 */
6502 	if (devid == NULL && fnamep == NULL && NFSVOPISLOCKED(vp) ==
6503 	    LK_EXCLUSIVE)
6504 		ret = vn_extattr_set(vp, IO_NODELOCKED,
6505 		    EXTATTR_NAMESPACE_SYSTEM, "pnfsd.dsfile", sizeof(*pf),
6506 		    (char *)pf, p);
6507 	NFSD_DEBUG(4, "eo nfsrv_pnfssetfh=%d\n", ret);
6508 }
6509 
6510 /*
6511  * Cause RPCs waiting on "nmp" to fail.  This is called for a DS mount point
6512  * when the DS has failed.
6513  */
6514 void
6515 nfsrv_killrpcs(struct nfsmount *nmp)
6516 {
6517 
6518 	/*
6519 	 * Call newnfs_nmcancelreqs() to cause
6520 	 * any RPCs in progress on the mount point to
6521 	 * fail.
6522 	 * This will cause any process waiting for an
6523 	 * RPC to complete while holding a vnode lock
6524 	 * on the mounted-on vnode (such as "df" or
6525 	 * a non-forced "umount") to fail.
6526 	 * This will unlock the mounted-on vnode so
6527 	 * a forced dismount can succeed.
6528 	 * The NFSMNTP_CANCELRPCS flag should be set when this function is
6529 	 * called.
6530 	 */
6531 	newnfs_nmcancelreqs(nmp);
6532 }
6533 
6534 /*
6535  * Sum up the statfs info for each of the DSs, so that the client will
6536  * receive the total for all DSs.
6537  */
6538 static int
6539 nfsrv_pnfsstatfs(struct statfs *sf, struct mount *mp)
6540 {
6541 	struct statfs *tsf;
6542 	struct nfsdevice *ds;
6543 	struct vnode **dvpp, **tdvpp, *dvp;
6544 	uint64_t tot;
6545 	int cnt, error = 0, i;
6546 
6547 	if (nfsrv_devidcnt <= 0)
6548 		return (ENXIO);
6549 	dvpp = mallocarray(nfsrv_devidcnt, sizeof(*dvpp), M_TEMP, M_WAITOK);
6550 	tsf = malloc(sizeof(*tsf), M_TEMP, M_WAITOK);
6551 
6552 	/* Get an array of the dvps for the DSs. */
6553 	tdvpp = dvpp;
6554 	i = 0;
6555 	NFSDDSLOCK();
6556 	/* First, search for matches for same file system. */
6557 	TAILQ_FOREACH(ds, &nfsrv_devidhead, nfsdev_list) {
6558 		if (ds->nfsdev_nmp != NULL && ds->nfsdev_mdsisset != 0 &&
6559 		    fsidcmp(&ds->nfsdev_mdsfsid, &mp->mnt_stat.f_fsid) == 0) {
6560 			if (++i > nfsrv_devidcnt)
6561 				break;
6562 			*tdvpp++ = ds->nfsdev_dvp;
6563 		}
6564 	}
6565 	/*
6566 	 * If no matches for same file system, total all servers not assigned
6567 	 * to a file system.
6568 	 */
6569 	if (i == 0) {
6570 		TAILQ_FOREACH(ds, &nfsrv_devidhead, nfsdev_list) {
6571 			if (ds->nfsdev_nmp != NULL &&
6572 			    ds->nfsdev_mdsisset == 0) {
6573 				if (++i > nfsrv_devidcnt)
6574 					break;
6575 				*tdvpp++ = ds->nfsdev_dvp;
6576 			}
6577 		}
6578 	}
6579 	NFSDDSUNLOCK();
6580 	cnt = i;
6581 
6582 	/* Do a VFS_STATFS() for each of the DSs and sum them up. */
6583 	tdvpp = dvpp;
6584 	for (i = 0; i < cnt && error == 0; i++) {
6585 		dvp = *tdvpp++;
6586 		error = VFS_STATFS(dvp->v_mount, tsf);
6587 		if (error == 0) {
6588 			if (sf->f_bsize == 0) {
6589 				if (tsf->f_bsize > 0)
6590 					sf->f_bsize = tsf->f_bsize;
6591 				else
6592 					sf->f_bsize = 8192;
6593 			}
6594 			if (tsf->f_blocks > 0) {
6595 				if (sf->f_bsize != tsf->f_bsize) {
6596 					tot = tsf->f_blocks * tsf->f_bsize;
6597 					sf->f_blocks += (tot / sf->f_bsize);
6598 				} else
6599 					sf->f_blocks += tsf->f_blocks;
6600 			}
6601 			if (tsf->f_bfree > 0) {
6602 				if (sf->f_bsize != tsf->f_bsize) {
6603 					tot = tsf->f_bfree * tsf->f_bsize;
6604 					sf->f_bfree += (tot / sf->f_bsize);
6605 				} else
6606 					sf->f_bfree += tsf->f_bfree;
6607 			}
6608 			if (tsf->f_bavail > 0) {
6609 				if (sf->f_bsize != tsf->f_bsize) {
6610 					tot = tsf->f_bavail * tsf->f_bsize;
6611 					sf->f_bavail += (tot / sf->f_bsize);
6612 				} else
6613 					sf->f_bavail += tsf->f_bavail;
6614 			}
6615 		}
6616 	}
6617 	free(tsf, M_TEMP);
6618 	free(dvpp, M_TEMP);
6619 	return (error);
6620 }
6621 
6622 /*
6623  * Set an NFSv4 acl.
6624  */
6625 int
6626 nfsrv_setacl(struct vnode *vp, NFSACL_T *aclp, struct ucred *cred, NFSPROC_T *p)
6627 {
6628 	int error;
6629 
6630 	if (nfsrv_useacl == 0 || nfs_supportsnfsv4acls(vp) == 0) {
6631 		error = NFSERR_ATTRNOTSUPP;
6632 		goto out;
6633 	}
6634 	/*
6635 	 * With NFSv4 ACLs, chmod(2) may need to add additional entries.
6636 	 * Make sure it has enough room for that - splitting every entry
6637 	 * into two and appending "canonical six" entries at the end.
6638 	 * Cribbed out of kern/vfs_acl.c - Rick M.
6639 	 */
6640 	if (aclp->acl_cnt > (ACL_MAX_ENTRIES - 6) / 2) {
6641 		error = NFSERR_ATTRNOTSUPP;
6642 		goto out;
6643 	}
6644 	error = VOP_SETACL(vp, ACL_TYPE_NFS4, aclp, cred, p);
6645 	if (error == 0) {
6646 		error = nfsrv_dssetacl(vp, aclp, cred, p);
6647 		if (error == ENOENT)
6648 			error = 0;
6649 	}
6650 
6651 out:
6652 	NFSEXITCODE(error);
6653 	return (error);
6654 }
6655 
6656 /*
6657  * Seek vnode op call (actually it is a VOP_IOCTL()).
6658  * This function is called with the vnode locked, but unlocks and vrele()s
6659  * the vp before returning.
6660  */
6661 int
6662 nfsvno_seek(struct nfsrv_descript *nd, struct vnode *vp, u_long cmd,
6663     off_t *offp, int content, bool *eofp, struct ucred *cred, NFSPROC_T *p)
6664 {
6665 	struct nfsvattr at;
6666 	int error, ret;
6667 
6668 	ASSERT_VOP_LOCKED(vp, "nfsvno_seek vp");
6669 	/*
6670 	 * Attempt to seek on a DS file. A return of ENOENT implies
6671 	 * there is no DS file to seek on.
6672 	 */
6673 	error = nfsrv_proxyds(vp, 0, 0, cred, p, NFSPROC_SEEKDS, NULL,
6674 	    NULL, NULL, NULL, NULL, offp, content, eofp);
6675 	if (error != ENOENT) {
6676 		vput(vp);
6677 		return (error);
6678 	}
6679 
6680 	/*
6681 	 * Do the VOP_IOCTL() call.  For the case where *offp == file_size,
6682 	 * VOP_IOCTL() will return ENXIO.  However, the correct reply for
6683 	 * NFSv4.2 is *eofp == true and error == 0 for this case.
6684 	 */
6685 	NFSVOPUNLOCK(vp);
6686 	error = VOP_IOCTL(vp, cmd, offp, 0, cred, p);
6687 	*eofp = false;
6688 	if (error == ENXIO || (error == 0 && cmd == FIOSEEKHOLE)) {
6689 		/* Handle the cases where we might be at EOF. */
6690 		ret = nfsvno_getattr(vp, &at, nd, p, 0, NULL);
6691 		if (ret == 0 && *offp == at.na_size) {
6692 			*eofp = true;
6693 			error = 0;
6694 		}
6695 		if (ret != 0 && error == 0)
6696 			error = ret;
6697 	}
6698 	vrele(vp);
6699 	NFSEXITCODE(error);
6700 	return (error);
6701 }
6702 
6703 /*
6704  * Allocate vnode op call.
6705  */
6706 int
6707 nfsvno_allocate(struct vnode *vp, off_t off, off_t len, struct ucred *cred,
6708     NFSPROC_T *p)
6709 {
6710 	int error;
6711 	off_t olen;
6712 
6713 	ASSERT_VOP_ELOCKED(vp, "nfsvno_allocate vp");
6714 	/*
6715 	 * Attempt to allocate on a DS file. A return of ENOENT implies
6716 	 * there is no DS file to allocate on.
6717 	 */
6718 	error = nfsrv_proxyds(vp, off, 0, cred, p, NFSPROC_ALLOCATE, NULL,
6719 	    NULL, NULL, NULL, NULL, &len, 0, NULL);
6720 	if (error != ENOENT)
6721 		return (error);
6722 
6723 	/*
6724 	 * Do the actual VOP_ALLOCATE(), looping so long as
6725 	 * progress is being made, to achieve completion.
6726 	 */
6727 	do {
6728 		olen = len;
6729 		error = VOP_ALLOCATE(vp, &off, &len, IO_SYNC, cred);
6730 		if (error == 0 && len > 0 && olen > len)
6731 			maybe_yield();
6732 	} while (error == 0 && len > 0 && olen > len);
6733 	if (error == 0 && len > 0)
6734 		error = NFSERR_IO;
6735 	NFSEXITCODE(error);
6736 	return (error);
6737 }
6738 
6739 /*
6740  * Deallocate vnode op call.
6741  */
6742 int
6743 nfsvno_deallocate(struct vnode *vp, off_t off, off_t len, struct ucred *cred,
6744     NFSPROC_T *p)
6745 {
6746 	int error;
6747 	off_t olen;
6748 
6749 	ASSERT_VOP_ELOCKED(vp, "nfsvno_deallocate vp");
6750 	/*
6751 	 * Attempt to deallocate on a DS file. A return of ENOENT implies
6752 	 * there is no DS file to deallocate on.
6753 	 */
6754 	error = nfsrv_proxyds(vp, off, 0, cred, p, NFSPROC_DEALLOCATE, NULL,
6755 	    NULL, NULL, NULL, NULL, &len, 0, NULL);
6756 	if (error != ENOENT)
6757 		return (error);
6758 
6759 	/*
6760 	 * Do the actual VOP_DEALLOCATE(), looping so long as
6761 	 * progress is being made, to achieve completion.
6762 	 */
6763 	do {
6764 		olen = len;
6765 		error = VOP_DEALLOCATE(vp, &off, &len, 0, IO_SYNC, cred);
6766 		if (error == 0 && len > 0 && olen > len)
6767 			maybe_yield();
6768 	} while (error == 0 && len > 0 && olen > len);
6769 	if (error == 0 && len > 0)
6770 		error = NFSERR_IO;
6771 	NFSEXITCODE(error);
6772 	return (error);
6773 }
6774 
6775 /*
6776  * Get Extended Atribute vnode op into an mbuf list.
6777  */
6778 int
6779 nfsvno_getxattr(struct vnode *vp, char *name, uint32_t maxresp,
6780     struct ucred *cred, uint64_t flag, int maxextsiz, struct thread *p,
6781     struct mbuf **mpp, struct mbuf **mpendp, int *lenp)
6782 {
6783 	struct iovec *iv;
6784 	struct uio io, *uiop = &io;
6785 	struct mbuf *m, *m2;
6786 	int alen, error, len, tlen;
6787 	size_t siz;
6788 
6789 	/* First, find out the size of the extended attribute. */
6790 	error = VOP_GETEXTATTR(vp, EXTATTR_NAMESPACE_USER, name, NULL,
6791 	    &siz, cred, p);
6792 	if (error != 0)
6793 		return (NFSERR_NOXATTR);
6794 	if (siz > maxresp - NFS_MAXXDR)
6795 		return (NFSERR_XATTR2BIG);
6796 	len = siz;
6797 	tlen = NFSM_RNDUP(len);
6798 	if (tlen > 0) {
6799 		/*
6800 		 * If cnt > MCLBYTES and the reply will not be saved, use
6801 		 * ext_pgs mbufs for TLS.
6802 		 * For NFSv4.0, we do not know for sure if the reply will
6803 		 * be saved, so do not use ext_pgs mbufs for NFSv4.0.
6804 		 * Always use ext_pgs mbufs if ND_EXTPG is set.
6805 		 */
6806 		if ((flag & ND_EXTPG) != 0 || (tlen > MCLBYTES &&
6807 		    (flag & (ND_TLS | ND_SAVEREPLY)) == ND_TLS &&
6808 		    (flag & (ND_NFSV4 | ND_NFSV41)) != ND_NFSV4))
6809 			uiop->uio_iovcnt = nfsrv_createiovec_extpgs(tlen,
6810 			    maxextsiz, &m, &m2, &iv);
6811 		else
6812 			uiop->uio_iovcnt = nfsrv_createiovec(tlen, &m, &m2,
6813 			    &iv);
6814 		uiop->uio_iov = iv;
6815 	} else {
6816 		uiop->uio_iovcnt = 0;
6817 		uiop->uio_iov = iv = NULL;
6818 		m = m2 = NULL;
6819 	}
6820 	uiop->uio_offset = 0;
6821 	uiop->uio_resid = tlen;
6822 	uiop->uio_rw = UIO_READ;
6823 	uiop->uio_segflg = UIO_SYSSPACE;
6824 	uiop->uio_td = p;
6825 #ifdef MAC
6826 	error = mac_vnode_check_getextattr(cred, vp, EXTATTR_NAMESPACE_USER,
6827 	    name);
6828 	if (error != 0)
6829 		goto out;
6830 #endif
6831 
6832 	if (tlen > 0)
6833 		error = VOP_GETEXTATTR(vp, EXTATTR_NAMESPACE_USER, name, uiop,
6834 		    NULL, cred, p);
6835 	if (error != 0)
6836 		goto out;
6837 	if (uiop->uio_resid > 0) {
6838 		alen = tlen;
6839 		len = tlen - uiop->uio_resid;
6840 		tlen = NFSM_RNDUP(len);
6841 		if (alen != tlen)
6842 			printf("nfsvno_getxattr: weird size read\n");
6843 		if (tlen == 0) {
6844 			m_freem(m);
6845 			m = m2 = NULL;
6846 		} else if (alen != tlen || tlen != len)
6847 			m2 = nfsrv_adj(m, alen - tlen, tlen - len);
6848 	}
6849 	*lenp = len;
6850 	*mpp = m;
6851 	*mpendp = m2;
6852 
6853 out:
6854 	if (error != 0) {
6855 		if (m != NULL)
6856 			m_freem(m);
6857 		*lenp = 0;
6858 	}
6859 	free(iv, M_TEMP);
6860 	NFSEXITCODE(error);
6861 	return (error);
6862 }
6863 
6864 /*
6865  * Set Extended attribute vnode op from an mbuf list.
6866  */
6867 int
6868 nfsvno_setxattr(struct vnode *vp, char *name, int len, struct mbuf *m,
6869     char *cp, struct ucred *cred, struct thread *p)
6870 {
6871 	struct iovec *iv;
6872 	struct uio uio, *uiop = &uio;
6873 	int cnt, error;
6874 
6875 	error = 0;
6876 #ifdef MAC
6877 	error = mac_vnode_check_setextattr(cred, vp, EXTATTR_NAMESPACE_USER,
6878 	    name);
6879 #endif
6880 	if (error != 0)
6881 		goto out;
6882 
6883 	uiop->uio_rw = UIO_WRITE;
6884 	uiop->uio_segflg = UIO_SYSSPACE;
6885 	uiop->uio_td = p;
6886 	uiop->uio_offset = 0;
6887 	uiop->uio_resid = len;
6888 	if (len > 0) {
6889 		error = nfsrv_createiovecw(len, m, cp, &iv, &cnt);
6890 		uiop->uio_iov = iv;
6891 		uiop->uio_iovcnt = cnt;
6892 	} else {
6893 		uiop->uio_iov = iv = NULL;
6894 		uiop->uio_iovcnt = 0;
6895 	}
6896 	if (error == 0) {
6897 		error = VOP_SETEXTATTR(vp, EXTATTR_NAMESPACE_USER, name, uiop,
6898 		    cred, p);
6899 		if (error == 0) {
6900 			if (vp->v_type == VREG && nfsrv_devidcnt != 0)
6901 				nfsvno_updateds(vp, cred, p);
6902 			error = VOP_FSYNC(vp, MNT_WAIT, p);
6903 		}
6904 		free(iv, M_TEMP);
6905 	}
6906 
6907 out:
6908 	NFSEXITCODE(error);
6909 	return (error);
6910 }
6911 
6912 /*
6913  * For a pNFS server, the DS file's ctime and
6914  * va_filerev (TimeMetadata and Change) needs to
6915  * be updated.  This is a hack, but works by
6916  * flipping the S_ISGID bit in va_mode and then
6917  * flipping it back.
6918  * It does result in two MDS->DS RPCs, but creating
6919  * a custom RPC just to do this seems overkill, since
6920  * Setxattr/Rmxattr will not be done that frequently.
6921  * If it fails part way through, that is not too
6922  * serious, since the DS file is never executed.
6923  */
6924 static void
6925 nfsvno_updateds(struct vnode *vp, struct ucred *cred, NFSPROC_T *p)
6926 {
6927 	struct nfsvattr nva;
6928 	int ret;
6929 	u_short tmode;
6930 
6931 	ret = VOP_GETATTR(vp, &nva.na_vattr, cred);
6932 	if (ret == 0) {
6933 		tmode = nva.na_mode;
6934 		NFSVNO_ATTRINIT(&nva);
6935 		tmode ^= S_ISGID;
6936 		NFSVNO_SETATTRVAL(&nva, mode, tmode);
6937 		ret = nfsrv_proxyds(vp, 0, 0, cred, p,
6938 		    NFSPROC_SETATTR, NULL, NULL, NULL, &nva,
6939 		    NULL, NULL, 0, NULL);
6940 		if (ret == 0) {
6941 			tmode ^= S_ISGID;
6942 			NFSVNO_SETATTRVAL(&nva, mode, tmode);
6943 			ret = nfsrv_proxyds(vp, 0, 0, cred, p,
6944 			    NFSPROC_SETATTR, NULL, NULL, NULL,
6945 			    &nva, NULL, NULL, 0, NULL);
6946 		}
6947 	}
6948 }
6949 
6950 /*
6951  * Remove Extended attribute vnode op.
6952  */
6953 int
6954 nfsvno_rmxattr(struct nfsrv_descript *nd, struct vnode *vp, char *name,
6955     struct ucred *cred, struct thread *p)
6956 {
6957 	int error;
6958 
6959 	/*
6960 	 * Get rid of any delegations.  I am not sure why this is required,
6961 	 * but RFC-8276 says so.
6962 	 */
6963 	error = nfsrv_checkremove(vp, 0, nd, nd->nd_clientid, p);
6964 	if (error != 0)
6965 		goto out;
6966 #ifdef MAC
6967 	error = mac_vnode_check_deleteextattr(cred, vp, EXTATTR_NAMESPACE_USER,
6968 	    name);
6969 	if (error != 0)
6970 		goto out;
6971 #endif
6972 
6973 	error = VOP_DELETEEXTATTR(vp, EXTATTR_NAMESPACE_USER, name, cred, p);
6974 	if (error == EOPNOTSUPP)
6975 		error = VOP_SETEXTATTR(vp, EXTATTR_NAMESPACE_USER, name, NULL,
6976 		    cred, p);
6977 	if (error == 0) {
6978 		if (vp->v_type == VREG && nfsrv_devidcnt != 0)
6979 			nfsvno_updateds(vp, cred, p);
6980 		error = VOP_FSYNC(vp, MNT_WAIT, p);
6981 	}
6982 out:
6983 	NFSEXITCODE(error);
6984 	return (error);
6985 }
6986 
6987 /*
6988  * List Extended Atribute vnode op into an mbuf list.
6989  */
6990 int
6991 nfsvno_listxattr(struct vnode *vp, uint64_t cookie, struct ucred *cred,
6992     struct thread *p, u_char **bufp, uint32_t *lenp, bool *eofp)
6993 {
6994 	struct iovec iv;
6995 	struct uio io;
6996 	int error;
6997 	size_t siz;
6998 
6999 	*bufp = NULL;
7000 	/* First, find out the size of the extended attribute. */
7001 	error = VOP_LISTEXTATTR(vp, EXTATTR_NAMESPACE_USER, NULL, &siz, cred,
7002 	    p);
7003 	if (error != 0)
7004 		return (NFSERR_NOXATTR);
7005 	if (siz <= cookie) {
7006 		*lenp = 0;
7007 		*eofp = true;
7008 		goto out;
7009 	}
7010 	if (siz > cookie + *lenp) {
7011 		siz = cookie + *lenp;
7012 		*eofp = false;
7013 	} else
7014 		*eofp = true;
7015 	/* Just choose a sanity limit of 10Mbytes for malloc(M_TEMP). */
7016 	if (siz > 10 * 1024 * 1024) {
7017 		error = NFSERR_XATTR2BIG;
7018 		goto out;
7019 	}
7020 	*bufp = malloc(siz, M_TEMP, M_WAITOK);
7021 	iv.iov_base = *bufp;
7022 	iv.iov_len = siz;
7023 	io.uio_iovcnt = 1;
7024 	io.uio_iov = &iv;
7025 	io.uio_offset = 0;
7026 	io.uio_resid = siz;
7027 	io.uio_rw = UIO_READ;
7028 	io.uio_segflg = UIO_SYSSPACE;
7029 	io.uio_td = p;
7030 #ifdef MAC
7031 	error = mac_vnode_check_listextattr(cred, vp, EXTATTR_NAMESPACE_USER);
7032 	if (error != 0)
7033 		goto out;
7034 #endif
7035 
7036 	error = VOP_LISTEXTATTR(vp, EXTATTR_NAMESPACE_USER, &io, NULL, cred,
7037 	    p);
7038 	if (error != 0)
7039 		goto out;
7040 	if (io.uio_resid > 0)
7041 		siz -= io.uio_resid;
7042 	*lenp = siz;
7043 
7044 out:
7045 	if (error != 0) {
7046 		free(*bufp, M_TEMP);
7047 		*bufp = NULL;
7048 	}
7049 	NFSEXITCODE(error);
7050 	return (error);
7051 }
7052 
7053 /*
7054  * Trim trailing data off the mbuf list being built.
7055  */
7056 void
7057 nfsm_trimtrailing(struct nfsrv_descript *nd, struct mbuf *mb, char *bpos,
7058     int bextpg, int bextpgsiz)
7059 {
7060 	vm_page_t pg;
7061 	int fullpgsiz, i;
7062 
7063 	if (mb->m_next != NULL) {
7064 		m_freem(mb->m_next);
7065 		mb->m_next = NULL;
7066 	}
7067 	if ((mb->m_flags & M_EXTPG) != 0) {
7068 		KASSERT(bextpg >= 0 && bextpg < mb->m_epg_npgs,
7069 		    ("nfsm_trimtrailing: bextpg out of range"));
7070 		KASSERT(bpos == (char *)(void *)
7071 		    PHYS_TO_DMAP(mb->m_epg_pa[bextpg]) + PAGE_SIZE - bextpgsiz,
7072 		    ("nfsm_trimtrailing: bextpgsiz bad!"));
7073 
7074 		/* First, get rid of any pages after this position. */
7075 		for (i = mb->m_epg_npgs - 1; i > bextpg; i--) {
7076 			pg = PHYS_TO_VM_PAGE(mb->m_epg_pa[i]);
7077 			vm_page_unwire_noq(pg);
7078 			vm_page_free(pg);
7079 		}
7080 		mb->m_epg_npgs = bextpg + 1;
7081 		if (bextpg == 0)
7082 			fullpgsiz = PAGE_SIZE - mb->m_epg_1st_off;
7083 		else
7084 			fullpgsiz = PAGE_SIZE;
7085 		mb->m_epg_last_len = fullpgsiz - bextpgsiz;
7086 		mb->m_len = m_epg_pagelen(mb, 0, mb->m_epg_1st_off);
7087 		for (i = 1; i < mb->m_epg_npgs; i++)
7088 			mb->m_len += m_epg_pagelen(mb, i, 0);
7089 		nd->nd_bextpgsiz = bextpgsiz;
7090 		nd->nd_bextpg = bextpg;
7091 	} else
7092 		mb->m_len = bpos - mtod(mb, char *);
7093 	nd->nd_mb = mb;
7094 	nd->nd_bpos = bpos;
7095 }
7096 
7097 
7098 /*
7099  * Check to see if a put file handle operation should test for
7100  * NFSERR_WRONGSEC, although NFSv3 actually returns NFSERR_AUTHERR.
7101  * When Open is the next operation, NFSERR_WRONGSEC cannot be
7102  * replied for the Open cases that use a component.  This can
7103  * be identified by the fact that the file handle's type is VDIR.
7104  */
7105 bool
7106 nfsrv_checkwrongsec(struct nfsrv_descript *nd, int nextop, __enum_uint8(vtype) vtyp)
7107 {
7108 
7109 	if ((nd->nd_flag & ND_NFSV4) == 0)
7110 		return (true);
7111 
7112 	if ((nd->nd_flag & ND_LASTOP) != 0)
7113 		return (false);
7114 
7115 	if (nextop == NFSV4OP_PUTROOTFH || nextop == NFSV4OP_PUTFH ||
7116 	    nextop == NFSV4OP_PUTPUBFH || nextop == NFSV4OP_RESTOREFH ||
7117 	    nextop == NFSV4OP_LOOKUP || nextop == NFSV4OP_LOOKUPP ||
7118 	    nextop == NFSV4OP_SECINFO || nextop == NFSV4OP_SECINFONONAME)
7119 		return (false);
7120 	if (nextop == NFSV4OP_OPEN && vtyp == VDIR)
7121 		return (false);
7122 	return (true);
7123 }
7124 
7125 /*
7126  * Check DSs marked no space.
7127  */
7128 void
7129 nfsrv_checknospc(void)
7130 {
7131 	struct statfs *tsf;
7132 	struct nfsdevice *ds;
7133 	struct vnode **dvpp, **tdvpp, *dvp;
7134 	char *devid, *tdevid;
7135 	int cnt, error = 0, i;
7136 
7137 	if (nfsrv_devidcnt <= 0)
7138 		return;
7139 	dvpp = mallocarray(nfsrv_devidcnt, sizeof(*dvpp), M_TEMP, M_WAITOK);
7140 	devid = malloc(nfsrv_devidcnt * NFSX_V4DEVICEID, M_TEMP, M_WAITOK);
7141 	tsf = malloc(sizeof(*tsf), M_TEMP, M_WAITOK);
7142 
7143 	/* Get an array of the dvps for the DSs. */
7144 	tdvpp = dvpp;
7145 	tdevid = devid;
7146 	i = 0;
7147 	NFSDDSLOCK();
7148 	/* First, search for matches for same file system. */
7149 	TAILQ_FOREACH(ds, &nfsrv_devidhead, nfsdev_list) {
7150 		if (ds->nfsdev_nmp != NULL && ds->nfsdev_nospc) {
7151 			if (++i > nfsrv_devidcnt)
7152 				break;
7153 			*tdvpp++ = ds->nfsdev_dvp;
7154 			NFSBCOPY(ds->nfsdev_deviceid, tdevid, NFSX_V4DEVICEID);
7155 			tdevid += NFSX_V4DEVICEID;
7156 		}
7157 	}
7158 	NFSDDSUNLOCK();
7159 
7160 	/* Do a VFS_STATFS() for each of the DSs and clear no space. */
7161 	cnt = i;
7162 	tdvpp = dvpp;
7163 	tdevid = devid;
7164 	for (i = 0; i < cnt && error == 0; i++) {
7165 		dvp = *tdvpp++;
7166 		error = VFS_STATFS(dvp->v_mount, tsf);
7167 		if (error == 0 && tsf->f_bavail > 0) {
7168 			NFSD_DEBUG(1, "nfsrv_checknospc: reset nospc\n");
7169 			nfsrv_marknospc(tdevid, false);
7170 		}
7171 		tdevid += NFSX_V4DEVICEID;
7172 	}
7173 	free(tsf, M_TEMP);
7174 	free(dvpp, M_TEMP);
7175 	free(devid, M_TEMP);
7176 }
7177 
7178 /*
7179  * Initialize everything that needs to be initialized for a vnet.
7180  */
7181 static void
7182 nfsrv_vnetinit(const void *unused __unused)
7183 {
7184 
7185 	nfsd_mntinit();
7186 }
7187 VNET_SYSINIT(nfsrv_vnetinit, SI_SUB_VNET_DONE, SI_ORDER_ANY,
7188     nfsrv_vnetinit, NULL);
7189 
7190 /*
7191  * Clean up everything that is in a vnet and needs to be
7192  * done when the jail is destroyed or the module unloaded.
7193  */
7194 static void
7195 nfsrv_cleanup(const void *unused __unused)
7196 {
7197 	int i;
7198 
7199 	NFSD_LOCK();
7200 	if (!NFSD_VNET(nfsrv_mntinited)) {
7201 		NFSD_UNLOCK();
7202 		return;
7203 	}
7204 	NFSD_VNET(nfsrv_mntinited) = false;
7205 	NFSD_UNLOCK();
7206 
7207 	/* Clean out all NFSv4 state. */
7208 	nfsrv_throwawayallstate(curthread);
7209 
7210 	/* Clean the NFS server reply cache */
7211 	nfsrvd_cleancache();
7212 
7213 	/* Clean out v4root exports. */
7214 	if (NFSD_VNET(nfsv4root_mnt)->mnt_export != NULL) {
7215 		vfs_free_addrlist(NFSD_VNET(nfsv4root_mnt)->mnt_export);
7216 		free(NFSD_VNET(nfsv4root_mnt)->mnt_export, M_MOUNT);
7217 		NFSD_VNET(nfsv4root_mnt)->mnt_export = NULL;
7218 	}
7219 
7220 	/* Free up the krpc server pool. */
7221 	if (NFSD_VNET(nfsrvd_pool) != NULL)
7222 		svcpool_destroy(NFSD_VNET(nfsrvd_pool));
7223 
7224 	/* and get rid of the locks */
7225 	for (i = 0; i < NFSRVCACHE_HASHSIZE; i++) {
7226 		mtx_destroy(&NFSD_VNET(nfsrchash_table)[i].mtx);
7227 		mtx_destroy(&NFSD_VNET(nfsrcahash_table)[i].mtx);
7228 	}
7229 	mtx_destroy(&NFSD_VNET(nfsv4root_mnt)->mnt_mtx);
7230 	for (i = 0; i < nfsrv_sessionhashsize; i++)
7231 		mtx_destroy(&NFSD_VNET(nfssessionhash)[i].mtx);
7232 	lockdestroy(&NFSD_VNET(nfsv4root_mnt)->mnt_explock);
7233 	free(NFSD_VNET(nfsrvudphashtbl), M_NFSRVCACHE);
7234 	free(NFSD_VNET(nfsrchash_table), M_NFSRVCACHE);
7235 	free(NFSD_VNET(nfsrcahash_table), M_NFSRVCACHE);
7236 	free(NFSD_VNET(nfsclienthash), M_NFSDCLIENT);
7237 	free(NFSD_VNET(nfslockhash), M_NFSDLOCKFILE);
7238 	free(NFSD_VNET(nfssessionhash), M_NFSDSESSION);
7239 	free(NFSD_VNET(nfsv4root_mnt), M_TEMP);
7240 	NFSD_VNET(nfsv4root_mnt) = NULL;
7241 }
7242 VNET_SYSUNINIT(nfsrv_cleanup, SI_SUB_VNET_DONE, SI_ORDER_ANY,
7243     nfsrv_cleanup, NULL);
7244 
7245 extern int (*nfsd_call_nfsd)(struct thread *, struct nfssvc_args *);
7246 
7247 /*
7248  * Called once to initialize data structures...
7249  */
7250 static int
7251 nfsd_modevent(module_t mod, int type, void *data)
7252 {
7253 	int error = 0, i;
7254 	static int loaded = 0;
7255 
7256 	switch (type) {
7257 	case MOD_LOAD:
7258 		if (loaded)
7259 			goto out;
7260 		newnfs_portinit();
7261 		mtx_init(&nfsrc_udpmtx, "nfsuc", NULL, MTX_DEF);
7262 		mtx_init(&nfs_v4root_mutex, "nfs4rt", NULL, MTX_DEF);
7263 		mtx_init(&nfsrv_dontlistlock_mtx, "nfs4dnl", NULL, MTX_DEF);
7264 		mtx_init(&nfsrv_recalllock_mtx, "nfs4rec", NULL, MTX_DEF);
7265 #ifdef VV_DISABLEDELEG
7266 		vn_deleg_ops.vndeleg_recall = nfsd_recalldelegation;
7267 		vn_deleg_ops.vndeleg_disable = nfsd_disabledelegation;
7268 #endif
7269 		nfsd_call_nfsd = nfssvc_nfsd;
7270 		loaded = 1;
7271 		break;
7272 
7273 	case MOD_UNLOAD:
7274 		if (newnfs_numnfsd != 0) {
7275 			error = EBUSY;
7276 			break;
7277 		}
7278 
7279 #ifdef VV_DISABLEDELEG
7280 		vn_deleg_ops.vndeleg_recall = NULL;
7281 		vn_deleg_ops.vndeleg_disable = NULL;
7282 #endif
7283 		nfsd_call_nfsd = NULL;
7284 		mtx_destroy(&nfsrc_udpmtx);
7285 		mtx_destroy(&nfs_v4root_mutex);
7286 		mtx_destroy(&nfsrv_dontlistlock_mtx);
7287 		mtx_destroy(&nfsrv_recalllock_mtx);
7288 		if (nfslayouthash != NULL) {
7289 			for (i = 0; i < nfsrv_layouthashsize; i++)
7290 				mtx_destroy(&nfslayouthash[i].mtx);
7291 			free(nfslayouthash, M_NFSDSESSION);
7292 		}
7293 		loaded = 0;
7294 		break;
7295 	default:
7296 		error = EOPNOTSUPP;
7297 		break;
7298 	}
7299 
7300 out:
7301 	NFSEXITCODE(error);
7302 	return (error);
7303 }
7304 static moduledata_t nfsd_mod = {
7305 	"nfsd",
7306 	nfsd_modevent,
7307 	NULL,
7308 };
7309 DECLARE_MODULE(nfsd, nfsd_mod, SI_SUB_VFS, SI_ORDER_ANY);
7310 
7311 /* So that loader and kldload(2) can find us, wherever we are.. */
7312 MODULE_VERSION(nfsd, 1);
7313 MODULE_DEPEND(nfsd, nfscommon, 1, 1, 1);
7314 MODULE_DEPEND(nfsd, nfslockd, 1, 1, 1);
7315 MODULE_DEPEND(nfsd, krpc, 1, 1, 1);
7316 MODULE_DEPEND(nfsd, nfssvc, 1, 1, 1);
7317