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