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