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