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