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