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