xref: /freebsd/sys/fs/nfsclient/nfs_clstate.c (revision 0957b409)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (c) 2009 Rick Macklem, University of Guelph
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  *
28  */
29 
30 #include <sys/cdefs.h>
31 __FBSDID("$FreeBSD$");
32 
33 /*
34  * These functions implement the client side state handling for NFSv4.
35  * NFSv4 state handling:
36  * - A lockowner is used to determine lock contention, so it
37  *   corresponds directly to a Posix pid. (1 to 1 mapping)
38  * - The correct granularity of an OpenOwner is not nearly so
39  *   obvious. An OpenOwner does the following:
40  *   - provides a serial sequencing of Open/Close/Lock-with-new-lockowner
41  *   - is used to check for Open/Share contention (not applicable to
42  *     this client, since all Opens are Deny_None)
43  *   As such, I considered both extreme.
44  *   1 OpenOwner per ClientID - Simple to manage, but fully serializes
45  *   all Open, Close and Lock (with a new lockowner) Ops.
46  *   1 OpenOwner for each Open - This one results in an OpenConfirm for
47  *   every Open, for most servers.
48  *   So, I chose to use the same mapping as I did for LockOwnwers.
49  *   The main concern here is that you can end up with multiple Opens
50  *   for the same File Handle, but on different OpenOwners (opens
51  *   inherited from parents, grandparents...) and you do not know
52  *   which of these the vnodeop close applies to. This is handled by
53  *   delaying the Close Op(s) until all of the Opens have been closed.
54  *   (It is not yet obvious if this is the correct granularity.)
55  * - How the code handles serialization:
56  *   - For the ClientId, it uses an exclusive lock while getting its
57  *     SetClientId and during recovery. Otherwise, it uses a shared
58  *     lock via a reference count.
59  *   - For the rest of the data structures, it uses an SMP mutex
60  *     (once the nfs client is SMP safe) and doesn't sleep while
61  *     manipulating the linked lists.
62  *   - The serialization of Open/Close/Lock/LockU falls out in the
63  *     "wash", since OpenOwners and LockOwners are both mapped from
64  *     Posix pid. In other words, there is only one Posix pid using
65  *     any given owner, so that owner is serialized. (If you change
66  *     the granularity of the OpenOwner, then code must be added to
67  *     serialize Ops on the OpenOwner.)
68  * - When to get rid of OpenOwners and LockOwners.
69  *   - The function nfscl_cleanup_common() is executed after a process exits.
70  *     It goes through the client list looking for all Open and Lock Owners.
71  *     When one is found, it is marked "defunct" or in the case of
72  *     an OpenOwner without any Opens, freed.
73  *     The renew thread scans for defunct Owners and gets rid of them,
74  *     if it can. The LockOwners will also be deleted when the
75  *     associated Open is closed.
76  *   - If the LockU or Close Op(s) fail during close in a way
77  *     that could be recovered upon retry, they are relinked to the
78  *     ClientId's defunct open list and retried by the renew thread
79  *     until they succeed or an unmount/recovery occurs.
80  *     (Since we are done with them, they do not need to be recovered.)
81  */
82 
83 #ifndef APPLEKEXT
84 #include <fs/nfs/nfsport.h>
85 
86 /*
87  * Global variables
88  */
89 extern struct nfsstatsv1 nfsstatsv1;
90 extern struct nfsreqhead nfsd_reqq;
91 extern u_int32_t newnfs_false, newnfs_true;
92 extern int nfscl_debuglevel;
93 extern int nfscl_enablecallb;
94 extern int nfs_numnfscbd;
95 NFSREQSPINLOCK;
96 NFSCLSTATEMUTEX;
97 int nfscl_inited = 0;
98 struct nfsclhead nfsclhead;	/* Head of clientid list */
99 int nfscl_deleghighwater = NFSCLDELEGHIGHWATER;
100 int nfscl_layouthighwater = NFSCLLAYOUTHIGHWATER;
101 #endif	/* !APPLEKEXT */
102 
103 static int nfscl_delegcnt = 0;
104 static int nfscl_layoutcnt = 0;
105 static int nfscl_getopen(struct nfsclownerhead *, u_int8_t *, int, u_int8_t *,
106     u_int8_t *, u_int32_t, struct nfscllockowner **, struct nfsclopen **);
107 static void nfscl_clrelease(struct nfsclclient *);
108 static void nfscl_cleanclient(struct nfsclclient *);
109 static void nfscl_expireclient(struct nfsclclient *, struct nfsmount *,
110     struct ucred *, NFSPROC_T *);
111 static int nfscl_expireopen(struct nfsclclient *, struct nfsclopen *,
112     struct nfsmount *, struct ucred *, NFSPROC_T *);
113 static void nfscl_recover(struct nfsclclient *, struct ucred *, NFSPROC_T *);
114 static void nfscl_insertlock(struct nfscllockowner *, struct nfscllock *,
115     struct nfscllock *, int);
116 static int nfscl_updatelock(struct nfscllockowner *, struct nfscllock **,
117     struct nfscllock **, int);
118 static void nfscl_delegreturnall(struct nfsclclient *, NFSPROC_T *);
119 static u_int32_t nfscl_nextcbident(void);
120 static mount_t nfscl_getmnt(int, uint8_t *, u_int32_t, struct nfsclclient **);
121 static struct nfsclclient *nfscl_getclnt(u_int32_t);
122 static struct nfsclclient *nfscl_getclntsess(uint8_t *);
123 static struct nfscldeleg *nfscl_finddeleg(struct nfsclclient *, u_int8_t *,
124     int);
125 static void nfscl_retoncloselayout(vnode_t, struct nfsclclient *, uint8_t *,
126     int, struct nfsclrecalllayout **);
127 static void nfscl_reldevinfo_locked(struct nfscldevinfo *);
128 static struct nfscllayout *nfscl_findlayout(struct nfsclclient *, u_int8_t *,
129     int);
130 static struct nfscldevinfo *nfscl_finddevinfo(struct nfsclclient *, uint8_t *);
131 static int nfscl_checkconflict(struct nfscllockownerhead *, struct nfscllock *,
132     u_int8_t *, struct nfscllock **);
133 static void nfscl_freealllocks(struct nfscllockownerhead *, int);
134 static int nfscl_localconflict(struct nfsclclient *, u_int8_t *, int,
135     struct nfscllock *, u_int8_t *, struct nfscldeleg *, struct nfscllock **);
136 static void nfscl_newopen(struct nfsclclient *, struct nfscldeleg *,
137     struct nfsclowner **, struct nfsclowner **, struct nfsclopen **,
138     struct nfsclopen **, u_int8_t *, u_int8_t *, int, struct ucred *, int *);
139 static int nfscl_moveopen(vnode_t , struct nfsclclient *,
140     struct nfsmount *, struct nfsclopen *, struct nfsclowner *,
141     struct nfscldeleg *, struct ucred *, NFSPROC_T *);
142 static void nfscl_totalrecall(struct nfsclclient *);
143 static int nfscl_relock(vnode_t , struct nfsclclient *, struct nfsmount *,
144     struct nfscllockowner *, struct nfscllock *, struct ucred *, NFSPROC_T *);
145 static int nfscl_tryopen(struct nfsmount *, vnode_t , u_int8_t *, int,
146     u_int8_t *, int, u_int32_t, struct nfsclopen *, u_int8_t *, int,
147     struct nfscldeleg **, int, u_int32_t, struct ucred *, NFSPROC_T *);
148 static int nfscl_trylock(struct nfsmount *, vnode_t , u_int8_t *,
149     int, struct nfscllockowner *, int, int, u_int64_t, u_int64_t, short,
150     struct ucred *, NFSPROC_T *);
151 static int nfsrpc_reopen(struct nfsmount *, u_int8_t *, int, u_int32_t,
152     struct nfsclopen *, struct nfscldeleg **, struct ucred *, NFSPROC_T *);
153 static void nfscl_freedeleg(struct nfscldeleghead *, struct nfscldeleg *);
154 static int nfscl_errmap(struct nfsrv_descript *, u_int32_t);
155 static void nfscl_cleanup_common(struct nfsclclient *, u_int8_t *);
156 static int nfscl_recalldeleg(struct nfsclclient *, struct nfsmount *,
157     struct nfscldeleg *, vnode_t, struct ucred *, NFSPROC_T *, int);
158 static void nfscl_freeopenowner(struct nfsclowner *, int);
159 static void nfscl_cleandeleg(struct nfscldeleg *);
160 static int nfscl_trydelegreturn(struct nfscldeleg *, struct ucred *,
161     struct nfsmount *, NFSPROC_T *);
162 static void nfscl_emptylockowner(struct nfscllockowner *,
163     struct nfscllockownerfhhead *);
164 static void nfscl_mergeflayouts(struct nfsclflayouthead *,
165     struct nfsclflayouthead *);
166 static int nfscl_layoutrecall(int, struct nfscllayout *, uint32_t, uint64_t,
167     uint64_t, uint32_t, uint32_t, uint32_t, char *, struct nfsclrecalllayout *);
168 static int nfscl_seq(uint32_t, uint32_t);
169 static void nfscl_layoutreturn(struct nfsmount *, struct nfscllayout *,
170     struct ucred *, NFSPROC_T *);
171 static void nfscl_dolayoutcommit(struct nfsmount *, struct nfscllayout *,
172     struct ucred *, NFSPROC_T *);
173 
174 static short nfscberr_null[] = {
175 	0,
176 	0,
177 };
178 
179 static short nfscberr_getattr[] = {
180 	NFSERR_RESOURCE,
181 	NFSERR_BADHANDLE,
182 	NFSERR_BADXDR,
183 	NFSERR_RESOURCE,
184 	NFSERR_SERVERFAULT,
185 	0,
186 };
187 
188 static short nfscberr_recall[] = {
189 	NFSERR_RESOURCE,
190 	NFSERR_BADHANDLE,
191 	NFSERR_BADSTATEID,
192 	NFSERR_BADXDR,
193 	NFSERR_RESOURCE,
194 	NFSERR_SERVERFAULT,
195 	0,
196 };
197 
198 static short *nfscl_cberrmap[] = {
199 	nfscberr_null,
200 	nfscberr_null,
201 	nfscberr_null,
202 	nfscberr_getattr,
203 	nfscberr_recall
204 };
205 
206 #define	NETFAMILY(clp) \
207 		(((clp)->nfsc_flags & NFSCLFLAGS_AFINET6) ? AF_INET6 : AF_INET)
208 
209 /*
210  * Called for an open operation.
211  * If the nfhp argument is NULL, just get an openowner.
212  */
213 APPLESTATIC int
214 nfscl_open(vnode_t vp, u_int8_t *nfhp, int fhlen, u_int32_t amode, int usedeleg,
215     struct ucred *cred, NFSPROC_T *p, struct nfsclowner **owpp,
216     struct nfsclopen **opp, int *newonep, int *retp, int lockit)
217 {
218 	struct nfsclclient *clp;
219 	struct nfsclowner *owp, *nowp;
220 	struct nfsclopen *op = NULL, *nop = NULL;
221 	struct nfscldeleg *dp;
222 	struct nfsclownerhead *ohp;
223 	u_int8_t own[NFSV4CL_LOCKNAMELEN];
224 	int ret;
225 
226 	if (newonep != NULL)
227 		*newonep = 0;
228 	if (opp != NULL)
229 		*opp = NULL;
230 	if (owpp != NULL)
231 		*owpp = NULL;
232 
233 	/*
234 	 * Might need one or both of these, so MALLOC them now, to
235 	 * avoid a tsleep() in MALLOC later.
236 	 */
237 	nowp = malloc(sizeof (struct nfsclowner),
238 	    M_NFSCLOWNER, M_WAITOK);
239 	if (nfhp != NULL)
240 	    nop = malloc(sizeof (struct nfsclopen) +
241 		fhlen - 1, M_NFSCLOPEN, M_WAITOK);
242 	ret = nfscl_getcl(vnode_mount(vp), cred, p, 1, &clp);
243 	if (ret != 0) {
244 		free(nowp, M_NFSCLOWNER);
245 		if (nop != NULL)
246 			free(nop, M_NFSCLOPEN);
247 		return (ret);
248 	}
249 
250 	/*
251 	 * Get the Open iff it already exists.
252 	 * If none found, add the new one or return error, depending upon
253 	 * "create".
254 	 */
255 	NFSLOCKCLSTATE();
256 	dp = NULL;
257 	/* First check the delegation list */
258 	if (nfhp != NULL && usedeleg) {
259 		LIST_FOREACH(dp, NFSCLDELEGHASH(clp, nfhp, fhlen), nfsdl_hash) {
260 			if (dp->nfsdl_fhlen == fhlen &&
261 			    !NFSBCMP(nfhp, dp->nfsdl_fh, fhlen)) {
262 				if (!(amode & NFSV4OPEN_ACCESSWRITE) ||
263 				    (dp->nfsdl_flags & NFSCLDL_WRITE))
264 					break;
265 				dp = NULL;
266 				break;
267 			}
268 		}
269 	}
270 
271 	if (dp != NULL) {
272 		nfscl_filllockowner(p->td_proc, own, F_POSIX);
273 		ohp = &dp->nfsdl_owner;
274 	} else {
275 		/* For NFSv4.1 and this option, use a single open_owner. */
276 		if (NFSHASONEOPENOWN(VFSTONFS(vnode_mount(vp))))
277 			nfscl_filllockowner(NULL, own, F_POSIX);
278 		else
279 			nfscl_filllockowner(p->td_proc, own, F_POSIX);
280 		ohp = &clp->nfsc_owner;
281 	}
282 	/* Now, search for an openowner */
283 	LIST_FOREACH(owp, ohp, nfsow_list) {
284 		if (!NFSBCMP(owp->nfsow_owner, own, NFSV4CL_LOCKNAMELEN))
285 			break;
286 	}
287 
288 	/*
289 	 * Create a new open, as required.
290 	 */
291 	nfscl_newopen(clp, dp, &owp, &nowp, &op, &nop, own, nfhp, fhlen,
292 	    cred, newonep);
293 
294 	/*
295 	 * Now, check the mode on the open and return the appropriate
296 	 * value.
297 	 */
298 	if (retp != NULL) {
299 		if (nfhp != NULL && dp != NULL && nop == NULL)
300 			/* new local open on delegation */
301 			*retp = NFSCLOPEN_SETCRED;
302 		else
303 			*retp = NFSCLOPEN_OK;
304 	}
305 	if (op != NULL && (amode & ~(op->nfso_mode))) {
306 		op->nfso_mode |= amode;
307 		if (retp != NULL && dp == NULL)
308 			*retp = NFSCLOPEN_DOOPEN;
309 	}
310 
311 	/*
312 	 * Serialize modifications to the open owner for multiple threads
313 	 * within the same process using a read/write sleep lock.
314 	 * For NFSv4.1 and a single OpenOwner, allow concurrent open operations
315 	 * by acquiring a shared lock.  The close operations still use an
316 	 * exclusive lock for this case.
317 	 */
318 	if (lockit != 0) {
319 		if (NFSHASONEOPENOWN(VFSTONFS(vnode_mount(vp)))) {
320 			/*
321 			 * Get a shared lock on the OpenOwner, but first
322 			 * wait for any pending exclusive lock, so that the
323 			 * exclusive locker gets priority.
324 			 */
325 			nfsv4_lock(&owp->nfsow_rwlock, 0, NULL,
326 			    NFSCLSTATEMUTEXPTR, NULL);
327 			nfsv4_getref(&owp->nfsow_rwlock, NULL,
328 			    NFSCLSTATEMUTEXPTR, NULL);
329 		} else
330 			nfscl_lockexcl(&owp->nfsow_rwlock, NFSCLSTATEMUTEXPTR);
331 	}
332 	NFSUNLOCKCLSTATE();
333 	if (nowp != NULL)
334 		free(nowp, M_NFSCLOWNER);
335 	if (nop != NULL)
336 		free(nop, M_NFSCLOPEN);
337 	if (owpp != NULL)
338 		*owpp = owp;
339 	if (opp != NULL)
340 		*opp = op;
341 	return (0);
342 }
343 
344 /*
345  * Create a new open, as required.
346  */
347 static void
348 nfscl_newopen(struct nfsclclient *clp, struct nfscldeleg *dp,
349     struct nfsclowner **owpp, struct nfsclowner **nowpp, struct nfsclopen **opp,
350     struct nfsclopen **nopp, u_int8_t *own, u_int8_t *fhp, int fhlen,
351     struct ucred *cred, int *newonep)
352 {
353 	struct nfsclowner *owp = *owpp, *nowp;
354 	struct nfsclopen *op, *nop;
355 
356 	if (nowpp != NULL)
357 		nowp = *nowpp;
358 	else
359 		nowp = NULL;
360 	if (nopp != NULL)
361 		nop = *nopp;
362 	else
363 		nop = NULL;
364 	if (owp == NULL && nowp != NULL) {
365 		NFSBCOPY(own, nowp->nfsow_owner, NFSV4CL_LOCKNAMELEN);
366 		LIST_INIT(&nowp->nfsow_open);
367 		nowp->nfsow_clp = clp;
368 		nowp->nfsow_seqid = 0;
369 		nowp->nfsow_defunct = 0;
370 		nfscl_lockinit(&nowp->nfsow_rwlock);
371 		if (dp != NULL) {
372 			nfsstatsv1.cllocalopenowners++;
373 			LIST_INSERT_HEAD(&dp->nfsdl_owner, nowp, nfsow_list);
374 		} else {
375 			nfsstatsv1.clopenowners++;
376 			LIST_INSERT_HEAD(&clp->nfsc_owner, nowp, nfsow_list);
377 		}
378 		owp = *owpp = nowp;
379 		*nowpp = NULL;
380 		if (newonep != NULL)
381 			*newonep = 1;
382 	}
383 
384 	 /* If an fhp has been specified, create an Open as well. */
385 	if (fhp != NULL) {
386 		/* and look for the correct open, based upon FH */
387 		LIST_FOREACH(op, &owp->nfsow_open, nfso_list) {
388 			if (op->nfso_fhlen == fhlen &&
389 			    !NFSBCMP(op->nfso_fh, fhp, fhlen))
390 				break;
391 		}
392 		if (op == NULL && nop != NULL) {
393 			nop->nfso_own = owp;
394 			nop->nfso_mode = 0;
395 			nop->nfso_opencnt = 0;
396 			nop->nfso_posixlock = 1;
397 			nop->nfso_fhlen = fhlen;
398 			NFSBCOPY(fhp, nop->nfso_fh, fhlen);
399 			LIST_INIT(&nop->nfso_lock);
400 			nop->nfso_stateid.seqid = 0;
401 			nop->nfso_stateid.other[0] = 0;
402 			nop->nfso_stateid.other[1] = 0;
403 			nop->nfso_stateid.other[2] = 0;
404 			KASSERT(cred != NULL, ("%s: cred NULL\n", __func__));
405 			newnfs_copyincred(cred, &nop->nfso_cred);
406 			if (dp != NULL) {
407 				TAILQ_REMOVE(&clp->nfsc_deleg, dp, nfsdl_list);
408 				TAILQ_INSERT_HEAD(&clp->nfsc_deleg, dp,
409 				    nfsdl_list);
410 				dp->nfsdl_timestamp = NFSD_MONOSEC + 120;
411 				nfsstatsv1.cllocalopens++;
412 			} else {
413 				nfsstatsv1.clopens++;
414 			}
415 			LIST_INSERT_HEAD(&owp->nfsow_open, nop, nfso_list);
416 			*opp = nop;
417 			*nopp = NULL;
418 			if (newonep != NULL)
419 				*newonep = 1;
420 		} else {
421 			*opp = op;
422 		}
423 	}
424 }
425 
426 /*
427  * Called to find/add a delegation to a client.
428  */
429 APPLESTATIC int
430 nfscl_deleg(mount_t mp, struct nfsclclient *clp, u_int8_t *nfhp,
431     int fhlen, struct ucred *cred, NFSPROC_T *p, struct nfscldeleg **dpp)
432 {
433 	struct nfscldeleg *dp = *dpp, *tdp;
434 
435 	/*
436 	 * First, if we have received a Read delegation for a file on a
437 	 * read/write file system, just return it, because they aren't
438 	 * useful, imho.
439 	 */
440 	if (mp != NULL && dp != NULL && !NFSMNT_RDONLY(mp) &&
441 	    (dp->nfsdl_flags & NFSCLDL_READ)) {
442 		(void) nfscl_trydelegreturn(dp, cred, VFSTONFS(mp), p);
443 		free(dp, M_NFSCLDELEG);
444 		*dpp = NULL;
445 		return (0);
446 	}
447 
448 	/* Look for the correct deleg, based upon FH */
449 	NFSLOCKCLSTATE();
450 	tdp = nfscl_finddeleg(clp, nfhp, fhlen);
451 	if (tdp == NULL) {
452 		if (dp == NULL) {
453 			NFSUNLOCKCLSTATE();
454 			return (NFSERR_BADSTATEID);
455 		}
456 		*dpp = NULL;
457 		TAILQ_INSERT_HEAD(&clp->nfsc_deleg, dp, nfsdl_list);
458 		LIST_INSERT_HEAD(NFSCLDELEGHASH(clp, nfhp, fhlen), dp,
459 		    nfsdl_hash);
460 		dp->nfsdl_timestamp = NFSD_MONOSEC + 120;
461 		nfsstatsv1.cldelegates++;
462 		nfscl_delegcnt++;
463 	} else {
464 		/*
465 		 * Delegation already exists, what do we do if a new one??
466 		 */
467 		if (dp != NULL) {
468 			printf("Deleg already exists!\n");
469 			free(dp, M_NFSCLDELEG);
470 			*dpp = NULL;
471 		} else {
472 			*dpp = tdp;
473 		}
474 	}
475 	NFSUNLOCKCLSTATE();
476 	return (0);
477 }
478 
479 /*
480  * Find a delegation for this file handle. Return NULL upon failure.
481  */
482 static struct nfscldeleg *
483 nfscl_finddeleg(struct nfsclclient *clp, u_int8_t *fhp, int fhlen)
484 {
485 	struct nfscldeleg *dp;
486 
487 	LIST_FOREACH(dp, NFSCLDELEGHASH(clp, fhp, fhlen), nfsdl_hash) {
488 	    if (dp->nfsdl_fhlen == fhlen &&
489 		!NFSBCMP(dp->nfsdl_fh, fhp, fhlen))
490 		break;
491 	}
492 	return (dp);
493 }
494 
495 /*
496  * Get a stateid for an I/O operation. First, look for an open and iff
497  * found, return either a lockowner stateid or the open stateid.
498  * If no Open is found, just return error and the special stateid of all zeros.
499  */
500 APPLESTATIC int
501 nfscl_getstateid(vnode_t vp, u_int8_t *nfhp, int fhlen, u_int32_t mode,
502     int fords, struct ucred *cred, NFSPROC_T *p, nfsv4stateid_t *stateidp,
503     void **lckpp)
504 {
505 	struct nfsclclient *clp;
506 	struct nfsclowner *owp;
507 	struct nfsclopen *op = NULL, *top;
508 	struct nfscllockowner *lp;
509 	struct nfscldeleg *dp;
510 	struct nfsnode *np;
511 	struct nfsmount *nmp;
512 	u_int8_t own[NFSV4CL_LOCKNAMELEN];
513 	int error, done;
514 
515 	*lckpp = NULL;
516 	/*
517 	 * Initially, just set the special stateid of all zeros.
518 	 * (Don't do this for a DS, since the special stateid can't be used.)
519 	 */
520 	if (fords == 0) {
521 		stateidp->seqid = 0;
522 		stateidp->other[0] = 0;
523 		stateidp->other[1] = 0;
524 		stateidp->other[2] = 0;
525 	}
526 	if (vnode_vtype(vp) != VREG)
527 		return (EISDIR);
528 	np = VTONFS(vp);
529 	nmp = VFSTONFS(vnode_mount(vp));
530 	NFSLOCKCLSTATE();
531 	clp = nfscl_findcl(nmp);
532 	if (clp == NULL) {
533 		NFSUNLOCKCLSTATE();
534 		return (EACCES);
535 	}
536 
537 	/*
538 	 * Wait for recovery to complete.
539 	 */
540 	while ((clp->nfsc_flags & NFSCLFLAGS_RECVRINPROG))
541 		(void) nfsmsleep(&clp->nfsc_flags, NFSCLSTATEMUTEXPTR,
542 		    PZERO, "nfsrecvr", NULL);
543 
544 	/*
545 	 * First, look for a delegation.
546 	 */
547 	LIST_FOREACH(dp, NFSCLDELEGHASH(clp, nfhp, fhlen), nfsdl_hash) {
548 		if (dp->nfsdl_fhlen == fhlen &&
549 		    !NFSBCMP(nfhp, dp->nfsdl_fh, fhlen)) {
550 			if (!(mode & NFSV4OPEN_ACCESSWRITE) ||
551 			    (dp->nfsdl_flags & NFSCLDL_WRITE)) {
552 				stateidp->seqid = dp->nfsdl_stateid.seqid;
553 				stateidp->other[0] = dp->nfsdl_stateid.other[0];
554 				stateidp->other[1] = dp->nfsdl_stateid.other[1];
555 				stateidp->other[2] = dp->nfsdl_stateid.other[2];
556 				if (!(np->n_flag & NDELEGRECALL)) {
557 					TAILQ_REMOVE(&clp->nfsc_deleg, dp,
558 					    nfsdl_list);
559 					TAILQ_INSERT_HEAD(&clp->nfsc_deleg, dp,
560 					    nfsdl_list);
561 					dp->nfsdl_timestamp = NFSD_MONOSEC +
562 					    120;
563 					dp->nfsdl_rwlock.nfslock_usecnt++;
564 					*lckpp = (void *)&dp->nfsdl_rwlock;
565 				}
566 				NFSUNLOCKCLSTATE();
567 				return (0);
568 			}
569 			break;
570 		}
571 	}
572 
573 	if (p != NULL) {
574 		/*
575 		 * If p != NULL, we want to search the parentage tree
576 		 * for a matching OpenOwner and use that.
577 		 */
578 		if (NFSHASONEOPENOWN(VFSTONFS(vnode_mount(vp))))
579 			nfscl_filllockowner(NULL, own, F_POSIX);
580 		else
581 			nfscl_filllockowner(p->td_proc, own, F_POSIX);
582 		lp = NULL;
583 		error = nfscl_getopen(&clp->nfsc_owner, nfhp, fhlen, own, own,
584 		    mode, &lp, &op);
585 		if (error == 0 && lp != NULL && fords == 0) {
586 			/* Don't return a lock stateid for a DS. */
587 			stateidp->seqid =
588 			    lp->nfsl_stateid.seqid;
589 			stateidp->other[0] =
590 			    lp->nfsl_stateid.other[0];
591 			stateidp->other[1] =
592 			    lp->nfsl_stateid.other[1];
593 			stateidp->other[2] =
594 			    lp->nfsl_stateid.other[2];
595 			NFSUNLOCKCLSTATE();
596 			return (0);
597 		}
598 	}
599 	if (op == NULL) {
600 		/* If not found, just look for any OpenOwner that will work. */
601 		top = NULL;
602 		done = 0;
603 		owp = LIST_FIRST(&clp->nfsc_owner);
604 		while (!done && owp != NULL) {
605 			LIST_FOREACH(op, &owp->nfsow_open, nfso_list) {
606 				if (op->nfso_fhlen == fhlen &&
607 				    !NFSBCMP(op->nfso_fh, nfhp, fhlen)) {
608 					if (top == NULL && (op->nfso_mode &
609 					    NFSV4OPEN_ACCESSWRITE) != 0 &&
610 					    (mode & NFSV4OPEN_ACCESSREAD) != 0)
611 						top = op;
612 					if ((mode & op->nfso_mode) == mode) {
613 						done = 1;
614 						break;
615 					}
616 				}
617 			}
618 			if (!done)
619 				owp = LIST_NEXT(owp, nfsow_list);
620 		}
621 		if (!done) {
622 			NFSCL_DEBUG(2, "openmode top=%p\n", top);
623 			if (top == NULL || NFSHASOPENMODE(nmp)) {
624 				NFSUNLOCKCLSTATE();
625 				return (ENOENT);
626 			} else
627 				op = top;
628 		}
629 		/*
630 		 * For read aheads or write behinds, use the open cred.
631 		 * A read ahead or write behind is indicated by p == NULL.
632 		 */
633 		if (p == NULL)
634 			newnfs_copycred(&op->nfso_cred, cred);
635 	}
636 
637 	/*
638 	 * No lock stateid, so return the open stateid.
639 	 */
640 	stateidp->seqid = op->nfso_stateid.seqid;
641 	stateidp->other[0] = op->nfso_stateid.other[0];
642 	stateidp->other[1] = op->nfso_stateid.other[1];
643 	stateidp->other[2] = op->nfso_stateid.other[2];
644 	NFSUNLOCKCLSTATE();
645 	return (0);
646 }
647 
648 /*
649  * Search for a matching file, mode and, optionally, lockowner.
650  */
651 static int
652 nfscl_getopen(struct nfsclownerhead *ohp, u_int8_t *nfhp, int fhlen,
653     u_int8_t *openown, u_int8_t *lockown, u_int32_t mode,
654     struct nfscllockowner **lpp, struct nfsclopen **opp)
655 {
656 	struct nfsclowner *owp;
657 	struct nfsclopen *op, *rop, *rop2;
658 	struct nfscllockowner *lp;
659 	int keep_looping;
660 
661 	if (lpp != NULL)
662 		*lpp = NULL;
663 	/*
664 	 * rop will be set to the open to be returned. There are three
665 	 * variants of this, all for an open of the correct file:
666 	 * 1 - A match of lockown.
667 	 * 2 - A match of the openown, when no lockown match exists.
668 	 * 3 - A match for any open, if no openown or lockown match exists.
669 	 * Looking for #2 over #3 probably isn't necessary, but since
670 	 * RFC3530 is vague w.r.t. the relationship between openowners and
671 	 * lockowners, I think this is the safer way to go.
672 	 */
673 	rop = NULL;
674 	rop2 = NULL;
675 	keep_looping = 1;
676 	/* Search the client list */
677 	owp = LIST_FIRST(ohp);
678 	while (owp != NULL && keep_looping != 0) {
679 		/* and look for the correct open */
680 		op = LIST_FIRST(&owp->nfsow_open);
681 		while (op != NULL && keep_looping != 0) {
682 			if (op->nfso_fhlen == fhlen &&
683 			    !NFSBCMP(op->nfso_fh, nfhp, fhlen)
684 			    && (op->nfso_mode & mode) == mode) {
685 				if (lpp != NULL) {
686 					/* Now look for a matching lockowner. */
687 					LIST_FOREACH(lp, &op->nfso_lock,
688 					    nfsl_list) {
689 						if (!NFSBCMP(lp->nfsl_owner,
690 						    lockown,
691 						    NFSV4CL_LOCKNAMELEN)) {
692 							*lpp = lp;
693 							rop = op;
694 							keep_looping = 0;
695 							break;
696 						}
697 					}
698 				}
699 				if (rop == NULL && !NFSBCMP(owp->nfsow_owner,
700 				    openown, NFSV4CL_LOCKNAMELEN)) {
701 					rop = op;
702 					if (lpp == NULL)
703 						keep_looping = 0;
704 				}
705 				if (rop2 == NULL)
706 					rop2 = op;
707 			}
708 			op = LIST_NEXT(op, nfso_list);
709 		}
710 		owp = LIST_NEXT(owp, nfsow_list);
711 	}
712 	if (rop == NULL)
713 		rop = rop2;
714 	if (rop == NULL)
715 		return (EBADF);
716 	*opp = rop;
717 	return (0);
718 }
719 
720 /*
721  * Release use of an open owner. Called when open operations are done
722  * with the open owner.
723  */
724 APPLESTATIC void
725 nfscl_ownerrelease(struct nfsmount *nmp, struct nfsclowner *owp,
726     __unused int error, __unused int candelete, int unlocked)
727 {
728 
729 	if (owp == NULL)
730 		return;
731 	NFSLOCKCLSTATE();
732 	if (unlocked == 0) {
733 		if (NFSHASONEOPENOWN(nmp))
734 			nfsv4_relref(&owp->nfsow_rwlock);
735 		else
736 			nfscl_lockunlock(&owp->nfsow_rwlock);
737 	}
738 	nfscl_clrelease(owp->nfsow_clp);
739 	NFSUNLOCKCLSTATE();
740 }
741 
742 /*
743  * Release use of an open structure under an open owner.
744  */
745 APPLESTATIC void
746 nfscl_openrelease(struct nfsmount *nmp, struct nfsclopen *op, int error,
747     int candelete)
748 {
749 	struct nfsclclient *clp;
750 	struct nfsclowner *owp;
751 
752 	if (op == NULL)
753 		return;
754 	NFSLOCKCLSTATE();
755 	owp = op->nfso_own;
756 	if (NFSHASONEOPENOWN(nmp))
757 		nfsv4_relref(&owp->nfsow_rwlock);
758 	else
759 		nfscl_lockunlock(&owp->nfsow_rwlock);
760 	clp = owp->nfsow_clp;
761 	if (error && candelete && op->nfso_opencnt == 0)
762 		nfscl_freeopen(op, 0);
763 	nfscl_clrelease(clp);
764 	NFSUNLOCKCLSTATE();
765 }
766 
767 /*
768  * Called to get a clientid structure. It will optionally lock the
769  * client data structures to do the SetClientId/SetClientId_confirm,
770  * but will release that lock and return the clientid with a reference
771  * count on it.
772  * If the "cred" argument is NULL, a new clientid should not be created.
773  * If the "p" argument is NULL, a SetClientID/SetClientIDConfirm cannot
774  * be done.
775  * The start_renewthread argument tells nfscl_getcl() to start a renew
776  * thread if this creates a new clp.
777  * It always clpp with a reference count on it, unless returning an error.
778  */
779 APPLESTATIC int
780 nfscl_getcl(struct mount *mp, struct ucred *cred, NFSPROC_T *p,
781     int start_renewthread, struct nfsclclient **clpp)
782 {
783 	struct nfsclclient *clp;
784 	struct nfsclclient *newclp = NULL;
785 	struct nfsmount *nmp;
786 	char uuid[HOSTUUIDLEN];
787 	int igotlock = 0, error, trystalecnt, clidinusedelay, i;
788 	u_int16_t idlen = 0;
789 
790 	nmp = VFSTONFS(mp);
791 	if (cred != NULL) {
792 		getcredhostuuid(cred, uuid, sizeof uuid);
793 		idlen = strlen(uuid);
794 		if (idlen > 0)
795 			idlen += sizeof (u_int64_t);
796 		else
797 			idlen += sizeof (u_int64_t) + 16; /* 16 random bytes */
798 		newclp = malloc(
799 		    sizeof (struct nfsclclient) + idlen - 1, M_NFSCLCLIENT,
800 		    M_WAITOK | M_ZERO);
801 	}
802 	NFSLOCKCLSTATE();
803 	/*
804 	 * If a forced dismount is already in progress, don't
805 	 * allocate a new clientid and get out now. For the case where
806 	 * clp != NULL, this is a harmless optimization.
807 	 */
808 	if (NFSCL_FORCEDISM(mp)) {
809 		NFSUNLOCKCLSTATE();
810 		if (newclp != NULL)
811 			free(newclp, M_NFSCLCLIENT);
812 		return (EBADF);
813 	}
814 	clp = nmp->nm_clp;
815 	if (clp == NULL) {
816 		if (newclp == NULL) {
817 			NFSUNLOCKCLSTATE();
818 			return (EACCES);
819 		}
820 		clp = newclp;
821 		clp->nfsc_idlen = idlen;
822 		LIST_INIT(&clp->nfsc_owner);
823 		TAILQ_INIT(&clp->nfsc_deleg);
824 		TAILQ_INIT(&clp->nfsc_layout);
825 		LIST_INIT(&clp->nfsc_devinfo);
826 		for (i = 0; i < NFSCLDELEGHASHSIZE; i++)
827 			LIST_INIT(&clp->nfsc_deleghash[i]);
828 		for (i = 0; i < NFSCLLAYOUTHASHSIZE; i++)
829 			LIST_INIT(&clp->nfsc_layouthash[i]);
830 		clp->nfsc_flags = NFSCLFLAGS_INITED;
831 		clp->nfsc_clientidrev = 1;
832 		clp->nfsc_cbident = nfscl_nextcbident();
833 		nfscl_fillclid(nmp->nm_clval, uuid, clp->nfsc_id,
834 		    clp->nfsc_idlen);
835 		LIST_INSERT_HEAD(&nfsclhead, clp, nfsc_list);
836 		nmp->nm_clp = clp;
837 		clp->nfsc_nmp = nmp;
838 		NFSUNLOCKCLSTATE();
839 		if (start_renewthread != 0)
840 			nfscl_start_renewthread(clp);
841 	} else {
842 		NFSUNLOCKCLSTATE();
843 		if (newclp != NULL)
844 			free(newclp, M_NFSCLCLIENT);
845 	}
846 	NFSLOCKCLSTATE();
847 	while ((clp->nfsc_flags & NFSCLFLAGS_HASCLIENTID) == 0 && !igotlock &&
848 	    !NFSCL_FORCEDISM(mp))
849 		igotlock = nfsv4_lock(&clp->nfsc_lock, 1, NULL,
850 		    NFSCLSTATEMUTEXPTR, mp);
851 	if (igotlock == 0) {
852 		/*
853 		 * Call nfsv4_lock() with "iwantlock == 0" so that it will
854 		 * wait for a pending exclusive lock request.  This gives the
855 		 * exclusive lock request priority over this shared lock
856 		 * request.
857 		 * An exclusive lock on nfsc_lock is used mainly for server
858 		 * crash recoveries.
859 		 */
860 		nfsv4_lock(&clp->nfsc_lock, 0, NULL, NFSCLSTATEMUTEXPTR, mp);
861 		nfsv4_getref(&clp->nfsc_lock, NULL, NFSCLSTATEMUTEXPTR, mp);
862 	}
863 	if (igotlock == 0 && NFSCL_FORCEDISM(mp)) {
864 		/*
865 		 * Both nfsv4_lock() and nfsv4_getref() know to check
866 		 * for NFSCL_FORCEDISM() and return without sleeping to
867 		 * wait for the exclusive lock to be released, since it
868 		 * might be held by nfscl_umount() and we need to get out
869 		 * now for that case and not wait until nfscl_umount()
870 		 * releases it.
871 		 */
872 		NFSUNLOCKCLSTATE();
873 		return (EBADF);
874 	}
875 	NFSUNLOCKCLSTATE();
876 
877 	/*
878 	 * If it needs a clientid, do the setclientid now.
879 	 */
880 	if ((clp->nfsc_flags & NFSCLFLAGS_HASCLIENTID) == 0) {
881 		if (!igotlock)
882 			panic("nfscl_clget");
883 		if (p == NULL || cred == NULL) {
884 			NFSLOCKCLSTATE();
885 			nfsv4_unlock(&clp->nfsc_lock, 0);
886 			NFSUNLOCKCLSTATE();
887 			return (EACCES);
888 		}
889 		/*
890 		 * If RFC3530 Sec. 14.2.33 is taken literally,
891 		 * NFSERR_CLIDINUSE will be returned persistently for the
892 		 * case where a new mount of the same file system is using
893 		 * a different principal. In practice, NFSERR_CLIDINUSE is
894 		 * only returned when there is outstanding unexpired state
895 		 * on the clientid. As such, try for twice the lease
896 		 * interval, if we know what that is. Otherwise, make a
897 		 * wild ass guess.
898 		 * The case of returning NFSERR_STALECLIENTID is far less
899 		 * likely, but might occur if there is a significant delay
900 		 * between doing the SetClientID and SetClientIDConfirm Ops,
901 		 * such that the server throws away the clientid before
902 		 * receiving the SetClientIDConfirm.
903 		 */
904 		if (clp->nfsc_renew > 0)
905 			clidinusedelay = NFSCL_LEASE(clp->nfsc_renew) * 2;
906 		else
907 			clidinusedelay = 120;
908 		trystalecnt = 3;
909 		do {
910 			error = nfsrpc_setclient(nmp, clp, 0, cred, p);
911 			if (error == NFSERR_STALECLIENTID ||
912 			    error == NFSERR_STALEDONTRECOVER ||
913 			    error == NFSERR_BADSESSION ||
914 			    error == NFSERR_CLIDINUSE) {
915 				(void) nfs_catnap(PZERO, error, "nfs_setcl");
916 			}
917 		} while (((error == NFSERR_STALECLIENTID ||
918 		     error == NFSERR_BADSESSION ||
919 		     error == NFSERR_STALEDONTRECOVER) && --trystalecnt > 0) ||
920 		    (error == NFSERR_CLIDINUSE && --clidinusedelay > 0));
921 		if (error) {
922 			NFSLOCKCLSTATE();
923 			nfsv4_unlock(&clp->nfsc_lock, 0);
924 			NFSUNLOCKCLSTATE();
925 			return (error);
926 		}
927 		clp->nfsc_flags |= NFSCLFLAGS_HASCLIENTID;
928 	}
929 	if (igotlock) {
930 		NFSLOCKCLSTATE();
931 		nfsv4_unlock(&clp->nfsc_lock, 1);
932 		NFSUNLOCKCLSTATE();
933 	}
934 
935 	*clpp = clp;
936 	return (0);
937 }
938 
939 /*
940  * Get a reference to a clientid and return it, if valid.
941  */
942 APPLESTATIC struct nfsclclient *
943 nfscl_findcl(struct nfsmount *nmp)
944 {
945 	struct nfsclclient *clp;
946 
947 	clp = nmp->nm_clp;
948 	if (clp == NULL || !(clp->nfsc_flags & NFSCLFLAGS_HASCLIENTID))
949 		return (NULL);
950 	return (clp);
951 }
952 
953 /*
954  * Release the clientid structure. It may be locked or reference counted.
955  */
956 static void
957 nfscl_clrelease(struct nfsclclient *clp)
958 {
959 
960 	if (clp->nfsc_lock.nfslock_lock & NFSV4LOCK_LOCK)
961 		nfsv4_unlock(&clp->nfsc_lock, 0);
962 	else
963 		nfsv4_relref(&clp->nfsc_lock);
964 }
965 
966 /*
967  * External call for nfscl_clrelease.
968  */
969 APPLESTATIC void
970 nfscl_clientrelease(struct nfsclclient *clp)
971 {
972 
973 	NFSLOCKCLSTATE();
974 	if (clp->nfsc_lock.nfslock_lock & NFSV4LOCK_LOCK)
975 		nfsv4_unlock(&clp->nfsc_lock, 0);
976 	else
977 		nfsv4_relref(&clp->nfsc_lock);
978 	NFSUNLOCKCLSTATE();
979 }
980 
981 /*
982  * Called when wanting to lock a byte region.
983  */
984 APPLESTATIC int
985 nfscl_getbytelock(vnode_t vp, u_int64_t off, u_int64_t len,
986     short type, struct ucred *cred, NFSPROC_T *p, struct nfsclclient *rclp,
987     int recovery, void *id, int flags, u_int8_t *rownp, u_int8_t *ropenownp,
988     struct nfscllockowner **lpp, int *newonep, int *donelocallyp)
989 {
990 	struct nfscllockowner *lp;
991 	struct nfsclopen *op;
992 	struct nfsclclient *clp;
993 	struct nfscllockowner *nlp;
994 	struct nfscllock *nlop, *otherlop;
995 	struct nfscldeleg *dp = NULL, *ldp = NULL;
996 	struct nfscllockownerhead *lhp = NULL;
997 	struct nfsnode *np;
998 	u_int8_t own[NFSV4CL_LOCKNAMELEN], *ownp, openown[NFSV4CL_LOCKNAMELEN];
999 	u_int8_t *openownp;
1000 	int error = 0, ret, donelocally = 0;
1001 	u_int32_t mode;
1002 
1003 	/* For Lock Ops, the open mode doesn't matter, so use 0 to match any. */
1004 	mode = 0;
1005 	np = VTONFS(vp);
1006 	*lpp = NULL;
1007 	lp = NULL;
1008 	*newonep = 0;
1009 	*donelocallyp = 0;
1010 
1011 	/*
1012 	 * Might need these, so MALLOC them now, to
1013 	 * avoid a tsleep() in MALLOC later.
1014 	 */
1015 	nlp = malloc(
1016 	    sizeof (struct nfscllockowner), M_NFSCLLOCKOWNER, M_WAITOK);
1017 	otherlop = malloc(
1018 	    sizeof (struct nfscllock), M_NFSCLLOCK, M_WAITOK);
1019 	nlop = malloc(
1020 	    sizeof (struct nfscllock), M_NFSCLLOCK, M_WAITOK);
1021 	nlop->nfslo_type = type;
1022 	nlop->nfslo_first = off;
1023 	if (len == NFS64BITSSET) {
1024 		nlop->nfslo_end = NFS64BITSSET;
1025 	} else {
1026 		nlop->nfslo_end = off + len;
1027 		if (nlop->nfslo_end <= nlop->nfslo_first)
1028 			error = NFSERR_INVAL;
1029 	}
1030 
1031 	if (!error) {
1032 		if (recovery)
1033 			clp = rclp;
1034 		else
1035 			error = nfscl_getcl(vnode_mount(vp), cred, p, 1, &clp);
1036 	}
1037 	if (error) {
1038 		free(nlp, M_NFSCLLOCKOWNER);
1039 		free(otherlop, M_NFSCLLOCK);
1040 		free(nlop, M_NFSCLLOCK);
1041 		return (error);
1042 	}
1043 
1044 	op = NULL;
1045 	if (recovery) {
1046 		ownp = rownp;
1047 		openownp = ropenownp;
1048 	} else {
1049 		nfscl_filllockowner(id, own, flags);
1050 		ownp = own;
1051 		if (NFSHASONEOPENOWN(VFSTONFS(vnode_mount(vp))))
1052 			nfscl_filllockowner(NULL, openown, F_POSIX);
1053 		else
1054 			nfscl_filllockowner(p->td_proc, openown, F_POSIX);
1055 		openownp = openown;
1056 	}
1057 	if (!recovery) {
1058 		NFSLOCKCLSTATE();
1059 		/*
1060 		 * First, search for a delegation. If one exists for this file,
1061 		 * the lock can be done locally against it, so long as there
1062 		 * isn't a local lock conflict.
1063 		 */
1064 		ldp = dp = nfscl_finddeleg(clp, np->n_fhp->nfh_fh,
1065 		    np->n_fhp->nfh_len);
1066 		/* Just sanity check for correct type of delegation */
1067 		if (dp != NULL && ((dp->nfsdl_flags &
1068 		    (NFSCLDL_RECALL | NFSCLDL_DELEGRET)) != 0 ||
1069 		     (type == F_WRLCK &&
1070 		      (dp->nfsdl_flags & NFSCLDL_WRITE) == 0)))
1071 			dp = NULL;
1072 	}
1073 	if (dp != NULL) {
1074 		/* Now, find an open and maybe a lockowner. */
1075 		ret = nfscl_getopen(&dp->nfsdl_owner, np->n_fhp->nfh_fh,
1076 		    np->n_fhp->nfh_len, openownp, ownp, mode, NULL, &op);
1077 		if (ret)
1078 			ret = nfscl_getopen(&clp->nfsc_owner,
1079 			    np->n_fhp->nfh_fh, np->n_fhp->nfh_len, openownp,
1080 			    ownp, mode, NULL, &op);
1081 		if (!ret) {
1082 			lhp = &dp->nfsdl_lock;
1083 			TAILQ_REMOVE(&clp->nfsc_deleg, dp, nfsdl_list);
1084 			TAILQ_INSERT_HEAD(&clp->nfsc_deleg, dp, nfsdl_list);
1085 			dp->nfsdl_timestamp = NFSD_MONOSEC + 120;
1086 			donelocally = 1;
1087 		} else {
1088 			dp = NULL;
1089 		}
1090 	}
1091 	if (!donelocally) {
1092 		/*
1093 		 * Get the related Open and maybe lockowner.
1094 		 */
1095 		error = nfscl_getopen(&clp->nfsc_owner,
1096 		    np->n_fhp->nfh_fh, np->n_fhp->nfh_len, openownp,
1097 		    ownp, mode, &lp, &op);
1098 		if (!error)
1099 			lhp = &op->nfso_lock;
1100 	}
1101 	if (!error && !recovery)
1102 		error = nfscl_localconflict(clp, np->n_fhp->nfh_fh,
1103 		    np->n_fhp->nfh_len, nlop, ownp, ldp, NULL);
1104 	if (error) {
1105 		if (!recovery) {
1106 			nfscl_clrelease(clp);
1107 			NFSUNLOCKCLSTATE();
1108 		}
1109 		free(nlp, M_NFSCLLOCKOWNER);
1110 		free(otherlop, M_NFSCLLOCK);
1111 		free(nlop, M_NFSCLLOCK);
1112 		return (error);
1113 	}
1114 
1115 	/*
1116 	 * Ok, see if a lockowner exists and create one, as required.
1117 	 */
1118 	if (lp == NULL)
1119 		LIST_FOREACH(lp, lhp, nfsl_list) {
1120 			if (!NFSBCMP(lp->nfsl_owner, ownp, NFSV4CL_LOCKNAMELEN))
1121 				break;
1122 		}
1123 	if (lp == NULL) {
1124 		NFSBCOPY(ownp, nlp->nfsl_owner, NFSV4CL_LOCKNAMELEN);
1125 		if (recovery)
1126 			NFSBCOPY(ropenownp, nlp->nfsl_openowner,
1127 			    NFSV4CL_LOCKNAMELEN);
1128 		else
1129 			NFSBCOPY(op->nfso_own->nfsow_owner, nlp->nfsl_openowner,
1130 			    NFSV4CL_LOCKNAMELEN);
1131 		nlp->nfsl_seqid = 0;
1132 		nlp->nfsl_lockflags = flags;
1133 		nlp->nfsl_inprog = NULL;
1134 		nfscl_lockinit(&nlp->nfsl_rwlock);
1135 		LIST_INIT(&nlp->nfsl_lock);
1136 		if (donelocally) {
1137 			nlp->nfsl_open = NULL;
1138 			nfsstatsv1.cllocallockowners++;
1139 		} else {
1140 			nlp->nfsl_open = op;
1141 			nfsstatsv1.cllockowners++;
1142 		}
1143 		LIST_INSERT_HEAD(lhp, nlp, nfsl_list);
1144 		lp = nlp;
1145 		nlp = NULL;
1146 		*newonep = 1;
1147 	}
1148 
1149 	/*
1150 	 * Now, update the byte ranges for locks.
1151 	 */
1152 	ret = nfscl_updatelock(lp, &nlop, &otherlop, donelocally);
1153 	if (!ret)
1154 		donelocally = 1;
1155 	if (donelocally) {
1156 		*donelocallyp = 1;
1157 		if (!recovery)
1158 			nfscl_clrelease(clp);
1159 	} else {
1160 		/*
1161 		 * Serial modifications on the lock owner for multiple threads
1162 		 * for the same process using a read/write lock.
1163 		 */
1164 		if (!recovery)
1165 			nfscl_lockexcl(&lp->nfsl_rwlock, NFSCLSTATEMUTEXPTR);
1166 	}
1167 	if (!recovery)
1168 		NFSUNLOCKCLSTATE();
1169 
1170 	if (nlp)
1171 		free(nlp, M_NFSCLLOCKOWNER);
1172 	if (nlop)
1173 		free(nlop, M_NFSCLLOCK);
1174 	if (otherlop)
1175 		free(otherlop, M_NFSCLLOCK);
1176 
1177 	*lpp = lp;
1178 	return (0);
1179 }
1180 
1181 /*
1182  * Called to unlock a byte range, for LockU.
1183  */
1184 APPLESTATIC int
1185 nfscl_relbytelock(vnode_t vp, u_int64_t off, u_int64_t len,
1186     __unused struct ucred *cred, NFSPROC_T *p, int callcnt,
1187     struct nfsclclient *clp, void *id, int flags,
1188     struct nfscllockowner **lpp, int *dorpcp)
1189 {
1190 	struct nfscllockowner *lp;
1191 	struct nfsclowner *owp;
1192 	struct nfsclopen *op;
1193 	struct nfscllock *nlop, *other_lop = NULL;
1194 	struct nfscldeleg *dp;
1195 	struct nfsnode *np;
1196 	u_int8_t own[NFSV4CL_LOCKNAMELEN];
1197 	int ret = 0, fnd;
1198 
1199 	np = VTONFS(vp);
1200 	*lpp = NULL;
1201 	*dorpcp = 0;
1202 
1203 	/*
1204 	 * Might need these, so MALLOC them now, to
1205 	 * avoid a tsleep() in MALLOC later.
1206 	 */
1207 	nlop = malloc(
1208 	    sizeof (struct nfscllock), M_NFSCLLOCK, M_WAITOK);
1209 	nlop->nfslo_type = F_UNLCK;
1210 	nlop->nfslo_first = off;
1211 	if (len == NFS64BITSSET) {
1212 		nlop->nfslo_end = NFS64BITSSET;
1213 	} else {
1214 		nlop->nfslo_end = off + len;
1215 		if (nlop->nfslo_end <= nlop->nfslo_first) {
1216 			free(nlop, M_NFSCLLOCK);
1217 			return (NFSERR_INVAL);
1218 		}
1219 	}
1220 	if (callcnt == 0) {
1221 		other_lop = malloc(
1222 		    sizeof (struct nfscllock), M_NFSCLLOCK, M_WAITOK);
1223 		*other_lop = *nlop;
1224 	}
1225 	nfscl_filllockowner(id, own, flags);
1226 	dp = NULL;
1227 	NFSLOCKCLSTATE();
1228 	if (callcnt == 0)
1229 		dp = nfscl_finddeleg(clp, np->n_fhp->nfh_fh,
1230 		    np->n_fhp->nfh_len);
1231 
1232 	/*
1233 	 * First, unlock any local regions on a delegation.
1234 	 */
1235 	if (dp != NULL) {
1236 		/* Look for this lockowner. */
1237 		LIST_FOREACH(lp, &dp->nfsdl_lock, nfsl_list) {
1238 			if (!NFSBCMP(lp->nfsl_owner, own,
1239 			    NFSV4CL_LOCKNAMELEN))
1240 				break;
1241 		}
1242 		if (lp != NULL)
1243 			/* Use other_lop, so nlop is still available */
1244 			(void)nfscl_updatelock(lp, &other_lop, NULL, 1);
1245 	}
1246 
1247 	/*
1248 	 * Now, find a matching open/lockowner that hasn't already been done,
1249 	 * as marked by nfsl_inprog.
1250 	 */
1251 	lp = NULL;
1252 	fnd = 0;
1253 	LIST_FOREACH(owp, &clp->nfsc_owner, nfsow_list) {
1254 	    LIST_FOREACH(op, &owp->nfsow_open, nfso_list) {
1255 		if (op->nfso_fhlen == np->n_fhp->nfh_len &&
1256 		    !NFSBCMP(op->nfso_fh, np->n_fhp->nfh_fh, op->nfso_fhlen)) {
1257 		    LIST_FOREACH(lp, &op->nfso_lock, nfsl_list) {
1258 			if (lp->nfsl_inprog == NULL &&
1259 			    !NFSBCMP(lp->nfsl_owner, own,
1260 			     NFSV4CL_LOCKNAMELEN)) {
1261 				fnd = 1;
1262 				break;
1263 			}
1264 		    }
1265 		    if (fnd)
1266 			break;
1267 		}
1268 	    }
1269 	    if (fnd)
1270 		break;
1271 	}
1272 
1273 	if (lp != NULL) {
1274 		ret = nfscl_updatelock(lp, &nlop, NULL, 0);
1275 		if (ret)
1276 			*dorpcp = 1;
1277 		/*
1278 		 * Serial modifications on the lock owner for multiple
1279 		 * threads for the same process using a read/write lock.
1280 		 */
1281 		lp->nfsl_inprog = p;
1282 		nfscl_lockexcl(&lp->nfsl_rwlock, NFSCLSTATEMUTEXPTR);
1283 		*lpp = lp;
1284 	}
1285 	NFSUNLOCKCLSTATE();
1286 	if (nlop)
1287 		free(nlop, M_NFSCLLOCK);
1288 	if (other_lop)
1289 		free(other_lop, M_NFSCLLOCK);
1290 	return (0);
1291 }
1292 
1293 /*
1294  * Release all lockowners marked in progess for this process and file.
1295  */
1296 APPLESTATIC void
1297 nfscl_releasealllocks(struct nfsclclient *clp, vnode_t vp, NFSPROC_T *p,
1298     void *id, int flags)
1299 {
1300 	struct nfsclowner *owp;
1301 	struct nfsclopen *op;
1302 	struct nfscllockowner *lp;
1303 	struct nfsnode *np;
1304 	u_int8_t own[NFSV4CL_LOCKNAMELEN];
1305 
1306 	np = VTONFS(vp);
1307 	nfscl_filllockowner(id, own, flags);
1308 	NFSLOCKCLSTATE();
1309 	LIST_FOREACH(owp, &clp->nfsc_owner, nfsow_list) {
1310 	    LIST_FOREACH(op, &owp->nfsow_open, nfso_list) {
1311 		if (op->nfso_fhlen == np->n_fhp->nfh_len &&
1312 		    !NFSBCMP(op->nfso_fh, np->n_fhp->nfh_fh, op->nfso_fhlen)) {
1313 		    LIST_FOREACH(lp, &op->nfso_lock, nfsl_list) {
1314 			if (lp->nfsl_inprog == p &&
1315 			    !NFSBCMP(lp->nfsl_owner, own,
1316 			    NFSV4CL_LOCKNAMELEN)) {
1317 			    lp->nfsl_inprog = NULL;
1318 			    nfscl_lockunlock(&lp->nfsl_rwlock);
1319 			}
1320 		    }
1321 		}
1322 	    }
1323 	}
1324 	nfscl_clrelease(clp);
1325 	NFSUNLOCKCLSTATE();
1326 }
1327 
1328 /*
1329  * Called to find out if any bytes within the byte range specified are
1330  * write locked by the calling process. Used to determine if flushing
1331  * is required before a LockU.
1332  * If in doubt, return 1, so the flush will occur.
1333  */
1334 APPLESTATIC int
1335 nfscl_checkwritelocked(vnode_t vp, struct flock *fl,
1336     struct ucred *cred, NFSPROC_T *p, void *id, int flags)
1337 {
1338 	struct nfsclowner *owp;
1339 	struct nfscllockowner *lp;
1340 	struct nfsclopen *op;
1341 	struct nfsclclient *clp;
1342 	struct nfscllock *lop;
1343 	struct nfscldeleg *dp;
1344 	struct nfsnode *np;
1345 	u_int64_t off, end;
1346 	u_int8_t own[NFSV4CL_LOCKNAMELEN];
1347 	int error = 0;
1348 
1349 	np = VTONFS(vp);
1350 	switch (fl->l_whence) {
1351 	case SEEK_SET:
1352 	case SEEK_CUR:
1353 		/*
1354 		 * Caller is responsible for adding any necessary offset
1355 		 * when SEEK_CUR is used.
1356 		 */
1357 		off = fl->l_start;
1358 		break;
1359 	case SEEK_END:
1360 		off = np->n_size + fl->l_start;
1361 		break;
1362 	default:
1363 		return (1);
1364 	}
1365 	if (fl->l_len != 0) {
1366 		end = off + fl->l_len;
1367 		if (end < off)
1368 			return (1);
1369 	} else {
1370 		end = NFS64BITSSET;
1371 	}
1372 
1373 	error = nfscl_getcl(vnode_mount(vp), cred, p, 1, &clp);
1374 	if (error)
1375 		return (1);
1376 	nfscl_filllockowner(id, own, flags);
1377 	NFSLOCKCLSTATE();
1378 
1379 	/*
1380 	 * First check the delegation locks.
1381 	 */
1382 	dp = nfscl_finddeleg(clp, np->n_fhp->nfh_fh, np->n_fhp->nfh_len);
1383 	if (dp != NULL) {
1384 		LIST_FOREACH(lp, &dp->nfsdl_lock, nfsl_list) {
1385 			if (!NFSBCMP(lp->nfsl_owner, own,
1386 			    NFSV4CL_LOCKNAMELEN))
1387 				break;
1388 		}
1389 		if (lp != NULL) {
1390 			LIST_FOREACH(lop, &lp->nfsl_lock, nfslo_list) {
1391 				if (lop->nfslo_first >= end)
1392 					break;
1393 				if (lop->nfslo_end <= off)
1394 					continue;
1395 				if (lop->nfslo_type == F_WRLCK) {
1396 					nfscl_clrelease(clp);
1397 					NFSUNLOCKCLSTATE();
1398 					return (1);
1399 				}
1400 			}
1401 		}
1402 	}
1403 
1404 	/*
1405 	 * Now, check state against the server.
1406 	 */
1407 	LIST_FOREACH(owp, &clp->nfsc_owner, nfsow_list) {
1408 	    LIST_FOREACH(op, &owp->nfsow_open, nfso_list) {
1409 		if (op->nfso_fhlen == np->n_fhp->nfh_len &&
1410 		    !NFSBCMP(op->nfso_fh, np->n_fhp->nfh_fh, op->nfso_fhlen)) {
1411 		    LIST_FOREACH(lp, &op->nfso_lock, nfsl_list) {
1412 			if (!NFSBCMP(lp->nfsl_owner, own,
1413 			    NFSV4CL_LOCKNAMELEN))
1414 			    break;
1415 		    }
1416 		    if (lp != NULL) {
1417 			LIST_FOREACH(lop, &lp->nfsl_lock, nfslo_list) {
1418 			    if (lop->nfslo_first >= end)
1419 				break;
1420 			    if (lop->nfslo_end <= off)
1421 				continue;
1422 			    if (lop->nfslo_type == F_WRLCK) {
1423 				nfscl_clrelease(clp);
1424 				NFSUNLOCKCLSTATE();
1425 				return (1);
1426 			    }
1427 			}
1428 		    }
1429 		}
1430 	    }
1431 	}
1432 	nfscl_clrelease(clp);
1433 	NFSUNLOCKCLSTATE();
1434 	return (0);
1435 }
1436 
1437 /*
1438  * Release a byte range lock owner structure.
1439  */
1440 APPLESTATIC void
1441 nfscl_lockrelease(struct nfscllockowner *lp, int error, int candelete)
1442 {
1443 	struct nfsclclient *clp;
1444 
1445 	if (lp == NULL)
1446 		return;
1447 	NFSLOCKCLSTATE();
1448 	clp = lp->nfsl_open->nfso_own->nfsow_clp;
1449 	if (error != 0 && candelete &&
1450 	    (lp->nfsl_rwlock.nfslock_lock & NFSV4LOCK_WANTED) == 0)
1451 		nfscl_freelockowner(lp, 0);
1452 	else
1453 		nfscl_lockunlock(&lp->nfsl_rwlock);
1454 	nfscl_clrelease(clp);
1455 	NFSUNLOCKCLSTATE();
1456 }
1457 
1458 /*
1459  * Free up an open structure and any associated byte range lock structures.
1460  */
1461 APPLESTATIC void
1462 nfscl_freeopen(struct nfsclopen *op, int local)
1463 {
1464 
1465 	LIST_REMOVE(op, nfso_list);
1466 	nfscl_freealllocks(&op->nfso_lock, local);
1467 	free(op, M_NFSCLOPEN);
1468 	if (local)
1469 		nfsstatsv1.cllocalopens--;
1470 	else
1471 		nfsstatsv1.clopens--;
1472 }
1473 
1474 /*
1475  * Free up all lock owners and associated locks.
1476  */
1477 static void
1478 nfscl_freealllocks(struct nfscllockownerhead *lhp, int local)
1479 {
1480 	struct nfscllockowner *lp, *nlp;
1481 
1482 	LIST_FOREACH_SAFE(lp, lhp, nfsl_list, nlp) {
1483 		if ((lp->nfsl_rwlock.nfslock_lock & NFSV4LOCK_WANTED))
1484 			panic("nfscllckw");
1485 		nfscl_freelockowner(lp, local);
1486 	}
1487 }
1488 
1489 /*
1490  * Called for an Open when NFSERR_EXPIRED is received from the server.
1491  * If there are no byte range locks nor a Share Deny lost, try to do a
1492  * fresh Open. Otherwise, free the open.
1493  */
1494 static int
1495 nfscl_expireopen(struct nfsclclient *clp, struct nfsclopen *op,
1496     struct nfsmount *nmp, struct ucred *cred, NFSPROC_T *p)
1497 {
1498 	struct nfscllockowner *lp;
1499 	struct nfscldeleg *dp;
1500 	int mustdelete = 0, error;
1501 
1502 	/*
1503 	 * Look for any byte range lock(s).
1504 	 */
1505 	LIST_FOREACH(lp, &op->nfso_lock, nfsl_list) {
1506 		if (!LIST_EMPTY(&lp->nfsl_lock)) {
1507 			mustdelete = 1;
1508 			break;
1509 		}
1510 	}
1511 
1512 	/*
1513 	 * If no byte range lock(s) nor a Share deny, try to re-open.
1514 	 */
1515 	if (!mustdelete && (op->nfso_mode & NFSLCK_DENYBITS) == 0) {
1516 		newnfs_copycred(&op->nfso_cred, cred);
1517 		dp = NULL;
1518 		error = nfsrpc_reopen(nmp, op->nfso_fh,
1519 		    op->nfso_fhlen, op->nfso_mode, op, &dp, cred, p);
1520 		if (error) {
1521 			mustdelete = 1;
1522 			if (dp != NULL) {
1523 				free(dp, M_NFSCLDELEG);
1524 				dp = NULL;
1525 			}
1526 		}
1527 		if (dp != NULL)
1528 			nfscl_deleg(nmp->nm_mountp, clp, op->nfso_fh,
1529 			    op->nfso_fhlen, cred, p, &dp);
1530 	}
1531 
1532 	/*
1533 	 * If a byte range lock or Share deny or couldn't re-open, free it.
1534 	 */
1535 	if (mustdelete)
1536 		nfscl_freeopen(op, 0);
1537 	return (mustdelete);
1538 }
1539 
1540 /*
1541  * Free up an open owner structure.
1542  */
1543 static void
1544 nfscl_freeopenowner(struct nfsclowner *owp, int local)
1545 {
1546 
1547 	LIST_REMOVE(owp, nfsow_list);
1548 	free(owp, M_NFSCLOWNER);
1549 	if (local)
1550 		nfsstatsv1.cllocalopenowners--;
1551 	else
1552 		nfsstatsv1.clopenowners--;
1553 }
1554 
1555 /*
1556  * Free up a byte range lock owner structure.
1557  */
1558 APPLESTATIC void
1559 nfscl_freelockowner(struct nfscllockowner *lp, int local)
1560 {
1561 	struct nfscllock *lop, *nlop;
1562 
1563 	LIST_REMOVE(lp, nfsl_list);
1564 	LIST_FOREACH_SAFE(lop, &lp->nfsl_lock, nfslo_list, nlop) {
1565 		nfscl_freelock(lop, local);
1566 	}
1567 	free(lp, M_NFSCLLOCKOWNER);
1568 	if (local)
1569 		nfsstatsv1.cllocallockowners--;
1570 	else
1571 		nfsstatsv1.cllockowners--;
1572 }
1573 
1574 /*
1575  * Free up a byte range lock structure.
1576  */
1577 APPLESTATIC void
1578 nfscl_freelock(struct nfscllock *lop, int local)
1579 {
1580 
1581 	LIST_REMOVE(lop, nfslo_list);
1582 	free(lop, M_NFSCLLOCK);
1583 	if (local)
1584 		nfsstatsv1.cllocallocks--;
1585 	else
1586 		nfsstatsv1.cllocks--;
1587 }
1588 
1589 /*
1590  * Clean out the state related to a delegation.
1591  */
1592 static void
1593 nfscl_cleandeleg(struct nfscldeleg *dp)
1594 {
1595 	struct nfsclowner *owp, *nowp;
1596 	struct nfsclopen *op;
1597 
1598 	LIST_FOREACH_SAFE(owp, &dp->nfsdl_owner, nfsow_list, nowp) {
1599 		op = LIST_FIRST(&owp->nfsow_open);
1600 		if (op != NULL) {
1601 			if (LIST_NEXT(op, nfso_list) != NULL)
1602 				panic("nfscleandel");
1603 			nfscl_freeopen(op, 1);
1604 		}
1605 		nfscl_freeopenowner(owp, 1);
1606 	}
1607 	nfscl_freealllocks(&dp->nfsdl_lock, 1);
1608 }
1609 
1610 /*
1611  * Free a delegation.
1612  */
1613 static void
1614 nfscl_freedeleg(struct nfscldeleghead *hdp, struct nfscldeleg *dp)
1615 {
1616 
1617 	TAILQ_REMOVE(hdp, dp, nfsdl_list);
1618 	LIST_REMOVE(dp, nfsdl_hash);
1619 	free(dp, M_NFSCLDELEG);
1620 	nfsstatsv1.cldelegates--;
1621 	nfscl_delegcnt--;
1622 }
1623 
1624 /*
1625  * Free up all state related to this client structure.
1626  */
1627 static void
1628 nfscl_cleanclient(struct nfsclclient *clp)
1629 {
1630 	struct nfsclowner *owp, *nowp;
1631 	struct nfsclopen *op, *nop;
1632 	struct nfscllayout *lyp, *nlyp;
1633 	struct nfscldevinfo *dip, *ndip;
1634 
1635 	TAILQ_FOREACH_SAFE(lyp, &clp->nfsc_layout, nfsly_list, nlyp)
1636 		nfscl_freelayout(lyp);
1637 
1638 	LIST_FOREACH_SAFE(dip, &clp->nfsc_devinfo, nfsdi_list, ndip)
1639 		nfscl_freedevinfo(dip);
1640 
1641 	/* Now, all the OpenOwners, etc. */
1642 	LIST_FOREACH_SAFE(owp, &clp->nfsc_owner, nfsow_list, nowp) {
1643 		LIST_FOREACH_SAFE(op, &owp->nfsow_open, nfso_list, nop) {
1644 			nfscl_freeopen(op, 0);
1645 		}
1646 		nfscl_freeopenowner(owp, 0);
1647 	}
1648 }
1649 
1650 /*
1651  * Called when an NFSERR_EXPIRED is received from the server.
1652  */
1653 static void
1654 nfscl_expireclient(struct nfsclclient *clp, struct nfsmount *nmp,
1655     struct ucred *cred, NFSPROC_T *p)
1656 {
1657 	struct nfsclowner *owp, *nowp, *towp;
1658 	struct nfsclopen *op, *nop, *top;
1659 	struct nfscldeleg *dp, *ndp;
1660 	int ret, printed = 0;
1661 
1662 	/*
1663 	 * First, merge locally issued Opens into the list for the server.
1664 	 */
1665 	dp = TAILQ_FIRST(&clp->nfsc_deleg);
1666 	while (dp != NULL) {
1667 	    ndp = TAILQ_NEXT(dp, nfsdl_list);
1668 	    owp = LIST_FIRST(&dp->nfsdl_owner);
1669 	    while (owp != NULL) {
1670 		nowp = LIST_NEXT(owp, nfsow_list);
1671 		op = LIST_FIRST(&owp->nfsow_open);
1672 		if (op != NULL) {
1673 		    if (LIST_NEXT(op, nfso_list) != NULL)
1674 			panic("nfsclexp");
1675 		    LIST_FOREACH(towp, &clp->nfsc_owner, nfsow_list) {
1676 			if (!NFSBCMP(towp->nfsow_owner, owp->nfsow_owner,
1677 			    NFSV4CL_LOCKNAMELEN))
1678 			    break;
1679 		    }
1680 		    if (towp != NULL) {
1681 			/* Merge opens in */
1682 			LIST_FOREACH(top, &towp->nfsow_open, nfso_list) {
1683 			    if (top->nfso_fhlen == op->nfso_fhlen &&
1684 				!NFSBCMP(top->nfso_fh, op->nfso_fh,
1685 				 op->nfso_fhlen)) {
1686 				top->nfso_mode |= op->nfso_mode;
1687 				top->nfso_opencnt += op->nfso_opencnt;
1688 				break;
1689 			    }
1690 			}
1691 			if (top == NULL) {
1692 			    /* Just add the open to the owner list */
1693 			    LIST_REMOVE(op, nfso_list);
1694 			    op->nfso_own = towp;
1695 			    LIST_INSERT_HEAD(&towp->nfsow_open, op, nfso_list);
1696 			    nfsstatsv1.cllocalopens--;
1697 			    nfsstatsv1.clopens++;
1698 			}
1699 		    } else {
1700 			/* Just add the openowner to the client list */
1701 			LIST_REMOVE(owp, nfsow_list);
1702 			owp->nfsow_clp = clp;
1703 			LIST_INSERT_HEAD(&clp->nfsc_owner, owp, nfsow_list);
1704 			nfsstatsv1.cllocalopenowners--;
1705 			nfsstatsv1.clopenowners++;
1706 			nfsstatsv1.cllocalopens--;
1707 			nfsstatsv1.clopens++;
1708 		    }
1709 		}
1710 		owp = nowp;
1711 	    }
1712 	    if (!printed && !LIST_EMPTY(&dp->nfsdl_lock)) {
1713 		printed = 1;
1714 		printf("nfsv4 expired locks lost\n");
1715 	    }
1716 	    nfscl_cleandeleg(dp);
1717 	    nfscl_freedeleg(&clp->nfsc_deleg, dp);
1718 	    dp = ndp;
1719 	}
1720 	if (!TAILQ_EMPTY(&clp->nfsc_deleg))
1721 	    panic("nfsclexp");
1722 
1723 	/*
1724 	 * Now, try and reopen against the server.
1725 	 */
1726 	LIST_FOREACH_SAFE(owp, &clp->nfsc_owner, nfsow_list, nowp) {
1727 		owp->nfsow_seqid = 0;
1728 		LIST_FOREACH_SAFE(op, &owp->nfsow_open, nfso_list, nop) {
1729 			ret = nfscl_expireopen(clp, op, nmp, cred, p);
1730 			if (ret && !printed) {
1731 				printed = 1;
1732 				printf("nfsv4 expired locks lost\n");
1733 			}
1734 		}
1735 		if (LIST_EMPTY(&owp->nfsow_open))
1736 			nfscl_freeopenowner(owp, 0);
1737 	}
1738 }
1739 
1740 /*
1741  * This function must be called after the process represented by "own" has
1742  * exited. Must be called with CLSTATE lock held.
1743  */
1744 static void
1745 nfscl_cleanup_common(struct nfsclclient *clp, u_int8_t *own)
1746 {
1747 	struct nfsclowner *owp, *nowp;
1748 	struct nfscllockowner *lp, *nlp;
1749 	struct nfscldeleg *dp;
1750 
1751 	/* First, get rid of local locks on delegations. */
1752 	TAILQ_FOREACH(dp, &clp->nfsc_deleg, nfsdl_list) {
1753 		LIST_FOREACH_SAFE(lp, &dp->nfsdl_lock, nfsl_list, nlp) {
1754 		    if (!NFSBCMP(lp->nfsl_owner, own, NFSV4CL_LOCKNAMELEN)) {
1755 			if ((lp->nfsl_rwlock.nfslock_lock & NFSV4LOCK_WANTED))
1756 			    panic("nfscllckw");
1757 			nfscl_freelockowner(lp, 1);
1758 		    }
1759 		}
1760 	}
1761 	owp = LIST_FIRST(&clp->nfsc_owner);
1762 	while (owp != NULL) {
1763 		nowp = LIST_NEXT(owp, nfsow_list);
1764 		if (!NFSBCMP(owp->nfsow_owner, own,
1765 		    NFSV4CL_LOCKNAMELEN)) {
1766 			/*
1767 			 * If there are children that haven't closed the
1768 			 * file descriptors yet, the opens will still be
1769 			 * here. For that case, let the renew thread clear
1770 			 * out the OpenOwner later.
1771 			 */
1772 			if (LIST_EMPTY(&owp->nfsow_open))
1773 				nfscl_freeopenowner(owp, 0);
1774 			else
1775 				owp->nfsow_defunct = 1;
1776 		}
1777 		owp = nowp;
1778 	}
1779 }
1780 
1781 /*
1782  * Find open/lock owners for processes that have exited.
1783  */
1784 static void
1785 nfscl_cleanupkext(struct nfsclclient *clp, struct nfscllockownerfhhead *lhp)
1786 {
1787 	struct nfsclowner *owp, *nowp;
1788 	struct nfsclopen *op;
1789 	struct nfscllockowner *lp, *nlp;
1790 	struct nfscldeleg *dp;
1791 
1792 	NFSPROCLISTLOCK();
1793 	NFSLOCKCLSTATE();
1794 	LIST_FOREACH_SAFE(owp, &clp->nfsc_owner, nfsow_list, nowp) {
1795 		LIST_FOREACH(op, &owp->nfsow_open, nfso_list) {
1796 			LIST_FOREACH_SAFE(lp, &op->nfso_lock, nfsl_list, nlp) {
1797 				if (LIST_EMPTY(&lp->nfsl_lock))
1798 					nfscl_emptylockowner(lp, lhp);
1799 			}
1800 		}
1801 		if (nfscl_procdoesntexist(owp->nfsow_owner))
1802 			nfscl_cleanup_common(clp, owp->nfsow_owner);
1803 	}
1804 
1805 	/*
1806 	 * For the single open_owner case, these lock owners need to be
1807 	 * checked to see if they still exist separately.
1808 	 * This is because nfscl_procdoesntexist() never returns true for
1809 	 * the single open_owner so that the above doesn't ever call
1810 	 * nfscl_cleanup_common().
1811 	 */
1812 	TAILQ_FOREACH(dp, &clp->nfsc_deleg, nfsdl_list) {
1813 		LIST_FOREACH_SAFE(lp, &dp->nfsdl_lock, nfsl_list, nlp) {
1814 			if (nfscl_procdoesntexist(lp->nfsl_owner))
1815 				nfscl_cleanup_common(clp, lp->nfsl_owner);
1816 		}
1817 	}
1818 	NFSUNLOCKCLSTATE();
1819 	NFSPROCLISTUNLOCK();
1820 }
1821 
1822 /*
1823  * Take the empty lock owner and move it to the local lhp list if the
1824  * associated process no longer exists.
1825  */
1826 static void
1827 nfscl_emptylockowner(struct nfscllockowner *lp,
1828     struct nfscllockownerfhhead *lhp)
1829 {
1830 	struct nfscllockownerfh *lfhp, *mylfhp;
1831 	struct nfscllockowner *nlp;
1832 	int fnd_it;
1833 
1834 	/* If not a Posix lock owner, just return. */
1835 	if ((lp->nfsl_lockflags & F_POSIX) == 0)
1836 		return;
1837 
1838 	fnd_it = 0;
1839 	mylfhp = NULL;
1840 	/*
1841 	 * First, search to see if this lock owner is already in the list.
1842 	 * If it is, then the associated process no longer exists.
1843 	 */
1844 	SLIST_FOREACH(lfhp, lhp, nfslfh_list) {
1845 		if (lfhp->nfslfh_len == lp->nfsl_open->nfso_fhlen &&
1846 		    !NFSBCMP(lfhp->nfslfh_fh, lp->nfsl_open->nfso_fh,
1847 		    lfhp->nfslfh_len))
1848 			mylfhp = lfhp;
1849 		LIST_FOREACH(nlp, &lfhp->nfslfh_lock, nfsl_list)
1850 			if (!NFSBCMP(nlp->nfsl_owner, lp->nfsl_owner,
1851 			    NFSV4CL_LOCKNAMELEN))
1852 				fnd_it = 1;
1853 	}
1854 	/* If not found, check if process still exists. */
1855 	if (fnd_it == 0 && nfscl_procdoesntexist(lp->nfsl_owner) == 0)
1856 		return;
1857 
1858 	/* Move the lock owner over to the local list. */
1859 	if (mylfhp == NULL) {
1860 		mylfhp = malloc(sizeof(struct nfscllockownerfh), M_TEMP,
1861 		    M_NOWAIT);
1862 		if (mylfhp == NULL)
1863 			return;
1864 		mylfhp->nfslfh_len = lp->nfsl_open->nfso_fhlen;
1865 		NFSBCOPY(lp->nfsl_open->nfso_fh, mylfhp->nfslfh_fh,
1866 		    mylfhp->nfslfh_len);
1867 		LIST_INIT(&mylfhp->nfslfh_lock);
1868 		SLIST_INSERT_HEAD(lhp, mylfhp, nfslfh_list);
1869 	}
1870 	LIST_REMOVE(lp, nfsl_list);
1871 	LIST_INSERT_HEAD(&mylfhp->nfslfh_lock, lp, nfsl_list);
1872 }
1873 
1874 static int	fake_global;	/* Used to force visibility of MNTK_UNMOUNTF */
1875 /*
1876  * Called from nfs umount to free up the clientid.
1877  */
1878 APPLESTATIC void
1879 nfscl_umount(struct nfsmount *nmp, NFSPROC_T *p)
1880 {
1881 	struct nfsclclient *clp;
1882 	struct ucred *cred;
1883 	int igotlock;
1884 
1885 	/*
1886 	 * For the case that matters, this is the thread that set
1887 	 * MNTK_UNMOUNTF, so it will see it set. The code that follows is
1888 	 * done to ensure that any thread executing nfscl_getcl() after
1889 	 * this time, will see MNTK_UNMOUNTF set. nfscl_getcl() uses the
1890 	 * mutex for NFSLOCKCLSTATE(), so it is "m" for the following
1891 	 * explanation, courtesy of Alan Cox.
1892 	 * What follows is a snippet from Alan Cox's email at:
1893 	 * https://docs.FreeBSD.org/cgi/mid.cgi?BANLkTikR3d65zPHo9==08ZfJ2vmqZucEvw
1894 	 *
1895 	 * 1. Set MNTK_UNMOUNTF
1896 	 * 2. Acquire a standard FreeBSD mutex "m".
1897 	 * 3. Update some data structures.
1898 	 * 4. Release mutex "m".
1899 	 *
1900 	 * Then, other threads that acquire "m" after step 4 has occurred will
1901 	 * see MNTK_UNMOUNTF as set.  But, other threads that beat thread X to
1902 	 * step 2 may or may not see MNTK_UNMOUNTF as set.
1903 	 */
1904 	NFSLOCKCLSTATE();
1905 	if ((nmp->nm_mountp->mnt_kern_flag & MNTK_UNMOUNTF) != 0) {
1906 		fake_global++;
1907 		NFSUNLOCKCLSTATE();
1908 		NFSLOCKCLSTATE();
1909 	}
1910 
1911 	clp = nmp->nm_clp;
1912 	if (clp != NULL) {
1913 		if ((clp->nfsc_flags & NFSCLFLAGS_INITED) == 0)
1914 			panic("nfscl umount");
1915 
1916 		/*
1917 		 * First, handshake with the nfscl renew thread, to terminate
1918 		 * it.
1919 		 */
1920 		clp->nfsc_flags |= NFSCLFLAGS_UMOUNT;
1921 		while (clp->nfsc_flags & NFSCLFLAGS_HASTHREAD)
1922 			(void)mtx_sleep(clp, NFSCLSTATEMUTEXPTR, PWAIT,
1923 			    "nfsclumnt", hz);
1924 
1925 		/*
1926 		 * Now, get the exclusive lock on the client state, so
1927 		 * that no uses of the state are still in progress.
1928 		 */
1929 		do {
1930 			igotlock = nfsv4_lock(&clp->nfsc_lock, 1, NULL,
1931 			    NFSCLSTATEMUTEXPTR, NULL);
1932 		} while (!igotlock);
1933 		NFSUNLOCKCLSTATE();
1934 
1935 		/*
1936 		 * Free up all the state. It will expire on the server, but
1937 		 * maybe we should do a SetClientId/SetClientIdConfirm so
1938 		 * the server throws it away?
1939 		 */
1940 		LIST_REMOVE(clp, nfsc_list);
1941 		nfscl_delegreturnall(clp, p);
1942 		cred = newnfs_getcred();
1943 		if (NFSHASNFSV4N(nmp)) {
1944 			(void)nfsrpc_destroysession(nmp, clp, cred, p);
1945 			(void)nfsrpc_destroyclient(nmp, clp, cred, p);
1946 		} else
1947 			(void)nfsrpc_setclient(nmp, clp, 0, cred, p);
1948 		nfscl_cleanclient(clp);
1949 		nmp->nm_clp = NULL;
1950 		NFSFREECRED(cred);
1951 		free(clp, M_NFSCLCLIENT);
1952 	} else
1953 		NFSUNLOCKCLSTATE();
1954 }
1955 
1956 /*
1957  * This function is called when a server replies with NFSERR_STALECLIENTID
1958  * NFSERR_STALESTATEID or NFSERR_BADSESSION. It traverses the clientid lists,
1959  * doing Opens and Locks with reclaim. If these fail, it deletes the
1960  * corresponding state.
1961  */
1962 static void
1963 nfscl_recover(struct nfsclclient *clp, struct ucred *cred, NFSPROC_T *p)
1964 {
1965 	struct nfsclowner *owp, *nowp;
1966 	struct nfsclopen *op, *nop;
1967 	struct nfscllockowner *lp, *nlp;
1968 	struct nfscllock *lop, *nlop;
1969 	struct nfscldeleg *dp, *ndp, *tdp;
1970 	struct nfsmount *nmp;
1971 	struct ucred *tcred;
1972 	struct nfsclopenhead extra_open;
1973 	struct nfscldeleghead extra_deleg;
1974 	struct nfsreq *rep;
1975 	u_int64_t len;
1976 	u_int32_t delegtype = NFSV4OPEN_DELEGATEWRITE, mode;
1977 	int i, igotlock = 0, error, trycnt, firstlock;
1978 	struct nfscllayout *lyp, *nlyp;
1979 
1980 	/*
1981 	 * First, lock the client structure, so everyone else will
1982 	 * block when trying to use state.
1983 	 */
1984 	NFSLOCKCLSTATE();
1985 	clp->nfsc_flags |= NFSCLFLAGS_RECVRINPROG;
1986 	do {
1987 		igotlock = nfsv4_lock(&clp->nfsc_lock, 1, NULL,
1988 		    NFSCLSTATEMUTEXPTR, NULL);
1989 	} while (!igotlock);
1990 	NFSUNLOCKCLSTATE();
1991 
1992 	nmp = clp->nfsc_nmp;
1993 	if (nmp == NULL)
1994 		panic("nfscl recover");
1995 
1996 	/*
1997 	 * For now, just get rid of all layouts. There may be a need
1998 	 * to do LayoutCommit Ops with reclaim == true later.
1999 	 */
2000 	TAILQ_FOREACH_SAFE(lyp, &clp->nfsc_layout, nfsly_list, nlyp)
2001 		nfscl_freelayout(lyp);
2002 	TAILQ_INIT(&clp->nfsc_layout);
2003 	for (i = 0; i < NFSCLLAYOUTHASHSIZE; i++)
2004 		LIST_INIT(&clp->nfsc_layouthash[i]);
2005 
2006 	trycnt = 5;
2007 	do {
2008 		error = nfsrpc_setclient(nmp, clp, 1, cred, p);
2009 	} while ((error == NFSERR_STALECLIENTID ||
2010 	     error == NFSERR_BADSESSION ||
2011 	     error == NFSERR_STALEDONTRECOVER) && --trycnt > 0);
2012 	if (error) {
2013 		NFSLOCKCLSTATE();
2014 		clp->nfsc_flags &= ~(NFSCLFLAGS_RECOVER |
2015 		    NFSCLFLAGS_RECVRINPROG);
2016 		wakeup(&clp->nfsc_flags);
2017 		nfsv4_unlock(&clp->nfsc_lock, 0);
2018 		NFSUNLOCKCLSTATE();
2019 		return;
2020 	}
2021 	clp->nfsc_flags |= NFSCLFLAGS_HASCLIENTID;
2022 	clp->nfsc_flags &= ~NFSCLFLAGS_RECOVER;
2023 
2024 	/*
2025 	 * Mark requests already queued on the server, so that they don't
2026 	 * initiate another recovery cycle. Any requests already in the
2027 	 * queue that handle state information will have the old stale
2028 	 * clientid/stateid and will get a NFSERR_STALESTATEID,
2029 	 * NFSERR_STALECLIENTID or NFSERR_BADSESSION reply from the server.
2030 	 * This will be translated to NFSERR_STALEDONTRECOVER when
2031 	 * R_DONTRECOVER is set.
2032 	 */
2033 	NFSLOCKREQ();
2034 	TAILQ_FOREACH(rep, &nfsd_reqq, r_chain) {
2035 		if (rep->r_nmp == nmp)
2036 			rep->r_flags |= R_DONTRECOVER;
2037 	}
2038 	NFSUNLOCKREQ();
2039 
2040 	/*
2041 	 * Now, mark all delegations "need reclaim".
2042 	 */
2043 	TAILQ_FOREACH(dp, &clp->nfsc_deleg, nfsdl_list)
2044 		dp->nfsdl_flags |= NFSCLDL_NEEDRECLAIM;
2045 
2046 	TAILQ_INIT(&extra_deleg);
2047 	LIST_INIT(&extra_open);
2048 	/*
2049 	 * Now traverse the state lists, doing Open and Lock Reclaims.
2050 	 */
2051 	tcred = newnfs_getcred();
2052 	owp = LIST_FIRST(&clp->nfsc_owner);
2053 	while (owp != NULL) {
2054 	    nowp = LIST_NEXT(owp, nfsow_list);
2055 	    owp->nfsow_seqid = 0;
2056 	    op = LIST_FIRST(&owp->nfsow_open);
2057 	    while (op != NULL) {
2058 		nop = LIST_NEXT(op, nfso_list);
2059 		if (error != NFSERR_NOGRACE && error != NFSERR_BADSESSION) {
2060 		    /* Search for a delegation to reclaim with the open */
2061 		    TAILQ_FOREACH(dp, &clp->nfsc_deleg, nfsdl_list) {
2062 			if (!(dp->nfsdl_flags & NFSCLDL_NEEDRECLAIM))
2063 			    continue;
2064 			if ((dp->nfsdl_flags & NFSCLDL_WRITE)) {
2065 			    mode = NFSV4OPEN_ACCESSWRITE;
2066 			    delegtype = NFSV4OPEN_DELEGATEWRITE;
2067 			} else {
2068 			    mode = NFSV4OPEN_ACCESSREAD;
2069 			    delegtype = NFSV4OPEN_DELEGATEREAD;
2070 			}
2071 			if ((op->nfso_mode & mode) == mode &&
2072 			    op->nfso_fhlen == dp->nfsdl_fhlen &&
2073 			    !NFSBCMP(op->nfso_fh, dp->nfsdl_fh, op->nfso_fhlen))
2074 			    break;
2075 		    }
2076 		    ndp = dp;
2077 		    if (dp == NULL)
2078 			delegtype = NFSV4OPEN_DELEGATENONE;
2079 		    newnfs_copycred(&op->nfso_cred, tcred);
2080 		    error = nfscl_tryopen(nmp, NULL, op->nfso_fh,
2081 			op->nfso_fhlen, op->nfso_fh, op->nfso_fhlen,
2082 			op->nfso_mode, op, NULL, 0, &ndp, 1, delegtype,
2083 			tcred, p);
2084 		    if (!error) {
2085 			/* Handle any replied delegation */
2086 			if (ndp != NULL && ((ndp->nfsdl_flags & NFSCLDL_WRITE)
2087 			    || NFSMNT_RDONLY(nmp->nm_mountp))) {
2088 			    if ((ndp->nfsdl_flags & NFSCLDL_WRITE))
2089 				mode = NFSV4OPEN_ACCESSWRITE;
2090 			    else
2091 				mode = NFSV4OPEN_ACCESSREAD;
2092 			    TAILQ_FOREACH(dp, &clp->nfsc_deleg, nfsdl_list) {
2093 				if (!(dp->nfsdl_flags & NFSCLDL_NEEDRECLAIM))
2094 				    continue;
2095 				if ((op->nfso_mode & mode) == mode &&
2096 				    op->nfso_fhlen == dp->nfsdl_fhlen &&
2097 				    !NFSBCMP(op->nfso_fh, dp->nfsdl_fh,
2098 				    op->nfso_fhlen)) {
2099 				    dp->nfsdl_stateid = ndp->nfsdl_stateid;
2100 				    dp->nfsdl_sizelimit = ndp->nfsdl_sizelimit;
2101 				    dp->nfsdl_ace = ndp->nfsdl_ace;
2102 				    dp->nfsdl_change = ndp->nfsdl_change;
2103 				    dp->nfsdl_flags &= ~NFSCLDL_NEEDRECLAIM;
2104 				    if ((ndp->nfsdl_flags & NFSCLDL_RECALL))
2105 					dp->nfsdl_flags |= NFSCLDL_RECALL;
2106 				    free(ndp, M_NFSCLDELEG);
2107 				    ndp = NULL;
2108 				    break;
2109 				}
2110 			    }
2111 			}
2112 			if (ndp != NULL)
2113 			    TAILQ_INSERT_HEAD(&extra_deleg, ndp, nfsdl_list);
2114 
2115 			/* and reclaim all byte range locks */
2116 			lp = LIST_FIRST(&op->nfso_lock);
2117 			while (lp != NULL) {
2118 			    nlp = LIST_NEXT(lp, nfsl_list);
2119 			    lp->nfsl_seqid = 0;
2120 			    firstlock = 1;
2121 			    lop = LIST_FIRST(&lp->nfsl_lock);
2122 			    while (lop != NULL) {
2123 				nlop = LIST_NEXT(lop, nfslo_list);
2124 				if (lop->nfslo_end == NFS64BITSSET)
2125 				    len = NFS64BITSSET;
2126 				else
2127 				    len = lop->nfslo_end - lop->nfslo_first;
2128 				error = nfscl_trylock(nmp, NULL,
2129 				    op->nfso_fh, op->nfso_fhlen, lp,
2130 				    firstlock, 1, lop->nfslo_first, len,
2131 				    lop->nfslo_type, tcred, p);
2132 				if (error != 0)
2133 				    nfscl_freelock(lop, 0);
2134 				else
2135 				    firstlock = 0;
2136 				lop = nlop;
2137 			    }
2138 			    /* If no locks, but a lockowner, just delete it. */
2139 			    if (LIST_EMPTY(&lp->nfsl_lock))
2140 				nfscl_freelockowner(lp, 0);
2141 			    lp = nlp;
2142 			}
2143 		    }
2144 		}
2145 		if (error != 0 && error != NFSERR_BADSESSION)
2146 		    nfscl_freeopen(op, 0);
2147 		op = nop;
2148 	    }
2149 	    owp = nowp;
2150 	}
2151 
2152 	/*
2153 	 * Now, try and get any delegations not yet reclaimed by cobbling
2154 	 * to-gether an appropriate open.
2155 	 */
2156 	nowp = NULL;
2157 	dp = TAILQ_FIRST(&clp->nfsc_deleg);
2158 	while (dp != NULL) {
2159 	    ndp = TAILQ_NEXT(dp, nfsdl_list);
2160 	    if ((dp->nfsdl_flags & NFSCLDL_NEEDRECLAIM)) {
2161 		if (nowp == NULL) {
2162 		    nowp = malloc(
2163 			sizeof (struct nfsclowner), M_NFSCLOWNER, M_WAITOK);
2164 		    /*
2165 		     * Name must be as long an largest possible
2166 		     * NFSV4CL_LOCKNAMELEN. 12 for now.
2167 		     */
2168 		    NFSBCOPY("RECLAIMDELEG", nowp->nfsow_owner,
2169 			NFSV4CL_LOCKNAMELEN);
2170 		    LIST_INIT(&nowp->nfsow_open);
2171 		    nowp->nfsow_clp = clp;
2172 		    nowp->nfsow_seqid = 0;
2173 		    nowp->nfsow_defunct = 0;
2174 		    nfscl_lockinit(&nowp->nfsow_rwlock);
2175 		}
2176 		nop = NULL;
2177 		if (error != NFSERR_NOGRACE && error != NFSERR_BADSESSION) {
2178 		    nop = malloc(sizeof (struct nfsclopen) +
2179 			dp->nfsdl_fhlen - 1, M_NFSCLOPEN, M_WAITOK);
2180 		    nop->nfso_own = nowp;
2181 		    if ((dp->nfsdl_flags & NFSCLDL_WRITE)) {
2182 			nop->nfso_mode = NFSV4OPEN_ACCESSWRITE;
2183 			delegtype = NFSV4OPEN_DELEGATEWRITE;
2184 		    } else {
2185 			nop->nfso_mode = NFSV4OPEN_ACCESSREAD;
2186 			delegtype = NFSV4OPEN_DELEGATEREAD;
2187 		    }
2188 		    nop->nfso_opencnt = 0;
2189 		    nop->nfso_posixlock = 1;
2190 		    nop->nfso_fhlen = dp->nfsdl_fhlen;
2191 		    NFSBCOPY(dp->nfsdl_fh, nop->nfso_fh, dp->nfsdl_fhlen);
2192 		    LIST_INIT(&nop->nfso_lock);
2193 		    nop->nfso_stateid.seqid = 0;
2194 		    nop->nfso_stateid.other[0] = 0;
2195 		    nop->nfso_stateid.other[1] = 0;
2196 		    nop->nfso_stateid.other[2] = 0;
2197 		    newnfs_copycred(&dp->nfsdl_cred, tcred);
2198 		    newnfs_copyincred(tcred, &nop->nfso_cred);
2199 		    tdp = NULL;
2200 		    error = nfscl_tryopen(nmp, NULL, nop->nfso_fh,
2201 			nop->nfso_fhlen, nop->nfso_fh, nop->nfso_fhlen,
2202 			nop->nfso_mode, nop, NULL, 0, &tdp, 1,
2203 			delegtype, tcred, p);
2204 		    if (tdp != NULL) {
2205 			if ((tdp->nfsdl_flags & NFSCLDL_WRITE))
2206 			    mode = NFSV4OPEN_ACCESSWRITE;
2207 			else
2208 			    mode = NFSV4OPEN_ACCESSREAD;
2209 			if ((nop->nfso_mode & mode) == mode &&
2210 			    nop->nfso_fhlen == tdp->nfsdl_fhlen &&
2211 			    !NFSBCMP(nop->nfso_fh, tdp->nfsdl_fh,
2212 			    nop->nfso_fhlen)) {
2213 			    dp->nfsdl_stateid = tdp->nfsdl_stateid;
2214 			    dp->nfsdl_sizelimit = tdp->nfsdl_sizelimit;
2215 			    dp->nfsdl_ace = tdp->nfsdl_ace;
2216 			    dp->nfsdl_change = tdp->nfsdl_change;
2217 			    dp->nfsdl_flags &= ~NFSCLDL_NEEDRECLAIM;
2218 			    if ((tdp->nfsdl_flags & NFSCLDL_RECALL))
2219 				dp->nfsdl_flags |= NFSCLDL_RECALL;
2220 			    free(tdp, M_NFSCLDELEG);
2221 			} else {
2222 			    TAILQ_INSERT_HEAD(&extra_deleg, tdp, nfsdl_list);
2223 			}
2224 		    }
2225 		}
2226 		if (error) {
2227 		    if (nop != NULL)
2228 			free(nop, M_NFSCLOPEN);
2229 		    /*
2230 		     * Couldn't reclaim it, so throw the state
2231 		     * away. Ouch!!
2232 		     */
2233 		    nfscl_cleandeleg(dp);
2234 		    nfscl_freedeleg(&clp->nfsc_deleg, dp);
2235 		} else {
2236 		    LIST_INSERT_HEAD(&extra_open, nop, nfso_list);
2237 		}
2238 	    }
2239 	    dp = ndp;
2240 	}
2241 
2242 	/*
2243 	 * Now, get rid of extra Opens and Delegations.
2244 	 */
2245 	LIST_FOREACH_SAFE(op, &extra_open, nfso_list, nop) {
2246 		do {
2247 			newnfs_copycred(&op->nfso_cred, tcred);
2248 			error = nfscl_tryclose(op, tcred, nmp, p);
2249 			if (error == NFSERR_GRACE)
2250 				(void) nfs_catnap(PZERO, error, "nfsexcls");
2251 		} while (error == NFSERR_GRACE);
2252 		LIST_REMOVE(op, nfso_list);
2253 		free(op, M_NFSCLOPEN);
2254 	}
2255 	if (nowp != NULL)
2256 		free(nowp, M_NFSCLOWNER);
2257 
2258 	TAILQ_FOREACH_SAFE(dp, &extra_deleg, nfsdl_list, ndp) {
2259 		do {
2260 			newnfs_copycred(&dp->nfsdl_cred, tcred);
2261 			error = nfscl_trydelegreturn(dp, tcred, nmp, p);
2262 			if (error == NFSERR_GRACE)
2263 				(void) nfs_catnap(PZERO, error, "nfsexdlg");
2264 		} while (error == NFSERR_GRACE);
2265 		TAILQ_REMOVE(&extra_deleg, dp, nfsdl_list);
2266 		free(dp, M_NFSCLDELEG);
2267 	}
2268 
2269 	/* For NFSv4.1 or later, do a RECLAIM_COMPLETE. */
2270 	if (NFSHASNFSV4N(nmp))
2271 		(void)nfsrpc_reclaimcomplete(nmp, cred, p);
2272 
2273 	NFSLOCKCLSTATE();
2274 	clp->nfsc_flags &= ~NFSCLFLAGS_RECVRINPROG;
2275 	wakeup(&clp->nfsc_flags);
2276 	nfsv4_unlock(&clp->nfsc_lock, 0);
2277 	NFSUNLOCKCLSTATE();
2278 	NFSFREECRED(tcred);
2279 }
2280 
2281 /*
2282  * This function is called when a server replies with NFSERR_EXPIRED.
2283  * It deletes all state for the client and does a fresh SetClientId/confirm.
2284  * XXX Someday it should post a signal to the process(es) that hold the
2285  * state, so they know that lock state has been lost.
2286  */
2287 APPLESTATIC int
2288 nfscl_hasexpired(struct nfsclclient *clp, u_int32_t clidrev, NFSPROC_T *p)
2289 {
2290 	struct nfsmount *nmp;
2291 	struct ucred *cred;
2292 	int igotlock = 0, error, trycnt;
2293 
2294 	/*
2295 	 * If the clientid has gone away or a new SetClientid has already
2296 	 * been done, just return ok.
2297 	 */
2298 	if (clp == NULL || clidrev != clp->nfsc_clientidrev)
2299 		return (0);
2300 
2301 	/*
2302 	 * First, lock the client structure, so everyone else will
2303 	 * block when trying to use state. Also, use NFSCLFLAGS_EXPIREIT so
2304 	 * that only one thread does the work.
2305 	 */
2306 	NFSLOCKCLSTATE();
2307 	clp->nfsc_flags |= NFSCLFLAGS_EXPIREIT;
2308 	do {
2309 		igotlock = nfsv4_lock(&clp->nfsc_lock, 1, NULL,
2310 		    NFSCLSTATEMUTEXPTR, NULL);
2311 	} while (!igotlock && (clp->nfsc_flags & NFSCLFLAGS_EXPIREIT));
2312 	if ((clp->nfsc_flags & NFSCLFLAGS_EXPIREIT) == 0) {
2313 		if (igotlock)
2314 			nfsv4_unlock(&clp->nfsc_lock, 0);
2315 		NFSUNLOCKCLSTATE();
2316 		return (0);
2317 	}
2318 	clp->nfsc_flags |= NFSCLFLAGS_RECVRINPROG;
2319 	NFSUNLOCKCLSTATE();
2320 
2321 	nmp = clp->nfsc_nmp;
2322 	if (nmp == NULL)
2323 		panic("nfscl expired");
2324 	cred = newnfs_getcred();
2325 	trycnt = 5;
2326 	do {
2327 		error = nfsrpc_setclient(nmp, clp, 0, cred, p);
2328 	} while ((error == NFSERR_STALECLIENTID ||
2329 	     error == NFSERR_BADSESSION ||
2330 	     error == NFSERR_STALEDONTRECOVER) && --trycnt > 0);
2331 	if (error) {
2332 		NFSLOCKCLSTATE();
2333 		clp->nfsc_flags &= ~NFSCLFLAGS_RECOVER;
2334 	} else {
2335 		/*
2336 		 * Expire the state for the client.
2337 		 */
2338 		nfscl_expireclient(clp, nmp, cred, p);
2339 		NFSLOCKCLSTATE();
2340 		clp->nfsc_flags |= NFSCLFLAGS_HASCLIENTID;
2341 		clp->nfsc_flags &= ~NFSCLFLAGS_RECOVER;
2342 	}
2343 	clp->nfsc_flags &= ~(NFSCLFLAGS_EXPIREIT | NFSCLFLAGS_RECVRINPROG);
2344 	wakeup(&clp->nfsc_flags);
2345 	nfsv4_unlock(&clp->nfsc_lock, 0);
2346 	NFSUNLOCKCLSTATE();
2347 	NFSFREECRED(cred);
2348 	return (error);
2349 }
2350 
2351 /*
2352  * This function inserts a lock in the list after insert_lop.
2353  */
2354 static void
2355 nfscl_insertlock(struct nfscllockowner *lp, struct nfscllock *new_lop,
2356     struct nfscllock *insert_lop, int local)
2357 {
2358 
2359 	if ((struct nfscllockowner *)insert_lop == lp)
2360 		LIST_INSERT_HEAD(&lp->nfsl_lock, new_lop, nfslo_list);
2361 	else
2362 		LIST_INSERT_AFTER(insert_lop, new_lop, nfslo_list);
2363 	if (local)
2364 		nfsstatsv1.cllocallocks++;
2365 	else
2366 		nfsstatsv1.cllocks++;
2367 }
2368 
2369 /*
2370  * This function updates the locking for a lock owner and given file. It
2371  * maintains a list of lock ranges ordered on increasing file offset that
2372  * are NFSCLLOCK_READ or NFSCLLOCK_WRITE and non-overlapping (aka POSIX style).
2373  * It always adds new_lop to the list and sometimes uses the one pointed
2374  * at by other_lopp.
2375  * Returns 1 if the locks were modified, 0 otherwise.
2376  */
2377 static int
2378 nfscl_updatelock(struct nfscllockowner *lp, struct nfscllock **new_lopp,
2379     struct nfscllock **other_lopp, int local)
2380 {
2381 	struct nfscllock *new_lop = *new_lopp;
2382 	struct nfscllock *lop, *tlop, *ilop;
2383 	struct nfscllock *other_lop;
2384 	int unlock = 0, modified = 0;
2385 	u_int64_t tmp;
2386 
2387 	/*
2388 	 * Work down the list until the lock is merged.
2389 	 */
2390 	if (new_lop->nfslo_type == F_UNLCK)
2391 		unlock = 1;
2392 	ilop = (struct nfscllock *)lp;
2393 	lop = LIST_FIRST(&lp->nfsl_lock);
2394 	while (lop != NULL) {
2395 	    /*
2396 	     * Only check locks for this file that aren't before the start of
2397 	     * new lock's range.
2398 	     */
2399 	    if (lop->nfslo_end >= new_lop->nfslo_first) {
2400 		if (new_lop->nfslo_end < lop->nfslo_first) {
2401 		    /*
2402 		     * If the new lock ends before the start of the
2403 		     * current lock's range, no merge, just insert
2404 		     * the new lock.
2405 		     */
2406 		    break;
2407 		}
2408 		if (new_lop->nfslo_type == lop->nfslo_type ||
2409 		    (new_lop->nfslo_first <= lop->nfslo_first &&
2410 		     new_lop->nfslo_end >= lop->nfslo_end)) {
2411 		    /*
2412 		     * This lock can be absorbed by the new lock/unlock.
2413 		     * This happens when it covers the entire range
2414 		     * of the old lock or is contiguous
2415 		     * with the old lock and is of the same type or an
2416 		     * unlock.
2417 		     */
2418 		    if (new_lop->nfslo_type != lop->nfslo_type ||
2419 			new_lop->nfslo_first != lop->nfslo_first ||
2420 			new_lop->nfslo_end != lop->nfslo_end)
2421 			modified = 1;
2422 		    if (lop->nfslo_first < new_lop->nfslo_first)
2423 			new_lop->nfslo_first = lop->nfslo_first;
2424 		    if (lop->nfslo_end > new_lop->nfslo_end)
2425 			new_lop->nfslo_end = lop->nfslo_end;
2426 		    tlop = lop;
2427 		    lop = LIST_NEXT(lop, nfslo_list);
2428 		    nfscl_freelock(tlop, local);
2429 		    continue;
2430 		}
2431 
2432 		/*
2433 		 * All these cases are for contiguous locks that are not the
2434 		 * same type, so they can't be merged.
2435 		 */
2436 		if (new_lop->nfslo_first <= lop->nfslo_first) {
2437 		    /*
2438 		     * This case is where the new lock overlaps with the
2439 		     * first part of the old lock. Move the start of the
2440 		     * old lock to just past the end of the new lock. The
2441 		     * new lock will be inserted in front of the old, since
2442 		     * ilop hasn't been updated. (We are done now.)
2443 		     */
2444 		    if (lop->nfslo_first != new_lop->nfslo_end) {
2445 			lop->nfslo_first = new_lop->nfslo_end;
2446 			modified = 1;
2447 		    }
2448 		    break;
2449 		}
2450 		if (new_lop->nfslo_end >= lop->nfslo_end) {
2451 		    /*
2452 		     * This case is where the new lock overlaps with the
2453 		     * end of the old lock's range. Move the old lock's
2454 		     * end to just before the new lock's first and insert
2455 		     * the new lock after the old lock.
2456 		     * Might not be done yet, since the new lock could
2457 		     * overlap further locks with higher ranges.
2458 		     */
2459 		    if (lop->nfslo_end != new_lop->nfslo_first) {
2460 			lop->nfslo_end = new_lop->nfslo_first;
2461 			modified = 1;
2462 		    }
2463 		    ilop = lop;
2464 		    lop = LIST_NEXT(lop, nfslo_list);
2465 		    continue;
2466 		}
2467 		/*
2468 		 * The final case is where the new lock's range is in the
2469 		 * middle of the current lock's and splits the current lock
2470 		 * up. Use *other_lopp to handle the second part of the
2471 		 * split old lock range. (We are done now.)
2472 		 * For unlock, we use new_lop as other_lop and tmp, since
2473 		 * other_lop and new_lop are the same for this case.
2474 		 * We noted the unlock case above, so we don't need
2475 		 * new_lop->nfslo_type any longer.
2476 		 */
2477 		tmp = new_lop->nfslo_first;
2478 		if (unlock) {
2479 		    other_lop = new_lop;
2480 		    *new_lopp = NULL;
2481 		} else {
2482 		    other_lop = *other_lopp;
2483 		    *other_lopp = NULL;
2484 		}
2485 		other_lop->nfslo_first = new_lop->nfslo_end;
2486 		other_lop->nfslo_end = lop->nfslo_end;
2487 		other_lop->nfslo_type = lop->nfslo_type;
2488 		lop->nfslo_end = tmp;
2489 		nfscl_insertlock(lp, other_lop, lop, local);
2490 		ilop = lop;
2491 		modified = 1;
2492 		break;
2493 	    }
2494 	    ilop = lop;
2495 	    lop = LIST_NEXT(lop, nfslo_list);
2496 	    if (lop == NULL)
2497 		break;
2498 	}
2499 
2500 	/*
2501 	 * Insert the new lock in the list at the appropriate place.
2502 	 */
2503 	if (!unlock) {
2504 		nfscl_insertlock(lp, new_lop, ilop, local);
2505 		*new_lopp = NULL;
2506 		modified = 1;
2507 	}
2508 	return (modified);
2509 }
2510 
2511 /*
2512  * This function must be run as a kernel thread.
2513  * It does Renew Ops and recovery, when required.
2514  */
2515 APPLESTATIC void
2516 nfscl_renewthread(struct nfsclclient *clp, NFSPROC_T *p)
2517 {
2518 	struct nfsclowner *owp, *nowp;
2519 	struct nfsclopen *op;
2520 	struct nfscllockowner *lp, *nlp;
2521 	struct nfscldeleghead dh;
2522 	struct nfscldeleg *dp, *ndp;
2523 	struct ucred *cred;
2524 	u_int32_t clidrev;
2525 	int error, cbpathdown, islept, igotlock, ret, clearok;
2526 	uint32_t recover_done_time = 0;
2527 	time_t mytime;
2528 	static time_t prevsec = 0;
2529 	struct nfscllockownerfh *lfhp, *nlfhp;
2530 	struct nfscllockownerfhhead lfh;
2531 	struct nfscllayout *lyp, *nlyp;
2532 	struct nfscldevinfo *dip, *ndip;
2533 	struct nfscllayouthead rlh;
2534 	struct nfsclrecalllayout *recallp;
2535 	struct nfsclds *dsp;
2536 
2537 	cred = newnfs_getcred();
2538 	NFSLOCKCLSTATE();
2539 	clp->nfsc_flags |= NFSCLFLAGS_HASTHREAD;
2540 	NFSUNLOCKCLSTATE();
2541 	for(;;) {
2542 		newnfs_setroot(cred);
2543 		cbpathdown = 0;
2544 		if (clp->nfsc_flags & NFSCLFLAGS_RECOVER) {
2545 			/*
2546 			 * Only allow one recover within 1/2 of the lease
2547 			 * duration (nfsc_renew).
2548 			 */
2549 			if (recover_done_time < NFSD_MONOSEC) {
2550 				recover_done_time = NFSD_MONOSEC +
2551 				    clp->nfsc_renew;
2552 				NFSCL_DEBUG(1, "Doing recovery..\n");
2553 				nfscl_recover(clp, cred, p);
2554 			} else {
2555 				NFSCL_DEBUG(1, "Clear Recovery dt=%u ms=%jd\n",
2556 				    recover_done_time, (intmax_t)NFSD_MONOSEC);
2557 				NFSLOCKCLSTATE();
2558 				clp->nfsc_flags &= ~NFSCLFLAGS_RECOVER;
2559 				NFSUNLOCKCLSTATE();
2560 			}
2561 		}
2562 		if (clp->nfsc_expire <= NFSD_MONOSEC &&
2563 		    (clp->nfsc_flags & NFSCLFLAGS_HASCLIENTID)) {
2564 			clp->nfsc_expire = NFSD_MONOSEC + clp->nfsc_renew;
2565 			clidrev = clp->nfsc_clientidrev;
2566 			error = nfsrpc_renew(clp, NULL, cred, p);
2567 			if (error == NFSERR_CBPATHDOWN)
2568 			    cbpathdown = 1;
2569 			else if (error == NFSERR_STALECLIENTID ||
2570 			    error == NFSERR_BADSESSION) {
2571 			    NFSLOCKCLSTATE();
2572 			    clp->nfsc_flags |= NFSCLFLAGS_RECOVER;
2573 			    NFSUNLOCKCLSTATE();
2574 			} else if (error == NFSERR_EXPIRED)
2575 			    (void) nfscl_hasexpired(clp, clidrev, p);
2576 		}
2577 
2578 checkdsrenew:
2579 		if (NFSHASNFSV4N(clp->nfsc_nmp)) {
2580 			/* Do renews for any DS sessions. */
2581 			NFSLOCKMNT(clp->nfsc_nmp);
2582 			/* Skip first entry, since the MDS is handled above. */
2583 			dsp = TAILQ_FIRST(&clp->nfsc_nmp->nm_sess);
2584 			if (dsp != NULL)
2585 				dsp = TAILQ_NEXT(dsp, nfsclds_list);
2586 			while (dsp != NULL) {
2587 				if (dsp->nfsclds_expire <= NFSD_MONOSEC &&
2588 				    dsp->nfsclds_sess.nfsess_defunct == 0) {
2589 					dsp->nfsclds_expire = NFSD_MONOSEC +
2590 					    clp->nfsc_renew;
2591 					NFSUNLOCKMNT(clp->nfsc_nmp);
2592 					(void)nfsrpc_renew(clp, dsp, cred, p);
2593 					goto checkdsrenew;
2594 				}
2595 				dsp = TAILQ_NEXT(dsp, nfsclds_list);
2596 			}
2597 			NFSUNLOCKMNT(clp->nfsc_nmp);
2598 		}
2599 
2600 		TAILQ_INIT(&dh);
2601 		NFSLOCKCLSTATE();
2602 		if (cbpathdown)
2603 			/* It's a Total Recall! */
2604 			nfscl_totalrecall(clp);
2605 
2606 		/*
2607 		 * Now, handle defunct owners.
2608 		 */
2609 		LIST_FOREACH_SAFE(owp, &clp->nfsc_owner, nfsow_list, nowp) {
2610 			if (LIST_EMPTY(&owp->nfsow_open)) {
2611 				if (owp->nfsow_defunct != 0)
2612 					nfscl_freeopenowner(owp, 0);
2613 			}
2614 		}
2615 
2616 		/*
2617 		 * Do the recall on any delegations. To avoid trouble, always
2618 		 * come back up here after having slept.
2619 		 */
2620 		igotlock = 0;
2621 tryagain:
2622 		dp = TAILQ_FIRST(&clp->nfsc_deleg);
2623 		while (dp != NULL) {
2624 			ndp = TAILQ_NEXT(dp, nfsdl_list);
2625 			if ((dp->nfsdl_flags & NFSCLDL_RECALL)) {
2626 				/*
2627 				 * Wait for outstanding I/O ops to be done.
2628 				 */
2629 				if (dp->nfsdl_rwlock.nfslock_usecnt > 0) {
2630 				    if (igotlock) {
2631 					nfsv4_unlock(&clp->nfsc_lock, 0);
2632 					igotlock = 0;
2633 				    }
2634 				    dp->nfsdl_rwlock.nfslock_lock |=
2635 					NFSV4LOCK_WANTED;
2636 				    (void) nfsmsleep(&dp->nfsdl_rwlock,
2637 					NFSCLSTATEMUTEXPTR, PZERO, "nfscld",
2638 					NULL);
2639 				    goto tryagain;
2640 				}
2641 				while (!igotlock) {
2642 				    igotlock = nfsv4_lock(&clp->nfsc_lock, 1,
2643 					&islept, NFSCLSTATEMUTEXPTR, NULL);
2644 				    if (islept)
2645 					goto tryagain;
2646 				}
2647 				NFSUNLOCKCLSTATE();
2648 				newnfs_copycred(&dp->nfsdl_cred, cred);
2649 				ret = nfscl_recalldeleg(clp, clp->nfsc_nmp, dp,
2650 				    NULL, cred, p, 1);
2651 				if (!ret) {
2652 				    nfscl_cleandeleg(dp);
2653 				    TAILQ_REMOVE(&clp->nfsc_deleg, dp,
2654 					nfsdl_list);
2655 				    LIST_REMOVE(dp, nfsdl_hash);
2656 				    TAILQ_INSERT_HEAD(&dh, dp, nfsdl_list);
2657 				    nfscl_delegcnt--;
2658 				    nfsstatsv1.cldelegates--;
2659 				}
2660 				NFSLOCKCLSTATE();
2661 			}
2662 			dp = ndp;
2663 		}
2664 
2665 		/*
2666 		 * Clear out old delegations, if we are above the high water
2667 		 * mark. Only clear out ones with no state related to them.
2668 		 * The tailq list is in LRU order.
2669 		 */
2670 		dp = TAILQ_LAST(&clp->nfsc_deleg, nfscldeleghead);
2671 		while (nfscl_delegcnt > nfscl_deleghighwater && dp != NULL) {
2672 		    ndp = TAILQ_PREV(dp, nfscldeleghead, nfsdl_list);
2673 		    if (dp->nfsdl_rwlock.nfslock_usecnt == 0 &&
2674 			dp->nfsdl_rwlock.nfslock_lock == 0 &&
2675 			dp->nfsdl_timestamp < NFSD_MONOSEC &&
2676 			(dp->nfsdl_flags & (NFSCLDL_RECALL | NFSCLDL_ZAPPED |
2677 			  NFSCLDL_NEEDRECLAIM | NFSCLDL_DELEGRET)) == 0) {
2678 			clearok = 1;
2679 			LIST_FOREACH(owp, &dp->nfsdl_owner, nfsow_list) {
2680 			    op = LIST_FIRST(&owp->nfsow_open);
2681 			    if (op != NULL) {
2682 				clearok = 0;
2683 				break;
2684 			    }
2685 			}
2686 			if (clearok) {
2687 			    LIST_FOREACH(lp, &dp->nfsdl_lock, nfsl_list) {
2688 				if (!LIST_EMPTY(&lp->nfsl_lock)) {
2689 				    clearok = 0;
2690 				    break;
2691 				}
2692 			    }
2693 			}
2694 			if (clearok) {
2695 			    TAILQ_REMOVE(&clp->nfsc_deleg, dp, nfsdl_list);
2696 			    LIST_REMOVE(dp, nfsdl_hash);
2697 			    TAILQ_INSERT_HEAD(&dh, dp, nfsdl_list);
2698 			    nfscl_delegcnt--;
2699 			    nfsstatsv1.cldelegates--;
2700 			}
2701 		    }
2702 		    dp = ndp;
2703 		}
2704 		if (igotlock)
2705 			nfsv4_unlock(&clp->nfsc_lock, 0);
2706 
2707 		/*
2708 		 * Do the recall on any layouts. To avoid trouble, always
2709 		 * come back up here after having slept.
2710 		 */
2711 		TAILQ_INIT(&rlh);
2712 tryagain2:
2713 		TAILQ_FOREACH_SAFE(lyp, &clp->nfsc_layout, nfsly_list, nlyp) {
2714 			if ((lyp->nfsly_flags & NFSLY_RECALL) != 0) {
2715 				/*
2716 				 * Wait for outstanding I/O ops to be done.
2717 				 */
2718 				if (lyp->nfsly_lock.nfslock_usecnt > 0 ||
2719 				    (lyp->nfsly_lock.nfslock_lock &
2720 				     NFSV4LOCK_LOCK) != 0) {
2721 					lyp->nfsly_lock.nfslock_lock |=
2722 					    NFSV4LOCK_WANTED;
2723 					nfsmsleep(&lyp->nfsly_lock.nfslock_lock,
2724 					    NFSCLSTATEMUTEXPTR, PZERO, "nfslyp",
2725 					    NULL);
2726 					goto tryagain2;
2727 				}
2728 				/* Move the layout to the recall list. */
2729 				TAILQ_REMOVE(&clp->nfsc_layout, lyp,
2730 				    nfsly_list);
2731 				LIST_REMOVE(lyp, nfsly_hash);
2732 				TAILQ_INSERT_HEAD(&rlh, lyp, nfsly_list);
2733 
2734 				/* Handle any layout commits. */
2735 				if (!NFSHASNOLAYOUTCOMMIT(clp->nfsc_nmp) &&
2736 				    (lyp->nfsly_flags & NFSLY_WRITTEN) != 0) {
2737 					lyp->nfsly_flags &= ~NFSLY_WRITTEN;
2738 					NFSUNLOCKCLSTATE();
2739 					NFSCL_DEBUG(3, "do layoutcommit\n");
2740 					nfscl_dolayoutcommit(clp->nfsc_nmp, lyp,
2741 					    cred, p);
2742 					NFSLOCKCLSTATE();
2743 					goto tryagain2;
2744 				}
2745 			}
2746 		}
2747 
2748 		/* Now, look for stale layouts. */
2749 		lyp = TAILQ_LAST(&clp->nfsc_layout, nfscllayouthead);
2750 		while (lyp != NULL) {
2751 			nlyp = TAILQ_PREV(lyp, nfscllayouthead, nfsly_list);
2752 			if (lyp->nfsly_timestamp < NFSD_MONOSEC &&
2753 			    (lyp->nfsly_flags & NFSLY_RECALL) == 0 &&
2754 			    lyp->nfsly_lock.nfslock_usecnt == 0 &&
2755 			    lyp->nfsly_lock.nfslock_lock == 0) {
2756 				NFSCL_DEBUG(4, "ret stale lay=%d\n",
2757 				    nfscl_layoutcnt);
2758 				recallp = malloc(sizeof(*recallp),
2759 				    M_NFSLAYRECALL, M_NOWAIT);
2760 				if (recallp == NULL)
2761 					break;
2762 				(void)nfscl_layoutrecall(NFSLAYOUTRETURN_FILE,
2763 				    lyp, NFSLAYOUTIOMODE_ANY, 0, UINT64_MAX,
2764 				    lyp->nfsly_stateid.seqid, 0, 0, NULL,
2765 				    recallp);
2766 			}
2767 			lyp = nlyp;
2768 		}
2769 
2770 		/*
2771 		 * Free up any unreferenced device info structures.
2772 		 */
2773 		LIST_FOREACH_SAFE(dip, &clp->nfsc_devinfo, nfsdi_list, ndip) {
2774 			if (dip->nfsdi_layoutrefs == 0 &&
2775 			    dip->nfsdi_refcnt == 0) {
2776 				NFSCL_DEBUG(4, "freeing devinfo\n");
2777 				LIST_REMOVE(dip, nfsdi_list);
2778 				nfscl_freedevinfo(dip);
2779 			}
2780 		}
2781 		NFSUNLOCKCLSTATE();
2782 
2783 		/* Do layout return(s), as required. */
2784 		TAILQ_FOREACH_SAFE(lyp, &rlh, nfsly_list, nlyp) {
2785 			TAILQ_REMOVE(&rlh, lyp, nfsly_list);
2786 			NFSCL_DEBUG(4, "ret layout\n");
2787 			nfscl_layoutreturn(clp->nfsc_nmp, lyp, cred, p);
2788 			nfscl_freelayout(lyp);
2789 		}
2790 
2791 		/*
2792 		 * Delegreturn any delegations cleaned out or recalled.
2793 		 */
2794 		TAILQ_FOREACH_SAFE(dp, &dh, nfsdl_list, ndp) {
2795 			newnfs_copycred(&dp->nfsdl_cred, cred);
2796 			(void) nfscl_trydelegreturn(dp, cred, clp->nfsc_nmp, p);
2797 			TAILQ_REMOVE(&dh, dp, nfsdl_list);
2798 			free(dp, M_NFSCLDELEG);
2799 		}
2800 
2801 		SLIST_INIT(&lfh);
2802 		/*
2803 		 * Call nfscl_cleanupkext() once per second to check for
2804 		 * open/lock owners where the process has exited.
2805 		 */
2806 		mytime = NFSD_MONOSEC;
2807 		if (prevsec != mytime) {
2808 			prevsec = mytime;
2809 			nfscl_cleanupkext(clp, &lfh);
2810 		}
2811 
2812 		/*
2813 		 * Do a ReleaseLockOwner for all lock owners where the
2814 		 * associated process no longer exists, as found by
2815 		 * nfscl_cleanupkext().
2816 		 */
2817 		newnfs_setroot(cred);
2818 		SLIST_FOREACH_SAFE(lfhp, &lfh, nfslfh_list, nlfhp) {
2819 			LIST_FOREACH_SAFE(lp, &lfhp->nfslfh_lock, nfsl_list,
2820 			    nlp) {
2821 				(void)nfsrpc_rellockown(clp->nfsc_nmp, lp,
2822 				    lfhp->nfslfh_fh, lfhp->nfslfh_len, cred,
2823 				    p);
2824 				nfscl_freelockowner(lp, 0);
2825 			}
2826 			free(lfhp, M_TEMP);
2827 		}
2828 		SLIST_INIT(&lfh);
2829 
2830 		NFSLOCKCLSTATE();
2831 		if ((clp->nfsc_flags & NFSCLFLAGS_RECOVER) == 0)
2832 			(void)mtx_sleep(clp, NFSCLSTATEMUTEXPTR, PWAIT, "nfscl",
2833 			    hz);
2834 		if (clp->nfsc_flags & NFSCLFLAGS_UMOUNT) {
2835 			clp->nfsc_flags &= ~NFSCLFLAGS_HASTHREAD;
2836 			NFSUNLOCKCLSTATE();
2837 			NFSFREECRED(cred);
2838 			wakeup((caddr_t)clp);
2839 			return;
2840 		}
2841 		NFSUNLOCKCLSTATE();
2842 	}
2843 }
2844 
2845 /*
2846  * Initiate state recovery. Called when NFSERR_STALECLIENTID,
2847  * NFSERR_STALESTATEID or NFSERR_BADSESSION is received.
2848  */
2849 APPLESTATIC void
2850 nfscl_initiate_recovery(struct nfsclclient *clp)
2851 {
2852 
2853 	if (clp == NULL)
2854 		return;
2855 	NFSLOCKCLSTATE();
2856 	clp->nfsc_flags |= NFSCLFLAGS_RECOVER;
2857 	NFSUNLOCKCLSTATE();
2858 	wakeup((caddr_t)clp);
2859 }
2860 
2861 /*
2862  * Dump out the state stuff for debugging.
2863  */
2864 APPLESTATIC void
2865 nfscl_dumpstate(struct nfsmount *nmp, int openowner, int opens,
2866     int lockowner, int locks)
2867 {
2868 	struct nfsclclient *clp;
2869 	struct nfsclowner *owp;
2870 	struct nfsclopen *op;
2871 	struct nfscllockowner *lp;
2872 	struct nfscllock *lop;
2873 	struct nfscldeleg *dp;
2874 
2875 	clp = nmp->nm_clp;
2876 	if (clp == NULL) {
2877 		printf("nfscl dumpstate NULL clp\n");
2878 		return;
2879 	}
2880 	NFSLOCKCLSTATE();
2881 	TAILQ_FOREACH(dp, &clp->nfsc_deleg, nfsdl_list) {
2882 	  LIST_FOREACH(owp, &dp->nfsdl_owner, nfsow_list) {
2883 	    if (openowner && !LIST_EMPTY(&owp->nfsow_open))
2884 		printf("owner=0x%x 0x%x 0x%x 0x%x seqid=%d\n",
2885 		    owp->nfsow_owner[0], owp->nfsow_owner[1],
2886 		    owp->nfsow_owner[2], owp->nfsow_owner[3],
2887 		    owp->nfsow_seqid);
2888 	    LIST_FOREACH(op, &owp->nfsow_open, nfso_list) {
2889 		if (opens)
2890 		    printf("open st=0x%x 0x%x 0x%x cnt=%d fh12=0x%x\n",
2891 			op->nfso_stateid.other[0], op->nfso_stateid.other[1],
2892 			op->nfso_stateid.other[2], op->nfso_opencnt,
2893 			op->nfso_fh[12]);
2894 		LIST_FOREACH(lp, &op->nfso_lock, nfsl_list) {
2895 		    if (lockowner)
2896 			printf("lckown=0x%x 0x%x 0x%x 0x%x seqid=%d st=0x%x 0x%x 0x%x\n",
2897 			    lp->nfsl_owner[0], lp->nfsl_owner[1],
2898 			    lp->nfsl_owner[2], lp->nfsl_owner[3],
2899 			    lp->nfsl_seqid,
2900 			    lp->nfsl_stateid.other[0], lp->nfsl_stateid.other[1],
2901 			    lp->nfsl_stateid.other[2]);
2902 		    LIST_FOREACH(lop, &lp->nfsl_lock, nfslo_list) {
2903 			if (locks)
2904 #ifdef __FreeBSD__
2905 			    printf("lck typ=%d fst=%ju end=%ju\n",
2906 				lop->nfslo_type, (intmax_t)lop->nfslo_first,
2907 				(intmax_t)lop->nfslo_end);
2908 #else
2909 			    printf("lck typ=%d fst=%qd end=%qd\n",
2910 				lop->nfslo_type, lop->nfslo_first,
2911 				lop->nfslo_end);
2912 #endif
2913 		    }
2914 		}
2915 	    }
2916 	  }
2917 	}
2918 	LIST_FOREACH(owp, &clp->nfsc_owner, nfsow_list) {
2919 	    if (openowner && !LIST_EMPTY(&owp->nfsow_open))
2920 		printf("owner=0x%x 0x%x 0x%x 0x%x seqid=%d\n",
2921 		    owp->nfsow_owner[0], owp->nfsow_owner[1],
2922 		    owp->nfsow_owner[2], owp->nfsow_owner[3],
2923 		    owp->nfsow_seqid);
2924 	    LIST_FOREACH(op, &owp->nfsow_open, nfso_list) {
2925 		if (opens)
2926 		    printf("open st=0x%x 0x%x 0x%x cnt=%d fh12=0x%x\n",
2927 			op->nfso_stateid.other[0], op->nfso_stateid.other[1],
2928 			op->nfso_stateid.other[2], op->nfso_opencnt,
2929 			op->nfso_fh[12]);
2930 		LIST_FOREACH(lp, &op->nfso_lock, nfsl_list) {
2931 		    if (lockowner)
2932 			printf("lckown=0x%x 0x%x 0x%x 0x%x seqid=%d st=0x%x 0x%x 0x%x\n",
2933 			    lp->nfsl_owner[0], lp->nfsl_owner[1],
2934 			    lp->nfsl_owner[2], lp->nfsl_owner[3],
2935 			    lp->nfsl_seqid,
2936 			    lp->nfsl_stateid.other[0], lp->nfsl_stateid.other[1],
2937 			    lp->nfsl_stateid.other[2]);
2938 		    LIST_FOREACH(lop, &lp->nfsl_lock, nfslo_list) {
2939 			if (locks)
2940 #ifdef __FreeBSD__
2941 			    printf("lck typ=%d fst=%ju end=%ju\n",
2942 				lop->nfslo_type, (intmax_t)lop->nfslo_first,
2943 				(intmax_t)lop->nfslo_end);
2944 #else
2945 			    printf("lck typ=%d fst=%qd end=%qd\n",
2946 				lop->nfslo_type, lop->nfslo_first,
2947 				lop->nfslo_end);
2948 #endif
2949 		    }
2950 		}
2951 	    }
2952 	}
2953 	NFSUNLOCKCLSTATE();
2954 }
2955 
2956 /*
2957  * Check for duplicate open owners and opens.
2958  * (Only used as a diagnostic aid.)
2959  */
2960 APPLESTATIC void
2961 nfscl_dupopen(vnode_t vp, int dupopens)
2962 {
2963 	struct nfsclclient *clp;
2964 	struct nfsclowner *owp, *owp2;
2965 	struct nfsclopen *op, *op2;
2966 	struct nfsfh *nfhp;
2967 
2968 	clp = VFSTONFS(vnode_mount(vp))->nm_clp;
2969 	if (clp == NULL) {
2970 		printf("nfscl dupopen NULL clp\n");
2971 		return;
2972 	}
2973 	nfhp = VTONFS(vp)->n_fhp;
2974 	NFSLOCKCLSTATE();
2975 
2976 	/*
2977 	 * First, search for duplicate owners.
2978 	 * These should never happen!
2979 	 */
2980 	LIST_FOREACH(owp2, &clp->nfsc_owner, nfsow_list) {
2981 	    LIST_FOREACH(owp, &clp->nfsc_owner, nfsow_list) {
2982 		if (owp != owp2 &&
2983 		    !NFSBCMP(owp->nfsow_owner, owp2->nfsow_owner,
2984 		    NFSV4CL_LOCKNAMELEN)) {
2985 			NFSUNLOCKCLSTATE();
2986 			printf("DUP OWNER\n");
2987 			nfscl_dumpstate(VFSTONFS(vnode_mount(vp)), 1, 1, 0, 0);
2988 			return;
2989 		}
2990 	    }
2991 	}
2992 
2993 	/*
2994 	 * Now, search for duplicate stateids.
2995 	 * These shouldn't happen, either.
2996 	 */
2997 	LIST_FOREACH(owp2, &clp->nfsc_owner, nfsow_list) {
2998 	    LIST_FOREACH(op2, &owp2->nfsow_open, nfso_list) {
2999 		LIST_FOREACH(owp, &clp->nfsc_owner, nfsow_list) {
3000 		    LIST_FOREACH(op, &owp->nfsow_open, nfso_list) {
3001 			if (op != op2 &&
3002 			    (op->nfso_stateid.other[0] != 0 ||
3003 			     op->nfso_stateid.other[1] != 0 ||
3004 			     op->nfso_stateid.other[2] != 0) &&
3005 			    op->nfso_stateid.other[0] == op2->nfso_stateid.other[0] &&
3006 			    op->nfso_stateid.other[1] == op2->nfso_stateid.other[1] &&
3007 			    op->nfso_stateid.other[2] == op2->nfso_stateid.other[2]) {
3008 			    NFSUNLOCKCLSTATE();
3009 			    printf("DUP STATEID\n");
3010 			    nfscl_dumpstate(VFSTONFS(vnode_mount(vp)), 1, 1, 0,
3011 				0);
3012 			    return;
3013 			}
3014 		    }
3015 		}
3016 	    }
3017 	}
3018 
3019 	/*
3020 	 * Now search for duplicate opens.
3021 	 * Duplicate opens for the same owner
3022 	 * should never occur. Other duplicates are
3023 	 * possible and are checked for if "dupopens"
3024 	 * is true.
3025 	 */
3026 	LIST_FOREACH(owp2, &clp->nfsc_owner, nfsow_list) {
3027 	    LIST_FOREACH(op2, &owp2->nfsow_open, nfso_list) {
3028 		if (nfhp->nfh_len == op2->nfso_fhlen &&
3029 		    !NFSBCMP(nfhp->nfh_fh, op2->nfso_fh, nfhp->nfh_len)) {
3030 		    LIST_FOREACH(owp, &clp->nfsc_owner, nfsow_list) {
3031 			LIST_FOREACH(op, &owp->nfsow_open, nfso_list) {
3032 			    if (op != op2 && nfhp->nfh_len == op->nfso_fhlen &&
3033 				!NFSBCMP(nfhp->nfh_fh, op->nfso_fh, nfhp->nfh_len) &&
3034 				(!NFSBCMP(op->nfso_own->nfsow_owner,
3035 				 op2->nfso_own->nfsow_owner, NFSV4CL_LOCKNAMELEN) ||
3036 				 dupopens)) {
3037 				if (!NFSBCMP(op->nfso_own->nfsow_owner,
3038 				    op2->nfso_own->nfsow_owner, NFSV4CL_LOCKNAMELEN)) {
3039 				    NFSUNLOCKCLSTATE();
3040 				    printf("BADDUP OPEN\n");
3041 				} else {
3042 				    NFSUNLOCKCLSTATE();
3043 				    printf("DUP OPEN\n");
3044 				}
3045 				nfscl_dumpstate(VFSTONFS(vnode_mount(vp)), 1, 1,
3046 				    0, 0);
3047 				return;
3048 			    }
3049 			}
3050 		    }
3051 		}
3052 	    }
3053 	}
3054 	NFSUNLOCKCLSTATE();
3055 }
3056 
3057 /*
3058  * During close, find an open that needs to be dereferenced and
3059  * dereference it. If there are no more opens for this file,
3060  * log a message to that effect.
3061  * Opens aren't actually Close'd until VOP_INACTIVE() is performed
3062  * on the file's vnode.
3063  * This is the safe way, since it is difficult to identify
3064  * which open the close is for and I/O can be performed after the
3065  * close(2) system call when a file is mmap'd.
3066  * If it returns 0 for success, there will be a referenced
3067  * clp returned via clpp.
3068  */
3069 APPLESTATIC int
3070 nfscl_getclose(vnode_t vp, struct nfsclclient **clpp)
3071 {
3072 	struct nfsclclient *clp;
3073 	struct nfsclowner *owp;
3074 	struct nfsclopen *op;
3075 	struct nfscldeleg *dp;
3076 	struct nfsfh *nfhp;
3077 	int error, notdecr;
3078 
3079 	error = nfscl_getcl(vnode_mount(vp), NULL, NULL, 1, &clp);
3080 	if (error)
3081 		return (error);
3082 	*clpp = clp;
3083 
3084 	nfhp = VTONFS(vp)->n_fhp;
3085 	notdecr = 1;
3086 	NFSLOCKCLSTATE();
3087 	/*
3088 	 * First, look for one under a delegation that was locally issued
3089 	 * and just decrement the opencnt for it. Since all my Opens against
3090 	 * the server are DENY_NONE, I don't see a problem with hanging
3091 	 * onto them. (It is much easier to use one of the extant Opens
3092 	 * that I already have on the server when a Delegation is recalled
3093 	 * than to do fresh Opens.) Someday, I might need to rethink this, but.
3094 	 */
3095 	dp = nfscl_finddeleg(clp, nfhp->nfh_fh, nfhp->nfh_len);
3096 	if (dp != NULL) {
3097 		LIST_FOREACH(owp, &dp->nfsdl_owner, nfsow_list) {
3098 			op = LIST_FIRST(&owp->nfsow_open);
3099 			if (op != NULL) {
3100 				/*
3101 				 * Since a delegation is for a file, there
3102 				 * should never be more than one open for
3103 				 * each openowner.
3104 				 */
3105 				if (LIST_NEXT(op, nfso_list) != NULL)
3106 					panic("nfscdeleg opens");
3107 				if (notdecr && op->nfso_opencnt > 0) {
3108 					notdecr = 0;
3109 					op->nfso_opencnt--;
3110 					break;
3111 				}
3112 			}
3113 		}
3114 	}
3115 
3116 	/* Now process the opens against the server. */
3117 	LIST_FOREACH(owp, &clp->nfsc_owner, nfsow_list) {
3118 		LIST_FOREACH(op, &owp->nfsow_open, nfso_list) {
3119 			if (op->nfso_fhlen == nfhp->nfh_len &&
3120 			    !NFSBCMP(op->nfso_fh, nfhp->nfh_fh,
3121 			    nfhp->nfh_len)) {
3122 				/* Found an open, decrement cnt if possible */
3123 				if (notdecr && op->nfso_opencnt > 0) {
3124 					notdecr = 0;
3125 					op->nfso_opencnt--;
3126 				}
3127 				/*
3128 				 * There are more opens, so just return.
3129 				 */
3130 				if (op->nfso_opencnt > 0) {
3131 					NFSUNLOCKCLSTATE();
3132 					return (0);
3133 				}
3134 			}
3135 		}
3136 	}
3137 	NFSUNLOCKCLSTATE();
3138 	if (notdecr)
3139 		printf("nfscl: never fnd open\n");
3140 	return (0);
3141 }
3142 
3143 APPLESTATIC int
3144 nfscl_doclose(vnode_t vp, struct nfsclclient **clpp, NFSPROC_T *p)
3145 {
3146 	struct nfsclclient *clp;
3147 	struct nfsclowner *owp, *nowp;
3148 	struct nfsclopen *op;
3149 	struct nfscldeleg *dp;
3150 	struct nfsfh *nfhp;
3151 	struct nfsclrecalllayout *recallp;
3152 	int error;
3153 
3154 	error = nfscl_getcl(vnode_mount(vp), NULL, NULL, 1, &clp);
3155 	if (error)
3156 		return (error);
3157 	*clpp = clp;
3158 
3159 	nfhp = VTONFS(vp)->n_fhp;
3160 	recallp = malloc(sizeof(*recallp), M_NFSLAYRECALL, M_WAITOK);
3161 	NFSLOCKCLSTATE();
3162 	/*
3163 	 * First get rid of the local Open structures, which should be no
3164 	 * longer in use.
3165 	 */
3166 	dp = nfscl_finddeleg(clp, nfhp->nfh_fh, nfhp->nfh_len);
3167 	if (dp != NULL) {
3168 		LIST_FOREACH_SAFE(owp, &dp->nfsdl_owner, nfsow_list, nowp) {
3169 			op = LIST_FIRST(&owp->nfsow_open);
3170 			if (op != NULL) {
3171 				KASSERT((op->nfso_opencnt == 0),
3172 				    ("nfscl: bad open cnt on deleg"));
3173 				nfscl_freeopen(op, 1);
3174 			}
3175 			nfscl_freeopenowner(owp, 1);
3176 		}
3177 	}
3178 
3179 	/* Return any layouts marked return on close. */
3180 	nfscl_retoncloselayout(vp, clp, nfhp->nfh_fh, nfhp->nfh_len, &recallp);
3181 
3182 	/* Now process the opens against the server. */
3183 lookformore:
3184 	LIST_FOREACH(owp, &clp->nfsc_owner, nfsow_list) {
3185 		op = LIST_FIRST(&owp->nfsow_open);
3186 		while (op != NULL) {
3187 			if (op->nfso_fhlen == nfhp->nfh_len &&
3188 			    !NFSBCMP(op->nfso_fh, nfhp->nfh_fh,
3189 			    nfhp->nfh_len)) {
3190 				/* Found an open, close it. */
3191 #ifdef DIAGNOSTIC
3192 				KASSERT((op->nfso_opencnt == 0),
3193 				    ("nfscl: bad open cnt on server (%d)",
3194 				     op->nfso_opencnt));
3195 #endif
3196 				NFSUNLOCKCLSTATE();
3197 				nfsrpc_doclose(VFSTONFS(vnode_mount(vp)), op,
3198 				    p);
3199 				NFSLOCKCLSTATE();
3200 				goto lookformore;
3201 			}
3202 			op = LIST_NEXT(op, nfso_list);
3203 		}
3204 	}
3205 	NFSUNLOCKCLSTATE();
3206 	/*
3207 	 * recallp has been set NULL by nfscl_retoncloselayout() if it was
3208 	 * used by the function, but calling free() with a NULL pointer is ok.
3209 	 */
3210 	free(recallp, M_NFSLAYRECALL);
3211 	return (0);
3212 }
3213 
3214 /*
3215  * Return all delegations on this client.
3216  * (Must be called with client sleep lock.)
3217  */
3218 static void
3219 nfscl_delegreturnall(struct nfsclclient *clp, NFSPROC_T *p)
3220 {
3221 	struct nfscldeleg *dp, *ndp;
3222 	struct ucred *cred;
3223 
3224 	cred = newnfs_getcred();
3225 	TAILQ_FOREACH_SAFE(dp, &clp->nfsc_deleg, nfsdl_list, ndp) {
3226 		nfscl_cleandeleg(dp);
3227 		(void) nfscl_trydelegreturn(dp, cred, clp->nfsc_nmp, p);
3228 		nfscl_freedeleg(&clp->nfsc_deleg, dp);
3229 	}
3230 	NFSFREECRED(cred);
3231 }
3232 
3233 /*
3234  * Do a callback RPC.
3235  */
3236 APPLESTATIC void
3237 nfscl_docb(struct nfsrv_descript *nd, NFSPROC_T *p)
3238 {
3239 	int clist, gotseq_ok, i, j, k, op, rcalls;
3240 	u_int32_t *tl;
3241 	struct nfsclclient *clp;
3242 	struct nfscldeleg *dp = NULL;
3243 	int numops, taglen = -1, error = 0, trunc __unused;
3244 	u_int32_t minorvers = 0, retops = 0, *retopsp = NULL, *repp, cbident;
3245 	u_char tag[NFSV4_SMALLSTR + 1], *tagstr;
3246 	vnode_t vp = NULL;
3247 	struct nfsnode *np;
3248 	struct vattr va;
3249 	struct nfsfh *nfhp;
3250 	mount_t mp;
3251 	nfsattrbit_t attrbits, rattrbits;
3252 	nfsv4stateid_t stateid;
3253 	uint32_t seqid, slotid = 0, highslot, cachethis __unused;
3254 	uint8_t sessionid[NFSX_V4SESSIONID];
3255 	struct mbuf *rep;
3256 	struct nfscllayout *lyp;
3257 	uint64_t filesid[2], len, off;
3258 	int changed, gotone, laytype, recalltype;
3259 	uint32_t iomode;
3260 	struct nfsclrecalllayout *recallp = NULL;
3261 	struct nfsclsession *tsep;
3262 
3263 	gotseq_ok = 0;
3264 	nfsrvd_rephead(nd);
3265 	NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
3266 	taglen = fxdr_unsigned(int, *tl);
3267 	if (taglen < 0) {
3268 		error = EBADRPC;
3269 		goto nfsmout;
3270 	}
3271 	if (taglen <= NFSV4_SMALLSTR)
3272 		tagstr = tag;
3273 	else
3274 		tagstr = malloc(taglen + 1, M_TEMP, M_WAITOK);
3275 	error = nfsrv_mtostr(nd, tagstr, taglen);
3276 	if (error) {
3277 		if (taglen > NFSV4_SMALLSTR)
3278 			free(tagstr, M_TEMP);
3279 		taglen = -1;
3280 		goto nfsmout;
3281 	}
3282 	(void) nfsm_strtom(nd, tag, taglen);
3283 	if (taglen > NFSV4_SMALLSTR) {
3284 		free(tagstr, M_TEMP);
3285 	}
3286 	NFSM_BUILD(retopsp, u_int32_t *, NFSX_UNSIGNED);
3287 	NFSM_DISSECT(tl, u_int32_t *, 3 * NFSX_UNSIGNED);
3288 	minorvers = fxdr_unsigned(u_int32_t, *tl++);
3289 	if (minorvers != NFSV4_MINORVERSION && minorvers != NFSV41_MINORVERSION)
3290 		nd->nd_repstat = NFSERR_MINORVERMISMATCH;
3291 	cbident = fxdr_unsigned(u_int32_t, *tl++);
3292 	if (nd->nd_repstat)
3293 		numops = 0;
3294 	else
3295 		numops = fxdr_unsigned(int, *tl);
3296 	/*
3297 	 * Loop around doing the sub ops.
3298 	 */
3299 	for (i = 0; i < numops; i++) {
3300 		NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
3301 		NFSM_BUILD(repp, u_int32_t *, 2 * NFSX_UNSIGNED);
3302 		*repp++ = *tl;
3303 		op = fxdr_unsigned(int, *tl);
3304 		if (op < NFSV4OP_CBGETATTR ||
3305 		   (op > NFSV4OP_CBRECALL && minorvers == NFSV4_MINORVERSION) ||
3306 		   (op > NFSV4OP_CBNOTIFYDEVID &&
3307 		    minorvers == NFSV41_MINORVERSION)) {
3308 		    nd->nd_repstat = NFSERR_OPILLEGAL;
3309 		    *repp = nfscl_errmap(nd, minorvers);
3310 		    retops++;
3311 		    break;
3312 		}
3313 		nd->nd_procnum = op;
3314 		if (op < NFSV41_CBNOPS)
3315 			nfsstatsv1.cbrpccnt[nd->nd_procnum]++;
3316 		switch (op) {
3317 		case NFSV4OP_CBGETATTR:
3318 			NFSCL_DEBUG(4, "cbgetattr\n");
3319 			mp = NULL;
3320 			vp = NULL;
3321 			error = nfsm_getfh(nd, &nfhp);
3322 			if (!error)
3323 				error = nfsrv_getattrbits(nd, &attrbits,
3324 				    NULL, NULL);
3325 			if (error == 0 && i == 0 &&
3326 			    minorvers != NFSV4_MINORVERSION)
3327 				error = NFSERR_OPNOTINSESS;
3328 			if (!error) {
3329 				mp = nfscl_getmnt(minorvers, sessionid, cbident,
3330 				    &clp);
3331 				if (mp == NULL)
3332 					error = NFSERR_SERVERFAULT;
3333 			}
3334 			if (!error) {
3335 				error = nfscl_ngetreopen(mp, nfhp->nfh_fh,
3336 				    nfhp->nfh_len, p, &np);
3337 				if (!error)
3338 					vp = NFSTOV(np);
3339 			}
3340 			if (!error) {
3341 				NFSZERO_ATTRBIT(&rattrbits);
3342 				NFSLOCKCLSTATE();
3343 				dp = nfscl_finddeleg(clp, nfhp->nfh_fh,
3344 				    nfhp->nfh_len);
3345 				if (dp != NULL) {
3346 					if (NFSISSET_ATTRBIT(&attrbits,
3347 					    NFSATTRBIT_SIZE)) {
3348 						if (vp != NULL)
3349 							va.va_size = np->n_size;
3350 						else
3351 							va.va_size =
3352 							    dp->nfsdl_size;
3353 						NFSSETBIT_ATTRBIT(&rattrbits,
3354 						    NFSATTRBIT_SIZE);
3355 					}
3356 					if (NFSISSET_ATTRBIT(&attrbits,
3357 					    NFSATTRBIT_CHANGE)) {
3358 						va.va_filerev =
3359 						    dp->nfsdl_change;
3360 						if (vp == NULL ||
3361 						    (np->n_flag & NDELEGMOD))
3362 							va.va_filerev++;
3363 						NFSSETBIT_ATTRBIT(&rattrbits,
3364 						    NFSATTRBIT_CHANGE);
3365 					}
3366 				} else
3367 					error = NFSERR_SERVERFAULT;
3368 				NFSUNLOCKCLSTATE();
3369 			}
3370 			if (vp != NULL)
3371 				vrele(vp);
3372 			if (mp != NULL)
3373 				vfs_unbusy(mp);
3374 			if (nfhp != NULL)
3375 				free(nfhp, M_NFSFH);
3376 			if (!error)
3377 				(void) nfsv4_fillattr(nd, NULL, NULL, NULL, &va,
3378 				    NULL, 0, &rattrbits, NULL, p, 0, 0, 0, 0,
3379 				    (uint64_t)0, NULL);
3380 			break;
3381 		case NFSV4OP_CBRECALL:
3382 			NFSCL_DEBUG(4, "cbrecall\n");
3383 			NFSM_DISSECT(tl, u_int32_t *, NFSX_STATEID +
3384 			    NFSX_UNSIGNED);
3385 			stateid.seqid = *tl++;
3386 			NFSBCOPY((caddr_t)tl, (caddr_t)stateid.other,
3387 			    NFSX_STATEIDOTHER);
3388 			tl += (NFSX_STATEIDOTHER / NFSX_UNSIGNED);
3389 			trunc = fxdr_unsigned(int, *tl);
3390 			error = nfsm_getfh(nd, &nfhp);
3391 			if (error == 0 && i == 0 &&
3392 			    minorvers != NFSV4_MINORVERSION)
3393 				error = NFSERR_OPNOTINSESS;
3394 			if (!error) {
3395 				NFSLOCKCLSTATE();
3396 				if (minorvers == NFSV4_MINORVERSION)
3397 					clp = nfscl_getclnt(cbident);
3398 				else
3399 					clp = nfscl_getclntsess(sessionid);
3400 				if (clp != NULL) {
3401 					dp = nfscl_finddeleg(clp, nfhp->nfh_fh,
3402 					    nfhp->nfh_len);
3403 					if (dp != NULL && (dp->nfsdl_flags &
3404 					    NFSCLDL_DELEGRET) == 0) {
3405 						dp->nfsdl_flags |=
3406 						    NFSCLDL_RECALL;
3407 						wakeup((caddr_t)clp);
3408 					}
3409 				} else {
3410 					error = NFSERR_SERVERFAULT;
3411 				}
3412 				NFSUNLOCKCLSTATE();
3413 			}
3414 			if (nfhp != NULL)
3415 				free(nfhp, M_NFSFH);
3416 			break;
3417 		case NFSV4OP_CBLAYOUTRECALL:
3418 			NFSCL_DEBUG(4, "cblayrec\n");
3419 			nfhp = NULL;
3420 			NFSM_DISSECT(tl, uint32_t *, 4 * NFSX_UNSIGNED);
3421 			laytype = fxdr_unsigned(int, *tl++);
3422 			iomode = fxdr_unsigned(uint32_t, *tl++);
3423 			if (newnfs_true == *tl++)
3424 				changed = 1;
3425 			else
3426 				changed = 0;
3427 			recalltype = fxdr_unsigned(int, *tl);
3428 			NFSCL_DEBUG(4, "layt=%d iom=%d ch=%d rectyp=%d\n",
3429 			    laytype, iomode, changed, recalltype);
3430 			recallp = malloc(sizeof(*recallp), M_NFSLAYRECALL,
3431 			    M_WAITOK);
3432 			if (laytype != NFSLAYOUT_NFSV4_1_FILES &&
3433 			    laytype != NFSLAYOUT_FLEXFILE)
3434 				error = NFSERR_NOMATCHLAYOUT;
3435 			else if (recalltype == NFSLAYOUTRETURN_FILE) {
3436 				error = nfsm_getfh(nd, &nfhp);
3437 				NFSCL_DEBUG(4, "retfile getfh=%d\n", error);
3438 				if (error != 0)
3439 					goto nfsmout;
3440 				NFSM_DISSECT(tl, u_int32_t *, 2 * NFSX_HYPER +
3441 				    NFSX_STATEID);
3442 				off = fxdr_hyper(tl); tl += 2;
3443 				len = fxdr_hyper(tl); tl += 2;
3444 				stateid.seqid = fxdr_unsigned(uint32_t, *tl++);
3445 				NFSBCOPY(tl, stateid.other, NFSX_STATEIDOTHER);
3446 				if (minorvers == NFSV4_MINORVERSION)
3447 					error = NFSERR_NOTSUPP;
3448 				else if (i == 0)
3449 					error = NFSERR_OPNOTINSESS;
3450 				NFSCL_DEBUG(4, "off=%ju len=%ju sq=%u err=%d\n",
3451 				    (uintmax_t)off, (uintmax_t)len,
3452 				    stateid.seqid, error);
3453 				if (error == 0) {
3454 					NFSLOCKCLSTATE();
3455 					clp = nfscl_getclntsess(sessionid);
3456 					NFSCL_DEBUG(4, "cbly clp=%p\n", clp);
3457 					if (clp != NULL) {
3458 						lyp = nfscl_findlayout(clp,
3459 						    nfhp->nfh_fh,
3460 						    nfhp->nfh_len);
3461 						NFSCL_DEBUG(4, "cblyp=%p\n",
3462 						    lyp);
3463 						if (lyp != NULL &&
3464 						    (lyp->nfsly_flags &
3465 						     (NFSLY_FILES |
3466 						      NFSLY_FLEXFILE)) != 0 &&
3467 						    !NFSBCMP(stateid.other,
3468 						    lyp->nfsly_stateid.other,
3469 						    NFSX_STATEIDOTHER)) {
3470 							error =
3471 							    nfscl_layoutrecall(
3472 							    recalltype,
3473 							    lyp, iomode, off,
3474 							    len, stateid.seqid,
3475 							    0, 0, NULL,
3476 							    recallp);
3477 							recallp = NULL;
3478 							wakeup(clp);
3479 							NFSCL_DEBUG(4,
3480 							    "aft layrcal=%d\n",
3481 							    error);
3482 						} else
3483 							error =
3484 							  NFSERR_NOMATCHLAYOUT;
3485 					} else
3486 						error = NFSERR_NOMATCHLAYOUT;
3487 					NFSUNLOCKCLSTATE();
3488 				}
3489 				free(nfhp, M_NFSFH);
3490 			} else if (recalltype == NFSLAYOUTRETURN_FSID) {
3491 				NFSM_DISSECT(tl, uint32_t *, 2 * NFSX_HYPER);
3492 				filesid[0] = fxdr_hyper(tl); tl += 2;
3493 				filesid[1] = fxdr_hyper(tl); tl += 2;
3494 				gotone = 0;
3495 				NFSLOCKCLSTATE();
3496 				clp = nfscl_getclntsess(sessionid);
3497 				if (clp != NULL) {
3498 					TAILQ_FOREACH(lyp, &clp->nfsc_layout,
3499 					    nfsly_list) {
3500 						if (lyp->nfsly_filesid[0] ==
3501 						    filesid[0] &&
3502 						    lyp->nfsly_filesid[1] ==
3503 						    filesid[1]) {
3504 							error =
3505 							    nfscl_layoutrecall(
3506 							    recalltype,
3507 							    lyp, iomode, 0,
3508 							    UINT64_MAX,
3509 							    lyp->nfsly_stateid.seqid,
3510 							    0, 0, NULL,
3511 							    recallp);
3512 							recallp = NULL;
3513 							gotone = 1;
3514 						}
3515 					}
3516 					if (gotone != 0)
3517 						wakeup(clp);
3518 					else
3519 						error = NFSERR_NOMATCHLAYOUT;
3520 				} else
3521 					error = NFSERR_NOMATCHLAYOUT;
3522 				NFSUNLOCKCLSTATE();
3523 			} else if (recalltype == NFSLAYOUTRETURN_ALL) {
3524 				gotone = 0;
3525 				NFSLOCKCLSTATE();
3526 				clp = nfscl_getclntsess(sessionid);
3527 				if (clp != NULL) {
3528 					TAILQ_FOREACH(lyp, &clp->nfsc_layout,
3529 					    nfsly_list) {
3530 						error = nfscl_layoutrecall(
3531 						    recalltype, lyp, iomode, 0,
3532 						    UINT64_MAX,
3533 						    lyp->nfsly_stateid.seqid,
3534 						    0, 0, NULL, recallp);
3535 						recallp = NULL;
3536 						gotone = 1;
3537 					}
3538 					if (gotone != 0)
3539 						wakeup(clp);
3540 					else
3541 						error = NFSERR_NOMATCHLAYOUT;
3542 				} else
3543 					error = NFSERR_NOMATCHLAYOUT;
3544 				NFSUNLOCKCLSTATE();
3545 			} else
3546 				error = NFSERR_NOMATCHLAYOUT;
3547 			if (recallp != NULL) {
3548 				free(recallp, M_NFSLAYRECALL);
3549 				recallp = NULL;
3550 			}
3551 			break;
3552 		case NFSV4OP_CBSEQUENCE:
3553 			NFSM_DISSECT(tl, uint32_t *, NFSX_V4SESSIONID +
3554 			    5 * NFSX_UNSIGNED);
3555 			bcopy(tl, sessionid, NFSX_V4SESSIONID);
3556 			tl += NFSX_V4SESSIONID / NFSX_UNSIGNED;
3557 			seqid = fxdr_unsigned(uint32_t, *tl++);
3558 			slotid = fxdr_unsigned(uint32_t, *tl++);
3559 			highslot = fxdr_unsigned(uint32_t, *tl++);
3560 			cachethis = *tl++;
3561 			/* Throw away the referring call stuff. */
3562 			clist = fxdr_unsigned(int, *tl);
3563 			for (j = 0; j < clist; j++) {
3564 				NFSM_DISSECT(tl, uint32_t *, NFSX_V4SESSIONID +
3565 				    NFSX_UNSIGNED);
3566 				tl += NFSX_V4SESSIONID / NFSX_UNSIGNED;
3567 				rcalls = fxdr_unsigned(int, *tl);
3568 				for (k = 0; k < rcalls; k++) {
3569 					NFSM_DISSECT(tl, uint32_t *,
3570 					    2 * NFSX_UNSIGNED);
3571 				}
3572 			}
3573 			NFSLOCKCLSTATE();
3574 			if (i == 0) {
3575 				clp = nfscl_getclntsess(sessionid);
3576 				if (clp == NULL)
3577 					error = NFSERR_SERVERFAULT;
3578 			} else
3579 				error = NFSERR_SEQUENCEPOS;
3580 			if (error == 0) {
3581 				tsep = nfsmnt_mdssession(clp->nfsc_nmp);
3582 				error = nfsv4_seqsession(seqid, slotid,
3583 				    highslot, tsep->nfsess_cbslots, &rep,
3584 				    tsep->nfsess_backslots);
3585 			}
3586 			NFSUNLOCKCLSTATE();
3587 			if (error == 0 || error == NFSERR_REPLYFROMCACHE) {
3588 				gotseq_ok = 1;
3589 				if (rep != NULL) {
3590 					/*
3591 					 * Handle a reply for a retried
3592 					 * callback.  The reply will be
3593 					 * re-inserted in the session cache
3594 					 * by the nfsv4_seqsess_cacherep() call
3595 					 * after out:
3596 					 */
3597 					KASSERT(error == NFSERR_REPLYFROMCACHE,
3598 					    ("cbsequence: non-NULL rep"));
3599 					NFSCL_DEBUG(4, "Got cbretry\n");
3600 					m_freem(nd->nd_mreq);
3601 					nd->nd_mreq = rep;
3602 					rep = NULL;
3603 					goto out;
3604 				}
3605 				NFSM_BUILD(tl, uint32_t *,
3606 				    NFSX_V4SESSIONID + 4 * NFSX_UNSIGNED);
3607 				bcopy(sessionid, tl, NFSX_V4SESSIONID);
3608 				tl += NFSX_V4SESSIONID / NFSX_UNSIGNED;
3609 				*tl++ = txdr_unsigned(seqid);
3610 				*tl++ = txdr_unsigned(slotid);
3611 				*tl++ = txdr_unsigned(NFSV4_CBSLOTS - 1);
3612 				*tl = txdr_unsigned(NFSV4_CBSLOTS - 1);
3613 			}
3614 			break;
3615 		default:
3616 			if (i == 0 && minorvers == NFSV41_MINORVERSION)
3617 				error = NFSERR_OPNOTINSESS;
3618 			else {
3619 				NFSCL_DEBUG(1, "unsupp callback %d\n", op);
3620 				error = NFSERR_NOTSUPP;
3621 			}
3622 			break;
3623 		}
3624 		if (error) {
3625 			if (error == EBADRPC || error == NFSERR_BADXDR) {
3626 				nd->nd_repstat = NFSERR_BADXDR;
3627 			} else {
3628 				nd->nd_repstat = error;
3629 			}
3630 			error = 0;
3631 		}
3632 		retops++;
3633 		if (nd->nd_repstat) {
3634 			*repp = nfscl_errmap(nd, minorvers);
3635 			break;
3636 		} else
3637 			*repp = 0;	/* NFS4_OK */
3638 	}
3639 nfsmout:
3640 	if (recallp != NULL)
3641 		free(recallp, M_NFSLAYRECALL);
3642 	if (error) {
3643 		if (error == EBADRPC || error == NFSERR_BADXDR)
3644 			nd->nd_repstat = NFSERR_BADXDR;
3645 		else
3646 			printf("nfsv4 comperr1=%d\n", error);
3647 	}
3648 	if (taglen == -1) {
3649 		NFSM_BUILD(tl, u_int32_t *, 2 * NFSX_UNSIGNED);
3650 		*tl++ = 0;
3651 		*tl = 0;
3652 	} else {
3653 		*retopsp = txdr_unsigned(retops);
3654 	}
3655 	*nd->nd_errp = nfscl_errmap(nd, minorvers);
3656 out:
3657 	if (gotseq_ok != 0) {
3658 		rep = m_copym(nd->nd_mreq, 0, M_COPYALL, M_WAITOK);
3659 		NFSLOCKCLSTATE();
3660 		clp = nfscl_getclntsess(sessionid);
3661 		if (clp != NULL) {
3662 			tsep = nfsmnt_mdssession(clp->nfsc_nmp);
3663 			nfsv4_seqsess_cacherep(slotid, tsep->nfsess_cbslots,
3664 			    NFSERR_OK, &rep);
3665 			NFSUNLOCKCLSTATE();
3666 		} else {
3667 			NFSUNLOCKCLSTATE();
3668 			m_freem(rep);
3669 		}
3670 	}
3671 }
3672 
3673 /*
3674  * Generate the next cbident value. Basically just increment a static value
3675  * and then check that it isn't already in the list, if it has wrapped around.
3676  */
3677 static u_int32_t
3678 nfscl_nextcbident(void)
3679 {
3680 	struct nfsclclient *clp;
3681 	int matched;
3682 	static u_int32_t nextcbident = 0;
3683 	static int haswrapped = 0;
3684 
3685 	nextcbident++;
3686 	if (nextcbident == 0)
3687 		haswrapped = 1;
3688 	if (haswrapped) {
3689 		/*
3690 		 * Search the clientid list for one already using this cbident.
3691 		 */
3692 		do {
3693 			matched = 0;
3694 			NFSLOCKCLSTATE();
3695 			LIST_FOREACH(clp, &nfsclhead, nfsc_list) {
3696 				if (clp->nfsc_cbident == nextcbident) {
3697 					matched = 1;
3698 					break;
3699 				}
3700 			}
3701 			NFSUNLOCKCLSTATE();
3702 			if (matched == 1)
3703 				nextcbident++;
3704 		} while (matched);
3705 	}
3706 	return (nextcbident);
3707 }
3708 
3709 /*
3710  * Get the mount point related to a given cbident or session and busy it.
3711  */
3712 static mount_t
3713 nfscl_getmnt(int minorvers, uint8_t *sessionid, u_int32_t cbident,
3714     struct nfsclclient **clpp)
3715 {
3716 	struct nfsclclient *clp;
3717 	mount_t mp;
3718 	int error;
3719 	struct nfsclsession *tsep;
3720 
3721 	*clpp = NULL;
3722 	NFSLOCKCLSTATE();
3723 	LIST_FOREACH(clp, &nfsclhead, nfsc_list) {
3724 		tsep = nfsmnt_mdssession(clp->nfsc_nmp);
3725 		if (minorvers == NFSV4_MINORVERSION) {
3726 			if (clp->nfsc_cbident == cbident)
3727 				break;
3728 		} else if (!NFSBCMP(tsep->nfsess_sessionid, sessionid,
3729 		    NFSX_V4SESSIONID))
3730 			break;
3731 	}
3732 	if (clp == NULL) {
3733 		NFSUNLOCKCLSTATE();
3734 		return (NULL);
3735 	}
3736 	mp = clp->nfsc_nmp->nm_mountp;
3737 	vfs_ref(mp);
3738 	NFSUNLOCKCLSTATE();
3739 	error = vfs_busy(mp, 0);
3740 	vfs_rel(mp);
3741 	if (error != 0)
3742 		return (NULL);
3743 	*clpp = clp;
3744 	return (mp);
3745 }
3746 
3747 /*
3748  * Get the clientid pointer related to a given cbident.
3749  */
3750 static struct nfsclclient *
3751 nfscl_getclnt(u_int32_t cbident)
3752 {
3753 	struct nfsclclient *clp;
3754 
3755 	LIST_FOREACH(clp, &nfsclhead, nfsc_list)
3756 		if (clp->nfsc_cbident == cbident)
3757 			break;
3758 	return (clp);
3759 }
3760 
3761 /*
3762  * Get the clientid pointer related to a given sessionid.
3763  */
3764 static struct nfsclclient *
3765 nfscl_getclntsess(uint8_t *sessionid)
3766 {
3767 	struct nfsclclient *clp;
3768 	struct nfsclsession *tsep;
3769 
3770 	LIST_FOREACH(clp, &nfsclhead, nfsc_list) {
3771 		tsep = nfsmnt_mdssession(clp->nfsc_nmp);
3772 		if (!NFSBCMP(tsep->nfsess_sessionid, sessionid,
3773 		    NFSX_V4SESSIONID))
3774 			break;
3775 	}
3776 	return (clp);
3777 }
3778 
3779 /*
3780  * Search for a lock conflict locally on the client. A conflict occurs if
3781  * - not same owner and overlapping byte range and at least one of them is
3782  *   a write lock or this is an unlock.
3783  */
3784 static int
3785 nfscl_localconflict(struct nfsclclient *clp, u_int8_t *fhp, int fhlen,
3786     struct nfscllock *nlop, u_int8_t *own, struct nfscldeleg *dp,
3787     struct nfscllock **lopp)
3788 {
3789 	struct nfsclowner *owp;
3790 	struct nfsclopen *op;
3791 	int ret;
3792 
3793 	if (dp != NULL) {
3794 		ret = nfscl_checkconflict(&dp->nfsdl_lock, nlop, own, lopp);
3795 		if (ret)
3796 			return (ret);
3797 	}
3798 	LIST_FOREACH(owp, &clp->nfsc_owner, nfsow_list) {
3799 		LIST_FOREACH(op, &owp->nfsow_open, nfso_list) {
3800 			if (op->nfso_fhlen == fhlen &&
3801 			    !NFSBCMP(op->nfso_fh, fhp, fhlen)) {
3802 				ret = nfscl_checkconflict(&op->nfso_lock, nlop,
3803 				    own, lopp);
3804 				if (ret)
3805 					return (ret);
3806 			}
3807 		}
3808 	}
3809 	return (0);
3810 }
3811 
3812 static int
3813 nfscl_checkconflict(struct nfscllockownerhead *lhp, struct nfscllock *nlop,
3814     u_int8_t *own, struct nfscllock **lopp)
3815 {
3816 	struct nfscllockowner *lp;
3817 	struct nfscllock *lop;
3818 
3819 	LIST_FOREACH(lp, lhp, nfsl_list) {
3820 		if (NFSBCMP(lp->nfsl_owner, own, NFSV4CL_LOCKNAMELEN)) {
3821 			LIST_FOREACH(lop, &lp->nfsl_lock, nfslo_list) {
3822 				if (lop->nfslo_first >= nlop->nfslo_end)
3823 					break;
3824 				if (lop->nfslo_end <= nlop->nfslo_first)
3825 					continue;
3826 				if (lop->nfslo_type == F_WRLCK ||
3827 				    nlop->nfslo_type == F_WRLCK ||
3828 				    nlop->nfslo_type == F_UNLCK) {
3829 					if (lopp != NULL)
3830 						*lopp = lop;
3831 					return (NFSERR_DENIED);
3832 				}
3833 			}
3834 		}
3835 	}
3836 	return (0);
3837 }
3838 
3839 /*
3840  * Check for a local conflicting lock.
3841  */
3842 APPLESTATIC int
3843 nfscl_lockt(vnode_t vp, struct nfsclclient *clp, u_int64_t off,
3844     u_int64_t len, struct flock *fl, NFSPROC_T *p, void *id, int flags)
3845 {
3846 	struct nfscllock *lop, nlck;
3847 	struct nfscldeleg *dp;
3848 	struct nfsnode *np;
3849 	u_int8_t own[NFSV4CL_LOCKNAMELEN];
3850 	int error;
3851 
3852 	nlck.nfslo_type = fl->l_type;
3853 	nlck.nfslo_first = off;
3854 	if (len == NFS64BITSSET) {
3855 		nlck.nfslo_end = NFS64BITSSET;
3856 	} else {
3857 		nlck.nfslo_end = off + len;
3858 		if (nlck.nfslo_end <= nlck.nfslo_first)
3859 			return (NFSERR_INVAL);
3860 	}
3861 	np = VTONFS(vp);
3862 	nfscl_filllockowner(id, own, flags);
3863 	NFSLOCKCLSTATE();
3864 	dp = nfscl_finddeleg(clp, np->n_fhp->nfh_fh, np->n_fhp->nfh_len);
3865 	error = nfscl_localconflict(clp, np->n_fhp->nfh_fh, np->n_fhp->nfh_len,
3866 	    &nlck, own, dp, &lop);
3867 	if (error != 0) {
3868 		fl->l_whence = SEEK_SET;
3869 		fl->l_start = lop->nfslo_first;
3870 		if (lop->nfslo_end == NFS64BITSSET)
3871 			fl->l_len = 0;
3872 		else
3873 			fl->l_len = lop->nfslo_end - lop->nfslo_first;
3874 		fl->l_pid = (pid_t)0;
3875 		fl->l_type = lop->nfslo_type;
3876 		error = -1;			/* no RPC required */
3877 	} else if (dp != NULL && ((dp->nfsdl_flags & NFSCLDL_WRITE) ||
3878 	    fl->l_type == F_RDLCK)) {
3879 		/*
3880 		 * The delegation ensures that there isn't a conflicting
3881 		 * lock on the server, so return -1 to indicate an RPC
3882 		 * isn't required.
3883 		 */
3884 		fl->l_type = F_UNLCK;
3885 		error = -1;
3886 	}
3887 	NFSUNLOCKCLSTATE();
3888 	return (error);
3889 }
3890 
3891 /*
3892  * Handle Recall of a delegation.
3893  * The clp must be exclusive locked when this is called.
3894  */
3895 static int
3896 nfscl_recalldeleg(struct nfsclclient *clp, struct nfsmount *nmp,
3897     struct nfscldeleg *dp, vnode_t vp, struct ucred *cred, NFSPROC_T *p,
3898     int called_from_renewthread)
3899 {
3900 	struct nfsclowner *owp, *lowp, *nowp;
3901 	struct nfsclopen *op, *lop;
3902 	struct nfscllockowner *lp;
3903 	struct nfscllock *lckp;
3904 	struct nfsnode *np;
3905 	int error = 0, ret, gotvp = 0;
3906 
3907 	if (vp == NULL) {
3908 		/*
3909 		 * First, get a vnode for the file. This is needed to do RPCs.
3910 		 */
3911 		ret = nfscl_ngetreopen(nmp->nm_mountp, dp->nfsdl_fh,
3912 		    dp->nfsdl_fhlen, p, &np);
3913 		if (ret) {
3914 			/*
3915 			 * File isn't open, so nothing to move over to the
3916 			 * server.
3917 			 */
3918 			return (0);
3919 		}
3920 		vp = NFSTOV(np);
3921 		gotvp = 1;
3922 	} else {
3923 		np = VTONFS(vp);
3924 	}
3925 	dp->nfsdl_flags &= ~NFSCLDL_MODTIMESET;
3926 
3927 	/*
3928 	 * Ok, if it's a write delegation, flush data to the server, so
3929 	 * that close/open consistency is retained.
3930 	 */
3931 	ret = 0;
3932 	NFSLOCKNODE(np);
3933 	if ((dp->nfsdl_flags & NFSCLDL_WRITE) && (np->n_flag & NMODIFIED)) {
3934 		np->n_flag |= NDELEGRECALL;
3935 		NFSUNLOCKNODE(np);
3936 		ret = ncl_flush(vp, MNT_WAIT, p, 1, called_from_renewthread);
3937 		NFSLOCKNODE(np);
3938 		np->n_flag &= ~NDELEGRECALL;
3939 	}
3940 	NFSINVALATTRCACHE(np);
3941 	NFSUNLOCKNODE(np);
3942 	if (ret == EIO && called_from_renewthread != 0) {
3943 		/*
3944 		 * If the flush failed with EIO for the renew thread,
3945 		 * return now, so that the dirty buffer will be flushed
3946 		 * later.
3947 		 */
3948 		if (gotvp != 0)
3949 			vrele(vp);
3950 		return (ret);
3951 	}
3952 
3953 	/*
3954 	 * Now, for each openowner with opens issued locally, move them
3955 	 * over to state against the server.
3956 	 */
3957 	LIST_FOREACH(lowp, &dp->nfsdl_owner, nfsow_list) {
3958 		lop = LIST_FIRST(&lowp->nfsow_open);
3959 		if (lop != NULL) {
3960 			if (LIST_NEXT(lop, nfso_list) != NULL)
3961 				panic("nfsdlg mult opens");
3962 			/*
3963 			 * Look for the same openowner against the server.
3964 			 */
3965 			LIST_FOREACH(owp, &clp->nfsc_owner, nfsow_list) {
3966 				if (!NFSBCMP(lowp->nfsow_owner,
3967 				    owp->nfsow_owner, NFSV4CL_LOCKNAMELEN)) {
3968 					newnfs_copycred(&dp->nfsdl_cred, cred);
3969 					ret = nfscl_moveopen(vp, clp, nmp, lop,
3970 					    owp, dp, cred, p);
3971 					if (ret == NFSERR_STALECLIENTID ||
3972 					    ret == NFSERR_STALEDONTRECOVER ||
3973 					    ret == NFSERR_BADSESSION) {
3974 						if (gotvp)
3975 							vrele(vp);
3976 						return (ret);
3977 					}
3978 					if (ret) {
3979 						nfscl_freeopen(lop, 1);
3980 						if (!error)
3981 							error = ret;
3982 					}
3983 					break;
3984 				}
3985 			}
3986 
3987 			/*
3988 			 * If no openowner found, create one and get an open
3989 			 * for it.
3990 			 */
3991 			if (owp == NULL) {
3992 				nowp = malloc(
3993 				    sizeof (struct nfsclowner), M_NFSCLOWNER,
3994 				    M_WAITOK);
3995 				nfscl_newopen(clp, NULL, &owp, &nowp, &op,
3996 				    NULL, lowp->nfsow_owner, dp->nfsdl_fh,
3997 				    dp->nfsdl_fhlen, NULL, NULL);
3998 				newnfs_copycred(&dp->nfsdl_cred, cred);
3999 				ret = nfscl_moveopen(vp, clp, nmp, lop,
4000 				    owp, dp, cred, p);
4001 				if (ret) {
4002 					nfscl_freeopenowner(owp, 0);
4003 					if (ret == NFSERR_STALECLIENTID ||
4004 					    ret == NFSERR_STALEDONTRECOVER ||
4005 					    ret == NFSERR_BADSESSION) {
4006 						if (gotvp)
4007 							vrele(vp);
4008 						return (ret);
4009 					}
4010 					if (ret) {
4011 						nfscl_freeopen(lop, 1);
4012 						if (!error)
4013 							error = ret;
4014 					}
4015 				}
4016 			}
4017 		}
4018 	}
4019 
4020 	/*
4021 	 * Now, get byte range locks for any locks done locally.
4022 	 */
4023 	LIST_FOREACH(lp, &dp->nfsdl_lock, nfsl_list) {
4024 		LIST_FOREACH(lckp, &lp->nfsl_lock, nfslo_list) {
4025 			newnfs_copycred(&dp->nfsdl_cred, cred);
4026 			ret = nfscl_relock(vp, clp, nmp, lp, lckp, cred, p);
4027 			if (ret == NFSERR_STALESTATEID ||
4028 			    ret == NFSERR_STALEDONTRECOVER ||
4029 			    ret == NFSERR_STALECLIENTID ||
4030 			    ret == NFSERR_BADSESSION) {
4031 				if (gotvp)
4032 					vrele(vp);
4033 				return (ret);
4034 			}
4035 			if (ret && !error)
4036 				error = ret;
4037 		}
4038 	}
4039 	if (gotvp)
4040 		vrele(vp);
4041 	return (error);
4042 }
4043 
4044 /*
4045  * Move a locally issued open over to an owner on the state list.
4046  * SIDE EFFECT: If it needs to sleep (do an rpc), it unlocks clstate and
4047  * returns with it unlocked.
4048  */
4049 static int
4050 nfscl_moveopen(vnode_t vp, struct nfsclclient *clp, struct nfsmount *nmp,
4051     struct nfsclopen *lop, struct nfsclowner *owp, struct nfscldeleg *dp,
4052     struct ucred *cred, NFSPROC_T *p)
4053 {
4054 	struct nfsclopen *op, *nop;
4055 	struct nfscldeleg *ndp;
4056 	struct nfsnode *np;
4057 	int error = 0, newone;
4058 
4059 	/*
4060 	 * First, look for an appropriate open, If found, just increment the
4061 	 * opencnt in it.
4062 	 */
4063 	LIST_FOREACH(op, &owp->nfsow_open, nfso_list) {
4064 		if ((op->nfso_mode & lop->nfso_mode) == lop->nfso_mode &&
4065 		    op->nfso_fhlen == lop->nfso_fhlen &&
4066 		    !NFSBCMP(op->nfso_fh, lop->nfso_fh, op->nfso_fhlen)) {
4067 			op->nfso_opencnt += lop->nfso_opencnt;
4068 			nfscl_freeopen(lop, 1);
4069 			return (0);
4070 		}
4071 	}
4072 
4073 	/* No appropriate open, so we have to do one against the server. */
4074 	np = VTONFS(vp);
4075 	nop = malloc(sizeof (struct nfsclopen) +
4076 	    lop->nfso_fhlen - 1, M_NFSCLOPEN, M_WAITOK);
4077 	newone = 0;
4078 	nfscl_newopen(clp, NULL, &owp, NULL, &op, &nop, owp->nfsow_owner,
4079 	    lop->nfso_fh, lop->nfso_fhlen, cred, &newone);
4080 	ndp = dp;
4081 	error = nfscl_tryopen(nmp, vp, np->n_v4->n4_data, np->n_v4->n4_fhlen,
4082 	    lop->nfso_fh, lop->nfso_fhlen, lop->nfso_mode, op,
4083 	    NFS4NODENAME(np->n_v4), np->n_v4->n4_namelen, &ndp, 0, 0, cred, p);
4084 	if (error) {
4085 		if (newone)
4086 			nfscl_freeopen(op, 0);
4087 	} else {
4088 		op->nfso_mode |= lop->nfso_mode;
4089 		op->nfso_opencnt += lop->nfso_opencnt;
4090 		nfscl_freeopen(lop, 1);
4091 	}
4092 	if (nop != NULL)
4093 		free(nop, M_NFSCLOPEN);
4094 	if (ndp != NULL) {
4095 		/*
4096 		 * What should I do with the returned delegation, since the
4097 		 * delegation is being recalled? For now, just printf and
4098 		 * through it away.
4099 		 */
4100 		printf("Moveopen returned deleg\n");
4101 		free(ndp, M_NFSCLDELEG);
4102 	}
4103 	return (error);
4104 }
4105 
4106 /*
4107  * Recall all delegations on this client.
4108  */
4109 static void
4110 nfscl_totalrecall(struct nfsclclient *clp)
4111 {
4112 	struct nfscldeleg *dp;
4113 
4114 	TAILQ_FOREACH(dp, &clp->nfsc_deleg, nfsdl_list) {
4115 		if ((dp->nfsdl_flags & NFSCLDL_DELEGRET) == 0)
4116 			dp->nfsdl_flags |= NFSCLDL_RECALL;
4117 	}
4118 }
4119 
4120 /*
4121  * Relock byte ranges. Called for delegation recall and state expiry.
4122  */
4123 static int
4124 nfscl_relock(vnode_t vp, struct nfsclclient *clp, struct nfsmount *nmp,
4125     struct nfscllockowner *lp, struct nfscllock *lop, struct ucred *cred,
4126     NFSPROC_T *p)
4127 {
4128 	struct nfscllockowner *nlp;
4129 	struct nfsfh *nfhp;
4130 	u_int64_t off, len;
4131 	int error, newone, donelocally;
4132 
4133 	off = lop->nfslo_first;
4134 	len = lop->nfslo_end - lop->nfslo_first;
4135 	error = nfscl_getbytelock(vp, off, len, lop->nfslo_type, cred, p,
4136 	    clp, 1, NULL, lp->nfsl_lockflags, lp->nfsl_owner,
4137 	    lp->nfsl_openowner, &nlp, &newone, &donelocally);
4138 	if (error || donelocally)
4139 		return (error);
4140 	nfhp = VTONFS(vp)->n_fhp;
4141 	error = nfscl_trylock(nmp, vp, nfhp->nfh_fh,
4142 	    nfhp->nfh_len, nlp, newone, 0, off,
4143 	    len, lop->nfslo_type, cred, p);
4144 	if (error)
4145 		nfscl_freelockowner(nlp, 0);
4146 	return (error);
4147 }
4148 
4149 /*
4150  * Called to re-open a file. Basically get a vnode for the file handle
4151  * and then call nfsrpc_openrpc() to do the rest.
4152  */
4153 static int
4154 nfsrpc_reopen(struct nfsmount *nmp, u_int8_t *fhp, int fhlen,
4155     u_int32_t mode, struct nfsclopen *op, struct nfscldeleg **dpp,
4156     struct ucred *cred, NFSPROC_T *p)
4157 {
4158 	struct nfsnode *np;
4159 	vnode_t vp;
4160 	int error;
4161 
4162 	error = nfscl_ngetreopen(nmp->nm_mountp, fhp, fhlen, p, &np);
4163 	if (error)
4164 		return (error);
4165 	vp = NFSTOV(np);
4166 	if (np->n_v4 != NULL) {
4167 		error = nfscl_tryopen(nmp, vp, np->n_v4->n4_data,
4168 		    np->n_v4->n4_fhlen, fhp, fhlen, mode, op,
4169 		    NFS4NODENAME(np->n_v4), np->n_v4->n4_namelen, dpp, 0, 0,
4170 		    cred, p);
4171 	} else {
4172 		error = EINVAL;
4173 	}
4174 	vrele(vp);
4175 	return (error);
4176 }
4177 
4178 /*
4179  * Try an open against the server. Just call nfsrpc_openrpc(), retrying while
4180  * NFSERR_DELAY. Also, try system credentials, if the passed in credentials
4181  * fail.
4182  */
4183 static int
4184 nfscl_tryopen(struct nfsmount *nmp, vnode_t vp, u_int8_t *fhp, int fhlen,
4185     u_int8_t *newfhp, int newfhlen, u_int32_t mode, struct nfsclopen *op,
4186     u_int8_t *name, int namelen, struct nfscldeleg **ndpp,
4187     int reclaim, u_int32_t delegtype, struct ucred *cred, NFSPROC_T *p)
4188 {
4189 	int error;
4190 
4191 	do {
4192 		error = nfsrpc_openrpc(nmp, vp, fhp, fhlen, newfhp, newfhlen,
4193 		    mode, op, name, namelen, ndpp, reclaim, delegtype, cred, p,
4194 		    0, 0);
4195 		if (error == NFSERR_DELAY)
4196 			(void) nfs_catnap(PZERO, error, "nfstryop");
4197 	} while (error == NFSERR_DELAY);
4198 	if (error == EAUTH || error == EACCES) {
4199 		/* Try again using system credentials */
4200 		newnfs_setroot(cred);
4201 		do {
4202 		    error = nfsrpc_openrpc(nmp, vp, fhp, fhlen, newfhp,
4203 			newfhlen, mode, op, name, namelen, ndpp, reclaim,
4204 			delegtype, cred, p, 1, 0);
4205 		    if (error == NFSERR_DELAY)
4206 			(void) nfs_catnap(PZERO, error, "nfstryop");
4207 		} while (error == NFSERR_DELAY);
4208 	}
4209 	return (error);
4210 }
4211 
4212 /*
4213  * Try a byte range lock. Just loop on nfsrpc_lock() while it returns
4214  * NFSERR_DELAY. Also, retry with system credentials, if the provided
4215  * cred don't work.
4216  */
4217 static int
4218 nfscl_trylock(struct nfsmount *nmp, vnode_t vp, u_int8_t *fhp,
4219     int fhlen, struct nfscllockowner *nlp, int newone, int reclaim,
4220     u_int64_t off, u_int64_t len, short type, struct ucred *cred, NFSPROC_T *p)
4221 {
4222 	struct nfsrv_descript nfsd, *nd = &nfsd;
4223 	int error;
4224 
4225 	do {
4226 		error = nfsrpc_lock(nd, nmp, vp, fhp, fhlen, nlp, newone,
4227 		    reclaim, off, len, type, cred, p, 0);
4228 		if (!error && nd->nd_repstat == NFSERR_DELAY)
4229 			(void) nfs_catnap(PZERO, (int)nd->nd_repstat,
4230 			    "nfstrylck");
4231 	} while (!error && nd->nd_repstat == NFSERR_DELAY);
4232 	if (!error)
4233 		error = nd->nd_repstat;
4234 	if (error == EAUTH || error == EACCES) {
4235 		/* Try again using root credentials */
4236 		newnfs_setroot(cred);
4237 		do {
4238 			error = nfsrpc_lock(nd, nmp, vp, fhp, fhlen, nlp,
4239 			    newone, reclaim, off, len, type, cred, p, 1);
4240 			if (!error && nd->nd_repstat == NFSERR_DELAY)
4241 				(void) nfs_catnap(PZERO, (int)nd->nd_repstat,
4242 				    "nfstrylck");
4243 		} while (!error && nd->nd_repstat == NFSERR_DELAY);
4244 		if (!error)
4245 			error = nd->nd_repstat;
4246 	}
4247 	return (error);
4248 }
4249 
4250 /*
4251  * Try a delegreturn against the server. Just call nfsrpc_delegreturn(),
4252  * retrying while NFSERR_DELAY. Also, try system credentials, if the passed in
4253  * credentials fail.
4254  */
4255 static int
4256 nfscl_trydelegreturn(struct nfscldeleg *dp, struct ucred *cred,
4257     struct nfsmount *nmp, NFSPROC_T *p)
4258 {
4259 	int error;
4260 
4261 	do {
4262 		error = nfsrpc_delegreturn(dp, cred, nmp, p, 0);
4263 		if (error == NFSERR_DELAY)
4264 			(void) nfs_catnap(PZERO, error, "nfstrydp");
4265 	} while (error == NFSERR_DELAY);
4266 	if (error == EAUTH || error == EACCES) {
4267 		/* Try again using system credentials */
4268 		newnfs_setroot(cred);
4269 		do {
4270 			error = nfsrpc_delegreturn(dp, cred, nmp, p, 1);
4271 			if (error == NFSERR_DELAY)
4272 				(void) nfs_catnap(PZERO, error, "nfstrydp");
4273 		} while (error == NFSERR_DELAY);
4274 	}
4275 	return (error);
4276 }
4277 
4278 /*
4279  * Try a close against the server. Just call nfsrpc_closerpc(),
4280  * retrying while NFSERR_DELAY. Also, try system credentials, if the passed in
4281  * credentials fail.
4282  */
4283 APPLESTATIC int
4284 nfscl_tryclose(struct nfsclopen *op, struct ucred *cred,
4285     struct nfsmount *nmp, NFSPROC_T *p)
4286 {
4287 	struct nfsrv_descript nfsd, *nd = &nfsd;
4288 	int error;
4289 
4290 	do {
4291 		error = nfsrpc_closerpc(nd, nmp, op, cred, p, 0);
4292 		if (error == NFSERR_DELAY)
4293 			(void) nfs_catnap(PZERO, error, "nfstrycl");
4294 	} while (error == NFSERR_DELAY);
4295 	if (error == EAUTH || error == EACCES) {
4296 		/* Try again using system credentials */
4297 		newnfs_setroot(cred);
4298 		do {
4299 			error = nfsrpc_closerpc(nd, nmp, op, cred, p, 1);
4300 			if (error == NFSERR_DELAY)
4301 				(void) nfs_catnap(PZERO, error, "nfstrycl");
4302 		} while (error == NFSERR_DELAY);
4303 	}
4304 	return (error);
4305 }
4306 
4307 /*
4308  * Decide if a delegation on a file permits close without flushing writes
4309  * to the server. This might be a big performance win in some environments.
4310  * (Not useful until the client does caching on local stable storage.)
4311  */
4312 APPLESTATIC int
4313 nfscl_mustflush(vnode_t vp)
4314 {
4315 	struct nfsclclient *clp;
4316 	struct nfscldeleg *dp;
4317 	struct nfsnode *np;
4318 	struct nfsmount *nmp;
4319 
4320 	np = VTONFS(vp);
4321 	nmp = VFSTONFS(vnode_mount(vp));
4322 	if (!NFSHASNFSV4(nmp))
4323 		return (1);
4324 	NFSLOCKCLSTATE();
4325 	clp = nfscl_findcl(nmp);
4326 	if (clp == NULL) {
4327 		NFSUNLOCKCLSTATE();
4328 		return (1);
4329 	}
4330 	dp = nfscl_finddeleg(clp, np->n_fhp->nfh_fh, np->n_fhp->nfh_len);
4331 	if (dp != NULL && (dp->nfsdl_flags &
4332 	    (NFSCLDL_WRITE | NFSCLDL_RECALL | NFSCLDL_DELEGRET)) ==
4333 	     NFSCLDL_WRITE &&
4334 	    (dp->nfsdl_sizelimit >= np->n_size ||
4335 	     !NFSHASSTRICT3530(nmp))) {
4336 		NFSUNLOCKCLSTATE();
4337 		return (0);
4338 	}
4339 	NFSUNLOCKCLSTATE();
4340 	return (1);
4341 }
4342 
4343 /*
4344  * See if a (write) delegation exists for this file.
4345  */
4346 APPLESTATIC int
4347 nfscl_nodeleg(vnode_t vp, int writedeleg)
4348 {
4349 	struct nfsclclient *clp;
4350 	struct nfscldeleg *dp;
4351 	struct nfsnode *np;
4352 	struct nfsmount *nmp;
4353 
4354 	np = VTONFS(vp);
4355 	nmp = VFSTONFS(vnode_mount(vp));
4356 	if (!NFSHASNFSV4(nmp))
4357 		return (1);
4358 	NFSLOCKCLSTATE();
4359 	clp = nfscl_findcl(nmp);
4360 	if (clp == NULL) {
4361 		NFSUNLOCKCLSTATE();
4362 		return (1);
4363 	}
4364 	dp = nfscl_finddeleg(clp, np->n_fhp->nfh_fh, np->n_fhp->nfh_len);
4365 	if (dp != NULL &&
4366 	    (dp->nfsdl_flags & (NFSCLDL_RECALL | NFSCLDL_DELEGRET)) == 0 &&
4367 	    (writedeleg == 0 || (dp->nfsdl_flags & NFSCLDL_WRITE) ==
4368 	     NFSCLDL_WRITE)) {
4369 		NFSUNLOCKCLSTATE();
4370 		return (0);
4371 	}
4372 	NFSUNLOCKCLSTATE();
4373 	return (1);
4374 }
4375 
4376 /*
4377  * Look for an associated delegation that should be DelegReturned.
4378  */
4379 APPLESTATIC int
4380 nfscl_removedeleg(vnode_t vp, NFSPROC_T *p, nfsv4stateid_t *stp)
4381 {
4382 	struct nfsclclient *clp;
4383 	struct nfscldeleg *dp;
4384 	struct nfsclowner *owp;
4385 	struct nfscllockowner *lp;
4386 	struct nfsmount *nmp;
4387 	struct ucred *cred;
4388 	struct nfsnode *np;
4389 	int igotlock = 0, triedrecall = 0, needsrecall, retcnt = 0, islept;
4390 
4391 	nmp = VFSTONFS(vnode_mount(vp));
4392 	np = VTONFS(vp);
4393 	NFSLOCKCLSTATE();
4394 	/*
4395 	 * Loop around waiting for:
4396 	 * - outstanding I/O operations on delegations to complete
4397 	 * - for a delegation on vp that has state, lock the client and
4398 	 *   do a recall
4399 	 * - return delegation with no state
4400 	 */
4401 	while (1) {
4402 		clp = nfscl_findcl(nmp);
4403 		if (clp == NULL) {
4404 			NFSUNLOCKCLSTATE();
4405 			return (retcnt);
4406 		}
4407 		dp = nfscl_finddeleg(clp, np->n_fhp->nfh_fh,
4408 		    np->n_fhp->nfh_len);
4409 		if (dp != NULL) {
4410 		    /*
4411 		     * Wait for outstanding I/O ops to be done.
4412 		     */
4413 		    if (dp->nfsdl_rwlock.nfslock_usecnt > 0) {
4414 			if (igotlock) {
4415 			    nfsv4_unlock(&clp->nfsc_lock, 0);
4416 			    igotlock = 0;
4417 			}
4418 			dp->nfsdl_rwlock.nfslock_lock |= NFSV4LOCK_WANTED;
4419 			(void) nfsmsleep(&dp->nfsdl_rwlock,
4420 			    NFSCLSTATEMUTEXPTR, PZERO, "nfscld", NULL);
4421 			continue;
4422 		    }
4423 		    needsrecall = 0;
4424 		    LIST_FOREACH(owp, &dp->nfsdl_owner, nfsow_list) {
4425 			if (!LIST_EMPTY(&owp->nfsow_open)) {
4426 			    needsrecall = 1;
4427 			    break;
4428 			}
4429 		    }
4430 		    if (!needsrecall) {
4431 			LIST_FOREACH(lp, &dp->nfsdl_lock, nfsl_list) {
4432 			    if (!LIST_EMPTY(&lp->nfsl_lock)) {
4433 				needsrecall = 1;
4434 				break;
4435 			    }
4436 			}
4437 		    }
4438 		    if (needsrecall && !triedrecall) {
4439 			dp->nfsdl_flags |= NFSCLDL_DELEGRET;
4440 			islept = 0;
4441 			while (!igotlock) {
4442 			    igotlock = nfsv4_lock(&clp->nfsc_lock, 1,
4443 				&islept, NFSCLSTATEMUTEXPTR, NULL);
4444 			    if (islept)
4445 				break;
4446 			}
4447 			if (islept)
4448 			    continue;
4449 			NFSUNLOCKCLSTATE();
4450 			cred = newnfs_getcred();
4451 			newnfs_copycred(&dp->nfsdl_cred, cred);
4452 			(void) nfscl_recalldeleg(clp, nmp, dp, vp, cred, p, 0);
4453 			NFSFREECRED(cred);
4454 			triedrecall = 1;
4455 			NFSLOCKCLSTATE();
4456 			nfsv4_unlock(&clp->nfsc_lock, 0);
4457 			igotlock = 0;
4458 			continue;
4459 		    }
4460 		    *stp = dp->nfsdl_stateid;
4461 		    retcnt = 1;
4462 		    nfscl_cleandeleg(dp);
4463 		    nfscl_freedeleg(&clp->nfsc_deleg, dp);
4464 		}
4465 		if (igotlock)
4466 		    nfsv4_unlock(&clp->nfsc_lock, 0);
4467 		NFSUNLOCKCLSTATE();
4468 		return (retcnt);
4469 	}
4470 }
4471 
4472 /*
4473  * Look for associated delegation(s) that should be DelegReturned.
4474  */
4475 APPLESTATIC int
4476 nfscl_renamedeleg(vnode_t fvp, nfsv4stateid_t *fstp, int *gotfdp, vnode_t tvp,
4477     nfsv4stateid_t *tstp, int *gottdp, NFSPROC_T *p)
4478 {
4479 	struct nfsclclient *clp;
4480 	struct nfscldeleg *dp;
4481 	struct nfsclowner *owp;
4482 	struct nfscllockowner *lp;
4483 	struct nfsmount *nmp;
4484 	struct ucred *cred;
4485 	struct nfsnode *np;
4486 	int igotlock = 0, triedrecall = 0, needsrecall, retcnt = 0, islept;
4487 
4488 	nmp = VFSTONFS(vnode_mount(fvp));
4489 	*gotfdp = 0;
4490 	*gottdp = 0;
4491 	NFSLOCKCLSTATE();
4492 	/*
4493 	 * Loop around waiting for:
4494 	 * - outstanding I/O operations on delegations to complete
4495 	 * - for a delegation on fvp that has state, lock the client and
4496 	 *   do a recall
4497 	 * - return delegation(s) with no state.
4498 	 */
4499 	while (1) {
4500 		clp = nfscl_findcl(nmp);
4501 		if (clp == NULL) {
4502 			NFSUNLOCKCLSTATE();
4503 			return (retcnt);
4504 		}
4505 		np = VTONFS(fvp);
4506 		dp = nfscl_finddeleg(clp, np->n_fhp->nfh_fh,
4507 		    np->n_fhp->nfh_len);
4508 		if (dp != NULL && *gotfdp == 0) {
4509 		    /*
4510 		     * Wait for outstanding I/O ops to be done.
4511 		     */
4512 		    if (dp->nfsdl_rwlock.nfslock_usecnt > 0) {
4513 			if (igotlock) {
4514 			    nfsv4_unlock(&clp->nfsc_lock, 0);
4515 			    igotlock = 0;
4516 			}
4517 			dp->nfsdl_rwlock.nfslock_lock |= NFSV4LOCK_WANTED;
4518 			(void) nfsmsleep(&dp->nfsdl_rwlock,
4519 			    NFSCLSTATEMUTEXPTR, PZERO, "nfscld", NULL);
4520 			continue;
4521 		    }
4522 		    needsrecall = 0;
4523 		    LIST_FOREACH(owp, &dp->nfsdl_owner, nfsow_list) {
4524 			if (!LIST_EMPTY(&owp->nfsow_open)) {
4525 			    needsrecall = 1;
4526 			    break;
4527 			}
4528 		    }
4529 		    if (!needsrecall) {
4530 			LIST_FOREACH(lp, &dp->nfsdl_lock, nfsl_list) {
4531 			    if (!LIST_EMPTY(&lp->nfsl_lock)) {
4532 				needsrecall = 1;
4533 				break;
4534 			    }
4535 			}
4536 		    }
4537 		    if (needsrecall && !triedrecall) {
4538 			dp->nfsdl_flags |= NFSCLDL_DELEGRET;
4539 			islept = 0;
4540 			while (!igotlock) {
4541 			    igotlock = nfsv4_lock(&clp->nfsc_lock, 1,
4542 				&islept, NFSCLSTATEMUTEXPTR, NULL);
4543 			    if (islept)
4544 				break;
4545 			}
4546 			if (islept)
4547 			    continue;
4548 			NFSUNLOCKCLSTATE();
4549 			cred = newnfs_getcred();
4550 			newnfs_copycred(&dp->nfsdl_cred, cred);
4551 			(void) nfscl_recalldeleg(clp, nmp, dp, fvp, cred, p, 0);
4552 			NFSFREECRED(cred);
4553 			triedrecall = 1;
4554 			NFSLOCKCLSTATE();
4555 			nfsv4_unlock(&clp->nfsc_lock, 0);
4556 			igotlock = 0;
4557 			continue;
4558 		    }
4559 		    *fstp = dp->nfsdl_stateid;
4560 		    retcnt++;
4561 		    *gotfdp = 1;
4562 		    nfscl_cleandeleg(dp);
4563 		    nfscl_freedeleg(&clp->nfsc_deleg, dp);
4564 		}
4565 		if (igotlock) {
4566 		    nfsv4_unlock(&clp->nfsc_lock, 0);
4567 		    igotlock = 0;
4568 		}
4569 		if (tvp != NULL) {
4570 		    np = VTONFS(tvp);
4571 		    dp = nfscl_finddeleg(clp, np->n_fhp->nfh_fh,
4572 			np->n_fhp->nfh_len);
4573 		    if (dp != NULL && *gottdp == 0) {
4574 			/*
4575 			 * Wait for outstanding I/O ops to be done.
4576 			 */
4577 			if (dp->nfsdl_rwlock.nfslock_usecnt > 0) {
4578 			    dp->nfsdl_rwlock.nfslock_lock |= NFSV4LOCK_WANTED;
4579 			    (void) nfsmsleep(&dp->nfsdl_rwlock,
4580 				NFSCLSTATEMUTEXPTR, PZERO, "nfscld", NULL);
4581 			    continue;
4582 			}
4583 			LIST_FOREACH(owp, &dp->nfsdl_owner, nfsow_list) {
4584 			    if (!LIST_EMPTY(&owp->nfsow_open)) {
4585 				NFSUNLOCKCLSTATE();
4586 				return (retcnt);
4587 			    }
4588 			}
4589 			LIST_FOREACH(lp, &dp->nfsdl_lock, nfsl_list) {
4590 			    if (!LIST_EMPTY(&lp->nfsl_lock)) {
4591 				NFSUNLOCKCLSTATE();
4592 				return (retcnt);
4593 			    }
4594 			}
4595 			*tstp = dp->nfsdl_stateid;
4596 			retcnt++;
4597 			*gottdp = 1;
4598 			nfscl_cleandeleg(dp);
4599 			nfscl_freedeleg(&clp->nfsc_deleg, dp);
4600 		    }
4601 		}
4602 		NFSUNLOCKCLSTATE();
4603 		return (retcnt);
4604 	}
4605 }
4606 
4607 /*
4608  * Get a reference on the clientid associated with the mount point.
4609  * Return 1 if success, 0 otherwise.
4610  */
4611 APPLESTATIC int
4612 nfscl_getref(struct nfsmount *nmp)
4613 {
4614 	struct nfsclclient *clp;
4615 
4616 	NFSLOCKCLSTATE();
4617 	clp = nfscl_findcl(nmp);
4618 	if (clp == NULL) {
4619 		NFSUNLOCKCLSTATE();
4620 		return (0);
4621 	}
4622 	nfsv4_getref(&clp->nfsc_lock, NULL, NFSCLSTATEMUTEXPTR, NULL);
4623 	NFSUNLOCKCLSTATE();
4624 	return (1);
4625 }
4626 
4627 /*
4628  * Release a reference on a clientid acquired with the above call.
4629  */
4630 APPLESTATIC void
4631 nfscl_relref(struct nfsmount *nmp)
4632 {
4633 	struct nfsclclient *clp;
4634 
4635 	NFSLOCKCLSTATE();
4636 	clp = nfscl_findcl(nmp);
4637 	if (clp == NULL) {
4638 		NFSUNLOCKCLSTATE();
4639 		return;
4640 	}
4641 	nfsv4_relref(&clp->nfsc_lock);
4642 	NFSUNLOCKCLSTATE();
4643 }
4644 
4645 /*
4646  * Save the size attribute in the delegation, since the nfsnode
4647  * is going away.
4648  */
4649 APPLESTATIC void
4650 nfscl_reclaimnode(vnode_t vp)
4651 {
4652 	struct nfsclclient *clp;
4653 	struct nfscldeleg *dp;
4654 	struct nfsnode *np = VTONFS(vp);
4655 	struct nfsmount *nmp;
4656 
4657 	nmp = VFSTONFS(vnode_mount(vp));
4658 	if (!NFSHASNFSV4(nmp))
4659 		return;
4660 	NFSLOCKCLSTATE();
4661 	clp = nfscl_findcl(nmp);
4662 	if (clp == NULL) {
4663 		NFSUNLOCKCLSTATE();
4664 		return;
4665 	}
4666 	dp = nfscl_finddeleg(clp, np->n_fhp->nfh_fh, np->n_fhp->nfh_len);
4667 	if (dp != NULL && (dp->nfsdl_flags & NFSCLDL_WRITE))
4668 		dp->nfsdl_size = np->n_size;
4669 	NFSUNLOCKCLSTATE();
4670 }
4671 
4672 /*
4673  * Get the saved size attribute in the delegation, since it is a
4674  * newly allocated nfsnode.
4675  */
4676 APPLESTATIC void
4677 nfscl_newnode(vnode_t vp)
4678 {
4679 	struct nfsclclient *clp;
4680 	struct nfscldeleg *dp;
4681 	struct nfsnode *np = VTONFS(vp);
4682 	struct nfsmount *nmp;
4683 
4684 	nmp = VFSTONFS(vnode_mount(vp));
4685 	if (!NFSHASNFSV4(nmp))
4686 		return;
4687 	NFSLOCKCLSTATE();
4688 	clp = nfscl_findcl(nmp);
4689 	if (clp == NULL) {
4690 		NFSUNLOCKCLSTATE();
4691 		return;
4692 	}
4693 	dp = nfscl_finddeleg(clp, np->n_fhp->nfh_fh, np->n_fhp->nfh_len);
4694 	if (dp != NULL && (dp->nfsdl_flags & NFSCLDL_WRITE))
4695 		np->n_size = dp->nfsdl_size;
4696 	NFSUNLOCKCLSTATE();
4697 }
4698 
4699 /*
4700  * If there is a valid write delegation for this file, set the modtime
4701  * to the local clock time.
4702  */
4703 APPLESTATIC void
4704 nfscl_delegmodtime(vnode_t vp)
4705 {
4706 	struct nfsclclient *clp;
4707 	struct nfscldeleg *dp;
4708 	struct nfsnode *np = VTONFS(vp);
4709 	struct nfsmount *nmp;
4710 
4711 	nmp = VFSTONFS(vnode_mount(vp));
4712 	if (!NFSHASNFSV4(nmp))
4713 		return;
4714 	NFSLOCKCLSTATE();
4715 	clp = nfscl_findcl(nmp);
4716 	if (clp == NULL) {
4717 		NFSUNLOCKCLSTATE();
4718 		return;
4719 	}
4720 	dp = nfscl_finddeleg(clp, np->n_fhp->nfh_fh, np->n_fhp->nfh_len);
4721 	if (dp != NULL && (dp->nfsdl_flags & NFSCLDL_WRITE)) {
4722 		nanotime(&dp->nfsdl_modtime);
4723 		dp->nfsdl_flags |= NFSCLDL_MODTIMESET;
4724 	}
4725 	NFSUNLOCKCLSTATE();
4726 }
4727 
4728 /*
4729  * If there is a valid write delegation for this file with a modtime set,
4730  * put that modtime in mtime.
4731  */
4732 APPLESTATIC void
4733 nfscl_deleggetmodtime(vnode_t vp, struct timespec *mtime)
4734 {
4735 	struct nfsclclient *clp;
4736 	struct nfscldeleg *dp;
4737 	struct nfsnode *np = VTONFS(vp);
4738 	struct nfsmount *nmp;
4739 
4740 	nmp = VFSTONFS(vnode_mount(vp));
4741 	if (!NFSHASNFSV4(nmp))
4742 		return;
4743 	NFSLOCKCLSTATE();
4744 	clp = nfscl_findcl(nmp);
4745 	if (clp == NULL) {
4746 		NFSUNLOCKCLSTATE();
4747 		return;
4748 	}
4749 	dp = nfscl_finddeleg(clp, np->n_fhp->nfh_fh, np->n_fhp->nfh_len);
4750 	if (dp != NULL &&
4751 	    (dp->nfsdl_flags & (NFSCLDL_WRITE | NFSCLDL_MODTIMESET)) ==
4752 	    (NFSCLDL_WRITE | NFSCLDL_MODTIMESET))
4753 		*mtime = dp->nfsdl_modtime;
4754 	NFSUNLOCKCLSTATE();
4755 }
4756 
4757 static int
4758 nfscl_errmap(struct nfsrv_descript *nd, u_int32_t minorvers)
4759 {
4760 	short *defaulterrp, *errp;
4761 
4762 	if (!nd->nd_repstat)
4763 		return (0);
4764 	if (nd->nd_procnum == NFSPROC_NOOP)
4765 		return (txdr_unsigned(nd->nd_repstat & 0xffff));
4766 	if (nd->nd_repstat == EBADRPC)
4767 		return (txdr_unsigned(NFSERR_BADXDR));
4768 	if (nd->nd_repstat == NFSERR_MINORVERMISMATCH ||
4769 	    nd->nd_repstat == NFSERR_OPILLEGAL)
4770 		return (txdr_unsigned(nd->nd_repstat));
4771 	if (nd->nd_repstat >= NFSERR_BADIOMODE && nd->nd_repstat < 20000 &&
4772 	    minorvers > NFSV4_MINORVERSION) {
4773 		/* NFSv4.n error. */
4774 		return (txdr_unsigned(nd->nd_repstat));
4775 	}
4776 	if (nd->nd_procnum < NFSV4OP_CBNOPS)
4777 		errp = defaulterrp = nfscl_cberrmap[nd->nd_procnum];
4778 	else
4779 		return (txdr_unsigned(nd->nd_repstat));
4780 	while (*++errp)
4781 		if (*errp == (short)nd->nd_repstat)
4782 			return (txdr_unsigned(nd->nd_repstat));
4783 	return (txdr_unsigned(*defaulterrp));
4784 }
4785 
4786 /*
4787  * Called to find/add a layout to a client.
4788  * This function returns the layout with a refcnt (shared lock) upon
4789  * success (returns 0) or with no lock/refcnt on the layout when an
4790  * error is returned.
4791  * If a layout is passed in via lypp, it is locked (exclusively locked).
4792  */
4793 APPLESTATIC int
4794 nfscl_layout(struct nfsmount *nmp, vnode_t vp, u_int8_t *fhp, int fhlen,
4795     nfsv4stateid_t *stateidp, int layouttype, int retonclose,
4796     struct nfsclflayouthead *fhlp, struct nfscllayout **lypp,
4797     struct ucred *cred, NFSPROC_T *p)
4798 {
4799 	struct nfsclclient *clp;
4800 	struct nfscllayout *lyp, *tlyp;
4801 	struct nfsclflayout *flp;
4802 	struct nfsnode *np = VTONFS(vp);
4803 	mount_t mp;
4804 	int layout_passed_in;
4805 
4806 	mp = nmp->nm_mountp;
4807 	layout_passed_in = 1;
4808 	tlyp = NULL;
4809 	lyp = *lypp;
4810 	if (lyp == NULL) {
4811 		layout_passed_in = 0;
4812 		tlyp = malloc(sizeof(*tlyp) + fhlen - 1, M_NFSLAYOUT,
4813 		    M_WAITOK | M_ZERO);
4814 	}
4815 
4816 	NFSLOCKCLSTATE();
4817 	clp = nmp->nm_clp;
4818 	if (clp == NULL) {
4819 		if (layout_passed_in != 0)
4820 			nfsv4_unlock(&lyp->nfsly_lock, 0);
4821 		NFSUNLOCKCLSTATE();
4822 		if (tlyp != NULL)
4823 			free(tlyp, M_NFSLAYOUT);
4824 		return (EPERM);
4825 	}
4826 	if (lyp == NULL) {
4827 		/*
4828 		 * Although no lyp was passed in, another thread might have
4829 		 * allocated one. If one is found, just increment it's ref
4830 		 * count and return it.
4831 		 */
4832 		lyp = nfscl_findlayout(clp, fhp, fhlen);
4833 		if (lyp == NULL) {
4834 			lyp = tlyp;
4835 			tlyp = NULL;
4836 			lyp->nfsly_stateid.seqid = stateidp->seqid;
4837 			lyp->nfsly_stateid.other[0] = stateidp->other[0];
4838 			lyp->nfsly_stateid.other[1] = stateidp->other[1];
4839 			lyp->nfsly_stateid.other[2] = stateidp->other[2];
4840 			lyp->nfsly_lastbyte = 0;
4841 			LIST_INIT(&lyp->nfsly_flayread);
4842 			LIST_INIT(&lyp->nfsly_flayrw);
4843 			LIST_INIT(&lyp->nfsly_recall);
4844 			lyp->nfsly_filesid[0] = np->n_vattr.na_filesid[0];
4845 			lyp->nfsly_filesid[1] = np->n_vattr.na_filesid[1];
4846 			lyp->nfsly_clp = clp;
4847 			if (layouttype == NFSLAYOUT_FLEXFILE)
4848 				lyp->nfsly_flags = NFSLY_FLEXFILE;
4849 			else
4850 				lyp->nfsly_flags = NFSLY_FILES;
4851 			if (retonclose != 0)
4852 				lyp->nfsly_flags |= NFSLY_RETONCLOSE;
4853 			lyp->nfsly_fhlen = fhlen;
4854 			NFSBCOPY(fhp, lyp->nfsly_fh, fhlen);
4855 			TAILQ_INSERT_HEAD(&clp->nfsc_layout, lyp, nfsly_list);
4856 			LIST_INSERT_HEAD(NFSCLLAYOUTHASH(clp, fhp, fhlen), lyp,
4857 			    nfsly_hash);
4858 			lyp->nfsly_timestamp = NFSD_MONOSEC + 120;
4859 			nfscl_layoutcnt++;
4860 		} else {
4861 			if (retonclose != 0)
4862 				lyp->nfsly_flags |= NFSLY_RETONCLOSE;
4863 			TAILQ_REMOVE(&clp->nfsc_layout, lyp, nfsly_list);
4864 			TAILQ_INSERT_HEAD(&clp->nfsc_layout, lyp, nfsly_list);
4865 			lyp->nfsly_timestamp = NFSD_MONOSEC + 120;
4866 		}
4867 		nfsv4_getref(&lyp->nfsly_lock, NULL, NFSCLSTATEMUTEXPTR, mp);
4868 		if (NFSCL_FORCEDISM(mp)) {
4869 			NFSUNLOCKCLSTATE();
4870 			if (tlyp != NULL)
4871 				free(tlyp, M_NFSLAYOUT);
4872 			return (EPERM);
4873 		}
4874 		*lypp = lyp;
4875 	} else
4876 		lyp->nfsly_stateid.seqid = stateidp->seqid;
4877 
4878 	/* Merge the new list of File Layouts into the list. */
4879 	flp = LIST_FIRST(fhlp);
4880 	if (flp != NULL) {
4881 		if (flp->nfsfl_iomode == NFSLAYOUTIOMODE_READ)
4882 			nfscl_mergeflayouts(&lyp->nfsly_flayread, fhlp);
4883 		else
4884 			nfscl_mergeflayouts(&lyp->nfsly_flayrw, fhlp);
4885 	}
4886 	if (layout_passed_in != 0)
4887 		nfsv4_unlock(&lyp->nfsly_lock, 1);
4888 	NFSUNLOCKCLSTATE();
4889 	if (tlyp != NULL)
4890 		free(tlyp, M_NFSLAYOUT);
4891 	return (0);
4892 }
4893 
4894 /*
4895  * Search for a layout by MDS file handle.
4896  * If one is found, it is returned with a refcnt (shared lock) iff
4897  * retflpp returned non-NULL and locked (exclusive locked) iff retflpp is
4898  * returned NULL.
4899  */
4900 struct nfscllayout *
4901 nfscl_getlayout(struct nfsclclient *clp, uint8_t *fhp, int fhlen,
4902     uint64_t off, struct nfsclflayout **retflpp, int *recalledp)
4903 {
4904 	struct nfscllayout *lyp;
4905 	mount_t mp;
4906 	int error, igotlock;
4907 
4908 	mp = clp->nfsc_nmp->nm_mountp;
4909 	*recalledp = 0;
4910 	*retflpp = NULL;
4911 	NFSLOCKCLSTATE();
4912 	lyp = nfscl_findlayout(clp, fhp, fhlen);
4913 	if (lyp != NULL) {
4914 		if ((lyp->nfsly_flags & NFSLY_RECALL) == 0) {
4915 			TAILQ_REMOVE(&clp->nfsc_layout, lyp, nfsly_list);
4916 			TAILQ_INSERT_HEAD(&clp->nfsc_layout, lyp, nfsly_list);
4917 			lyp->nfsly_timestamp = NFSD_MONOSEC + 120;
4918 			error = nfscl_findlayoutforio(lyp, off,
4919 			    NFSV4OPEN_ACCESSREAD, retflpp);
4920 			if (error == 0)
4921 				nfsv4_getref(&lyp->nfsly_lock, NULL,
4922 				    NFSCLSTATEMUTEXPTR, mp);
4923 			else {
4924 				do {
4925 					igotlock = nfsv4_lock(&lyp->nfsly_lock,
4926 					    1, NULL, NFSCLSTATEMUTEXPTR, mp);
4927 				} while (igotlock == 0 && !NFSCL_FORCEDISM(mp));
4928 				*retflpp = NULL;
4929 			}
4930 			if (NFSCL_FORCEDISM(mp)) {
4931 				lyp = NULL;
4932 				*recalledp = 1;
4933 			}
4934 		} else {
4935 			lyp = NULL;
4936 			*recalledp = 1;
4937 		}
4938 	}
4939 	NFSUNLOCKCLSTATE();
4940 	return (lyp);
4941 }
4942 
4943 /*
4944  * Search for a layout by MDS file handle. If one is found, mark in to be
4945  * recalled, if it already marked "return on close".
4946  */
4947 static void
4948 nfscl_retoncloselayout(vnode_t vp, struct nfsclclient *clp, uint8_t *fhp,
4949     int fhlen, struct nfsclrecalllayout **recallpp)
4950 {
4951 	struct nfscllayout *lyp;
4952 	uint32_t iomode;
4953 
4954 	if (vp->v_type != VREG || !NFSHASPNFS(VFSTONFS(vnode_mount(vp))) ||
4955 	    nfscl_enablecallb == 0 || nfs_numnfscbd == 0 ||
4956 	    (VTONFS(vp)->n_flag & NNOLAYOUT) != 0)
4957 		return;
4958 	lyp = nfscl_findlayout(clp, fhp, fhlen);
4959 	if (lyp != NULL && (lyp->nfsly_flags & (NFSLY_RETONCLOSE |
4960 	    NFSLY_RECALL)) == NFSLY_RETONCLOSE) {
4961 		iomode = 0;
4962 		if (!LIST_EMPTY(&lyp->nfsly_flayread))
4963 			iomode |= NFSLAYOUTIOMODE_READ;
4964 		if (!LIST_EMPTY(&lyp->nfsly_flayrw))
4965 			iomode |= NFSLAYOUTIOMODE_RW;
4966 		(void)nfscl_layoutrecall(NFSLAYOUTRETURN_FILE, lyp, iomode,
4967 		    0, UINT64_MAX, lyp->nfsly_stateid.seqid, 0, 0, NULL,
4968 		    *recallpp);
4969 		NFSCL_DEBUG(4, "retoncls recall iomode=%d\n", iomode);
4970 		*recallpp = NULL;
4971 	}
4972 }
4973 
4974 /*
4975  * Mark the layout to be recalled and with an error.
4976  * Also, disable the dsp from further use.
4977  */
4978 void
4979 nfscl_dserr(uint32_t op, uint32_t stat, struct nfscldevinfo *dp,
4980     struct nfscllayout *lyp, struct nfsclds *dsp)
4981 {
4982 	struct nfsclrecalllayout *recallp;
4983 	uint32_t iomode;
4984 
4985 	printf("DS being disabled, error=%d\n", stat);
4986 	/* Set up the return of the layout. */
4987 	recallp = malloc(sizeof(*recallp), M_NFSLAYRECALL, M_WAITOK);
4988 	iomode = 0;
4989 	NFSLOCKCLSTATE();
4990 	if ((lyp->nfsly_flags & NFSLY_RECALL) == 0) {
4991 		if (!LIST_EMPTY(&lyp->nfsly_flayread))
4992 			iomode |= NFSLAYOUTIOMODE_READ;
4993 		if (!LIST_EMPTY(&lyp->nfsly_flayrw))
4994 			iomode |= NFSLAYOUTIOMODE_RW;
4995 		(void)nfscl_layoutrecall(NFSLAYOUTRETURN_FILE, lyp, iomode,
4996 		    0, UINT64_MAX, lyp->nfsly_stateid.seqid, stat, op,
4997 		    dp->nfsdi_deviceid, recallp);
4998 		NFSUNLOCKCLSTATE();
4999 		NFSCL_DEBUG(4, "nfscl_dserr recall iomode=%d\n", iomode);
5000 	} else {
5001 		NFSUNLOCKCLSTATE();
5002 		free(recallp, M_NFSLAYRECALL);
5003 	}
5004 
5005 	/* And shut the TCP connection down. */
5006 	nfscl_cancelreqs(dsp);
5007 }
5008 
5009 /*
5010  * Cancel all RPCs for this "dsp" by closing the connection.
5011  * Also, mark the session as defunct.
5012  * If NFSCLDS_SAMECONN is set, the connection is shared with other DSs and
5013  * cannot be shut down.
5014  */
5015 APPLESTATIC void
5016 nfscl_cancelreqs(struct nfsclds *dsp)
5017 {
5018 	struct __rpc_client *cl;
5019 	static int non_event;
5020 
5021 	NFSLOCKDS(dsp);
5022 	if ((dsp->nfsclds_flags & (NFSCLDS_CLOSED | NFSCLDS_SAMECONN)) == 0 &&
5023 	    dsp->nfsclds_sockp != NULL &&
5024 	    dsp->nfsclds_sockp->nr_client != NULL) {
5025 		dsp->nfsclds_flags |= NFSCLDS_CLOSED;
5026 		cl = dsp->nfsclds_sockp->nr_client;
5027 		dsp->nfsclds_sess.nfsess_defunct = 1;
5028 		NFSUNLOCKDS(dsp);
5029 		CLNT_CLOSE(cl);
5030 		/*
5031 		 * This 1sec sleep is done to reduce the number of reconnect
5032 		 * attempts made on the DS while it has failed.
5033 		 */
5034 		tsleep(&non_event, PVFS, "ndscls", hz);
5035 		return;
5036 	}
5037 	NFSUNLOCKDS(dsp);
5038 }
5039 
5040 /*
5041  * Dereference a layout.
5042  */
5043 void
5044 nfscl_rellayout(struct nfscllayout *lyp, int exclocked)
5045 {
5046 
5047 	NFSLOCKCLSTATE();
5048 	if (exclocked != 0)
5049 		nfsv4_unlock(&lyp->nfsly_lock, 0);
5050 	else
5051 		nfsv4_relref(&lyp->nfsly_lock);
5052 	NFSUNLOCKCLSTATE();
5053 }
5054 
5055 /*
5056  * Search for a devinfo by deviceid. If one is found, return it after
5057  * acquiring a reference count on it.
5058  */
5059 struct nfscldevinfo *
5060 nfscl_getdevinfo(struct nfsclclient *clp, uint8_t *deviceid,
5061     struct nfscldevinfo *dip)
5062 {
5063 
5064 	NFSLOCKCLSTATE();
5065 	if (dip == NULL)
5066 		dip = nfscl_finddevinfo(clp, deviceid);
5067 	if (dip != NULL)
5068 		dip->nfsdi_refcnt++;
5069 	NFSUNLOCKCLSTATE();
5070 	return (dip);
5071 }
5072 
5073 /*
5074  * Dereference a devinfo structure.
5075  */
5076 static void
5077 nfscl_reldevinfo_locked(struct nfscldevinfo *dip)
5078 {
5079 
5080 	dip->nfsdi_refcnt--;
5081 	if (dip->nfsdi_refcnt == 0)
5082 		wakeup(&dip->nfsdi_refcnt);
5083 }
5084 
5085 /*
5086  * Dereference a devinfo structure.
5087  */
5088 void
5089 nfscl_reldevinfo(struct nfscldevinfo *dip)
5090 {
5091 
5092 	NFSLOCKCLSTATE();
5093 	nfscl_reldevinfo_locked(dip);
5094 	NFSUNLOCKCLSTATE();
5095 }
5096 
5097 /*
5098  * Find a layout for this file handle. Return NULL upon failure.
5099  */
5100 static struct nfscllayout *
5101 nfscl_findlayout(struct nfsclclient *clp, u_int8_t *fhp, int fhlen)
5102 {
5103 	struct nfscllayout *lyp;
5104 
5105 	LIST_FOREACH(lyp, NFSCLLAYOUTHASH(clp, fhp, fhlen), nfsly_hash)
5106 		if (lyp->nfsly_fhlen == fhlen &&
5107 		    !NFSBCMP(lyp->nfsly_fh, fhp, fhlen))
5108 			break;
5109 	return (lyp);
5110 }
5111 
5112 /*
5113  * Find a devinfo for this deviceid. Return NULL upon failure.
5114  */
5115 static struct nfscldevinfo *
5116 nfscl_finddevinfo(struct nfsclclient *clp, uint8_t *deviceid)
5117 {
5118 	struct nfscldevinfo *dip;
5119 
5120 	LIST_FOREACH(dip, &clp->nfsc_devinfo, nfsdi_list)
5121 		if (NFSBCMP(dip->nfsdi_deviceid, deviceid, NFSX_V4DEVICEID)
5122 		    == 0)
5123 			break;
5124 	return (dip);
5125 }
5126 
5127 /*
5128  * Merge the new file layout list into the main one, maintaining it in
5129  * increasing offset order.
5130  */
5131 static void
5132 nfscl_mergeflayouts(struct nfsclflayouthead *fhlp,
5133     struct nfsclflayouthead *newfhlp)
5134 {
5135 	struct nfsclflayout *flp, *nflp, *prevflp, *tflp;
5136 
5137 	flp = LIST_FIRST(fhlp);
5138 	prevflp = NULL;
5139 	LIST_FOREACH_SAFE(nflp, newfhlp, nfsfl_list, tflp) {
5140 		while (flp != NULL && flp->nfsfl_off < nflp->nfsfl_off) {
5141 			prevflp = flp;
5142 			flp = LIST_NEXT(flp, nfsfl_list);
5143 		}
5144 		if (prevflp == NULL)
5145 			LIST_INSERT_HEAD(fhlp, nflp, nfsfl_list);
5146 		else
5147 			LIST_INSERT_AFTER(prevflp, nflp, nfsfl_list);
5148 		prevflp = nflp;
5149 	}
5150 }
5151 
5152 /*
5153  * Add this nfscldevinfo to the client, if it doesn't already exist.
5154  * This function consumes the structure pointed at by dip, if not NULL.
5155  */
5156 APPLESTATIC int
5157 nfscl_adddevinfo(struct nfsmount *nmp, struct nfscldevinfo *dip, int ind,
5158     struct nfsclflayout *flp)
5159 {
5160 	struct nfsclclient *clp;
5161 	struct nfscldevinfo *tdip;
5162 	uint8_t *dev;
5163 
5164 	NFSLOCKCLSTATE();
5165 	clp = nmp->nm_clp;
5166 	if (clp == NULL) {
5167 		NFSUNLOCKCLSTATE();
5168 		if (dip != NULL)
5169 			free(dip, M_NFSDEVINFO);
5170 		return (ENODEV);
5171 	}
5172 	if ((flp->nfsfl_flags & NFSFL_FILE) != 0)
5173 		dev = flp->nfsfl_dev;
5174 	else
5175 		dev = flp->nfsfl_ffm[ind].dev;
5176 	tdip = nfscl_finddevinfo(clp, dev);
5177 	if (tdip != NULL) {
5178 		tdip->nfsdi_layoutrefs++;
5179 		if ((flp->nfsfl_flags & NFSFL_FILE) != 0)
5180 			flp->nfsfl_devp = tdip;
5181 		else
5182 			flp->nfsfl_ffm[ind].devp = tdip;
5183 		nfscl_reldevinfo_locked(tdip);
5184 		NFSUNLOCKCLSTATE();
5185 		if (dip != NULL)
5186 			free(dip, M_NFSDEVINFO);
5187 		return (0);
5188 	}
5189 	if (dip != NULL) {
5190 		LIST_INSERT_HEAD(&clp->nfsc_devinfo, dip, nfsdi_list);
5191 		dip->nfsdi_layoutrefs = 1;
5192 		if ((flp->nfsfl_flags & NFSFL_FILE) != 0)
5193 			flp->nfsfl_devp = dip;
5194 		else
5195 			flp->nfsfl_ffm[ind].devp = dip;
5196 	}
5197 	NFSUNLOCKCLSTATE();
5198 	if (dip == NULL)
5199 		return (ENODEV);
5200 	return (0);
5201 }
5202 
5203 /*
5204  * Free up a layout structure and associated file layout structure(s).
5205  */
5206 APPLESTATIC void
5207 nfscl_freelayout(struct nfscllayout *layp)
5208 {
5209 	struct nfsclflayout *flp, *nflp;
5210 	struct nfsclrecalllayout *rp, *nrp;
5211 
5212 	LIST_FOREACH_SAFE(flp, &layp->nfsly_flayread, nfsfl_list, nflp) {
5213 		LIST_REMOVE(flp, nfsfl_list);
5214 		nfscl_freeflayout(flp);
5215 	}
5216 	LIST_FOREACH_SAFE(flp, &layp->nfsly_flayrw, nfsfl_list, nflp) {
5217 		LIST_REMOVE(flp, nfsfl_list);
5218 		nfscl_freeflayout(flp);
5219 	}
5220 	LIST_FOREACH_SAFE(rp, &layp->nfsly_recall, nfsrecly_list, nrp) {
5221 		LIST_REMOVE(rp, nfsrecly_list);
5222 		free(rp, M_NFSLAYRECALL);
5223 	}
5224 	nfscl_layoutcnt--;
5225 	free(layp, M_NFSLAYOUT);
5226 }
5227 
5228 /*
5229  * Free up a file layout structure.
5230  */
5231 APPLESTATIC void
5232 nfscl_freeflayout(struct nfsclflayout *flp)
5233 {
5234 	int i, j;
5235 
5236 	if ((flp->nfsfl_flags & NFSFL_FILE) != 0) {
5237 		for (i = 0; i < flp->nfsfl_fhcnt; i++)
5238 			free(flp->nfsfl_fh[i], M_NFSFH);
5239 		if (flp->nfsfl_devp != NULL)
5240 			flp->nfsfl_devp->nfsdi_layoutrefs--;
5241 	}
5242 	if ((flp->nfsfl_flags & NFSFL_FLEXFILE) != 0)
5243 		for (i = 0; i < flp->nfsfl_mirrorcnt; i++) {
5244 			for (j = 0; j < flp->nfsfl_ffm[i].fhcnt; j++)
5245 				free(flp->nfsfl_ffm[i].fh[j], M_NFSFH);
5246 			if (flp->nfsfl_ffm[i].devp != NULL)
5247 				flp->nfsfl_ffm[i].devp->nfsdi_layoutrefs--;
5248 		}
5249 	free(flp, M_NFSFLAYOUT);
5250 }
5251 
5252 /*
5253  * Free up a file layout devinfo structure.
5254  */
5255 APPLESTATIC void
5256 nfscl_freedevinfo(struct nfscldevinfo *dip)
5257 {
5258 
5259 	free(dip, M_NFSDEVINFO);
5260 }
5261 
5262 /*
5263  * Mark any layouts that match as recalled.
5264  */
5265 static int
5266 nfscl_layoutrecall(int recalltype, struct nfscllayout *lyp, uint32_t iomode,
5267     uint64_t off, uint64_t len, uint32_t stateseqid, uint32_t stat, uint32_t op,
5268     char *devid, struct nfsclrecalllayout *recallp)
5269 {
5270 	struct nfsclrecalllayout *rp, *orp;
5271 
5272 	recallp->nfsrecly_recalltype = recalltype;
5273 	recallp->nfsrecly_iomode = iomode;
5274 	recallp->nfsrecly_stateseqid = stateseqid;
5275 	recallp->nfsrecly_off = off;
5276 	recallp->nfsrecly_len = len;
5277 	recallp->nfsrecly_stat = stat;
5278 	recallp->nfsrecly_op = op;
5279 	if (devid != NULL)
5280 		NFSBCOPY(devid, recallp->nfsrecly_devid, NFSX_V4DEVICEID);
5281 	/*
5282 	 * Order the list as file returns first, followed by fsid and any
5283 	 * returns, both in increasing stateseqid order.
5284 	 * Note that the seqids wrap around, so 1 is after 0xffffffff.
5285 	 * (I'm not sure this is correct because I find RFC5661 confusing
5286 	 *  on this, but hopefully it will work ok.)
5287 	 */
5288 	orp = NULL;
5289 	LIST_FOREACH(rp, &lyp->nfsly_recall, nfsrecly_list) {
5290 		orp = rp;
5291 		if ((recalltype == NFSLAYOUTRETURN_FILE &&
5292 		     (rp->nfsrecly_recalltype != NFSLAYOUTRETURN_FILE ||
5293 		      nfscl_seq(stateseqid, rp->nfsrecly_stateseqid) != 0)) ||
5294 		    (recalltype != NFSLAYOUTRETURN_FILE &&
5295 		     rp->nfsrecly_recalltype != NFSLAYOUTRETURN_FILE &&
5296 		     nfscl_seq(stateseqid, rp->nfsrecly_stateseqid) != 0)) {
5297 			LIST_INSERT_BEFORE(rp, recallp, nfsrecly_list);
5298 			break;
5299 		}
5300 
5301 		/*
5302 		 * Put any error return on all the file returns that will
5303 		 * preceed this one.
5304 		 */
5305 		if (rp->nfsrecly_recalltype == NFSLAYOUTRETURN_FILE &&
5306 		   stat != 0 && rp->nfsrecly_stat == 0) {
5307 			rp->nfsrecly_stat = stat;
5308 			rp->nfsrecly_op = op;
5309 			if (devid != NULL)
5310 				NFSBCOPY(devid, rp->nfsrecly_devid,
5311 				    NFSX_V4DEVICEID);
5312 		}
5313 	}
5314 	if (rp == NULL) {
5315 		if (orp == NULL)
5316 			LIST_INSERT_HEAD(&lyp->nfsly_recall, recallp,
5317 			    nfsrecly_list);
5318 		else
5319 			LIST_INSERT_AFTER(orp, recallp, nfsrecly_list);
5320 	}
5321 	lyp->nfsly_flags |= NFSLY_RECALL;
5322 	wakeup(lyp->nfsly_clp);
5323 	return (0);
5324 }
5325 
5326 /*
5327  * Compare the two seqids for ordering. The trick is that the seqids can
5328  * wrap around from 0xffffffff->0, so check for the cases where one
5329  * has wrapped around.
5330  * Return 1 if seqid1 comes before seqid2, 0 otherwise.
5331  */
5332 static int
5333 nfscl_seq(uint32_t seqid1, uint32_t seqid2)
5334 {
5335 
5336 	if (seqid2 > seqid1 && (seqid2 - seqid1) >= 0x7fffffff)
5337 		/* seqid2 has wrapped around. */
5338 		return (0);
5339 	if (seqid1 > seqid2 && (seqid1 - seqid2) >= 0x7fffffff)
5340 		/* seqid1 has wrapped around. */
5341 		return (1);
5342 	if (seqid1 <= seqid2)
5343 		return (1);
5344 	return (0);
5345 }
5346 
5347 /*
5348  * Do a layout return for each of the recalls.
5349  */
5350 static void
5351 nfscl_layoutreturn(struct nfsmount *nmp, struct nfscllayout *lyp,
5352     struct ucred *cred, NFSPROC_T *p)
5353 {
5354 	struct nfsclrecalllayout *rp;
5355 	nfsv4stateid_t stateid;
5356 	int layouttype;
5357 
5358 	NFSBCOPY(lyp->nfsly_stateid.other, stateid.other, NFSX_STATEIDOTHER);
5359 	stateid.seqid = lyp->nfsly_stateid.seqid;
5360 	if ((lyp->nfsly_flags & NFSLY_FILES) != 0)
5361 		layouttype = NFSLAYOUT_NFSV4_1_FILES;
5362 	else
5363 		layouttype = NFSLAYOUT_FLEXFILE;
5364 	LIST_FOREACH(rp, &lyp->nfsly_recall, nfsrecly_list) {
5365 		(void)nfsrpc_layoutreturn(nmp, lyp->nfsly_fh,
5366 		    lyp->nfsly_fhlen, 0, layouttype,
5367 		    rp->nfsrecly_iomode, rp->nfsrecly_recalltype,
5368 		    rp->nfsrecly_off, rp->nfsrecly_len,
5369 		    &stateid, cred, p, rp->nfsrecly_stat, rp->nfsrecly_op,
5370 		    rp->nfsrecly_devid);
5371 	}
5372 }
5373 
5374 /*
5375  * Do the layout commit for a file layout.
5376  */
5377 static void
5378 nfscl_dolayoutcommit(struct nfsmount *nmp, struct nfscllayout *lyp,
5379     struct ucred *cred, NFSPROC_T *p)
5380 {
5381 	struct nfsclflayout *flp;
5382 	uint64_t len;
5383 	int error, layouttype;
5384 
5385 	if ((lyp->nfsly_flags & NFSLY_FILES) != 0)
5386 		layouttype = NFSLAYOUT_NFSV4_1_FILES;
5387 	else
5388 		layouttype = NFSLAYOUT_FLEXFILE;
5389 	LIST_FOREACH(flp, &lyp->nfsly_flayrw, nfsfl_list) {
5390 		if (layouttype == NFSLAYOUT_FLEXFILE &&
5391 		    (flp->nfsfl_fflags & NFSFLEXFLAG_NO_LAYOUTCOMMIT) != 0) {
5392 			NFSCL_DEBUG(4, "Flex file: no layoutcommit\n");
5393 			/* If not supported, don't bother doing it. */
5394 			NFSLOCKMNT(nmp);
5395 			nmp->nm_state |= NFSSTA_NOLAYOUTCOMMIT;
5396 			NFSUNLOCKMNT(nmp);
5397 			break;
5398 		} else if (flp->nfsfl_off <= lyp->nfsly_lastbyte) {
5399 			len = flp->nfsfl_end - flp->nfsfl_off;
5400 			error = nfsrpc_layoutcommit(nmp, lyp->nfsly_fh,
5401 			    lyp->nfsly_fhlen, 0, flp->nfsfl_off, len,
5402 			    lyp->nfsly_lastbyte, &lyp->nfsly_stateid,
5403 			    layouttype, cred, p, NULL);
5404 			NFSCL_DEBUG(4, "layoutcommit err=%d\n", error);
5405 			if (error == NFSERR_NOTSUPP) {
5406 				/* If not supported, don't bother doing it. */
5407 				NFSLOCKMNT(nmp);
5408 				nmp->nm_state |= NFSSTA_NOLAYOUTCOMMIT;
5409 				NFSUNLOCKMNT(nmp);
5410 				break;
5411 			}
5412 		}
5413 	}
5414 }
5415 
5416 /*
5417  * Commit all layouts for a file (vnode).
5418  */
5419 int
5420 nfscl_layoutcommit(vnode_t vp, NFSPROC_T *p)
5421 {
5422 	struct nfsclclient *clp;
5423 	struct nfscllayout *lyp;
5424 	struct nfsnode *np = VTONFS(vp);
5425 	mount_t mp;
5426 	struct nfsmount *nmp;
5427 
5428 	mp = vnode_mount(vp);
5429 	nmp = VFSTONFS(mp);
5430 	if (NFSHASNOLAYOUTCOMMIT(nmp))
5431 		return (0);
5432 	NFSLOCKCLSTATE();
5433 	clp = nmp->nm_clp;
5434 	if (clp == NULL) {
5435 		NFSUNLOCKCLSTATE();
5436 		return (EPERM);
5437 	}
5438 	lyp = nfscl_findlayout(clp, np->n_fhp->nfh_fh, np->n_fhp->nfh_len);
5439 	if (lyp == NULL) {
5440 		NFSUNLOCKCLSTATE();
5441 		return (EPERM);
5442 	}
5443 	nfsv4_getref(&lyp->nfsly_lock, NULL, NFSCLSTATEMUTEXPTR, mp);
5444 	if (NFSCL_FORCEDISM(mp)) {
5445 		NFSUNLOCKCLSTATE();
5446 		return (EPERM);
5447 	}
5448 tryagain:
5449 	if ((lyp->nfsly_flags & NFSLY_WRITTEN) != 0) {
5450 		lyp->nfsly_flags &= ~NFSLY_WRITTEN;
5451 		NFSUNLOCKCLSTATE();
5452 		NFSCL_DEBUG(4, "do layoutcommit2\n");
5453 		nfscl_dolayoutcommit(clp->nfsc_nmp, lyp, NFSPROCCRED(p), p);
5454 		NFSLOCKCLSTATE();
5455 		goto tryagain;
5456 	}
5457 	nfsv4_relref(&lyp->nfsly_lock);
5458 	NFSUNLOCKCLSTATE();
5459 	return (0);
5460 }
5461 
5462