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