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