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