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