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