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