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