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