xref: /freebsd/sys/fs/nfsserver/nfs_nfsdstate.c (revision d93a896e)
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 #ifndef APPLEKEXT
32 #include <fs/nfs/nfsport.h>
33 
34 struct nfsrv_stablefirst nfsrv_stablefirst;
35 int nfsrv_issuedelegs = 0;
36 int nfsrv_dolocallocks = 0;
37 struct nfsv4lock nfsv4rootfs_lock;
38 
39 extern int newnfs_numnfsd;
40 extern struct nfsstatsv1 nfsstatsv1;
41 extern int nfsrv_lease;
42 extern struct timeval nfsboottime;
43 extern u_int32_t newnfs_true, newnfs_false;
44 NFSV4ROOTLOCKMUTEX;
45 NFSSTATESPINLOCK;
46 
47 SYSCTL_DECL(_vfs_nfsd);
48 int	nfsrv_statehashsize = NFSSTATEHASHSIZE;
49 SYSCTL_INT(_vfs_nfsd, OID_AUTO, statehashsize, CTLFLAG_RDTUN,
50     &nfsrv_statehashsize, 0,
51     "Size of state hash table set via loader.conf");
52 
53 int	nfsrv_clienthashsize = NFSCLIENTHASHSIZE;
54 SYSCTL_INT(_vfs_nfsd, OID_AUTO, clienthashsize, CTLFLAG_RDTUN,
55     &nfsrv_clienthashsize, 0,
56     "Size of client hash table set via loader.conf");
57 
58 int	nfsrv_lockhashsize = NFSLOCKHASHSIZE;
59 SYSCTL_INT(_vfs_nfsd, OID_AUTO, fhhashsize, CTLFLAG_RDTUN,
60     &nfsrv_lockhashsize, 0,
61     "Size of file handle hash table set via loader.conf");
62 
63 int	nfsrv_sessionhashsize = NFSSESSIONHASHSIZE;
64 SYSCTL_INT(_vfs_nfsd, OID_AUTO, sessionhashsize, CTLFLAG_RDTUN,
65     &nfsrv_sessionhashsize, 0,
66     "Size of session hash table set via loader.conf");
67 
68 static int	nfsrv_v4statelimit = NFSRV_V4STATELIMIT;
69 SYSCTL_INT(_vfs_nfsd, OID_AUTO, v4statelimit, CTLFLAG_RWTUN,
70     &nfsrv_v4statelimit, 0,
71     "High water limit for NFSv4 opens+locks+delegations");
72 
73 static int	nfsrv_writedelegifpos = 0;
74 SYSCTL_INT(_vfs_nfsd, OID_AUTO, writedelegifpos, CTLFLAG_RW,
75     &nfsrv_writedelegifpos, 0,
76     "Issue a write delegation for read opens if possible");
77 
78 static int	nfsrv_allowreadforwriteopen = 1;
79 SYSCTL_INT(_vfs_nfsd, OID_AUTO, allowreadforwriteopen, CTLFLAG_RW,
80     &nfsrv_allowreadforwriteopen, 0,
81     "Allow Reads to be done with Write Access StateIDs");
82 
83 /*
84  * Hash lists for nfs V4.
85  */
86 struct nfsclienthashhead	*nfsclienthash;
87 struct nfslockhashhead		*nfslockhash;
88 struct nfssessionhash		*nfssessionhash;
89 #endif	/* !APPLEKEXT */
90 
91 static u_int32_t nfsrv_openpluslock = 0, nfsrv_delegatecnt = 0;
92 static time_t nfsrvboottime;
93 static int nfsrv_returnoldstateid = 0, nfsrv_clients = 0;
94 static int nfsrv_clienthighwater = NFSRV_CLIENTHIGHWATER;
95 static int nfsrv_nogsscallback = 0;
96 
97 /* local functions */
98 static void nfsrv_dumpaclient(struct nfsclient *clp,
99     struct nfsd_dumpclients *dumpp);
100 static void nfsrv_freeopenowner(struct nfsstate *stp, int cansleep,
101     NFSPROC_T *p);
102 static int nfsrv_freeopen(struct nfsstate *stp, vnode_t vp, int cansleep,
103     NFSPROC_T *p);
104 static void nfsrv_freelockowner(struct nfsstate *stp, vnode_t vp, int cansleep,
105     NFSPROC_T *p);
106 static void nfsrv_freeallnfslocks(struct nfsstate *stp, vnode_t vp,
107     int cansleep, NFSPROC_T *p);
108 static void nfsrv_freenfslock(struct nfslock *lop);
109 static void nfsrv_freenfslockfile(struct nfslockfile *lfp);
110 static void nfsrv_freedeleg(struct nfsstate *);
111 static int nfsrv_getstate(struct nfsclient *clp, nfsv4stateid_t *stateidp,
112     u_int32_t flags, struct nfsstate **stpp);
113 static void nfsrv_getowner(struct nfsstatehead *hp, struct nfsstate *new_stp,
114     struct nfsstate **stpp);
115 static int nfsrv_getlockfh(vnode_t vp, u_short flags,
116     struct nfslockfile *new_lfp, fhandle_t *nfhp, NFSPROC_T *p);
117 static int nfsrv_getlockfile(u_short flags, struct nfslockfile **new_lfpp,
118     struct nfslockfile **lfpp, fhandle_t *nfhp, int lockit);
119 static void nfsrv_insertlock(struct nfslock *new_lop,
120     struct nfslock *insert_lop, struct nfsstate *stp, struct nfslockfile *lfp);
121 static void nfsrv_updatelock(struct nfsstate *stp, struct nfslock **new_lopp,
122     struct nfslock **other_lopp, struct nfslockfile *lfp);
123 static int nfsrv_getipnumber(u_char *cp);
124 static int nfsrv_checkrestart(nfsquad_t clientid, u_int32_t flags,
125     nfsv4stateid_t *stateidp, int specialid);
126 static int nfsrv_checkgrace(struct nfsrv_descript *nd, struct nfsclient *clp,
127     u_int32_t flags);
128 static int nfsrv_docallback(struct nfsclient *clp, int procnum,
129     nfsv4stateid_t *stateidp, int trunc, fhandle_t *fhp,
130     struct nfsvattr *nap, nfsattrbit_t *attrbitp, NFSPROC_T *p);
131 static int nfsrv_cbcallargs(struct nfsrv_descript *nd, struct nfsclient *clp,
132     uint32_t callback, int op, const char *optag, struct nfsdsession **sepp);
133 static u_int32_t nfsrv_nextclientindex(void);
134 static u_int32_t nfsrv_nextstateindex(struct nfsclient *clp);
135 static void nfsrv_markstable(struct nfsclient *clp);
136 static int nfsrv_checkstable(struct nfsclient *clp);
137 static int nfsrv_clientconflict(struct nfsclient *clp, int *haslockp, struct
138     vnode *vp, NFSPROC_T *p);
139 static int nfsrv_delegconflict(struct nfsstate *stp, int *haslockp,
140     NFSPROC_T *p, vnode_t vp);
141 static int nfsrv_cleandeleg(vnode_t vp, struct nfslockfile *lfp,
142     struct nfsclient *clp, int *haslockp, NFSPROC_T *p);
143 static int nfsrv_notsamecredname(struct nfsrv_descript *nd,
144     struct nfsclient *clp);
145 static time_t nfsrv_leaseexpiry(void);
146 static void nfsrv_delaydelegtimeout(struct nfsstate *stp);
147 static int nfsrv_checkseqid(struct nfsrv_descript *nd, u_int32_t seqid,
148     struct nfsstate *stp, struct nfsrvcache *op);
149 static int nfsrv_nootherstate(struct nfsstate *stp);
150 static int nfsrv_locallock(vnode_t vp, struct nfslockfile *lfp, int flags,
151     uint64_t first, uint64_t end, struct nfslockconflict *cfp, NFSPROC_T *p);
152 static void nfsrv_localunlock(vnode_t vp, struct nfslockfile *lfp,
153     uint64_t init_first, uint64_t init_end, NFSPROC_T *p);
154 static int nfsrv_dolocal(vnode_t vp, struct nfslockfile *lfp, int flags,
155     int oldflags, uint64_t first, uint64_t end, struct nfslockconflict *cfp,
156     NFSPROC_T *p);
157 static void nfsrv_locallock_rollback(vnode_t vp, struct nfslockfile *lfp,
158     NFSPROC_T *p);
159 static void nfsrv_locallock_commit(struct nfslockfile *lfp, int flags,
160     uint64_t first, uint64_t end);
161 static void nfsrv_locklf(struct nfslockfile *lfp);
162 static void nfsrv_unlocklf(struct nfslockfile *lfp);
163 static struct nfsdsession *nfsrv_findsession(uint8_t *sessionid);
164 static int nfsrv_freesession(struct nfsdsession *sep, uint8_t *sessionid);
165 static int nfsv4_setcbsequence(struct nfsrv_descript *nd, struct nfsclient *clp,
166     int dont_replycache, struct nfsdsession **sepp);
167 static int nfsv4_getcbsession(struct nfsclient *clp, struct nfsdsession **sepp);
168 
169 /*
170  * Scan the client list for a match and either return the current one,
171  * create a new entry or return an error.
172  * If returning a non-error, the clp structure must either be linked into
173  * the client list or free'd.
174  */
175 APPLESTATIC int
176 nfsrv_setclient(struct nfsrv_descript *nd, struct nfsclient **new_clpp,
177     nfsquad_t *clientidp, nfsquad_t *confirmp, NFSPROC_T *p)
178 {
179 	struct nfsclient *clp = NULL, *new_clp = *new_clpp;
180 	int i, error = 0;
181 	struct nfsstate *stp, *tstp;
182 	struct sockaddr_in *sad, *rad;
183 	int zapit = 0, gotit, hasstate = 0, igotlock;
184 	static u_int64_t confirm_index = 0;
185 
186 	/*
187 	 * Check for state resource limit exceeded.
188 	 */
189 	if (nfsrv_openpluslock > nfsrv_v4statelimit) {
190 		error = NFSERR_RESOURCE;
191 		goto out;
192 	}
193 
194 	if (nfsrv_issuedelegs == 0 ||
195 	    ((nd->nd_flag & ND_GSS) != 0 && nfsrv_nogsscallback != 0))
196 		/*
197 		 * Don't do callbacks when delegations are disabled or
198 		 * for AUTH_GSS unless enabled via nfsrv_nogsscallback.
199 		 * If establishing a callback connection is attempted
200 		 * when a firewall is blocking the callback path, the
201 		 * server may wait too long for the connect attempt to
202 		 * succeed during the Open. Some clients, such as Linux,
203 		 * may timeout and give up on the Open before the server
204 		 * replies. Also, since AUTH_GSS callbacks are not
205 		 * yet interoperability tested, they might cause the
206 		 * server to crap out, if they get past the Init call to
207 		 * the client.
208 		 */
209 		new_clp->lc_program = 0;
210 
211 	/* Lock out other nfsd threads */
212 	NFSLOCKV4ROOTMUTEX();
213 	nfsv4_relref(&nfsv4rootfs_lock);
214 	do {
215 		igotlock = nfsv4_lock(&nfsv4rootfs_lock, 1, NULL,
216 		    NFSV4ROOTLOCKMUTEXPTR, NULL);
217 	} while (!igotlock);
218 	NFSUNLOCKV4ROOTMUTEX();
219 
220 	/*
221 	 * Search for a match in the client list.
222 	 */
223 	gotit = i = 0;
224 	while (i < nfsrv_clienthashsize && !gotit) {
225 	    LIST_FOREACH(clp, &nfsclienthash[i], lc_hash) {
226 		if (new_clp->lc_idlen == clp->lc_idlen &&
227 		    !NFSBCMP(new_clp->lc_id, clp->lc_id, clp->lc_idlen)) {
228 			gotit = 1;
229 			break;
230 		}
231 	    }
232 	    if (gotit == 0)
233 		i++;
234 	}
235 	if (!gotit ||
236 	    (clp->lc_flags & (LCL_NEEDSCONFIRM | LCL_ADMINREVOKED))) {
237 		if ((nd->nd_flag & ND_NFSV41) != 0 && confirmp->lval[1] != 0) {
238 			/*
239 			 * For NFSv4.1, if confirmp->lval[1] is non-zero, the
240 			 * client is trying to update a confirmed clientid.
241 			 */
242 			NFSLOCKV4ROOTMUTEX();
243 			nfsv4_unlock(&nfsv4rootfs_lock, 1);
244 			NFSUNLOCKV4ROOTMUTEX();
245 			confirmp->lval[1] = 0;
246 			error = NFSERR_NOENT;
247 			goto out;
248 		}
249 		/*
250 		 * Get rid of the old one.
251 		 */
252 		if (i != nfsrv_clienthashsize) {
253 			LIST_REMOVE(clp, lc_hash);
254 			nfsrv_cleanclient(clp, p);
255 			nfsrv_freedeleglist(&clp->lc_deleg);
256 			nfsrv_freedeleglist(&clp->lc_olddeleg);
257 			zapit = 1;
258 		}
259 		/*
260 		 * Add it after assigning a client id to it.
261 		 */
262 		new_clp->lc_flags |= LCL_NEEDSCONFIRM;
263 		if ((nd->nd_flag & ND_NFSV41) != 0)
264 			new_clp->lc_confirm.lval[0] = confirmp->lval[0] =
265 			    ++confirm_index;
266 		else
267 			confirmp->qval = new_clp->lc_confirm.qval =
268 			    ++confirm_index;
269 		clientidp->lval[0] = new_clp->lc_clientid.lval[0] =
270 		    (u_int32_t)nfsrvboottime;
271 		clientidp->lval[1] = new_clp->lc_clientid.lval[1] =
272 		    nfsrv_nextclientindex();
273 		new_clp->lc_stateindex = 0;
274 		new_clp->lc_statemaxindex = 0;
275 		new_clp->lc_cbref = 0;
276 		new_clp->lc_expiry = nfsrv_leaseexpiry();
277 		LIST_INIT(&new_clp->lc_open);
278 		LIST_INIT(&new_clp->lc_deleg);
279 		LIST_INIT(&new_clp->lc_olddeleg);
280 		LIST_INIT(&new_clp->lc_session);
281 		for (i = 0; i < nfsrv_statehashsize; i++)
282 			LIST_INIT(&new_clp->lc_stateid[i]);
283 		LIST_INSERT_HEAD(NFSCLIENTHASH(new_clp->lc_clientid), new_clp,
284 		    lc_hash);
285 		nfsstatsv1.srvclients++;
286 		nfsrv_openpluslock++;
287 		nfsrv_clients++;
288 		NFSLOCKV4ROOTMUTEX();
289 		nfsv4_unlock(&nfsv4rootfs_lock, 1);
290 		NFSUNLOCKV4ROOTMUTEX();
291 		if (zapit)
292 			nfsrv_zapclient(clp, p);
293 		*new_clpp = NULL;
294 		goto out;
295 	}
296 
297 	/*
298 	 * Now, handle the cases where the id is already issued.
299 	 */
300 	if (nfsrv_notsamecredname(nd, clp)) {
301 	    /*
302 	     * Check to see if there is expired state that should go away.
303 	     */
304 	    if (clp->lc_expiry < NFSD_MONOSEC &&
305 	        (!LIST_EMPTY(&clp->lc_open) || !LIST_EMPTY(&clp->lc_deleg))) {
306 		nfsrv_cleanclient(clp, p);
307 		nfsrv_freedeleglist(&clp->lc_deleg);
308 	    }
309 
310 	    /*
311 	     * If there is outstanding state, then reply NFSERR_CLIDINUSE per
312 	     * RFC3530 Sec. 8.1.2 last para.
313 	     */
314 	    if (!LIST_EMPTY(&clp->lc_deleg)) {
315 		hasstate = 1;
316 	    } else if (LIST_EMPTY(&clp->lc_open)) {
317 		hasstate = 0;
318 	    } else {
319 		hasstate = 0;
320 		/* Look for an Open on the OpenOwner */
321 		LIST_FOREACH(stp, &clp->lc_open, ls_list) {
322 		    if (!LIST_EMPTY(&stp->ls_open)) {
323 			hasstate = 1;
324 			break;
325 		    }
326 		}
327 	    }
328 	    if (hasstate) {
329 		/*
330 		 * If the uid doesn't match, return NFSERR_CLIDINUSE after
331 		 * filling out the correct ipaddr and portnum.
332 		 */
333 		sad = NFSSOCKADDR(new_clp->lc_req.nr_nam, struct sockaddr_in *);
334 		rad = NFSSOCKADDR(clp->lc_req.nr_nam, struct sockaddr_in *);
335 		sad->sin_addr.s_addr = rad->sin_addr.s_addr;
336 		sad->sin_port = rad->sin_port;
337 		NFSLOCKV4ROOTMUTEX();
338 		nfsv4_unlock(&nfsv4rootfs_lock, 1);
339 		NFSUNLOCKV4ROOTMUTEX();
340 		error = NFSERR_CLIDINUSE;
341 		goto out;
342 	    }
343 	}
344 
345 	if (NFSBCMP(new_clp->lc_verf, clp->lc_verf, NFSX_VERF)) {
346 		/*
347 		 * If the verifier has changed, the client has rebooted
348 		 * and a new client id is issued. The old state info
349 		 * can be thrown away once the SETCLIENTID_CONFIRM occurs.
350 		 */
351 		LIST_REMOVE(clp, lc_hash);
352 		new_clp->lc_flags |= LCL_NEEDSCONFIRM;
353 		if ((nd->nd_flag & ND_NFSV41) != 0)
354 			new_clp->lc_confirm.lval[0] = confirmp->lval[0] =
355 			    ++confirm_index;
356 		else
357 			confirmp->qval = new_clp->lc_confirm.qval =
358 			    ++confirm_index;
359 		clientidp->lval[0] = new_clp->lc_clientid.lval[0] =
360 		    nfsrvboottime;
361 		clientidp->lval[1] = new_clp->lc_clientid.lval[1] =
362 		    nfsrv_nextclientindex();
363 		new_clp->lc_stateindex = 0;
364 		new_clp->lc_statemaxindex = 0;
365 		new_clp->lc_cbref = 0;
366 		new_clp->lc_expiry = nfsrv_leaseexpiry();
367 
368 		/*
369 		 * Save the state until confirmed.
370 		 */
371 		LIST_NEWHEAD(&new_clp->lc_open, &clp->lc_open, ls_list);
372 		LIST_FOREACH(tstp, &new_clp->lc_open, ls_list)
373 			tstp->ls_clp = new_clp;
374 		LIST_NEWHEAD(&new_clp->lc_deleg, &clp->lc_deleg, ls_list);
375 		LIST_FOREACH(tstp, &new_clp->lc_deleg, ls_list)
376 			tstp->ls_clp = new_clp;
377 		LIST_NEWHEAD(&new_clp->lc_olddeleg, &clp->lc_olddeleg,
378 		    ls_list);
379 		LIST_FOREACH(tstp, &new_clp->lc_olddeleg, ls_list)
380 			tstp->ls_clp = new_clp;
381 		for (i = 0; i < nfsrv_statehashsize; i++) {
382 			LIST_NEWHEAD(&new_clp->lc_stateid[i],
383 			    &clp->lc_stateid[i], ls_hash);
384 			LIST_FOREACH(tstp, &new_clp->lc_stateid[i], ls_hash)
385 				tstp->ls_clp = new_clp;
386 		}
387 		LIST_INSERT_HEAD(NFSCLIENTHASH(new_clp->lc_clientid), new_clp,
388 		    lc_hash);
389 		nfsstatsv1.srvclients++;
390 		nfsrv_openpluslock++;
391 		nfsrv_clients++;
392 		NFSLOCKV4ROOTMUTEX();
393 		nfsv4_unlock(&nfsv4rootfs_lock, 1);
394 		NFSUNLOCKV4ROOTMUTEX();
395 
396 		/*
397 		 * Must wait until any outstanding callback on the old clp
398 		 * completes.
399 		 */
400 		NFSLOCKSTATE();
401 		while (clp->lc_cbref) {
402 			clp->lc_flags |= LCL_WAKEUPWANTED;
403 			(void)mtx_sleep(clp, NFSSTATEMUTEXPTR, PZERO - 1,
404 			    "nfsd clp", 10 * hz);
405 		}
406 		NFSUNLOCKSTATE();
407 		nfsrv_zapclient(clp, p);
408 		*new_clpp = NULL;
409 		goto out;
410 	}
411 
412 	/* For NFSv4.1, mark that we found a confirmed clientid. */
413 	if ((nd->nd_flag & ND_NFSV41) != 0) {
414 		clientidp->lval[0] = clp->lc_clientid.lval[0];
415 		clientidp->lval[1] = clp->lc_clientid.lval[1];
416 		confirmp->lval[0] = 0;	/* Ignored by client */
417 		confirmp->lval[1] = 1;
418 	} else {
419 		/*
420 		 * id and verifier match, so update the net address info
421 		 * and get rid of any existing callback authentication
422 		 * handle, so a new one will be acquired.
423 		 */
424 		LIST_REMOVE(clp, lc_hash);
425 		new_clp->lc_flags |= (LCL_NEEDSCONFIRM | LCL_DONTCLEAN);
426 		new_clp->lc_expiry = nfsrv_leaseexpiry();
427 		confirmp->qval = new_clp->lc_confirm.qval = ++confirm_index;
428 		clientidp->lval[0] = new_clp->lc_clientid.lval[0] =
429 		    clp->lc_clientid.lval[0];
430 		clientidp->lval[1] = new_clp->lc_clientid.lval[1] =
431 		    clp->lc_clientid.lval[1];
432 		new_clp->lc_delegtime = clp->lc_delegtime;
433 		new_clp->lc_stateindex = clp->lc_stateindex;
434 		new_clp->lc_statemaxindex = clp->lc_statemaxindex;
435 		new_clp->lc_cbref = 0;
436 		LIST_NEWHEAD(&new_clp->lc_open, &clp->lc_open, ls_list);
437 		LIST_FOREACH(tstp, &new_clp->lc_open, ls_list)
438 			tstp->ls_clp = new_clp;
439 		LIST_NEWHEAD(&new_clp->lc_deleg, &clp->lc_deleg, ls_list);
440 		LIST_FOREACH(tstp, &new_clp->lc_deleg, ls_list)
441 			tstp->ls_clp = new_clp;
442 		LIST_NEWHEAD(&new_clp->lc_olddeleg, &clp->lc_olddeleg, ls_list);
443 		LIST_FOREACH(tstp, &new_clp->lc_olddeleg, ls_list)
444 			tstp->ls_clp = new_clp;
445 		for (i = 0; i < nfsrv_statehashsize; i++) {
446 			LIST_NEWHEAD(&new_clp->lc_stateid[i],
447 			    &clp->lc_stateid[i], ls_hash);
448 			LIST_FOREACH(tstp, &new_clp->lc_stateid[i], ls_hash)
449 				tstp->ls_clp = new_clp;
450 		}
451 		LIST_INSERT_HEAD(NFSCLIENTHASH(new_clp->lc_clientid), new_clp,
452 		    lc_hash);
453 		nfsstatsv1.srvclients++;
454 		nfsrv_openpluslock++;
455 		nfsrv_clients++;
456 	}
457 	NFSLOCKV4ROOTMUTEX();
458 	nfsv4_unlock(&nfsv4rootfs_lock, 1);
459 	NFSUNLOCKV4ROOTMUTEX();
460 
461 	if ((nd->nd_flag & ND_NFSV41) == 0) {
462 		/*
463 		 * Must wait until any outstanding callback on the old clp
464 		 * completes.
465 		 */
466 		NFSLOCKSTATE();
467 		while (clp->lc_cbref) {
468 			clp->lc_flags |= LCL_WAKEUPWANTED;
469 			(void)mtx_sleep(clp, NFSSTATEMUTEXPTR, PZERO - 1,
470 			    "nfsdclp", 10 * hz);
471 		}
472 		NFSUNLOCKSTATE();
473 		nfsrv_zapclient(clp, p);
474 		*new_clpp = NULL;
475 	}
476 
477 out:
478 	NFSEXITCODE2(error, nd);
479 	return (error);
480 }
481 
482 /*
483  * Check to see if the client id exists and optionally confirm it.
484  */
485 APPLESTATIC int
486 nfsrv_getclient(nfsquad_t clientid, int opflags, struct nfsclient **clpp,
487     struct nfsdsession *nsep, nfsquad_t confirm, uint32_t cbprogram,
488     struct nfsrv_descript *nd, NFSPROC_T *p)
489 {
490 	struct nfsclient *clp;
491 	struct nfsstate *stp;
492 	int i;
493 	struct nfsclienthashhead *hp;
494 	int error = 0, igotlock, doneok;
495 	struct nfssessionhash *shp;
496 	struct nfsdsession *sep;
497 	uint64_t sessid[2];
498 	static uint64_t next_sess = 0;
499 
500 	if (clpp)
501 		*clpp = NULL;
502 	if ((nd == NULL || (nd->nd_flag & ND_NFSV41) == 0 ||
503 	    opflags != CLOPS_RENEW) && nfsrvboottime != clientid.lval[0]) {
504 		error = NFSERR_STALECLIENTID;
505 		goto out;
506 	}
507 
508 	/*
509 	 * If called with opflags == CLOPS_RENEW, the State Lock is
510 	 * already held. Otherwise, we need to get either that or,
511 	 * for the case of Confirm, lock out the nfsd threads.
512 	 */
513 	if (opflags & CLOPS_CONFIRM) {
514 		NFSLOCKV4ROOTMUTEX();
515 		nfsv4_relref(&nfsv4rootfs_lock);
516 		do {
517 			igotlock = nfsv4_lock(&nfsv4rootfs_lock, 1, NULL,
518 			    NFSV4ROOTLOCKMUTEXPTR, NULL);
519 		} while (!igotlock);
520 		/*
521 		 * Create a new sessionid here, since we need to do it where
522 		 * there is a mutex held to serialize update of next_sess.
523 		 */
524 		if ((nd->nd_flag & ND_NFSV41) != 0) {
525 			sessid[0] = ++next_sess;
526 			sessid[1] = clientid.qval;
527 		}
528 		NFSUNLOCKV4ROOTMUTEX();
529 	} else if (opflags != CLOPS_RENEW) {
530 		NFSLOCKSTATE();
531 	}
532 
533 	/* For NFSv4.1, the clp is acquired from the associated session. */
534 	if (nd != NULL && (nd->nd_flag & ND_NFSV41) != 0 &&
535 	    opflags == CLOPS_RENEW) {
536 		clp = NULL;
537 		if ((nd->nd_flag & ND_HASSEQUENCE) != 0) {
538 			shp = NFSSESSIONHASH(nd->nd_sessionid);
539 			NFSLOCKSESSION(shp);
540 			sep = nfsrv_findsession(nd->nd_sessionid);
541 			if (sep != NULL)
542 				clp = sep->sess_clp;
543 			NFSUNLOCKSESSION(shp);
544 		}
545 	} else {
546 		hp = NFSCLIENTHASH(clientid);
547 		LIST_FOREACH(clp, hp, lc_hash) {
548 			if (clp->lc_clientid.lval[1] == clientid.lval[1])
549 				break;
550 		}
551 	}
552 	if (clp == NULL) {
553 		if (opflags & CLOPS_CONFIRM)
554 			error = NFSERR_STALECLIENTID;
555 		else
556 			error = NFSERR_EXPIRED;
557 	} else if (clp->lc_flags & LCL_ADMINREVOKED) {
558 		/*
559 		 * If marked admin revoked, just return the error.
560 		 */
561 		error = NFSERR_ADMINREVOKED;
562 	}
563 	if (error) {
564 		if (opflags & CLOPS_CONFIRM) {
565 			NFSLOCKV4ROOTMUTEX();
566 			nfsv4_unlock(&nfsv4rootfs_lock, 1);
567 			NFSUNLOCKV4ROOTMUTEX();
568 		} else if (opflags != CLOPS_RENEW) {
569 			NFSUNLOCKSTATE();
570 		}
571 		goto out;
572 	}
573 
574 	/*
575 	 * Perform any operations specified by the opflags.
576 	 */
577 	if (opflags & CLOPS_CONFIRM) {
578 		if (((nd->nd_flag & ND_NFSV41) != 0 &&
579 		     clp->lc_confirm.lval[0] != confirm.lval[0]) ||
580 		    ((nd->nd_flag & ND_NFSV41) == 0 &&
581 		     clp->lc_confirm.qval != confirm.qval))
582 			error = NFSERR_STALECLIENTID;
583 		else if (nfsrv_notsamecredname(nd, clp))
584 			error = NFSERR_CLIDINUSE;
585 
586 		if (!error) {
587 		    if ((clp->lc_flags & (LCL_NEEDSCONFIRM | LCL_DONTCLEAN)) ==
588 			LCL_NEEDSCONFIRM) {
589 			/*
590 			 * Hang onto the delegations (as old delegations)
591 			 * for an Open with CLAIM_DELEGATE_PREV unless in
592 			 * grace, but get rid of the rest of the state.
593 			 */
594 			nfsrv_cleanclient(clp, p);
595 			nfsrv_freedeleglist(&clp->lc_olddeleg);
596 			if (nfsrv_checkgrace(nd, clp, 0)) {
597 			    /* In grace, so just delete delegations */
598 			    nfsrv_freedeleglist(&clp->lc_deleg);
599 			} else {
600 			    LIST_FOREACH(stp, &clp->lc_deleg, ls_list)
601 				stp->ls_flags |= NFSLCK_OLDDELEG;
602 			    clp->lc_delegtime = NFSD_MONOSEC +
603 				nfsrv_lease + NFSRV_LEASEDELTA;
604 			    LIST_NEWHEAD(&clp->lc_olddeleg, &clp->lc_deleg,
605 				ls_list);
606 			}
607 			if ((nd->nd_flag & ND_NFSV41) != 0)
608 			    clp->lc_program = cbprogram;
609 		    }
610 		    clp->lc_flags &= ~(LCL_NEEDSCONFIRM | LCL_DONTCLEAN);
611 		    if (clp->lc_program)
612 			clp->lc_flags |= LCL_NEEDSCBNULL;
613 		    /* For NFSv4.1, link the session onto the client. */
614 		    if (nsep != NULL) {
615 			/* Hold a reference on the xprt for a backchannel. */
616 			if ((nsep->sess_crflags & NFSV4CRSESS_CONNBACKCHAN)
617 			    != 0 && clp->lc_req.nr_client == NULL) {
618 			    clp->lc_req.nr_client = (struct __rpc_client *)
619 				clnt_bck_create(nd->nd_xprt->xp_socket,
620 				cbprogram, NFSV4_CBVERS);
621 			    if (clp->lc_req.nr_client != NULL) {
622 				SVC_ACQUIRE(nd->nd_xprt);
623 				nd->nd_xprt->xp_p2 =
624 				    clp->lc_req.nr_client->cl_private;
625 				/* Disable idle timeout. */
626 				nd->nd_xprt->xp_idletimeout = 0;
627 				nsep->sess_cbsess.nfsess_xprt = nd->nd_xprt;
628 			    } else
629 				nsep->sess_crflags &= ~NFSV4CRSESS_CONNBACKCHAN;
630 			}
631 			NFSBCOPY(sessid, nsep->sess_sessionid,
632 			    NFSX_V4SESSIONID);
633 			NFSBCOPY(sessid, nsep->sess_cbsess.nfsess_sessionid,
634 			    NFSX_V4SESSIONID);
635 			shp = NFSSESSIONHASH(nsep->sess_sessionid);
636 			NFSLOCKSTATE();
637 			NFSLOCKSESSION(shp);
638 			LIST_INSERT_HEAD(&shp->list, nsep, sess_hash);
639 			LIST_INSERT_HEAD(&clp->lc_session, nsep, sess_list);
640 			nsep->sess_clp = clp;
641 			NFSUNLOCKSESSION(shp);
642 			NFSUNLOCKSTATE();
643 		    }
644 		}
645 	} else if (clp->lc_flags & LCL_NEEDSCONFIRM) {
646 		error = NFSERR_EXPIRED;
647 	}
648 
649 	/*
650 	 * If called by the Renew Op, we must check the principal.
651 	 */
652 	if (!error && (opflags & CLOPS_RENEWOP)) {
653 	    if (nfsrv_notsamecredname(nd, clp)) {
654 		doneok = 0;
655 		for (i = 0; i < nfsrv_statehashsize && doneok == 0; i++) {
656 		    LIST_FOREACH(stp, &clp->lc_stateid[i], ls_hash) {
657 			if ((stp->ls_flags & NFSLCK_OPEN) &&
658 			    stp->ls_uid == nd->nd_cred->cr_uid) {
659 				doneok = 1;
660 				break;
661 			}
662 		    }
663 		}
664 		if (!doneok)
665 			error = NFSERR_ACCES;
666 	    }
667 	    if (!error && (clp->lc_flags & LCL_CBDOWN))
668 		error = NFSERR_CBPATHDOWN;
669 	}
670 	if ((!error || error == NFSERR_CBPATHDOWN) &&
671 	     (opflags & CLOPS_RENEW)) {
672 		clp->lc_expiry = nfsrv_leaseexpiry();
673 	}
674 	if (opflags & CLOPS_CONFIRM) {
675 		NFSLOCKV4ROOTMUTEX();
676 		nfsv4_unlock(&nfsv4rootfs_lock, 1);
677 		NFSUNLOCKV4ROOTMUTEX();
678 	} else if (opflags != CLOPS_RENEW) {
679 		NFSUNLOCKSTATE();
680 	}
681 	if (clpp)
682 		*clpp = clp;
683 
684 out:
685 	NFSEXITCODE2(error, nd);
686 	return (error);
687 }
688 
689 /*
690  * Perform the NFSv4.1 destroy clientid.
691  */
692 int
693 nfsrv_destroyclient(nfsquad_t clientid, NFSPROC_T *p)
694 {
695 	struct nfsclient *clp;
696 	struct nfsclienthashhead *hp;
697 	int error = 0, i, igotlock;
698 
699 	if (nfsrvboottime != clientid.lval[0]) {
700 		error = NFSERR_STALECLIENTID;
701 		goto out;
702 	}
703 
704 	/* Lock out other nfsd threads */
705 	NFSLOCKV4ROOTMUTEX();
706 	nfsv4_relref(&nfsv4rootfs_lock);
707 	do {
708 		igotlock = nfsv4_lock(&nfsv4rootfs_lock, 1, NULL,
709 		    NFSV4ROOTLOCKMUTEXPTR, NULL);
710 	} while (igotlock == 0);
711 	NFSUNLOCKV4ROOTMUTEX();
712 
713 	hp = NFSCLIENTHASH(clientid);
714 	LIST_FOREACH(clp, hp, lc_hash) {
715 		if (clp->lc_clientid.lval[1] == clientid.lval[1])
716 			break;
717 	}
718 	if (clp == NULL) {
719 		NFSLOCKV4ROOTMUTEX();
720 		nfsv4_unlock(&nfsv4rootfs_lock, 1);
721 		NFSUNLOCKV4ROOTMUTEX();
722 		/* Just return ok, since it is gone. */
723 		goto out;
724 	}
725 
726 	/* Scan for state on the clientid. */
727 	for (i = 0; i < nfsrv_statehashsize; i++)
728 		if (!LIST_EMPTY(&clp->lc_stateid[i])) {
729 			NFSLOCKV4ROOTMUTEX();
730 			nfsv4_unlock(&nfsv4rootfs_lock, 1);
731 			NFSUNLOCKV4ROOTMUTEX();
732 			error = NFSERR_CLIENTIDBUSY;
733 			goto out;
734 		}
735 	if (!LIST_EMPTY(&clp->lc_session) || !LIST_EMPTY(&clp->lc_deleg)) {
736 		NFSLOCKV4ROOTMUTEX();
737 		nfsv4_unlock(&nfsv4rootfs_lock, 1);
738 		NFSUNLOCKV4ROOTMUTEX();
739 		error = NFSERR_CLIENTIDBUSY;
740 		goto out;
741 	}
742 
743 	/* Destroy the clientid and return ok. */
744 	nfsrv_cleanclient(clp, p);
745 	nfsrv_freedeleglist(&clp->lc_deleg);
746 	nfsrv_freedeleglist(&clp->lc_olddeleg);
747 	LIST_REMOVE(clp, lc_hash);
748 	NFSLOCKV4ROOTMUTEX();
749 	nfsv4_unlock(&nfsv4rootfs_lock, 1);
750 	NFSUNLOCKV4ROOTMUTEX();
751 	nfsrv_zapclient(clp, p);
752 out:
753 	NFSEXITCODE2(error, nd);
754 	return (error);
755 }
756 
757 /*
758  * Called from the new nfssvc syscall to admin revoke a clientid.
759  * Returns 0 for success, error otherwise.
760  */
761 APPLESTATIC int
762 nfsrv_adminrevoke(struct nfsd_clid *revokep, NFSPROC_T *p)
763 {
764 	struct nfsclient *clp = NULL;
765 	int i, error = 0;
766 	int gotit, igotlock;
767 
768 	/*
769 	 * First, lock out the nfsd so that state won't change while the
770 	 * revocation record is being written to the stable storage restart
771 	 * file.
772 	 */
773 	NFSLOCKV4ROOTMUTEX();
774 	do {
775 		igotlock = nfsv4_lock(&nfsv4rootfs_lock, 1, NULL,
776 		    NFSV4ROOTLOCKMUTEXPTR, NULL);
777 	} while (!igotlock);
778 	NFSUNLOCKV4ROOTMUTEX();
779 
780 	/*
781 	 * Search for a match in the client list.
782 	 */
783 	gotit = i = 0;
784 	while (i < nfsrv_clienthashsize && !gotit) {
785 	    LIST_FOREACH(clp, &nfsclienthash[i], lc_hash) {
786 		if (revokep->nclid_idlen == clp->lc_idlen &&
787 		    !NFSBCMP(revokep->nclid_id, clp->lc_id, clp->lc_idlen)) {
788 			gotit = 1;
789 			break;
790 		}
791 	    }
792 	    i++;
793 	}
794 	if (!gotit) {
795 		NFSLOCKV4ROOTMUTEX();
796 		nfsv4_unlock(&nfsv4rootfs_lock, 0);
797 		NFSUNLOCKV4ROOTMUTEX();
798 		error = EPERM;
799 		goto out;
800 	}
801 
802 	/*
803 	 * Now, write out the revocation record
804 	 */
805 	nfsrv_writestable(clp->lc_id, clp->lc_idlen, NFSNST_REVOKE, p);
806 	nfsrv_backupstable();
807 
808 	/*
809 	 * and clear out the state, marking the clientid revoked.
810 	 */
811 	clp->lc_flags &= ~LCL_CALLBACKSON;
812 	clp->lc_flags |= LCL_ADMINREVOKED;
813 	nfsrv_cleanclient(clp, p);
814 	nfsrv_freedeleglist(&clp->lc_deleg);
815 	nfsrv_freedeleglist(&clp->lc_olddeleg);
816 	NFSLOCKV4ROOTMUTEX();
817 	nfsv4_unlock(&nfsv4rootfs_lock, 0);
818 	NFSUNLOCKV4ROOTMUTEX();
819 
820 out:
821 	NFSEXITCODE(error);
822 	return (error);
823 }
824 
825 /*
826  * Dump out stats for all clients. Called from nfssvc(2), that is used
827  * nfsstatsv1.
828  */
829 APPLESTATIC void
830 nfsrv_dumpclients(struct nfsd_dumpclients *dumpp, int maxcnt)
831 {
832 	struct nfsclient *clp;
833 	int i = 0, cnt = 0;
834 
835 	/*
836 	 * First, get a reference on the nfsv4rootfs_lock so that an
837 	 * exclusive lock cannot be acquired while dumping the clients.
838 	 */
839 	NFSLOCKV4ROOTMUTEX();
840 	nfsv4_getref(&nfsv4rootfs_lock, NULL, NFSV4ROOTLOCKMUTEXPTR, NULL);
841 	NFSUNLOCKV4ROOTMUTEX();
842 	NFSLOCKSTATE();
843 	/*
844 	 * Rattle through the client lists until done.
845 	 */
846 	while (i < nfsrv_clienthashsize && cnt < maxcnt) {
847 	    clp = LIST_FIRST(&nfsclienthash[i]);
848 	    while (clp != LIST_END(&nfsclienthash[i]) && cnt < maxcnt) {
849 		nfsrv_dumpaclient(clp, &dumpp[cnt]);
850 		cnt++;
851 		clp = LIST_NEXT(clp, lc_hash);
852 	    }
853 	    i++;
854 	}
855 	if (cnt < maxcnt)
856 	    dumpp[cnt].ndcl_clid.nclid_idlen = 0;
857 	NFSUNLOCKSTATE();
858 	NFSLOCKV4ROOTMUTEX();
859 	nfsv4_relref(&nfsv4rootfs_lock);
860 	NFSUNLOCKV4ROOTMUTEX();
861 }
862 
863 /*
864  * Dump stats for a client. Must be called with the NFSSTATELOCK and spl'd.
865  */
866 static void
867 nfsrv_dumpaclient(struct nfsclient *clp, struct nfsd_dumpclients *dumpp)
868 {
869 	struct nfsstate *stp, *openstp, *lckownstp;
870 	struct nfslock *lop;
871 	struct sockaddr *sad;
872 	struct sockaddr_in *rad;
873 	struct sockaddr_in6 *rad6;
874 
875 	dumpp->ndcl_nopenowners = dumpp->ndcl_nlockowners = 0;
876 	dumpp->ndcl_nopens = dumpp->ndcl_nlocks = 0;
877 	dumpp->ndcl_ndelegs = dumpp->ndcl_nolddelegs = 0;
878 	dumpp->ndcl_flags = clp->lc_flags;
879 	dumpp->ndcl_clid.nclid_idlen = clp->lc_idlen;
880 	NFSBCOPY(clp->lc_id, dumpp->ndcl_clid.nclid_id, clp->lc_idlen);
881 	sad = NFSSOCKADDR(clp->lc_req.nr_nam, struct sockaddr *);
882 	dumpp->ndcl_addrfam = sad->sa_family;
883 	if (sad->sa_family == AF_INET) {
884 		rad = (struct sockaddr_in *)sad;
885 		dumpp->ndcl_cbaddr.sin_addr = rad->sin_addr;
886 	} else {
887 		rad6 = (struct sockaddr_in6 *)sad;
888 		dumpp->ndcl_cbaddr.sin6_addr = rad6->sin6_addr;
889 	}
890 
891 	/*
892 	 * Now, scan the state lists and total up the opens and locks.
893 	 */
894 	LIST_FOREACH(stp, &clp->lc_open, ls_list) {
895 	    dumpp->ndcl_nopenowners++;
896 	    LIST_FOREACH(openstp, &stp->ls_open, ls_list) {
897 		dumpp->ndcl_nopens++;
898 		LIST_FOREACH(lckownstp, &openstp->ls_open, ls_list) {
899 		    dumpp->ndcl_nlockowners++;
900 		    LIST_FOREACH(lop, &lckownstp->ls_lock, lo_lckowner) {
901 			dumpp->ndcl_nlocks++;
902 		    }
903 		}
904 	    }
905 	}
906 
907 	/*
908 	 * and the delegation lists.
909 	 */
910 	LIST_FOREACH(stp, &clp->lc_deleg, ls_list) {
911 	    dumpp->ndcl_ndelegs++;
912 	}
913 	LIST_FOREACH(stp, &clp->lc_olddeleg, ls_list) {
914 	    dumpp->ndcl_nolddelegs++;
915 	}
916 }
917 
918 /*
919  * Dump out lock stats for a file.
920  */
921 APPLESTATIC void
922 nfsrv_dumplocks(vnode_t vp, struct nfsd_dumplocks *ldumpp, int maxcnt,
923     NFSPROC_T *p)
924 {
925 	struct nfsstate *stp;
926 	struct nfslock *lop;
927 	int cnt = 0;
928 	struct nfslockfile *lfp;
929 	struct sockaddr *sad;
930 	struct sockaddr_in *rad;
931 	struct sockaddr_in6 *rad6;
932 	int ret;
933 	fhandle_t nfh;
934 
935 	ret = nfsrv_getlockfh(vp, 0, NULL, &nfh, p);
936 	/*
937 	 * First, get a reference on the nfsv4rootfs_lock so that an
938 	 * exclusive lock on it cannot be acquired while dumping the locks.
939 	 */
940 	NFSLOCKV4ROOTMUTEX();
941 	nfsv4_getref(&nfsv4rootfs_lock, NULL, NFSV4ROOTLOCKMUTEXPTR, NULL);
942 	NFSUNLOCKV4ROOTMUTEX();
943 	NFSLOCKSTATE();
944 	if (!ret)
945 		ret = nfsrv_getlockfile(0, NULL, &lfp, &nfh, 0);
946 	if (ret) {
947 		ldumpp[0].ndlck_clid.nclid_idlen = 0;
948 		NFSUNLOCKSTATE();
949 		NFSLOCKV4ROOTMUTEX();
950 		nfsv4_relref(&nfsv4rootfs_lock);
951 		NFSUNLOCKV4ROOTMUTEX();
952 		return;
953 	}
954 
955 	/*
956 	 * For each open share on file, dump it out.
957 	 */
958 	stp = LIST_FIRST(&lfp->lf_open);
959 	while (stp != LIST_END(&lfp->lf_open) && cnt < maxcnt) {
960 		ldumpp[cnt].ndlck_flags = stp->ls_flags;
961 		ldumpp[cnt].ndlck_stateid.seqid = stp->ls_stateid.seqid;
962 		ldumpp[cnt].ndlck_stateid.other[0] = stp->ls_stateid.other[0];
963 		ldumpp[cnt].ndlck_stateid.other[1] = stp->ls_stateid.other[1];
964 		ldumpp[cnt].ndlck_stateid.other[2] = stp->ls_stateid.other[2];
965 		ldumpp[cnt].ndlck_owner.nclid_idlen =
966 		    stp->ls_openowner->ls_ownerlen;
967 		NFSBCOPY(stp->ls_openowner->ls_owner,
968 		    ldumpp[cnt].ndlck_owner.nclid_id,
969 		    stp->ls_openowner->ls_ownerlen);
970 		ldumpp[cnt].ndlck_clid.nclid_idlen = stp->ls_clp->lc_idlen;
971 		NFSBCOPY(stp->ls_clp->lc_id, ldumpp[cnt].ndlck_clid.nclid_id,
972 		    stp->ls_clp->lc_idlen);
973 		sad=NFSSOCKADDR(stp->ls_clp->lc_req.nr_nam, struct sockaddr *);
974 		ldumpp[cnt].ndlck_addrfam = sad->sa_family;
975 		if (sad->sa_family == AF_INET) {
976 			rad = (struct sockaddr_in *)sad;
977 			ldumpp[cnt].ndlck_cbaddr.sin_addr = rad->sin_addr;
978 		} else {
979 			rad6 = (struct sockaddr_in6 *)sad;
980 			ldumpp[cnt].ndlck_cbaddr.sin6_addr = rad6->sin6_addr;
981 		}
982 		stp = LIST_NEXT(stp, ls_file);
983 		cnt++;
984 	}
985 
986 	/*
987 	 * and all locks.
988 	 */
989 	lop = LIST_FIRST(&lfp->lf_lock);
990 	while (lop != LIST_END(&lfp->lf_lock) && cnt < maxcnt) {
991 		stp = lop->lo_stp;
992 		ldumpp[cnt].ndlck_flags = lop->lo_flags;
993 		ldumpp[cnt].ndlck_first = lop->lo_first;
994 		ldumpp[cnt].ndlck_end = lop->lo_end;
995 		ldumpp[cnt].ndlck_stateid.seqid = stp->ls_stateid.seqid;
996 		ldumpp[cnt].ndlck_stateid.other[0] = stp->ls_stateid.other[0];
997 		ldumpp[cnt].ndlck_stateid.other[1] = stp->ls_stateid.other[1];
998 		ldumpp[cnt].ndlck_stateid.other[2] = stp->ls_stateid.other[2];
999 		ldumpp[cnt].ndlck_owner.nclid_idlen = stp->ls_ownerlen;
1000 		NFSBCOPY(stp->ls_owner, ldumpp[cnt].ndlck_owner.nclid_id,
1001 		    stp->ls_ownerlen);
1002 		ldumpp[cnt].ndlck_clid.nclid_idlen = stp->ls_clp->lc_idlen;
1003 		NFSBCOPY(stp->ls_clp->lc_id, ldumpp[cnt].ndlck_clid.nclid_id,
1004 		    stp->ls_clp->lc_idlen);
1005 		sad=NFSSOCKADDR(stp->ls_clp->lc_req.nr_nam, struct sockaddr *);
1006 		ldumpp[cnt].ndlck_addrfam = sad->sa_family;
1007 		if (sad->sa_family == AF_INET) {
1008 			rad = (struct sockaddr_in *)sad;
1009 			ldumpp[cnt].ndlck_cbaddr.sin_addr = rad->sin_addr;
1010 		} else {
1011 			rad6 = (struct sockaddr_in6 *)sad;
1012 			ldumpp[cnt].ndlck_cbaddr.sin6_addr = rad6->sin6_addr;
1013 		}
1014 		lop = LIST_NEXT(lop, lo_lckfile);
1015 		cnt++;
1016 	}
1017 
1018 	/*
1019 	 * and the delegations.
1020 	 */
1021 	stp = LIST_FIRST(&lfp->lf_deleg);
1022 	while (stp != LIST_END(&lfp->lf_deleg) && cnt < maxcnt) {
1023 		ldumpp[cnt].ndlck_flags = stp->ls_flags;
1024 		ldumpp[cnt].ndlck_stateid.seqid = stp->ls_stateid.seqid;
1025 		ldumpp[cnt].ndlck_stateid.other[0] = stp->ls_stateid.other[0];
1026 		ldumpp[cnt].ndlck_stateid.other[1] = stp->ls_stateid.other[1];
1027 		ldumpp[cnt].ndlck_stateid.other[2] = stp->ls_stateid.other[2];
1028 		ldumpp[cnt].ndlck_owner.nclid_idlen = 0;
1029 		ldumpp[cnt].ndlck_clid.nclid_idlen = stp->ls_clp->lc_idlen;
1030 		NFSBCOPY(stp->ls_clp->lc_id, ldumpp[cnt].ndlck_clid.nclid_id,
1031 		    stp->ls_clp->lc_idlen);
1032 		sad=NFSSOCKADDR(stp->ls_clp->lc_req.nr_nam, struct sockaddr *);
1033 		ldumpp[cnt].ndlck_addrfam = sad->sa_family;
1034 		if (sad->sa_family == AF_INET) {
1035 			rad = (struct sockaddr_in *)sad;
1036 			ldumpp[cnt].ndlck_cbaddr.sin_addr = rad->sin_addr;
1037 		} else {
1038 			rad6 = (struct sockaddr_in6 *)sad;
1039 			ldumpp[cnt].ndlck_cbaddr.sin6_addr = rad6->sin6_addr;
1040 		}
1041 		stp = LIST_NEXT(stp, ls_file);
1042 		cnt++;
1043 	}
1044 
1045 	/*
1046 	 * If list isn't full, mark end of list by setting the client name
1047 	 * to zero length.
1048 	 */
1049 	if (cnt < maxcnt)
1050 		ldumpp[cnt].ndlck_clid.nclid_idlen = 0;
1051 	NFSUNLOCKSTATE();
1052 	NFSLOCKV4ROOTMUTEX();
1053 	nfsv4_relref(&nfsv4rootfs_lock);
1054 	NFSUNLOCKV4ROOTMUTEX();
1055 }
1056 
1057 /*
1058  * Server timer routine. It can scan any linked list, so long
1059  * as it holds the spin/mutex lock and there is no exclusive lock on
1060  * nfsv4rootfs_lock.
1061  * (For OpenBSD, a kthread is ok. For FreeBSD, I think it is ok
1062  *  to do this from a callout, since the spin locks work. For
1063  *  Darwin, I'm not sure what will work correctly yet.)
1064  * Should be called once per second.
1065  */
1066 APPLESTATIC void
1067 nfsrv_servertimer(void)
1068 {
1069 	struct nfsclient *clp, *nclp;
1070 	struct nfsstate *stp, *nstp;
1071 	int got_ref, i;
1072 
1073 	/*
1074 	 * Make sure nfsboottime is set. This is used by V3 as well
1075 	 * as V4. Note that nfsboottime is not nfsrvboottime, which is
1076 	 * only used by the V4 server for leases.
1077 	 */
1078 	if (nfsboottime.tv_sec == 0)
1079 		NFSSETBOOTTIME(nfsboottime);
1080 
1081 	/*
1082 	 * If server hasn't started yet, just return.
1083 	 */
1084 	NFSLOCKSTATE();
1085 	if (nfsrv_stablefirst.nsf_eograce == 0) {
1086 		NFSUNLOCKSTATE();
1087 		return;
1088 	}
1089 	if (!(nfsrv_stablefirst.nsf_flags & NFSNSF_UPDATEDONE)) {
1090 		if (!(nfsrv_stablefirst.nsf_flags & NFSNSF_GRACEOVER) &&
1091 		    NFSD_MONOSEC > nfsrv_stablefirst.nsf_eograce)
1092 			nfsrv_stablefirst.nsf_flags |=
1093 			    (NFSNSF_GRACEOVER | NFSNSF_NEEDLOCK);
1094 		NFSUNLOCKSTATE();
1095 		return;
1096 	}
1097 
1098 	/*
1099 	 * Try and get a reference count on the nfsv4rootfs_lock so that
1100 	 * no nfsd thread can acquire an exclusive lock on it before this
1101 	 * call is done. If it is already exclusively locked, just return.
1102 	 */
1103 	NFSLOCKV4ROOTMUTEX();
1104 	got_ref = nfsv4_getref_nonblock(&nfsv4rootfs_lock);
1105 	NFSUNLOCKV4ROOTMUTEX();
1106 	if (got_ref == 0) {
1107 		NFSUNLOCKSTATE();
1108 		return;
1109 	}
1110 
1111 	/*
1112 	 * For each client...
1113 	 */
1114 	for (i = 0; i < nfsrv_clienthashsize; i++) {
1115 	    clp = LIST_FIRST(&nfsclienthash[i]);
1116 	    while (clp != LIST_END(&nfsclienthash[i])) {
1117 		nclp = LIST_NEXT(clp, lc_hash);
1118 		if (!(clp->lc_flags & LCL_EXPIREIT)) {
1119 		    if (((clp->lc_expiry + NFSRV_STALELEASE) < NFSD_MONOSEC
1120 			 && ((LIST_EMPTY(&clp->lc_deleg)
1121 			      && LIST_EMPTY(&clp->lc_open)) ||
1122 			     nfsrv_clients > nfsrv_clienthighwater)) ||
1123 			(clp->lc_expiry + NFSRV_MOULDYLEASE) < NFSD_MONOSEC ||
1124 			(clp->lc_expiry < NFSD_MONOSEC &&
1125 			 (nfsrv_openpluslock * 10 / 9) > nfsrv_v4statelimit)) {
1126 			/*
1127 			 * Lease has expired several nfsrv_lease times ago:
1128 			 * PLUS
1129 			 *    - no state is associated with it
1130 			 *    OR
1131 			 *    - above high water mark for number of clients
1132 			 *      (nfsrv_clienthighwater should be large enough
1133 			 *       that this only occurs when clients fail to
1134 			 *       use the same nfs_client_id4.id. Maybe somewhat
1135 			 *       higher that the maximum number of clients that
1136 			 *       will mount this server?)
1137 			 * OR
1138 			 * Lease has expired a very long time ago
1139 			 * OR
1140 			 * Lease has expired PLUS the number of opens + locks
1141 			 * has exceeded 90% of capacity
1142 			 *
1143 			 * --> Mark for expiry. The actual expiry will be done
1144 			 *     by an nfsd sometime soon.
1145 			 */
1146 			clp->lc_flags |= LCL_EXPIREIT;
1147 			nfsrv_stablefirst.nsf_flags |=
1148 			    (NFSNSF_NEEDLOCK | NFSNSF_EXPIREDCLIENT);
1149 		    } else {
1150 			/*
1151 			 * If there are no opens, increment no open tick cnt
1152 			 * If time exceeds NFSNOOPEN, mark it to be thrown away
1153 			 * otherwise, if there is an open, reset no open time
1154 			 * Hopefully, this will avoid excessive re-creation
1155 			 * of open owners and subsequent open confirms.
1156 			 */
1157 			stp = LIST_FIRST(&clp->lc_open);
1158 			while (stp != LIST_END(&clp->lc_open)) {
1159 				nstp = LIST_NEXT(stp, ls_list);
1160 				if (LIST_EMPTY(&stp->ls_open)) {
1161 					stp->ls_noopens++;
1162 					if (stp->ls_noopens > NFSNOOPEN ||
1163 					    (nfsrv_openpluslock * 2) >
1164 					    nfsrv_v4statelimit)
1165 						nfsrv_stablefirst.nsf_flags |=
1166 							NFSNSF_NOOPENS;
1167 				} else {
1168 					stp->ls_noopens = 0;
1169 				}
1170 				stp = nstp;
1171 			}
1172 		    }
1173 		}
1174 		clp = nclp;
1175 	    }
1176 	}
1177 	NFSUNLOCKSTATE();
1178 	NFSLOCKV4ROOTMUTEX();
1179 	nfsv4_relref(&nfsv4rootfs_lock);
1180 	NFSUNLOCKV4ROOTMUTEX();
1181 }
1182 
1183 /*
1184  * The following set of functions free up the various data structures.
1185  */
1186 /*
1187  * Clear out all open/lock state related to this nfsclient.
1188  * Caller must hold an exclusive lock on nfsv4rootfs_lock, so that
1189  * there are no other active nfsd threads.
1190  */
1191 APPLESTATIC void
1192 nfsrv_cleanclient(struct nfsclient *clp, NFSPROC_T *p)
1193 {
1194 	struct nfsstate *stp, *nstp;
1195 	struct nfsdsession *sep, *nsep;
1196 
1197 	LIST_FOREACH_SAFE(stp, &clp->lc_open, ls_list, nstp)
1198 		nfsrv_freeopenowner(stp, 1, p);
1199 	if ((clp->lc_flags & LCL_ADMINREVOKED) == 0)
1200 		LIST_FOREACH_SAFE(sep, &clp->lc_session, sess_list, nsep)
1201 			(void)nfsrv_freesession(sep, NULL);
1202 }
1203 
1204 /*
1205  * Free a client that has been cleaned. It should also already have been
1206  * removed from the lists.
1207  * (Just to be safe w.r.t. newnfs_disconnect(), call this function when
1208  *  softclock interrupts are enabled.)
1209  */
1210 APPLESTATIC void
1211 nfsrv_zapclient(struct nfsclient *clp, NFSPROC_T *p)
1212 {
1213 
1214 #ifdef notyet
1215 	if ((clp->lc_flags & (LCL_GSS | LCL_CALLBACKSON)) ==
1216 	     (LCL_GSS | LCL_CALLBACKSON) &&
1217 	    (clp->lc_hand.nfsh_flag & NFSG_COMPLETE) &&
1218 	    clp->lc_handlelen > 0) {
1219 		clp->lc_hand.nfsh_flag &= ~NFSG_COMPLETE;
1220 		clp->lc_hand.nfsh_flag |= NFSG_DESTROYED;
1221 		(void) nfsrv_docallback(clp, NFSV4PROC_CBNULL,
1222 			NULL, 0, NULL, NULL, NULL, p);
1223 	}
1224 #endif
1225 	newnfs_disconnect(&clp->lc_req);
1226 	NFSSOCKADDRFREE(clp->lc_req.nr_nam);
1227 	NFSFREEMUTEX(&clp->lc_req.nr_mtx);
1228 	free(clp->lc_stateid, M_NFSDCLIENT);
1229 	free(clp, M_NFSDCLIENT);
1230 	NFSLOCKSTATE();
1231 	nfsstatsv1.srvclients--;
1232 	nfsrv_openpluslock--;
1233 	nfsrv_clients--;
1234 	NFSUNLOCKSTATE();
1235 }
1236 
1237 /*
1238  * Free a list of delegation state structures.
1239  * (This function will also free all nfslockfile structures that no
1240  *  longer have associated state.)
1241  */
1242 APPLESTATIC void
1243 nfsrv_freedeleglist(struct nfsstatehead *sthp)
1244 {
1245 	struct nfsstate *stp, *nstp;
1246 
1247 	LIST_FOREACH_SAFE(stp, sthp, ls_list, nstp) {
1248 		nfsrv_freedeleg(stp);
1249 	}
1250 	LIST_INIT(sthp);
1251 }
1252 
1253 /*
1254  * Free up a delegation.
1255  */
1256 static void
1257 nfsrv_freedeleg(struct nfsstate *stp)
1258 {
1259 	struct nfslockfile *lfp;
1260 
1261 	LIST_REMOVE(stp, ls_hash);
1262 	LIST_REMOVE(stp, ls_list);
1263 	LIST_REMOVE(stp, ls_file);
1264 	lfp = stp->ls_lfp;
1265 	if (LIST_EMPTY(&lfp->lf_open) &&
1266 	    LIST_EMPTY(&lfp->lf_lock) && LIST_EMPTY(&lfp->lf_deleg) &&
1267 	    LIST_EMPTY(&lfp->lf_locallock) && LIST_EMPTY(&lfp->lf_rollback) &&
1268 	    lfp->lf_usecount == 0 &&
1269 	    nfsv4_testlock(&lfp->lf_locallock_lck) == 0)
1270 		nfsrv_freenfslockfile(lfp);
1271 	FREE((caddr_t)stp, M_NFSDSTATE);
1272 	nfsstatsv1.srvdelegates--;
1273 	nfsrv_openpluslock--;
1274 	nfsrv_delegatecnt--;
1275 }
1276 
1277 /*
1278  * This function frees an open owner and all associated opens.
1279  */
1280 static void
1281 nfsrv_freeopenowner(struct nfsstate *stp, int cansleep, NFSPROC_T *p)
1282 {
1283 	struct nfsstate *nstp, *tstp;
1284 
1285 	LIST_REMOVE(stp, ls_list);
1286 	/*
1287 	 * Now, free all associated opens.
1288 	 */
1289 	nstp = LIST_FIRST(&stp->ls_open);
1290 	while (nstp != LIST_END(&stp->ls_open)) {
1291 		tstp = nstp;
1292 		nstp = LIST_NEXT(nstp, ls_list);
1293 		(void) nfsrv_freeopen(tstp, NULL, cansleep, p);
1294 	}
1295 	if (stp->ls_op)
1296 		nfsrvd_derefcache(stp->ls_op);
1297 	FREE((caddr_t)stp, M_NFSDSTATE);
1298 	nfsstatsv1.srvopenowners--;
1299 	nfsrv_openpluslock--;
1300 }
1301 
1302 /*
1303  * This function frees an open (nfsstate open structure) with all associated
1304  * lock_owners and locks. It also frees the nfslockfile structure iff there
1305  * are no other opens on the file.
1306  * Returns 1 if it free'd the nfslockfile, 0 otherwise.
1307  */
1308 static int
1309 nfsrv_freeopen(struct nfsstate *stp, vnode_t vp, int cansleep, NFSPROC_T *p)
1310 {
1311 	struct nfsstate *nstp, *tstp;
1312 	struct nfslockfile *lfp;
1313 	int ret;
1314 
1315 	LIST_REMOVE(stp, ls_hash);
1316 	LIST_REMOVE(stp, ls_list);
1317 	LIST_REMOVE(stp, ls_file);
1318 
1319 	lfp = stp->ls_lfp;
1320 	/*
1321 	 * Now, free all lockowners associated with this open.
1322 	 */
1323 	LIST_FOREACH_SAFE(tstp, &stp->ls_open, ls_list, nstp)
1324 		nfsrv_freelockowner(tstp, vp, cansleep, p);
1325 
1326 	/*
1327 	 * The nfslockfile is freed here if there are no locks
1328 	 * associated with the open.
1329 	 * If there are locks associated with the open, the
1330 	 * nfslockfile structure can be freed via nfsrv_freelockowner().
1331 	 * Acquire the state mutex to avoid races with calls to
1332 	 * nfsrv_getlockfile().
1333 	 */
1334 	if (cansleep != 0)
1335 		NFSLOCKSTATE();
1336 	if (lfp != NULL && LIST_EMPTY(&lfp->lf_open) &&
1337 	    LIST_EMPTY(&lfp->lf_deleg) && LIST_EMPTY(&lfp->lf_lock) &&
1338 	    LIST_EMPTY(&lfp->lf_locallock) && LIST_EMPTY(&lfp->lf_rollback) &&
1339 	    lfp->lf_usecount == 0 &&
1340 	    (cansleep != 0 || nfsv4_testlock(&lfp->lf_locallock_lck) == 0)) {
1341 		nfsrv_freenfslockfile(lfp);
1342 		ret = 1;
1343 	} else
1344 		ret = 0;
1345 	if (cansleep != 0)
1346 		NFSUNLOCKSTATE();
1347 	FREE((caddr_t)stp, M_NFSDSTATE);
1348 	nfsstatsv1.srvopens--;
1349 	nfsrv_openpluslock--;
1350 	return (ret);
1351 }
1352 
1353 /*
1354  * Frees a lockowner and all associated locks.
1355  */
1356 static void
1357 nfsrv_freelockowner(struct nfsstate *stp, vnode_t vp, int cansleep,
1358     NFSPROC_T *p)
1359 {
1360 
1361 	LIST_REMOVE(stp, ls_hash);
1362 	LIST_REMOVE(stp, ls_list);
1363 	nfsrv_freeallnfslocks(stp, vp, cansleep, p);
1364 	if (stp->ls_op)
1365 		nfsrvd_derefcache(stp->ls_op);
1366 	FREE((caddr_t)stp, M_NFSDSTATE);
1367 	nfsstatsv1.srvlockowners--;
1368 	nfsrv_openpluslock--;
1369 }
1370 
1371 /*
1372  * Free all the nfs locks on a lockowner.
1373  */
1374 static void
1375 nfsrv_freeallnfslocks(struct nfsstate *stp, vnode_t vp, int cansleep,
1376     NFSPROC_T *p)
1377 {
1378 	struct nfslock *lop, *nlop;
1379 	struct nfsrollback *rlp, *nrlp;
1380 	struct nfslockfile *lfp = NULL;
1381 	int gottvp = 0;
1382 	vnode_t tvp = NULL;
1383 	uint64_t first, end;
1384 
1385 	if (vp != NULL)
1386 		ASSERT_VOP_UNLOCKED(vp, "nfsrv_freeallnfslocks: vnode locked");
1387 	lop = LIST_FIRST(&stp->ls_lock);
1388 	while (lop != LIST_END(&stp->ls_lock)) {
1389 		nlop = LIST_NEXT(lop, lo_lckowner);
1390 		/*
1391 		 * Since all locks should be for the same file, lfp should
1392 		 * not change.
1393 		 */
1394 		if (lfp == NULL)
1395 			lfp = lop->lo_lfp;
1396 		else if (lfp != lop->lo_lfp)
1397 			panic("allnfslocks");
1398 		/*
1399 		 * If vp is NULL and cansleep != 0, a vnode must be acquired
1400 		 * from the file handle. This only occurs when called from
1401 		 * nfsrv_cleanclient().
1402 		 */
1403 		if (gottvp == 0) {
1404 			if (nfsrv_dolocallocks == 0)
1405 				tvp = NULL;
1406 			else if (vp == NULL && cansleep != 0) {
1407 				tvp = nfsvno_getvp(&lfp->lf_fh);
1408 				NFSVOPUNLOCK(tvp, 0);
1409 			} else
1410 				tvp = vp;
1411 			gottvp = 1;
1412 		}
1413 
1414 		if (tvp != NULL) {
1415 			if (cansleep == 0)
1416 				panic("allnfs2");
1417 			first = lop->lo_first;
1418 			end = lop->lo_end;
1419 			nfsrv_freenfslock(lop);
1420 			nfsrv_localunlock(tvp, lfp, first, end, p);
1421 			LIST_FOREACH_SAFE(rlp, &lfp->lf_rollback, rlck_list,
1422 			    nrlp)
1423 				free(rlp, M_NFSDROLLBACK);
1424 			LIST_INIT(&lfp->lf_rollback);
1425 		} else
1426 			nfsrv_freenfslock(lop);
1427 		lop = nlop;
1428 	}
1429 	if (vp == NULL && tvp != NULL)
1430 		vrele(tvp);
1431 }
1432 
1433 /*
1434  * Free an nfslock structure.
1435  */
1436 static void
1437 nfsrv_freenfslock(struct nfslock *lop)
1438 {
1439 
1440 	if (lop->lo_lckfile.le_prev != NULL) {
1441 		LIST_REMOVE(lop, lo_lckfile);
1442 		nfsstatsv1.srvlocks--;
1443 		nfsrv_openpluslock--;
1444 	}
1445 	LIST_REMOVE(lop, lo_lckowner);
1446 	FREE((caddr_t)lop, M_NFSDLOCK);
1447 }
1448 
1449 /*
1450  * This function frees an nfslockfile structure.
1451  */
1452 static void
1453 nfsrv_freenfslockfile(struct nfslockfile *lfp)
1454 {
1455 
1456 	LIST_REMOVE(lfp, lf_hash);
1457 	FREE((caddr_t)lfp, M_NFSDLOCKFILE);
1458 }
1459 
1460 /*
1461  * This function looks up an nfsstate structure via stateid.
1462  */
1463 static int
1464 nfsrv_getstate(struct nfsclient *clp, nfsv4stateid_t *stateidp, __unused u_int32_t flags,
1465     struct nfsstate **stpp)
1466 {
1467 	struct nfsstate *stp;
1468 	struct nfsstatehead *hp;
1469 	int error = 0;
1470 
1471 	*stpp = NULL;
1472 	hp = NFSSTATEHASH(clp, *stateidp);
1473 	LIST_FOREACH(stp, hp, ls_hash) {
1474 		if (!NFSBCMP(stp->ls_stateid.other, stateidp->other,
1475 			NFSX_STATEIDOTHER))
1476 			break;
1477 	}
1478 
1479 	/*
1480 	 * If no state id in list, return NFSERR_BADSTATEID.
1481 	 */
1482 	if (stp == LIST_END(hp)) {
1483 		error = NFSERR_BADSTATEID;
1484 		goto out;
1485 	}
1486 	*stpp = stp;
1487 
1488 out:
1489 	NFSEXITCODE(error);
1490 	return (error);
1491 }
1492 
1493 /*
1494  * This function gets an nfsstate structure via owner string.
1495  */
1496 static void
1497 nfsrv_getowner(struct nfsstatehead *hp, struct nfsstate *new_stp,
1498     struct nfsstate **stpp)
1499 {
1500 	struct nfsstate *stp;
1501 
1502 	*stpp = NULL;
1503 	LIST_FOREACH(stp, hp, ls_list) {
1504 		if (new_stp->ls_ownerlen == stp->ls_ownerlen &&
1505 		  !NFSBCMP(new_stp->ls_owner,stp->ls_owner,stp->ls_ownerlen)) {
1506 			*stpp = stp;
1507 			return;
1508 		}
1509 	}
1510 }
1511 
1512 /*
1513  * Lock control function called to update lock status.
1514  * Returns 0 upon success, -1 if there is no lock and the flags indicate
1515  * that one isn't to be created and an NFSERR_xxx for other errors.
1516  * The structures new_stp and new_lop are passed in as pointers that should
1517  * be set to NULL if the structure is used and shouldn't be free'd.
1518  * For the NFSLCK_TEST and NFSLCK_CHECK cases, the structures are
1519  * never used and can safely be allocated on the stack. For all other
1520  * cases, *new_stpp and *new_lopp should be malloc'd before the call,
1521  * in case they are used.
1522  */
1523 APPLESTATIC int
1524 nfsrv_lockctrl(vnode_t vp, struct nfsstate **new_stpp,
1525     struct nfslock **new_lopp, struct nfslockconflict *cfp,
1526     nfsquad_t clientid, nfsv4stateid_t *stateidp,
1527     __unused struct nfsexstuff *exp,
1528     struct nfsrv_descript *nd, NFSPROC_T *p)
1529 {
1530 	struct nfslock *lop;
1531 	struct nfsstate *new_stp = *new_stpp;
1532 	struct nfslock *new_lop = *new_lopp;
1533 	struct nfsstate *tstp, *mystp, *nstp;
1534 	int specialid = 0;
1535 	struct nfslockfile *lfp;
1536 	struct nfslock *other_lop = NULL;
1537 	struct nfsstate *stp, *lckstp = NULL;
1538 	struct nfsclient *clp = NULL;
1539 	u_int32_t bits;
1540 	int error = 0, haslock = 0, ret, reterr;
1541 	int getlckret, delegation = 0, filestruct_locked, vnode_unlocked = 0;
1542 	fhandle_t nfh;
1543 	uint64_t first, end;
1544 	uint32_t lock_flags;
1545 
1546 	if (new_stp->ls_flags & (NFSLCK_CHECK | NFSLCK_SETATTR)) {
1547 		/*
1548 		 * Note the special cases of "all 1s" or "all 0s" stateids and
1549 		 * let reads with all 1s go ahead.
1550 		 */
1551 		if (new_stp->ls_stateid.seqid == 0x0 &&
1552 		    new_stp->ls_stateid.other[0] == 0x0 &&
1553 		    new_stp->ls_stateid.other[1] == 0x0 &&
1554 		    new_stp->ls_stateid.other[2] == 0x0)
1555 			specialid = 1;
1556 		else if (new_stp->ls_stateid.seqid == 0xffffffff &&
1557 		    new_stp->ls_stateid.other[0] == 0xffffffff &&
1558 		    new_stp->ls_stateid.other[1] == 0xffffffff &&
1559 		    new_stp->ls_stateid.other[2] == 0xffffffff)
1560 			specialid = 2;
1561 	}
1562 
1563 	/*
1564 	 * Check for restart conditions (client and server).
1565 	 */
1566 	error = nfsrv_checkrestart(clientid, new_stp->ls_flags,
1567 	    &new_stp->ls_stateid, specialid);
1568 	if (error)
1569 		goto out;
1570 
1571 	/*
1572 	 * Check for state resource limit exceeded.
1573 	 */
1574 	if ((new_stp->ls_flags & NFSLCK_LOCK) &&
1575 	    nfsrv_openpluslock > nfsrv_v4statelimit) {
1576 		error = NFSERR_RESOURCE;
1577 		goto out;
1578 	}
1579 
1580 	/*
1581 	 * For the lock case, get another nfslock structure,
1582 	 * just in case we need it.
1583 	 * Malloc now, before we start sifting through the linked lists,
1584 	 * in case we have to wait for memory.
1585 	 */
1586 tryagain:
1587 	if (new_stp->ls_flags & NFSLCK_LOCK)
1588 		MALLOC(other_lop, struct nfslock *, sizeof (struct nfslock),
1589 		    M_NFSDLOCK, M_WAITOK);
1590 	filestruct_locked = 0;
1591 	reterr = 0;
1592 	lfp = NULL;
1593 
1594 	/*
1595 	 * Get the lockfile structure for CFH now, so we can do a sanity
1596 	 * check against the stateid, before incrementing the seqid#, since
1597 	 * we want to return NFSERR_BADSTATEID on failure and the seqid#
1598 	 * shouldn't be incremented for this case.
1599 	 * If nfsrv_getlockfile() returns -1, it means "not found", which
1600 	 * will be handled later.
1601 	 * If we are doing Lock/LockU and local locking is enabled, sleep
1602 	 * lock the nfslockfile structure.
1603 	 */
1604 	getlckret = nfsrv_getlockfh(vp, new_stp->ls_flags, NULL, &nfh, p);
1605 	NFSLOCKSTATE();
1606 	if (getlckret == 0) {
1607 		if ((new_stp->ls_flags & (NFSLCK_LOCK | NFSLCK_UNLOCK)) != 0 &&
1608 		    nfsrv_dolocallocks != 0 && nd->nd_repstat == 0) {
1609 			getlckret = nfsrv_getlockfile(new_stp->ls_flags, NULL,
1610 			    &lfp, &nfh, 1);
1611 			if (getlckret == 0)
1612 				filestruct_locked = 1;
1613 		} else
1614 			getlckret = nfsrv_getlockfile(new_stp->ls_flags, NULL,
1615 			    &lfp, &nfh, 0);
1616 	}
1617 	if (getlckret != 0 && getlckret != -1)
1618 		reterr = getlckret;
1619 
1620 	if (filestruct_locked != 0) {
1621 		LIST_INIT(&lfp->lf_rollback);
1622 		if ((new_stp->ls_flags & NFSLCK_LOCK)) {
1623 			/*
1624 			 * For local locking, do the advisory locking now, so
1625 			 * that any conflict can be detected. A failure later
1626 			 * can be rolled back locally. If an error is returned,
1627 			 * struct nfslockfile has been unlocked and any local
1628 			 * locking rolled back.
1629 			 */
1630 			NFSUNLOCKSTATE();
1631 			if (vnode_unlocked == 0) {
1632 				ASSERT_VOP_ELOCKED(vp, "nfsrv_lockctrl1");
1633 				vnode_unlocked = 1;
1634 				NFSVOPUNLOCK(vp, 0);
1635 			}
1636 			reterr = nfsrv_locallock(vp, lfp,
1637 			    (new_lop->lo_flags & (NFSLCK_READ | NFSLCK_WRITE)),
1638 			    new_lop->lo_first, new_lop->lo_end, cfp, p);
1639 			NFSLOCKSTATE();
1640 		}
1641 	}
1642 
1643 	if (specialid == 0) {
1644 	    if (new_stp->ls_flags & NFSLCK_TEST) {
1645 		/*
1646 		 * RFC 3530 does not list LockT as an op that renews a
1647 		 * lease, but the consensus seems to be that it is ok
1648 		 * for a server to do so.
1649 		 */
1650 		error = nfsrv_getclient(clientid, CLOPS_RENEW, &clp, NULL,
1651 		    (nfsquad_t)((u_quad_t)0), 0, nd, p);
1652 
1653 		/*
1654 		 * Since NFSERR_EXPIRED, NFSERR_ADMINREVOKED are not valid
1655 		 * error returns for LockT, just go ahead and test for a lock,
1656 		 * since there are no locks for this client, but other locks
1657 		 * can conflict. (ie. same client will always be false)
1658 		 */
1659 		if (error == NFSERR_EXPIRED || error == NFSERR_ADMINREVOKED)
1660 		    error = 0;
1661 		lckstp = new_stp;
1662 	    } else {
1663 	      error = nfsrv_getclient(clientid, CLOPS_RENEW, &clp, NULL,
1664 		(nfsquad_t)((u_quad_t)0), 0, nd, p);
1665 	      if (error == 0)
1666 		/*
1667 		 * Look up the stateid
1668 		 */
1669 		error = nfsrv_getstate(clp, &new_stp->ls_stateid,
1670 		  new_stp->ls_flags, &stp);
1671 	      /*
1672 	       * do some sanity checks for an unconfirmed open or a
1673 	       * stateid that refers to the wrong file, for an open stateid
1674 	       */
1675 	      if (error == 0 && (stp->ls_flags & NFSLCK_OPEN) &&
1676 		  ((stp->ls_openowner->ls_flags & NFSLCK_NEEDSCONFIRM) ||
1677 		   (getlckret == 0 && stp->ls_lfp != lfp))){
1678 		      /*
1679 		       * NFSLCK_SETATTR should return OK rather than NFSERR_BADSTATEID
1680 		       * The only exception is using SETATTR with SIZE.
1681 		       * */
1682                     if ((new_stp->ls_flags &
1683                          (NFSLCK_SETATTR | NFSLCK_CHECK)) != NFSLCK_SETATTR)
1684 			     error = NFSERR_BADSTATEID;
1685 	      }
1686 
1687 		if (error == 0 &&
1688 		  (stp->ls_flags & (NFSLCK_DELEGREAD | NFSLCK_DELEGWRITE)) &&
1689 		  getlckret == 0 && stp->ls_lfp != lfp)
1690 			error = NFSERR_BADSTATEID;
1691 
1692 	      /*
1693 	       * If the lockowner stateid doesn't refer to the same file,
1694 	       * I believe that is considered ok, since some clients will
1695 	       * only create a single lockowner and use that for all locks
1696 	       * on all files.
1697 	       * For now, log it as a diagnostic, instead of considering it
1698 	       * a BadStateid.
1699 	       */
1700 	      if (error == 0 && (stp->ls_flags &
1701 		  (NFSLCK_OPEN | NFSLCK_DELEGREAD | NFSLCK_DELEGWRITE)) == 0 &&
1702 		  getlckret == 0 && stp->ls_lfp != lfp) {
1703 #ifdef DIAGNOSTIC
1704 		  printf("Got a lock statid for different file open\n");
1705 #endif
1706 		  /*
1707 		  error = NFSERR_BADSTATEID;
1708 		  */
1709 	      }
1710 
1711 	      if (error == 0) {
1712 		    if (new_stp->ls_flags & NFSLCK_OPENTOLOCK) {
1713 			/*
1714 			 * If haslock set, we've already checked the seqid.
1715 			 */
1716 			if (!haslock) {
1717 			    if (stp->ls_flags & NFSLCK_OPEN)
1718 				error = nfsrv_checkseqid(nd, new_stp->ls_seq,
1719 				    stp->ls_openowner, new_stp->ls_op);
1720 			    else
1721 				error = NFSERR_BADSTATEID;
1722 			}
1723 			if (!error)
1724 			    nfsrv_getowner(&stp->ls_open, new_stp, &lckstp);
1725 			if (lckstp)
1726 			    /*
1727 			     * I believe this should be an error, but it
1728 			     * isn't obvious what NFSERR_xxx would be
1729 			     * appropriate, so I'll use NFSERR_INVAL for now.
1730 			     */
1731 			    error = NFSERR_INVAL;
1732 			else
1733 			    lckstp = new_stp;
1734 		    } else if (new_stp->ls_flags&(NFSLCK_LOCK|NFSLCK_UNLOCK)) {
1735 			/*
1736 			 * If haslock set, ditto above.
1737 			 */
1738 			if (!haslock) {
1739 			    if (stp->ls_flags & NFSLCK_OPEN)
1740 				error = NFSERR_BADSTATEID;
1741 			    else
1742 				error = nfsrv_checkseqid(nd, new_stp->ls_seq,
1743 				    stp, new_stp->ls_op);
1744 			}
1745 			lckstp = stp;
1746 		    } else {
1747 			lckstp = stp;
1748 		    }
1749 	      }
1750 	      /*
1751 	       * If the seqid part of the stateid isn't the same, return
1752 	       * NFSERR_OLDSTATEID for cases other than I/O Ops.
1753 	       * For I/O Ops, only return NFSERR_OLDSTATEID if
1754 	       * nfsrv_returnoldstateid is set. (The consensus on the email
1755 	       * list was that most clients would prefer to not receive
1756 	       * NFSERR_OLDSTATEID for I/O Ops, but the RFC suggests that that
1757 	       * is what will happen, so I use the nfsrv_returnoldstateid to
1758 	       * allow for either server configuration.)
1759 	       */
1760 	      if (!error && stp->ls_stateid.seqid!=new_stp->ls_stateid.seqid &&
1761 		  (((nd->nd_flag & ND_NFSV41) == 0 &&
1762 		   (!(new_stp->ls_flags & NFSLCK_CHECK) ||
1763 		    nfsrv_returnoldstateid)) ||
1764 		   ((nd->nd_flag & ND_NFSV41) != 0 &&
1765 		    new_stp->ls_stateid.seqid != 0)))
1766 		    error = NFSERR_OLDSTATEID;
1767 	    }
1768 	}
1769 
1770 	/*
1771 	 * Now we can check for grace.
1772 	 */
1773 	if (!error)
1774 		error = nfsrv_checkgrace(nd, clp, new_stp->ls_flags);
1775 	if ((new_stp->ls_flags & NFSLCK_RECLAIM) && !error &&
1776 		nfsrv_checkstable(clp))
1777 		error = NFSERR_NOGRACE;
1778 	/*
1779 	 * If we successfully Reclaimed state, note that.
1780 	 */
1781 	if ((new_stp->ls_flags & NFSLCK_RECLAIM) && !error)
1782 		nfsrv_markstable(clp);
1783 
1784 	/*
1785 	 * At this point, either error == NFSERR_BADSTATEID or the
1786 	 * seqid# has been updated, so we can return any error.
1787 	 * If error == 0, there may be an error in:
1788 	 *    nd_repstat - Set by the calling function.
1789 	 *    reterr - Set above, if getting the nfslockfile structure
1790 	 *       or acquiring the local lock failed.
1791 	 *    (If both of these are set, nd_repstat should probably be
1792 	 *     returned, since that error was detected before this
1793 	 *     function call.)
1794 	 */
1795 	if (error != 0 || nd->nd_repstat != 0 || reterr != 0) {
1796 		if (error == 0) {
1797 			if (nd->nd_repstat != 0)
1798 				error = nd->nd_repstat;
1799 			else
1800 				error = reterr;
1801 		}
1802 		if (filestruct_locked != 0) {
1803 			/* Roll back local locks. */
1804 			NFSUNLOCKSTATE();
1805 			if (vnode_unlocked == 0) {
1806 				ASSERT_VOP_ELOCKED(vp, "nfsrv_lockctrl2");
1807 				vnode_unlocked = 1;
1808 				NFSVOPUNLOCK(vp, 0);
1809 			}
1810 			nfsrv_locallock_rollback(vp, lfp, p);
1811 			NFSLOCKSTATE();
1812 			nfsrv_unlocklf(lfp);
1813 		}
1814 		NFSUNLOCKSTATE();
1815 		goto out;
1816 	}
1817 
1818 	/*
1819 	 * Check the nfsrv_getlockfile return.
1820 	 * Returned -1 if no structure found.
1821 	 */
1822 	if (getlckret == -1) {
1823 		error = NFSERR_EXPIRED;
1824 		/*
1825 		 * Called from lockt, so no lock is OK.
1826 		 */
1827 		if (new_stp->ls_flags & NFSLCK_TEST) {
1828 			error = 0;
1829 		} else if (new_stp->ls_flags &
1830 		    (NFSLCK_CHECK | NFSLCK_SETATTR)) {
1831 			/*
1832 			 * Called to check for a lock, OK if the stateid is all
1833 			 * 1s or all 0s, but there should be an nfsstate
1834 			 * otherwise.
1835 			 * (ie. If there is no open, I'll assume no share
1836 			 *  deny bits.)
1837 			 */
1838 			if (specialid)
1839 				error = 0;
1840 			else
1841 				error = NFSERR_BADSTATEID;
1842 		}
1843 		NFSUNLOCKSTATE();
1844 		goto out;
1845 	}
1846 
1847 	/*
1848 	 * For NFSLCK_CHECK and NFSLCK_LOCK, test for a share conflict.
1849 	 * For NFSLCK_CHECK, allow a read if write access is granted,
1850 	 * but check for a deny. For NFSLCK_LOCK, require correct access,
1851 	 * which implies a conflicting deny can't exist.
1852 	 */
1853 	if (new_stp->ls_flags & (NFSLCK_CHECK | NFSLCK_LOCK)) {
1854 	    /*
1855 	     * Four kinds of state id:
1856 	     * - specialid (all 0s or all 1s), only for NFSLCK_CHECK
1857 	     * - stateid for an open
1858 	     * - stateid for a delegation
1859 	     * - stateid for a lock owner
1860 	     */
1861 	    if (!specialid) {
1862 		if (stp->ls_flags & (NFSLCK_DELEGREAD | NFSLCK_DELEGWRITE)) {
1863 		    delegation = 1;
1864 		    mystp = stp;
1865 		    nfsrv_delaydelegtimeout(stp);
1866 	        } else if (stp->ls_flags & NFSLCK_OPEN) {
1867 		    mystp = stp;
1868 		} else {
1869 		    mystp = stp->ls_openstp;
1870 		}
1871 		/*
1872 		 * If locking or checking, require correct access
1873 		 * bit set.
1874 		 */
1875 		if (((new_stp->ls_flags & NFSLCK_LOCK) &&
1876 		     !((new_lop->lo_flags >> NFSLCK_LOCKSHIFT) &
1877 		       mystp->ls_flags & NFSLCK_ACCESSBITS)) ||
1878 		    ((new_stp->ls_flags & (NFSLCK_CHECK|NFSLCK_READACCESS)) ==
1879 		      (NFSLCK_CHECK | NFSLCK_READACCESS) &&
1880 		     !(mystp->ls_flags & NFSLCK_READACCESS) &&
1881 		     nfsrv_allowreadforwriteopen == 0) ||
1882 		    ((new_stp->ls_flags & (NFSLCK_CHECK|NFSLCK_WRITEACCESS)) ==
1883 		      (NFSLCK_CHECK | NFSLCK_WRITEACCESS) &&
1884 		     !(mystp->ls_flags & NFSLCK_WRITEACCESS))) {
1885 			if (filestruct_locked != 0) {
1886 				/* Roll back local locks. */
1887 				NFSUNLOCKSTATE();
1888 				if (vnode_unlocked == 0) {
1889 					ASSERT_VOP_ELOCKED(vp,
1890 					    "nfsrv_lockctrl3");
1891 					vnode_unlocked = 1;
1892 					NFSVOPUNLOCK(vp, 0);
1893 				}
1894 				nfsrv_locallock_rollback(vp, lfp, p);
1895 				NFSLOCKSTATE();
1896 				nfsrv_unlocklf(lfp);
1897 			}
1898 			NFSUNLOCKSTATE();
1899 			error = NFSERR_OPENMODE;
1900 			goto out;
1901 		}
1902 	    } else
1903 		mystp = NULL;
1904 	    if ((new_stp->ls_flags & NFSLCK_CHECK) && !delegation) {
1905 		/*
1906 		 * Check for a conflicting deny bit.
1907 		 */
1908 		LIST_FOREACH(tstp, &lfp->lf_open, ls_file) {
1909 		    if (tstp != mystp) {
1910 			bits = tstp->ls_flags;
1911 			bits >>= NFSLCK_SHIFT;
1912 			if (new_stp->ls_flags & bits & NFSLCK_ACCESSBITS) {
1913 			    KASSERT(vnode_unlocked == 0,
1914 				("nfsrv_lockctrl: vnode unlocked1"));
1915 			    ret = nfsrv_clientconflict(tstp->ls_clp, &haslock,
1916 				vp, p);
1917 			    if (ret == 1) {
1918 				/*
1919 				* nfsrv_clientconflict unlocks state
1920 				 * when it returns non-zero.
1921 				 */
1922 				lckstp = NULL;
1923 				goto tryagain;
1924 			    }
1925 			    if (ret == 0)
1926 				NFSUNLOCKSTATE();
1927 			    if (ret == 2)
1928 				error = NFSERR_PERM;
1929 			    else
1930 				error = NFSERR_OPENMODE;
1931 			    goto out;
1932 			}
1933 		    }
1934 		}
1935 
1936 		/* We're outta here */
1937 		NFSUNLOCKSTATE();
1938 		goto out;
1939 	    }
1940 	}
1941 
1942 	/*
1943 	 * For setattr, just get rid of all the Delegations for other clients.
1944 	 */
1945 	if (new_stp->ls_flags & NFSLCK_SETATTR) {
1946 		KASSERT(vnode_unlocked == 0,
1947 		    ("nfsrv_lockctrl: vnode unlocked2"));
1948 		ret = nfsrv_cleandeleg(vp, lfp, clp, &haslock, p);
1949 		if (ret) {
1950 			/*
1951 			 * nfsrv_cleandeleg() unlocks state when it
1952 			 * returns non-zero.
1953 			 */
1954 			if (ret == -1) {
1955 				lckstp = NULL;
1956 				goto tryagain;
1957 			}
1958 			error = ret;
1959 			goto out;
1960 		}
1961 		if (!(new_stp->ls_flags & NFSLCK_CHECK) ||
1962 		    (LIST_EMPTY(&lfp->lf_open) && LIST_EMPTY(&lfp->lf_lock) &&
1963 		     LIST_EMPTY(&lfp->lf_deleg))) {
1964 			NFSUNLOCKSTATE();
1965 			goto out;
1966 		}
1967 	}
1968 
1969 	/*
1970 	 * Check for a conflicting delegation. If one is found, call
1971 	 * nfsrv_delegconflict() to handle it. If the v4root lock hasn't
1972 	 * been set yet, it will get the lock. Otherwise, it will recall
1973 	 * the delegation. Then, we try try again...
1974 	 * I currently believe the conflict algorithm to be:
1975 	 * For Lock Ops (Lock/LockT/LockU)
1976 	 * - there is a conflict iff a different client has a write delegation
1977 	 * For Reading (Read Op)
1978 	 * - there is a conflict iff a different client has a write delegation
1979 	 *   (the specialids are always a different client)
1980 	 * For Writing (Write/Setattr of size)
1981 	 * - there is a conflict if a different client has any delegation
1982 	 * - there is a conflict if the same client has a read delegation
1983 	 *   (I don't understand why this isn't allowed, but that seems to be
1984 	 *    the current consensus?)
1985 	 */
1986 	tstp = LIST_FIRST(&lfp->lf_deleg);
1987 	while (tstp != LIST_END(&lfp->lf_deleg)) {
1988 	    nstp = LIST_NEXT(tstp, ls_file);
1989 	    if ((((new_stp->ls_flags&(NFSLCK_LOCK|NFSLCK_UNLOCK|NFSLCK_TEST))||
1990 		 ((new_stp->ls_flags & NFSLCK_CHECK) &&
1991 		  (new_lop->lo_flags & NFSLCK_READ))) &&
1992 		  clp != tstp->ls_clp &&
1993 		 (tstp->ls_flags & NFSLCK_DELEGWRITE)) ||
1994 		 ((new_stp->ls_flags & NFSLCK_CHECK) &&
1995 		   (new_lop->lo_flags & NFSLCK_WRITE) &&
1996 		  (clp != tstp->ls_clp ||
1997 		   (tstp->ls_flags & NFSLCK_DELEGREAD)))) {
1998 		ret = 0;
1999 		if (filestruct_locked != 0) {
2000 			/* Roll back local locks. */
2001 			NFSUNLOCKSTATE();
2002 			if (vnode_unlocked == 0) {
2003 				ASSERT_VOP_ELOCKED(vp, "nfsrv_lockctrl4");
2004 				NFSVOPUNLOCK(vp, 0);
2005 			}
2006 			nfsrv_locallock_rollback(vp, lfp, p);
2007 			NFSLOCKSTATE();
2008 			nfsrv_unlocklf(lfp);
2009 			NFSUNLOCKSTATE();
2010 			NFSVOPLOCK(vp, LK_EXCLUSIVE | LK_RETRY);
2011 			vnode_unlocked = 0;
2012 			if ((vp->v_iflag & VI_DOOMED) != 0)
2013 				ret = NFSERR_SERVERFAULT;
2014 			NFSLOCKSTATE();
2015 		}
2016 		if (ret == 0)
2017 			ret = nfsrv_delegconflict(tstp, &haslock, p, vp);
2018 		if (ret) {
2019 		    /*
2020 		     * nfsrv_delegconflict unlocks state when it
2021 		     * returns non-zero, which it always does.
2022 		     */
2023 		    if (other_lop) {
2024 			FREE((caddr_t)other_lop, M_NFSDLOCK);
2025 			other_lop = NULL;
2026 		    }
2027 		    if (ret == -1) {
2028 			lckstp = NULL;
2029 			goto tryagain;
2030 		    }
2031 		    error = ret;
2032 		    goto out;
2033 		}
2034 		/* Never gets here. */
2035 	    }
2036 	    tstp = nstp;
2037 	}
2038 
2039 	/*
2040 	 * Handle the unlock case by calling nfsrv_updatelock().
2041 	 * (Should I have done some access checking above for unlock? For now,
2042 	 *  just let it happen.)
2043 	 */
2044 	if (new_stp->ls_flags & NFSLCK_UNLOCK) {
2045 		first = new_lop->lo_first;
2046 		end = new_lop->lo_end;
2047 		nfsrv_updatelock(stp, new_lopp, &other_lop, lfp);
2048 		stateidp->seqid = ++(stp->ls_stateid.seqid);
2049 		if ((nd->nd_flag & ND_NFSV41) != 0 && stateidp->seqid == 0)
2050 			stateidp->seqid = stp->ls_stateid.seqid = 1;
2051 		stateidp->other[0] = stp->ls_stateid.other[0];
2052 		stateidp->other[1] = stp->ls_stateid.other[1];
2053 		stateidp->other[2] = stp->ls_stateid.other[2];
2054 		if (filestruct_locked != 0) {
2055 			NFSUNLOCKSTATE();
2056 			if (vnode_unlocked == 0) {
2057 				ASSERT_VOP_ELOCKED(vp, "nfsrv_lockctrl5");
2058 				vnode_unlocked = 1;
2059 				NFSVOPUNLOCK(vp, 0);
2060 			}
2061 			/* Update the local locks. */
2062 			nfsrv_localunlock(vp, lfp, first, end, p);
2063 			NFSLOCKSTATE();
2064 			nfsrv_unlocklf(lfp);
2065 		}
2066 		NFSUNLOCKSTATE();
2067 		goto out;
2068 	}
2069 
2070 	/*
2071 	 * Search for a conflicting lock. A lock conflicts if:
2072 	 * - the lock range overlaps and
2073 	 * - at least one lock is a write lock and
2074 	 * - it is not owned by the same lock owner
2075 	 */
2076 	if (!delegation) {
2077 	  LIST_FOREACH(lop, &lfp->lf_lock, lo_lckfile) {
2078 	    if (new_lop->lo_end > lop->lo_first &&
2079 		new_lop->lo_first < lop->lo_end &&
2080 		(new_lop->lo_flags == NFSLCK_WRITE ||
2081 		 lop->lo_flags == NFSLCK_WRITE) &&
2082 		lckstp != lop->lo_stp &&
2083 		(clp != lop->lo_stp->ls_clp ||
2084 		 lckstp->ls_ownerlen != lop->lo_stp->ls_ownerlen ||
2085 		 NFSBCMP(lckstp->ls_owner, lop->lo_stp->ls_owner,
2086 		    lckstp->ls_ownerlen))) {
2087 		if (other_lop) {
2088 		    FREE((caddr_t)other_lop, M_NFSDLOCK);
2089 		    other_lop = NULL;
2090 		}
2091 		if (vnode_unlocked != 0)
2092 		    ret = nfsrv_clientconflict(lop->lo_stp->ls_clp, &haslock,
2093 			NULL, p);
2094 		else
2095 		    ret = nfsrv_clientconflict(lop->lo_stp->ls_clp, &haslock,
2096 			vp, p);
2097 		if (ret == 1) {
2098 		    if (filestruct_locked != 0) {
2099 			if (vnode_unlocked == 0) {
2100 				ASSERT_VOP_ELOCKED(vp, "nfsrv_lockctrl6");
2101 				NFSVOPUNLOCK(vp, 0);
2102 			}
2103 			/* Roll back local locks. */
2104 			nfsrv_locallock_rollback(vp, lfp, p);
2105 			NFSLOCKSTATE();
2106 			nfsrv_unlocklf(lfp);
2107 			NFSUNLOCKSTATE();
2108 			NFSVOPLOCK(vp, LK_EXCLUSIVE | LK_RETRY);
2109 			vnode_unlocked = 0;
2110 			if ((vp->v_iflag & VI_DOOMED) != 0) {
2111 				error = NFSERR_SERVERFAULT;
2112 				goto out;
2113 			}
2114 		    }
2115 		    /*
2116 		     * nfsrv_clientconflict() unlocks state when it
2117 		     * returns non-zero.
2118 		     */
2119 		    lckstp = NULL;
2120 		    goto tryagain;
2121 		}
2122 		/*
2123 		 * Found a conflicting lock, so record the conflict and
2124 		 * return the error.
2125 		 */
2126 		if (cfp != NULL && ret == 0) {
2127 		    cfp->cl_clientid.lval[0]=lop->lo_stp->ls_stateid.other[0];
2128 		    cfp->cl_clientid.lval[1]=lop->lo_stp->ls_stateid.other[1];
2129 		    cfp->cl_first = lop->lo_first;
2130 		    cfp->cl_end = lop->lo_end;
2131 		    cfp->cl_flags = lop->lo_flags;
2132 		    cfp->cl_ownerlen = lop->lo_stp->ls_ownerlen;
2133 		    NFSBCOPY(lop->lo_stp->ls_owner, cfp->cl_owner,
2134 			cfp->cl_ownerlen);
2135 		}
2136 		if (ret == 2)
2137 		    error = NFSERR_PERM;
2138 		else if (new_stp->ls_flags & NFSLCK_RECLAIM)
2139 		    error = NFSERR_RECLAIMCONFLICT;
2140 		else if (new_stp->ls_flags & NFSLCK_CHECK)
2141 		    error = NFSERR_LOCKED;
2142 		else
2143 		    error = NFSERR_DENIED;
2144 		if (filestruct_locked != 0 && ret == 0) {
2145 			/* Roll back local locks. */
2146 			NFSUNLOCKSTATE();
2147 			if (vnode_unlocked == 0) {
2148 				ASSERT_VOP_ELOCKED(vp, "nfsrv_lockctrl7");
2149 				vnode_unlocked = 1;
2150 				NFSVOPUNLOCK(vp, 0);
2151 			}
2152 			nfsrv_locallock_rollback(vp, lfp, p);
2153 			NFSLOCKSTATE();
2154 			nfsrv_unlocklf(lfp);
2155 		}
2156 		if (ret == 0)
2157 			NFSUNLOCKSTATE();
2158 		goto out;
2159 	    }
2160 	  }
2161 	}
2162 
2163 	/*
2164 	 * We only get here if there was no lock that conflicted.
2165 	 */
2166 	if (new_stp->ls_flags & (NFSLCK_TEST | NFSLCK_CHECK)) {
2167 		NFSUNLOCKSTATE();
2168 		goto out;
2169 	}
2170 
2171 	/*
2172 	 * We only get here when we are creating or modifying a lock.
2173 	 * There are two variants:
2174 	 * - exist_lock_owner where lock_owner exists
2175 	 * - open_to_lock_owner with new lock_owner
2176 	 */
2177 	first = new_lop->lo_first;
2178 	end = new_lop->lo_end;
2179 	lock_flags = new_lop->lo_flags;
2180 	if (!(new_stp->ls_flags & NFSLCK_OPENTOLOCK)) {
2181 		nfsrv_updatelock(lckstp, new_lopp, &other_lop, lfp);
2182 		stateidp->seqid = ++(lckstp->ls_stateid.seqid);
2183 		if ((nd->nd_flag & ND_NFSV41) != 0 && stateidp->seqid == 0)
2184 			stateidp->seqid = lckstp->ls_stateid.seqid = 1;
2185 		stateidp->other[0] = lckstp->ls_stateid.other[0];
2186 		stateidp->other[1] = lckstp->ls_stateid.other[1];
2187 		stateidp->other[2] = lckstp->ls_stateid.other[2];
2188 	} else {
2189 		/*
2190 		 * The new open_to_lock_owner case.
2191 		 * Link the new nfsstate into the lists.
2192 		 */
2193 		new_stp->ls_seq = new_stp->ls_opentolockseq;
2194 		nfsrvd_refcache(new_stp->ls_op);
2195 		stateidp->seqid = new_stp->ls_stateid.seqid = 1;
2196 		stateidp->other[0] = new_stp->ls_stateid.other[0] =
2197 		    clp->lc_clientid.lval[0];
2198 		stateidp->other[1] = new_stp->ls_stateid.other[1] =
2199 		    clp->lc_clientid.lval[1];
2200 		stateidp->other[2] = new_stp->ls_stateid.other[2] =
2201 		    nfsrv_nextstateindex(clp);
2202 		new_stp->ls_clp = clp;
2203 		LIST_INIT(&new_stp->ls_lock);
2204 		new_stp->ls_openstp = stp;
2205 		new_stp->ls_lfp = lfp;
2206 		nfsrv_insertlock(new_lop, (struct nfslock *)new_stp, new_stp,
2207 		    lfp);
2208 		LIST_INSERT_HEAD(NFSSTATEHASH(clp, new_stp->ls_stateid),
2209 		    new_stp, ls_hash);
2210 		LIST_INSERT_HEAD(&stp->ls_open, new_stp, ls_list);
2211 		*new_lopp = NULL;
2212 		*new_stpp = NULL;
2213 		nfsstatsv1.srvlockowners++;
2214 		nfsrv_openpluslock++;
2215 	}
2216 	if (filestruct_locked != 0) {
2217 		NFSUNLOCKSTATE();
2218 		nfsrv_locallock_commit(lfp, lock_flags, first, end);
2219 		NFSLOCKSTATE();
2220 		nfsrv_unlocklf(lfp);
2221 	}
2222 	NFSUNLOCKSTATE();
2223 
2224 out:
2225 	if (haslock) {
2226 		NFSLOCKV4ROOTMUTEX();
2227 		nfsv4_unlock(&nfsv4rootfs_lock, 1);
2228 		NFSUNLOCKV4ROOTMUTEX();
2229 	}
2230 	if (vnode_unlocked != 0) {
2231 		NFSVOPLOCK(vp, LK_EXCLUSIVE | LK_RETRY);
2232 		if (error == 0 && (vp->v_iflag & VI_DOOMED) != 0)
2233 			error = NFSERR_SERVERFAULT;
2234 	}
2235 	if (other_lop)
2236 		FREE((caddr_t)other_lop, M_NFSDLOCK);
2237 	NFSEXITCODE2(error, nd);
2238 	return (error);
2239 }
2240 
2241 /*
2242  * Check for state errors for Open.
2243  * repstat is passed back out as an error if more critical errors
2244  * are not detected.
2245  */
2246 APPLESTATIC int
2247 nfsrv_opencheck(nfsquad_t clientid, nfsv4stateid_t *stateidp,
2248     struct nfsstate *new_stp, vnode_t vp, struct nfsrv_descript *nd,
2249     NFSPROC_T *p, int repstat)
2250 {
2251 	struct nfsstate *stp, *nstp;
2252 	struct nfsclient *clp;
2253 	struct nfsstate *ownerstp;
2254 	struct nfslockfile *lfp, *new_lfp;
2255 	int error = 0, haslock = 0, ret, readonly = 0, getfhret = 0;
2256 
2257 	if ((new_stp->ls_flags & NFSLCK_SHAREBITS) == NFSLCK_READACCESS)
2258 		readonly = 1;
2259 	/*
2260 	 * Check for restart conditions (client and server).
2261 	 */
2262 	error = nfsrv_checkrestart(clientid, new_stp->ls_flags,
2263 		&new_stp->ls_stateid, 0);
2264 	if (error)
2265 		goto out;
2266 
2267 	/*
2268 	 * Check for state resource limit exceeded.
2269 	 * Technically this should be SMP protected, but the worst
2270 	 * case error is "out by one or two" on the count when it
2271 	 * returns NFSERR_RESOURCE and the limit is just a rather
2272 	 * arbitrary high water mark, so no harm is done.
2273 	 */
2274 	if (nfsrv_openpluslock > nfsrv_v4statelimit) {
2275 		error = NFSERR_RESOURCE;
2276 		goto out;
2277 	}
2278 
2279 tryagain:
2280 	MALLOC(new_lfp, struct nfslockfile *, sizeof (struct nfslockfile),
2281 	    M_NFSDLOCKFILE, M_WAITOK);
2282 	if (vp)
2283 		getfhret = nfsrv_getlockfh(vp, new_stp->ls_flags, new_lfp,
2284 		    NULL, p);
2285 	NFSLOCKSTATE();
2286 	/*
2287 	 * Get the nfsclient structure.
2288 	 */
2289 	error = nfsrv_getclient(clientid, CLOPS_RENEW, &clp, NULL,
2290 	    (nfsquad_t)((u_quad_t)0), 0, nd, p);
2291 
2292 	/*
2293 	 * Look up the open owner. See if it needs confirmation and
2294 	 * check the seq#, as required.
2295 	 */
2296 	if (!error)
2297 		nfsrv_getowner(&clp->lc_open, new_stp, &ownerstp);
2298 
2299 	if (!error && ownerstp) {
2300 		error = nfsrv_checkseqid(nd, new_stp->ls_seq, ownerstp,
2301 		    new_stp->ls_op);
2302 		/*
2303 		 * If the OpenOwner hasn't been confirmed, assume the
2304 		 * old one was a replay and this one is ok.
2305 		 * See: RFC3530 Sec. 14.2.18.
2306 		 */
2307 		if (error == NFSERR_BADSEQID &&
2308 		    (ownerstp->ls_flags & NFSLCK_NEEDSCONFIRM))
2309 			error = 0;
2310 	}
2311 
2312 	/*
2313 	 * Check for grace.
2314 	 */
2315 	if (!error)
2316 		error = nfsrv_checkgrace(nd, clp, new_stp->ls_flags);
2317 	if ((new_stp->ls_flags & NFSLCK_RECLAIM) && !error &&
2318 		nfsrv_checkstable(clp))
2319 		error = NFSERR_NOGRACE;
2320 
2321 	/*
2322 	 * If none of the above errors occurred, let repstat be
2323 	 * returned.
2324 	 */
2325 	if (repstat && !error)
2326 		error = repstat;
2327 	if (error) {
2328 		NFSUNLOCKSTATE();
2329 		if (haslock) {
2330 			NFSLOCKV4ROOTMUTEX();
2331 			nfsv4_unlock(&nfsv4rootfs_lock, 1);
2332 			NFSUNLOCKV4ROOTMUTEX();
2333 		}
2334 		free((caddr_t)new_lfp, M_NFSDLOCKFILE);
2335 		goto out;
2336 	}
2337 
2338 	/*
2339 	 * If vp == NULL, the file doesn't exist yet, so return ok.
2340 	 * (This always happens on the first pass, so haslock must be 0.)
2341 	 */
2342 	if (vp == NULL) {
2343 		NFSUNLOCKSTATE();
2344 		FREE((caddr_t)new_lfp, M_NFSDLOCKFILE);
2345 		goto out;
2346 	}
2347 
2348 	/*
2349 	 * Get the structure for the underlying file.
2350 	 */
2351 	if (getfhret)
2352 		error = getfhret;
2353 	else
2354 		error = nfsrv_getlockfile(new_stp->ls_flags, &new_lfp, &lfp,
2355 		    NULL, 0);
2356 	if (new_lfp)
2357 		FREE((caddr_t)new_lfp, M_NFSDLOCKFILE);
2358 	if (error) {
2359 		NFSUNLOCKSTATE();
2360 		if (haslock) {
2361 			NFSLOCKV4ROOTMUTEX();
2362 			nfsv4_unlock(&nfsv4rootfs_lock, 1);
2363 			NFSUNLOCKV4ROOTMUTEX();
2364 		}
2365 		goto out;
2366 	}
2367 
2368 	/*
2369 	 * Search for a conflicting open/share.
2370 	 */
2371 	if (new_stp->ls_flags & NFSLCK_DELEGCUR) {
2372 	    /*
2373 	     * For Delegate_Cur, search for the matching Delegation,
2374 	     * which indicates no conflict.
2375 	     * An old delegation should have been recovered by the
2376 	     * client doing a Claim_DELEGATE_Prev, so I won't let
2377 	     * it match and return NFSERR_EXPIRED. Should I let it
2378 	     * match?
2379 	     */
2380 	    LIST_FOREACH(stp, &lfp->lf_deleg, ls_file) {
2381 		if (!(stp->ls_flags & NFSLCK_OLDDELEG) &&
2382 		    (((nd->nd_flag & ND_NFSV41) != 0 &&
2383 		    stateidp->seqid == 0) ||
2384 		    stateidp->seqid == stp->ls_stateid.seqid) &&
2385 		    !NFSBCMP(stateidp->other, stp->ls_stateid.other,
2386 			  NFSX_STATEIDOTHER))
2387 			break;
2388 	    }
2389 	    if (stp == LIST_END(&lfp->lf_deleg) ||
2390 		((new_stp->ls_flags & NFSLCK_WRITEACCESS) &&
2391 		 (stp->ls_flags & NFSLCK_DELEGREAD))) {
2392 		NFSUNLOCKSTATE();
2393 		if (haslock) {
2394 			NFSLOCKV4ROOTMUTEX();
2395 			nfsv4_unlock(&nfsv4rootfs_lock, 1);
2396 			NFSUNLOCKV4ROOTMUTEX();
2397 		}
2398 		error = NFSERR_EXPIRED;
2399 		goto out;
2400 	    }
2401 	}
2402 
2403 	/*
2404 	 * Check for access/deny bit conflicts. I check for the same
2405 	 * owner as well, in case the client didn't bother.
2406 	 */
2407 	LIST_FOREACH(stp, &lfp->lf_open, ls_file) {
2408 		if (!(new_stp->ls_flags & NFSLCK_DELEGCUR) &&
2409 		    (((new_stp->ls_flags & NFSLCK_ACCESSBITS) &
2410 		      ((stp->ls_flags>>NFSLCK_SHIFT) & NFSLCK_ACCESSBITS))||
2411 		     ((stp->ls_flags & NFSLCK_ACCESSBITS) &
2412 		      ((new_stp->ls_flags>>NFSLCK_SHIFT)&NFSLCK_ACCESSBITS)))){
2413 			ret = nfsrv_clientconflict(stp->ls_clp,&haslock,vp,p);
2414 			if (ret == 1) {
2415 				/*
2416 				 * nfsrv_clientconflict() unlocks
2417 				 * state when it returns non-zero.
2418 				 */
2419 				goto tryagain;
2420 			}
2421 			if (ret == 2)
2422 				error = NFSERR_PERM;
2423 			else if (new_stp->ls_flags & NFSLCK_RECLAIM)
2424 				error = NFSERR_RECLAIMCONFLICT;
2425 			else
2426 				error = NFSERR_SHAREDENIED;
2427 			if (ret == 0)
2428 				NFSUNLOCKSTATE();
2429 			if (haslock) {
2430 				NFSLOCKV4ROOTMUTEX();
2431 				nfsv4_unlock(&nfsv4rootfs_lock, 1);
2432 				NFSUNLOCKV4ROOTMUTEX();
2433 			}
2434 			goto out;
2435 		}
2436 	}
2437 
2438 	/*
2439 	 * Check for a conflicting delegation. If one is found, call
2440 	 * nfsrv_delegconflict() to handle it. If the v4root lock hasn't
2441 	 * been set yet, it will get the lock. Otherwise, it will recall
2442 	 * the delegation. Then, we try try again...
2443 	 * (If NFSLCK_DELEGCUR is set, it has a delegation, so there
2444 	 *  isn't a conflict.)
2445 	 * I currently believe the conflict algorithm to be:
2446 	 * For Open with Read Access and Deny None
2447 	 * - there is a conflict iff a different client has a write delegation
2448 	 * For Open with other Write Access or any Deny except None
2449 	 * - there is a conflict if a different client has any delegation
2450 	 * - there is a conflict if the same client has a read delegation
2451 	 *   (The current consensus is that this last case should be
2452 	 *    considered a conflict since the client with a read delegation
2453 	 *    could have done an Open with ReadAccess and WriteDeny
2454 	 *    locally and then not have checked for the WriteDeny.)
2455 	 * Don't check for a Reclaim, since that will be dealt with
2456 	 * by nfsrv_openctrl().
2457 	 */
2458 	if (!(new_stp->ls_flags &
2459 		(NFSLCK_DELEGPREV | NFSLCK_DELEGCUR | NFSLCK_RECLAIM))) {
2460 	    stp = LIST_FIRST(&lfp->lf_deleg);
2461 	    while (stp != LIST_END(&lfp->lf_deleg)) {
2462 		nstp = LIST_NEXT(stp, ls_file);
2463 		if ((readonly && stp->ls_clp != clp &&
2464 		       (stp->ls_flags & NFSLCK_DELEGWRITE)) ||
2465 		    (!readonly && (stp->ls_clp != clp ||
2466 		         (stp->ls_flags & NFSLCK_DELEGREAD)))) {
2467 			ret = nfsrv_delegconflict(stp, &haslock, p, vp);
2468 			if (ret) {
2469 			    /*
2470 			     * nfsrv_delegconflict() unlocks state
2471 			     * when it returns non-zero.
2472 			     */
2473 			    if (ret == -1)
2474 				goto tryagain;
2475 			    error = ret;
2476 			    goto out;
2477 			}
2478 		}
2479 		stp = nstp;
2480 	    }
2481 	}
2482 	NFSUNLOCKSTATE();
2483 	if (haslock) {
2484 		NFSLOCKV4ROOTMUTEX();
2485 		nfsv4_unlock(&nfsv4rootfs_lock, 1);
2486 		NFSUNLOCKV4ROOTMUTEX();
2487 	}
2488 
2489 out:
2490 	NFSEXITCODE2(error, nd);
2491 	return (error);
2492 }
2493 
2494 /*
2495  * Open control function to create/update open state for an open.
2496  */
2497 APPLESTATIC int
2498 nfsrv_openctrl(struct nfsrv_descript *nd, vnode_t vp,
2499     struct nfsstate **new_stpp, nfsquad_t clientid, nfsv4stateid_t *stateidp,
2500     nfsv4stateid_t *delegstateidp, u_int32_t *rflagsp, struct nfsexstuff *exp,
2501     NFSPROC_T *p, u_quad_t filerev)
2502 {
2503 	struct nfsstate *new_stp = *new_stpp;
2504 	struct nfsstate *stp, *nstp;
2505 	struct nfsstate *openstp = NULL, *new_open, *ownerstp, *new_deleg;
2506 	struct nfslockfile *lfp, *new_lfp;
2507 	struct nfsclient *clp;
2508 	int error = 0, haslock = 0, ret, delegate = 1, writedeleg = 1;
2509 	int readonly = 0, cbret = 1, getfhret = 0;
2510 	int gotstate = 0, len = 0;
2511 	u_char *clidp = NULL;
2512 
2513 	if ((new_stp->ls_flags & NFSLCK_SHAREBITS) == NFSLCK_READACCESS)
2514 		readonly = 1;
2515 	/*
2516 	 * Check for restart conditions (client and server).
2517 	 * (Paranoia, should have been detected by nfsrv_opencheck().)
2518 	 * If an error does show up, return NFSERR_EXPIRED, since the
2519 	 * the seqid# has already been incremented.
2520 	 */
2521 	error = nfsrv_checkrestart(clientid, new_stp->ls_flags,
2522 	    &new_stp->ls_stateid, 0);
2523 	if (error) {
2524 		printf("Nfsd: openctrl unexpected restart err=%d\n",
2525 		    error);
2526 		error = NFSERR_EXPIRED;
2527 		goto out;
2528 	}
2529 
2530 	clidp = malloc(NFSV4_OPAQUELIMIT, M_TEMP, M_WAITOK);
2531 tryagain:
2532 	MALLOC(new_lfp, struct nfslockfile *, sizeof (struct nfslockfile),
2533 	    M_NFSDLOCKFILE, M_WAITOK);
2534 	MALLOC(new_open, struct nfsstate *, sizeof (struct nfsstate),
2535 	    M_NFSDSTATE, M_WAITOK);
2536 	MALLOC(new_deleg, struct nfsstate *, sizeof (struct nfsstate),
2537 	    M_NFSDSTATE, M_WAITOK);
2538 	getfhret = nfsrv_getlockfh(vp, new_stp->ls_flags, new_lfp,
2539 	    NULL, p);
2540 	NFSLOCKSTATE();
2541 	/*
2542 	 * Get the client structure. Since the linked lists could be changed
2543 	 * by other nfsd processes if this process does a tsleep(), one of
2544 	 * two things must be done.
2545 	 * 1 - don't tsleep()
2546 	 * or
2547 	 * 2 - get the nfsv4_lock() { indicated by haslock == 1 }
2548 	 *     before using the lists, since this lock stops the other
2549 	 *     nfsd. This should only be used for rare cases, since it
2550 	 *     essentially single threads the nfsd.
2551 	 *     At this time, it is only done for cases where the stable
2552 	 *     storage file must be written prior to completion of state
2553 	 *     expiration.
2554 	 */
2555 	error = nfsrv_getclient(clientid, CLOPS_RENEW, &clp, NULL,
2556 	    (nfsquad_t)((u_quad_t)0), 0, nd, p);
2557 	if (!error && (clp->lc_flags & LCL_NEEDSCBNULL) &&
2558 	    clp->lc_program) {
2559 		/*
2560 		 * This happens on the first open for a client
2561 		 * that supports callbacks.
2562 		 */
2563 		NFSUNLOCKSTATE();
2564 		/*
2565 		 * Although nfsrv_docallback() will sleep, clp won't
2566 		 * go away, since they are only removed when the
2567 		 * nfsv4_lock() has blocked the nfsd threads. The
2568 		 * fields in clp can change, but having multiple
2569 		 * threads do this Null callback RPC should be
2570 		 * harmless.
2571 		 */
2572 		cbret = nfsrv_docallback(clp, NFSV4PROC_CBNULL,
2573 		    NULL, 0, NULL, NULL, NULL, p);
2574 		NFSLOCKSTATE();
2575 		clp->lc_flags &= ~LCL_NEEDSCBNULL;
2576 		if (!cbret)
2577 			clp->lc_flags |= LCL_CALLBACKSON;
2578 	}
2579 
2580 	/*
2581 	 * Look up the open owner. See if it needs confirmation and
2582 	 * check the seq#, as required.
2583 	 */
2584 	if (!error)
2585 		nfsrv_getowner(&clp->lc_open, new_stp, &ownerstp);
2586 
2587 	if (error) {
2588 		NFSUNLOCKSTATE();
2589 		printf("Nfsd: openctrl unexpected state err=%d\n",
2590 			error);
2591 		free((caddr_t)new_lfp, M_NFSDLOCKFILE);
2592 		free((caddr_t)new_open, M_NFSDSTATE);
2593 		free((caddr_t)new_deleg, M_NFSDSTATE);
2594 		if (haslock) {
2595 			NFSLOCKV4ROOTMUTEX();
2596 			nfsv4_unlock(&nfsv4rootfs_lock, 1);
2597 			NFSUNLOCKV4ROOTMUTEX();
2598 		}
2599 		error = NFSERR_EXPIRED;
2600 		goto out;
2601 	}
2602 
2603 	if (new_stp->ls_flags & NFSLCK_RECLAIM)
2604 		nfsrv_markstable(clp);
2605 
2606 	/*
2607 	 * Get the structure for the underlying file.
2608 	 */
2609 	if (getfhret)
2610 		error = getfhret;
2611 	else
2612 		error = nfsrv_getlockfile(new_stp->ls_flags, &new_lfp, &lfp,
2613 		    NULL, 0);
2614 	if (new_lfp)
2615 		FREE((caddr_t)new_lfp, M_NFSDLOCKFILE);
2616 	if (error) {
2617 		NFSUNLOCKSTATE();
2618 		printf("Nfsd openctrl unexpected getlockfile err=%d\n",
2619 		    error);
2620 		free((caddr_t)new_open, M_NFSDSTATE);
2621 		free((caddr_t)new_deleg, M_NFSDSTATE);
2622 		if (haslock) {
2623 			NFSLOCKV4ROOTMUTEX();
2624 			nfsv4_unlock(&nfsv4rootfs_lock, 1);
2625 			NFSUNLOCKV4ROOTMUTEX();
2626 		}
2627 		goto out;
2628 	}
2629 
2630 	/*
2631 	 * Search for a conflicting open/share.
2632 	 */
2633 	if (new_stp->ls_flags & NFSLCK_DELEGCUR) {
2634 	    /*
2635 	     * For Delegate_Cur, search for the matching Delegation,
2636 	     * which indicates no conflict.
2637 	     * An old delegation should have been recovered by the
2638 	     * client doing a Claim_DELEGATE_Prev, so I won't let
2639 	     * it match and return NFSERR_EXPIRED. Should I let it
2640 	     * match?
2641 	     */
2642 	    LIST_FOREACH(stp, &lfp->lf_deleg, ls_file) {
2643 		if (!(stp->ls_flags & NFSLCK_OLDDELEG) &&
2644 		    (((nd->nd_flag & ND_NFSV41) != 0 &&
2645 		    stateidp->seqid == 0) ||
2646 		    stateidp->seqid == stp->ls_stateid.seqid) &&
2647 		    !NFSBCMP(stateidp->other, stp->ls_stateid.other,
2648 			NFSX_STATEIDOTHER))
2649 			break;
2650 	    }
2651 	    if (stp == LIST_END(&lfp->lf_deleg) ||
2652 		((new_stp->ls_flags & NFSLCK_WRITEACCESS) &&
2653 		 (stp->ls_flags & NFSLCK_DELEGREAD))) {
2654 		NFSUNLOCKSTATE();
2655 		printf("Nfsd openctrl unexpected expiry\n");
2656 		free((caddr_t)new_open, M_NFSDSTATE);
2657 		free((caddr_t)new_deleg, M_NFSDSTATE);
2658 		if (haslock) {
2659 			NFSLOCKV4ROOTMUTEX();
2660 			nfsv4_unlock(&nfsv4rootfs_lock, 1);
2661 			NFSUNLOCKV4ROOTMUTEX();
2662 		}
2663 		error = NFSERR_EXPIRED;
2664 		goto out;
2665 	    }
2666 
2667 	    /*
2668 	     * Don't issue a Delegation, since one already exists and
2669 	     * delay delegation timeout, as required.
2670 	     */
2671 	    delegate = 0;
2672 	    nfsrv_delaydelegtimeout(stp);
2673 	}
2674 
2675 	/*
2676 	 * Check for access/deny bit conflicts. I also check for the
2677 	 * same owner, since the client might not have bothered to check.
2678 	 * Also, note an open for the same file and owner, if found,
2679 	 * which is all we do here for Delegate_Cur, since conflict
2680 	 * checking is already done.
2681 	 */
2682 	LIST_FOREACH(stp, &lfp->lf_open, ls_file) {
2683 		if (ownerstp && stp->ls_openowner == ownerstp)
2684 			openstp = stp;
2685 		if (!(new_stp->ls_flags & NFSLCK_DELEGCUR)) {
2686 		    /*
2687 		     * If another client has the file open, the only
2688 		     * delegation that can be issued is a Read delegation
2689 		     * and only if it is a Read open with Deny none.
2690 		     */
2691 		    if (clp != stp->ls_clp) {
2692 			if ((stp->ls_flags & NFSLCK_SHAREBITS) ==
2693 			    NFSLCK_READACCESS)
2694 			    writedeleg = 0;
2695 			else
2696 			    delegate = 0;
2697 		    }
2698 		    if(((new_stp->ls_flags & NFSLCK_ACCESSBITS) &
2699 		        ((stp->ls_flags>>NFSLCK_SHIFT) & NFSLCK_ACCESSBITS))||
2700 		       ((stp->ls_flags & NFSLCK_ACCESSBITS) &
2701 		        ((new_stp->ls_flags>>NFSLCK_SHIFT)&NFSLCK_ACCESSBITS))){
2702 			ret = nfsrv_clientconflict(stp->ls_clp,&haslock,vp,p);
2703 			if (ret == 1) {
2704 				/*
2705 				 * nfsrv_clientconflict() unlocks state
2706 				 * when it returns non-zero.
2707 				 */
2708 				free((caddr_t)new_open, M_NFSDSTATE);
2709 				free((caddr_t)new_deleg, M_NFSDSTATE);
2710 				openstp = NULL;
2711 				goto tryagain;
2712 			}
2713 			if (ret == 2)
2714 				error = NFSERR_PERM;
2715 			else if (new_stp->ls_flags & NFSLCK_RECLAIM)
2716 				error = NFSERR_RECLAIMCONFLICT;
2717 			else
2718 				error = NFSERR_SHAREDENIED;
2719 			if (ret == 0)
2720 				NFSUNLOCKSTATE();
2721 			if (haslock) {
2722 				NFSLOCKV4ROOTMUTEX();
2723 				nfsv4_unlock(&nfsv4rootfs_lock, 1);
2724 				NFSUNLOCKV4ROOTMUTEX();
2725 			}
2726 			free((caddr_t)new_open, M_NFSDSTATE);
2727 			free((caddr_t)new_deleg, M_NFSDSTATE);
2728 			printf("nfsd openctrl unexpected client cnfl\n");
2729 			goto out;
2730 		    }
2731 		}
2732 	}
2733 
2734 	/*
2735 	 * Check for a conflicting delegation. If one is found, call
2736 	 * nfsrv_delegconflict() to handle it. If the v4root lock hasn't
2737 	 * been set yet, it will get the lock. Otherwise, it will recall
2738 	 * the delegation. Then, we try try again...
2739 	 * (If NFSLCK_DELEGCUR is set, it has a delegation, so there
2740 	 *  isn't a conflict.)
2741 	 * I currently believe the conflict algorithm to be:
2742 	 * For Open with Read Access and Deny None
2743 	 * - there is a conflict iff a different client has a write delegation
2744 	 * For Open with other Write Access or any Deny except None
2745 	 * - there is a conflict if a different client has any delegation
2746 	 * - there is a conflict if the same client has a read delegation
2747 	 *   (The current consensus is that this last case should be
2748 	 *    considered a conflict since the client with a read delegation
2749 	 *    could have done an Open with ReadAccess and WriteDeny
2750 	 *    locally and then not have checked for the WriteDeny.)
2751 	 */
2752 	if (!(new_stp->ls_flags & (NFSLCK_DELEGPREV | NFSLCK_DELEGCUR))) {
2753 	    stp = LIST_FIRST(&lfp->lf_deleg);
2754 	    while (stp != LIST_END(&lfp->lf_deleg)) {
2755 		nstp = LIST_NEXT(stp, ls_file);
2756 		if (stp->ls_clp != clp && (stp->ls_flags & NFSLCK_DELEGREAD))
2757 			writedeleg = 0;
2758 		else
2759 			delegate = 0;
2760 		if ((readonly && stp->ls_clp != clp &&
2761 		       (stp->ls_flags & NFSLCK_DELEGWRITE)) ||
2762 		    (!readonly && (stp->ls_clp != clp ||
2763 		         (stp->ls_flags & NFSLCK_DELEGREAD)))) {
2764 		    if (new_stp->ls_flags & NFSLCK_RECLAIM) {
2765 			delegate = 2;
2766 		    } else {
2767 			ret = nfsrv_delegconflict(stp, &haslock, p, vp);
2768 			if (ret) {
2769 			    /*
2770 			     * nfsrv_delegconflict() unlocks state
2771 			     * when it returns non-zero.
2772 			     */
2773 			    printf("Nfsd openctrl unexpected deleg cnfl\n");
2774 			    free((caddr_t)new_open, M_NFSDSTATE);
2775 			    free((caddr_t)new_deleg, M_NFSDSTATE);
2776 			    if (ret == -1) {
2777 				openstp = NULL;
2778 				goto tryagain;
2779 			    }
2780 			    error = ret;
2781 			    goto out;
2782 			}
2783 		    }
2784 		}
2785 		stp = nstp;
2786 	    }
2787 	}
2788 
2789 	/*
2790 	 * We only get here if there was no open that conflicted.
2791 	 * If an open for the owner exists, or in the access/deny bits.
2792 	 * Otherwise it is a new open. If the open_owner hasn't been
2793 	 * confirmed, replace the open with the new one needing confirmation,
2794 	 * otherwise add the open.
2795 	 */
2796 	if (new_stp->ls_flags & NFSLCK_DELEGPREV) {
2797 	    /*
2798 	     * Handle NFSLCK_DELEGPREV by searching the old delegations for
2799 	     * a match. If found, just move the old delegation to the current
2800 	     * delegation list and issue open. If not found, return
2801 	     * NFSERR_EXPIRED.
2802 	     */
2803 	    LIST_FOREACH(stp, &clp->lc_olddeleg, ls_list) {
2804 		if (stp->ls_lfp == lfp) {
2805 		    /* Found it */
2806 		    if (stp->ls_clp != clp)
2807 			panic("olddeleg clp");
2808 		    LIST_REMOVE(stp, ls_list);
2809 		    LIST_REMOVE(stp, ls_hash);
2810 		    stp->ls_flags &= ~NFSLCK_OLDDELEG;
2811 		    stp->ls_stateid.seqid = delegstateidp->seqid = 1;
2812 		    stp->ls_stateid.other[0] = delegstateidp->other[0] =
2813 			clp->lc_clientid.lval[0];
2814 		    stp->ls_stateid.other[1] = delegstateidp->other[1] =
2815 			clp->lc_clientid.lval[1];
2816 		    stp->ls_stateid.other[2] = delegstateidp->other[2] =
2817 			nfsrv_nextstateindex(clp);
2818 		    stp->ls_compref = nd->nd_compref;
2819 		    LIST_INSERT_HEAD(&clp->lc_deleg, stp, ls_list);
2820 		    LIST_INSERT_HEAD(NFSSTATEHASH(clp,
2821 			stp->ls_stateid), stp, ls_hash);
2822 		    if (stp->ls_flags & NFSLCK_DELEGWRITE)
2823 			*rflagsp |= NFSV4OPEN_WRITEDELEGATE;
2824 		    else
2825 			*rflagsp |= NFSV4OPEN_READDELEGATE;
2826 		    clp->lc_delegtime = NFSD_MONOSEC +
2827 			nfsrv_lease + NFSRV_LEASEDELTA;
2828 
2829 		    /*
2830 		     * Now, do the associated open.
2831 		     */
2832 		    new_open->ls_stateid.seqid = 1;
2833 		    new_open->ls_stateid.other[0] = clp->lc_clientid.lval[0];
2834 		    new_open->ls_stateid.other[1] = clp->lc_clientid.lval[1];
2835 		    new_open->ls_stateid.other[2] = nfsrv_nextstateindex(clp);
2836 		    new_open->ls_flags = (new_stp->ls_flags&NFSLCK_DENYBITS)|
2837 			NFSLCK_OPEN;
2838 		    if (stp->ls_flags & NFSLCK_DELEGWRITE)
2839 			new_open->ls_flags |= (NFSLCK_READACCESS |
2840 			    NFSLCK_WRITEACCESS);
2841 		    else
2842 			new_open->ls_flags |= NFSLCK_READACCESS;
2843 		    new_open->ls_uid = new_stp->ls_uid;
2844 		    new_open->ls_lfp = lfp;
2845 		    new_open->ls_clp = clp;
2846 		    LIST_INIT(&new_open->ls_open);
2847 		    LIST_INSERT_HEAD(&lfp->lf_open, new_open, ls_file);
2848 		    LIST_INSERT_HEAD(NFSSTATEHASH(clp, new_open->ls_stateid),
2849 			new_open, ls_hash);
2850 		    /*
2851 		     * and handle the open owner
2852 		     */
2853 		    if (ownerstp) {
2854 			new_open->ls_openowner = ownerstp;
2855 			LIST_INSERT_HEAD(&ownerstp->ls_open,new_open,ls_list);
2856 		    } else {
2857 			new_open->ls_openowner = new_stp;
2858 			new_stp->ls_flags = 0;
2859 			nfsrvd_refcache(new_stp->ls_op);
2860 			new_stp->ls_noopens = 0;
2861 			LIST_INIT(&new_stp->ls_open);
2862 			LIST_INSERT_HEAD(&new_stp->ls_open, new_open, ls_list);
2863 			LIST_INSERT_HEAD(&clp->lc_open, new_stp, ls_list);
2864 			*new_stpp = NULL;
2865 			nfsstatsv1.srvopenowners++;
2866 			nfsrv_openpluslock++;
2867 		    }
2868 		    openstp = new_open;
2869 		    new_open = NULL;
2870 		    nfsstatsv1.srvopens++;
2871 		    nfsrv_openpluslock++;
2872 		    break;
2873 		}
2874 	    }
2875 	    if (stp == LIST_END(&clp->lc_olddeleg))
2876 		error = NFSERR_EXPIRED;
2877 	} else if (new_stp->ls_flags & (NFSLCK_DELEGREAD | NFSLCK_DELEGWRITE)) {
2878 	    /*
2879 	     * Scan to see that no delegation for this client and file
2880 	     * doesn't already exist.
2881 	     * There also shouldn't yet be an Open for this file and
2882 	     * openowner.
2883 	     */
2884 	    LIST_FOREACH(stp, &lfp->lf_deleg, ls_file) {
2885 		if (stp->ls_clp == clp)
2886 		    break;
2887 	    }
2888 	    if (stp == LIST_END(&lfp->lf_deleg) && openstp == NULL) {
2889 		/*
2890 		 * This is the Claim_Previous case with a delegation
2891 		 * type != Delegate_None.
2892 		 */
2893 		/*
2894 		 * First, add the delegation. (Although we must issue the
2895 		 * delegation, we can also ask for an immediate return.)
2896 		 */
2897 		new_deleg->ls_stateid.seqid = delegstateidp->seqid = 1;
2898 		new_deleg->ls_stateid.other[0] = delegstateidp->other[0] =
2899 		    clp->lc_clientid.lval[0];
2900 		new_deleg->ls_stateid.other[1] = delegstateidp->other[1] =
2901 		    clp->lc_clientid.lval[1];
2902 		new_deleg->ls_stateid.other[2] = delegstateidp->other[2] =
2903 		    nfsrv_nextstateindex(clp);
2904 		if (new_stp->ls_flags & NFSLCK_DELEGWRITE) {
2905 		    new_deleg->ls_flags = (NFSLCK_DELEGWRITE |
2906 			NFSLCK_READACCESS | NFSLCK_WRITEACCESS);
2907 		    *rflagsp |= NFSV4OPEN_WRITEDELEGATE;
2908 		} else {
2909 		    new_deleg->ls_flags = (NFSLCK_DELEGREAD |
2910 			NFSLCK_READACCESS);
2911 		    *rflagsp |= NFSV4OPEN_READDELEGATE;
2912 		}
2913 		new_deleg->ls_uid = new_stp->ls_uid;
2914 		new_deleg->ls_lfp = lfp;
2915 		new_deleg->ls_clp = clp;
2916 		new_deleg->ls_filerev = filerev;
2917 		new_deleg->ls_compref = nd->nd_compref;
2918 		LIST_INSERT_HEAD(&lfp->lf_deleg, new_deleg, ls_file);
2919 		LIST_INSERT_HEAD(NFSSTATEHASH(clp,
2920 		    new_deleg->ls_stateid), new_deleg, ls_hash);
2921 		LIST_INSERT_HEAD(&clp->lc_deleg, new_deleg, ls_list);
2922 		new_deleg = NULL;
2923 		if (delegate == 2 || nfsrv_issuedelegs == 0 ||
2924 		    (clp->lc_flags & (LCL_CALLBACKSON | LCL_CBDOWN)) !=
2925 		     LCL_CALLBACKSON ||
2926 		    NFSRV_V4DELEGLIMIT(nfsrv_delegatecnt) ||
2927 		    !NFSVNO_DELEGOK(vp))
2928 		    *rflagsp |= NFSV4OPEN_RECALL;
2929 		nfsstatsv1.srvdelegates++;
2930 		nfsrv_openpluslock++;
2931 		nfsrv_delegatecnt++;
2932 
2933 		/*
2934 		 * Now, do the associated open.
2935 		 */
2936 		new_open->ls_stateid.seqid = 1;
2937 		new_open->ls_stateid.other[0] = clp->lc_clientid.lval[0];
2938 		new_open->ls_stateid.other[1] = clp->lc_clientid.lval[1];
2939 		new_open->ls_stateid.other[2] = nfsrv_nextstateindex(clp);
2940 		new_open->ls_flags = (new_stp->ls_flags & NFSLCK_DENYBITS) |
2941 		    NFSLCK_OPEN;
2942 		if (new_stp->ls_flags & NFSLCK_DELEGWRITE)
2943 			new_open->ls_flags |= (NFSLCK_READACCESS |
2944 			    NFSLCK_WRITEACCESS);
2945 		else
2946 			new_open->ls_flags |= NFSLCK_READACCESS;
2947 		new_open->ls_uid = new_stp->ls_uid;
2948 		new_open->ls_lfp = lfp;
2949 		new_open->ls_clp = clp;
2950 		LIST_INIT(&new_open->ls_open);
2951 		LIST_INSERT_HEAD(&lfp->lf_open, new_open, ls_file);
2952 		LIST_INSERT_HEAD(NFSSTATEHASH(clp, new_open->ls_stateid),
2953 		   new_open, ls_hash);
2954 		/*
2955 		 * and handle the open owner
2956 		 */
2957 		if (ownerstp) {
2958 		    new_open->ls_openowner = ownerstp;
2959 		    LIST_INSERT_HEAD(&ownerstp->ls_open, new_open, ls_list);
2960 		} else {
2961 		    new_open->ls_openowner = new_stp;
2962 		    new_stp->ls_flags = 0;
2963 		    nfsrvd_refcache(new_stp->ls_op);
2964 		    new_stp->ls_noopens = 0;
2965 		    LIST_INIT(&new_stp->ls_open);
2966 		    LIST_INSERT_HEAD(&new_stp->ls_open, new_open, ls_list);
2967 		    LIST_INSERT_HEAD(&clp->lc_open, new_stp, ls_list);
2968 		    *new_stpp = NULL;
2969 		    nfsstatsv1.srvopenowners++;
2970 		    nfsrv_openpluslock++;
2971 		}
2972 		openstp = new_open;
2973 		new_open = NULL;
2974 		nfsstatsv1.srvopens++;
2975 		nfsrv_openpluslock++;
2976 	    } else {
2977 		error = NFSERR_RECLAIMCONFLICT;
2978 	    }
2979 	} else if (ownerstp) {
2980 		if (ownerstp->ls_flags & NFSLCK_NEEDSCONFIRM) {
2981 		    /* Replace the open */
2982 		    if (ownerstp->ls_op)
2983 			nfsrvd_derefcache(ownerstp->ls_op);
2984 		    ownerstp->ls_op = new_stp->ls_op;
2985 		    nfsrvd_refcache(ownerstp->ls_op);
2986 		    ownerstp->ls_seq = new_stp->ls_seq;
2987 		    *rflagsp |= NFSV4OPEN_RESULTCONFIRM;
2988 		    stp = LIST_FIRST(&ownerstp->ls_open);
2989 		    stp->ls_flags = (new_stp->ls_flags & NFSLCK_SHAREBITS) |
2990 			NFSLCK_OPEN;
2991 		    stp->ls_stateid.seqid = 1;
2992 		    stp->ls_uid = new_stp->ls_uid;
2993 		    if (lfp != stp->ls_lfp) {
2994 			LIST_REMOVE(stp, ls_file);
2995 			LIST_INSERT_HEAD(&lfp->lf_open, stp, ls_file);
2996 			stp->ls_lfp = lfp;
2997 		    }
2998 		    openstp = stp;
2999 		} else if (openstp) {
3000 		    openstp->ls_flags |= (new_stp->ls_flags & NFSLCK_SHAREBITS);
3001 		    openstp->ls_stateid.seqid++;
3002 		    if ((nd->nd_flag & ND_NFSV41) != 0 &&
3003 			openstp->ls_stateid.seqid == 0)
3004 			openstp->ls_stateid.seqid = 1;
3005 
3006 		    /*
3007 		     * This is where we can choose to issue a delegation.
3008 		     */
3009 		    if (delegate == 0 || writedeleg == 0 ||
3010 			NFSVNO_EXRDONLY(exp) || (readonly != 0 &&
3011 			nfsrv_writedelegifpos == 0) ||
3012 			!NFSVNO_DELEGOK(vp) ||
3013 			(new_stp->ls_flags & NFSLCK_WANTRDELEG) != 0 ||
3014 			(clp->lc_flags & (LCL_CALLBACKSON | LCL_CBDOWN)) !=
3015 			 LCL_CALLBACKSON)
3016 			*rflagsp |= NFSV4OPEN_WDCONTENTION;
3017 		    else if (nfsrv_issuedelegs == 0 ||
3018 			NFSRV_V4DELEGLIMIT(nfsrv_delegatecnt))
3019 			*rflagsp |= NFSV4OPEN_WDRESOURCE;
3020 		    else if ((new_stp->ls_flags & NFSLCK_WANTNODELEG) != 0)
3021 			*rflagsp |= NFSV4OPEN_WDNOTWANTED;
3022 		    else {
3023 			new_deleg->ls_stateid.seqid = delegstateidp->seqid = 1;
3024 			new_deleg->ls_stateid.other[0] = delegstateidp->other[0]
3025 			    = clp->lc_clientid.lval[0];
3026 			new_deleg->ls_stateid.other[1] = delegstateidp->other[1]
3027 			    = clp->lc_clientid.lval[1];
3028 			new_deleg->ls_stateid.other[2] = delegstateidp->other[2]
3029 			    = nfsrv_nextstateindex(clp);
3030 			new_deleg->ls_flags = (NFSLCK_DELEGWRITE |
3031 			    NFSLCK_READACCESS | NFSLCK_WRITEACCESS);
3032 			*rflagsp |= NFSV4OPEN_WRITEDELEGATE;
3033 			new_deleg->ls_uid = new_stp->ls_uid;
3034 			new_deleg->ls_lfp = lfp;
3035 			new_deleg->ls_clp = clp;
3036 			new_deleg->ls_filerev = filerev;
3037 			new_deleg->ls_compref = nd->nd_compref;
3038 			LIST_INSERT_HEAD(&lfp->lf_deleg, new_deleg, ls_file);
3039 			LIST_INSERT_HEAD(NFSSTATEHASH(clp,
3040 			    new_deleg->ls_stateid), new_deleg, ls_hash);
3041 			LIST_INSERT_HEAD(&clp->lc_deleg, new_deleg, ls_list);
3042 			new_deleg = NULL;
3043 			nfsstatsv1.srvdelegates++;
3044 			nfsrv_openpluslock++;
3045 			nfsrv_delegatecnt++;
3046 		    }
3047 		} else {
3048 		    new_open->ls_stateid.seqid = 1;
3049 		    new_open->ls_stateid.other[0] = clp->lc_clientid.lval[0];
3050 		    new_open->ls_stateid.other[1] = clp->lc_clientid.lval[1];
3051 		    new_open->ls_stateid.other[2] = nfsrv_nextstateindex(clp);
3052 		    new_open->ls_flags = (new_stp->ls_flags & NFSLCK_SHAREBITS)|
3053 			NFSLCK_OPEN;
3054 		    new_open->ls_uid = new_stp->ls_uid;
3055 		    new_open->ls_openowner = ownerstp;
3056 		    new_open->ls_lfp = lfp;
3057 		    new_open->ls_clp = clp;
3058 		    LIST_INIT(&new_open->ls_open);
3059 		    LIST_INSERT_HEAD(&lfp->lf_open, new_open, ls_file);
3060 		    LIST_INSERT_HEAD(&ownerstp->ls_open, new_open, ls_list);
3061 		    LIST_INSERT_HEAD(NFSSTATEHASH(clp, new_open->ls_stateid),
3062 			new_open, ls_hash);
3063 		    openstp = new_open;
3064 		    new_open = NULL;
3065 		    nfsstatsv1.srvopens++;
3066 		    nfsrv_openpluslock++;
3067 
3068 		    /*
3069 		     * This is where we can choose to issue a delegation.
3070 		     */
3071 		    if (delegate == 0 || (writedeleg == 0 && readonly == 0) ||
3072 			!NFSVNO_DELEGOK(vp) ||
3073 			(clp->lc_flags & (LCL_CALLBACKSON | LCL_CBDOWN)) !=
3074 			 LCL_CALLBACKSON)
3075 			*rflagsp |= NFSV4OPEN_WDCONTENTION;
3076 		    else if (nfsrv_issuedelegs == 0 ||
3077 			NFSRV_V4DELEGLIMIT(nfsrv_delegatecnt))
3078 			*rflagsp |= NFSV4OPEN_WDRESOURCE;
3079 		    else if ((new_stp->ls_flags & NFSLCK_WANTNODELEG) != 0)
3080 			*rflagsp |= NFSV4OPEN_WDNOTWANTED;
3081 		    else {
3082 			new_deleg->ls_stateid.seqid = delegstateidp->seqid = 1;
3083 			new_deleg->ls_stateid.other[0] = delegstateidp->other[0]
3084 			    = clp->lc_clientid.lval[0];
3085 			new_deleg->ls_stateid.other[1] = delegstateidp->other[1]
3086 			    = clp->lc_clientid.lval[1];
3087 			new_deleg->ls_stateid.other[2] = delegstateidp->other[2]
3088 			    = nfsrv_nextstateindex(clp);
3089 			if (writedeleg && !NFSVNO_EXRDONLY(exp) &&
3090 			    (nfsrv_writedelegifpos || !readonly) &&
3091 			    (new_stp->ls_flags & NFSLCK_WANTRDELEG) == 0) {
3092 			    new_deleg->ls_flags = (NFSLCK_DELEGWRITE |
3093 				NFSLCK_READACCESS | NFSLCK_WRITEACCESS);
3094 			    *rflagsp |= NFSV4OPEN_WRITEDELEGATE;
3095 			} else {
3096 			    new_deleg->ls_flags = (NFSLCK_DELEGREAD |
3097 				NFSLCK_READACCESS);
3098 			    *rflagsp |= NFSV4OPEN_READDELEGATE;
3099 			}
3100 			new_deleg->ls_uid = new_stp->ls_uid;
3101 			new_deleg->ls_lfp = lfp;
3102 			new_deleg->ls_clp = clp;
3103 			new_deleg->ls_filerev = filerev;
3104 			new_deleg->ls_compref = nd->nd_compref;
3105 			LIST_INSERT_HEAD(&lfp->lf_deleg, new_deleg, ls_file);
3106 			LIST_INSERT_HEAD(NFSSTATEHASH(clp,
3107 			    new_deleg->ls_stateid), new_deleg, ls_hash);
3108 			LIST_INSERT_HEAD(&clp->lc_deleg, new_deleg, ls_list);
3109 			new_deleg = NULL;
3110 			nfsstatsv1.srvdelegates++;
3111 			nfsrv_openpluslock++;
3112 			nfsrv_delegatecnt++;
3113 		    }
3114 		}
3115 	} else {
3116 		/*
3117 		 * New owner case. Start the open_owner sequence with a
3118 		 * Needs confirmation (unless a reclaim) and hang the
3119 		 * new open off it.
3120 		 */
3121 		new_open->ls_stateid.seqid = 1;
3122 		new_open->ls_stateid.other[0] = clp->lc_clientid.lval[0];
3123 		new_open->ls_stateid.other[1] = clp->lc_clientid.lval[1];
3124 		new_open->ls_stateid.other[2] = nfsrv_nextstateindex(clp);
3125 		new_open->ls_flags = (new_stp->ls_flags & NFSLCK_SHAREBITS) |
3126 		    NFSLCK_OPEN;
3127 		new_open->ls_uid = new_stp->ls_uid;
3128 		LIST_INIT(&new_open->ls_open);
3129 		new_open->ls_openowner = new_stp;
3130 		new_open->ls_lfp = lfp;
3131 		new_open->ls_clp = clp;
3132 		LIST_INSERT_HEAD(&lfp->lf_open, new_open, ls_file);
3133 		if (new_stp->ls_flags & NFSLCK_RECLAIM) {
3134 			new_stp->ls_flags = 0;
3135 		} else if ((nd->nd_flag & ND_NFSV41) != 0) {
3136 			/* NFSv4.1 never needs confirmation. */
3137 			new_stp->ls_flags = 0;
3138 
3139 			/*
3140 			 * This is where we can choose to issue a delegation.
3141 			 */
3142 			if (delegate && nfsrv_issuedelegs &&
3143 			    (writedeleg || readonly) &&
3144 			    (clp->lc_flags & (LCL_CALLBACKSON | LCL_CBDOWN)) ==
3145 			     LCL_CALLBACKSON &&
3146 			    !NFSRV_V4DELEGLIMIT(nfsrv_delegatecnt) &&
3147 			    NFSVNO_DELEGOK(vp) &&
3148 			    ((nd->nd_flag & ND_NFSV41) == 0 ||
3149 			     (new_stp->ls_flags & NFSLCK_WANTNODELEG) == 0)) {
3150 				new_deleg->ls_stateid.seqid =
3151 				    delegstateidp->seqid = 1;
3152 				new_deleg->ls_stateid.other[0] =
3153 				    delegstateidp->other[0]
3154 				    = clp->lc_clientid.lval[0];
3155 				new_deleg->ls_stateid.other[1] =
3156 				    delegstateidp->other[1]
3157 				    = clp->lc_clientid.lval[1];
3158 				new_deleg->ls_stateid.other[2] =
3159 				    delegstateidp->other[2]
3160 				    = nfsrv_nextstateindex(clp);
3161 				if (writedeleg && !NFSVNO_EXRDONLY(exp) &&
3162 				    (nfsrv_writedelegifpos || !readonly) &&
3163 				    ((nd->nd_flag & ND_NFSV41) == 0 ||
3164 				     (new_stp->ls_flags & NFSLCK_WANTRDELEG) ==
3165 				     0)) {
3166 					new_deleg->ls_flags =
3167 					    (NFSLCK_DELEGWRITE |
3168 					     NFSLCK_READACCESS |
3169 					     NFSLCK_WRITEACCESS);
3170 					*rflagsp |= NFSV4OPEN_WRITEDELEGATE;
3171 				} else {
3172 					new_deleg->ls_flags =
3173 					    (NFSLCK_DELEGREAD |
3174 					     NFSLCK_READACCESS);
3175 					*rflagsp |= NFSV4OPEN_READDELEGATE;
3176 				}
3177 				new_deleg->ls_uid = new_stp->ls_uid;
3178 				new_deleg->ls_lfp = lfp;
3179 				new_deleg->ls_clp = clp;
3180 				new_deleg->ls_filerev = filerev;
3181 				new_deleg->ls_compref = nd->nd_compref;
3182 				LIST_INSERT_HEAD(&lfp->lf_deleg, new_deleg,
3183 				    ls_file);
3184 				LIST_INSERT_HEAD(NFSSTATEHASH(clp,
3185 				    new_deleg->ls_stateid), new_deleg, ls_hash);
3186 				LIST_INSERT_HEAD(&clp->lc_deleg, new_deleg,
3187 				    ls_list);
3188 				new_deleg = NULL;
3189 				nfsstatsv1.srvdelegates++;
3190 				nfsrv_openpluslock++;
3191 				nfsrv_delegatecnt++;
3192 			}
3193 			/*
3194 			 * Since NFSv4.1 never does an OpenConfirm, the first
3195 			 * open state will be acquired here.
3196 			 */
3197 			if (!(clp->lc_flags & LCL_STAMPEDSTABLE)) {
3198 				clp->lc_flags |= LCL_STAMPEDSTABLE;
3199 				len = clp->lc_idlen;
3200 				NFSBCOPY(clp->lc_id, clidp, len);
3201 				gotstate = 1;
3202 			}
3203 		} else {
3204 			*rflagsp |= NFSV4OPEN_RESULTCONFIRM;
3205 			new_stp->ls_flags = NFSLCK_NEEDSCONFIRM;
3206 		}
3207 		nfsrvd_refcache(new_stp->ls_op);
3208 		new_stp->ls_noopens = 0;
3209 		LIST_INIT(&new_stp->ls_open);
3210 		LIST_INSERT_HEAD(&new_stp->ls_open, new_open, ls_list);
3211 		LIST_INSERT_HEAD(&clp->lc_open, new_stp, ls_list);
3212 		LIST_INSERT_HEAD(NFSSTATEHASH(clp, new_open->ls_stateid),
3213 		    new_open, ls_hash);
3214 		openstp = new_open;
3215 		new_open = NULL;
3216 		*new_stpp = NULL;
3217 		nfsstatsv1.srvopens++;
3218 		nfsrv_openpluslock++;
3219 		nfsstatsv1.srvopenowners++;
3220 		nfsrv_openpluslock++;
3221 	}
3222 	if (!error) {
3223 		stateidp->seqid = openstp->ls_stateid.seqid;
3224 		stateidp->other[0] = openstp->ls_stateid.other[0];
3225 		stateidp->other[1] = openstp->ls_stateid.other[1];
3226 		stateidp->other[2] = openstp->ls_stateid.other[2];
3227 	}
3228 	NFSUNLOCKSTATE();
3229 	if (haslock) {
3230 		NFSLOCKV4ROOTMUTEX();
3231 		nfsv4_unlock(&nfsv4rootfs_lock, 1);
3232 		NFSUNLOCKV4ROOTMUTEX();
3233 	}
3234 	if (new_open)
3235 		FREE((caddr_t)new_open, M_NFSDSTATE);
3236 	if (new_deleg)
3237 		FREE((caddr_t)new_deleg, M_NFSDSTATE);
3238 
3239 	/*
3240 	 * If the NFSv4.1 client just acquired its first open, write a timestamp
3241 	 * to the stable storage file.
3242 	 */
3243 	if (gotstate != 0) {
3244 		nfsrv_writestable(clidp, len, NFSNST_NEWSTATE, p);
3245 		nfsrv_backupstable();
3246 	}
3247 
3248 out:
3249 	free(clidp, M_TEMP);
3250 	NFSEXITCODE2(error, nd);
3251 	return (error);
3252 }
3253 
3254 /*
3255  * Open update. Does the confirm, downgrade and close.
3256  */
3257 APPLESTATIC int
3258 nfsrv_openupdate(vnode_t vp, struct nfsstate *new_stp, nfsquad_t clientid,
3259     nfsv4stateid_t *stateidp, struct nfsrv_descript *nd, NFSPROC_T *p)
3260 {
3261 	struct nfsstate *stp, *ownerstp;
3262 	struct nfsclient *clp;
3263 	struct nfslockfile *lfp;
3264 	u_int32_t bits;
3265 	int error = 0, gotstate = 0, len = 0;
3266 	u_char *clidp = NULL;
3267 
3268 	/*
3269 	 * Check for restart conditions (client and server).
3270 	 */
3271 	error = nfsrv_checkrestart(clientid, new_stp->ls_flags,
3272 	    &new_stp->ls_stateid, 0);
3273 	if (error)
3274 		goto out;
3275 
3276 	clidp = malloc(NFSV4_OPAQUELIMIT, M_TEMP, M_WAITOK);
3277 	NFSLOCKSTATE();
3278 	/*
3279 	 * Get the open structure via clientid and stateid.
3280 	 */
3281 	error = nfsrv_getclient(clientid, CLOPS_RENEW, &clp, NULL,
3282 	    (nfsquad_t)((u_quad_t)0), 0, nd, p);
3283 	if (!error)
3284 		error = nfsrv_getstate(clp, &new_stp->ls_stateid,
3285 		    new_stp->ls_flags, &stp);
3286 
3287 	/*
3288 	 * Sanity check the open.
3289 	 */
3290 	if (!error && (!(stp->ls_flags & NFSLCK_OPEN) ||
3291 		(!(new_stp->ls_flags & NFSLCK_CONFIRM) &&
3292 		 (stp->ls_openowner->ls_flags & NFSLCK_NEEDSCONFIRM)) ||
3293 		((new_stp->ls_flags & NFSLCK_CONFIRM) &&
3294 		 (!(stp->ls_openowner->ls_flags & NFSLCK_NEEDSCONFIRM)))))
3295 		error = NFSERR_BADSTATEID;
3296 
3297 	if (!error)
3298 		error = nfsrv_checkseqid(nd, new_stp->ls_seq,
3299 		    stp->ls_openowner, new_stp->ls_op);
3300 	if (!error && stp->ls_stateid.seqid != new_stp->ls_stateid.seqid &&
3301 	    (((nd->nd_flag & ND_NFSV41) == 0 &&
3302 	      !(new_stp->ls_flags & NFSLCK_CONFIRM)) ||
3303 	     ((nd->nd_flag & ND_NFSV41) != 0 &&
3304 	      new_stp->ls_stateid.seqid != 0)))
3305 		error = NFSERR_OLDSTATEID;
3306 	if (!error && vnode_vtype(vp) != VREG) {
3307 		if (vnode_vtype(vp) == VDIR)
3308 			error = NFSERR_ISDIR;
3309 		else
3310 			error = NFSERR_INVAL;
3311 	}
3312 
3313 	if (error) {
3314 		/*
3315 		 * If a client tries to confirm an Open with a bad
3316 		 * seqid# and there are no byte range locks or other Opens
3317 		 * on the openowner, just throw it away, so the next use of the
3318 		 * openowner will start a fresh seq#.
3319 		 */
3320 		if (error == NFSERR_BADSEQID &&
3321 		    (new_stp->ls_flags & NFSLCK_CONFIRM) &&
3322 		    nfsrv_nootherstate(stp))
3323 			nfsrv_freeopenowner(stp->ls_openowner, 0, p);
3324 		NFSUNLOCKSTATE();
3325 		goto out;
3326 	}
3327 
3328 	/*
3329 	 * Set the return stateid.
3330 	 */
3331 	stateidp->seqid = stp->ls_stateid.seqid + 1;
3332 	if ((nd->nd_flag & ND_NFSV41) != 0 && stateidp->seqid == 0)
3333 		stateidp->seqid = 1;
3334 	stateidp->other[0] = stp->ls_stateid.other[0];
3335 	stateidp->other[1] = stp->ls_stateid.other[1];
3336 	stateidp->other[2] = stp->ls_stateid.other[2];
3337 	/*
3338 	 * Now, handle the three cases.
3339 	 */
3340 	if (new_stp->ls_flags & NFSLCK_CONFIRM) {
3341 		/*
3342 		 * If the open doesn't need confirmation, it seems to me that
3343 		 * there is a client error, but I'll just log it and keep going?
3344 		 */
3345 		if (!(stp->ls_openowner->ls_flags & NFSLCK_NEEDSCONFIRM))
3346 			printf("Nfsv4d: stray open confirm\n");
3347 		stp->ls_openowner->ls_flags = 0;
3348 		stp->ls_stateid.seqid++;
3349 		if ((nd->nd_flag & ND_NFSV41) != 0 &&
3350 		    stp->ls_stateid.seqid == 0)
3351 			stp->ls_stateid.seqid = 1;
3352 		if (!(clp->lc_flags & LCL_STAMPEDSTABLE)) {
3353 			clp->lc_flags |= LCL_STAMPEDSTABLE;
3354 			len = clp->lc_idlen;
3355 			NFSBCOPY(clp->lc_id, clidp, len);
3356 			gotstate = 1;
3357 		}
3358 		NFSUNLOCKSTATE();
3359 	} else if (new_stp->ls_flags & NFSLCK_CLOSE) {
3360 		ownerstp = stp->ls_openowner;
3361 		lfp = stp->ls_lfp;
3362 		if (nfsrv_dolocallocks != 0 && !LIST_EMPTY(&stp->ls_open)) {
3363 			/* Get the lf lock */
3364 			nfsrv_locklf(lfp);
3365 			NFSUNLOCKSTATE();
3366 			ASSERT_VOP_ELOCKED(vp, "nfsrv_openupdate");
3367 			NFSVOPUNLOCK(vp, 0);
3368 			if (nfsrv_freeopen(stp, vp, 1, p) == 0) {
3369 				NFSLOCKSTATE();
3370 				nfsrv_unlocklf(lfp);
3371 				NFSUNLOCKSTATE();
3372 			}
3373 			NFSVOPLOCK(vp, LK_EXCLUSIVE | LK_RETRY);
3374 		} else {
3375 			(void) nfsrv_freeopen(stp, NULL, 0, p);
3376 			NFSUNLOCKSTATE();
3377 		}
3378 	} else {
3379 		/*
3380 		 * Update the share bits, making sure that the new set are a
3381 		 * subset of the old ones.
3382 		 */
3383 		bits = (new_stp->ls_flags & NFSLCK_SHAREBITS);
3384 		if (~(stp->ls_flags) & bits) {
3385 			NFSUNLOCKSTATE();
3386 			error = NFSERR_INVAL;
3387 			goto out;
3388 		}
3389 		stp->ls_flags = (bits | NFSLCK_OPEN);
3390 		stp->ls_stateid.seqid++;
3391 		if ((nd->nd_flag & ND_NFSV41) != 0 &&
3392 		    stp->ls_stateid.seqid == 0)
3393 			stp->ls_stateid.seqid = 1;
3394 		NFSUNLOCKSTATE();
3395 	}
3396 
3397 	/*
3398 	 * If the client just confirmed its first open, write a timestamp
3399 	 * to the stable storage file.
3400 	 */
3401 	if (gotstate != 0) {
3402 		nfsrv_writestable(clidp, len, NFSNST_NEWSTATE, p);
3403 		nfsrv_backupstable();
3404 	}
3405 
3406 out:
3407 	free(clidp, M_TEMP);
3408 	NFSEXITCODE2(error, nd);
3409 	return (error);
3410 }
3411 
3412 /*
3413  * Delegation update. Does the purge and return.
3414  */
3415 APPLESTATIC int
3416 nfsrv_delegupdate(struct nfsrv_descript *nd, nfsquad_t clientid,
3417     nfsv4stateid_t *stateidp, vnode_t vp, int op, struct ucred *cred,
3418     NFSPROC_T *p)
3419 {
3420 	struct nfsstate *stp;
3421 	struct nfsclient *clp;
3422 	int error = 0;
3423 	fhandle_t fh;
3424 
3425 	/*
3426 	 * Do a sanity check against the file handle for DelegReturn.
3427 	 */
3428 	if (vp) {
3429 		error = nfsvno_getfh(vp, &fh, p);
3430 		if (error)
3431 			goto out;
3432 	}
3433 	/*
3434 	 * Check for restart conditions (client and server).
3435 	 */
3436 	if (op == NFSV4OP_DELEGRETURN)
3437 		error = nfsrv_checkrestart(clientid, NFSLCK_DELEGRETURN,
3438 			stateidp, 0);
3439 	else
3440 		error = nfsrv_checkrestart(clientid, NFSLCK_DELEGPURGE,
3441 			stateidp, 0);
3442 
3443 	NFSLOCKSTATE();
3444 	/*
3445 	 * Get the open structure via clientid and stateid.
3446 	 */
3447 	if (!error)
3448 	    error = nfsrv_getclient(clientid, CLOPS_RENEW, &clp, NULL,
3449 		(nfsquad_t)((u_quad_t)0), 0, nd, p);
3450 	if (error) {
3451 		if (error == NFSERR_CBPATHDOWN)
3452 			error = 0;
3453 		if (error == NFSERR_STALECLIENTID && op == NFSV4OP_DELEGRETURN)
3454 			error = NFSERR_STALESTATEID;
3455 	}
3456 	if (!error && op == NFSV4OP_DELEGRETURN) {
3457 	    error = nfsrv_getstate(clp, stateidp, NFSLCK_DELEGRETURN, &stp);
3458 	    if (!error && stp->ls_stateid.seqid != stateidp->seqid &&
3459 		((nd->nd_flag & ND_NFSV41) == 0 || stateidp->seqid != 0))
3460 		error = NFSERR_OLDSTATEID;
3461 	}
3462 	/*
3463 	 * NFSERR_EXPIRED means that the state has gone away,
3464 	 * so Delegations have been purged. Just return ok.
3465 	 */
3466 	if (error == NFSERR_EXPIRED && op == NFSV4OP_DELEGPURGE) {
3467 		NFSUNLOCKSTATE();
3468 		error = 0;
3469 		goto out;
3470 	}
3471 	if (error) {
3472 		NFSUNLOCKSTATE();
3473 		goto out;
3474 	}
3475 
3476 	if (op == NFSV4OP_DELEGRETURN) {
3477 		if (NFSBCMP((caddr_t)&fh, (caddr_t)&stp->ls_lfp->lf_fh,
3478 		    sizeof (fhandle_t))) {
3479 			NFSUNLOCKSTATE();
3480 			error = NFSERR_BADSTATEID;
3481 			goto out;
3482 		}
3483 		nfsrv_freedeleg(stp);
3484 	} else {
3485 		nfsrv_freedeleglist(&clp->lc_olddeleg);
3486 	}
3487 	NFSUNLOCKSTATE();
3488 	error = 0;
3489 
3490 out:
3491 	NFSEXITCODE(error);
3492 	return (error);
3493 }
3494 
3495 /*
3496  * Release lock owner.
3497  */
3498 APPLESTATIC int
3499 nfsrv_releaselckown(struct nfsstate *new_stp, nfsquad_t clientid,
3500     NFSPROC_T *p)
3501 {
3502 	struct nfsstate *stp, *nstp, *openstp, *ownstp;
3503 	struct nfsclient *clp;
3504 	int error = 0;
3505 
3506 	/*
3507 	 * Check for restart conditions (client and server).
3508 	 */
3509 	error = nfsrv_checkrestart(clientid, new_stp->ls_flags,
3510 	    &new_stp->ls_stateid, 0);
3511 	if (error)
3512 		goto out;
3513 
3514 	NFSLOCKSTATE();
3515 	/*
3516 	 * Get the lock owner by name.
3517 	 */
3518 	error = nfsrv_getclient(clientid, CLOPS_RENEW, &clp, NULL,
3519 	    (nfsquad_t)((u_quad_t)0), 0, NULL, p);
3520 	if (error) {
3521 		NFSUNLOCKSTATE();
3522 		goto out;
3523 	}
3524 	LIST_FOREACH(ownstp, &clp->lc_open, ls_list) {
3525 	    LIST_FOREACH(openstp, &ownstp->ls_open, ls_list) {
3526 		stp = LIST_FIRST(&openstp->ls_open);
3527 		while (stp != LIST_END(&openstp->ls_open)) {
3528 		    nstp = LIST_NEXT(stp, ls_list);
3529 		    /*
3530 		     * If the owner matches, check for locks and
3531 		     * then free or return an error.
3532 		     */
3533 		    if (stp->ls_ownerlen == new_stp->ls_ownerlen &&
3534 			!NFSBCMP(stp->ls_owner, new_stp->ls_owner,
3535 			 stp->ls_ownerlen)){
3536 			if (LIST_EMPTY(&stp->ls_lock)) {
3537 			    nfsrv_freelockowner(stp, NULL, 0, p);
3538 			} else {
3539 			    NFSUNLOCKSTATE();
3540 			    error = NFSERR_LOCKSHELD;
3541 			    goto out;
3542 			}
3543 		    }
3544 		    stp = nstp;
3545 		}
3546 	    }
3547 	}
3548 	NFSUNLOCKSTATE();
3549 
3550 out:
3551 	NFSEXITCODE(error);
3552 	return (error);
3553 }
3554 
3555 /*
3556  * Get the file handle for a lock structure.
3557  */
3558 static int
3559 nfsrv_getlockfh(vnode_t vp, u_short flags, struct nfslockfile *new_lfp,
3560     fhandle_t *nfhp, NFSPROC_T *p)
3561 {
3562 	fhandle_t *fhp = NULL;
3563 	int error;
3564 
3565 	/*
3566 	 * For lock, use the new nfslock structure, otherwise just
3567 	 * a fhandle_t on the stack.
3568 	 */
3569 	if (flags & NFSLCK_OPEN) {
3570 		KASSERT(new_lfp != NULL, ("nfsrv_getlockfh: new_lfp NULL"));
3571 		fhp = &new_lfp->lf_fh;
3572 	} else if (nfhp) {
3573 		fhp = nfhp;
3574 	} else {
3575 		panic("nfsrv_getlockfh");
3576 	}
3577 	error = nfsvno_getfh(vp, fhp, p);
3578 	NFSEXITCODE(error);
3579 	return (error);
3580 }
3581 
3582 /*
3583  * Get an nfs lock structure. Allocate one, as required, and return a
3584  * pointer to it.
3585  * Returns an NFSERR_xxx upon failure or -1 to indicate no current lock.
3586  */
3587 static int
3588 nfsrv_getlockfile(u_short flags, struct nfslockfile **new_lfpp,
3589     struct nfslockfile **lfpp, fhandle_t *nfhp, int lockit)
3590 {
3591 	struct nfslockfile *lfp;
3592 	fhandle_t *fhp = NULL, *tfhp;
3593 	struct nfslockhashhead *hp;
3594 	struct nfslockfile *new_lfp = NULL;
3595 
3596 	/*
3597 	 * For lock, use the new nfslock structure, otherwise just
3598 	 * a fhandle_t on the stack.
3599 	 */
3600 	if (flags & NFSLCK_OPEN) {
3601 		new_lfp = *new_lfpp;
3602 		fhp = &new_lfp->lf_fh;
3603 	} else if (nfhp) {
3604 		fhp = nfhp;
3605 	} else {
3606 		panic("nfsrv_getlockfile");
3607 	}
3608 
3609 	hp = NFSLOCKHASH(fhp);
3610 	LIST_FOREACH(lfp, hp, lf_hash) {
3611 		tfhp = &lfp->lf_fh;
3612 		if (NFSVNO_CMPFH(fhp, tfhp)) {
3613 			if (lockit)
3614 				nfsrv_locklf(lfp);
3615 			*lfpp = lfp;
3616 			return (0);
3617 		}
3618 	}
3619 	if (!(flags & NFSLCK_OPEN))
3620 		return (-1);
3621 
3622 	/*
3623 	 * No match, so chain the new one into the list.
3624 	 */
3625 	LIST_INIT(&new_lfp->lf_open);
3626 	LIST_INIT(&new_lfp->lf_lock);
3627 	LIST_INIT(&new_lfp->lf_deleg);
3628 	LIST_INIT(&new_lfp->lf_locallock);
3629 	LIST_INIT(&new_lfp->lf_rollback);
3630 	new_lfp->lf_locallock_lck.nfslock_usecnt = 0;
3631 	new_lfp->lf_locallock_lck.nfslock_lock = 0;
3632 	new_lfp->lf_usecount = 0;
3633 	LIST_INSERT_HEAD(hp, new_lfp, lf_hash);
3634 	*lfpp = new_lfp;
3635 	*new_lfpp = NULL;
3636 	return (0);
3637 }
3638 
3639 /*
3640  * This function adds a nfslock lock structure to the list for the associated
3641  * nfsstate and nfslockfile structures. It will be inserted after the
3642  * entry pointed at by insert_lop.
3643  */
3644 static void
3645 nfsrv_insertlock(struct nfslock *new_lop, struct nfslock *insert_lop,
3646     struct nfsstate *stp, struct nfslockfile *lfp)
3647 {
3648 	struct nfslock *lop, *nlop;
3649 
3650 	new_lop->lo_stp = stp;
3651 	new_lop->lo_lfp = lfp;
3652 
3653 	if (stp != NULL) {
3654 		/* Insert in increasing lo_first order */
3655 		lop = LIST_FIRST(&lfp->lf_lock);
3656 		if (lop == LIST_END(&lfp->lf_lock) ||
3657 		    new_lop->lo_first <= lop->lo_first) {
3658 			LIST_INSERT_HEAD(&lfp->lf_lock, new_lop, lo_lckfile);
3659 		} else {
3660 			nlop = LIST_NEXT(lop, lo_lckfile);
3661 			while (nlop != LIST_END(&lfp->lf_lock) &&
3662 			       nlop->lo_first < new_lop->lo_first) {
3663 				lop = nlop;
3664 				nlop = LIST_NEXT(lop, lo_lckfile);
3665 			}
3666 			LIST_INSERT_AFTER(lop, new_lop, lo_lckfile);
3667 		}
3668 	} else {
3669 		new_lop->lo_lckfile.le_prev = NULL;	/* list not used */
3670 	}
3671 
3672 	/*
3673 	 * Insert after insert_lop, which is overloaded as stp or lfp for
3674 	 * an empty list.
3675 	 */
3676 	if (stp == NULL && (struct nfslockfile *)insert_lop == lfp)
3677 		LIST_INSERT_HEAD(&lfp->lf_locallock, new_lop, lo_lckowner);
3678 	else if ((struct nfsstate *)insert_lop == stp)
3679 		LIST_INSERT_HEAD(&stp->ls_lock, new_lop, lo_lckowner);
3680 	else
3681 		LIST_INSERT_AFTER(insert_lop, new_lop, lo_lckowner);
3682 	if (stp != NULL) {
3683 		nfsstatsv1.srvlocks++;
3684 		nfsrv_openpluslock++;
3685 	}
3686 }
3687 
3688 /*
3689  * This function updates the locking for a lock owner and given file. It
3690  * maintains a list of lock ranges ordered on increasing file offset that
3691  * are NFSLCK_READ or NFSLCK_WRITE and non-overlapping (aka POSIX style).
3692  * It always adds new_lop to the list and sometimes uses the one pointed
3693  * at by other_lopp.
3694  */
3695 static void
3696 nfsrv_updatelock(struct nfsstate *stp, struct nfslock **new_lopp,
3697     struct nfslock **other_lopp, struct nfslockfile *lfp)
3698 {
3699 	struct nfslock *new_lop = *new_lopp;
3700 	struct nfslock *lop, *tlop, *ilop;
3701 	struct nfslock *other_lop = *other_lopp;
3702 	int unlock = 0, myfile = 0;
3703 	u_int64_t tmp;
3704 
3705 	/*
3706 	 * Work down the list until the lock is merged.
3707 	 */
3708 	if (new_lop->lo_flags & NFSLCK_UNLOCK)
3709 		unlock = 1;
3710 	if (stp != NULL) {
3711 		ilop = (struct nfslock *)stp;
3712 		lop = LIST_FIRST(&stp->ls_lock);
3713 	} else {
3714 		ilop = (struct nfslock *)lfp;
3715 		lop = LIST_FIRST(&lfp->lf_locallock);
3716 	}
3717 	while (lop != NULL) {
3718 	    /*
3719 	     * Only check locks for this file that aren't before the start of
3720 	     * new lock's range.
3721 	     */
3722 	    if (lop->lo_lfp == lfp) {
3723 	      myfile = 1;
3724 	      if (lop->lo_end >= new_lop->lo_first) {
3725 		if (new_lop->lo_end < lop->lo_first) {
3726 			/*
3727 			 * If the new lock ends before the start of the
3728 			 * current lock's range, no merge, just insert
3729 			 * the new lock.
3730 			 */
3731 			break;
3732 		}
3733 		if (new_lop->lo_flags == lop->lo_flags ||
3734 		    (new_lop->lo_first <= lop->lo_first &&
3735 		     new_lop->lo_end >= lop->lo_end)) {
3736 			/*
3737 			 * This lock can be absorbed by the new lock/unlock.
3738 			 * This happens when it covers the entire range
3739 			 * of the old lock or is contiguous
3740 			 * with the old lock and is of the same type or an
3741 			 * unlock.
3742 			 */
3743 			if (lop->lo_first < new_lop->lo_first)
3744 				new_lop->lo_first = lop->lo_first;
3745 			if (lop->lo_end > new_lop->lo_end)
3746 				new_lop->lo_end = lop->lo_end;
3747 			tlop = lop;
3748 			lop = LIST_NEXT(lop, lo_lckowner);
3749 			nfsrv_freenfslock(tlop);
3750 			continue;
3751 		}
3752 
3753 		/*
3754 		 * All these cases are for contiguous locks that are not the
3755 		 * same type, so they can't be merged.
3756 		 */
3757 		if (new_lop->lo_first <= lop->lo_first) {
3758 			/*
3759 			 * This case is where the new lock overlaps with the
3760 			 * first part of the old lock. Move the start of the
3761 			 * old lock to just past the end of the new lock. The
3762 			 * new lock will be inserted in front of the old, since
3763 			 * ilop hasn't been updated. (We are done now.)
3764 			 */
3765 			lop->lo_first = new_lop->lo_end;
3766 			break;
3767 		}
3768 		if (new_lop->lo_end >= lop->lo_end) {
3769 			/*
3770 			 * This case is where the new lock overlaps with the
3771 			 * end of the old lock's range. Move the old lock's
3772 			 * end to just before the new lock's first and insert
3773 			 * the new lock after the old lock.
3774 			 * Might not be done yet, since the new lock could
3775 			 * overlap further locks with higher ranges.
3776 			 */
3777 			lop->lo_end = new_lop->lo_first;
3778 			ilop = lop;
3779 			lop = LIST_NEXT(lop, lo_lckowner);
3780 			continue;
3781 		}
3782 		/*
3783 		 * The final case is where the new lock's range is in the
3784 		 * middle of the current lock's and splits the current lock
3785 		 * up. Use *other_lopp to handle the second part of the
3786 		 * split old lock range. (We are done now.)
3787 		 * For unlock, we use new_lop as other_lop and tmp, since
3788 		 * other_lop and new_lop are the same for this case.
3789 		 * We noted the unlock case above, so we don't need
3790 		 * new_lop->lo_flags any longer.
3791 		 */
3792 		tmp = new_lop->lo_first;
3793 		if (other_lop == NULL) {
3794 			if (!unlock)
3795 				panic("nfsd srv update unlock");
3796 			other_lop = new_lop;
3797 			*new_lopp = NULL;
3798 		}
3799 		other_lop->lo_first = new_lop->lo_end;
3800 		other_lop->lo_end = lop->lo_end;
3801 		other_lop->lo_flags = lop->lo_flags;
3802 		other_lop->lo_stp = stp;
3803 		other_lop->lo_lfp = lfp;
3804 		lop->lo_end = tmp;
3805 		nfsrv_insertlock(other_lop, lop, stp, lfp);
3806 		*other_lopp = NULL;
3807 		ilop = lop;
3808 		break;
3809 	      }
3810 	    }
3811 	    ilop = lop;
3812 	    lop = LIST_NEXT(lop, lo_lckowner);
3813 	    if (myfile && (lop == NULL || lop->lo_lfp != lfp))
3814 		break;
3815 	}
3816 
3817 	/*
3818 	 * Insert the new lock in the list at the appropriate place.
3819 	 */
3820 	if (!unlock) {
3821 		nfsrv_insertlock(new_lop, ilop, stp, lfp);
3822 		*new_lopp = NULL;
3823 	}
3824 }
3825 
3826 /*
3827  * This function handles sequencing of locks, etc.
3828  * It returns an error that indicates what the caller should do.
3829  */
3830 static int
3831 nfsrv_checkseqid(struct nfsrv_descript *nd, u_int32_t seqid,
3832     struct nfsstate *stp, struct nfsrvcache *op)
3833 {
3834 	int error = 0;
3835 
3836 	if ((nd->nd_flag & ND_NFSV41) != 0)
3837 		/* NFSv4.1 ignores the open_seqid and lock_seqid. */
3838 		goto out;
3839 	if (op != nd->nd_rp)
3840 		panic("nfsrvstate checkseqid");
3841 	if (!(op->rc_flag & RC_INPROG))
3842 		panic("nfsrvstate not inprog");
3843 	if (stp->ls_op && stp->ls_op->rc_refcnt <= 0) {
3844 		printf("refcnt=%d\n", stp->ls_op->rc_refcnt);
3845 		panic("nfsrvstate op refcnt");
3846 	}
3847 	if ((stp->ls_seq + 1) == seqid) {
3848 		if (stp->ls_op)
3849 			nfsrvd_derefcache(stp->ls_op);
3850 		stp->ls_op = op;
3851 		nfsrvd_refcache(op);
3852 		stp->ls_seq = seqid;
3853 		goto out;
3854 	} else if (stp->ls_seq == seqid && stp->ls_op &&
3855 		op->rc_xid == stp->ls_op->rc_xid &&
3856 		op->rc_refcnt == 0 &&
3857 		op->rc_reqlen == stp->ls_op->rc_reqlen &&
3858 		op->rc_cksum == stp->ls_op->rc_cksum) {
3859 		if (stp->ls_op->rc_flag & RC_INPROG) {
3860 			error = NFSERR_DONTREPLY;
3861 			goto out;
3862 		}
3863 		nd->nd_rp = stp->ls_op;
3864 		nd->nd_rp->rc_flag |= RC_INPROG;
3865 		nfsrvd_delcache(op);
3866 		error = NFSERR_REPLYFROMCACHE;
3867 		goto out;
3868 	}
3869 	error = NFSERR_BADSEQID;
3870 
3871 out:
3872 	NFSEXITCODE2(error, nd);
3873 	return (error);
3874 }
3875 
3876 /*
3877  * Get the client ip address for callbacks. If the strings can't be parsed,
3878  * just set lc_program to 0 to indicate no callbacks are possible.
3879  * (For cases where the address can't be parsed or is 0.0.0.0.0.0, set
3880  *  the address to the client's transport address. This won't be used
3881  *  for callbacks, but can be printed out by nfsstats for info.)
3882  * Return error if the xdr can't be parsed, 0 otherwise.
3883  */
3884 APPLESTATIC int
3885 nfsrv_getclientipaddr(struct nfsrv_descript *nd, struct nfsclient *clp)
3886 {
3887 	u_int32_t *tl;
3888 	u_char *cp, *cp2;
3889 	int i, j;
3890 	struct sockaddr_in *rad, *sad;
3891 	u_char protocol[5], addr[24];
3892 	int error = 0, cantparse = 0;
3893 	union {
3894 		u_long ival;
3895 		u_char cval[4];
3896 	} ip;
3897 	union {
3898 		u_short sval;
3899 		u_char cval[2];
3900 	} port;
3901 
3902 	rad = NFSSOCKADDR(clp->lc_req.nr_nam, struct sockaddr_in *);
3903 	rad->sin_family = AF_INET;
3904 	rad->sin_len = sizeof (struct sockaddr_in);
3905 	rad->sin_addr.s_addr = 0;
3906 	rad->sin_port = 0;
3907 	clp->lc_req.nr_client = NULL;
3908 	clp->lc_req.nr_lock = 0;
3909 	NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
3910 	i = fxdr_unsigned(int, *tl);
3911 	if (i >= 3 && i <= 4) {
3912 		error = nfsrv_mtostr(nd, protocol, i);
3913 		if (error)
3914 			goto nfsmout;
3915 		if (!strcmp(protocol, "tcp")) {
3916 			clp->lc_flags |= LCL_TCPCALLBACK;
3917 			clp->lc_req.nr_sotype = SOCK_STREAM;
3918 			clp->lc_req.nr_soproto = IPPROTO_TCP;
3919 		} else if (!strcmp(protocol, "udp")) {
3920 			clp->lc_req.nr_sotype = SOCK_DGRAM;
3921 			clp->lc_req.nr_soproto = IPPROTO_UDP;
3922 		} else {
3923 			cantparse = 1;
3924 		}
3925 	} else {
3926 		cantparse = 1;
3927 		if (i > 0) {
3928 			error = nfsm_advance(nd, NFSM_RNDUP(i), -1);
3929 			if (error)
3930 				goto nfsmout;
3931 		}
3932 	}
3933 	NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
3934 	i = fxdr_unsigned(int, *tl);
3935 	if (i < 0) {
3936 		error = NFSERR_BADXDR;
3937 		goto nfsmout;
3938 	} else if (i == 0) {
3939 		cantparse = 1;
3940 	} else if (!cantparse && i <= 23 && i >= 11) {
3941 		error = nfsrv_mtostr(nd, addr, i);
3942 		if (error)
3943 			goto nfsmout;
3944 
3945 		/*
3946 		 * Parse out the address fields. We expect 6 decimal numbers
3947 		 * separated by '.'s.
3948 		 */
3949 		cp = addr;
3950 		i = 0;
3951 		while (*cp && i < 6) {
3952 			cp2 = cp;
3953 			while (*cp2 && *cp2 != '.')
3954 				cp2++;
3955 			if (*cp2)
3956 				*cp2++ = '\0';
3957 			else if (i != 5) {
3958 				cantparse = 1;
3959 				break;
3960 			}
3961 			j = nfsrv_getipnumber(cp);
3962 			if (j >= 0) {
3963 				if (i < 4)
3964 					ip.cval[3 - i] = j;
3965 				else
3966 					port.cval[5 - i] = j;
3967 			} else {
3968 				cantparse = 1;
3969 				break;
3970 			}
3971 			cp = cp2;
3972 			i++;
3973 		}
3974 		if (!cantparse) {
3975 			if (ip.ival != 0x0) {
3976 				rad->sin_addr.s_addr = htonl(ip.ival);
3977 				rad->sin_port = htons(port.sval);
3978 			} else {
3979 				cantparse = 1;
3980 			}
3981 		}
3982 	} else {
3983 		cantparse = 1;
3984 		if (i > 0) {
3985 			error = nfsm_advance(nd, NFSM_RNDUP(i), -1);
3986 			if (error)
3987 				goto nfsmout;
3988 		}
3989 	}
3990 	if (cantparse) {
3991 		sad = NFSSOCKADDR(nd->nd_nam, struct sockaddr_in *);
3992 		rad->sin_addr.s_addr = sad->sin_addr.s_addr;
3993 		rad->sin_port = 0x0;
3994 		clp->lc_program = 0;
3995 	}
3996 nfsmout:
3997 	NFSEXITCODE2(error, nd);
3998 	return (error);
3999 }
4000 
4001 /*
4002  * Turn a string of up to three decimal digits into a number. Return -1 upon
4003  * error.
4004  */
4005 static int
4006 nfsrv_getipnumber(u_char *cp)
4007 {
4008 	int i = 0, j = 0;
4009 
4010 	while (*cp) {
4011 		if (j > 2 || *cp < '0' || *cp > '9')
4012 			return (-1);
4013 		i *= 10;
4014 		i += (*cp - '0');
4015 		cp++;
4016 		j++;
4017 	}
4018 	if (i < 256)
4019 		return (i);
4020 	return (-1);
4021 }
4022 
4023 /*
4024  * This function checks for restart conditions.
4025  */
4026 static int
4027 nfsrv_checkrestart(nfsquad_t clientid, u_int32_t flags,
4028     nfsv4stateid_t *stateidp, int specialid)
4029 {
4030 	int ret = 0;
4031 
4032 	/*
4033 	 * First check for a server restart. Open, LockT, ReleaseLockOwner
4034 	 * and DelegPurge have a clientid, the rest a stateid.
4035 	 */
4036 	if (flags &
4037 	    (NFSLCK_OPEN | NFSLCK_TEST | NFSLCK_RELEASE | NFSLCK_DELEGPURGE)) {
4038 		if (clientid.lval[0] != nfsrvboottime) {
4039 			ret = NFSERR_STALECLIENTID;
4040 			goto out;
4041 		}
4042 	} else if (stateidp->other[0] != nfsrvboottime &&
4043 		specialid == 0) {
4044 		ret = NFSERR_STALESTATEID;
4045 		goto out;
4046 	}
4047 
4048 	/*
4049 	 * Read, Write, Setattr and LockT can return NFSERR_GRACE and do
4050 	 * not use a lock/open owner seqid#, so the check can be done now.
4051 	 * (The others will be checked, as required, later.)
4052 	 */
4053 	if (!(flags & (NFSLCK_CHECK | NFSLCK_TEST)))
4054 		goto out;
4055 
4056 	NFSLOCKSTATE();
4057 	ret = nfsrv_checkgrace(NULL, NULL, flags);
4058 	NFSUNLOCKSTATE();
4059 
4060 out:
4061 	NFSEXITCODE(ret);
4062 	return (ret);
4063 }
4064 
4065 /*
4066  * Check for grace.
4067  */
4068 static int
4069 nfsrv_checkgrace(struct nfsrv_descript *nd, struct nfsclient *clp,
4070     u_int32_t flags)
4071 {
4072 	int error = 0;
4073 
4074 	if ((nfsrv_stablefirst.nsf_flags & NFSNSF_GRACEOVER) != 0) {
4075 		if (flags & NFSLCK_RECLAIM) {
4076 			error = NFSERR_NOGRACE;
4077 			goto out;
4078 		}
4079 	} else {
4080 		if (!(flags & NFSLCK_RECLAIM)) {
4081 			error = NFSERR_GRACE;
4082 			goto out;
4083 		}
4084 		if (nd != NULL && clp != NULL &&
4085 		    (nd->nd_flag & ND_NFSV41) != 0 &&
4086 		    (clp->lc_flags & LCL_RECLAIMCOMPLETE) != 0) {
4087 			error = NFSERR_NOGRACE;
4088 			goto out;
4089 		}
4090 
4091 		/*
4092 		 * If grace is almost over and we are still getting Reclaims,
4093 		 * extend grace a bit.
4094 		 */
4095 		if ((NFSD_MONOSEC + NFSRV_LEASEDELTA) >
4096 		    nfsrv_stablefirst.nsf_eograce)
4097 			nfsrv_stablefirst.nsf_eograce = NFSD_MONOSEC +
4098 				NFSRV_LEASEDELTA;
4099 	}
4100 
4101 out:
4102 	NFSEXITCODE(error);
4103 	return (error);
4104 }
4105 
4106 /*
4107  * Do a server callback.
4108  */
4109 static int
4110 nfsrv_docallback(struct nfsclient *clp, int procnum,
4111     nfsv4stateid_t *stateidp, int trunc, fhandle_t *fhp,
4112     struct nfsvattr *nap, nfsattrbit_t *attrbitp, NFSPROC_T *p)
4113 {
4114 	mbuf_t m;
4115 	u_int32_t *tl;
4116 	struct nfsrv_descript nfsd, *nd = &nfsd;
4117 	struct ucred *cred;
4118 	int error = 0;
4119 	u_int32_t callback;
4120 	struct nfsdsession *sep = NULL;
4121 
4122 	cred = newnfs_getcred();
4123 	NFSLOCKSTATE();	/* mostly for lc_cbref++ */
4124 	if (clp->lc_flags & LCL_NEEDSCONFIRM) {
4125 		NFSUNLOCKSTATE();
4126 		panic("docallb");
4127 	}
4128 	clp->lc_cbref++;
4129 
4130 	/*
4131 	 * Fill the callback program# and version into the request
4132 	 * structure for newnfs_connect() to use.
4133 	 */
4134 	clp->lc_req.nr_prog = clp->lc_program;
4135 #ifdef notnow
4136 	if ((clp->lc_flags & LCL_NFSV41) != 0)
4137 		clp->lc_req.nr_vers = NFSV41_CBVERS;
4138 	else
4139 #endif
4140 		clp->lc_req.nr_vers = NFSV4_CBVERS;
4141 
4142 	/*
4143 	 * First, fill in some of the fields of nd and cr.
4144 	 */
4145 	nd->nd_flag = ND_NFSV4;
4146 	if (clp->lc_flags & LCL_GSS)
4147 		nd->nd_flag |= ND_KERBV;
4148 	if ((clp->lc_flags & LCL_NFSV41) != 0)
4149 		nd->nd_flag |= ND_NFSV41;
4150 	nd->nd_repstat = 0;
4151 	cred->cr_uid = clp->lc_uid;
4152 	cred->cr_gid = clp->lc_gid;
4153 	callback = clp->lc_callback;
4154 	NFSUNLOCKSTATE();
4155 	cred->cr_ngroups = 1;
4156 
4157 	/*
4158 	 * Get the first mbuf for the request.
4159 	 */
4160 	MGET(m, M_WAITOK, MT_DATA);
4161 	mbuf_setlen(m, 0);
4162 	nd->nd_mreq = nd->nd_mb = m;
4163 	nd->nd_bpos = NFSMTOD(m, caddr_t);
4164 
4165 	/*
4166 	 * and build the callback request.
4167 	 */
4168 	if (procnum == NFSV4OP_CBGETATTR) {
4169 		nd->nd_procnum = NFSV4PROC_CBCOMPOUND;
4170 		error = nfsrv_cbcallargs(nd, clp, callback, NFSV4OP_CBGETATTR,
4171 		    "CB Getattr", &sep);
4172 		if (error != 0) {
4173 			mbuf_freem(nd->nd_mreq);
4174 			goto errout;
4175 		}
4176 		(void)nfsm_fhtom(nd, (u_int8_t *)fhp, NFSX_MYFH, 0);
4177 		(void)nfsrv_putattrbit(nd, attrbitp);
4178 	} else if (procnum == NFSV4OP_CBRECALL) {
4179 		nd->nd_procnum = NFSV4PROC_CBCOMPOUND;
4180 		error = nfsrv_cbcallargs(nd, clp, callback, NFSV4OP_CBRECALL,
4181 		    "CB Recall", &sep);
4182 		if (error != 0) {
4183 			mbuf_freem(nd->nd_mreq);
4184 			goto errout;
4185 		}
4186 		NFSM_BUILD(tl, u_int32_t *, NFSX_UNSIGNED + NFSX_STATEID);
4187 		*tl++ = txdr_unsigned(stateidp->seqid);
4188 		NFSBCOPY((caddr_t)stateidp->other, (caddr_t)tl,
4189 		    NFSX_STATEIDOTHER);
4190 		tl += (NFSX_STATEIDOTHER / NFSX_UNSIGNED);
4191 		if (trunc)
4192 			*tl = newnfs_true;
4193 		else
4194 			*tl = newnfs_false;
4195 		(void)nfsm_fhtom(nd, (u_int8_t *)fhp, NFSX_MYFH, 0);
4196 	} else if (procnum == NFSV4PROC_CBNULL) {
4197 		nd->nd_procnum = NFSV4PROC_CBNULL;
4198 		if ((clp->lc_flags & LCL_NFSV41) != 0) {
4199 			error = nfsv4_getcbsession(clp, &sep);
4200 			if (error != 0) {
4201 				mbuf_freem(nd->nd_mreq);
4202 				goto errout;
4203 			}
4204 		}
4205 	} else {
4206 		error = NFSERR_SERVERFAULT;
4207 		mbuf_freem(nd->nd_mreq);
4208 		goto errout;
4209 	}
4210 
4211 	/*
4212 	 * Call newnfs_connect(), as required, and then newnfs_request().
4213 	 */
4214 	(void) newnfs_sndlock(&clp->lc_req.nr_lock);
4215 	if (clp->lc_req.nr_client == NULL) {
4216 		if ((clp->lc_flags & LCL_NFSV41) != 0)
4217 			error = ECONNREFUSED;
4218 		else if (nd->nd_procnum == NFSV4PROC_CBNULL)
4219 			error = newnfs_connect(NULL, &clp->lc_req, cred,
4220 			    NULL, 1);
4221 		else
4222 			error = newnfs_connect(NULL, &clp->lc_req, cred,
4223 			    NULL, 3);
4224 	}
4225 	newnfs_sndunlock(&clp->lc_req.nr_lock);
4226 	if (!error) {
4227 		if ((nd->nd_flag & ND_NFSV41) != 0) {
4228 			KASSERT(sep != NULL, ("sep NULL"));
4229 			if (sep->sess_cbsess.nfsess_xprt != NULL)
4230 				error = newnfs_request(nd, NULL, clp,
4231 				    &clp->lc_req, NULL, NULL, cred,
4232 				    clp->lc_program, clp->lc_req.nr_vers, NULL,
4233 				    1, NULL, &sep->sess_cbsess);
4234 			else {
4235 				/*
4236 				 * This should probably never occur, but if a
4237 				 * client somehow does an RPC without a
4238 				 * SequenceID Op that causes a callback just
4239 				 * after the nfsd threads have been terminated
4240 				 * and restared we could conceivably get here
4241 				 * without a backchannel xprt.
4242 				 */
4243 				printf("nfsrv_docallback: no xprt\n");
4244 				error = ECONNREFUSED;
4245 			}
4246 			nfsrv_freesession(sep, NULL);
4247 		} else
4248 			error = newnfs_request(nd, NULL, clp, &clp->lc_req,
4249 			    NULL, NULL, cred, clp->lc_program,
4250 			    clp->lc_req.nr_vers, NULL, 1, NULL, NULL);
4251 	}
4252 errout:
4253 	NFSFREECRED(cred);
4254 
4255 	/*
4256 	 * If error is set here, the Callback path isn't working
4257 	 * properly, so twiddle the appropriate LCL_ flags.
4258 	 * (nd_repstat != 0 indicates the Callback path is working,
4259 	 *  but the callback failed on the client.)
4260 	 */
4261 	if (error) {
4262 		/*
4263 		 * Mark the callback pathway down, which disabled issuing
4264 		 * of delegations and gets Renew to return NFSERR_CBPATHDOWN.
4265 		 */
4266 		NFSLOCKSTATE();
4267 		clp->lc_flags |= LCL_CBDOWN;
4268 		NFSUNLOCKSTATE();
4269 	} else {
4270 		/*
4271 		 * Callback worked. If the callback path was down, disable
4272 		 * callbacks, so no more delegations will be issued. (This
4273 		 * is done on the assumption that the callback pathway is
4274 		 * flakey.)
4275 		 */
4276 		NFSLOCKSTATE();
4277 		if (clp->lc_flags & LCL_CBDOWN)
4278 			clp->lc_flags &= ~(LCL_CBDOWN | LCL_CALLBACKSON);
4279 		NFSUNLOCKSTATE();
4280 		if (nd->nd_repstat)
4281 			error = nd->nd_repstat;
4282 		else if (error == 0 && procnum == NFSV4OP_CBGETATTR)
4283 			error = nfsv4_loadattr(nd, NULL, nap, NULL, NULL, 0,
4284 			    NULL, NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL,
4285 			    p, NULL);
4286 		mbuf_freem(nd->nd_mrep);
4287 	}
4288 	NFSLOCKSTATE();
4289 	clp->lc_cbref--;
4290 	if ((clp->lc_flags & LCL_WAKEUPWANTED) && clp->lc_cbref == 0) {
4291 		clp->lc_flags &= ~LCL_WAKEUPWANTED;
4292 		wakeup(clp);
4293 	}
4294 	NFSUNLOCKSTATE();
4295 
4296 	NFSEXITCODE(error);
4297 	return (error);
4298 }
4299 
4300 /*
4301  * Set up the compound RPC for the callback.
4302  */
4303 static int
4304 nfsrv_cbcallargs(struct nfsrv_descript *nd, struct nfsclient *clp,
4305     uint32_t callback, int op, const char *optag, struct nfsdsession **sepp)
4306 {
4307 	uint32_t *tl;
4308 	int error, len;
4309 
4310 	len = strlen(optag);
4311 	(void)nfsm_strtom(nd, optag, len);
4312 	NFSM_BUILD(tl, uint32_t *, 4 * NFSX_UNSIGNED);
4313 	if ((nd->nd_flag & ND_NFSV41) != 0) {
4314 		*tl++ = txdr_unsigned(NFSV41_MINORVERSION);
4315 		*tl++ = txdr_unsigned(callback);
4316 		*tl++ = txdr_unsigned(2);
4317 		*tl = txdr_unsigned(NFSV4OP_CBSEQUENCE);
4318 		error = nfsv4_setcbsequence(nd, clp, 1, sepp);
4319 		if (error != 0)
4320 			return (error);
4321 		NFSM_BUILD(tl, u_int32_t *, NFSX_UNSIGNED);
4322 		*tl = txdr_unsigned(op);
4323 	} else {
4324 		*tl++ = txdr_unsigned(NFSV4_MINORVERSION);
4325 		*tl++ = txdr_unsigned(callback);
4326 		*tl++ = txdr_unsigned(1);
4327 		*tl = txdr_unsigned(op);
4328 	}
4329 	return (0);
4330 }
4331 
4332 /*
4333  * Return the next index# for a clientid. Mostly just increment and return
4334  * the next one, but... if the 32bit unsigned does actually wrap around,
4335  * it should be rebooted.
4336  * At an average rate of one new client per second, it will wrap around in
4337  * approximately 136 years. (I think the server will have been shut
4338  * down or rebooted before then.)
4339  */
4340 static u_int32_t
4341 nfsrv_nextclientindex(void)
4342 {
4343 	static u_int32_t client_index = 0;
4344 
4345 	client_index++;
4346 	if (client_index != 0)
4347 		return (client_index);
4348 
4349 	printf("%s: out of clientids\n", __func__);
4350 	return (client_index);
4351 }
4352 
4353 /*
4354  * Return the next index# for a stateid. Mostly just increment and return
4355  * the next one, but... if the 32bit unsigned does actually wrap around
4356  * (will a BSD server stay up that long?), find
4357  * new start and end values.
4358  */
4359 static u_int32_t
4360 nfsrv_nextstateindex(struct nfsclient *clp)
4361 {
4362 	struct nfsstate *stp;
4363 	int i;
4364 	u_int32_t canuse, min_index, max_index;
4365 
4366 	if (!(clp->lc_flags & LCL_INDEXNOTOK)) {
4367 		clp->lc_stateindex++;
4368 		if (clp->lc_stateindex != clp->lc_statemaxindex)
4369 			return (clp->lc_stateindex);
4370 	}
4371 
4372 	/*
4373 	 * Yuck, we've hit the end.
4374 	 * Look for a new min and max.
4375 	 */
4376 	min_index = 0;
4377 	max_index = 0xffffffff;
4378 	for (i = 0; i < nfsrv_statehashsize; i++) {
4379 	    LIST_FOREACH(stp, &clp->lc_stateid[i], ls_hash) {
4380 		if (stp->ls_stateid.other[2] > 0x80000000) {
4381 		    if (stp->ls_stateid.other[2] < max_index)
4382 			max_index = stp->ls_stateid.other[2];
4383 		} else {
4384 		    if (stp->ls_stateid.other[2] > min_index)
4385 			min_index = stp->ls_stateid.other[2];
4386 		}
4387 	    }
4388 	}
4389 
4390 	/*
4391 	 * Yikes, highly unlikely, but I'll handle it anyhow.
4392 	 */
4393 	if (min_index == 0x80000000 && max_index == 0x80000001) {
4394 	    canuse = 0;
4395 	    /*
4396 	     * Loop around until we find an unused entry. Return that
4397 	     * and set LCL_INDEXNOTOK, so the search will continue next time.
4398 	     * (This is one of those rare cases where a goto is the
4399 	     *  cleanest way to code the loop.)
4400 	     */
4401 tryagain:
4402 	    for (i = 0; i < nfsrv_statehashsize; i++) {
4403 		LIST_FOREACH(stp, &clp->lc_stateid[i], ls_hash) {
4404 		    if (stp->ls_stateid.other[2] == canuse) {
4405 			canuse++;
4406 			goto tryagain;
4407 		    }
4408 		}
4409 	    }
4410 	    clp->lc_flags |= LCL_INDEXNOTOK;
4411 	    return (canuse);
4412 	}
4413 
4414 	/*
4415 	 * Ok to start again from min + 1.
4416 	 */
4417 	clp->lc_stateindex = min_index + 1;
4418 	clp->lc_statemaxindex = max_index;
4419 	clp->lc_flags &= ~LCL_INDEXNOTOK;
4420 	return (clp->lc_stateindex);
4421 }
4422 
4423 /*
4424  * The following functions handle the stable storage file that deals with
4425  * the edge conditions described in RFC3530 Sec. 8.6.3.
4426  * The file is as follows:
4427  * - a single record at the beginning that has the lease time of the
4428  *   previous server instance (before the last reboot) and the nfsrvboottime
4429  *   values for the previous server boots.
4430  *   These previous boot times are used to ensure that the current
4431  *   nfsrvboottime does not, somehow, get set to a previous one.
4432  *   (This is important so that Stale ClientIDs and StateIDs can
4433  *    be recognized.)
4434  *   The number of previous nfsvrboottime values precedes the list.
4435  * - followed by some number of appended records with:
4436  *   - client id string
4437  *   - flag that indicates it is a record revoking state via lease
4438  *     expiration or similar
4439  *     OR has successfully acquired state.
4440  * These structures vary in length, with the client string at the end, up
4441  * to NFSV4_OPAQUELIMIT in size.
4442  *
4443  * At the end of the grace period, the file is truncated, the first
4444  * record is rewritten with updated information and any acquired state
4445  * records for successful reclaims of state are written.
4446  *
4447  * Subsequent records are appended when the first state is issued to
4448  * a client and when state is revoked for a client.
4449  *
4450  * When reading the file in, state issued records that come later in
4451  * the file override older ones, since the append log is in cronological order.
4452  * If, for some reason, the file can't be read, the grace period is
4453  * immediately terminated and all reclaims get NFSERR_NOGRACE.
4454  */
4455 
4456 /*
4457  * Read in the stable storage file. Called by nfssvc() before the nfsd
4458  * processes start servicing requests.
4459  */
4460 APPLESTATIC void
4461 nfsrv_setupstable(NFSPROC_T *p)
4462 {
4463 	struct nfsrv_stablefirst *sf = &nfsrv_stablefirst;
4464 	struct nfsrv_stable *sp, *nsp;
4465 	struct nfst_rec *tsp;
4466 	int error, i, tryagain;
4467 	off_t off = 0;
4468 	ssize_t aresid, len;
4469 
4470 	/*
4471 	 * If NFSNSF_UPDATEDONE is set, this is a restart of the nfsds without
4472 	 * a reboot, so state has not been lost.
4473 	 */
4474 	if (sf->nsf_flags & NFSNSF_UPDATEDONE)
4475 		return;
4476 	/*
4477 	 * Set Grace over just until the file reads successfully.
4478 	 */
4479 	nfsrvboottime = time_second;
4480 	LIST_INIT(&sf->nsf_head);
4481 	sf->nsf_flags = (NFSNSF_GRACEOVER | NFSNSF_NEEDLOCK);
4482 	sf->nsf_eograce = NFSD_MONOSEC + NFSRV_LEASEDELTA;
4483 	if (sf->nsf_fp == NULL)
4484 		return;
4485 	error = NFSD_RDWR(UIO_READ, NFSFPVNODE(sf->nsf_fp),
4486 	    (caddr_t)&sf->nsf_rec, sizeof (struct nfsf_rec), off, UIO_SYSSPACE,
4487 	    0, NFSFPCRED(sf->nsf_fp), &aresid, p);
4488 	if (error || aresid || sf->nsf_numboots == 0 ||
4489 		sf->nsf_numboots > NFSNSF_MAXNUMBOOTS)
4490 		return;
4491 
4492 	/*
4493 	 * Now, read in the boottimes.
4494 	 */
4495 	sf->nsf_bootvals = (time_t *)malloc((sf->nsf_numboots + 1) *
4496 		sizeof (time_t), M_TEMP, M_WAITOK);
4497 	off = sizeof (struct nfsf_rec);
4498 	error = NFSD_RDWR(UIO_READ, NFSFPVNODE(sf->nsf_fp),
4499 	    (caddr_t)sf->nsf_bootvals, sf->nsf_numboots * sizeof (time_t), off,
4500 	    UIO_SYSSPACE, 0, NFSFPCRED(sf->nsf_fp), &aresid, p);
4501 	if (error || aresid) {
4502 		free((caddr_t)sf->nsf_bootvals, M_TEMP);
4503 		sf->nsf_bootvals = NULL;
4504 		return;
4505 	}
4506 
4507 	/*
4508 	 * Make sure this nfsrvboottime is different from all recorded
4509 	 * previous ones.
4510 	 */
4511 	do {
4512 		tryagain = 0;
4513 		for (i = 0; i < sf->nsf_numboots; i++) {
4514 			if (nfsrvboottime == sf->nsf_bootvals[i]) {
4515 				nfsrvboottime++;
4516 				tryagain = 1;
4517 				break;
4518 			}
4519 		}
4520 	} while (tryagain);
4521 
4522 	sf->nsf_flags |= NFSNSF_OK;
4523 	off += (sf->nsf_numboots * sizeof (time_t));
4524 
4525 	/*
4526 	 * Read through the file, building a list of records for grace
4527 	 * checking.
4528 	 * Each record is between sizeof (struct nfst_rec) and
4529 	 * sizeof (struct nfst_rec) + NFSV4_OPAQUELIMIT - 1
4530 	 * and is actually sizeof (struct nfst_rec) + nst_len - 1.
4531 	 */
4532 	tsp = (struct nfst_rec *)malloc(sizeof (struct nfst_rec) +
4533 		NFSV4_OPAQUELIMIT - 1, M_TEMP, M_WAITOK);
4534 	do {
4535 	    error = NFSD_RDWR(UIO_READ, NFSFPVNODE(sf->nsf_fp),
4536 	        (caddr_t)tsp, sizeof (struct nfst_rec) + NFSV4_OPAQUELIMIT - 1,
4537 	        off, UIO_SYSSPACE, 0, NFSFPCRED(sf->nsf_fp), &aresid, p);
4538 	    len = (sizeof (struct nfst_rec) + NFSV4_OPAQUELIMIT - 1) - aresid;
4539 	    if (error || (len > 0 && (len < sizeof (struct nfst_rec) ||
4540 		len < (sizeof (struct nfst_rec) + tsp->len - 1)))) {
4541 		/*
4542 		 * Yuck, the file has been corrupted, so just return
4543 		 * after clearing out any restart state, so the grace period
4544 		 * is over.
4545 		 */
4546 		LIST_FOREACH_SAFE(sp, &sf->nsf_head, nst_list, nsp) {
4547 			LIST_REMOVE(sp, nst_list);
4548 			free((caddr_t)sp, M_TEMP);
4549 		}
4550 		free((caddr_t)tsp, M_TEMP);
4551 		sf->nsf_flags &= ~NFSNSF_OK;
4552 		free((caddr_t)sf->nsf_bootvals, M_TEMP);
4553 		sf->nsf_bootvals = NULL;
4554 		return;
4555 	    }
4556 	    if (len > 0) {
4557 		off += sizeof (struct nfst_rec) + tsp->len - 1;
4558 		/*
4559 		 * Search the list for a matching client.
4560 		 */
4561 		LIST_FOREACH(sp, &sf->nsf_head, nst_list) {
4562 			if (tsp->len == sp->nst_len &&
4563 			    !NFSBCMP(tsp->client, sp->nst_client, tsp->len))
4564 				break;
4565 		}
4566 		if (sp == LIST_END(&sf->nsf_head)) {
4567 			sp = (struct nfsrv_stable *)malloc(tsp->len +
4568 				sizeof (struct nfsrv_stable) - 1, M_TEMP,
4569 				M_WAITOK);
4570 			NFSBCOPY((caddr_t)tsp, (caddr_t)&sp->nst_rec,
4571 				sizeof (struct nfst_rec) + tsp->len - 1);
4572 			LIST_INSERT_HEAD(&sf->nsf_head, sp, nst_list);
4573 		} else {
4574 			if (tsp->flag == NFSNST_REVOKE)
4575 				sp->nst_flag |= NFSNST_REVOKE;
4576 			else
4577 				/*
4578 				 * A subsequent timestamp indicates the client
4579 				 * did a setclientid/confirm and any previous
4580 				 * revoke is no longer relevant.
4581 				 */
4582 				sp->nst_flag &= ~NFSNST_REVOKE;
4583 		}
4584 	    }
4585 	} while (len > 0);
4586 	free((caddr_t)tsp, M_TEMP);
4587 	sf->nsf_flags = NFSNSF_OK;
4588 	sf->nsf_eograce = NFSD_MONOSEC + sf->nsf_lease +
4589 		NFSRV_LEASEDELTA;
4590 }
4591 
4592 /*
4593  * Update the stable storage file, now that the grace period is over.
4594  */
4595 APPLESTATIC void
4596 nfsrv_updatestable(NFSPROC_T *p)
4597 {
4598 	struct nfsrv_stablefirst *sf = &nfsrv_stablefirst;
4599 	struct nfsrv_stable *sp, *nsp;
4600 	int i;
4601 	struct nfsvattr nva;
4602 	vnode_t vp;
4603 #if defined(__FreeBSD_version) && (__FreeBSD_version >= 500000)
4604 	mount_t mp = NULL;
4605 #endif
4606 	int error;
4607 
4608 	if (sf->nsf_fp == NULL || (sf->nsf_flags & NFSNSF_UPDATEDONE))
4609 		return;
4610 	sf->nsf_flags |= NFSNSF_UPDATEDONE;
4611 	/*
4612 	 * Ok, we need to rewrite the stable storage file.
4613 	 * - truncate to 0 length
4614 	 * - write the new first structure
4615 	 * - loop through the data structures, writing out any that
4616 	 *   have timestamps older than the old boot
4617 	 */
4618 	if (sf->nsf_bootvals) {
4619 		sf->nsf_numboots++;
4620 		for (i = sf->nsf_numboots - 2; i >= 0; i--)
4621 			sf->nsf_bootvals[i + 1] = sf->nsf_bootvals[i];
4622 	} else {
4623 		sf->nsf_numboots = 1;
4624 		sf->nsf_bootvals = (time_t *)malloc(sizeof (time_t),
4625 			M_TEMP, M_WAITOK);
4626 	}
4627 	sf->nsf_bootvals[0] = nfsrvboottime;
4628 	sf->nsf_lease = nfsrv_lease;
4629 	NFSVNO_ATTRINIT(&nva);
4630 	NFSVNO_SETATTRVAL(&nva, size, 0);
4631 	vp = NFSFPVNODE(sf->nsf_fp);
4632 	vn_start_write(vp, &mp, V_WAIT);
4633 	if (NFSVOPLOCK(vp, LK_EXCLUSIVE) == 0) {
4634 		error = nfsvno_setattr(vp, &nva, NFSFPCRED(sf->nsf_fp), p,
4635 		    NULL);
4636 		NFSVOPUNLOCK(vp, 0);
4637 	} else
4638 		error = EPERM;
4639 	vn_finished_write(mp);
4640 	if (!error)
4641 	    error = NFSD_RDWR(UIO_WRITE, vp,
4642 		(caddr_t)&sf->nsf_rec, sizeof (struct nfsf_rec), (off_t)0,
4643 		UIO_SYSSPACE, IO_SYNC, NFSFPCRED(sf->nsf_fp), NULL, p);
4644 	if (!error)
4645 	    error = NFSD_RDWR(UIO_WRITE, vp,
4646 		(caddr_t)sf->nsf_bootvals,
4647 		sf->nsf_numboots * sizeof (time_t),
4648 		(off_t)(sizeof (struct nfsf_rec)),
4649 		UIO_SYSSPACE, IO_SYNC, NFSFPCRED(sf->nsf_fp), NULL, p);
4650 	free((caddr_t)sf->nsf_bootvals, M_TEMP);
4651 	sf->nsf_bootvals = NULL;
4652 	if (error) {
4653 		sf->nsf_flags &= ~NFSNSF_OK;
4654 		printf("EEK! Can't write NfsV4 stable storage file\n");
4655 		return;
4656 	}
4657 	sf->nsf_flags |= NFSNSF_OK;
4658 
4659 	/*
4660 	 * Loop through the list and write out timestamp records for
4661 	 * any clients that successfully reclaimed state.
4662 	 */
4663 	LIST_FOREACH_SAFE(sp, &sf->nsf_head, nst_list, nsp) {
4664 		if (sp->nst_flag & NFSNST_GOTSTATE) {
4665 			nfsrv_writestable(sp->nst_client, sp->nst_len,
4666 				NFSNST_NEWSTATE, p);
4667 			sp->nst_clp->lc_flags |= LCL_STAMPEDSTABLE;
4668 		}
4669 		LIST_REMOVE(sp, nst_list);
4670 		free((caddr_t)sp, M_TEMP);
4671 	}
4672 	nfsrv_backupstable();
4673 }
4674 
4675 /*
4676  * Append a record to the stable storage file.
4677  */
4678 APPLESTATIC void
4679 nfsrv_writestable(u_char *client, int len, int flag, NFSPROC_T *p)
4680 {
4681 	struct nfsrv_stablefirst *sf = &nfsrv_stablefirst;
4682 	struct nfst_rec *sp;
4683 	int error;
4684 
4685 	if (!(sf->nsf_flags & NFSNSF_OK) || sf->nsf_fp == NULL)
4686 		return;
4687 	sp = (struct nfst_rec *)malloc(sizeof (struct nfst_rec) +
4688 		len - 1, M_TEMP, M_WAITOK);
4689 	sp->len = len;
4690 	NFSBCOPY(client, sp->client, len);
4691 	sp->flag = flag;
4692 	error = NFSD_RDWR(UIO_WRITE, NFSFPVNODE(sf->nsf_fp),
4693 	    (caddr_t)sp, sizeof (struct nfst_rec) + len - 1, (off_t)0,
4694 	    UIO_SYSSPACE, (IO_SYNC | IO_APPEND), NFSFPCRED(sf->nsf_fp), NULL, p);
4695 	free((caddr_t)sp, M_TEMP);
4696 	if (error) {
4697 		sf->nsf_flags &= ~NFSNSF_OK;
4698 		printf("EEK! Can't write NfsV4 stable storage file\n");
4699 	}
4700 }
4701 
4702 /*
4703  * This function is called during the grace period to mark a client
4704  * that successfully reclaimed state.
4705  */
4706 static void
4707 nfsrv_markstable(struct nfsclient *clp)
4708 {
4709 	struct nfsrv_stable *sp;
4710 
4711 	/*
4712 	 * First find the client structure.
4713 	 */
4714 	LIST_FOREACH(sp, &nfsrv_stablefirst.nsf_head, nst_list) {
4715 		if (sp->nst_len == clp->lc_idlen &&
4716 		    !NFSBCMP(sp->nst_client, clp->lc_id, sp->nst_len))
4717 			break;
4718 	}
4719 	if (sp == LIST_END(&nfsrv_stablefirst.nsf_head))
4720 		return;
4721 
4722 	/*
4723 	 * Now, just mark it and set the nfsclient back pointer.
4724 	 */
4725 	sp->nst_flag |= NFSNST_GOTSTATE;
4726 	sp->nst_clp = clp;
4727 }
4728 
4729 /*
4730  * This function is called for a reclaim, to see if it gets grace.
4731  * It returns 0 if a reclaim is allowed, 1 otherwise.
4732  */
4733 static int
4734 nfsrv_checkstable(struct nfsclient *clp)
4735 {
4736 	struct nfsrv_stable *sp;
4737 
4738 	/*
4739 	 * First, find the entry for the client.
4740 	 */
4741 	LIST_FOREACH(sp, &nfsrv_stablefirst.nsf_head, nst_list) {
4742 		if (sp->nst_len == clp->lc_idlen &&
4743 		    !NFSBCMP(sp->nst_client, clp->lc_id, sp->nst_len))
4744 			break;
4745 	}
4746 
4747 	/*
4748 	 * If not in the list, state was revoked or no state was issued
4749 	 * since the previous reboot, a reclaim is denied.
4750 	 */
4751 	if (sp == LIST_END(&nfsrv_stablefirst.nsf_head) ||
4752 	    (sp->nst_flag & NFSNST_REVOKE) ||
4753 	    !(nfsrv_stablefirst.nsf_flags & NFSNSF_OK))
4754 		return (1);
4755 	return (0);
4756 }
4757 
4758 /*
4759  * Test for and try to clear out a conflicting client. This is called by
4760  * nfsrv_lockctrl() and nfsrv_openctrl() when conflicts with other clients
4761  * a found.
4762  * The trick here is that it can't revoke a conflicting client with an
4763  * expired lease unless it holds the v4root lock, so...
4764  * If no v4root lock, get the lock and return 1 to indicate "try again".
4765  * Return 0 to indicate the conflict can't be revoked and 1 to indicate
4766  * the revocation worked and the conflicting client is "bye, bye", so it
4767  * can be tried again.
4768  * Return 2 to indicate that the vnode is VI_DOOMED after NFSVOPLOCK().
4769  * Unlocks State before a non-zero value is returned.
4770  */
4771 static int
4772 nfsrv_clientconflict(struct nfsclient *clp, int *haslockp, vnode_t vp,
4773     NFSPROC_T *p)
4774 {
4775 	int gotlock, lktype = 0;
4776 
4777 	/*
4778 	 * If lease hasn't expired, we can't fix it.
4779 	 */
4780 	if (clp->lc_expiry >= NFSD_MONOSEC ||
4781 	    !(nfsrv_stablefirst.nsf_flags & NFSNSF_UPDATEDONE))
4782 		return (0);
4783 	if (*haslockp == 0) {
4784 		NFSUNLOCKSTATE();
4785 		if (vp != NULL) {
4786 			lktype = NFSVOPISLOCKED(vp);
4787 			NFSVOPUNLOCK(vp, 0);
4788 		}
4789 		NFSLOCKV4ROOTMUTEX();
4790 		nfsv4_relref(&nfsv4rootfs_lock);
4791 		do {
4792 			gotlock = nfsv4_lock(&nfsv4rootfs_lock, 1, NULL,
4793 			    NFSV4ROOTLOCKMUTEXPTR, NULL);
4794 		} while (!gotlock);
4795 		NFSUNLOCKV4ROOTMUTEX();
4796 		*haslockp = 1;
4797 		if (vp != NULL) {
4798 			NFSVOPLOCK(vp, lktype | LK_RETRY);
4799 			if ((vp->v_iflag & VI_DOOMED) != 0)
4800 				return (2);
4801 		}
4802 		return (1);
4803 	}
4804 	NFSUNLOCKSTATE();
4805 
4806 	/*
4807 	 * Ok, we can expire the conflicting client.
4808 	 */
4809 	nfsrv_writestable(clp->lc_id, clp->lc_idlen, NFSNST_REVOKE, p);
4810 	nfsrv_backupstable();
4811 	nfsrv_cleanclient(clp, p);
4812 	nfsrv_freedeleglist(&clp->lc_deleg);
4813 	nfsrv_freedeleglist(&clp->lc_olddeleg);
4814 	LIST_REMOVE(clp, lc_hash);
4815 	nfsrv_zapclient(clp, p);
4816 	return (1);
4817 }
4818 
4819 /*
4820  * Resolve a delegation conflict.
4821  * Returns 0 to indicate the conflict was resolved without sleeping.
4822  * Return -1 to indicate that the caller should check for conflicts again.
4823  * Return > 0 for an error that should be returned, normally NFSERR_DELAY.
4824  *
4825  * Also, manipulate the nfsv4root_lock, as required. It isn't changed
4826  * for a return of 0, since there was no sleep and it could be required
4827  * later. It is released for a return of NFSERR_DELAY, since the caller
4828  * will return that error. It is released when a sleep was done waiting
4829  * for the delegation to be returned or expire (so that other nfsds can
4830  * handle ops). Then, it must be acquired for the write to stable storage.
4831  * (This function is somewhat similar to nfsrv_clientconflict(), but
4832  *  the semantics differ in a couple of subtle ways. The return of 0
4833  *  indicates the conflict was resolved without sleeping here, not
4834  *  that the conflict can't be resolved and the handling of nfsv4root_lock
4835  *  differs, as noted above.)
4836  * Unlocks State before returning a non-zero value.
4837  */
4838 static int
4839 nfsrv_delegconflict(struct nfsstate *stp, int *haslockp, NFSPROC_T *p,
4840     vnode_t vp)
4841 {
4842 	struct nfsclient *clp = stp->ls_clp;
4843 	int gotlock, error, lktype = 0, retrycnt, zapped_clp;
4844 	nfsv4stateid_t tstateid;
4845 	fhandle_t tfh;
4846 
4847 	/*
4848 	 * If the conflict is with an old delegation...
4849 	 */
4850 	if (stp->ls_flags & NFSLCK_OLDDELEG) {
4851 		/*
4852 		 * You can delete it, if it has expired.
4853 		 */
4854 		if (clp->lc_delegtime < NFSD_MONOSEC) {
4855 			nfsrv_freedeleg(stp);
4856 			NFSUNLOCKSTATE();
4857 			error = -1;
4858 			goto out;
4859 		}
4860 		NFSUNLOCKSTATE();
4861 		/*
4862 		 * During this delay, the old delegation could expire or it
4863 		 * could be recovered by the client via an Open with
4864 		 * CLAIM_DELEGATE_PREV.
4865 		 * Release the nfsv4root_lock, if held.
4866 		 */
4867 		if (*haslockp) {
4868 			*haslockp = 0;
4869 			NFSLOCKV4ROOTMUTEX();
4870 			nfsv4_unlock(&nfsv4rootfs_lock, 1);
4871 			NFSUNLOCKV4ROOTMUTEX();
4872 		}
4873 		error = NFSERR_DELAY;
4874 		goto out;
4875 	}
4876 
4877 	/*
4878 	 * It's a current delegation, so:
4879 	 * - check to see if the delegation has expired
4880 	 *   - if so, get the v4root lock and then expire it
4881 	 */
4882 	if (!(stp->ls_flags & NFSLCK_DELEGRECALL)) {
4883 		/*
4884 		 * - do a recall callback, since not yet done
4885 		 * For now, never allow truncate to be set. To use
4886 		 * truncate safely, it must be guaranteed that the
4887 		 * Remove, Rename or Setattr with size of 0 will
4888 		 * succeed and that would require major changes to
4889 		 * the VFS/Vnode OPs.
4890 		 * Set the expiry time large enough so that it won't expire
4891 		 * until after the callback, then set it correctly, once
4892 		 * the callback is done. (The delegation will now time
4893 		 * out whether or not the Recall worked ok. The timeout
4894 		 * will be extended when ops are done on the delegation
4895 		 * stateid, up to the timelimit.)
4896 		 */
4897 		stp->ls_delegtime = NFSD_MONOSEC + (2 * nfsrv_lease) +
4898 		    NFSRV_LEASEDELTA;
4899 		stp->ls_delegtimelimit = NFSD_MONOSEC + (6 * nfsrv_lease) +
4900 		    NFSRV_LEASEDELTA;
4901 		stp->ls_flags |= NFSLCK_DELEGRECALL;
4902 
4903 		/*
4904 		 * Loop NFSRV_CBRETRYCNT times while the CBRecall replies
4905 		 * NFSERR_BADSTATEID or NFSERR_BADHANDLE. This is done
4906 		 * in order to try and avoid a race that could happen
4907 		 * when a CBRecall request passed the Open reply with
4908 		 * the delegation in it when transitting the network.
4909 		 * Since nfsrv_docallback will sleep, don't use stp after
4910 		 * the call.
4911 		 */
4912 		NFSBCOPY((caddr_t)&stp->ls_stateid, (caddr_t)&tstateid,
4913 		    sizeof (tstateid));
4914 		NFSBCOPY((caddr_t)&stp->ls_lfp->lf_fh, (caddr_t)&tfh,
4915 		    sizeof (tfh));
4916 		NFSUNLOCKSTATE();
4917 		if (*haslockp) {
4918 			*haslockp = 0;
4919 			NFSLOCKV4ROOTMUTEX();
4920 			nfsv4_unlock(&nfsv4rootfs_lock, 1);
4921 			NFSUNLOCKV4ROOTMUTEX();
4922 		}
4923 		retrycnt = 0;
4924 		do {
4925 		    error = nfsrv_docallback(clp, NFSV4OP_CBRECALL,
4926 			&tstateid, 0, &tfh, NULL, NULL, p);
4927 		    retrycnt++;
4928 		} while ((error == NFSERR_BADSTATEID ||
4929 		    error == NFSERR_BADHANDLE) && retrycnt < NFSV4_CBRETRYCNT);
4930 		error = NFSERR_DELAY;
4931 		goto out;
4932 	}
4933 
4934 	if (clp->lc_expiry >= NFSD_MONOSEC &&
4935 	    stp->ls_delegtime >= NFSD_MONOSEC) {
4936 		NFSUNLOCKSTATE();
4937 		/*
4938 		 * A recall has been done, but it has not yet expired.
4939 		 * So, RETURN_DELAY.
4940 		 */
4941 		if (*haslockp) {
4942 			*haslockp = 0;
4943 			NFSLOCKV4ROOTMUTEX();
4944 			nfsv4_unlock(&nfsv4rootfs_lock, 1);
4945 			NFSUNLOCKV4ROOTMUTEX();
4946 		}
4947 		error = NFSERR_DELAY;
4948 		goto out;
4949 	}
4950 
4951 	/*
4952 	 * If we don't yet have the lock, just get it and then return,
4953 	 * since we need that before deleting expired state, such as
4954 	 * this delegation.
4955 	 * When getting the lock, unlock the vnode, so other nfsds that
4956 	 * are in progress, won't get stuck waiting for the vnode lock.
4957 	 */
4958 	if (*haslockp == 0) {
4959 		NFSUNLOCKSTATE();
4960 		if (vp != NULL) {
4961 			lktype = NFSVOPISLOCKED(vp);
4962 			NFSVOPUNLOCK(vp, 0);
4963 		}
4964 		NFSLOCKV4ROOTMUTEX();
4965 		nfsv4_relref(&nfsv4rootfs_lock);
4966 		do {
4967 			gotlock = nfsv4_lock(&nfsv4rootfs_lock, 1, NULL,
4968 			    NFSV4ROOTLOCKMUTEXPTR, NULL);
4969 		} while (!gotlock);
4970 		NFSUNLOCKV4ROOTMUTEX();
4971 		*haslockp = 1;
4972 		if (vp != NULL) {
4973 			NFSVOPLOCK(vp, lktype | LK_RETRY);
4974 			if ((vp->v_iflag & VI_DOOMED) != 0) {
4975 				*haslockp = 0;
4976 				NFSLOCKV4ROOTMUTEX();
4977 				nfsv4_unlock(&nfsv4rootfs_lock, 1);
4978 				NFSUNLOCKV4ROOTMUTEX();
4979 				error = NFSERR_PERM;
4980 				goto out;
4981 			}
4982 		}
4983 		error = -1;
4984 		goto out;
4985 	}
4986 
4987 	NFSUNLOCKSTATE();
4988 	/*
4989 	 * Ok, we can delete the expired delegation.
4990 	 * First, write the Revoke record to stable storage and then
4991 	 * clear out the conflict.
4992 	 * Since all other nfsd threads are now blocked, we can safely
4993 	 * sleep without the state changing.
4994 	 */
4995 	nfsrv_writestable(clp->lc_id, clp->lc_idlen, NFSNST_REVOKE, p);
4996 	nfsrv_backupstable();
4997 	if (clp->lc_expiry < NFSD_MONOSEC) {
4998 		nfsrv_cleanclient(clp, p);
4999 		nfsrv_freedeleglist(&clp->lc_deleg);
5000 		nfsrv_freedeleglist(&clp->lc_olddeleg);
5001 		LIST_REMOVE(clp, lc_hash);
5002 		zapped_clp = 1;
5003 	} else {
5004 		nfsrv_freedeleg(stp);
5005 		zapped_clp = 0;
5006 	}
5007 	if (zapped_clp)
5008 		nfsrv_zapclient(clp, p);
5009 	error = -1;
5010 
5011 out:
5012 	NFSEXITCODE(error);
5013 	return (error);
5014 }
5015 
5016 /*
5017  * Check for a remove allowed, if remove is set to 1 and get rid of
5018  * delegations.
5019  */
5020 APPLESTATIC int
5021 nfsrv_checkremove(vnode_t vp, int remove, NFSPROC_T *p)
5022 {
5023 	struct nfsstate *stp;
5024 	struct nfslockfile *lfp;
5025 	int error, haslock = 0;
5026 	fhandle_t nfh;
5027 
5028 	/*
5029 	 * First, get the lock file structure.
5030 	 * (A return of -1 means no associated state, so remove ok.)
5031 	 */
5032 	error = nfsrv_getlockfh(vp, NFSLCK_CHECK, NULL, &nfh, p);
5033 tryagain:
5034 	NFSLOCKSTATE();
5035 	if (!error)
5036 		error = nfsrv_getlockfile(NFSLCK_CHECK, NULL, &lfp, &nfh, 0);
5037 	if (error) {
5038 		NFSUNLOCKSTATE();
5039 		if (haslock) {
5040 			NFSLOCKV4ROOTMUTEX();
5041 			nfsv4_unlock(&nfsv4rootfs_lock, 1);
5042 			NFSUNLOCKV4ROOTMUTEX();
5043 		}
5044 		if (error == -1)
5045 			error = 0;
5046 		goto out;
5047 	}
5048 
5049 	/*
5050 	 * Now, we must Recall any delegations.
5051 	 */
5052 	error = nfsrv_cleandeleg(vp, lfp, NULL, &haslock, p);
5053 	if (error) {
5054 		/*
5055 		 * nfsrv_cleandeleg() unlocks state for non-zero
5056 		 * return.
5057 		 */
5058 		if (error == -1)
5059 			goto tryagain;
5060 		if (haslock) {
5061 			NFSLOCKV4ROOTMUTEX();
5062 			nfsv4_unlock(&nfsv4rootfs_lock, 1);
5063 			NFSUNLOCKV4ROOTMUTEX();
5064 		}
5065 		goto out;
5066 	}
5067 
5068 	/*
5069 	 * Now, look for a conflicting open share.
5070 	 */
5071 	if (remove) {
5072 		/*
5073 		 * If the entry in the directory was the last reference to the
5074 		 * corresponding filesystem object, the object can be destroyed
5075 		 * */
5076 		if(lfp->lf_usecount>1)
5077 			LIST_FOREACH(stp, &lfp->lf_open, ls_file) {
5078 				if (stp->ls_flags & NFSLCK_WRITEDENY) {
5079 					error = NFSERR_FILEOPEN;
5080 					break;
5081 				}
5082 			}
5083 	}
5084 
5085 	NFSUNLOCKSTATE();
5086 	if (haslock) {
5087 		NFSLOCKV4ROOTMUTEX();
5088 		nfsv4_unlock(&nfsv4rootfs_lock, 1);
5089 		NFSUNLOCKV4ROOTMUTEX();
5090 	}
5091 
5092 out:
5093 	NFSEXITCODE(error);
5094 	return (error);
5095 }
5096 
5097 /*
5098  * Clear out all delegations for the file referred to by lfp.
5099  * May return NFSERR_DELAY, if there will be a delay waiting for
5100  * delegations to expire.
5101  * Returns -1 to indicate it slept while recalling a delegation.
5102  * This function has the side effect of deleting the nfslockfile structure,
5103  * if it no longer has associated state and didn't have to sleep.
5104  * Unlocks State before a non-zero value is returned.
5105  */
5106 static int
5107 nfsrv_cleandeleg(vnode_t vp, struct nfslockfile *lfp,
5108     struct nfsclient *clp, int *haslockp, NFSPROC_T *p)
5109 {
5110 	struct nfsstate *stp, *nstp;
5111 	int ret = 0;
5112 
5113 	stp = LIST_FIRST(&lfp->lf_deleg);
5114 	while (stp != LIST_END(&lfp->lf_deleg)) {
5115 		nstp = LIST_NEXT(stp, ls_file);
5116 		if (stp->ls_clp != clp) {
5117 			ret = nfsrv_delegconflict(stp, haslockp, p, vp);
5118 			if (ret) {
5119 				/*
5120 				 * nfsrv_delegconflict() unlocks state
5121 				 * when it returns non-zero.
5122 				 */
5123 				goto out;
5124 			}
5125 		}
5126 		stp = nstp;
5127 	}
5128 out:
5129 	NFSEXITCODE(ret);
5130 	return (ret);
5131 }
5132 
5133 /*
5134  * There are certain operations that, when being done outside of NFSv4,
5135  * require that any NFSv4 delegation for the file be recalled.
5136  * This function is to be called for those cases:
5137  * VOP_RENAME() - When a delegation is being recalled for any reason,
5138  *	the client may have to do Opens against the server, using the file's
5139  *	final component name. If the file has been renamed on the server,
5140  *	that component name will be incorrect and the Open will fail.
5141  * VOP_REMOVE() - Theoretically, a client could Open a file after it has
5142  *	been removed on the server, if there is a delegation issued to
5143  *	that client for the file. I say "theoretically" since clients
5144  *	normally do an Access Op before the Open and that Access Op will
5145  *	fail with ESTALE. Note that NFSv2 and 3 don't even do Opens, so
5146  *	they will detect the file's removal in the same manner. (There is
5147  *	one case where RFC3530 allows a client to do an Open without first
5148  *	doing an Access Op, which is passage of a check against the ACE
5149  *	returned with a Write delegation, but current practice is to ignore
5150  *	the ACE and always do an Access Op.)
5151  *	Since the functions can only be called with an unlocked vnode, this
5152  *	can't be done at this time.
5153  * VOP_ADVLOCK() - When a client holds a delegation, it can issue byte range
5154  *	locks locally in the client, which are not visible to the server. To
5155  *	deal with this, issuing of delegations for a vnode must be disabled
5156  *	and all delegations for the vnode recalled. This is done via the
5157  *	second function, using the VV_DISABLEDELEG vflag on the vnode.
5158  */
5159 APPLESTATIC void
5160 nfsd_recalldelegation(vnode_t vp, NFSPROC_T *p)
5161 {
5162 	time_t starttime;
5163 	int error;
5164 
5165 	/*
5166 	 * First, check to see if the server is currently running and it has
5167 	 * been called for a regular file when issuing delegations.
5168 	 */
5169 	if (newnfs_numnfsd == 0 || vp->v_type != VREG ||
5170 	    nfsrv_issuedelegs == 0)
5171 		return;
5172 
5173 	KASSERT((NFSVOPISLOCKED(vp) != LK_EXCLUSIVE), ("vp %p is locked", vp));
5174 	/*
5175 	 * First, get a reference on the nfsv4rootfs_lock so that an
5176 	 * exclusive lock cannot be acquired by another thread.
5177 	 */
5178 	NFSLOCKV4ROOTMUTEX();
5179 	nfsv4_getref(&nfsv4rootfs_lock, NULL, NFSV4ROOTLOCKMUTEXPTR, NULL);
5180 	NFSUNLOCKV4ROOTMUTEX();
5181 
5182 	/*
5183 	 * Now, call nfsrv_checkremove() in a loop while it returns
5184 	 * NFSERR_DELAY. Return upon any other error or when timed out.
5185 	 */
5186 	starttime = NFSD_MONOSEC;
5187 	do {
5188 		if (NFSVOPLOCK(vp, LK_EXCLUSIVE) == 0) {
5189 			error = nfsrv_checkremove(vp, 0, p);
5190 			NFSVOPUNLOCK(vp, 0);
5191 		} else
5192 			error = EPERM;
5193 		if (error == NFSERR_DELAY) {
5194 			if (NFSD_MONOSEC - starttime > NFS_REMOVETIMEO)
5195 				break;
5196 			/* Sleep for a short period of time */
5197 			(void) nfs_catnap(PZERO, 0, "nfsremove");
5198 		}
5199 	} while (error == NFSERR_DELAY);
5200 	NFSLOCKV4ROOTMUTEX();
5201 	nfsv4_relref(&nfsv4rootfs_lock);
5202 	NFSUNLOCKV4ROOTMUTEX();
5203 }
5204 
5205 APPLESTATIC void
5206 nfsd_disabledelegation(vnode_t vp, NFSPROC_T *p)
5207 {
5208 
5209 #ifdef VV_DISABLEDELEG
5210 	/*
5211 	 * First, flag issuance of delegations disabled.
5212 	 */
5213 	atomic_set_long(&vp->v_vflag, VV_DISABLEDELEG);
5214 #endif
5215 
5216 	/*
5217 	 * Then call nfsd_recalldelegation() to get rid of all extant
5218 	 * delegations.
5219 	 */
5220 	nfsd_recalldelegation(vp, p);
5221 }
5222 
5223 /*
5224  * Check for conflicting locks, etc. and then get rid of delegations.
5225  * (At one point I thought that I should get rid of delegations for any
5226  *  Setattr, since it could potentially disallow the I/O op (read or write)
5227  *  allowed by the delegation. However, Setattr Ops that aren't changing
5228  *  the size get a stateid of all 0s, so you can't tell if it is a delegation
5229  *  for the same client or a different one, so I decided to only get rid
5230  *  of delegations for other clients when the size is being changed.)
5231  * In general, a Setattr can disable NFS I/O Ops that are outstanding, such
5232  * as Write backs, even if there is no delegation, so it really isn't any
5233  * different?)
5234  */
5235 APPLESTATIC int
5236 nfsrv_checksetattr(vnode_t vp, struct nfsrv_descript *nd,
5237     nfsv4stateid_t *stateidp, struct nfsvattr *nvap, nfsattrbit_t *attrbitp,
5238     struct nfsexstuff *exp, NFSPROC_T *p)
5239 {
5240 	struct nfsstate st, *stp = &st;
5241 	struct nfslock lo, *lop = &lo;
5242 	int error = 0;
5243 	nfsquad_t clientid;
5244 
5245 	if (NFSISSET_ATTRBIT(attrbitp, NFSATTRBIT_SIZE)) {
5246 		stp->ls_flags = (NFSLCK_CHECK | NFSLCK_WRITEACCESS);
5247 		lop->lo_first = nvap->na_size;
5248 	} else {
5249 		stp->ls_flags = 0;
5250 		lop->lo_first = 0;
5251 	}
5252 	if (NFSISSET_ATTRBIT(attrbitp, NFSATTRBIT_OWNER) ||
5253 	    NFSISSET_ATTRBIT(attrbitp, NFSATTRBIT_OWNERGROUP) ||
5254 	    NFSISSET_ATTRBIT(attrbitp, NFSATTRBIT_MODE) ||
5255 	    NFSISSET_ATTRBIT(attrbitp, NFSATTRBIT_ACL))
5256 		stp->ls_flags |= NFSLCK_SETATTR;
5257 	if (stp->ls_flags == 0)
5258 		goto out;
5259 	lop->lo_end = NFS64BITSSET;
5260 	lop->lo_flags = NFSLCK_WRITE;
5261 	stp->ls_ownerlen = 0;
5262 	stp->ls_op = NULL;
5263 	stp->ls_uid = nd->nd_cred->cr_uid;
5264 	stp->ls_stateid.seqid = stateidp->seqid;
5265 	clientid.lval[0] = stp->ls_stateid.other[0] = stateidp->other[0];
5266 	clientid.lval[1] = stp->ls_stateid.other[1] = stateidp->other[1];
5267 	stp->ls_stateid.other[2] = stateidp->other[2];
5268 	error = nfsrv_lockctrl(vp, &stp, &lop, NULL, clientid,
5269 	    stateidp, exp, nd, p);
5270 
5271 out:
5272 	NFSEXITCODE2(error, nd);
5273 	return (error);
5274 }
5275 
5276 /*
5277  * Check for a write delegation and do a CBGETATTR if there is one, updating
5278  * the attributes, as required.
5279  * Should I return an error if I can't get the attributes? (For now, I'll
5280  * just return ok.
5281  */
5282 APPLESTATIC int
5283 nfsrv_checkgetattr(struct nfsrv_descript *nd, vnode_t vp,
5284     struct nfsvattr *nvap, nfsattrbit_t *attrbitp, struct ucred *cred,
5285     NFSPROC_T *p)
5286 {
5287 	struct nfsstate *stp;
5288 	struct nfslockfile *lfp;
5289 	struct nfsclient *clp;
5290 	struct nfsvattr nva;
5291 	fhandle_t nfh;
5292 	int error = 0;
5293 	nfsattrbit_t cbbits;
5294 	u_quad_t delegfilerev;
5295 
5296 	NFSCBGETATTR_ATTRBIT(attrbitp, &cbbits);
5297 	if (!NFSNONZERO_ATTRBIT(&cbbits))
5298 		goto out;
5299 
5300 	/*
5301 	 * Get the lock file structure.
5302 	 * (A return of -1 means no associated state, so return ok.)
5303 	 */
5304 	error = nfsrv_getlockfh(vp, NFSLCK_CHECK, NULL, &nfh, p);
5305 	NFSLOCKSTATE();
5306 	if (!error)
5307 		error = nfsrv_getlockfile(NFSLCK_CHECK, NULL, &lfp, &nfh, 0);
5308 	if (error) {
5309 		NFSUNLOCKSTATE();
5310 		if (error == -1)
5311 			error = 0;
5312 		goto out;
5313 	}
5314 
5315 	/*
5316 	 * Now, look for a write delegation.
5317 	 */
5318 	LIST_FOREACH(stp, &lfp->lf_deleg, ls_file) {
5319 		if (stp->ls_flags & NFSLCK_DELEGWRITE)
5320 			break;
5321 	}
5322 	if (stp == LIST_END(&lfp->lf_deleg)) {
5323 		NFSUNLOCKSTATE();
5324 		goto out;
5325 	}
5326 	clp = stp->ls_clp;
5327 	delegfilerev = stp->ls_filerev;
5328 
5329 	/*
5330 	 * If the Write delegation was issued as a part of this Compound RPC
5331 	 * or if we have an Implied Clientid (used in a previous Op in this
5332 	 * compound) and it is the client the delegation was issued to,
5333 	 * just return ok.
5334 	 * I also assume that it is from the same client iff the network
5335 	 * host IP address is the same as the callback address. (Not
5336 	 * exactly correct by the RFC, but avoids a lot of Getattr
5337 	 * callbacks.)
5338 	 */
5339 	if (nd->nd_compref == stp->ls_compref ||
5340 	    ((nd->nd_flag & ND_IMPLIEDCLID) &&
5341 	     clp->lc_clientid.qval == nd->nd_clientid.qval) ||
5342 	     nfsaddr2_match(clp->lc_req.nr_nam, nd->nd_nam)) {
5343 		NFSUNLOCKSTATE();
5344 		goto out;
5345 	}
5346 
5347 	/*
5348 	 * We are now done with the delegation state structure,
5349 	 * so the statelock can be released and we can now tsleep().
5350 	 */
5351 
5352 	/*
5353 	 * Now, we must do the CB Getattr callback, to see if Change or Size
5354 	 * has changed.
5355 	 */
5356 	if (clp->lc_expiry >= NFSD_MONOSEC) {
5357 		NFSUNLOCKSTATE();
5358 		NFSVNO_ATTRINIT(&nva);
5359 		nva.na_filerev = NFS64BITSSET;
5360 		error = nfsrv_docallback(clp, NFSV4OP_CBGETATTR, NULL,
5361 		    0, &nfh, &nva, &cbbits, p);
5362 		if (!error) {
5363 			if ((nva.na_filerev != NFS64BITSSET &&
5364 			    nva.na_filerev > delegfilerev) ||
5365 			    (NFSVNO_ISSETSIZE(&nva) &&
5366 			     nva.na_size != nvap->na_size)) {
5367 				error = nfsvno_updfilerev(vp, nvap, cred, p);
5368 				if (NFSVNO_ISSETSIZE(&nva))
5369 					nvap->na_size = nva.na_size;
5370 			}
5371 		} else
5372 			error = 0;	/* Ignore callback errors for now. */
5373 	} else {
5374 		NFSUNLOCKSTATE();
5375 	}
5376 
5377 out:
5378 	NFSEXITCODE2(error, nd);
5379 	return (error);
5380 }
5381 
5382 /*
5383  * This function looks for openowners that haven't had any opens for
5384  * a while and throws them away. Called by an nfsd when NFSNSF_NOOPENS
5385  * is set.
5386  */
5387 APPLESTATIC void
5388 nfsrv_throwawayopens(NFSPROC_T *p)
5389 {
5390 	struct nfsclient *clp, *nclp;
5391 	struct nfsstate *stp, *nstp;
5392 	int i;
5393 
5394 	NFSLOCKSTATE();
5395 	nfsrv_stablefirst.nsf_flags &= ~NFSNSF_NOOPENS;
5396 	/*
5397 	 * For each client...
5398 	 */
5399 	for (i = 0; i < nfsrv_clienthashsize; i++) {
5400 	    LIST_FOREACH_SAFE(clp, &nfsclienthash[i], lc_hash, nclp) {
5401 		LIST_FOREACH_SAFE(stp, &clp->lc_open, ls_list, nstp) {
5402 			if (LIST_EMPTY(&stp->ls_open) &&
5403 			    (stp->ls_noopens > NFSNOOPEN ||
5404 			     (nfsrv_openpluslock * 2) >
5405 			     nfsrv_v4statelimit))
5406 				nfsrv_freeopenowner(stp, 0, p);
5407 		}
5408 	    }
5409 	}
5410 	NFSUNLOCKSTATE();
5411 }
5412 
5413 /*
5414  * This function checks to see if the credentials are the same.
5415  * Returns 1 for not same, 0 otherwise.
5416  */
5417 static int
5418 nfsrv_notsamecredname(struct nfsrv_descript *nd, struct nfsclient *clp)
5419 {
5420 
5421 	if (nd->nd_flag & ND_GSS) {
5422 		if (!(clp->lc_flags & LCL_GSS))
5423 			return (1);
5424 		if (clp->lc_flags & LCL_NAME) {
5425 			if (nd->nd_princlen != clp->lc_namelen ||
5426 			    NFSBCMP(nd->nd_principal, clp->lc_name,
5427 				clp->lc_namelen))
5428 				return (1);
5429 			else
5430 				return (0);
5431 		}
5432 		if (nd->nd_cred->cr_uid == clp->lc_uid)
5433 			return (0);
5434 		else
5435 			return (1);
5436 	} else if (clp->lc_flags & LCL_GSS)
5437 		return (1);
5438 	/*
5439 	 * For AUTH_SYS, allow the same uid or root. (This is underspecified
5440 	 * in RFC3530, which talks about principals, but doesn't say anything
5441 	 * about uids for AUTH_SYS.)
5442 	 */
5443 	if (nd->nd_cred->cr_uid == clp->lc_uid || nd->nd_cred->cr_uid == 0)
5444 		return (0);
5445 	else
5446 		return (1);
5447 }
5448 
5449 /*
5450  * Calculate the lease expiry time.
5451  */
5452 static time_t
5453 nfsrv_leaseexpiry(void)
5454 {
5455 
5456 	if (nfsrv_stablefirst.nsf_eograce > NFSD_MONOSEC)
5457 		return (NFSD_MONOSEC + 2 * (nfsrv_lease + NFSRV_LEASEDELTA));
5458 	return (NFSD_MONOSEC + nfsrv_lease + NFSRV_LEASEDELTA);
5459 }
5460 
5461 /*
5462  * Delay the delegation timeout as far as ls_delegtimelimit, as required.
5463  */
5464 static void
5465 nfsrv_delaydelegtimeout(struct nfsstate *stp)
5466 {
5467 
5468 	if ((stp->ls_flags & NFSLCK_DELEGRECALL) == 0)
5469 		return;
5470 
5471 	if ((stp->ls_delegtime + 15) > NFSD_MONOSEC &&
5472 	    stp->ls_delegtime < stp->ls_delegtimelimit) {
5473 		stp->ls_delegtime += nfsrv_lease;
5474 		if (stp->ls_delegtime > stp->ls_delegtimelimit)
5475 			stp->ls_delegtime = stp->ls_delegtimelimit;
5476 	}
5477 }
5478 
5479 /*
5480  * This function checks to see if there is any other state associated
5481  * with the openowner for this Open.
5482  * It returns 1 if there is no other state, 0 otherwise.
5483  */
5484 static int
5485 nfsrv_nootherstate(struct nfsstate *stp)
5486 {
5487 	struct nfsstate *tstp;
5488 
5489 	LIST_FOREACH(tstp, &stp->ls_openowner->ls_open, ls_list) {
5490 		if (tstp != stp || !LIST_EMPTY(&tstp->ls_lock))
5491 			return (0);
5492 	}
5493 	return (1);
5494 }
5495 
5496 /*
5497  * Create a list of lock deltas (changes to local byte range locking
5498  * that can be rolled back using the list) and apply the changes via
5499  * nfsvno_advlock(). Optionally, lock the list. It is expected that either
5500  * the rollback or update function will be called after this.
5501  * It returns an error (and rolls back, as required), if any nfsvno_advlock()
5502  * call fails. If it returns an error, it will unlock the list.
5503  */
5504 static int
5505 nfsrv_locallock(vnode_t vp, struct nfslockfile *lfp, int flags,
5506     uint64_t first, uint64_t end, struct nfslockconflict *cfp, NFSPROC_T *p)
5507 {
5508 	struct nfslock *lop, *nlop;
5509 	int error = 0;
5510 
5511 	/* Loop through the list of locks. */
5512 	lop = LIST_FIRST(&lfp->lf_locallock);
5513 	while (first < end && lop != NULL) {
5514 		nlop = LIST_NEXT(lop, lo_lckowner);
5515 		if (first >= lop->lo_end) {
5516 			/* not there yet */
5517 			lop = nlop;
5518 		} else if (first < lop->lo_first) {
5519 			/* new one starts before entry in list */
5520 			if (end <= lop->lo_first) {
5521 				/* no overlap between old and new */
5522 				error = nfsrv_dolocal(vp, lfp, flags,
5523 				    NFSLCK_UNLOCK, first, end, cfp, p);
5524 				if (error != 0)
5525 					break;
5526 				first = end;
5527 			} else {
5528 				/* handle fragment overlapped with new one */
5529 				error = nfsrv_dolocal(vp, lfp, flags,
5530 				    NFSLCK_UNLOCK, first, lop->lo_first, cfp,
5531 				    p);
5532 				if (error != 0)
5533 					break;
5534 				first = lop->lo_first;
5535 			}
5536 		} else {
5537 			/* new one overlaps this entry in list */
5538 			if (end <= lop->lo_end) {
5539 				/* overlaps all of new one */
5540 				error = nfsrv_dolocal(vp, lfp, flags,
5541 				    lop->lo_flags, first, end, cfp, p);
5542 				if (error != 0)
5543 					break;
5544 				first = end;
5545 			} else {
5546 				/* handle fragment overlapped with new one */
5547 				error = nfsrv_dolocal(vp, lfp, flags,
5548 				    lop->lo_flags, first, lop->lo_end, cfp, p);
5549 				if (error != 0)
5550 					break;
5551 				first = lop->lo_end;
5552 				lop = nlop;
5553 			}
5554 		}
5555 	}
5556 	if (first < end && error == 0)
5557 		/* handle fragment past end of list */
5558 		error = nfsrv_dolocal(vp, lfp, flags, NFSLCK_UNLOCK, first,
5559 		    end, cfp, p);
5560 
5561 	NFSEXITCODE(error);
5562 	return (error);
5563 }
5564 
5565 /*
5566  * Local lock unlock. Unlock all byte ranges that are no longer locked
5567  * by NFSv4. To do this, unlock any subranges of first-->end that
5568  * do not overlap with the byte ranges of any lock in the lfp->lf_lock
5569  * list. This list has all locks for the file held by other
5570  * <clientid, lockowner> tuples. The list is ordered by increasing
5571  * lo_first value, but may have entries that overlap each other, for
5572  * the case of read locks.
5573  */
5574 static void
5575 nfsrv_localunlock(vnode_t vp, struct nfslockfile *lfp, uint64_t init_first,
5576     uint64_t init_end, NFSPROC_T *p)
5577 {
5578 	struct nfslock *lop;
5579 	uint64_t first, end, prevfirst;
5580 
5581 	first = init_first;
5582 	end = init_end;
5583 	while (first < init_end) {
5584 		/* Loop through all nfs locks, adjusting first and end */
5585 		prevfirst = 0;
5586 		LIST_FOREACH(lop, &lfp->lf_lock, lo_lckfile) {
5587 			KASSERT(prevfirst <= lop->lo_first,
5588 			    ("nfsv4 locks out of order"));
5589 			KASSERT(lop->lo_first < lop->lo_end,
5590 			    ("nfsv4 bogus lock"));
5591 			prevfirst = lop->lo_first;
5592 			if (first >= lop->lo_first &&
5593 			    first < lop->lo_end)
5594 				/*
5595 				 * Overlaps with initial part, so trim
5596 				 * off that initial part by moving first past
5597 				 * it.
5598 				 */
5599 				first = lop->lo_end;
5600 			else if (end > lop->lo_first &&
5601 			    lop->lo_first > first) {
5602 				/*
5603 				 * This lock defines the end of the
5604 				 * segment to unlock, so set end to the
5605 				 * start of it and break out of the loop.
5606 				 */
5607 				end = lop->lo_first;
5608 				break;
5609 			}
5610 			if (first >= end)
5611 				/*
5612 				 * There is no segment left to do, so
5613 				 * break out of this loop and then exit
5614 				 * the outer while() since first will be set
5615 				 * to end, which must equal init_end here.
5616 				 */
5617 				break;
5618 		}
5619 		if (first < end) {
5620 			/* Unlock this segment */
5621 			(void) nfsrv_dolocal(vp, lfp, NFSLCK_UNLOCK,
5622 			    NFSLCK_READ, first, end, NULL, p);
5623 			nfsrv_locallock_commit(lfp, NFSLCK_UNLOCK,
5624 			    first, end);
5625 		}
5626 		/*
5627 		 * Now move past this segment and look for any further
5628 		 * segment in the range, if there is one.
5629 		 */
5630 		first = end;
5631 		end = init_end;
5632 	}
5633 }
5634 
5635 /*
5636  * Do the local lock operation and update the rollback list, as required.
5637  * Perform the rollback and return the error if nfsvno_advlock() fails.
5638  */
5639 static int
5640 nfsrv_dolocal(vnode_t vp, struct nfslockfile *lfp, int flags, int oldflags,
5641     uint64_t first, uint64_t end, struct nfslockconflict *cfp, NFSPROC_T *p)
5642 {
5643 	struct nfsrollback *rlp;
5644 	int error = 0, ltype, oldltype;
5645 
5646 	if (flags & NFSLCK_WRITE)
5647 		ltype = F_WRLCK;
5648 	else if (flags & NFSLCK_READ)
5649 		ltype = F_RDLCK;
5650 	else
5651 		ltype = F_UNLCK;
5652 	if (oldflags & NFSLCK_WRITE)
5653 		oldltype = F_WRLCK;
5654 	else if (oldflags & NFSLCK_READ)
5655 		oldltype = F_RDLCK;
5656 	else
5657 		oldltype = F_UNLCK;
5658 	if (ltype == oldltype || (oldltype == F_WRLCK && ltype == F_RDLCK))
5659 		/* nothing to do */
5660 		goto out;
5661 	error = nfsvno_advlock(vp, ltype, first, end, p);
5662 	if (error != 0) {
5663 		if (cfp != NULL) {
5664 			cfp->cl_clientid.lval[0] = 0;
5665 			cfp->cl_clientid.lval[1] = 0;
5666 			cfp->cl_first = 0;
5667 			cfp->cl_end = NFS64BITSSET;
5668 			cfp->cl_flags = NFSLCK_WRITE;
5669 			cfp->cl_ownerlen = 5;
5670 			NFSBCOPY("LOCAL", cfp->cl_owner, 5);
5671 		}
5672 		nfsrv_locallock_rollback(vp, lfp, p);
5673 	} else if (ltype != F_UNLCK) {
5674 		rlp = malloc(sizeof (struct nfsrollback), M_NFSDROLLBACK,
5675 		    M_WAITOK);
5676 		rlp->rlck_first = first;
5677 		rlp->rlck_end = end;
5678 		rlp->rlck_type = oldltype;
5679 		LIST_INSERT_HEAD(&lfp->lf_rollback, rlp, rlck_list);
5680 	}
5681 
5682 out:
5683 	NFSEXITCODE(error);
5684 	return (error);
5685 }
5686 
5687 /*
5688  * Roll back local lock changes and free up the rollback list.
5689  */
5690 static void
5691 nfsrv_locallock_rollback(vnode_t vp, struct nfslockfile *lfp, NFSPROC_T *p)
5692 {
5693 	struct nfsrollback *rlp, *nrlp;
5694 
5695 	LIST_FOREACH_SAFE(rlp, &lfp->lf_rollback, rlck_list, nrlp) {
5696 		(void) nfsvno_advlock(vp, rlp->rlck_type, rlp->rlck_first,
5697 		    rlp->rlck_end, p);
5698 		free(rlp, M_NFSDROLLBACK);
5699 	}
5700 	LIST_INIT(&lfp->lf_rollback);
5701 }
5702 
5703 /*
5704  * Update local lock list and delete rollback list (ie now committed to the
5705  * local locks). Most of the work is done by the internal function.
5706  */
5707 static void
5708 nfsrv_locallock_commit(struct nfslockfile *lfp, int flags, uint64_t first,
5709     uint64_t end)
5710 {
5711 	struct nfsrollback *rlp, *nrlp;
5712 	struct nfslock *new_lop, *other_lop;
5713 
5714 	new_lop = malloc(sizeof (struct nfslock), M_NFSDLOCK, M_WAITOK);
5715 	if (flags & (NFSLCK_READ | NFSLCK_WRITE))
5716 		other_lop = malloc(sizeof (struct nfslock), M_NFSDLOCK,
5717 		    M_WAITOK);
5718 	else
5719 		other_lop = NULL;
5720 	new_lop->lo_flags = flags;
5721 	new_lop->lo_first = first;
5722 	new_lop->lo_end = end;
5723 	nfsrv_updatelock(NULL, &new_lop, &other_lop, lfp);
5724 	if (new_lop != NULL)
5725 		free(new_lop, M_NFSDLOCK);
5726 	if (other_lop != NULL)
5727 		free(other_lop, M_NFSDLOCK);
5728 
5729 	/* and get rid of the rollback list */
5730 	LIST_FOREACH_SAFE(rlp, &lfp->lf_rollback, rlck_list, nrlp)
5731 		free(rlp, M_NFSDROLLBACK);
5732 	LIST_INIT(&lfp->lf_rollback);
5733 }
5734 
5735 /*
5736  * Lock the struct nfslockfile for local lock updating.
5737  */
5738 static void
5739 nfsrv_locklf(struct nfslockfile *lfp)
5740 {
5741 	int gotlock;
5742 
5743 	/* lf_usecount ensures *lfp won't be free'd */
5744 	lfp->lf_usecount++;
5745 	do {
5746 		gotlock = nfsv4_lock(&lfp->lf_locallock_lck, 1, NULL,
5747 		    NFSSTATEMUTEXPTR, NULL);
5748 	} while (gotlock == 0);
5749 	lfp->lf_usecount--;
5750 }
5751 
5752 /*
5753  * Unlock the struct nfslockfile after local lock updating.
5754  */
5755 static void
5756 nfsrv_unlocklf(struct nfslockfile *lfp)
5757 {
5758 
5759 	nfsv4_unlock(&lfp->lf_locallock_lck, 0);
5760 }
5761 
5762 /*
5763  * Clear out all state for the NFSv4 server.
5764  * Must be called by a thread that can sleep when no nfsds are running.
5765  */
5766 void
5767 nfsrv_throwawayallstate(NFSPROC_T *p)
5768 {
5769 	struct nfsclient *clp, *nclp;
5770 	struct nfslockfile *lfp, *nlfp;
5771 	int i;
5772 
5773 	/*
5774 	 * For each client, clean out the state and then free the structure.
5775 	 */
5776 	for (i = 0; i < nfsrv_clienthashsize; i++) {
5777 		LIST_FOREACH_SAFE(clp, &nfsclienthash[i], lc_hash, nclp) {
5778 			nfsrv_cleanclient(clp, p);
5779 			nfsrv_freedeleglist(&clp->lc_deleg);
5780 			nfsrv_freedeleglist(&clp->lc_olddeleg);
5781 			free(clp->lc_stateid, M_NFSDCLIENT);
5782 			free(clp, M_NFSDCLIENT);
5783 		}
5784 	}
5785 
5786 	/*
5787 	 * Also, free up any remaining lock file structures.
5788 	 */
5789 	for (i = 0; i < nfsrv_lockhashsize; i++) {
5790 		LIST_FOREACH_SAFE(lfp, &nfslockhash[i], lf_hash, nlfp) {
5791 			printf("nfsd unload: fnd a lock file struct\n");
5792 			nfsrv_freenfslockfile(lfp);
5793 		}
5794 	}
5795 }
5796 
5797 /*
5798  * Check the sequence# for the session and slot provided as an argument.
5799  * Also, renew the lease if the session will return NFS_OK.
5800  */
5801 int
5802 nfsrv_checksequence(struct nfsrv_descript *nd, uint32_t sequenceid,
5803     uint32_t *highest_slotidp, uint32_t *target_highest_slotidp, int cache_this,
5804     uint32_t *sflagsp, NFSPROC_T *p)
5805 {
5806 	struct nfsdsession *sep;
5807 	struct nfssessionhash *shp;
5808 	int error;
5809 	SVCXPRT *savxprt;
5810 
5811 	shp = NFSSESSIONHASH(nd->nd_sessionid);
5812 	NFSLOCKSESSION(shp);
5813 	sep = nfsrv_findsession(nd->nd_sessionid);
5814 	if (sep == NULL) {
5815 		NFSUNLOCKSESSION(shp);
5816 		return (NFSERR_BADSESSION);
5817 	}
5818 	error = nfsv4_seqsession(sequenceid, nd->nd_slotid, *highest_slotidp,
5819 	    sep->sess_slots, NULL, NFSV4_SLOTS - 1);
5820 	if (error != 0) {
5821 		NFSUNLOCKSESSION(shp);
5822 		return (error);
5823 	}
5824 	if (cache_this != 0)
5825 		nd->nd_flag |= ND_SAVEREPLY;
5826 	/* Renew the lease. */
5827 	sep->sess_clp->lc_expiry = nfsrv_leaseexpiry();
5828 	nd->nd_clientid.qval = sep->sess_clp->lc_clientid.qval;
5829 	nd->nd_flag |= ND_IMPLIEDCLID;
5830 
5831 	/*
5832 	 * If this session handles the backchannel, save the nd_xprt for this
5833 	 * RPC, since this is the one being used.
5834 	 */
5835 	if (sep->sess_clp->lc_req.nr_client != NULL &&
5836 	    (sep->sess_crflags & NFSV4CRSESS_CONNBACKCHAN) != 0) {
5837 		savxprt = sep->sess_cbsess.nfsess_xprt;
5838 		SVC_ACQUIRE(nd->nd_xprt);
5839 		nd->nd_xprt->xp_p2 =
5840 		    sep->sess_clp->lc_req.nr_client->cl_private;
5841 		nd->nd_xprt->xp_idletimeout = 0;	/* Disable timeout. */
5842 		sep->sess_cbsess.nfsess_xprt = nd->nd_xprt;
5843 		if (savxprt != NULL)
5844 			SVC_RELEASE(savxprt);
5845 	}
5846 
5847 	*sflagsp = 0;
5848 	if (sep->sess_clp->lc_req.nr_client == NULL)
5849 		*sflagsp |= NFSV4SEQ_CBPATHDOWN;
5850 	NFSUNLOCKSESSION(shp);
5851 	if (error == NFSERR_EXPIRED) {
5852 		*sflagsp |= NFSV4SEQ_EXPIREDALLSTATEREVOKED;
5853 		error = 0;
5854 	} else if (error == NFSERR_ADMINREVOKED) {
5855 		*sflagsp |= NFSV4SEQ_ADMINSTATEREVOKED;
5856 		error = 0;
5857 	}
5858 	*highest_slotidp = *target_highest_slotidp = NFSV4_SLOTS - 1;
5859 	return (0);
5860 }
5861 
5862 /*
5863  * Check/set reclaim complete for this session/clientid.
5864  */
5865 int
5866 nfsrv_checkreclaimcomplete(struct nfsrv_descript *nd)
5867 {
5868 	struct nfsdsession *sep;
5869 	struct nfssessionhash *shp;
5870 	int error = 0;
5871 
5872 	shp = NFSSESSIONHASH(nd->nd_sessionid);
5873 	NFSLOCKSTATE();
5874 	NFSLOCKSESSION(shp);
5875 	sep = nfsrv_findsession(nd->nd_sessionid);
5876 	if (sep == NULL) {
5877 		NFSUNLOCKSESSION(shp);
5878 		NFSUNLOCKSTATE();
5879 		return (NFSERR_BADSESSION);
5880 	}
5881 
5882 	/* Check to see if reclaim complete has already happened. */
5883 	if ((sep->sess_clp->lc_flags & LCL_RECLAIMCOMPLETE) != 0)
5884 		error = NFSERR_COMPLETEALREADY;
5885 	else
5886 		sep->sess_clp->lc_flags |= LCL_RECLAIMCOMPLETE;
5887 	NFSUNLOCKSESSION(shp);
5888 	NFSUNLOCKSTATE();
5889 	return (error);
5890 }
5891 
5892 /*
5893  * Cache the reply in a session slot.
5894  */
5895 void
5896 nfsrv_cache_session(uint8_t *sessionid, uint32_t slotid, int repstat,
5897    struct mbuf **m)
5898 {
5899 	struct nfsdsession *sep;
5900 	struct nfssessionhash *shp;
5901 
5902 	shp = NFSSESSIONHASH(sessionid);
5903 	NFSLOCKSESSION(shp);
5904 	sep = nfsrv_findsession(sessionid);
5905 	if (sep == NULL) {
5906 		NFSUNLOCKSESSION(shp);
5907 		printf("nfsrv_cache_session: no session\n");
5908 		m_freem(*m);
5909 		return;
5910 	}
5911 	nfsv4_seqsess_cacherep(slotid, sep->sess_slots, repstat, m);
5912 	NFSUNLOCKSESSION(shp);
5913 }
5914 
5915 /*
5916  * Search for a session that matches the sessionid.
5917  */
5918 static struct nfsdsession *
5919 nfsrv_findsession(uint8_t *sessionid)
5920 {
5921 	struct nfsdsession *sep;
5922 	struct nfssessionhash *shp;
5923 
5924 	shp = NFSSESSIONHASH(sessionid);
5925 	LIST_FOREACH(sep, &shp->list, sess_hash) {
5926 		if (!NFSBCMP(sessionid, sep->sess_sessionid, NFSX_V4SESSIONID))
5927 			break;
5928 	}
5929 	return (sep);
5930 }
5931 
5932 /*
5933  * Destroy a session.
5934  */
5935 int
5936 nfsrv_destroysession(struct nfsrv_descript *nd, uint8_t *sessionid)
5937 {
5938 	int error, samesess;
5939 
5940 	samesess = 0;
5941 	if (!NFSBCMP(sessionid, nd->nd_sessionid, NFSX_V4SESSIONID)) {
5942 		samesess = 1;
5943 		if ((nd->nd_flag & ND_LASTOP) == 0)
5944 			return (NFSERR_BADSESSION);
5945 	}
5946 	error = nfsrv_freesession(NULL, sessionid);
5947 	if (error == 0 && samesess != 0)
5948 		nd->nd_flag &= ~ND_HASSEQUENCE;
5949 	return (error);
5950 }
5951 
5952 /*
5953  * Free up a session structure.
5954  */
5955 static int
5956 nfsrv_freesession(struct nfsdsession *sep, uint8_t *sessionid)
5957 {
5958 	struct nfssessionhash *shp;
5959 	int i;
5960 
5961 	NFSLOCKSTATE();
5962 	if (sep == NULL) {
5963 		shp = NFSSESSIONHASH(sessionid);
5964 		NFSLOCKSESSION(shp);
5965 		sep = nfsrv_findsession(sessionid);
5966 	} else {
5967 		shp = NFSSESSIONHASH(sep->sess_sessionid);
5968 		NFSLOCKSESSION(shp);
5969 	}
5970 	if (sep != NULL) {
5971 		sep->sess_refcnt--;
5972 		if (sep->sess_refcnt > 0) {
5973 			NFSUNLOCKSESSION(shp);
5974 			NFSUNLOCKSTATE();
5975 			return (0);
5976 		}
5977 		LIST_REMOVE(sep, sess_hash);
5978 		LIST_REMOVE(sep, sess_list);
5979 	}
5980 	NFSUNLOCKSESSION(shp);
5981 	NFSUNLOCKSTATE();
5982 	if (sep == NULL)
5983 		return (NFSERR_BADSESSION);
5984 	for (i = 0; i < NFSV4_SLOTS; i++)
5985 		if (sep->sess_slots[i].nfssl_reply != NULL)
5986 			m_freem(sep->sess_slots[i].nfssl_reply);
5987 	if (sep->sess_cbsess.nfsess_xprt != NULL)
5988 		SVC_RELEASE(sep->sess_cbsess.nfsess_xprt);
5989 	free(sep, M_NFSDSESSION);
5990 	return (0);
5991 }
5992 
5993 /*
5994  * Free a stateid.
5995  * RFC5661 says that it should fail when there are associated opens, locks
5996  * or delegations. Since stateids represent opens, I don't see how you can
5997  * free an open stateid (it will be free'd when closed), so this function
5998  * only works for lock stateids (freeing the lock_owner) or delegations.
5999  */
6000 int
6001 nfsrv_freestateid(struct nfsrv_descript *nd, nfsv4stateid_t *stateidp,
6002     NFSPROC_T *p)
6003 {
6004 	struct nfsclient *clp;
6005 	struct nfsstate *stp;
6006 	int error;
6007 
6008 	NFSLOCKSTATE();
6009 	/*
6010 	 * Look up the stateid
6011 	 */
6012 	error = nfsrv_getclient((nfsquad_t)((u_quad_t)0), CLOPS_RENEW, &clp,
6013 	    NULL, (nfsquad_t)((u_quad_t)0), 0, nd, p);
6014 	if (error == 0) {
6015 		/* First, check for a delegation. */
6016 		LIST_FOREACH(stp, &clp->lc_deleg, ls_list) {
6017 			if (!NFSBCMP(stp->ls_stateid.other, stateidp->other,
6018 			    NFSX_STATEIDOTHER))
6019 				break;
6020 		}
6021 		if (stp != NULL) {
6022 			nfsrv_freedeleg(stp);
6023 			NFSUNLOCKSTATE();
6024 			return (error);
6025 		}
6026 	}
6027 	/* Not a delegation, try for a lock_owner. */
6028 	if (error == 0)
6029 		error = nfsrv_getstate(clp, stateidp, 0, &stp);
6030 	if (error == 0 && ((stp->ls_flags & (NFSLCK_OPEN | NFSLCK_DELEGREAD |
6031 	    NFSLCK_DELEGWRITE)) != 0 || (stp->ls_flags & NFSLCK_LOCK) == 0))
6032 		/* Not a lock_owner stateid. */
6033 		error = NFSERR_LOCKSHELD;
6034 	if (error == 0 && !LIST_EMPTY(&stp->ls_lock))
6035 		error = NFSERR_LOCKSHELD;
6036 	if (error == 0)
6037 		nfsrv_freelockowner(stp, NULL, 0, p);
6038 	NFSUNLOCKSTATE();
6039 	return (error);
6040 }
6041 
6042 /*
6043  * Generate the xdr for an NFSv4.1 CBSequence Operation.
6044  */
6045 static int
6046 nfsv4_setcbsequence(struct nfsrv_descript *nd, struct nfsclient *clp,
6047     int dont_replycache, struct nfsdsession **sepp)
6048 {
6049 	struct nfsdsession *sep;
6050 	uint32_t *tl, slotseq = 0;
6051 	int maxslot, slotpos;
6052 	uint8_t sessionid[NFSX_V4SESSIONID];
6053 	int error;
6054 
6055 	error = nfsv4_getcbsession(clp, sepp);
6056 	if (error != 0)
6057 		return (error);
6058 	sep = *sepp;
6059 	(void)nfsv4_sequencelookup(NULL, &sep->sess_cbsess, &slotpos, &maxslot,
6060 	    &slotseq, sessionid);
6061 	KASSERT(maxslot >= 0, ("nfsv4_setcbsequence neg maxslot"));
6062 
6063 	/* Build the Sequence arguments. */
6064 	NFSM_BUILD(tl, uint32_t *, NFSX_V4SESSIONID + 5 * NFSX_UNSIGNED);
6065 	bcopy(sessionid, tl, NFSX_V4SESSIONID);
6066 	tl += NFSX_V4SESSIONID / NFSX_UNSIGNED;
6067 	nd->nd_slotseq = tl;
6068 	*tl++ = txdr_unsigned(slotseq);
6069 	*tl++ = txdr_unsigned(slotpos);
6070 	*tl++ = txdr_unsigned(maxslot);
6071 	if (dont_replycache == 0)
6072 		*tl++ = newnfs_true;
6073 	else
6074 		*tl++ = newnfs_false;
6075 	*tl = 0;			/* No referring call list, for now. */
6076 	nd->nd_flag |= ND_HASSEQUENCE;
6077 	return (0);
6078 }
6079 
6080 /*
6081  * Get a session for the callback.
6082  */
6083 static int
6084 nfsv4_getcbsession(struct nfsclient *clp, struct nfsdsession **sepp)
6085 {
6086 	struct nfsdsession *sep;
6087 
6088 	NFSLOCKSTATE();
6089 	LIST_FOREACH(sep, &clp->lc_session, sess_list) {
6090 		if ((sep->sess_crflags & NFSV4CRSESS_CONNBACKCHAN) != 0)
6091 			break;
6092 	}
6093 	if (sep == NULL) {
6094 		NFSUNLOCKSTATE();
6095 		return (NFSERR_BADSESSION);
6096 	}
6097 	sep->sess_refcnt++;
6098 	*sepp = sep;
6099 	NFSUNLOCKSTATE();
6100 	return (0);
6101 }
6102 
6103 /*
6104  * Free up all backchannel xprts.  This needs to be done when the nfsd threads
6105  * exit, since those transports will all be going away.
6106  * This is only called after all the nfsd threads are done performing RPCs,
6107  * so locking shouldn't be an issue.
6108  */
6109 APPLESTATIC void
6110 nfsrv_freeallbackchannel_xprts(void)
6111 {
6112 	struct nfsdsession *sep;
6113 	struct nfsclient *clp;
6114 	SVCXPRT *xprt;
6115 	int i;
6116 
6117 	for (i = 0; i < nfsrv_clienthashsize; i++) {
6118 		LIST_FOREACH(clp, &nfsclienthash[i], lc_hash) {
6119 			LIST_FOREACH(sep, &clp->lc_session, sess_list) {
6120 				xprt = sep->sess_cbsess.nfsess_xprt;
6121 				sep->sess_cbsess.nfsess_xprt = NULL;
6122 				if (xprt != NULL)
6123 					SVC_RELEASE(xprt);
6124 			}
6125 		}
6126 	}
6127 }
6128 
6129