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