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