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