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