xref: /freebsd/sys/fs/nfsserver/nfs_nfsdstate.c (revision a3d9bf49b57923118c339642594246ef73872ee8)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (c) 2009 Rick Macklem, University of Guelph
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  *
28  */
29 
30 #include <sys/cdefs.h>
31 __FBSDID("$FreeBSD$");
32 
33 #include "opt_inet.h"
34 #include "opt_inet6.h"
35 #include <sys/extattr.h>
36 #include <fs/nfs/nfsport.h>
37 
38 struct nfsrv_stablefirst nfsrv_stablefirst;
39 int nfsrv_issuedelegs = 0;
40 int nfsrv_dolocallocks = 0;
41 struct nfsv4lock nfsv4rootfs_lock;
42 time_t nfsdev_time = 0;
43 int nfsrv_layouthashsize;
44 volatile int nfsrv_layoutcnt = 0;
45 
46 extern int newnfs_numnfsd;
47 extern struct nfsstatsv1 nfsstatsv1;
48 extern int nfsrv_lease;
49 extern struct timeval nfsboottime;
50 extern u_int32_t newnfs_true, newnfs_false;
51 extern struct mtx nfsrv_dslock_mtx;
52 extern struct mtx nfsrv_recalllock_mtx;
53 extern struct mtx nfsrv_dontlistlock_mtx;
54 extern int nfsd_debuglevel;
55 extern u_int nfsrv_dsdirsize;
56 extern struct nfsdevicehead nfsrv_devidhead;
57 extern int nfsrv_doflexfile;
58 extern int nfsrv_maxpnfsmirror;
59 NFSV4ROOTLOCKMUTEX;
60 NFSSTATESPINLOCK;
61 extern struct nfsdontlisthead nfsrv_dontlisthead;
62 extern volatile int nfsrv_devidcnt;
63 extern struct nfslayouthead nfsrv_recalllisthead;
64 extern char *nfsrv_zeropnfsdat;
65 
66 SYSCTL_DECL(_vfs_nfsd);
67 int	nfsrv_statehashsize = NFSSTATEHASHSIZE;
68 SYSCTL_INT(_vfs_nfsd, OID_AUTO, statehashsize, CTLFLAG_RDTUN,
69     &nfsrv_statehashsize, 0,
70     "Size of state hash table set via loader.conf");
71 
72 int	nfsrv_clienthashsize = NFSCLIENTHASHSIZE;
73 SYSCTL_INT(_vfs_nfsd, OID_AUTO, clienthashsize, CTLFLAG_RDTUN,
74     &nfsrv_clienthashsize, 0,
75     "Size of client hash table set via loader.conf");
76 
77 int	nfsrv_lockhashsize = NFSLOCKHASHSIZE;
78 SYSCTL_INT(_vfs_nfsd, OID_AUTO, fhhashsize, CTLFLAG_RDTUN,
79     &nfsrv_lockhashsize, 0,
80     "Size of file handle hash table set via loader.conf");
81 
82 int	nfsrv_sessionhashsize = NFSSESSIONHASHSIZE;
83 SYSCTL_INT(_vfs_nfsd, OID_AUTO, sessionhashsize, CTLFLAG_RDTUN,
84     &nfsrv_sessionhashsize, 0,
85     "Size of session hash table set via loader.conf");
86 
87 int	nfsrv_layouthighwater = NFSLAYOUTHIGHWATER;
88 SYSCTL_INT(_vfs_nfsd, OID_AUTO, layouthighwater, CTLFLAG_RDTUN,
89     &nfsrv_layouthighwater, 0,
90     "High water mark for number of layouts set via loader.conf");
91 
92 static int	nfsrv_v4statelimit = NFSRV_V4STATELIMIT;
93 SYSCTL_INT(_vfs_nfsd, OID_AUTO, v4statelimit, CTLFLAG_RWTUN,
94     &nfsrv_v4statelimit, 0,
95     "High water limit for NFSv4 opens+locks+delegations");
96 
97 static int	nfsrv_writedelegifpos = 0;
98 SYSCTL_INT(_vfs_nfsd, OID_AUTO, writedelegifpos, CTLFLAG_RW,
99     &nfsrv_writedelegifpos, 0,
100     "Issue a write delegation for read opens if possible");
101 
102 static int	nfsrv_allowreadforwriteopen = 1;
103 SYSCTL_INT(_vfs_nfsd, OID_AUTO, allowreadforwriteopen, CTLFLAG_RW,
104     &nfsrv_allowreadforwriteopen, 0,
105     "Allow Reads to be done with Write Access StateIDs");
106 
107 int	nfsrv_pnfsatime = 0;
108 SYSCTL_INT(_vfs_nfsd, OID_AUTO, pnfsstrictatime, CTLFLAG_RW,
109     &nfsrv_pnfsatime, 0,
110     "For pNFS service, do Getattr ops to keep atime up-to-date");
111 
112 int	nfsrv_flexlinuxhack = 0;
113 SYSCTL_INT(_vfs_nfsd, OID_AUTO, flexlinuxhack, CTLFLAG_RW,
114     &nfsrv_flexlinuxhack, 0,
115     "For Linux clients, hack around Flex File Layout bug");
116 
117 /*
118  * Hash lists for nfs V4.
119  */
120 struct nfsclienthashhead	*nfsclienthash;
121 struct nfslockhashhead		*nfslockhash;
122 struct nfssessionhash		*nfssessionhash;
123 struct nfslayouthash		*nfslayouthash;
124 volatile int nfsrv_dontlistlen = 0;
125 
126 static u_int32_t nfsrv_openpluslock = 0, nfsrv_delegatecnt = 0;
127 static time_t nfsrvboottime;
128 static int nfsrv_returnoldstateid = 0, nfsrv_clients = 0;
129 static int nfsrv_clienthighwater = NFSRV_CLIENTHIGHWATER;
130 static int nfsrv_nogsscallback = 0;
131 static volatile int nfsrv_writedelegcnt = 0;
132 static int nfsrv_faildscnt;
133 
134 /* local functions */
135 static void nfsrv_dumpaclient(struct nfsclient *clp,
136     struct nfsd_dumpclients *dumpp);
137 static void nfsrv_freeopenowner(struct nfsstate *stp, int cansleep,
138     NFSPROC_T *p);
139 static int nfsrv_freeopen(struct nfsstate *stp, vnode_t vp, int cansleep,
140     NFSPROC_T *p);
141 static void nfsrv_freelockowner(struct nfsstate *stp, vnode_t vp, int cansleep,
142     NFSPROC_T *p);
143 static void nfsrv_freeallnfslocks(struct nfsstate *stp, vnode_t vp,
144     int cansleep, NFSPROC_T *p);
145 static void nfsrv_freenfslock(struct nfslock *lop);
146 static void nfsrv_freenfslockfile(struct nfslockfile *lfp);
147 static void nfsrv_freedeleg(struct nfsstate *);
148 static int nfsrv_getstate(struct nfsclient *clp, nfsv4stateid_t *stateidp,
149     u_int32_t flags, struct nfsstate **stpp);
150 static void nfsrv_getowner(struct nfsstatehead *hp, struct nfsstate *new_stp,
151     struct nfsstate **stpp);
152 static int nfsrv_getlockfh(vnode_t vp, u_short flags,
153     struct nfslockfile *new_lfp, fhandle_t *nfhp, NFSPROC_T *p);
154 static int nfsrv_getlockfile(u_short flags, struct nfslockfile **new_lfpp,
155     struct nfslockfile **lfpp, fhandle_t *nfhp, int lockit);
156 static void nfsrv_insertlock(struct nfslock *new_lop,
157     struct nfslock *insert_lop, struct nfsstate *stp, struct nfslockfile *lfp);
158 static void nfsrv_updatelock(struct nfsstate *stp, struct nfslock **new_lopp,
159     struct nfslock **other_lopp, struct nfslockfile *lfp);
160 static int nfsrv_getipnumber(u_char *cp);
161 static int nfsrv_checkrestart(nfsquad_t clientid, u_int32_t flags,
162     nfsv4stateid_t *stateidp, int specialid);
163 static int nfsrv_checkgrace(struct nfsrv_descript *nd, struct nfsclient *clp,
164     u_int32_t flags);
165 static int nfsrv_docallback(struct nfsclient *clp, int procnum,
166     nfsv4stateid_t *stateidp, int trunc, fhandle_t *fhp,
167     struct nfsvattr *nap, nfsattrbit_t *attrbitp, int laytype, NFSPROC_T *p);
168 static int nfsrv_cbcallargs(struct nfsrv_descript *nd, struct nfsclient *clp,
169     uint32_t callback, int op, const char *optag, struct nfsdsession **sepp);
170 static u_int32_t nfsrv_nextclientindex(void);
171 static u_int32_t nfsrv_nextstateindex(struct nfsclient *clp);
172 static void nfsrv_markstable(struct nfsclient *clp);
173 static void nfsrv_markreclaim(struct nfsclient *clp);
174 static int nfsrv_checkstable(struct nfsclient *clp);
175 static int nfsrv_clientconflict(struct nfsclient *clp, int *haslockp, struct
176     vnode *vp, NFSPROC_T *p);
177 static int nfsrv_delegconflict(struct nfsstate *stp, int *haslockp,
178     NFSPROC_T *p, vnode_t vp);
179 static int nfsrv_cleandeleg(vnode_t vp, struct nfslockfile *lfp,
180     struct nfsclient *clp, int *haslockp, NFSPROC_T *p);
181 static int nfsrv_notsamecredname(struct nfsrv_descript *nd,
182     struct nfsclient *clp);
183 static time_t nfsrv_leaseexpiry(void);
184 static void nfsrv_delaydelegtimeout(struct nfsstate *stp);
185 static int nfsrv_checkseqid(struct nfsrv_descript *nd, u_int32_t seqid,
186     struct nfsstate *stp, struct nfsrvcache *op);
187 static int nfsrv_nootherstate(struct nfsstate *stp);
188 static int nfsrv_locallock(vnode_t vp, struct nfslockfile *lfp, int flags,
189     uint64_t first, uint64_t end, struct nfslockconflict *cfp, NFSPROC_T *p);
190 static void nfsrv_localunlock(vnode_t vp, struct nfslockfile *lfp,
191     uint64_t init_first, uint64_t init_end, NFSPROC_T *p);
192 static int nfsrv_dolocal(vnode_t vp, struct nfslockfile *lfp, int flags,
193     int oldflags, uint64_t first, uint64_t end, struct nfslockconflict *cfp,
194     NFSPROC_T *p);
195 static void nfsrv_locallock_rollback(vnode_t vp, struct nfslockfile *lfp,
196     NFSPROC_T *p);
197 static void nfsrv_locallock_commit(struct nfslockfile *lfp, int flags,
198     uint64_t first, uint64_t end);
199 static void nfsrv_locklf(struct nfslockfile *lfp);
200 static void nfsrv_unlocklf(struct nfslockfile *lfp);
201 static struct nfsdsession *nfsrv_findsession(uint8_t *sessionid);
202 static int nfsrv_freesession(struct nfsdsession *sep, uint8_t *sessionid);
203 static int nfsv4_setcbsequence(struct nfsrv_descript *nd, struct nfsclient *clp,
204     int dont_replycache, struct nfsdsession **sepp);
205 static int nfsv4_getcbsession(struct nfsclient *clp, struct nfsdsession **sepp);
206 static int nfsrv_addlayout(struct nfsrv_descript *nd, struct nfslayout **lypp,
207     nfsv4stateid_t *stateidp, char *layp, int *layoutlenp, NFSPROC_T *p);
208 static void nfsrv_freelayout(struct nfslayouthead *lhp, struct nfslayout *lyp);
209 static void nfsrv_freelayoutlist(nfsquad_t clientid);
210 static void nfsrv_freelayouts(nfsquad_t *clid, fsid_t *fs, int laytype,
211     int iomode);
212 static void nfsrv_freealllayouts(void);
213 static void nfsrv_freedevid(struct nfsdevice *ds);
214 static int nfsrv_setdsserver(char *dspathp, char *mdspathp, NFSPROC_T *p,
215     struct nfsdevice **dsp);
216 static void nfsrv_deleteds(struct nfsdevice *fndds);
217 static void nfsrv_allocdevid(struct nfsdevice *ds, char *addr, char *dnshost);
218 static void nfsrv_freealldevids(void);
219 static void nfsrv_flexlayouterr(struct nfsrv_descript *nd, uint32_t *layp,
220     int maxcnt, NFSPROC_T *p);
221 static int nfsrv_recalllayout(nfsquad_t clid, nfsv4stateid_t *stateidp,
222     fhandle_t *fhp, struct nfslayout *lyp, int changed, int laytype,
223     NFSPROC_T *p);
224 static int nfsrv_findlayout(nfsquad_t *clientidp, fhandle_t *fhp, int laytype,
225     NFSPROC_T *, struct nfslayout **lypp);
226 static int nfsrv_fndclid(nfsquad_t *clidvec, nfsquad_t clid, int clidcnt);
227 static struct nfslayout *nfsrv_filelayout(struct nfsrv_descript *nd, int iomode,
228     fhandle_t *fhp, fhandle_t *dsfhp, char *devid, fsid_t fs);
229 static struct nfslayout *nfsrv_flexlayout(struct nfsrv_descript *nd, int iomode,
230     int mirrorcnt, fhandle_t *fhp, fhandle_t *dsfhp, char *devid, fsid_t fs);
231 static int nfsrv_dontlayout(fhandle_t *fhp);
232 static int nfsrv_createdsfile(vnode_t vp, fhandle_t *fhp, struct pnfsdsfile *pf,
233     vnode_t dvp, struct nfsdevice *ds, struct ucred *cred, NFSPROC_T *p,
234     vnode_t *tvpp);
235 static struct nfsdevice *nfsrv_findmirroredds(struct nfsmount *nmp);
236 
237 /*
238  * Scan the client list for a match and either return the current one,
239  * create a new entry or return an error.
240  * If returning a non-error, the clp structure must either be linked into
241  * the client list or free'd.
242  */
243 int
244 nfsrv_setclient(struct nfsrv_descript *nd, struct nfsclient **new_clpp,
245     nfsquad_t *clientidp, nfsquad_t *confirmp, NFSPROC_T *p)
246 {
247 	struct nfsclient *clp = NULL, *new_clp = *new_clpp;
248 	int i, error = 0, ret;
249 	struct nfsstate *stp, *tstp;
250 #ifdef INET
251 	struct sockaddr_in *sin, *rin;
252 #endif
253 #ifdef INET6
254 	struct sockaddr_in6 *sin6, *rin6;
255 #endif
256 	struct nfsdsession *sep, *nsep;
257 	int zapit = 0, gotit, hasstate = 0, igotlock;
258 	static u_int64_t confirm_index = 0;
259 
260 	/*
261 	 * Check for state resource limit exceeded.
262 	 */
263 	if (nfsrv_openpluslock > nfsrv_v4statelimit) {
264 		error = NFSERR_RESOURCE;
265 		goto out;
266 	}
267 
268 	if (nfsrv_issuedelegs == 0 ||
269 	    ((nd->nd_flag & ND_GSS) != 0 && nfsrv_nogsscallback != 0))
270 		/*
271 		 * Don't do callbacks when delegations are disabled or
272 		 * for AUTH_GSS unless enabled via nfsrv_nogsscallback.
273 		 * If establishing a callback connection is attempted
274 		 * when a firewall is blocking the callback path, the
275 		 * server may wait too long for the connect attempt to
276 		 * succeed during the Open. Some clients, such as Linux,
277 		 * may timeout and give up on the Open before the server
278 		 * replies. Also, since AUTH_GSS callbacks are not
279 		 * yet interoperability tested, they might cause the
280 		 * server to crap out, if they get past the Init call to
281 		 * the client.
282 		 */
283 		new_clp->lc_program = 0;
284 
285 	/* Lock out other nfsd threads */
286 	NFSLOCKV4ROOTMUTEX();
287 	nfsv4_relref(&nfsv4rootfs_lock);
288 	do {
289 		igotlock = nfsv4_lock(&nfsv4rootfs_lock, 1, NULL,
290 		    NFSV4ROOTLOCKMUTEXPTR, NULL);
291 	} while (!igotlock);
292 	NFSUNLOCKV4ROOTMUTEX();
293 
294 	/*
295 	 * Search for a match in the client list.
296 	 */
297 	gotit = i = 0;
298 	while (i < nfsrv_clienthashsize && !gotit) {
299 	    LIST_FOREACH(clp, &nfsclienthash[i], lc_hash) {
300 		if (new_clp->lc_idlen == clp->lc_idlen &&
301 		    !NFSBCMP(new_clp->lc_id, clp->lc_id, clp->lc_idlen)) {
302 			gotit = 1;
303 			break;
304 		}
305 	    }
306 	    if (gotit == 0)
307 		i++;
308 	}
309 	if (!gotit ||
310 	    (clp->lc_flags & (LCL_NEEDSCONFIRM | LCL_ADMINREVOKED))) {
311 		if ((nd->nd_flag & ND_NFSV41) != 0 && confirmp->lval[1] != 0) {
312 			/*
313 			 * For NFSv4.1, if confirmp->lval[1] is non-zero, the
314 			 * client is trying to update a confirmed clientid.
315 			 */
316 			NFSLOCKV4ROOTMUTEX();
317 			nfsv4_unlock(&nfsv4rootfs_lock, 1);
318 			NFSUNLOCKV4ROOTMUTEX();
319 			confirmp->lval[1] = 0;
320 			error = NFSERR_NOENT;
321 			goto out;
322 		}
323 		/*
324 		 * Get rid of the old one.
325 		 */
326 		if (i != nfsrv_clienthashsize) {
327 			LIST_REMOVE(clp, lc_hash);
328 			nfsrv_cleanclient(clp, p);
329 			nfsrv_freedeleglist(&clp->lc_deleg);
330 			nfsrv_freedeleglist(&clp->lc_olddeleg);
331 			zapit = 1;
332 		}
333 		/*
334 		 * Add it after assigning a client id to it.
335 		 */
336 		new_clp->lc_flags |= LCL_NEEDSCONFIRM;
337 		if ((nd->nd_flag & ND_NFSV41) != 0)
338 			new_clp->lc_confirm.lval[0] = confirmp->lval[0] =
339 			    ++confirm_index;
340 		else
341 			confirmp->qval = new_clp->lc_confirm.qval =
342 			    ++confirm_index;
343 		clientidp->lval[0] = new_clp->lc_clientid.lval[0] =
344 		    (u_int32_t)nfsrvboottime;
345 		clientidp->lval[1] = new_clp->lc_clientid.lval[1] =
346 		    nfsrv_nextclientindex();
347 		new_clp->lc_stateindex = 0;
348 		new_clp->lc_statemaxindex = 0;
349 		new_clp->lc_cbref = 0;
350 		new_clp->lc_expiry = nfsrv_leaseexpiry();
351 		LIST_INIT(&new_clp->lc_open);
352 		LIST_INIT(&new_clp->lc_deleg);
353 		LIST_INIT(&new_clp->lc_olddeleg);
354 		LIST_INIT(&new_clp->lc_session);
355 		for (i = 0; i < nfsrv_statehashsize; i++)
356 			LIST_INIT(&new_clp->lc_stateid[i]);
357 		LIST_INSERT_HEAD(NFSCLIENTHASH(new_clp->lc_clientid), new_clp,
358 		    lc_hash);
359 		nfsstatsv1.srvclients++;
360 		nfsrv_openpluslock++;
361 		nfsrv_clients++;
362 		NFSLOCKV4ROOTMUTEX();
363 		nfsv4_unlock(&nfsv4rootfs_lock, 1);
364 		NFSUNLOCKV4ROOTMUTEX();
365 		if (zapit)
366 			nfsrv_zapclient(clp, p);
367 		*new_clpp = NULL;
368 		goto out;
369 	}
370 
371 	/*
372 	 * Now, handle the cases where the id is already issued.
373 	 */
374 	if (nfsrv_notsamecredname(nd, clp)) {
375 	    /*
376 	     * Check to see if there is expired state that should go away.
377 	     */
378 	    if (clp->lc_expiry < NFSD_MONOSEC &&
379 	        (!LIST_EMPTY(&clp->lc_open) || !LIST_EMPTY(&clp->lc_deleg))) {
380 		nfsrv_cleanclient(clp, p);
381 		nfsrv_freedeleglist(&clp->lc_deleg);
382 	    }
383 
384 	    /*
385 	     * If there is outstanding state, then reply NFSERR_CLIDINUSE per
386 	     * RFC3530 Sec. 8.1.2 last para.
387 	     */
388 	    if (!LIST_EMPTY(&clp->lc_deleg)) {
389 		hasstate = 1;
390 	    } else if (LIST_EMPTY(&clp->lc_open)) {
391 		hasstate = 0;
392 	    } else {
393 		hasstate = 0;
394 		/* Look for an Open on the OpenOwner */
395 		LIST_FOREACH(stp, &clp->lc_open, ls_list) {
396 		    if (!LIST_EMPTY(&stp->ls_open)) {
397 			hasstate = 1;
398 			break;
399 		    }
400 		}
401 	    }
402 	    if (hasstate) {
403 		/*
404 		 * If the uid doesn't match, return NFSERR_CLIDINUSE after
405 		 * filling out the correct ipaddr and portnum.
406 		 */
407 		switch (clp->lc_req.nr_nam->sa_family) {
408 #ifdef INET
409 		case AF_INET:
410 			sin = (struct sockaddr_in *)new_clp->lc_req.nr_nam;
411 			rin = (struct sockaddr_in *)clp->lc_req.nr_nam;
412 			sin->sin_addr.s_addr = rin->sin_addr.s_addr;
413 			sin->sin_port = rin->sin_port;
414 			break;
415 #endif
416 #ifdef INET6
417 		case AF_INET6:
418 			sin6 = (struct sockaddr_in6 *)new_clp->lc_req.nr_nam;
419 			rin6 = (struct sockaddr_in6 *)clp->lc_req.nr_nam;
420 			sin6->sin6_addr = rin6->sin6_addr;
421 			sin6->sin6_port = rin6->sin6_port;
422 			break;
423 #endif
424 		}
425 		NFSLOCKV4ROOTMUTEX();
426 		nfsv4_unlock(&nfsv4rootfs_lock, 1);
427 		NFSUNLOCKV4ROOTMUTEX();
428 		error = NFSERR_CLIDINUSE;
429 		goto out;
430 	    }
431 	}
432 
433 	if (NFSBCMP(new_clp->lc_verf, clp->lc_verf, NFSX_VERF)) {
434 		/*
435 		 * If the verifier has changed, the client has rebooted
436 		 * and a new client id is issued. The old state info
437 		 * can be thrown away once the SETCLIENTID_CONFIRM occurs.
438 		 */
439 		LIST_REMOVE(clp, lc_hash);
440 
441 		/* Get rid of all sessions on this clientid. */
442 		LIST_FOREACH_SAFE(sep, &clp->lc_session, sess_list, nsep) {
443 			ret = nfsrv_freesession(sep, NULL);
444 			if (ret != 0)
445 				printf("nfsrv_setclient: verifier changed free"
446 				    " session failed=%d\n", ret);
447 		}
448 
449 		new_clp->lc_flags |= LCL_NEEDSCONFIRM;
450 		if ((nd->nd_flag & ND_NFSV41) != 0)
451 			new_clp->lc_confirm.lval[0] = confirmp->lval[0] =
452 			    ++confirm_index;
453 		else
454 			confirmp->qval = new_clp->lc_confirm.qval =
455 			    ++confirm_index;
456 		clientidp->lval[0] = new_clp->lc_clientid.lval[0] =
457 		    nfsrvboottime;
458 		clientidp->lval[1] = new_clp->lc_clientid.lval[1] =
459 		    nfsrv_nextclientindex();
460 		new_clp->lc_stateindex = 0;
461 		new_clp->lc_statemaxindex = 0;
462 		new_clp->lc_cbref = 0;
463 		new_clp->lc_expiry = nfsrv_leaseexpiry();
464 
465 		/*
466 		 * Save the state until confirmed.
467 		 */
468 		LIST_NEWHEAD(&new_clp->lc_open, &clp->lc_open, ls_list);
469 		LIST_FOREACH(tstp, &new_clp->lc_open, ls_list)
470 			tstp->ls_clp = new_clp;
471 		LIST_NEWHEAD(&new_clp->lc_deleg, &clp->lc_deleg, ls_list);
472 		LIST_FOREACH(tstp, &new_clp->lc_deleg, ls_list)
473 			tstp->ls_clp = new_clp;
474 		LIST_NEWHEAD(&new_clp->lc_olddeleg, &clp->lc_olddeleg,
475 		    ls_list);
476 		LIST_FOREACH(tstp, &new_clp->lc_olddeleg, ls_list)
477 			tstp->ls_clp = new_clp;
478 		for (i = 0; i < nfsrv_statehashsize; i++) {
479 			LIST_NEWHEAD(&new_clp->lc_stateid[i],
480 			    &clp->lc_stateid[i], ls_hash);
481 			LIST_FOREACH(tstp, &new_clp->lc_stateid[i], ls_hash)
482 				tstp->ls_clp = new_clp;
483 		}
484 		LIST_INIT(&new_clp->lc_session);
485 		LIST_INSERT_HEAD(NFSCLIENTHASH(new_clp->lc_clientid), new_clp,
486 		    lc_hash);
487 		nfsstatsv1.srvclients++;
488 		nfsrv_openpluslock++;
489 		nfsrv_clients++;
490 		NFSLOCKV4ROOTMUTEX();
491 		nfsv4_unlock(&nfsv4rootfs_lock, 1);
492 		NFSUNLOCKV4ROOTMUTEX();
493 
494 		/*
495 		 * Must wait until any outstanding callback on the old clp
496 		 * completes.
497 		 */
498 		NFSLOCKSTATE();
499 		while (clp->lc_cbref) {
500 			clp->lc_flags |= LCL_WAKEUPWANTED;
501 			(void)mtx_sleep(clp, NFSSTATEMUTEXPTR, PZERO - 1,
502 			    "nfsd clp", 10 * hz);
503 		}
504 		NFSUNLOCKSTATE();
505 		nfsrv_zapclient(clp, p);
506 		*new_clpp = NULL;
507 		goto out;
508 	}
509 
510 	/* For NFSv4.1, mark that we found a confirmed clientid. */
511 	if ((nd->nd_flag & ND_NFSV41) != 0) {
512 		clientidp->lval[0] = clp->lc_clientid.lval[0];
513 		clientidp->lval[1] = clp->lc_clientid.lval[1];
514 		confirmp->lval[0] = 0;	/* Ignored by client */
515 		confirmp->lval[1] = 1;
516 	} else {
517 		/*
518 		 * id and verifier match, so update the net address info
519 		 * and get rid of any existing callback authentication
520 		 * handle, so a new one will be acquired.
521 		 */
522 		LIST_REMOVE(clp, lc_hash);
523 		new_clp->lc_flags |= (LCL_NEEDSCONFIRM | LCL_DONTCLEAN);
524 		new_clp->lc_expiry = nfsrv_leaseexpiry();
525 		confirmp->qval = new_clp->lc_confirm.qval = ++confirm_index;
526 		clientidp->lval[0] = new_clp->lc_clientid.lval[0] =
527 		    clp->lc_clientid.lval[0];
528 		clientidp->lval[1] = new_clp->lc_clientid.lval[1] =
529 		    clp->lc_clientid.lval[1];
530 		new_clp->lc_delegtime = clp->lc_delegtime;
531 		new_clp->lc_stateindex = clp->lc_stateindex;
532 		new_clp->lc_statemaxindex = clp->lc_statemaxindex;
533 		new_clp->lc_cbref = 0;
534 		LIST_NEWHEAD(&new_clp->lc_open, &clp->lc_open, ls_list);
535 		LIST_FOREACH(tstp, &new_clp->lc_open, ls_list)
536 			tstp->ls_clp = new_clp;
537 		LIST_NEWHEAD(&new_clp->lc_deleg, &clp->lc_deleg, ls_list);
538 		LIST_FOREACH(tstp, &new_clp->lc_deleg, ls_list)
539 			tstp->ls_clp = new_clp;
540 		LIST_NEWHEAD(&new_clp->lc_olddeleg, &clp->lc_olddeleg, ls_list);
541 		LIST_FOREACH(tstp, &new_clp->lc_olddeleg, ls_list)
542 			tstp->ls_clp = new_clp;
543 		for (i = 0; i < nfsrv_statehashsize; i++) {
544 			LIST_NEWHEAD(&new_clp->lc_stateid[i],
545 			    &clp->lc_stateid[i], ls_hash);
546 			LIST_FOREACH(tstp, &new_clp->lc_stateid[i], ls_hash)
547 				tstp->ls_clp = new_clp;
548 		}
549 		LIST_INIT(&new_clp->lc_session);
550 		LIST_INSERT_HEAD(NFSCLIENTHASH(new_clp->lc_clientid), new_clp,
551 		    lc_hash);
552 		nfsstatsv1.srvclients++;
553 		nfsrv_openpluslock++;
554 		nfsrv_clients++;
555 	}
556 	NFSLOCKV4ROOTMUTEX();
557 	nfsv4_unlock(&nfsv4rootfs_lock, 1);
558 	NFSUNLOCKV4ROOTMUTEX();
559 
560 	if ((nd->nd_flag & ND_NFSV41) == 0) {
561 		/*
562 		 * Must wait until any outstanding callback on the old clp
563 		 * completes.
564 		 */
565 		NFSLOCKSTATE();
566 		while (clp->lc_cbref) {
567 			clp->lc_flags |= LCL_WAKEUPWANTED;
568 			(void)mtx_sleep(clp, NFSSTATEMUTEXPTR, PZERO - 1,
569 			    "nfsdclp", 10 * hz);
570 		}
571 		NFSUNLOCKSTATE();
572 		nfsrv_zapclient(clp, p);
573 		*new_clpp = NULL;
574 	}
575 
576 out:
577 	NFSEXITCODE2(error, nd);
578 	return (error);
579 }
580 
581 /*
582  * Check to see if the client id exists and optionally confirm it.
583  */
584 int
585 nfsrv_getclient(nfsquad_t clientid, int opflags, struct nfsclient **clpp,
586     struct nfsdsession *nsep, nfsquad_t confirm, uint32_t cbprogram,
587     struct nfsrv_descript *nd, NFSPROC_T *p)
588 {
589 	struct nfsclient *clp;
590 	struct nfsstate *stp;
591 	int i;
592 	struct nfsclienthashhead *hp;
593 	int error = 0, igotlock, doneok;
594 	struct nfssessionhash *shp;
595 	struct nfsdsession *sep;
596 	uint64_t sessid[2];
597 	static uint64_t next_sess = 0;
598 
599 	if (clpp)
600 		*clpp = NULL;
601 	if ((nd == NULL || (nd->nd_flag & ND_NFSV41) == 0 ||
602 	    opflags != CLOPS_RENEW) && nfsrvboottime != clientid.lval[0]) {
603 		error = NFSERR_STALECLIENTID;
604 		goto out;
605 	}
606 
607 	/*
608 	 * If called with opflags == CLOPS_RENEW, the State Lock is
609 	 * already held. Otherwise, we need to get either that or,
610 	 * for the case of Confirm, lock out the nfsd threads.
611 	 */
612 	if (opflags & CLOPS_CONFIRM) {
613 		NFSLOCKV4ROOTMUTEX();
614 		nfsv4_relref(&nfsv4rootfs_lock);
615 		do {
616 			igotlock = nfsv4_lock(&nfsv4rootfs_lock, 1, NULL,
617 			    NFSV4ROOTLOCKMUTEXPTR, NULL);
618 		} while (!igotlock);
619 		/*
620 		 * Create a new sessionid here, since we need to do it where
621 		 * there is a mutex held to serialize update of next_sess.
622 		 */
623 		if ((nd->nd_flag & ND_NFSV41) != 0) {
624 			sessid[0] = ++next_sess;
625 			sessid[1] = clientid.qval;
626 		}
627 		NFSUNLOCKV4ROOTMUTEX();
628 	} else if (opflags != CLOPS_RENEW) {
629 		NFSLOCKSTATE();
630 	}
631 
632 	/* For NFSv4.1, the clp is acquired from the associated session. */
633 	if (nd != NULL && (nd->nd_flag & ND_NFSV41) != 0 &&
634 	    opflags == CLOPS_RENEW) {
635 		clp = NULL;
636 		if ((nd->nd_flag & ND_HASSEQUENCE) != 0) {
637 			shp = NFSSESSIONHASH(nd->nd_sessionid);
638 			NFSLOCKSESSION(shp);
639 			sep = nfsrv_findsession(nd->nd_sessionid);
640 			if (sep != NULL)
641 				clp = sep->sess_clp;
642 			NFSUNLOCKSESSION(shp);
643 		}
644 	} else {
645 		hp = NFSCLIENTHASH(clientid);
646 		LIST_FOREACH(clp, hp, lc_hash) {
647 			if (clp->lc_clientid.lval[1] == clientid.lval[1])
648 				break;
649 		}
650 	}
651 	if (clp == NULL) {
652 		if (opflags & CLOPS_CONFIRM)
653 			error = NFSERR_STALECLIENTID;
654 		else
655 			error = NFSERR_EXPIRED;
656 	} else if (clp->lc_flags & LCL_ADMINREVOKED) {
657 		/*
658 		 * If marked admin revoked, just return the error.
659 		 */
660 		error = NFSERR_ADMINREVOKED;
661 	}
662 	if (error) {
663 		if (opflags & CLOPS_CONFIRM) {
664 			NFSLOCKV4ROOTMUTEX();
665 			nfsv4_unlock(&nfsv4rootfs_lock, 1);
666 			NFSUNLOCKV4ROOTMUTEX();
667 		} else if (opflags != CLOPS_RENEW) {
668 			NFSUNLOCKSTATE();
669 		}
670 		goto out;
671 	}
672 
673 	/*
674 	 * Perform any operations specified by the opflags.
675 	 */
676 	if (opflags & CLOPS_CONFIRM) {
677 		if (((nd->nd_flag & ND_NFSV41) != 0 &&
678 		     clp->lc_confirm.lval[0] != confirm.lval[0]) ||
679 		    ((nd->nd_flag & ND_NFSV41) == 0 &&
680 		     clp->lc_confirm.qval != confirm.qval))
681 			error = NFSERR_STALECLIENTID;
682 		else if (nfsrv_notsamecredname(nd, clp))
683 			error = NFSERR_CLIDINUSE;
684 
685 		if (!error) {
686 		    if ((clp->lc_flags & (LCL_NEEDSCONFIRM | LCL_DONTCLEAN)) ==
687 			LCL_NEEDSCONFIRM) {
688 			/*
689 			 * Hang onto the delegations (as old delegations)
690 			 * for an Open with CLAIM_DELEGATE_PREV unless in
691 			 * grace, but get rid of the rest of the state.
692 			 */
693 			nfsrv_cleanclient(clp, p);
694 			nfsrv_freedeleglist(&clp->lc_olddeleg);
695 			if (nfsrv_checkgrace(nd, clp, 0)) {
696 			    /* In grace, so just delete delegations */
697 			    nfsrv_freedeleglist(&clp->lc_deleg);
698 			} else {
699 			    LIST_FOREACH(stp, &clp->lc_deleg, ls_list)
700 				stp->ls_flags |= NFSLCK_OLDDELEG;
701 			    clp->lc_delegtime = NFSD_MONOSEC +
702 				nfsrv_lease + NFSRV_LEASEDELTA;
703 			    LIST_NEWHEAD(&clp->lc_olddeleg, &clp->lc_deleg,
704 				ls_list);
705 			}
706 			if ((nd->nd_flag & ND_NFSV41) != 0)
707 			    clp->lc_program = cbprogram;
708 		    }
709 		    clp->lc_flags &= ~(LCL_NEEDSCONFIRM | LCL_DONTCLEAN);
710 		    if (clp->lc_program)
711 			clp->lc_flags |= LCL_NEEDSCBNULL;
712 		    /* For NFSv4.1, link the session onto the client. */
713 		    if (nsep != NULL) {
714 			/* Hold a reference on the xprt for a backchannel. */
715 			if ((nsep->sess_crflags & NFSV4CRSESS_CONNBACKCHAN)
716 			    != 0) {
717 			    if (clp->lc_req.nr_client == NULL)
718 				clp->lc_req.nr_client = (struct __rpc_client *)
719 				    clnt_bck_create(nd->nd_xprt->xp_socket,
720 				    cbprogram, NFSV4_CBVERS);
721 			    if (clp->lc_req.nr_client != NULL) {
722 				SVC_ACQUIRE(nd->nd_xprt);
723 				nd->nd_xprt->xp_p2 =
724 				    clp->lc_req.nr_client->cl_private;
725 				/* Disable idle timeout. */
726 				nd->nd_xprt->xp_idletimeout = 0;
727 				nsep->sess_cbsess.nfsess_xprt = nd->nd_xprt;
728 			    } else
729 				nsep->sess_crflags &= ~NFSV4CRSESS_CONNBACKCHAN;
730 			}
731 			NFSBCOPY(sessid, nsep->sess_sessionid,
732 			    NFSX_V4SESSIONID);
733 			NFSBCOPY(sessid, nsep->sess_cbsess.nfsess_sessionid,
734 			    NFSX_V4SESSIONID);
735 			shp = NFSSESSIONHASH(nsep->sess_sessionid);
736 			NFSLOCKSTATE();
737 			NFSLOCKSESSION(shp);
738 			LIST_INSERT_HEAD(&shp->list, nsep, sess_hash);
739 			LIST_INSERT_HEAD(&clp->lc_session, nsep, sess_list);
740 			nsep->sess_clp = clp;
741 			NFSUNLOCKSESSION(shp);
742 			NFSUNLOCKSTATE();
743 		    }
744 		}
745 	} else if (clp->lc_flags & LCL_NEEDSCONFIRM) {
746 		error = NFSERR_EXPIRED;
747 	}
748 
749 	/*
750 	 * If called by the Renew Op, we must check the principal.
751 	 */
752 	if (!error && (opflags & CLOPS_RENEWOP)) {
753 	    if (nfsrv_notsamecredname(nd, clp)) {
754 		doneok = 0;
755 		for (i = 0; i < nfsrv_statehashsize && doneok == 0; i++) {
756 		    LIST_FOREACH(stp, &clp->lc_stateid[i], ls_hash) {
757 			if ((stp->ls_flags & NFSLCK_OPEN) &&
758 			    stp->ls_uid == nd->nd_cred->cr_uid) {
759 				doneok = 1;
760 				break;
761 			}
762 		    }
763 		}
764 		if (!doneok)
765 			error = NFSERR_ACCES;
766 	    }
767 	    if (!error && (clp->lc_flags & LCL_CBDOWN))
768 		error = NFSERR_CBPATHDOWN;
769 	}
770 	if ((!error || error == NFSERR_CBPATHDOWN) &&
771 	     (opflags & CLOPS_RENEW)) {
772 		clp->lc_expiry = nfsrv_leaseexpiry();
773 	}
774 	if (opflags & CLOPS_CONFIRM) {
775 		NFSLOCKV4ROOTMUTEX();
776 		nfsv4_unlock(&nfsv4rootfs_lock, 1);
777 		NFSUNLOCKV4ROOTMUTEX();
778 	} else if (opflags != CLOPS_RENEW) {
779 		NFSUNLOCKSTATE();
780 	}
781 	if (clpp)
782 		*clpp = clp;
783 
784 out:
785 	NFSEXITCODE2(error, nd);
786 	return (error);
787 }
788 
789 /*
790  * Perform the NFSv4.1 destroy clientid.
791  */
792 int
793 nfsrv_destroyclient(nfsquad_t clientid, NFSPROC_T *p)
794 {
795 	struct nfsclient *clp;
796 	struct nfsclienthashhead *hp;
797 	int error = 0, i, igotlock;
798 
799 	if (nfsrvboottime != clientid.lval[0]) {
800 		error = NFSERR_STALECLIENTID;
801 		goto out;
802 	}
803 
804 	/* Lock out other nfsd threads */
805 	NFSLOCKV4ROOTMUTEX();
806 	nfsv4_relref(&nfsv4rootfs_lock);
807 	do {
808 		igotlock = nfsv4_lock(&nfsv4rootfs_lock, 1, NULL,
809 		    NFSV4ROOTLOCKMUTEXPTR, NULL);
810 	} while (igotlock == 0);
811 	NFSUNLOCKV4ROOTMUTEX();
812 
813 	hp = NFSCLIENTHASH(clientid);
814 	LIST_FOREACH(clp, hp, lc_hash) {
815 		if (clp->lc_clientid.lval[1] == clientid.lval[1])
816 			break;
817 	}
818 	if (clp == NULL) {
819 		NFSLOCKV4ROOTMUTEX();
820 		nfsv4_unlock(&nfsv4rootfs_lock, 1);
821 		NFSUNLOCKV4ROOTMUTEX();
822 		/* Just return ok, since it is gone. */
823 		goto out;
824 	}
825 
826 	/*
827 	 * Free up all layouts on the clientid.  Should the client return the
828 	 * layouts?
829 	 */
830 	nfsrv_freelayoutlist(clientid);
831 
832 	/* Scan for state on the clientid. */
833 	for (i = 0; i < nfsrv_statehashsize; i++)
834 		if (!LIST_EMPTY(&clp->lc_stateid[i])) {
835 			NFSLOCKV4ROOTMUTEX();
836 			nfsv4_unlock(&nfsv4rootfs_lock, 1);
837 			NFSUNLOCKV4ROOTMUTEX();
838 			error = NFSERR_CLIENTIDBUSY;
839 			goto out;
840 		}
841 	if (!LIST_EMPTY(&clp->lc_session) || !LIST_EMPTY(&clp->lc_deleg)) {
842 		NFSLOCKV4ROOTMUTEX();
843 		nfsv4_unlock(&nfsv4rootfs_lock, 1);
844 		NFSUNLOCKV4ROOTMUTEX();
845 		error = NFSERR_CLIENTIDBUSY;
846 		goto out;
847 	}
848 
849 	/* Destroy the clientid and return ok. */
850 	nfsrv_cleanclient(clp, p);
851 	nfsrv_freedeleglist(&clp->lc_deleg);
852 	nfsrv_freedeleglist(&clp->lc_olddeleg);
853 	LIST_REMOVE(clp, lc_hash);
854 	NFSLOCKV4ROOTMUTEX();
855 	nfsv4_unlock(&nfsv4rootfs_lock, 1);
856 	NFSUNLOCKV4ROOTMUTEX();
857 	nfsrv_zapclient(clp, p);
858 out:
859 	NFSEXITCODE2(error, nd);
860 	return (error);
861 }
862 
863 /*
864  * Called from the new nfssvc syscall to admin revoke a clientid.
865  * Returns 0 for success, error otherwise.
866  */
867 int
868 nfsrv_adminrevoke(struct nfsd_clid *revokep, NFSPROC_T *p)
869 {
870 	struct nfsclient *clp = NULL;
871 	int i, error = 0;
872 	int gotit, igotlock;
873 
874 	/*
875 	 * First, lock out the nfsd so that state won't change while the
876 	 * revocation record is being written to the stable storage restart
877 	 * file.
878 	 */
879 	NFSLOCKV4ROOTMUTEX();
880 	do {
881 		igotlock = nfsv4_lock(&nfsv4rootfs_lock, 1, NULL,
882 		    NFSV4ROOTLOCKMUTEXPTR, NULL);
883 	} while (!igotlock);
884 	NFSUNLOCKV4ROOTMUTEX();
885 
886 	/*
887 	 * Search for a match in the client list.
888 	 */
889 	gotit = i = 0;
890 	while (i < nfsrv_clienthashsize && !gotit) {
891 	    LIST_FOREACH(clp, &nfsclienthash[i], lc_hash) {
892 		if (revokep->nclid_idlen == clp->lc_idlen &&
893 		    !NFSBCMP(revokep->nclid_id, clp->lc_id, clp->lc_idlen)) {
894 			gotit = 1;
895 			break;
896 		}
897 	    }
898 	    i++;
899 	}
900 	if (!gotit) {
901 		NFSLOCKV4ROOTMUTEX();
902 		nfsv4_unlock(&nfsv4rootfs_lock, 0);
903 		NFSUNLOCKV4ROOTMUTEX();
904 		error = EPERM;
905 		goto out;
906 	}
907 
908 	/*
909 	 * Now, write out the revocation record
910 	 */
911 	nfsrv_writestable(clp->lc_id, clp->lc_idlen, NFSNST_REVOKE, p);
912 	nfsrv_backupstable();
913 
914 	/*
915 	 * and clear out the state, marking the clientid revoked.
916 	 */
917 	clp->lc_flags &= ~LCL_CALLBACKSON;
918 	clp->lc_flags |= LCL_ADMINREVOKED;
919 	nfsrv_cleanclient(clp, p);
920 	nfsrv_freedeleglist(&clp->lc_deleg);
921 	nfsrv_freedeleglist(&clp->lc_olddeleg);
922 	NFSLOCKV4ROOTMUTEX();
923 	nfsv4_unlock(&nfsv4rootfs_lock, 0);
924 	NFSUNLOCKV4ROOTMUTEX();
925 
926 out:
927 	NFSEXITCODE(error);
928 	return (error);
929 }
930 
931 /*
932  * Dump out stats for all clients. Called from nfssvc(2), that is used
933  * nfsstatsv1.
934  */
935 void
936 nfsrv_dumpclients(struct nfsd_dumpclients *dumpp, int maxcnt)
937 {
938 	struct nfsclient *clp;
939 	int i = 0, cnt = 0;
940 
941 	/*
942 	 * First, get a reference on the nfsv4rootfs_lock so that an
943 	 * exclusive lock cannot be acquired while dumping the clients.
944 	 */
945 	NFSLOCKV4ROOTMUTEX();
946 	nfsv4_getref(&nfsv4rootfs_lock, NULL, NFSV4ROOTLOCKMUTEXPTR, NULL);
947 	NFSUNLOCKV4ROOTMUTEX();
948 	NFSLOCKSTATE();
949 	/*
950 	 * Rattle through the client lists until done.
951 	 */
952 	while (i < nfsrv_clienthashsize && cnt < maxcnt) {
953 	    clp = LIST_FIRST(&nfsclienthash[i]);
954 	    while (clp != LIST_END(&nfsclienthash[i]) && cnt < maxcnt) {
955 		nfsrv_dumpaclient(clp, &dumpp[cnt]);
956 		cnt++;
957 		clp = LIST_NEXT(clp, lc_hash);
958 	    }
959 	    i++;
960 	}
961 	if (cnt < maxcnt)
962 	    dumpp[cnt].ndcl_clid.nclid_idlen = 0;
963 	NFSUNLOCKSTATE();
964 	NFSLOCKV4ROOTMUTEX();
965 	nfsv4_relref(&nfsv4rootfs_lock);
966 	NFSUNLOCKV4ROOTMUTEX();
967 }
968 
969 /*
970  * Dump stats for a client. Must be called with the NFSSTATELOCK and spl'd.
971  */
972 static void
973 nfsrv_dumpaclient(struct nfsclient *clp, struct nfsd_dumpclients *dumpp)
974 {
975 	struct nfsstate *stp, *openstp, *lckownstp;
976 	struct nfslock *lop;
977 	sa_family_t af;
978 #ifdef INET
979 	struct sockaddr_in *rin;
980 #endif
981 #ifdef INET6
982 	struct sockaddr_in6 *rin6;
983 #endif
984 
985 	dumpp->ndcl_nopenowners = dumpp->ndcl_nlockowners = 0;
986 	dumpp->ndcl_nopens = dumpp->ndcl_nlocks = 0;
987 	dumpp->ndcl_ndelegs = dumpp->ndcl_nolddelegs = 0;
988 	dumpp->ndcl_flags = clp->lc_flags;
989 	dumpp->ndcl_clid.nclid_idlen = clp->lc_idlen;
990 	NFSBCOPY(clp->lc_id, dumpp->ndcl_clid.nclid_id, clp->lc_idlen);
991 	af = clp->lc_req.nr_nam->sa_family;
992 	dumpp->ndcl_addrfam = af;
993 	switch (af) {
994 #ifdef INET
995 	case AF_INET:
996 		rin = (struct sockaddr_in *)clp->lc_req.nr_nam;
997 		dumpp->ndcl_cbaddr.sin_addr = rin->sin_addr;
998 		break;
999 #endif
1000 #ifdef INET6
1001 	case AF_INET6:
1002 		rin6 = (struct sockaddr_in6 *)clp->lc_req.nr_nam;
1003 		dumpp->ndcl_cbaddr.sin6_addr = rin6->sin6_addr;
1004 		break;
1005 #endif
1006 	}
1007 
1008 	/*
1009 	 * Now, scan the state lists and total up the opens and locks.
1010 	 */
1011 	LIST_FOREACH(stp, &clp->lc_open, ls_list) {
1012 	    dumpp->ndcl_nopenowners++;
1013 	    LIST_FOREACH(openstp, &stp->ls_open, ls_list) {
1014 		dumpp->ndcl_nopens++;
1015 		LIST_FOREACH(lckownstp, &openstp->ls_open, ls_list) {
1016 		    dumpp->ndcl_nlockowners++;
1017 		    LIST_FOREACH(lop, &lckownstp->ls_lock, lo_lckowner) {
1018 			dumpp->ndcl_nlocks++;
1019 		    }
1020 		}
1021 	    }
1022 	}
1023 
1024 	/*
1025 	 * and the delegation lists.
1026 	 */
1027 	LIST_FOREACH(stp, &clp->lc_deleg, ls_list) {
1028 	    dumpp->ndcl_ndelegs++;
1029 	}
1030 	LIST_FOREACH(stp, &clp->lc_olddeleg, ls_list) {
1031 	    dumpp->ndcl_nolddelegs++;
1032 	}
1033 }
1034 
1035 /*
1036  * Dump out lock stats for a file.
1037  */
1038 void
1039 nfsrv_dumplocks(vnode_t vp, struct nfsd_dumplocks *ldumpp, int maxcnt,
1040     NFSPROC_T *p)
1041 {
1042 	struct nfsstate *stp;
1043 	struct nfslock *lop;
1044 	int cnt = 0;
1045 	struct nfslockfile *lfp;
1046 	sa_family_t af;
1047 #ifdef INET
1048 	struct sockaddr_in *rin;
1049 #endif
1050 #ifdef INET6
1051 	struct sockaddr_in6 *rin6;
1052 #endif
1053 	int ret;
1054 	fhandle_t nfh;
1055 
1056 	ret = nfsrv_getlockfh(vp, 0, NULL, &nfh, p);
1057 	/*
1058 	 * First, get a reference on the nfsv4rootfs_lock so that an
1059 	 * exclusive lock on it cannot be acquired while dumping the locks.
1060 	 */
1061 	NFSLOCKV4ROOTMUTEX();
1062 	nfsv4_getref(&nfsv4rootfs_lock, NULL, NFSV4ROOTLOCKMUTEXPTR, NULL);
1063 	NFSUNLOCKV4ROOTMUTEX();
1064 	NFSLOCKSTATE();
1065 	if (!ret)
1066 		ret = nfsrv_getlockfile(0, NULL, &lfp, &nfh, 0);
1067 	if (ret) {
1068 		ldumpp[0].ndlck_clid.nclid_idlen = 0;
1069 		NFSUNLOCKSTATE();
1070 		NFSLOCKV4ROOTMUTEX();
1071 		nfsv4_relref(&nfsv4rootfs_lock);
1072 		NFSUNLOCKV4ROOTMUTEX();
1073 		return;
1074 	}
1075 
1076 	/*
1077 	 * For each open share on file, dump it out.
1078 	 */
1079 	stp = LIST_FIRST(&lfp->lf_open);
1080 	while (stp != LIST_END(&lfp->lf_open) && cnt < maxcnt) {
1081 		ldumpp[cnt].ndlck_flags = stp->ls_flags;
1082 		ldumpp[cnt].ndlck_stateid.seqid = stp->ls_stateid.seqid;
1083 		ldumpp[cnt].ndlck_stateid.other[0] = stp->ls_stateid.other[0];
1084 		ldumpp[cnt].ndlck_stateid.other[1] = stp->ls_stateid.other[1];
1085 		ldumpp[cnt].ndlck_stateid.other[2] = stp->ls_stateid.other[2];
1086 		ldumpp[cnt].ndlck_owner.nclid_idlen =
1087 		    stp->ls_openowner->ls_ownerlen;
1088 		NFSBCOPY(stp->ls_openowner->ls_owner,
1089 		    ldumpp[cnt].ndlck_owner.nclid_id,
1090 		    stp->ls_openowner->ls_ownerlen);
1091 		ldumpp[cnt].ndlck_clid.nclid_idlen = stp->ls_clp->lc_idlen;
1092 		NFSBCOPY(stp->ls_clp->lc_id, ldumpp[cnt].ndlck_clid.nclid_id,
1093 		    stp->ls_clp->lc_idlen);
1094 		af = stp->ls_clp->lc_req.nr_nam->sa_family;
1095 		ldumpp[cnt].ndlck_addrfam = af;
1096 		switch (af) {
1097 #ifdef INET
1098 		case AF_INET:
1099 			rin = (struct sockaddr_in *)stp->ls_clp->lc_req.nr_nam;
1100 			ldumpp[cnt].ndlck_cbaddr.sin_addr = rin->sin_addr;
1101 			break;
1102 #endif
1103 #ifdef INET6
1104 		case AF_INET6:
1105 			rin6 = (struct sockaddr_in6 *)
1106 			    stp->ls_clp->lc_req.nr_nam;
1107 			ldumpp[cnt].ndlck_cbaddr.sin6_addr = rin6->sin6_addr;
1108 			break;
1109 #endif
1110 		}
1111 		stp = LIST_NEXT(stp, ls_file);
1112 		cnt++;
1113 	}
1114 
1115 	/*
1116 	 * and all locks.
1117 	 */
1118 	lop = LIST_FIRST(&lfp->lf_lock);
1119 	while (lop != LIST_END(&lfp->lf_lock) && cnt < maxcnt) {
1120 		stp = lop->lo_stp;
1121 		ldumpp[cnt].ndlck_flags = lop->lo_flags;
1122 		ldumpp[cnt].ndlck_first = lop->lo_first;
1123 		ldumpp[cnt].ndlck_end = lop->lo_end;
1124 		ldumpp[cnt].ndlck_stateid.seqid = stp->ls_stateid.seqid;
1125 		ldumpp[cnt].ndlck_stateid.other[0] = stp->ls_stateid.other[0];
1126 		ldumpp[cnt].ndlck_stateid.other[1] = stp->ls_stateid.other[1];
1127 		ldumpp[cnt].ndlck_stateid.other[2] = stp->ls_stateid.other[2];
1128 		ldumpp[cnt].ndlck_owner.nclid_idlen = stp->ls_ownerlen;
1129 		NFSBCOPY(stp->ls_owner, ldumpp[cnt].ndlck_owner.nclid_id,
1130 		    stp->ls_ownerlen);
1131 		ldumpp[cnt].ndlck_clid.nclid_idlen = stp->ls_clp->lc_idlen;
1132 		NFSBCOPY(stp->ls_clp->lc_id, ldumpp[cnt].ndlck_clid.nclid_id,
1133 		    stp->ls_clp->lc_idlen);
1134 		af = stp->ls_clp->lc_req.nr_nam->sa_family;
1135 		ldumpp[cnt].ndlck_addrfam = af;
1136 		switch (af) {
1137 #ifdef INET
1138 		case AF_INET:
1139 			rin = (struct sockaddr_in *)stp->ls_clp->lc_req.nr_nam;
1140 			ldumpp[cnt].ndlck_cbaddr.sin_addr = rin->sin_addr;
1141 			break;
1142 #endif
1143 #ifdef INET6
1144 		case AF_INET6:
1145 			rin6 = (struct sockaddr_in6 *)
1146 			    stp->ls_clp->lc_req.nr_nam;
1147 			ldumpp[cnt].ndlck_cbaddr.sin6_addr = rin6->sin6_addr;
1148 			break;
1149 #endif
1150 		}
1151 		lop = LIST_NEXT(lop, lo_lckfile);
1152 		cnt++;
1153 	}
1154 
1155 	/*
1156 	 * and the delegations.
1157 	 */
1158 	stp = LIST_FIRST(&lfp->lf_deleg);
1159 	while (stp != LIST_END(&lfp->lf_deleg) && cnt < maxcnt) {
1160 		ldumpp[cnt].ndlck_flags = stp->ls_flags;
1161 		ldumpp[cnt].ndlck_stateid.seqid = stp->ls_stateid.seqid;
1162 		ldumpp[cnt].ndlck_stateid.other[0] = stp->ls_stateid.other[0];
1163 		ldumpp[cnt].ndlck_stateid.other[1] = stp->ls_stateid.other[1];
1164 		ldumpp[cnt].ndlck_stateid.other[2] = stp->ls_stateid.other[2];
1165 		ldumpp[cnt].ndlck_owner.nclid_idlen = 0;
1166 		ldumpp[cnt].ndlck_clid.nclid_idlen = stp->ls_clp->lc_idlen;
1167 		NFSBCOPY(stp->ls_clp->lc_id, ldumpp[cnt].ndlck_clid.nclid_id,
1168 		    stp->ls_clp->lc_idlen);
1169 		af = stp->ls_clp->lc_req.nr_nam->sa_family;
1170 		ldumpp[cnt].ndlck_addrfam = af;
1171 		switch (af) {
1172 #ifdef INET
1173 		case AF_INET:
1174 			rin = (struct sockaddr_in *)stp->ls_clp->lc_req.nr_nam;
1175 			ldumpp[cnt].ndlck_cbaddr.sin_addr = rin->sin_addr;
1176 			break;
1177 #endif
1178 #ifdef INET6
1179 		case AF_INET6:
1180 			rin6 = (struct sockaddr_in6 *)
1181 			    stp->ls_clp->lc_req.nr_nam;
1182 			ldumpp[cnt].ndlck_cbaddr.sin6_addr = rin6->sin6_addr;
1183 			break;
1184 #endif
1185 		}
1186 		stp = LIST_NEXT(stp, ls_file);
1187 		cnt++;
1188 	}
1189 
1190 	/*
1191 	 * If list isn't full, mark end of list by setting the client name
1192 	 * to zero length.
1193 	 */
1194 	if (cnt < maxcnt)
1195 		ldumpp[cnt].ndlck_clid.nclid_idlen = 0;
1196 	NFSUNLOCKSTATE();
1197 	NFSLOCKV4ROOTMUTEX();
1198 	nfsv4_relref(&nfsv4rootfs_lock);
1199 	NFSUNLOCKV4ROOTMUTEX();
1200 }
1201 
1202 /*
1203  * Server timer routine. It can scan any linked list, so long
1204  * as it holds the spin/mutex lock and there is no exclusive lock on
1205  * nfsv4rootfs_lock.
1206  * (For OpenBSD, a kthread is ok. For FreeBSD, I think it is ok
1207  *  to do this from a callout, since the spin locks work. For
1208  *  Darwin, I'm not sure what will work correctly yet.)
1209  * Should be called once per second.
1210  */
1211 void
1212 nfsrv_servertimer(void)
1213 {
1214 	struct nfsclient *clp, *nclp;
1215 	struct nfsstate *stp, *nstp;
1216 	int got_ref, i;
1217 
1218 	/*
1219 	 * Make sure nfsboottime is set. This is used by V3 as well
1220 	 * as V4. Note that nfsboottime is not nfsrvboottime, which is
1221 	 * only used by the V4 server for leases.
1222 	 */
1223 	if (nfsboottime.tv_sec == 0)
1224 		NFSSETBOOTTIME(nfsboottime);
1225 
1226 	/*
1227 	 * If server hasn't started yet, just return.
1228 	 */
1229 	NFSLOCKSTATE();
1230 	if (nfsrv_stablefirst.nsf_eograce == 0) {
1231 		NFSUNLOCKSTATE();
1232 		return;
1233 	}
1234 	if (!(nfsrv_stablefirst.nsf_flags & NFSNSF_UPDATEDONE)) {
1235 		if (!(nfsrv_stablefirst.nsf_flags & NFSNSF_GRACEOVER) &&
1236 		    NFSD_MONOSEC > nfsrv_stablefirst.nsf_eograce)
1237 			nfsrv_stablefirst.nsf_flags |=
1238 			    (NFSNSF_GRACEOVER | NFSNSF_NEEDLOCK);
1239 		NFSUNLOCKSTATE();
1240 		return;
1241 	}
1242 
1243 	/*
1244 	 * Try and get a reference count on the nfsv4rootfs_lock so that
1245 	 * no nfsd thread can acquire an exclusive lock on it before this
1246 	 * call is done. If it is already exclusively locked, just return.
1247 	 */
1248 	NFSLOCKV4ROOTMUTEX();
1249 	got_ref = nfsv4_getref_nonblock(&nfsv4rootfs_lock);
1250 	NFSUNLOCKV4ROOTMUTEX();
1251 	if (got_ref == 0) {
1252 		NFSUNLOCKSTATE();
1253 		return;
1254 	}
1255 
1256 	/*
1257 	 * For each client...
1258 	 */
1259 	for (i = 0; i < nfsrv_clienthashsize; i++) {
1260 	    clp = LIST_FIRST(&nfsclienthash[i]);
1261 	    while (clp != LIST_END(&nfsclienthash[i])) {
1262 		nclp = LIST_NEXT(clp, lc_hash);
1263 		if (!(clp->lc_flags & LCL_EXPIREIT)) {
1264 		    if (((clp->lc_expiry + NFSRV_STALELEASE) < NFSD_MONOSEC
1265 			 && ((LIST_EMPTY(&clp->lc_deleg)
1266 			      && LIST_EMPTY(&clp->lc_open)) ||
1267 			     nfsrv_clients > nfsrv_clienthighwater)) ||
1268 			(clp->lc_expiry + NFSRV_MOULDYLEASE) < NFSD_MONOSEC ||
1269 			(clp->lc_expiry < NFSD_MONOSEC &&
1270 			 (nfsrv_openpluslock * 10 / 9) > nfsrv_v4statelimit)) {
1271 			/*
1272 			 * Lease has expired several nfsrv_lease times ago:
1273 			 * PLUS
1274 			 *    - no state is associated with it
1275 			 *    OR
1276 			 *    - above high water mark for number of clients
1277 			 *      (nfsrv_clienthighwater should be large enough
1278 			 *       that this only occurs when clients fail to
1279 			 *       use the same nfs_client_id4.id. Maybe somewhat
1280 			 *       higher that the maximum number of clients that
1281 			 *       will mount this server?)
1282 			 * OR
1283 			 * Lease has expired a very long time ago
1284 			 * OR
1285 			 * Lease has expired PLUS the number of opens + locks
1286 			 * has exceeded 90% of capacity
1287 			 *
1288 			 * --> Mark for expiry. The actual expiry will be done
1289 			 *     by an nfsd sometime soon.
1290 			 */
1291 			clp->lc_flags |= LCL_EXPIREIT;
1292 			nfsrv_stablefirst.nsf_flags |=
1293 			    (NFSNSF_NEEDLOCK | NFSNSF_EXPIREDCLIENT);
1294 		    } else {
1295 			/*
1296 			 * If there are no opens, increment no open tick cnt
1297 			 * If time exceeds NFSNOOPEN, mark it to be thrown away
1298 			 * otherwise, if there is an open, reset no open time
1299 			 * Hopefully, this will avoid excessive re-creation
1300 			 * of open owners and subsequent open confirms.
1301 			 */
1302 			stp = LIST_FIRST(&clp->lc_open);
1303 			while (stp != LIST_END(&clp->lc_open)) {
1304 				nstp = LIST_NEXT(stp, ls_list);
1305 				if (LIST_EMPTY(&stp->ls_open)) {
1306 					stp->ls_noopens++;
1307 					if (stp->ls_noopens > NFSNOOPEN ||
1308 					    (nfsrv_openpluslock * 2) >
1309 					    nfsrv_v4statelimit)
1310 						nfsrv_stablefirst.nsf_flags |=
1311 							NFSNSF_NOOPENS;
1312 				} else {
1313 					stp->ls_noopens = 0;
1314 				}
1315 				stp = nstp;
1316 			}
1317 		    }
1318 		}
1319 		clp = nclp;
1320 	    }
1321 	}
1322 	NFSUNLOCKSTATE();
1323 	NFSLOCKV4ROOTMUTEX();
1324 	nfsv4_relref(&nfsv4rootfs_lock);
1325 	NFSUNLOCKV4ROOTMUTEX();
1326 }
1327 
1328 /*
1329  * The following set of functions free up the various data structures.
1330  */
1331 /*
1332  * Clear out all open/lock state related to this nfsclient.
1333  * Caller must hold an exclusive lock on nfsv4rootfs_lock, so that
1334  * there are no other active nfsd threads.
1335  */
1336 void
1337 nfsrv_cleanclient(struct nfsclient *clp, NFSPROC_T *p)
1338 {
1339 	struct nfsstate *stp, *nstp;
1340 	struct nfsdsession *sep, *nsep;
1341 
1342 	LIST_FOREACH_SAFE(stp, &clp->lc_open, ls_list, nstp)
1343 		nfsrv_freeopenowner(stp, 1, p);
1344 	if ((clp->lc_flags & LCL_ADMINREVOKED) == 0)
1345 		LIST_FOREACH_SAFE(sep, &clp->lc_session, sess_list, nsep)
1346 			(void)nfsrv_freesession(sep, NULL);
1347 }
1348 
1349 /*
1350  * Free a client that has been cleaned. It should also already have been
1351  * removed from the lists.
1352  * (Just to be safe w.r.t. newnfs_disconnect(), call this function when
1353  *  softclock interrupts are enabled.)
1354  */
1355 void
1356 nfsrv_zapclient(struct nfsclient *clp, NFSPROC_T *p)
1357 {
1358 
1359 #ifdef notyet
1360 	if ((clp->lc_flags & (LCL_GSS | LCL_CALLBACKSON)) ==
1361 	     (LCL_GSS | LCL_CALLBACKSON) &&
1362 	    (clp->lc_hand.nfsh_flag & NFSG_COMPLETE) &&
1363 	    clp->lc_handlelen > 0) {
1364 		clp->lc_hand.nfsh_flag &= ~NFSG_COMPLETE;
1365 		clp->lc_hand.nfsh_flag |= NFSG_DESTROYED;
1366 		(void) nfsrv_docallback(clp, NFSV4PROC_CBNULL,
1367 			NULL, 0, NULL, NULL, NULL, 0, p);
1368 	}
1369 #endif
1370 	newnfs_disconnect(&clp->lc_req);
1371 	free(clp->lc_req.nr_nam, M_SONAME);
1372 	NFSFREEMUTEX(&clp->lc_req.nr_mtx);
1373 	free(clp->lc_stateid, M_NFSDCLIENT);
1374 	free(clp, M_NFSDCLIENT);
1375 	NFSLOCKSTATE();
1376 	nfsstatsv1.srvclients--;
1377 	nfsrv_openpluslock--;
1378 	nfsrv_clients--;
1379 	NFSUNLOCKSTATE();
1380 }
1381 
1382 /*
1383  * Free a list of delegation state structures.
1384  * (This function will also free all nfslockfile structures that no
1385  *  longer have associated state.)
1386  */
1387 void
1388 nfsrv_freedeleglist(struct nfsstatehead *sthp)
1389 {
1390 	struct nfsstate *stp, *nstp;
1391 
1392 	LIST_FOREACH_SAFE(stp, sthp, ls_list, nstp) {
1393 		nfsrv_freedeleg(stp);
1394 	}
1395 	LIST_INIT(sthp);
1396 }
1397 
1398 /*
1399  * Free up a delegation.
1400  */
1401 static void
1402 nfsrv_freedeleg(struct nfsstate *stp)
1403 {
1404 	struct nfslockfile *lfp;
1405 
1406 	LIST_REMOVE(stp, ls_hash);
1407 	LIST_REMOVE(stp, ls_list);
1408 	LIST_REMOVE(stp, ls_file);
1409 	if ((stp->ls_flags & NFSLCK_DELEGWRITE) != 0)
1410 		nfsrv_writedelegcnt--;
1411 	lfp = stp->ls_lfp;
1412 	if (LIST_EMPTY(&lfp->lf_open) &&
1413 	    LIST_EMPTY(&lfp->lf_lock) && LIST_EMPTY(&lfp->lf_deleg) &&
1414 	    LIST_EMPTY(&lfp->lf_locallock) && LIST_EMPTY(&lfp->lf_rollback) &&
1415 	    lfp->lf_usecount == 0 &&
1416 	    nfsv4_testlock(&lfp->lf_locallock_lck) == 0)
1417 		nfsrv_freenfslockfile(lfp);
1418 	free(stp, M_NFSDSTATE);
1419 	nfsstatsv1.srvdelegates--;
1420 	nfsrv_openpluslock--;
1421 	nfsrv_delegatecnt--;
1422 }
1423 
1424 /*
1425  * This function frees an open owner and all associated opens.
1426  */
1427 static void
1428 nfsrv_freeopenowner(struct nfsstate *stp, int cansleep, NFSPROC_T *p)
1429 {
1430 	struct nfsstate *nstp, *tstp;
1431 
1432 	LIST_REMOVE(stp, ls_list);
1433 	/*
1434 	 * Now, free all associated opens.
1435 	 */
1436 	nstp = LIST_FIRST(&stp->ls_open);
1437 	while (nstp != LIST_END(&stp->ls_open)) {
1438 		tstp = nstp;
1439 		nstp = LIST_NEXT(nstp, ls_list);
1440 		(void) nfsrv_freeopen(tstp, NULL, cansleep, p);
1441 	}
1442 	if (stp->ls_op)
1443 		nfsrvd_derefcache(stp->ls_op);
1444 	free(stp, M_NFSDSTATE);
1445 	nfsstatsv1.srvopenowners--;
1446 	nfsrv_openpluslock--;
1447 }
1448 
1449 /*
1450  * This function frees an open (nfsstate open structure) with all associated
1451  * lock_owners and locks. It also frees the nfslockfile structure iff there
1452  * are no other opens on the file.
1453  * Returns 1 if it free'd the nfslockfile, 0 otherwise.
1454  */
1455 static int
1456 nfsrv_freeopen(struct nfsstate *stp, vnode_t vp, int cansleep, NFSPROC_T *p)
1457 {
1458 	struct nfsstate *nstp, *tstp;
1459 	struct nfslockfile *lfp;
1460 	int ret;
1461 
1462 	LIST_REMOVE(stp, ls_hash);
1463 	LIST_REMOVE(stp, ls_list);
1464 	LIST_REMOVE(stp, ls_file);
1465 
1466 	lfp = stp->ls_lfp;
1467 	/*
1468 	 * Now, free all lockowners associated with this open.
1469 	 */
1470 	LIST_FOREACH_SAFE(tstp, &stp->ls_open, ls_list, nstp)
1471 		nfsrv_freelockowner(tstp, vp, cansleep, p);
1472 
1473 	/*
1474 	 * The nfslockfile is freed here if there are no locks
1475 	 * associated with the open.
1476 	 * If there are locks associated with the open, the
1477 	 * nfslockfile structure can be freed via nfsrv_freelockowner().
1478 	 * Acquire the state mutex to avoid races with calls to
1479 	 * nfsrv_getlockfile().
1480 	 */
1481 	if (cansleep != 0)
1482 		NFSLOCKSTATE();
1483 	if (lfp != NULL && LIST_EMPTY(&lfp->lf_open) &&
1484 	    LIST_EMPTY(&lfp->lf_deleg) && LIST_EMPTY(&lfp->lf_lock) &&
1485 	    LIST_EMPTY(&lfp->lf_locallock) && LIST_EMPTY(&lfp->lf_rollback) &&
1486 	    lfp->lf_usecount == 0 &&
1487 	    (cansleep != 0 || nfsv4_testlock(&lfp->lf_locallock_lck) == 0)) {
1488 		nfsrv_freenfslockfile(lfp);
1489 		ret = 1;
1490 	} else
1491 		ret = 0;
1492 	if (cansleep != 0)
1493 		NFSUNLOCKSTATE();
1494 	free(stp, M_NFSDSTATE);
1495 	nfsstatsv1.srvopens--;
1496 	nfsrv_openpluslock--;
1497 	return (ret);
1498 }
1499 
1500 /*
1501  * Frees a lockowner and all associated locks.
1502  */
1503 static void
1504 nfsrv_freelockowner(struct nfsstate *stp, vnode_t vp, int cansleep,
1505     NFSPROC_T *p)
1506 {
1507 
1508 	LIST_REMOVE(stp, ls_hash);
1509 	LIST_REMOVE(stp, ls_list);
1510 	nfsrv_freeallnfslocks(stp, vp, cansleep, p);
1511 	if (stp->ls_op)
1512 		nfsrvd_derefcache(stp->ls_op);
1513 	free(stp, M_NFSDSTATE);
1514 	nfsstatsv1.srvlockowners--;
1515 	nfsrv_openpluslock--;
1516 }
1517 
1518 /*
1519  * Free all the nfs locks on a lockowner.
1520  */
1521 static void
1522 nfsrv_freeallnfslocks(struct nfsstate *stp, vnode_t vp, int cansleep,
1523     NFSPROC_T *p)
1524 {
1525 	struct nfslock *lop, *nlop;
1526 	struct nfsrollback *rlp, *nrlp;
1527 	struct nfslockfile *lfp = NULL;
1528 	int gottvp = 0;
1529 	vnode_t tvp = NULL;
1530 	uint64_t first, end;
1531 
1532 	if (vp != NULL)
1533 		ASSERT_VOP_UNLOCKED(vp, "nfsrv_freeallnfslocks: vnode locked");
1534 	lop = LIST_FIRST(&stp->ls_lock);
1535 	while (lop != LIST_END(&stp->ls_lock)) {
1536 		nlop = LIST_NEXT(lop, lo_lckowner);
1537 		/*
1538 		 * Since all locks should be for the same file, lfp should
1539 		 * not change.
1540 		 */
1541 		if (lfp == NULL)
1542 			lfp = lop->lo_lfp;
1543 		else if (lfp != lop->lo_lfp)
1544 			panic("allnfslocks");
1545 		/*
1546 		 * If vp is NULL and cansleep != 0, a vnode must be acquired
1547 		 * from the file handle. This only occurs when called from
1548 		 * nfsrv_cleanclient().
1549 		 */
1550 		if (gottvp == 0) {
1551 			if (nfsrv_dolocallocks == 0)
1552 				tvp = NULL;
1553 			else if (vp == NULL && cansleep != 0) {
1554 				tvp = nfsvno_getvp(&lfp->lf_fh);
1555 				if (tvp != NULL)
1556 					NFSVOPUNLOCK(tvp);
1557 			} else
1558 				tvp = vp;
1559 			gottvp = 1;
1560 		}
1561 
1562 		if (tvp != NULL) {
1563 			if (cansleep == 0)
1564 				panic("allnfs2");
1565 			first = lop->lo_first;
1566 			end = lop->lo_end;
1567 			nfsrv_freenfslock(lop);
1568 			nfsrv_localunlock(tvp, lfp, first, end, p);
1569 			LIST_FOREACH_SAFE(rlp, &lfp->lf_rollback, rlck_list,
1570 			    nrlp)
1571 				free(rlp, M_NFSDROLLBACK);
1572 			LIST_INIT(&lfp->lf_rollback);
1573 		} else
1574 			nfsrv_freenfslock(lop);
1575 		lop = nlop;
1576 	}
1577 	if (vp == NULL && tvp != NULL)
1578 		vrele(tvp);
1579 }
1580 
1581 /*
1582  * Free an nfslock structure.
1583  */
1584 static void
1585 nfsrv_freenfslock(struct nfslock *lop)
1586 {
1587 
1588 	if (lop->lo_lckfile.le_prev != NULL) {
1589 		LIST_REMOVE(lop, lo_lckfile);
1590 		nfsstatsv1.srvlocks--;
1591 		nfsrv_openpluslock--;
1592 	}
1593 	LIST_REMOVE(lop, lo_lckowner);
1594 	free(lop, M_NFSDLOCK);
1595 }
1596 
1597 /*
1598  * This function frees an nfslockfile structure.
1599  */
1600 static void
1601 nfsrv_freenfslockfile(struct nfslockfile *lfp)
1602 {
1603 
1604 	LIST_REMOVE(lfp, lf_hash);
1605 	free(lfp, M_NFSDLOCKFILE);
1606 }
1607 
1608 /*
1609  * This function looks up an nfsstate structure via stateid.
1610  */
1611 static int
1612 nfsrv_getstate(struct nfsclient *clp, nfsv4stateid_t *stateidp, __unused u_int32_t flags,
1613     struct nfsstate **stpp)
1614 {
1615 	struct nfsstate *stp;
1616 	struct nfsstatehead *hp;
1617 	int error = 0;
1618 
1619 	*stpp = NULL;
1620 	hp = NFSSTATEHASH(clp, *stateidp);
1621 	LIST_FOREACH(stp, hp, ls_hash) {
1622 		if (!NFSBCMP(stp->ls_stateid.other, stateidp->other,
1623 			NFSX_STATEIDOTHER))
1624 			break;
1625 	}
1626 
1627 	/*
1628 	 * If no state id in list, return NFSERR_BADSTATEID.
1629 	 */
1630 	if (stp == LIST_END(hp)) {
1631 		error = NFSERR_BADSTATEID;
1632 		goto out;
1633 	}
1634 	*stpp = stp;
1635 
1636 out:
1637 	NFSEXITCODE(error);
1638 	return (error);
1639 }
1640 
1641 /*
1642  * This function gets an nfsstate structure via owner string.
1643  */
1644 static void
1645 nfsrv_getowner(struct nfsstatehead *hp, struct nfsstate *new_stp,
1646     struct nfsstate **stpp)
1647 {
1648 	struct nfsstate *stp;
1649 
1650 	*stpp = NULL;
1651 	LIST_FOREACH(stp, hp, ls_list) {
1652 		if (new_stp->ls_ownerlen == stp->ls_ownerlen &&
1653 		  !NFSBCMP(new_stp->ls_owner,stp->ls_owner,stp->ls_ownerlen)) {
1654 			*stpp = stp;
1655 			return;
1656 		}
1657 	}
1658 }
1659 
1660 /*
1661  * Lock control function called to update lock status.
1662  * Returns 0 upon success, -1 if there is no lock and the flags indicate
1663  * that one isn't to be created and an NFSERR_xxx for other errors.
1664  * The structures new_stp and new_lop are passed in as pointers that should
1665  * be set to NULL if the structure is used and shouldn't be free'd.
1666  * For the NFSLCK_TEST and NFSLCK_CHECK cases, the structures are
1667  * never used and can safely be allocated on the stack. For all other
1668  * cases, *new_stpp and *new_lopp should be malloc'd before the call,
1669  * in case they are used.
1670  */
1671 int
1672 nfsrv_lockctrl(vnode_t vp, struct nfsstate **new_stpp,
1673     struct nfslock **new_lopp, struct nfslockconflict *cfp,
1674     nfsquad_t clientid, nfsv4stateid_t *stateidp,
1675     __unused struct nfsexstuff *exp,
1676     struct nfsrv_descript *nd, NFSPROC_T *p)
1677 {
1678 	struct nfslock *lop;
1679 	struct nfsstate *new_stp = *new_stpp;
1680 	struct nfslock *new_lop = *new_lopp;
1681 	struct nfsstate *tstp, *mystp, *nstp;
1682 	int specialid = 0;
1683 	struct nfslockfile *lfp;
1684 	struct nfslock *other_lop = NULL;
1685 	struct nfsstate *stp, *lckstp = NULL;
1686 	struct nfsclient *clp = NULL;
1687 	u_int32_t bits;
1688 	int error = 0, haslock = 0, ret, reterr;
1689 	int getlckret, delegation = 0, filestruct_locked, vnode_unlocked = 0;
1690 	fhandle_t nfh;
1691 	uint64_t first, end;
1692 	uint32_t lock_flags;
1693 
1694 	if (new_stp->ls_flags & (NFSLCK_CHECK | NFSLCK_SETATTR)) {
1695 		/*
1696 		 * Note the special cases of "all 1s" or "all 0s" stateids and
1697 		 * let reads with all 1s go ahead.
1698 		 */
1699 		if (new_stp->ls_stateid.seqid == 0x0 &&
1700 		    new_stp->ls_stateid.other[0] == 0x0 &&
1701 		    new_stp->ls_stateid.other[1] == 0x0 &&
1702 		    new_stp->ls_stateid.other[2] == 0x0)
1703 			specialid = 1;
1704 		else if (new_stp->ls_stateid.seqid == 0xffffffff &&
1705 		    new_stp->ls_stateid.other[0] == 0xffffffff &&
1706 		    new_stp->ls_stateid.other[1] == 0xffffffff &&
1707 		    new_stp->ls_stateid.other[2] == 0xffffffff)
1708 			specialid = 2;
1709 	}
1710 
1711 	/*
1712 	 * Check for restart conditions (client and server).
1713 	 */
1714 	error = nfsrv_checkrestart(clientid, new_stp->ls_flags,
1715 	    &new_stp->ls_stateid, specialid);
1716 	if (error)
1717 		goto out;
1718 
1719 	/*
1720 	 * Check for state resource limit exceeded.
1721 	 */
1722 	if ((new_stp->ls_flags & NFSLCK_LOCK) &&
1723 	    nfsrv_openpluslock > nfsrv_v4statelimit) {
1724 		error = NFSERR_RESOURCE;
1725 		goto out;
1726 	}
1727 
1728 	/*
1729 	 * For the lock case, get another nfslock structure,
1730 	 * just in case we need it.
1731 	 * Malloc now, before we start sifting through the linked lists,
1732 	 * in case we have to wait for memory.
1733 	 */
1734 tryagain:
1735 	if (new_stp->ls_flags & NFSLCK_LOCK)
1736 		other_lop = malloc(sizeof (struct nfslock),
1737 		    M_NFSDLOCK, M_WAITOK);
1738 	filestruct_locked = 0;
1739 	reterr = 0;
1740 	lfp = NULL;
1741 
1742 	/*
1743 	 * Get the lockfile structure for CFH now, so we can do a sanity
1744 	 * check against the stateid, before incrementing the seqid#, since
1745 	 * we want to return NFSERR_BADSTATEID on failure and the seqid#
1746 	 * shouldn't be incremented for this case.
1747 	 * If nfsrv_getlockfile() returns -1, it means "not found", which
1748 	 * will be handled later.
1749 	 * If we are doing Lock/LockU and local locking is enabled, sleep
1750 	 * lock the nfslockfile structure.
1751 	 */
1752 	getlckret = nfsrv_getlockfh(vp, new_stp->ls_flags, NULL, &nfh, p);
1753 	NFSLOCKSTATE();
1754 	if (getlckret == 0) {
1755 		if ((new_stp->ls_flags & (NFSLCK_LOCK | NFSLCK_UNLOCK)) != 0 &&
1756 		    nfsrv_dolocallocks != 0 && nd->nd_repstat == 0) {
1757 			getlckret = nfsrv_getlockfile(new_stp->ls_flags, NULL,
1758 			    &lfp, &nfh, 1);
1759 			if (getlckret == 0)
1760 				filestruct_locked = 1;
1761 		} else
1762 			getlckret = nfsrv_getlockfile(new_stp->ls_flags, NULL,
1763 			    &lfp, &nfh, 0);
1764 	}
1765 	if (getlckret != 0 && getlckret != -1)
1766 		reterr = getlckret;
1767 
1768 	if (filestruct_locked != 0) {
1769 		LIST_INIT(&lfp->lf_rollback);
1770 		if ((new_stp->ls_flags & NFSLCK_LOCK)) {
1771 			/*
1772 			 * For local locking, do the advisory locking now, so
1773 			 * that any conflict can be detected. A failure later
1774 			 * can be rolled back locally. If an error is returned,
1775 			 * struct nfslockfile has been unlocked and any local
1776 			 * locking rolled back.
1777 			 */
1778 			NFSUNLOCKSTATE();
1779 			if (vnode_unlocked == 0) {
1780 				ASSERT_VOP_ELOCKED(vp, "nfsrv_lockctrl1");
1781 				vnode_unlocked = 1;
1782 				NFSVOPUNLOCK(vp);
1783 			}
1784 			reterr = nfsrv_locallock(vp, lfp,
1785 			    (new_lop->lo_flags & (NFSLCK_READ | NFSLCK_WRITE)),
1786 			    new_lop->lo_first, new_lop->lo_end, cfp, p);
1787 			NFSLOCKSTATE();
1788 		}
1789 	}
1790 
1791 	if (specialid == 0) {
1792 	    if (new_stp->ls_flags & NFSLCK_TEST) {
1793 		/*
1794 		 * RFC 3530 does not list LockT as an op that renews a
1795 		 * lease, but the consensus seems to be that it is ok
1796 		 * for a server to do so.
1797 		 */
1798 		error = nfsrv_getclient(clientid, CLOPS_RENEW, &clp, NULL,
1799 		    (nfsquad_t)((u_quad_t)0), 0, nd, p);
1800 
1801 		/*
1802 		 * Since NFSERR_EXPIRED, NFSERR_ADMINREVOKED are not valid
1803 		 * error returns for LockT, just go ahead and test for a lock,
1804 		 * since there are no locks for this client, but other locks
1805 		 * can conflict. (ie. same client will always be false)
1806 		 */
1807 		if (error == NFSERR_EXPIRED || error == NFSERR_ADMINREVOKED)
1808 		    error = 0;
1809 		lckstp = new_stp;
1810 	    } else {
1811 	      error = nfsrv_getclient(clientid, CLOPS_RENEW, &clp, NULL,
1812 		(nfsquad_t)((u_quad_t)0), 0, nd, p);
1813 	      if (error == 0)
1814 		/*
1815 		 * Look up the stateid
1816 		 */
1817 		error = nfsrv_getstate(clp, &new_stp->ls_stateid,
1818 		  new_stp->ls_flags, &stp);
1819 	      /*
1820 	       * do some sanity checks for an unconfirmed open or a
1821 	       * stateid that refers to the wrong file, for an open stateid
1822 	       */
1823 	      if (error == 0 && (stp->ls_flags & NFSLCK_OPEN) &&
1824 		  ((stp->ls_openowner->ls_flags & NFSLCK_NEEDSCONFIRM) ||
1825 		   (getlckret == 0 && stp->ls_lfp != lfp))){
1826 		      /*
1827 		       * NFSLCK_SETATTR should return OK rather than NFSERR_BADSTATEID
1828 		       * The only exception is using SETATTR with SIZE.
1829 		       * */
1830                     if ((new_stp->ls_flags &
1831                          (NFSLCK_SETATTR | NFSLCK_CHECK)) != NFSLCK_SETATTR)
1832 			     error = NFSERR_BADSTATEID;
1833 	      }
1834 
1835 		if (error == 0 &&
1836 		  (stp->ls_flags & (NFSLCK_DELEGREAD | NFSLCK_DELEGWRITE)) &&
1837 		  getlckret == 0 && stp->ls_lfp != lfp)
1838 			error = NFSERR_BADSTATEID;
1839 
1840 	      /*
1841 	       * If the lockowner stateid doesn't refer to the same file,
1842 	       * I believe that is considered ok, since some clients will
1843 	       * only create a single lockowner and use that for all locks
1844 	       * on all files.
1845 	       * For now, log it as a diagnostic, instead of considering it
1846 	       * a BadStateid.
1847 	       */
1848 	      if (error == 0 && (stp->ls_flags &
1849 		  (NFSLCK_OPEN | NFSLCK_DELEGREAD | NFSLCK_DELEGWRITE)) == 0 &&
1850 		  getlckret == 0 && stp->ls_lfp != lfp) {
1851 #ifdef DIAGNOSTIC
1852 		  printf("Got a lock statid for different file open\n");
1853 #endif
1854 		  /*
1855 		  error = NFSERR_BADSTATEID;
1856 		  */
1857 	      }
1858 
1859 	      if (error == 0) {
1860 		    if (new_stp->ls_flags & NFSLCK_OPENTOLOCK) {
1861 			/*
1862 			 * If haslock set, we've already checked the seqid.
1863 			 */
1864 			if (!haslock) {
1865 			    if (stp->ls_flags & NFSLCK_OPEN)
1866 				error = nfsrv_checkseqid(nd, new_stp->ls_seq,
1867 				    stp->ls_openowner, new_stp->ls_op);
1868 			    else
1869 				error = NFSERR_BADSTATEID;
1870 			}
1871 			if (!error)
1872 			    nfsrv_getowner(&stp->ls_open, new_stp, &lckstp);
1873 			if (lckstp)
1874 			    /*
1875 			     * I believe this should be an error, but it
1876 			     * isn't obvious what NFSERR_xxx would be
1877 			     * appropriate, so I'll use NFSERR_INVAL for now.
1878 			     */
1879 			    error = NFSERR_INVAL;
1880 			else
1881 			    lckstp = new_stp;
1882 		    } else if (new_stp->ls_flags&(NFSLCK_LOCK|NFSLCK_UNLOCK)) {
1883 			/*
1884 			 * If haslock set, ditto above.
1885 			 */
1886 			if (!haslock) {
1887 			    if (stp->ls_flags & NFSLCK_OPEN)
1888 				error = NFSERR_BADSTATEID;
1889 			    else
1890 				error = nfsrv_checkseqid(nd, new_stp->ls_seq,
1891 				    stp, new_stp->ls_op);
1892 			}
1893 			lckstp = stp;
1894 		    } else {
1895 			lckstp = stp;
1896 		    }
1897 	      }
1898 	      /*
1899 	       * If the seqid part of the stateid isn't the same, return
1900 	       * NFSERR_OLDSTATEID for cases other than I/O Ops.
1901 	       * For I/O Ops, only return NFSERR_OLDSTATEID if
1902 	       * nfsrv_returnoldstateid is set. (The consensus on the email
1903 	       * list was that most clients would prefer to not receive
1904 	       * NFSERR_OLDSTATEID for I/O Ops, but the RFC suggests that that
1905 	       * is what will happen, so I use the nfsrv_returnoldstateid to
1906 	       * allow for either server configuration.)
1907 	       */
1908 	      if (!error && stp->ls_stateid.seqid!=new_stp->ls_stateid.seqid &&
1909 		  (((nd->nd_flag & ND_NFSV41) == 0 &&
1910 		   (!(new_stp->ls_flags & NFSLCK_CHECK) ||
1911 		    nfsrv_returnoldstateid)) ||
1912 		   ((nd->nd_flag & ND_NFSV41) != 0 &&
1913 		    new_stp->ls_stateid.seqid != 0)))
1914 		    error = NFSERR_OLDSTATEID;
1915 	    }
1916 	}
1917 
1918 	/*
1919 	 * Now we can check for grace.
1920 	 */
1921 	if (!error)
1922 		error = nfsrv_checkgrace(nd, clp, new_stp->ls_flags);
1923 	if ((new_stp->ls_flags & NFSLCK_RECLAIM) && !error &&
1924 		nfsrv_checkstable(clp))
1925 		error = NFSERR_NOGRACE;
1926 	/*
1927 	 * If we successfully Reclaimed state, note that.
1928 	 */
1929 	if ((new_stp->ls_flags & NFSLCK_RECLAIM) && !error)
1930 		nfsrv_markstable(clp);
1931 
1932 	/*
1933 	 * At this point, either error == NFSERR_BADSTATEID or the
1934 	 * seqid# has been updated, so we can return any error.
1935 	 * If error == 0, there may be an error in:
1936 	 *    nd_repstat - Set by the calling function.
1937 	 *    reterr - Set above, if getting the nfslockfile structure
1938 	 *       or acquiring the local lock failed.
1939 	 *    (If both of these are set, nd_repstat should probably be
1940 	 *     returned, since that error was detected before this
1941 	 *     function call.)
1942 	 */
1943 	if (error != 0 || nd->nd_repstat != 0 || reterr != 0) {
1944 		if (error == 0) {
1945 			if (nd->nd_repstat != 0)
1946 				error = nd->nd_repstat;
1947 			else
1948 				error = reterr;
1949 		}
1950 		if (filestruct_locked != 0) {
1951 			/* Roll back local locks. */
1952 			NFSUNLOCKSTATE();
1953 			if (vnode_unlocked == 0) {
1954 				ASSERT_VOP_ELOCKED(vp, "nfsrv_lockctrl2");
1955 				vnode_unlocked = 1;
1956 				NFSVOPUNLOCK(vp);
1957 			}
1958 			nfsrv_locallock_rollback(vp, lfp, p);
1959 			NFSLOCKSTATE();
1960 			nfsrv_unlocklf(lfp);
1961 		}
1962 		NFSUNLOCKSTATE();
1963 		goto out;
1964 	}
1965 
1966 	/*
1967 	 * Check the nfsrv_getlockfile return.
1968 	 * Returned -1 if no structure found.
1969 	 */
1970 	if (getlckret == -1) {
1971 		error = NFSERR_EXPIRED;
1972 		/*
1973 		 * Called from lockt, so no lock is OK.
1974 		 */
1975 		if (new_stp->ls_flags & NFSLCK_TEST) {
1976 			error = 0;
1977 		} else if (new_stp->ls_flags &
1978 		    (NFSLCK_CHECK | NFSLCK_SETATTR)) {
1979 			/*
1980 			 * Called to check for a lock, OK if the stateid is all
1981 			 * 1s or all 0s, but there should be an nfsstate
1982 			 * otherwise.
1983 			 * (ie. If there is no open, I'll assume no share
1984 			 *  deny bits.)
1985 			 */
1986 			if (specialid)
1987 				error = 0;
1988 			else
1989 				error = NFSERR_BADSTATEID;
1990 		}
1991 		NFSUNLOCKSTATE();
1992 		goto out;
1993 	}
1994 
1995 	/*
1996 	 * For NFSLCK_CHECK and NFSLCK_LOCK, test for a share conflict.
1997 	 * For NFSLCK_CHECK, allow a read if write access is granted,
1998 	 * but check for a deny. For NFSLCK_LOCK, require correct access,
1999 	 * which implies a conflicting deny can't exist.
2000 	 */
2001 	if (new_stp->ls_flags & (NFSLCK_CHECK | NFSLCK_LOCK)) {
2002 	    /*
2003 	     * Four kinds of state id:
2004 	     * - specialid (all 0s or all 1s), only for NFSLCK_CHECK
2005 	     * - stateid for an open
2006 	     * - stateid for a delegation
2007 	     * - stateid for a lock owner
2008 	     */
2009 	    if (!specialid) {
2010 		if (stp->ls_flags & (NFSLCK_DELEGREAD | NFSLCK_DELEGWRITE)) {
2011 		    delegation = 1;
2012 		    mystp = stp;
2013 		    nfsrv_delaydelegtimeout(stp);
2014 	        } else if (stp->ls_flags & NFSLCK_OPEN) {
2015 		    mystp = stp;
2016 		} else {
2017 		    mystp = stp->ls_openstp;
2018 		}
2019 		/*
2020 		 * If locking or checking, require correct access
2021 		 * bit set.
2022 		 */
2023 		if (((new_stp->ls_flags & NFSLCK_LOCK) &&
2024 		     !((new_lop->lo_flags >> NFSLCK_LOCKSHIFT) &
2025 		       mystp->ls_flags & NFSLCK_ACCESSBITS)) ||
2026 		    ((new_stp->ls_flags & (NFSLCK_CHECK|NFSLCK_READACCESS)) ==
2027 		      (NFSLCK_CHECK | NFSLCK_READACCESS) &&
2028 		     !(mystp->ls_flags & NFSLCK_READACCESS) &&
2029 		     nfsrv_allowreadforwriteopen == 0) ||
2030 		    ((new_stp->ls_flags & (NFSLCK_CHECK|NFSLCK_WRITEACCESS)) ==
2031 		      (NFSLCK_CHECK | NFSLCK_WRITEACCESS) &&
2032 		     !(mystp->ls_flags & NFSLCK_WRITEACCESS))) {
2033 			if (filestruct_locked != 0) {
2034 				/* Roll back local locks. */
2035 				NFSUNLOCKSTATE();
2036 				if (vnode_unlocked == 0) {
2037 					ASSERT_VOP_ELOCKED(vp,
2038 					    "nfsrv_lockctrl3");
2039 					vnode_unlocked = 1;
2040 					NFSVOPUNLOCK(vp);
2041 				}
2042 				nfsrv_locallock_rollback(vp, lfp, p);
2043 				NFSLOCKSTATE();
2044 				nfsrv_unlocklf(lfp);
2045 			}
2046 			NFSUNLOCKSTATE();
2047 			error = NFSERR_OPENMODE;
2048 			goto out;
2049 		}
2050 	    } else
2051 		mystp = NULL;
2052 	    if ((new_stp->ls_flags & NFSLCK_CHECK) && !delegation) {
2053 		/*
2054 		 * Check for a conflicting deny bit.
2055 		 */
2056 		LIST_FOREACH(tstp, &lfp->lf_open, ls_file) {
2057 		    if (tstp != mystp) {
2058 			bits = tstp->ls_flags;
2059 			bits >>= NFSLCK_SHIFT;
2060 			if (new_stp->ls_flags & bits & NFSLCK_ACCESSBITS) {
2061 			    KASSERT(vnode_unlocked == 0,
2062 				("nfsrv_lockctrl: vnode unlocked1"));
2063 			    ret = nfsrv_clientconflict(tstp->ls_clp, &haslock,
2064 				vp, p);
2065 			    if (ret == 1) {
2066 				/*
2067 				* nfsrv_clientconflict unlocks state
2068 				 * when it returns non-zero.
2069 				 */
2070 				lckstp = NULL;
2071 				goto tryagain;
2072 			    }
2073 			    if (ret == 0)
2074 				NFSUNLOCKSTATE();
2075 			    if (ret == 2)
2076 				error = NFSERR_PERM;
2077 			    else
2078 				error = NFSERR_OPENMODE;
2079 			    goto out;
2080 			}
2081 		    }
2082 		}
2083 
2084 		/* We're outta here */
2085 		NFSUNLOCKSTATE();
2086 		goto out;
2087 	    }
2088 	}
2089 
2090 	/*
2091 	 * For setattr, just get rid of all the Delegations for other clients.
2092 	 */
2093 	if (new_stp->ls_flags & NFSLCK_SETATTR) {
2094 		KASSERT(vnode_unlocked == 0,
2095 		    ("nfsrv_lockctrl: vnode unlocked2"));
2096 		ret = nfsrv_cleandeleg(vp, lfp, clp, &haslock, p);
2097 		if (ret) {
2098 			/*
2099 			 * nfsrv_cleandeleg() unlocks state when it
2100 			 * returns non-zero.
2101 			 */
2102 			if (ret == -1) {
2103 				lckstp = NULL;
2104 				goto tryagain;
2105 			}
2106 			error = ret;
2107 			goto out;
2108 		}
2109 		if (!(new_stp->ls_flags & NFSLCK_CHECK) ||
2110 		    (LIST_EMPTY(&lfp->lf_open) && LIST_EMPTY(&lfp->lf_lock) &&
2111 		     LIST_EMPTY(&lfp->lf_deleg))) {
2112 			NFSUNLOCKSTATE();
2113 			goto out;
2114 		}
2115 	}
2116 
2117 	/*
2118 	 * Check for a conflicting delegation. If one is found, call
2119 	 * nfsrv_delegconflict() to handle it. If the v4root lock hasn't
2120 	 * been set yet, it will get the lock. Otherwise, it will recall
2121 	 * the delegation. Then, we try try again...
2122 	 * I currently believe the conflict algorithm to be:
2123 	 * For Lock Ops (Lock/LockT/LockU)
2124 	 * - there is a conflict iff a different client has a write delegation
2125 	 * For Reading (Read Op)
2126 	 * - there is a conflict iff a different client has a write delegation
2127 	 *   (the specialids are always a different client)
2128 	 * For Writing (Write/Setattr of size)
2129 	 * - there is a conflict if a different client has any delegation
2130 	 * - there is a conflict if the same client has a read delegation
2131 	 *   (I don't understand why this isn't allowed, but that seems to be
2132 	 *    the current consensus?)
2133 	 */
2134 	tstp = LIST_FIRST(&lfp->lf_deleg);
2135 	while (tstp != LIST_END(&lfp->lf_deleg)) {
2136 	    nstp = LIST_NEXT(tstp, ls_file);
2137 	    if ((((new_stp->ls_flags&(NFSLCK_LOCK|NFSLCK_UNLOCK|NFSLCK_TEST))||
2138 		 ((new_stp->ls_flags & NFSLCK_CHECK) &&
2139 		  (new_lop->lo_flags & NFSLCK_READ))) &&
2140 		  clp != tstp->ls_clp &&
2141 		 (tstp->ls_flags & NFSLCK_DELEGWRITE)) ||
2142 		 ((new_stp->ls_flags & NFSLCK_CHECK) &&
2143 		   (new_lop->lo_flags & NFSLCK_WRITE) &&
2144 		  (clp != tstp->ls_clp ||
2145 		   (tstp->ls_flags & NFSLCK_DELEGREAD)))) {
2146 		ret = 0;
2147 		if (filestruct_locked != 0) {
2148 			/* Roll back local locks. */
2149 			NFSUNLOCKSTATE();
2150 			if (vnode_unlocked == 0) {
2151 				ASSERT_VOP_ELOCKED(vp, "nfsrv_lockctrl4");
2152 				NFSVOPUNLOCK(vp);
2153 			}
2154 			nfsrv_locallock_rollback(vp, lfp, p);
2155 			NFSLOCKSTATE();
2156 			nfsrv_unlocklf(lfp);
2157 			NFSUNLOCKSTATE();
2158 			NFSVOPLOCK(vp, LK_EXCLUSIVE | LK_RETRY);
2159 			vnode_unlocked = 0;
2160 			if (VN_IS_DOOMED(vp))
2161 				ret = NFSERR_SERVERFAULT;
2162 			NFSLOCKSTATE();
2163 		}
2164 		if (ret == 0)
2165 			ret = nfsrv_delegconflict(tstp, &haslock, p, vp);
2166 		if (ret) {
2167 		    /*
2168 		     * nfsrv_delegconflict unlocks state when it
2169 		     * returns non-zero, which it always does.
2170 		     */
2171 		    if (other_lop) {
2172 			free(other_lop, M_NFSDLOCK);
2173 			other_lop = NULL;
2174 		    }
2175 		    if (ret == -1) {
2176 			lckstp = NULL;
2177 			goto tryagain;
2178 		    }
2179 		    error = ret;
2180 		    goto out;
2181 		}
2182 		/* Never gets here. */
2183 	    }
2184 	    tstp = nstp;
2185 	}
2186 
2187 	/*
2188 	 * Handle the unlock case by calling nfsrv_updatelock().
2189 	 * (Should I have done some access checking above for unlock? For now,
2190 	 *  just let it happen.)
2191 	 */
2192 	if (new_stp->ls_flags & NFSLCK_UNLOCK) {
2193 		first = new_lop->lo_first;
2194 		end = new_lop->lo_end;
2195 		nfsrv_updatelock(stp, new_lopp, &other_lop, lfp);
2196 		stateidp->seqid = ++(stp->ls_stateid.seqid);
2197 		if ((nd->nd_flag & ND_NFSV41) != 0 && stateidp->seqid == 0)
2198 			stateidp->seqid = stp->ls_stateid.seqid = 1;
2199 		stateidp->other[0] = stp->ls_stateid.other[0];
2200 		stateidp->other[1] = stp->ls_stateid.other[1];
2201 		stateidp->other[2] = stp->ls_stateid.other[2];
2202 		if (filestruct_locked != 0) {
2203 			NFSUNLOCKSTATE();
2204 			if (vnode_unlocked == 0) {
2205 				ASSERT_VOP_ELOCKED(vp, "nfsrv_lockctrl5");
2206 				vnode_unlocked = 1;
2207 				NFSVOPUNLOCK(vp);
2208 			}
2209 			/* Update the local locks. */
2210 			nfsrv_localunlock(vp, lfp, first, end, p);
2211 			NFSLOCKSTATE();
2212 			nfsrv_unlocklf(lfp);
2213 		}
2214 		NFSUNLOCKSTATE();
2215 		goto out;
2216 	}
2217 
2218 	/*
2219 	 * Search for a conflicting lock. A lock conflicts if:
2220 	 * - the lock range overlaps and
2221 	 * - at least one lock is a write lock and
2222 	 * - it is not owned by the same lock owner
2223 	 */
2224 	if (!delegation) {
2225 	  LIST_FOREACH(lop, &lfp->lf_lock, lo_lckfile) {
2226 	    if (new_lop->lo_end > lop->lo_first &&
2227 		new_lop->lo_first < lop->lo_end &&
2228 		(new_lop->lo_flags == NFSLCK_WRITE ||
2229 		 lop->lo_flags == NFSLCK_WRITE) &&
2230 		lckstp != lop->lo_stp &&
2231 		(clp != lop->lo_stp->ls_clp ||
2232 		 lckstp->ls_ownerlen != lop->lo_stp->ls_ownerlen ||
2233 		 NFSBCMP(lckstp->ls_owner, lop->lo_stp->ls_owner,
2234 		    lckstp->ls_ownerlen))) {
2235 		if (other_lop) {
2236 		    free(other_lop, M_NFSDLOCK);
2237 		    other_lop = NULL;
2238 		}
2239 		if (vnode_unlocked != 0)
2240 		    ret = nfsrv_clientconflict(lop->lo_stp->ls_clp, &haslock,
2241 			NULL, p);
2242 		else
2243 		    ret = nfsrv_clientconflict(lop->lo_stp->ls_clp, &haslock,
2244 			vp, p);
2245 		if (ret == 1) {
2246 		    if (filestruct_locked != 0) {
2247 			if (vnode_unlocked == 0) {
2248 				ASSERT_VOP_ELOCKED(vp, "nfsrv_lockctrl6");
2249 				NFSVOPUNLOCK(vp);
2250 			}
2251 			/* Roll back local locks. */
2252 			nfsrv_locallock_rollback(vp, lfp, p);
2253 			NFSLOCKSTATE();
2254 			nfsrv_unlocklf(lfp);
2255 			NFSUNLOCKSTATE();
2256 			NFSVOPLOCK(vp, LK_EXCLUSIVE | LK_RETRY);
2257 			vnode_unlocked = 0;
2258 			if (VN_IS_DOOMED(vp)) {
2259 				error = NFSERR_SERVERFAULT;
2260 				goto out;
2261 			}
2262 		    }
2263 		    /*
2264 		     * nfsrv_clientconflict() unlocks state when it
2265 		     * returns non-zero.
2266 		     */
2267 		    lckstp = NULL;
2268 		    goto tryagain;
2269 		}
2270 		/*
2271 		 * Found a conflicting lock, so record the conflict and
2272 		 * return the error.
2273 		 */
2274 		if (cfp != NULL && ret == 0) {
2275 		    cfp->cl_clientid.lval[0]=lop->lo_stp->ls_stateid.other[0];
2276 		    cfp->cl_clientid.lval[1]=lop->lo_stp->ls_stateid.other[1];
2277 		    cfp->cl_first = lop->lo_first;
2278 		    cfp->cl_end = lop->lo_end;
2279 		    cfp->cl_flags = lop->lo_flags;
2280 		    cfp->cl_ownerlen = lop->lo_stp->ls_ownerlen;
2281 		    NFSBCOPY(lop->lo_stp->ls_owner, cfp->cl_owner,
2282 			cfp->cl_ownerlen);
2283 		}
2284 		if (ret == 2)
2285 		    error = NFSERR_PERM;
2286 		else if (new_stp->ls_flags & NFSLCK_RECLAIM)
2287 		    error = NFSERR_RECLAIMCONFLICT;
2288 		else if (new_stp->ls_flags & NFSLCK_CHECK)
2289 		    error = NFSERR_LOCKED;
2290 		else
2291 		    error = NFSERR_DENIED;
2292 		if (filestruct_locked != 0 && ret == 0) {
2293 			/* Roll back local locks. */
2294 			NFSUNLOCKSTATE();
2295 			if (vnode_unlocked == 0) {
2296 				ASSERT_VOP_ELOCKED(vp, "nfsrv_lockctrl7");
2297 				vnode_unlocked = 1;
2298 				NFSVOPUNLOCK(vp);
2299 			}
2300 			nfsrv_locallock_rollback(vp, lfp, p);
2301 			NFSLOCKSTATE();
2302 			nfsrv_unlocklf(lfp);
2303 		}
2304 		if (ret == 0)
2305 			NFSUNLOCKSTATE();
2306 		goto out;
2307 	    }
2308 	  }
2309 	}
2310 
2311 	/*
2312 	 * We only get here if there was no lock that conflicted.
2313 	 */
2314 	if (new_stp->ls_flags & (NFSLCK_TEST | NFSLCK_CHECK)) {
2315 		NFSUNLOCKSTATE();
2316 		goto out;
2317 	}
2318 
2319 	/*
2320 	 * We only get here when we are creating or modifying a lock.
2321 	 * There are two variants:
2322 	 * - exist_lock_owner where lock_owner exists
2323 	 * - open_to_lock_owner with new lock_owner
2324 	 */
2325 	first = new_lop->lo_first;
2326 	end = new_lop->lo_end;
2327 	lock_flags = new_lop->lo_flags;
2328 	if (!(new_stp->ls_flags & NFSLCK_OPENTOLOCK)) {
2329 		nfsrv_updatelock(lckstp, new_lopp, &other_lop, lfp);
2330 		stateidp->seqid = ++(lckstp->ls_stateid.seqid);
2331 		if ((nd->nd_flag & ND_NFSV41) != 0 && stateidp->seqid == 0)
2332 			stateidp->seqid = lckstp->ls_stateid.seqid = 1;
2333 		stateidp->other[0] = lckstp->ls_stateid.other[0];
2334 		stateidp->other[1] = lckstp->ls_stateid.other[1];
2335 		stateidp->other[2] = lckstp->ls_stateid.other[2];
2336 	} else {
2337 		/*
2338 		 * The new open_to_lock_owner case.
2339 		 * Link the new nfsstate into the lists.
2340 		 */
2341 		new_stp->ls_seq = new_stp->ls_opentolockseq;
2342 		nfsrvd_refcache(new_stp->ls_op);
2343 		stateidp->seqid = new_stp->ls_stateid.seqid = 1;
2344 		stateidp->other[0] = new_stp->ls_stateid.other[0] =
2345 		    clp->lc_clientid.lval[0];
2346 		stateidp->other[1] = new_stp->ls_stateid.other[1] =
2347 		    clp->lc_clientid.lval[1];
2348 		stateidp->other[2] = new_stp->ls_stateid.other[2] =
2349 		    nfsrv_nextstateindex(clp);
2350 		new_stp->ls_clp = clp;
2351 		LIST_INIT(&new_stp->ls_lock);
2352 		new_stp->ls_openstp = stp;
2353 		new_stp->ls_lfp = lfp;
2354 		nfsrv_insertlock(new_lop, (struct nfslock *)new_stp, new_stp,
2355 		    lfp);
2356 		LIST_INSERT_HEAD(NFSSTATEHASH(clp, new_stp->ls_stateid),
2357 		    new_stp, ls_hash);
2358 		LIST_INSERT_HEAD(&stp->ls_open, new_stp, ls_list);
2359 		*new_lopp = NULL;
2360 		*new_stpp = NULL;
2361 		nfsstatsv1.srvlockowners++;
2362 		nfsrv_openpluslock++;
2363 	}
2364 	if (filestruct_locked != 0) {
2365 		NFSUNLOCKSTATE();
2366 		nfsrv_locallock_commit(lfp, lock_flags, first, end);
2367 		NFSLOCKSTATE();
2368 		nfsrv_unlocklf(lfp);
2369 	}
2370 	NFSUNLOCKSTATE();
2371 
2372 out:
2373 	if (haslock) {
2374 		NFSLOCKV4ROOTMUTEX();
2375 		nfsv4_unlock(&nfsv4rootfs_lock, 1);
2376 		NFSUNLOCKV4ROOTMUTEX();
2377 	}
2378 	if (vnode_unlocked != 0) {
2379 		NFSVOPLOCK(vp, LK_EXCLUSIVE | LK_RETRY);
2380 		if (error == 0 && VN_IS_DOOMED(vp))
2381 			error = NFSERR_SERVERFAULT;
2382 	}
2383 	if (other_lop)
2384 		free(other_lop, M_NFSDLOCK);
2385 	NFSEXITCODE2(error, nd);
2386 	return (error);
2387 }
2388 
2389 /*
2390  * Check for state errors for Open.
2391  * repstat is passed back out as an error if more critical errors
2392  * are not detected.
2393  */
2394 int
2395 nfsrv_opencheck(nfsquad_t clientid, nfsv4stateid_t *stateidp,
2396     struct nfsstate *new_stp, vnode_t vp, struct nfsrv_descript *nd,
2397     NFSPROC_T *p, int repstat)
2398 {
2399 	struct nfsstate *stp, *nstp;
2400 	struct nfsclient *clp;
2401 	struct nfsstate *ownerstp;
2402 	struct nfslockfile *lfp, *new_lfp;
2403 	int error = 0, haslock = 0, ret, readonly = 0, getfhret = 0;
2404 
2405 	if ((new_stp->ls_flags & NFSLCK_SHAREBITS) == NFSLCK_READACCESS)
2406 		readonly = 1;
2407 	/*
2408 	 * Check for restart conditions (client and server).
2409 	 */
2410 	error = nfsrv_checkrestart(clientid, new_stp->ls_flags,
2411 		&new_stp->ls_stateid, 0);
2412 	if (error)
2413 		goto out;
2414 
2415 	/*
2416 	 * Check for state resource limit exceeded.
2417 	 * Technically this should be SMP protected, but the worst
2418 	 * case error is "out by one or two" on the count when it
2419 	 * returns NFSERR_RESOURCE and the limit is just a rather
2420 	 * arbitrary high water mark, so no harm is done.
2421 	 */
2422 	if (nfsrv_openpluslock > nfsrv_v4statelimit) {
2423 		error = NFSERR_RESOURCE;
2424 		goto out;
2425 	}
2426 
2427 tryagain:
2428 	new_lfp = malloc(sizeof (struct nfslockfile),
2429 	    M_NFSDLOCKFILE, M_WAITOK);
2430 	if (vp)
2431 		getfhret = nfsrv_getlockfh(vp, new_stp->ls_flags, new_lfp,
2432 		    NULL, p);
2433 	NFSLOCKSTATE();
2434 	/*
2435 	 * Get the nfsclient structure.
2436 	 */
2437 	error = nfsrv_getclient(clientid, CLOPS_RENEW, &clp, NULL,
2438 	    (nfsquad_t)((u_quad_t)0), 0, nd, p);
2439 
2440 	/*
2441 	 * Look up the open owner. See if it needs confirmation and
2442 	 * check the seq#, as required.
2443 	 */
2444 	if (!error)
2445 		nfsrv_getowner(&clp->lc_open, new_stp, &ownerstp);
2446 
2447 	if (!error && ownerstp) {
2448 		error = nfsrv_checkseqid(nd, new_stp->ls_seq, ownerstp,
2449 		    new_stp->ls_op);
2450 		/*
2451 		 * If the OpenOwner hasn't been confirmed, assume the
2452 		 * old one was a replay and this one is ok.
2453 		 * See: RFC3530 Sec. 14.2.18.
2454 		 */
2455 		if (error == NFSERR_BADSEQID &&
2456 		    (ownerstp->ls_flags & NFSLCK_NEEDSCONFIRM))
2457 			error = 0;
2458 	}
2459 
2460 	/*
2461 	 * Check for grace.
2462 	 */
2463 	if (!error)
2464 		error = nfsrv_checkgrace(nd, clp, new_stp->ls_flags);
2465 	if ((new_stp->ls_flags & NFSLCK_RECLAIM) && !error &&
2466 		nfsrv_checkstable(clp))
2467 		error = NFSERR_NOGRACE;
2468 
2469 	/*
2470 	 * If none of the above errors occurred, let repstat be
2471 	 * returned.
2472 	 */
2473 	if (repstat && !error)
2474 		error = repstat;
2475 	if (error) {
2476 		NFSUNLOCKSTATE();
2477 		if (haslock) {
2478 			NFSLOCKV4ROOTMUTEX();
2479 			nfsv4_unlock(&nfsv4rootfs_lock, 1);
2480 			NFSUNLOCKV4ROOTMUTEX();
2481 		}
2482 		free(new_lfp, M_NFSDLOCKFILE);
2483 		goto out;
2484 	}
2485 
2486 	/*
2487 	 * If vp == NULL, the file doesn't exist yet, so return ok.
2488 	 * (This always happens on the first pass, so haslock must be 0.)
2489 	 */
2490 	if (vp == NULL) {
2491 		NFSUNLOCKSTATE();
2492 		free(new_lfp, M_NFSDLOCKFILE);
2493 		goto out;
2494 	}
2495 
2496 	/*
2497 	 * Get the structure for the underlying file.
2498 	 */
2499 	if (getfhret)
2500 		error = getfhret;
2501 	else
2502 		error = nfsrv_getlockfile(new_stp->ls_flags, &new_lfp, &lfp,
2503 		    NULL, 0);
2504 	if (new_lfp)
2505 		free(new_lfp, M_NFSDLOCKFILE);
2506 	if (error) {
2507 		NFSUNLOCKSTATE();
2508 		if (haslock) {
2509 			NFSLOCKV4ROOTMUTEX();
2510 			nfsv4_unlock(&nfsv4rootfs_lock, 1);
2511 			NFSUNLOCKV4ROOTMUTEX();
2512 		}
2513 		goto out;
2514 	}
2515 
2516 	/*
2517 	 * Search for a conflicting open/share.
2518 	 */
2519 	if (new_stp->ls_flags & NFSLCK_DELEGCUR) {
2520 	    /*
2521 	     * For Delegate_Cur, search for the matching Delegation,
2522 	     * which indicates no conflict.
2523 	     * An old delegation should have been recovered by the
2524 	     * client doing a Claim_DELEGATE_Prev, so I won't let
2525 	     * it match and return NFSERR_EXPIRED. Should I let it
2526 	     * match?
2527 	     */
2528 	    LIST_FOREACH(stp, &lfp->lf_deleg, ls_file) {
2529 		if (!(stp->ls_flags & NFSLCK_OLDDELEG) &&
2530 		    (((nd->nd_flag & ND_NFSV41) != 0 &&
2531 		    stateidp->seqid == 0) ||
2532 		    stateidp->seqid == stp->ls_stateid.seqid) &&
2533 		    !NFSBCMP(stateidp->other, stp->ls_stateid.other,
2534 			  NFSX_STATEIDOTHER))
2535 			break;
2536 	    }
2537 	    if (stp == LIST_END(&lfp->lf_deleg) ||
2538 		((new_stp->ls_flags & NFSLCK_WRITEACCESS) &&
2539 		 (stp->ls_flags & NFSLCK_DELEGREAD))) {
2540 		NFSUNLOCKSTATE();
2541 		if (haslock) {
2542 			NFSLOCKV4ROOTMUTEX();
2543 			nfsv4_unlock(&nfsv4rootfs_lock, 1);
2544 			NFSUNLOCKV4ROOTMUTEX();
2545 		}
2546 		error = NFSERR_EXPIRED;
2547 		goto out;
2548 	    }
2549 	}
2550 
2551 	/*
2552 	 * Check for access/deny bit conflicts. I check for the same
2553 	 * owner as well, in case the client didn't bother.
2554 	 */
2555 	LIST_FOREACH(stp, &lfp->lf_open, ls_file) {
2556 		if (!(new_stp->ls_flags & NFSLCK_DELEGCUR) &&
2557 		    (((new_stp->ls_flags & NFSLCK_ACCESSBITS) &
2558 		      ((stp->ls_flags>>NFSLCK_SHIFT) & NFSLCK_ACCESSBITS))||
2559 		     ((stp->ls_flags & NFSLCK_ACCESSBITS) &
2560 		      ((new_stp->ls_flags>>NFSLCK_SHIFT)&NFSLCK_ACCESSBITS)))){
2561 			ret = nfsrv_clientconflict(stp->ls_clp,&haslock,vp,p);
2562 			if (ret == 1) {
2563 				/*
2564 				 * nfsrv_clientconflict() unlocks
2565 				 * state when it returns non-zero.
2566 				 */
2567 				goto tryagain;
2568 			}
2569 			if (ret == 2)
2570 				error = NFSERR_PERM;
2571 			else if (new_stp->ls_flags & NFSLCK_RECLAIM)
2572 				error = NFSERR_RECLAIMCONFLICT;
2573 			else
2574 				error = NFSERR_SHAREDENIED;
2575 			if (ret == 0)
2576 				NFSUNLOCKSTATE();
2577 			if (haslock) {
2578 				NFSLOCKV4ROOTMUTEX();
2579 				nfsv4_unlock(&nfsv4rootfs_lock, 1);
2580 				NFSUNLOCKV4ROOTMUTEX();
2581 			}
2582 			goto out;
2583 		}
2584 	}
2585 
2586 	/*
2587 	 * Check for a conflicting delegation. If one is found, call
2588 	 * nfsrv_delegconflict() to handle it. If the v4root lock hasn't
2589 	 * been set yet, it will get the lock. Otherwise, it will recall
2590 	 * the delegation. Then, we try try again...
2591 	 * (If NFSLCK_DELEGCUR is set, it has a delegation, so there
2592 	 *  isn't a conflict.)
2593 	 * I currently believe the conflict algorithm to be:
2594 	 * For Open with Read Access and Deny None
2595 	 * - there is a conflict iff a different client has a write delegation
2596 	 * For Open with other Write Access or any Deny except None
2597 	 * - there is a conflict if a different client has any delegation
2598 	 * - there is a conflict if the same client has a read delegation
2599 	 *   (The current consensus is that this last case should be
2600 	 *    considered a conflict since the client with a read delegation
2601 	 *    could have done an Open with ReadAccess and WriteDeny
2602 	 *    locally and then not have checked for the WriteDeny.)
2603 	 * Don't check for a Reclaim, since that will be dealt with
2604 	 * by nfsrv_openctrl().
2605 	 */
2606 	if (!(new_stp->ls_flags &
2607 		(NFSLCK_DELEGPREV | NFSLCK_DELEGCUR | NFSLCK_RECLAIM))) {
2608 	    stp = LIST_FIRST(&lfp->lf_deleg);
2609 	    while (stp != LIST_END(&lfp->lf_deleg)) {
2610 		nstp = LIST_NEXT(stp, ls_file);
2611 		if ((readonly && stp->ls_clp != clp &&
2612 		       (stp->ls_flags & NFSLCK_DELEGWRITE)) ||
2613 		    (!readonly && (stp->ls_clp != clp ||
2614 		         (stp->ls_flags & NFSLCK_DELEGREAD)))) {
2615 			ret = nfsrv_delegconflict(stp, &haslock, p, vp);
2616 			if (ret) {
2617 			    /*
2618 			     * nfsrv_delegconflict() unlocks state
2619 			     * when it returns non-zero.
2620 			     */
2621 			    if (ret == -1)
2622 				goto tryagain;
2623 			    error = ret;
2624 			    goto out;
2625 			}
2626 		}
2627 		stp = nstp;
2628 	    }
2629 	}
2630 	NFSUNLOCKSTATE();
2631 	if (haslock) {
2632 		NFSLOCKV4ROOTMUTEX();
2633 		nfsv4_unlock(&nfsv4rootfs_lock, 1);
2634 		NFSUNLOCKV4ROOTMUTEX();
2635 	}
2636 
2637 out:
2638 	NFSEXITCODE2(error, nd);
2639 	return (error);
2640 }
2641 
2642 /*
2643  * Open control function to create/update open state for an open.
2644  */
2645 int
2646 nfsrv_openctrl(struct nfsrv_descript *nd, vnode_t vp,
2647     struct nfsstate **new_stpp, nfsquad_t clientid, nfsv4stateid_t *stateidp,
2648     nfsv4stateid_t *delegstateidp, u_int32_t *rflagsp, struct nfsexstuff *exp,
2649     NFSPROC_T *p, u_quad_t filerev)
2650 {
2651 	struct nfsstate *new_stp = *new_stpp;
2652 	struct nfsstate *stp, *nstp;
2653 	struct nfsstate *openstp = NULL, *new_open, *ownerstp, *new_deleg;
2654 	struct nfslockfile *lfp, *new_lfp;
2655 	struct nfsclient *clp;
2656 	int error = 0, haslock = 0, ret, delegate = 1, writedeleg = 1;
2657 	int readonly = 0, cbret = 1, getfhret = 0;
2658 	int gotstate = 0, len = 0;
2659 	u_char *clidp = NULL;
2660 
2661 	if ((new_stp->ls_flags & NFSLCK_SHAREBITS) == NFSLCK_READACCESS)
2662 		readonly = 1;
2663 	/*
2664 	 * Check for restart conditions (client and server).
2665 	 * (Paranoia, should have been detected by nfsrv_opencheck().)
2666 	 * If an error does show up, return NFSERR_EXPIRED, since the
2667 	 * the seqid# has already been incremented.
2668 	 */
2669 	error = nfsrv_checkrestart(clientid, new_stp->ls_flags,
2670 	    &new_stp->ls_stateid, 0);
2671 	if (error) {
2672 		printf("Nfsd: openctrl unexpected restart err=%d\n",
2673 		    error);
2674 		error = NFSERR_EXPIRED;
2675 		goto out;
2676 	}
2677 
2678 	clidp = malloc(NFSV4_OPAQUELIMIT, M_TEMP, M_WAITOK);
2679 tryagain:
2680 	new_lfp = malloc(sizeof (struct nfslockfile),
2681 	    M_NFSDLOCKFILE, M_WAITOK);
2682 	new_open = malloc(sizeof (struct nfsstate),
2683 	    M_NFSDSTATE, M_WAITOK);
2684 	new_deleg = malloc(sizeof (struct nfsstate),
2685 	    M_NFSDSTATE, M_WAITOK);
2686 	getfhret = nfsrv_getlockfh(vp, new_stp->ls_flags, new_lfp,
2687 	    NULL, p);
2688 	NFSLOCKSTATE();
2689 	/*
2690 	 * Get the client structure. Since the linked lists could be changed
2691 	 * by other nfsd processes if this process does a tsleep(), one of
2692 	 * two things must be done.
2693 	 * 1 - don't tsleep()
2694 	 * or
2695 	 * 2 - get the nfsv4_lock() { indicated by haslock == 1 }
2696 	 *     before using the lists, since this lock stops the other
2697 	 *     nfsd. This should only be used for rare cases, since it
2698 	 *     essentially single threads the nfsd.
2699 	 *     At this time, it is only done for cases where the stable
2700 	 *     storage file must be written prior to completion of state
2701 	 *     expiration.
2702 	 */
2703 	error = nfsrv_getclient(clientid, CLOPS_RENEW, &clp, NULL,
2704 	    (nfsquad_t)((u_quad_t)0), 0, nd, p);
2705 	if (!error && (clp->lc_flags & LCL_NEEDSCBNULL) &&
2706 	    clp->lc_program) {
2707 		/*
2708 		 * This happens on the first open for a client
2709 		 * that supports callbacks.
2710 		 */
2711 		NFSUNLOCKSTATE();
2712 		/*
2713 		 * Although nfsrv_docallback() will sleep, clp won't
2714 		 * go away, since they are only removed when the
2715 		 * nfsv4_lock() has blocked the nfsd threads. The
2716 		 * fields in clp can change, but having multiple
2717 		 * threads do this Null callback RPC should be
2718 		 * harmless.
2719 		 */
2720 		cbret = nfsrv_docallback(clp, NFSV4PROC_CBNULL,
2721 		    NULL, 0, NULL, NULL, NULL, 0, p);
2722 		NFSLOCKSTATE();
2723 		clp->lc_flags &= ~LCL_NEEDSCBNULL;
2724 		if (!cbret)
2725 			clp->lc_flags |= LCL_CALLBACKSON;
2726 	}
2727 
2728 	/*
2729 	 * Look up the open owner. See if it needs confirmation and
2730 	 * check the seq#, as required.
2731 	 */
2732 	if (!error)
2733 		nfsrv_getowner(&clp->lc_open, new_stp, &ownerstp);
2734 
2735 	if (error) {
2736 		NFSUNLOCKSTATE();
2737 		printf("Nfsd: openctrl unexpected state err=%d\n",
2738 			error);
2739 		free(new_lfp, M_NFSDLOCKFILE);
2740 		free(new_open, M_NFSDSTATE);
2741 		free(new_deleg, M_NFSDSTATE);
2742 		if (haslock) {
2743 			NFSLOCKV4ROOTMUTEX();
2744 			nfsv4_unlock(&nfsv4rootfs_lock, 1);
2745 			NFSUNLOCKV4ROOTMUTEX();
2746 		}
2747 		error = NFSERR_EXPIRED;
2748 		goto out;
2749 	}
2750 
2751 	if (new_stp->ls_flags & NFSLCK_RECLAIM)
2752 		nfsrv_markstable(clp);
2753 
2754 	/*
2755 	 * Get the structure for the underlying file.
2756 	 */
2757 	if (getfhret)
2758 		error = getfhret;
2759 	else
2760 		error = nfsrv_getlockfile(new_stp->ls_flags, &new_lfp, &lfp,
2761 		    NULL, 0);
2762 	if (new_lfp)
2763 		free(new_lfp, M_NFSDLOCKFILE);
2764 	if (error) {
2765 		NFSUNLOCKSTATE();
2766 		printf("Nfsd openctrl unexpected getlockfile err=%d\n",
2767 		    error);
2768 		free(new_open, M_NFSDSTATE);
2769 		free(new_deleg, M_NFSDSTATE);
2770 		if (haslock) {
2771 			NFSLOCKV4ROOTMUTEX();
2772 			nfsv4_unlock(&nfsv4rootfs_lock, 1);
2773 			NFSUNLOCKV4ROOTMUTEX();
2774 		}
2775 		goto out;
2776 	}
2777 
2778 	/*
2779 	 * Search for a conflicting open/share.
2780 	 */
2781 	if (new_stp->ls_flags & NFSLCK_DELEGCUR) {
2782 	    /*
2783 	     * For Delegate_Cur, search for the matching Delegation,
2784 	     * which indicates no conflict.
2785 	     * An old delegation should have been recovered by the
2786 	     * client doing a Claim_DELEGATE_Prev, so I won't let
2787 	     * it match and return NFSERR_EXPIRED. Should I let it
2788 	     * match?
2789 	     */
2790 	    LIST_FOREACH(stp, &lfp->lf_deleg, ls_file) {
2791 		if (!(stp->ls_flags & NFSLCK_OLDDELEG) &&
2792 		    (((nd->nd_flag & ND_NFSV41) != 0 &&
2793 		    stateidp->seqid == 0) ||
2794 		    stateidp->seqid == stp->ls_stateid.seqid) &&
2795 		    !NFSBCMP(stateidp->other, stp->ls_stateid.other,
2796 			NFSX_STATEIDOTHER))
2797 			break;
2798 	    }
2799 	    if (stp == LIST_END(&lfp->lf_deleg) ||
2800 		((new_stp->ls_flags & NFSLCK_WRITEACCESS) &&
2801 		 (stp->ls_flags & NFSLCK_DELEGREAD))) {
2802 		NFSUNLOCKSTATE();
2803 		printf("Nfsd openctrl unexpected expiry\n");
2804 		free(new_open, M_NFSDSTATE);
2805 		free(new_deleg, M_NFSDSTATE);
2806 		if (haslock) {
2807 			NFSLOCKV4ROOTMUTEX();
2808 			nfsv4_unlock(&nfsv4rootfs_lock, 1);
2809 			NFSUNLOCKV4ROOTMUTEX();
2810 		}
2811 		error = NFSERR_EXPIRED;
2812 		goto out;
2813 	    }
2814 
2815 	    /*
2816 	     * Don't issue a Delegation, since one already exists and
2817 	     * delay delegation timeout, as required.
2818 	     */
2819 	    delegate = 0;
2820 	    nfsrv_delaydelegtimeout(stp);
2821 	}
2822 
2823 	/*
2824 	 * Check for access/deny bit conflicts. I also check for the
2825 	 * same owner, since the client might not have bothered to check.
2826 	 * Also, note an open for the same file and owner, if found,
2827 	 * which is all we do here for Delegate_Cur, since conflict
2828 	 * checking is already done.
2829 	 */
2830 	LIST_FOREACH(stp, &lfp->lf_open, ls_file) {
2831 		if (ownerstp && stp->ls_openowner == ownerstp)
2832 			openstp = stp;
2833 		if (!(new_stp->ls_flags & NFSLCK_DELEGCUR)) {
2834 		    /*
2835 		     * If another client has the file open, the only
2836 		     * delegation that can be issued is a Read delegation
2837 		     * and only if it is a Read open with Deny none.
2838 		     */
2839 		    if (clp != stp->ls_clp) {
2840 			if ((stp->ls_flags & NFSLCK_SHAREBITS) ==
2841 			    NFSLCK_READACCESS)
2842 			    writedeleg = 0;
2843 			else
2844 			    delegate = 0;
2845 		    }
2846 		    if(((new_stp->ls_flags & NFSLCK_ACCESSBITS) &
2847 		        ((stp->ls_flags>>NFSLCK_SHIFT) & NFSLCK_ACCESSBITS))||
2848 		       ((stp->ls_flags & NFSLCK_ACCESSBITS) &
2849 		        ((new_stp->ls_flags>>NFSLCK_SHIFT)&NFSLCK_ACCESSBITS))){
2850 			ret = nfsrv_clientconflict(stp->ls_clp,&haslock,vp,p);
2851 			if (ret == 1) {
2852 				/*
2853 				 * nfsrv_clientconflict() unlocks state
2854 				 * when it returns non-zero.
2855 				 */
2856 				free(new_open, M_NFSDSTATE);
2857 				free(new_deleg, M_NFSDSTATE);
2858 				openstp = NULL;
2859 				goto tryagain;
2860 			}
2861 			if (ret == 2)
2862 				error = NFSERR_PERM;
2863 			else if (new_stp->ls_flags & NFSLCK_RECLAIM)
2864 				error = NFSERR_RECLAIMCONFLICT;
2865 			else
2866 				error = NFSERR_SHAREDENIED;
2867 			if (ret == 0)
2868 				NFSUNLOCKSTATE();
2869 			if (haslock) {
2870 				NFSLOCKV4ROOTMUTEX();
2871 				nfsv4_unlock(&nfsv4rootfs_lock, 1);
2872 				NFSUNLOCKV4ROOTMUTEX();
2873 			}
2874 			free(new_open, M_NFSDSTATE);
2875 			free(new_deleg, M_NFSDSTATE);
2876 			printf("nfsd openctrl unexpected client cnfl\n");
2877 			goto out;
2878 		    }
2879 		}
2880 	}
2881 
2882 	/*
2883 	 * Check for a conflicting delegation. If one is found, call
2884 	 * nfsrv_delegconflict() to handle it. If the v4root lock hasn't
2885 	 * been set yet, it will get the lock. Otherwise, it will recall
2886 	 * the delegation. Then, we try try again...
2887 	 * (If NFSLCK_DELEGCUR is set, it has a delegation, so there
2888 	 *  isn't a conflict.)
2889 	 * I currently believe the conflict algorithm to be:
2890 	 * For Open with Read Access and Deny None
2891 	 * - there is a conflict iff a different client has a write delegation
2892 	 * For Open with other Write Access or any Deny except None
2893 	 * - there is a conflict if a different client has any delegation
2894 	 * - there is a conflict if the same client has a read delegation
2895 	 *   (The current consensus is that this last case should be
2896 	 *    considered a conflict since the client with a read delegation
2897 	 *    could have done an Open with ReadAccess and WriteDeny
2898 	 *    locally and then not have checked for the WriteDeny.)
2899 	 */
2900 	if (!(new_stp->ls_flags & (NFSLCK_DELEGPREV | NFSLCK_DELEGCUR))) {
2901 	    stp = LIST_FIRST(&lfp->lf_deleg);
2902 	    while (stp != LIST_END(&lfp->lf_deleg)) {
2903 		nstp = LIST_NEXT(stp, ls_file);
2904 		if (stp->ls_clp != clp && (stp->ls_flags & NFSLCK_DELEGREAD))
2905 			writedeleg = 0;
2906 		else
2907 			delegate = 0;
2908 		if ((readonly && stp->ls_clp != clp &&
2909 		       (stp->ls_flags & NFSLCK_DELEGWRITE)) ||
2910 		    (!readonly && (stp->ls_clp != clp ||
2911 		         (stp->ls_flags & NFSLCK_DELEGREAD)))) {
2912 		    if (new_stp->ls_flags & NFSLCK_RECLAIM) {
2913 			delegate = 2;
2914 		    } else {
2915 			ret = nfsrv_delegconflict(stp, &haslock, p, vp);
2916 			if (ret) {
2917 			    /*
2918 			     * nfsrv_delegconflict() unlocks state
2919 			     * when it returns non-zero.
2920 			     */
2921 			    printf("Nfsd openctrl unexpected deleg cnfl\n");
2922 			    free(new_open, M_NFSDSTATE);
2923 			    free(new_deleg, M_NFSDSTATE);
2924 			    if (ret == -1) {
2925 				openstp = NULL;
2926 				goto tryagain;
2927 			    }
2928 			    error = ret;
2929 			    goto out;
2930 			}
2931 		    }
2932 		}
2933 		stp = nstp;
2934 	    }
2935 	}
2936 
2937 	/*
2938 	 * We only get here if there was no open that conflicted.
2939 	 * If an open for the owner exists, or in the access/deny bits.
2940 	 * Otherwise it is a new open. If the open_owner hasn't been
2941 	 * confirmed, replace the open with the new one needing confirmation,
2942 	 * otherwise add the open.
2943 	 */
2944 	if (new_stp->ls_flags & NFSLCK_DELEGPREV) {
2945 	    /*
2946 	     * Handle NFSLCK_DELEGPREV by searching the old delegations for
2947 	     * a match. If found, just move the old delegation to the current
2948 	     * delegation list and issue open. If not found, return
2949 	     * NFSERR_EXPIRED.
2950 	     */
2951 	    LIST_FOREACH(stp, &clp->lc_olddeleg, ls_list) {
2952 		if (stp->ls_lfp == lfp) {
2953 		    /* Found it */
2954 		    if (stp->ls_clp != clp)
2955 			panic("olddeleg clp");
2956 		    LIST_REMOVE(stp, ls_list);
2957 		    LIST_REMOVE(stp, ls_hash);
2958 		    stp->ls_flags &= ~NFSLCK_OLDDELEG;
2959 		    stp->ls_stateid.seqid = delegstateidp->seqid = 1;
2960 		    stp->ls_stateid.other[0] = delegstateidp->other[0] =
2961 			clp->lc_clientid.lval[0];
2962 		    stp->ls_stateid.other[1] = delegstateidp->other[1] =
2963 			clp->lc_clientid.lval[1];
2964 		    stp->ls_stateid.other[2] = delegstateidp->other[2] =
2965 			nfsrv_nextstateindex(clp);
2966 		    stp->ls_compref = nd->nd_compref;
2967 		    LIST_INSERT_HEAD(&clp->lc_deleg, stp, ls_list);
2968 		    LIST_INSERT_HEAD(NFSSTATEHASH(clp,
2969 			stp->ls_stateid), stp, ls_hash);
2970 		    if (stp->ls_flags & NFSLCK_DELEGWRITE)
2971 			*rflagsp |= NFSV4OPEN_WRITEDELEGATE;
2972 		    else
2973 			*rflagsp |= NFSV4OPEN_READDELEGATE;
2974 		    clp->lc_delegtime = NFSD_MONOSEC +
2975 			nfsrv_lease + NFSRV_LEASEDELTA;
2976 
2977 		    /*
2978 		     * Now, do the associated open.
2979 		     */
2980 		    new_open->ls_stateid.seqid = 1;
2981 		    new_open->ls_stateid.other[0] = clp->lc_clientid.lval[0];
2982 		    new_open->ls_stateid.other[1] = clp->lc_clientid.lval[1];
2983 		    new_open->ls_stateid.other[2] = nfsrv_nextstateindex(clp);
2984 		    new_open->ls_flags = (new_stp->ls_flags&NFSLCK_DENYBITS)|
2985 			NFSLCK_OPEN;
2986 		    if (stp->ls_flags & NFSLCK_DELEGWRITE)
2987 			new_open->ls_flags |= (NFSLCK_READACCESS |
2988 			    NFSLCK_WRITEACCESS);
2989 		    else
2990 			new_open->ls_flags |= NFSLCK_READACCESS;
2991 		    new_open->ls_uid = new_stp->ls_uid;
2992 		    new_open->ls_lfp = lfp;
2993 		    new_open->ls_clp = clp;
2994 		    LIST_INIT(&new_open->ls_open);
2995 		    LIST_INSERT_HEAD(&lfp->lf_open, new_open, ls_file);
2996 		    LIST_INSERT_HEAD(NFSSTATEHASH(clp, new_open->ls_stateid),
2997 			new_open, ls_hash);
2998 		    /*
2999 		     * and handle the open owner
3000 		     */
3001 		    if (ownerstp) {
3002 			new_open->ls_openowner = ownerstp;
3003 			LIST_INSERT_HEAD(&ownerstp->ls_open,new_open,ls_list);
3004 		    } else {
3005 			new_open->ls_openowner = new_stp;
3006 			new_stp->ls_flags = 0;
3007 			nfsrvd_refcache(new_stp->ls_op);
3008 			new_stp->ls_noopens = 0;
3009 			LIST_INIT(&new_stp->ls_open);
3010 			LIST_INSERT_HEAD(&new_stp->ls_open, new_open, ls_list);
3011 			LIST_INSERT_HEAD(&clp->lc_open, new_stp, ls_list);
3012 			*new_stpp = NULL;
3013 			nfsstatsv1.srvopenowners++;
3014 			nfsrv_openpluslock++;
3015 		    }
3016 		    openstp = new_open;
3017 		    new_open = NULL;
3018 		    nfsstatsv1.srvopens++;
3019 		    nfsrv_openpluslock++;
3020 		    break;
3021 		}
3022 	    }
3023 	    if (stp == LIST_END(&clp->lc_olddeleg))
3024 		error = NFSERR_EXPIRED;
3025 	} else if (new_stp->ls_flags & (NFSLCK_DELEGREAD | NFSLCK_DELEGWRITE)) {
3026 	    /*
3027 	     * Scan to see that no delegation for this client and file
3028 	     * doesn't already exist.
3029 	     * There also shouldn't yet be an Open for this file and
3030 	     * openowner.
3031 	     */
3032 	    LIST_FOREACH(stp, &lfp->lf_deleg, ls_file) {
3033 		if (stp->ls_clp == clp)
3034 		    break;
3035 	    }
3036 	    if (stp == LIST_END(&lfp->lf_deleg) && openstp == NULL) {
3037 		/*
3038 		 * This is the Claim_Previous case with a delegation
3039 		 * type != Delegate_None.
3040 		 */
3041 		/*
3042 		 * First, add the delegation. (Although we must issue the
3043 		 * delegation, we can also ask for an immediate return.)
3044 		 */
3045 		new_deleg->ls_stateid.seqid = delegstateidp->seqid = 1;
3046 		new_deleg->ls_stateid.other[0] = delegstateidp->other[0] =
3047 		    clp->lc_clientid.lval[0];
3048 		new_deleg->ls_stateid.other[1] = delegstateidp->other[1] =
3049 		    clp->lc_clientid.lval[1];
3050 		new_deleg->ls_stateid.other[2] = delegstateidp->other[2] =
3051 		    nfsrv_nextstateindex(clp);
3052 		if (new_stp->ls_flags & NFSLCK_DELEGWRITE) {
3053 		    new_deleg->ls_flags = (NFSLCK_DELEGWRITE |
3054 			NFSLCK_READACCESS | NFSLCK_WRITEACCESS);
3055 		    *rflagsp |= NFSV4OPEN_WRITEDELEGATE;
3056 		    nfsrv_writedelegcnt++;
3057 		} else {
3058 		    new_deleg->ls_flags = (NFSLCK_DELEGREAD |
3059 			NFSLCK_READACCESS);
3060 		    *rflagsp |= NFSV4OPEN_READDELEGATE;
3061 		}
3062 		new_deleg->ls_uid = new_stp->ls_uid;
3063 		new_deleg->ls_lfp = lfp;
3064 		new_deleg->ls_clp = clp;
3065 		new_deleg->ls_filerev = filerev;
3066 		new_deleg->ls_compref = nd->nd_compref;
3067 		LIST_INSERT_HEAD(&lfp->lf_deleg, new_deleg, ls_file);
3068 		LIST_INSERT_HEAD(NFSSTATEHASH(clp,
3069 		    new_deleg->ls_stateid), new_deleg, ls_hash);
3070 		LIST_INSERT_HEAD(&clp->lc_deleg, new_deleg, ls_list);
3071 		new_deleg = NULL;
3072 		if (delegate == 2 || nfsrv_issuedelegs == 0 ||
3073 		    (clp->lc_flags & (LCL_CALLBACKSON | LCL_CBDOWN)) !=
3074 		     LCL_CALLBACKSON ||
3075 		    NFSRV_V4DELEGLIMIT(nfsrv_delegatecnt) ||
3076 		    !NFSVNO_DELEGOK(vp))
3077 		    *rflagsp |= NFSV4OPEN_RECALL;
3078 		nfsstatsv1.srvdelegates++;
3079 		nfsrv_openpluslock++;
3080 		nfsrv_delegatecnt++;
3081 
3082 		/*
3083 		 * Now, do the associated open.
3084 		 */
3085 		new_open->ls_stateid.seqid = 1;
3086 		new_open->ls_stateid.other[0] = clp->lc_clientid.lval[0];
3087 		new_open->ls_stateid.other[1] = clp->lc_clientid.lval[1];
3088 		new_open->ls_stateid.other[2] = nfsrv_nextstateindex(clp);
3089 		new_open->ls_flags = (new_stp->ls_flags & NFSLCK_DENYBITS) |
3090 		    NFSLCK_OPEN;
3091 		if (new_stp->ls_flags & NFSLCK_DELEGWRITE)
3092 			new_open->ls_flags |= (NFSLCK_READACCESS |
3093 			    NFSLCK_WRITEACCESS);
3094 		else
3095 			new_open->ls_flags |= NFSLCK_READACCESS;
3096 		new_open->ls_uid = new_stp->ls_uid;
3097 		new_open->ls_lfp = lfp;
3098 		new_open->ls_clp = clp;
3099 		LIST_INIT(&new_open->ls_open);
3100 		LIST_INSERT_HEAD(&lfp->lf_open, new_open, ls_file);
3101 		LIST_INSERT_HEAD(NFSSTATEHASH(clp, new_open->ls_stateid),
3102 		   new_open, ls_hash);
3103 		/*
3104 		 * and handle the open owner
3105 		 */
3106 		if (ownerstp) {
3107 		    new_open->ls_openowner = ownerstp;
3108 		    LIST_INSERT_HEAD(&ownerstp->ls_open, new_open, ls_list);
3109 		} else {
3110 		    new_open->ls_openowner = new_stp;
3111 		    new_stp->ls_flags = 0;
3112 		    nfsrvd_refcache(new_stp->ls_op);
3113 		    new_stp->ls_noopens = 0;
3114 		    LIST_INIT(&new_stp->ls_open);
3115 		    LIST_INSERT_HEAD(&new_stp->ls_open, new_open, ls_list);
3116 		    LIST_INSERT_HEAD(&clp->lc_open, new_stp, ls_list);
3117 		    *new_stpp = NULL;
3118 		    nfsstatsv1.srvopenowners++;
3119 		    nfsrv_openpluslock++;
3120 		}
3121 		openstp = new_open;
3122 		new_open = NULL;
3123 		nfsstatsv1.srvopens++;
3124 		nfsrv_openpluslock++;
3125 	    } else {
3126 		error = NFSERR_RECLAIMCONFLICT;
3127 	    }
3128 	} else if (ownerstp) {
3129 		if (ownerstp->ls_flags & NFSLCK_NEEDSCONFIRM) {
3130 		    /* Replace the open */
3131 		    if (ownerstp->ls_op)
3132 			nfsrvd_derefcache(ownerstp->ls_op);
3133 		    ownerstp->ls_op = new_stp->ls_op;
3134 		    nfsrvd_refcache(ownerstp->ls_op);
3135 		    ownerstp->ls_seq = new_stp->ls_seq;
3136 		    *rflagsp |= NFSV4OPEN_RESULTCONFIRM;
3137 		    stp = LIST_FIRST(&ownerstp->ls_open);
3138 		    stp->ls_flags = (new_stp->ls_flags & NFSLCK_SHAREBITS) |
3139 			NFSLCK_OPEN;
3140 		    stp->ls_stateid.seqid = 1;
3141 		    stp->ls_uid = new_stp->ls_uid;
3142 		    if (lfp != stp->ls_lfp) {
3143 			LIST_REMOVE(stp, ls_file);
3144 			LIST_INSERT_HEAD(&lfp->lf_open, stp, ls_file);
3145 			stp->ls_lfp = lfp;
3146 		    }
3147 		    openstp = stp;
3148 		} else if (openstp) {
3149 		    openstp->ls_flags |= (new_stp->ls_flags & NFSLCK_SHAREBITS);
3150 		    openstp->ls_stateid.seqid++;
3151 		    if ((nd->nd_flag & ND_NFSV41) != 0 &&
3152 			openstp->ls_stateid.seqid == 0)
3153 			openstp->ls_stateid.seqid = 1;
3154 
3155 		    /*
3156 		     * This is where we can choose to issue a delegation.
3157 		     */
3158 		    if ((new_stp->ls_flags & NFSLCK_WANTNODELEG) != 0)
3159 			*rflagsp |= NFSV4OPEN_WDNOTWANTED;
3160 		    else if (nfsrv_issuedelegs == 0)
3161 			*rflagsp |= NFSV4OPEN_WDSUPPFTYPE;
3162 		    else if (NFSRV_V4DELEGLIMIT(nfsrv_delegatecnt))
3163 			*rflagsp |= NFSV4OPEN_WDRESOURCE;
3164 		    else if (delegate == 0 || writedeleg == 0 ||
3165 			NFSVNO_EXRDONLY(exp) || (readonly != 0 &&
3166 			nfsrv_writedelegifpos == 0) ||
3167 			!NFSVNO_DELEGOK(vp) ||
3168 			(new_stp->ls_flags & NFSLCK_WANTRDELEG) != 0 ||
3169 			(clp->lc_flags & (LCL_CALLBACKSON | LCL_CBDOWN)) !=
3170 			 LCL_CALLBACKSON)
3171 			*rflagsp |= NFSV4OPEN_WDCONTENTION;
3172 		    else {
3173 			new_deleg->ls_stateid.seqid = delegstateidp->seqid = 1;
3174 			new_deleg->ls_stateid.other[0] = delegstateidp->other[0]
3175 			    = clp->lc_clientid.lval[0];
3176 			new_deleg->ls_stateid.other[1] = delegstateidp->other[1]
3177 			    = clp->lc_clientid.lval[1];
3178 			new_deleg->ls_stateid.other[2] = delegstateidp->other[2]
3179 			    = nfsrv_nextstateindex(clp);
3180 			new_deleg->ls_flags = (NFSLCK_DELEGWRITE |
3181 			    NFSLCK_READACCESS | NFSLCK_WRITEACCESS);
3182 			*rflagsp |= NFSV4OPEN_WRITEDELEGATE;
3183 			new_deleg->ls_uid = new_stp->ls_uid;
3184 			new_deleg->ls_lfp = lfp;
3185 			new_deleg->ls_clp = clp;
3186 			new_deleg->ls_filerev = filerev;
3187 			new_deleg->ls_compref = nd->nd_compref;
3188 			nfsrv_writedelegcnt++;
3189 			LIST_INSERT_HEAD(&lfp->lf_deleg, new_deleg, ls_file);
3190 			LIST_INSERT_HEAD(NFSSTATEHASH(clp,
3191 			    new_deleg->ls_stateid), new_deleg, ls_hash);
3192 			LIST_INSERT_HEAD(&clp->lc_deleg, new_deleg, ls_list);
3193 			new_deleg = NULL;
3194 			nfsstatsv1.srvdelegates++;
3195 			nfsrv_openpluslock++;
3196 			nfsrv_delegatecnt++;
3197 		    }
3198 		} else {
3199 		    new_open->ls_stateid.seqid = 1;
3200 		    new_open->ls_stateid.other[0] = clp->lc_clientid.lval[0];
3201 		    new_open->ls_stateid.other[1] = clp->lc_clientid.lval[1];
3202 		    new_open->ls_stateid.other[2] = nfsrv_nextstateindex(clp);
3203 		    new_open->ls_flags = (new_stp->ls_flags & NFSLCK_SHAREBITS)|
3204 			NFSLCK_OPEN;
3205 		    new_open->ls_uid = new_stp->ls_uid;
3206 		    new_open->ls_openowner = ownerstp;
3207 		    new_open->ls_lfp = lfp;
3208 		    new_open->ls_clp = clp;
3209 		    LIST_INIT(&new_open->ls_open);
3210 		    LIST_INSERT_HEAD(&lfp->lf_open, new_open, ls_file);
3211 		    LIST_INSERT_HEAD(&ownerstp->ls_open, new_open, ls_list);
3212 		    LIST_INSERT_HEAD(NFSSTATEHASH(clp, new_open->ls_stateid),
3213 			new_open, ls_hash);
3214 		    openstp = new_open;
3215 		    new_open = NULL;
3216 		    nfsstatsv1.srvopens++;
3217 		    nfsrv_openpluslock++;
3218 
3219 		    /*
3220 		     * This is where we can choose to issue a delegation.
3221 		     */
3222 		    if ((new_stp->ls_flags & NFSLCK_WANTNODELEG) != 0)
3223 			*rflagsp |= NFSV4OPEN_WDNOTWANTED;
3224 		    else if (nfsrv_issuedelegs == 0)
3225 			*rflagsp |= NFSV4OPEN_WDSUPPFTYPE;
3226 		    else if (NFSRV_V4DELEGLIMIT(nfsrv_delegatecnt))
3227 			*rflagsp |= NFSV4OPEN_WDRESOURCE;
3228 		    else if (delegate == 0 || (writedeleg == 0 &&
3229 			readonly == 0) || !NFSVNO_DELEGOK(vp) ||
3230 			(clp->lc_flags & (LCL_CALLBACKSON | LCL_CBDOWN)) !=
3231 			 LCL_CALLBACKSON)
3232 			*rflagsp |= NFSV4OPEN_WDCONTENTION;
3233 		    else {
3234 			new_deleg->ls_stateid.seqid = delegstateidp->seqid = 1;
3235 			new_deleg->ls_stateid.other[0] = delegstateidp->other[0]
3236 			    = clp->lc_clientid.lval[0];
3237 			new_deleg->ls_stateid.other[1] = delegstateidp->other[1]
3238 			    = clp->lc_clientid.lval[1];
3239 			new_deleg->ls_stateid.other[2] = delegstateidp->other[2]
3240 			    = nfsrv_nextstateindex(clp);
3241 			if (writedeleg && !NFSVNO_EXRDONLY(exp) &&
3242 			    (nfsrv_writedelegifpos || !readonly) &&
3243 			    (new_stp->ls_flags & NFSLCK_WANTRDELEG) == 0) {
3244 			    new_deleg->ls_flags = (NFSLCK_DELEGWRITE |
3245 				NFSLCK_READACCESS | NFSLCK_WRITEACCESS);
3246 			    *rflagsp |= NFSV4OPEN_WRITEDELEGATE;
3247 			    nfsrv_writedelegcnt++;
3248 			} else {
3249 			    new_deleg->ls_flags = (NFSLCK_DELEGREAD |
3250 				NFSLCK_READACCESS);
3251 			    *rflagsp |= NFSV4OPEN_READDELEGATE;
3252 			}
3253 			new_deleg->ls_uid = new_stp->ls_uid;
3254 			new_deleg->ls_lfp = lfp;
3255 			new_deleg->ls_clp = clp;
3256 			new_deleg->ls_filerev = filerev;
3257 			new_deleg->ls_compref = nd->nd_compref;
3258 			LIST_INSERT_HEAD(&lfp->lf_deleg, new_deleg, ls_file);
3259 			LIST_INSERT_HEAD(NFSSTATEHASH(clp,
3260 			    new_deleg->ls_stateid), new_deleg, ls_hash);
3261 			LIST_INSERT_HEAD(&clp->lc_deleg, new_deleg, ls_list);
3262 			new_deleg = NULL;
3263 			nfsstatsv1.srvdelegates++;
3264 			nfsrv_openpluslock++;
3265 			nfsrv_delegatecnt++;
3266 		    }
3267 		}
3268 	} else {
3269 		/*
3270 		 * New owner case. Start the open_owner sequence with a
3271 		 * Needs confirmation (unless a reclaim) and hang the
3272 		 * new open off it.
3273 		 */
3274 		new_open->ls_stateid.seqid = 1;
3275 		new_open->ls_stateid.other[0] = clp->lc_clientid.lval[0];
3276 		new_open->ls_stateid.other[1] = clp->lc_clientid.lval[1];
3277 		new_open->ls_stateid.other[2] = nfsrv_nextstateindex(clp);
3278 		new_open->ls_flags = (new_stp->ls_flags & NFSLCK_SHAREBITS) |
3279 		    NFSLCK_OPEN;
3280 		new_open->ls_uid = new_stp->ls_uid;
3281 		LIST_INIT(&new_open->ls_open);
3282 		new_open->ls_openowner = new_stp;
3283 		new_open->ls_lfp = lfp;
3284 		new_open->ls_clp = clp;
3285 		LIST_INSERT_HEAD(&lfp->lf_open, new_open, ls_file);
3286 		if (new_stp->ls_flags & NFSLCK_RECLAIM) {
3287 			new_stp->ls_flags = 0;
3288 		} else if ((nd->nd_flag & ND_NFSV41) != 0) {
3289 			/* NFSv4.1 never needs confirmation. */
3290 			new_stp->ls_flags = 0;
3291 
3292 			/*
3293 			 * This is where we can choose to issue a delegation.
3294 			 */
3295 			if (delegate && nfsrv_issuedelegs &&
3296 			    (writedeleg || readonly) &&
3297 			    (clp->lc_flags & (LCL_CALLBACKSON | LCL_CBDOWN)) ==
3298 			     LCL_CALLBACKSON &&
3299 			    !NFSRV_V4DELEGLIMIT(nfsrv_delegatecnt) &&
3300 			    NFSVNO_DELEGOK(vp) &&
3301 			    ((nd->nd_flag & ND_NFSV41) == 0 ||
3302 			     (new_stp->ls_flags & NFSLCK_WANTNODELEG) == 0)) {
3303 				new_deleg->ls_stateid.seqid =
3304 				    delegstateidp->seqid = 1;
3305 				new_deleg->ls_stateid.other[0] =
3306 				    delegstateidp->other[0]
3307 				    = clp->lc_clientid.lval[0];
3308 				new_deleg->ls_stateid.other[1] =
3309 				    delegstateidp->other[1]
3310 				    = clp->lc_clientid.lval[1];
3311 				new_deleg->ls_stateid.other[2] =
3312 				    delegstateidp->other[2]
3313 				    = nfsrv_nextstateindex(clp);
3314 				if (writedeleg && !NFSVNO_EXRDONLY(exp) &&
3315 				    (nfsrv_writedelegifpos || !readonly) &&
3316 				    ((nd->nd_flag & ND_NFSV41) == 0 ||
3317 				     (new_stp->ls_flags & NFSLCK_WANTRDELEG) ==
3318 				     0)) {
3319 					new_deleg->ls_flags =
3320 					    (NFSLCK_DELEGWRITE |
3321 					     NFSLCK_READACCESS |
3322 					     NFSLCK_WRITEACCESS);
3323 					*rflagsp |= NFSV4OPEN_WRITEDELEGATE;
3324 					nfsrv_writedelegcnt++;
3325 				} else {
3326 					new_deleg->ls_flags =
3327 					    (NFSLCK_DELEGREAD |
3328 					     NFSLCK_READACCESS);
3329 					*rflagsp |= NFSV4OPEN_READDELEGATE;
3330 				}
3331 				new_deleg->ls_uid = new_stp->ls_uid;
3332 				new_deleg->ls_lfp = lfp;
3333 				new_deleg->ls_clp = clp;
3334 				new_deleg->ls_filerev = filerev;
3335 				new_deleg->ls_compref = nd->nd_compref;
3336 				LIST_INSERT_HEAD(&lfp->lf_deleg, new_deleg,
3337 				    ls_file);
3338 				LIST_INSERT_HEAD(NFSSTATEHASH(clp,
3339 				    new_deleg->ls_stateid), new_deleg, ls_hash);
3340 				LIST_INSERT_HEAD(&clp->lc_deleg, new_deleg,
3341 				    ls_list);
3342 				new_deleg = NULL;
3343 				nfsstatsv1.srvdelegates++;
3344 				nfsrv_openpluslock++;
3345 				nfsrv_delegatecnt++;
3346 			}
3347 			/*
3348 			 * Since NFSv4.1 never does an OpenConfirm, the first
3349 			 * open state will be acquired here.
3350 			 */
3351 			if (!(clp->lc_flags & LCL_STAMPEDSTABLE)) {
3352 				clp->lc_flags |= LCL_STAMPEDSTABLE;
3353 				len = clp->lc_idlen;
3354 				NFSBCOPY(clp->lc_id, clidp, len);
3355 				gotstate = 1;
3356 			}
3357 		} else {
3358 			*rflagsp |= NFSV4OPEN_RESULTCONFIRM;
3359 			new_stp->ls_flags = NFSLCK_NEEDSCONFIRM;
3360 		}
3361 		nfsrvd_refcache(new_stp->ls_op);
3362 		new_stp->ls_noopens = 0;
3363 		LIST_INIT(&new_stp->ls_open);
3364 		LIST_INSERT_HEAD(&new_stp->ls_open, new_open, ls_list);
3365 		LIST_INSERT_HEAD(&clp->lc_open, new_stp, ls_list);
3366 		LIST_INSERT_HEAD(NFSSTATEHASH(clp, new_open->ls_stateid),
3367 		    new_open, ls_hash);
3368 		openstp = new_open;
3369 		new_open = NULL;
3370 		*new_stpp = NULL;
3371 		nfsstatsv1.srvopens++;
3372 		nfsrv_openpluslock++;
3373 		nfsstatsv1.srvopenowners++;
3374 		nfsrv_openpluslock++;
3375 	}
3376 	if (!error) {
3377 		stateidp->seqid = openstp->ls_stateid.seqid;
3378 		stateidp->other[0] = openstp->ls_stateid.other[0];
3379 		stateidp->other[1] = openstp->ls_stateid.other[1];
3380 		stateidp->other[2] = openstp->ls_stateid.other[2];
3381 	}
3382 	NFSUNLOCKSTATE();
3383 	if (haslock) {
3384 		NFSLOCKV4ROOTMUTEX();
3385 		nfsv4_unlock(&nfsv4rootfs_lock, 1);
3386 		NFSUNLOCKV4ROOTMUTEX();
3387 	}
3388 	if (new_open)
3389 		free(new_open, M_NFSDSTATE);
3390 	if (new_deleg)
3391 		free(new_deleg, M_NFSDSTATE);
3392 
3393 	/*
3394 	 * If the NFSv4.1 client just acquired its first open, write a timestamp
3395 	 * to the stable storage file.
3396 	 */
3397 	if (gotstate != 0) {
3398 		nfsrv_writestable(clidp, len, NFSNST_NEWSTATE, p);
3399 		nfsrv_backupstable();
3400 	}
3401 
3402 out:
3403 	free(clidp, M_TEMP);
3404 	NFSEXITCODE2(error, nd);
3405 	return (error);
3406 }
3407 
3408 /*
3409  * Open update. Does the confirm, downgrade and close.
3410  */
3411 int
3412 nfsrv_openupdate(vnode_t vp, struct nfsstate *new_stp, nfsquad_t clientid,
3413     nfsv4stateid_t *stateidp, struct nfsrv_descript *nd, NFSPROC_T *p,
3414     int *retwriteaccessp)
3415 {
3416 	struct nfsstate *stp;
3417 	struct nfsclient *clp;
3418 	struct nfslockfile *lfp;
3419 	u_int32_t bits;
3420 	int error = 0, gotstate = 0, len = 0;
3421 	u_char *clidp = NULL;
3422 
3423 	/*
3424 	 * Check for restart conditions (client and server).
3425 	 */
3426 	error = nfsrv_checkrestart(clientid, new_stp->ls_flags,
3427 	    &new_stp->ls_stateid, 0);
3428 	if (error)
3429 		goto out;
3430 
3431 	clidp = malloc(NFSV4_OPAQUELIMIT, M_TEMP, M_WAITOK);
3432 	NFSLOCKSTATE();
3433 	/*
3434 	 * Get the open structure via clientid and stateid.
3435 	 */
3436 	error = nfsrv_getclient(clientid, CLOPS_RENEW, &clp, NULL,
3437 	    (nfsquad_t)((u_quad_t)0), 0, nd, p);
3438 	if (!error)
3439 		error = nfsrv_getstate(clp, &new_stp->ls_stateid,
3440 		    new_stp->ls_flags, &stp);
3441 
3442 	/*
3443 	 * Sanity check the open.
3444 	 */
3445 	if (!error && (!(stp->ls_flags & NFSLCK_OPEN) ||
3446 		(!(new_stp->ls_flags & NFSLCK_CONFIRM) &&
3447 		 (stp->ls_openowner->ls_flags & NFSLCK_NEEDSCONFIRM)) ||
3448 		((new_stp->ls_flags & NFSLCK_CONFIRM) &&
3449 		 (!(stp->ls_openowner->ls_flags & NFSLCK_NEEDSCONFIRM)))))
3450 		error = NFSERR_BADSTATEID;
3451 
3452 	if (!error)
3453 		error = nfsrv_checkseqid(nd, new_stp->ls_seq,
3454 		    stp->ls_openowner, new_stp->ls_op);
3455 	if (!error && stp->ls_stateid.seqid != new_stp->ls_stateid.seqid &&
3456 	    (((nd->nd_flag & ND_NFSV41) == 0 &&
3457 	      !(new_stp->ls_flags & NFSLCK_CONFIRM)) ||
3458 	     ((nd->nd_flag & ND_NFSV41) != 0 &&
3459 	      new_stp->ls_stateid.seqid != 0)))
3460 		error = NFSERR_OLDSTATEID;
3461 	if (!error && vnode_vtype(vp) != VREG) {
3462 		if (vnode_vtype(vp) == VDIR)
3463 			error = NFSERR_ISDIR;
3464 		else
3465 			error = NFSERR_INVAL;
3466 	}
3467 
3468 	if (error) {
3469 		/*
3470 		 * If a client tries to confirm an Open with a bad
3471 		 * seqid# and there are no byte range locks or other Opens
3472 		 * on the openowner, just throw it away, so the next use of the
3473 		 * openowner will start a fresh seq#.
3474 		 */
3475 		if (error == NFSERR_BADSEQID &&
3476 		    (new_stp->ls_flags & NFSLCK_CONFIRM) &&
3477 		    nfsrv_nootherstate(stp))
3478 			nfsrv_freeopenowner(stp->ls_openowner, 0, p);
3479 		NFSUNLOCKSTATE();
3480 		goto out;
3481 	}
3482 
3483 	/*
3484 	 * Set the return stateid.
3485 	 */
3486 	stateidp->seqid = stp->ls_stateid.seqid + 1;
3487 	if ((nd->nd_flag & ND_NFSV41) != 0 && stateidp->seqid == 0)
3488 		stateidp->seqid = 1;
3489 	stateidp->other[0] = stp->ls_stateid.other[0];
3490 	stateidp->other[1] = stp->ls_stateid.other[1];
3491 	stateidp->other[2] = stp->ls_stateid.other[2];
3492 	/*
3493 	 * Now, handle the three cases.
3494 	 */
3495 	if (new_stp->ls_flags & NFSLCK_CONFIRM) {
3496 		/*
3497 		 * If the open doesn't need confirmation, it seems to me that
3498 		 * there is a client error, but I'll just log it and keep going?
3499 		 */
3500 		if (!(stp->ls_openowner->ls_flags & NFSLCK_NEEDSCONFIRM))
3501 			printf("Nfsv4d: stray open confirm\n");
3502 		stp->ls_openowner->ls_flags = 0;
3503 		stp->ls_stateid.seqid++;
3504 		if ((nd->nd_flag & ND_NFSV41) != 0 &&
3505 		    stp->ls_stateid.seqid == 0)
3506 			stp->ls_stateid.seqid = 1;
3507 		if (!(clp->lc_flags & LCL_STAMPEDSTABLE)) {
3508 			clp->lc_flags |= LCL_STAMPEDSTABLE;
3509 			len = clp->lc_idlen;
3510 			NFSBCOPY(clp->lc_id, clidp, len);
3511 			gotstate = 1;
3512 		}
3513 		NFSUNLOCKSTATE();
3514 	} else if (new_stp->ls_flags & NFSLCK_CLOSE) {
3515 		lfp = stp->ls_lfp;
3516 		if (retwriteaccessp != NULL) {
3517 			if ((stp->ls_flags & NFSLCK_WRITEACCESS) != 0)
3518 				*retwriteaccessp = 1;
3519 			else
3520 				*retwriteaccessp = 0;
3521 		}
3522 		if (nfsrv_dolocallocks != 0 && !LIST_EMPTY(&stp->ls_open)) {
3523 			/* Get the lf lock */
3524 			nfsrv_locklf(lfp);
3525 			NFSUNLOCKSTATE();
3526 			ASSERT_VOP_ELOCKED(vp, "nfsrv_openupdate");
3527 			NFSVOPUNLOCK(vp);
3528 			if (nfsrv_freeopen(stp, vp, 1, p) == 0) {
3529 				NFSLOCKSTATE();
3530 				nfsrv_unlocklf(lfp);
3531 				NFSUNLOCKSTATE();
3532 			}
3533 			NFSVOPLOCK(vp, LK_EXCLUSIVE | LK_RETRY);
3534 		} else {
3535 			(void) nfsrv_freeopen(stp, NULL, 0, p);
3536 			NFSUNLOCKSTATE();
3537 		}
3538 	} else {
3539 		/*
3540 		 * Update the share bits, making sure that the new set are a
3541 		 * subset of the old ones.
3542 		 */
3543 		bits = (new_stp->ls_flags & NFSLCK_SHAREBITS);
3544 		if (~(stp->ls_flags) & bits) {
3545 			NFSUNLOCKSTATE();
3546 			error = NFSERR_INVAL;
3547 			goto out;
3548 		}
3549 		stp->ls_flags = (bits | NFSLCK_OPEN);
3550 		stp->ls_stateid.seqid++;
3551 		if ((nd->nd_flag & ND_NFSV41) != 0 &&
3552 		    stp->ls_stateid.seqid == 0)
3553 			stp->ls_stateid.seqid = 1;
3554 		NFSUNLOCKSTATE();
3555 	}
3556 
3557 	/*
3558 	 * If the client just confirmed its first open, write a timestamp
3559 	 * to the stable storage file.
3560 	 */
3561 	if (gotstate != 0) {
3562 		nfsrv_writestable(clidp, len, NFSNST_NEWSTATE, p);
3563 		nfsrv_backupstable();
3564 	}
3565 
3566 out:
3567 	free(clidp, M_TEMP);
3568 	NFSEXITCODE2(error, nd);
3569 	return (error);
3570 }
3571 
3572 /*
3573  * Delegation update. Does the purge and return.
3574  */
3575 int
3576 nfsrv_delegupdate(struct nfsrv_descript *nd, nfsquad_t clientid,
3577     nfsv4stateid_t *stateidp, vnode_t vp, int op, struct ucred *cred,
3578     NFSPROC_T *p, int *retwriteaccessp)
3579 {
3580 	struct nfsstate *stp;
3581 	struct nfsclient *clp;
3582 	int error = 0;
3583 	fhandle_t fh;
3584 
3585 	/*
3586 	 * Do a sanity check against the file handle for DelegReturn.
3587 	 */
3588 	if (vp) {
3589 		error = nfsvno_getfh(vp, &fh, p);
3590 		if (error)
3591 			goto out;
3592 	}
3593 	/*
3594 	 * Check for restart conditions (client and server).
3595 	 */
3596 	if (op == NFSV4OP_DELEGRETURN)
3597 		error = nfsrv_checkrestart(clientid, NFSLCK_DELEGRETURN,
3598 			stateidp, 0);
3599 	else
3600 		error = nfsrv_checkrestart(clientid, NFSLCK_DELEGPURGE,
3601 			stateidp, 0);
3602 
3603 	NFSLOCKSTATE();
3604 	/*
3605 	 * Get the open structure via clientid and stateid.
3606 	 */
3607 	if (!error)
3608 	    error = nfsrv_getclient(clientid, CLOPS_RENEW, &clp, NULL,
3609 		(nfsquad_t)((u_quad_t)0), 0, nd, p);
3610 	if (error) {
3611 		if (error == NFSERR_CBPATHDOWN)
3612 			error = 0;
3613 		if (error == NFSERR_STALECLIENTID && op == NFSV4OP_DELEGRETURN)
3614 			error = NFSERR_STALESTATEID;
3615 	}
3616 	if (!error && op == NFSV4OP_DELEGRETURN) {
3617 	    error = nfsrv_getstate(clp, stateidp, NFSLCK_DELEGRETURN, &stp);
3618 	    if (!error && stp->ls_stateid.seqid != stateidp->seqid &&
3619 		((nd->nd_flag & ND_NFSV41) == 0 || stateidp->seqid != 0))
3620 		error = NFSERR_OLDSTATEID;
3621 	}
3622 	/*
3623 	 * NFSERR_EXPIRED means that the state has gone away,
3624 	 * so Delegations have been purged. Just return ok.
3625 	 */
3626 	if (error == NFSERR_EXPIRED && op == NFSV4OP_DELEGPURGE) {
3627 		NFSUNLOCKSTATE();
3628 		error = 0;
3629 		goto out;
3630 	}
3631 	if (error) {
3632 		NFSUNLOCKSTATE();
3633 		goto out;
3634 	}
3635 
3636 	if (op == NFSV4OP_DELEGRETURN) {
3637 		if (NFSBCMP((caddr_t)&fh, (caddr_t)&stp->ls_lfp->lf_fh,
3638 		    sizeof (fhandle_t))) {
3639 			NFSUNLOCKSTATE();
3640 			error = NFSERR_BADSTATEID;
3641 			goto out;
3642 		}
3643 		if (retwriteaccessp != NULL) {
3644 			if ((stp->ls_flags & NFSLCK_DELEGWRITE) != 0)
3645 				*retwriteaccessp = 1;
3646 			else
3647 				*retwriteaccessp = 0;
3648 		}
3649 		nfsrv_freedeleg(stp);
3650 	} else {
3651 		nfsrv_freedeleglist(&clp->lc_olddeleg);
3652 	}
3653 	NFSUNLOCKSTATE();
3654 	error = 0;
3655 
3656 out:
3657 	NFSEXITCODE(error);
3658 	return (error);
3659 }
3660 
3661 /*
3662  * Release lock owner.
3663  */
3664 int
3665 nfsrv_releaselckown(struct nfsstate *new_stp, nfsquad_t clientid,
3666     NFSPROC_T *p)
3667 {
3668 	struct nfsstate *stp, *nstp, *openstp, *ownstp;
3669 	struct nfsclient *clp;
3670 	int error = 0;
3671 
3672 	/*
3673 	 * Check for restart conditions (client and server).
3674 	 */
3675 	error = nfsrv_checkrestart(clientid, new_stp->ls_flags,
3676 	    &new_stp->ls_stateid, 0);
3677 	if (error)
3678 		goto out;
3679 
3680 	NFSLOCKSTATE();
3681 	/*
3682 	 * Get the lock owner by name.
3683 	 */
3684 	error = nfsrv_getclient(clientid, CLOPS_RENEW, &clp, NULL,
3685 	    (nfsquad_t)((u_quad_t)0), 0, NULL, p);
3686 	if (error) {
3687 		NFSUNLOCKSTATE();
3688 		goto out;
3689 	}
3690 	LIST_FOREACH(ownstp, &clp->lc_open, ls_list) {
3691 	    LIST_FOREACH(openstp, &ownstp->ls_open, ls_list) {
3692 		stp = LIST_FIRST(&openstp->ls_open);
3693 		while (stp != LIST_END(&openstp->ls_open)) {
3694 		    nstp = LIST_NEXT(stp, ls_list);
3695 		    /*
3696 		     * If the owner matches, check for locks and
3697 		     * then free or return an error.
3698 		     */
3699 		    if (stp->ls_ownerlen == new_stp->ls_ownerlen &&
3700 			!NFSBCMP(stp->ls_owner, new_stp->ls_owner,
3701 			 stp->ls_ownerlen)){
3702 			if (LIST_EMPTY(&stp->ls_lock)) {
3703 			    nfsrv_freelockowner(stp, NULL, 0, p);
3704 			} else {
3705 			    NFSUNLOCKSTATE();
3706 			    error = NFSERR_LOCKSHELD;
3707 			    goto out;
3708 			}
3709 		    }
3710 		    stp = nstp;
3711 		}
3712 	    }
3713 	}
3714 	NFSUNLOCKSTATE();
3715 
3716 out:
3717 	NFSEXITCODE(error);
3718 	return (error);
3719 }
3720 
3721 /*
3722  * Get the file handle for a lock structure.
3723  */
3724 static int
3725 nfsrv_getlockfh(vnode_t vp, u_short flags, struct nfslockfile *new_lfp,
3726     fhandle_t *nfhp, NFSPROC_T *p)
3727 {
3728 	fhandle_t *fhp = NULL;
3729 	int error;
3730 
3731 	/*
3732 	 * For lock, use the new nfslock structure, otherwise just
3733 	 * a fhandle_t on the stack.
3734 	 */
3735 	if (flags & NFSLCK_OPEN) {
3736 		KASSERT(new_lfp != NULL, ("nfsrv_getlockfh: new_lfp NULL"));
3737 		fhp = &new_lfp->lf_fh;
3738 	} else if (nfhp) {
3739 		fhp = nfhp;
3740 	} else {
3741 		panic("nfsrv_getlockfh");
3742 	}
3743 	error = nfsvno_getfh(vp, fhp, p);
3744 	NFSEXITCODE(error);
3745 	return (error);
3746 }
3747 
3748 /*
3749  * Get an nfs lock structure. Allocate one, as required, and return a
3750  * pointer to it.
3751  * Returns an NFSERR_xxx upon failure or -1 to indicate no current lock.
3752  */
3753 static int
3754 nfsrv_getlockfile(u_short flags, struct nfslockfile **new_lfpp,
3755     struct nfslockfile **lfpp, fhandle_t *nfhp, int lockit)
3756 {
3757 	struct nfslockfile *lfp;
3758 	fhandle_t *fhp = NULL, *tfhp;
3759 	struct nfslockhashhead *hp;
3760 	struct nfslockfile *new_lfp = NULL;
3761 
3762 	/*
3763 	 * For lock, use the new nfslock structure, otherwise just
3764 	 * a fhandle_t on the stack.
3765 	 */
3766 	if (flags & NFSLCK_OPEN) {
3767 		new_lfp = *new_lfpp;
3768 		fhp = &new_lfp->lf_fh;
3769 	} else if (nfhp) {
3770 		fhp = nfhp;
3771 	} else {
3772 		panic("nfsrv_getlockfile");
3773 	}
3774 
3775 	hp = NFSLOCKHASH(fhp);
3776 	LIST_FOREACH(lfp, hp, lf_hash) {
3777 		tfhp = &lfp->lf_fh;
3778 		if (NFSVNO_CMPFH(fhp, tfhp)) {
3779 			if (lockit)
3780 				nfsrv_locklf(lfp);
3781 			*lfpp = lfp;
3782 			return (0);
3783 		}
3784 	}
3785 	if (!(flags & NFSLCK_OPEN))
3786 		return (-1);
3787 
3788 	/*
3789 	 * No match, so chain the new one into the list.
3790 	 */
3791 	LIST_INIT(&new_lfp->lf_open);
3792 	LIST_INIT(&new_lfp->lf_lock);
3793 	LIST_INIT(&new_lfp->lf_deleg);
3794 	LIST_INIT(&new_lfp->lf_locallock);
3795 	LIST_INIT(&new_lfp->lf_rollback);
3796 	new_lfp->lf_locallock_lck.nfslock_usecnt = 0;
3797 	new_lfp->lf_locallock_lck.nfslock_lock = 0;
3798 	new_lfp->lf_usecount = 0;
3799 	LIST_INSERT_HEAD(hp, new_lfp, lf_hash);
3800 	*lfpp = new_lfp;
3801 	*new_lfpp = NULL;
3802 	return (0);
3803 }
3804 
3805 /*
3806  * This function adds a nfslock lock structure to the list for the associated
3807  * nfsstate and nfslockfile structures. It will be inserted after the
3808  * entry pointed at by insert_lop.
3809  */
3810 static void
3811 nfsrv_insertlock(struct nfslock *new_lop, struct nfslock *insert_lop,
3812     struct nfsstate *stp, struct nfslockfile *lfp)
3813 {
3814 	struct nfslock *lop, *nlop;
3815 
3816 	new_lop->lo_stp = stp;
3817 	new_lop->lo_lfp = lfp;
3818 
3819 	if (stp != NULL) {
3820 		/* Insert in increasing lo_first order */
3821 		lop = LIST_FIRST(&lfp->lf_lock);
3822 		if (lop == LIST_END(&lfp->lf_lock) ||
3823 		    new_lop->lo_first <= lop->lo_first) {
3824 			LIST_INSERT_HEAD(&lfp->lf_lock, new_lop, lo_lckfile);
3825 		} else {
3826 			nlop = LIST_NEXT(lop, lo_lckfile);
3827 			while (nlop != LIST_END(&lfp->lf_lock) &&
3828 			       nlop->lo_first < new_lop->lo_first) {
3829 				lop = nlop;
3830 				nlop = LIST_NEXT(lop, lo_lckfile);
3831 			}
3832 			LIST_INSERT_AFTER(lop, new_lop, lo_lckfile);
3833 		}
3834 	} else {
3835 		new_lop->lo_lckfile.le_prev = NULL;	/* list not used */
3836 	}
3837 
3838 	/*
3839 	 * Insert after insert_lop, which is overloaded as stp or lfp for
3840 	 * an empty list.
3841 	 */
3842 	if (stp == NULL && (struct nfslockfile *)insert_lop == lfp)
3843 		LIST_INSERT_HEAD(&lfp->lf_locallock, new_lop, lo_lckowner);
3844 	else if ((struct nfsstate *)insert_lop == stp)
3845 		LIST_INSERT_HEAD(&stp->ls_lock, new_lop, lo_lckowner);
3846 	else
3847 		LIST_INSERT_AFTER(insert_lop, new_lop, lo_lckowner);
3848 	if (stp != NULL) {
3849 		nfsstatsv1.srvlocks++;
3850 		nfsrv_openpluslock++;
3851 	}
3852 }
3853 
3854 /*
3855  * This function updates the locking for a lock owner and given file. It
3856  * maintains a list of lock ranges ordered on increasing file offset that
3857  * are NFSLCK_READ or NFSLCK_WRITE and non-overlapping (aka POSIX style).
3858  * It always adds new_lop to the list and sometimes uses the one pointed
3859  * at by other_lopp.
3860  */
3861 static void
3862 nfsrv_updatelock(struct nfsstate *stp, struct nfslock **new_lopp,
3863     struct nfslock **other_lopp, struct nfslockfile *lfp)
3864 {
3865 	struct nfslock *new_lop = *new_lopp;
3866 	struct nfslock *lop, *tlop, *ilop;
3867 	struct nfslock *other_lop = *other_lopp;
3868 	int unlock = 0, myfile = 0;
3869 	u_int64_t tmp;
3870 
3871 	/*
3872 	 * Work down the list until the lock is merged.
3873 	 */
3874 	if (new_lop->lo_flags & NFSLCK_UNLOCK)
3875 		unlock = 1;
3876 	if (stp != NULL) {
3877 		ilop = (struct nfslock *)stp;
3878 		lop = LIST_FIRST(&stp->ls_lock);
3879 	} else {
3880 		ilop = (struct nfslock *)lfp;
3881 		lop = LIST_FIRST(&lfp->lf_locallock);
3882 	}
3883 	while (lop != NULL) {
3884 	    /*
3885 	     * Only check locks for this file that aren't before the start of
3886 	     * new lock's range.
3887 	     */
3888 	    if (lop->lo_lfp == lfp) {
3889 	      myfile = 1;
3890 	      if (lop->lo_end >= new_lop->lo_first) {
3891 		if (new_lop->lo_end < lop->lo_first) {
3892 			/*
3893 			 * If the new lock ends before the start of the
3894 			 * current lock's range, no merge, just insert
3895 			 * the new lock.
3896 			 */
3897 			break;
3898 		}
3899 		if (new_lop->lo_flags == lop->lo_flags ||
3900 		    (new_lop->lo_first <= lop->lo_first &&
3901 		     new_lop->lo_end >= lop->lo_end)) {
3902 			/*
3903 			 * This lock can be absorbed by the new lock/unlock.
3904 			 * This happens when it covers the entire range
3905 			 * of the old lock or is contiguous
3906 			 * with the old lock and is of the same type or an
3907 			 * unlock.
3908 			 */
3909 			if (lop->lo_first < new_lop->lo_first)
3910 				new_lop->lo_first = lop->lo_first;
3911 			if (lop->lo_end > new_lop->lo_end)
3912 				new_lop->lo_end = lop->lo_end;
3913 			tlop = lop;
3914 			lop = LIST_NEXT(lop, lo_lckowner);
3915 			nfsrv_freenfslock(tlop);
3916 			continue;
3917 		}
3918 
3919 		/*
3920 		 * All these cases are for contiguous locks that are not the
3921 		 * same type, so they can't be merged.
3922 		 */
3923 		if (new_lop->lo_first <= lop->lo_first) {
3924 			/*
3925 			 * This case is where the new lock overlaps with the
3926 			 * first part of the old lock. Move the start of the
3927 			 * old lock to just past the end of the new lock. The
3928 			 * new lock will be inserted in front of the old, since
3929 			 * ilop hasn't been updated. (We are done now.)
3930 			 */
3931 			lop->lo_first = new_lop->lo_end;
3932 			break;
3933 		}
3934 		if (new_lop->lo_end >= lop->lo_end) {
3935 			/*
3936 			 * This case is where the new lock overlaps with the
3937 			 * end of the old lock's range. Move the old lock's
3938 			 * end to just before the new lock's first and insert
3939 			 * the new lock after the old lock.
3940 			 * Might not be done yet, since the new lock could
3941 			 * overlap further locks with higher ranges.
3942 			 */
3943 			lop->lo_end = new_lop->lo_first;
3944 			ilop = lop;
3945 			lop = LIST_NEXT(lop, lo_lckowner);
3946 			continue;
3947 		}
3948 		/*
3949 		 * The final case is where the new lock's range is in the
3950 		 * middle of the current lock's and splits the current lock
3951 		 * up. Use *other_lopp to handle the second part of the
3952 		 * split old lock range. (We are done now.)
3953 		 * For unlock, we use new_lop as other_lop and tmp, since
3954 		 * other_lop and new_lop are the same for this case.
3955 		 * We noted the unlock case above, so we don't need
3956 		 * new_lop->lo_flags any longer.
3957 		 */
3958 		tmp = new_lop->lo_first;
3959 		if (other_lop == NULL) {
3960 			if (!unlock)
3961 				panic("nfsd srv update unlock");
3962 			other_lop = new_lop;
3963 			*new_lopp = NULL;
3964 		}
3965 		other_lop->lo_first = new_lop->lo_end;
3966 		other_lop->lo_end = lop->lo_end;
3967 		other_lop->lo_flags = lop->lo_flags;
3968 		other_lop->lo_stp = stp;
3969 		other_lop->lo_lfp = lfp;
3970 		lop->lo_end = tmp;
3971 		nfsrv_insertlock(other_lop, lop, stp, lfp);
3972 		*other_lopp = NULL;
3973 		ilop = lop;
3974 		break;
3975 	      }
3976 	    }
3977 	    ilop = lop;
3978 	    lop = LIST_NEXT(lop, lo_lckowner);
3979 	    if (myfile && (lop == NULL || lop->lo_lfp != lfp))
3980 		break;
3981 	}
3982 
3983 	/*
3984 	 * Insert the new lock in the list at the appropriate place.
3985 	 */
3986 	if (!unlock) {
3987 		nfsrv_insertlock(new_lop, ilop, stp, lfp);
3988 		*new_lopp = NULL;
3989 	}
3990 }
3991 
3992 /*
3993  * This function handles sequencing of locks, etc.
3994  * It returns an error that indicates what the caller should do.
3995  */
3996 static int
3997 nfsrv_checkseqid(struct nfsrv_descript *nd, u_int32_t seqid,
3998     struct nfsstate *stp, struct nfsrvcache *op)
3999 {
4000 	int error = 0;
4001 
4002 	if ((nd->nd_flag & ND_NFSV41) != 0)
4003 		/* NFSv4.1 ignores the open_seqid and lock_seqid. */
4004 		goto out;
4005 	if (op != nd->nd_rp)
4006 		panic("nfsrvstate checkseqid");
4007 	if (!(op->rc_flag & RC_INPROG))
4008 		panic("nfsrvstate not inprog");
4009 	if (stp->ls_op && stp->ls_op->rc_refcnt <= 0) {
4010 		printf("refcnt=%d\n", stp->ls_op->rc_refcnt);
4011 		panic("nfsrvstate op refcnt");
4012 	}
4013 	if ((stp->ls_seq + 1) == seqid) {
4014 		if (stp->ls_op)
4015 			nfsrvd_derefcache(stp->ls_op);
4016 		stp->ls_op = op;
4017 		nfsrvd_refcache(op);
4018 		stp->ls_seq = seqid;
4019 		goto out;
4020 	} else if (stp->ls_seq == seqid && stp->ls_op &&
4021 		op->rc_xid == stp->ls_op->rc_xid &&
4022 		op->rc_refcnt == 0 &&
4023 		op->rc_reqlen == stp->ls_op->rc_reqlen &&
4024 		op->rc_cksum == stp->ls_op->rc_cksum) {
4025 		if (stp->ls_op->rc_flag & RC_INPROG) {
4026 			error = NFSERR_DONTREPLY;
4027 			goto out;
4028 		}
4029 		nd->nd_rp = stp->ls_op;
4030 		nd->nd_rp->rc_flag |= RC_INPROG;
4031 		nfsrvd_delcache(op);
4032 		error = NFSERR_REPLYFROMCACHE;
4033 		goto out;
4034 	}
4035 	error = NFSERR_BADSEQID;
4036 
4037 out:
4038 	NFSEXITCODE2(error, nd);
4039 	return (error);
4040 }
4041 
4042 /*
4043  * Get the client ip address for callbacks. If the strings can't be parsed,
4044  * just set lc_program to 0 to indicate no callbacks are possible.
4045  * (For cases where the address can't be parsed or is 0.0.0.0.0.0, set
4046  *  the address to the client's transport address. This won't be used
4047  *  for callbacks, but can be printed out by nfsstats for info.)
4048  * Return error if the xdr can't be parsed, 0 otherwise.
4049  */
4050 int
4051 nfsrv_getclientipaddr(struct nfsrv_descript *nd, struct nfsclient *clp)
4052 {
4053 	u_int32_t *tl;
4054 	u_char *cp, *cp2;
4055 	int i, j, maxalen = 0, minalen = 0;
4056 	sa_family_t af;
4057 #ifdef INET
4058 	struct sockaddr_in *rin = NULL, *sin;
4059 #endif
4060 #ifdef INET6
4061 	struct sockaddr_in6 *rin6 = NULL, *sin6;
4062 #endif
4063 	u_char *addr;
4064 	int error = 0, cantparse = 0;
4065 	union {
4066 		in_addr_t ival;
4067 		u_char cval[4];
4068 	} ip;
4069 	union {
4070 		in_port_t sval;
4071 		u_char cval[2];
4072 	} port;
4073 
4074 	/* 8 is the maximum length of the port# string. */
4075 	addr = malloc(INET6_ADDRSTRLEN + 8, M_TEMP, M_WAITOK);
4076 	clp->lc_req.nr_client = NULL;
4077 	clp->lc_req.nr_lock = 0;
4078 	af = AF_UNSPEC;
4079 	NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
4080 	i = fxdr_unsigned(int, *tl);
4081 	if (i >= 3 && i <= 4) {
4082 		error = nfsrv_mtostr(nd, addr, i);
4083 		if (error)
4084 			goto nfsmout;
4085 #ifdef INET
4086 		if (!strcmp(addr, "tcp")) {
4087 			clp->lc_flags |= LCL_TCPCALLBACK;
4088 			clp->lc_req.nr_sotype = SOCK_STREAM;
4089 			clp->lc_req.nr_soproto = IPPROTO_TCP;
4090 			af = AF_INET;
4091 		} else if (!strcmp(addr, "udp")) {
4092 			clp->lc_req.nr_sotype = SOCK_DGRAM;
4093 			clp->lc_req.nr_soproto = IPPROTO_UDP;
4094 			af = AF_INET;
4095 		}
4096 #endif
4097 #ifdef INET6
4098 		if (af == AF_UNSPEC) {
4099 			if (!strcmp(addr, "tcp6")) {
4100 				clp->lc_flags |= LCL_TCPCALLBACK;
4101 				clp->lc_req.nr_sotype = SOCK_STREAM;
4102 				clp->lc_req.nr_soproto = IPPROTO_TCP;
4103 				af = AF_INET6;
4104 			} else if (!strcmp(addr, "udp6")) {
4105 				clp->lc_req.nr_sotype = SOCK_DGRAM;
4106 				clp->lc_req.nr_soproto = IPPROTO_UDP;
4107 				af = AF_INET6;
4108 			}
4109 		}
4110 #endif
4111 		if (af == AF_UNSPEC) {
4112 			cantparse = 1;
4113 		}
4114 	} else {
4115 		cantparse = 1;
4116 		if (i > 0) {
4117 			error = nfsm_advance(nd, NFSM_RNDUP(i), -1);
4118 			if (error)
4119 				goto nfsmout;
4120 		}
4121 	}
4122 	/*
4123 	 * The caller has allocated clp->lc_req.nr_nam to be large enough
4124 	 * for either AF_INET or AF_INET6 and zeroed out the contents.
4125 	 * maxalen is set to the maximum length of the host IP address string
4126 	 * plus 8 for the maximum length of the port#.
4127 	 * minalen is set to the minimum length of the host IP address string
4128 	 * plus 4 for the minimum length of the port#.
4129 	 * These lengths do not include NULL termination,
4130 	 * so INET[6]_ADDRSTRLEN - 1 is used in the calculations.
4131 	 */
4132 	switch (af) {
4133 #ifdef INET
4134 	case AF_INET:
4135 		rin = (struct sockaddr_in *)clp->lc_req.nr_nam;
4136 		rin->sin_family = AF_INET;
4137 		rin->sin_len = sizeof(struct sockaddr_in);
4138 		maxalen = INET_ADDRSTRLEN - 1 + 8;
4139 		minalen = 7 + 4;
4140 		break;
4141 #endif
4142 #ifdef INET6
4143 	case AF_INET6:
4144 		rin6 = (struct sockaddr_in6 *)clp->lc_req.nr_nam;
4145 		rin6->sin6_family = AF_INET6;
4146 		rin6->sin6_len = sizeof(struct sockaddr_in6);
4147 		maxalen = INET6_ADDRSTRLEN - 1 + 8;
4148 		minalen = 3 + 4;
4149 		break;
4150 #endif
4151 	}
4152 	NFSM_DISSECT(tl, u_int32_t *, NFSX_UNSIGNED);
4153 	i = fxdr_unsigned(int, *tl);
4154 	if (i < 0) {
4155 		error = NFSERR_BADXDR;
4156 		goto nfsmout;
4157 	} else if (i == 0) {
4158 		cantparse = 1;
4159 	} else if (!cantparse && i <= maxalen && i >= minalen) {
4160 		error = nfsrv_mtostr(nd, addr, i);
4161 		if (error)
4162 			goto nfsmout;
4163 
4164 		/*
4165 		 * Parse out the address fields. We expect 6 decimal numbers
4166 		 * separated by '.'s for AF_INET and two decimal numbers
4167 		 * preceeded by '.'s for AF_INET6.
4168 		 */
4169 		cp = NULL;
4170 		switch (af) {
4171 #ifdef INET6
4172 		/*
4173 		 * For AF_INET6, first parse the host address.
4174 		 */
4175 		case AF_INET6:
4176 			cp = strchr(addr, '.');
4177 			if (cp != NULL) {
4178 				*cp++ = '\0';
4179 				if (inet_pton(af, addr, &rin6->sin6_addr) == 1)
4180 					i = 4;
4181 				else {
4182 					cp = NULL;
4183 					cantparse = 1;
4184 				}
4185 			}
4186 			break;
4187 #endif
4188 #ifdef INET
4189 		case AF_INET:
4190 			cp = addr;
4191 			i = 0;
4192 			break;
4193 #endif
4194 		}
4195 		while (cp != NULL && *cp && i < 6) {
4196 			cp2 = cp;
4197 			while (*cp2 && *cp2 != '.')
4198 				cp2++;
4199 			if (*cp2)
4200 				*cp2++ = '\0';
4201 			else if (i != 5) {
4202 				cantparse = 1;
4203 				break;
4204 			}
4205 			j = nfsrv_getipnumber(cp);
4206 			if (j >= 0) {
4207 				if (i < 4)
4208 					ip.cval[3 - i] = j;
4209 				else
4210 					port.cval[5 - i] = j;
4211 			} else {
4212 				cantparse = 1;
4213 				break;
4214 			}
4215 			cp = cp2;
4216 			i++;
4217 		}
4218 		if (!cantparse) {
4219 			/*
4220 			 * The host address INADDR_ANY is (mis)used to indicate
4221 			 * "there is no valid callback address".
4222 			 */
4223 			switch (af) {
4224 #ifdef INET6
4225 			case AF_INET6:
4226 				if (!IN6_ARE_ADDR_EQUAL(&rin6->sin6_addr,
4227 				    &in6addr_any))
4228 					rin6->sin6_port = htons(port.sval);
4229 				else
4230 					cantparse = 1;
4231 				break;
4232 #endif
4233 #ifdef INET
4234 			case AF_INET:
4235 				if (ip.ival != INADDR_ANY) {
4236 					rin->sin_addr.s_addr = htonl(ip.ival);
4237 					rin->sin_port = htons(port.sval);
4238 				} else {
4239 					cantparse = 1;
4240 				}
4241 				break;
4242 #endif
4243 			}
4244 		}
4245 	} else {
4246 		cantparse = 1;
4247 		if (i > 0) {
4248 			error = nfsm_advance(nd, NFSM_RNDUP(i), -1);
4249 			if (error)
4250 				goto nfsmout;
4251 		}
4252 	}
4253 	if (cantparse) {
4254 		switch (nd->nd_nam->sa_family) {
4255 #ifdef INET
4256 		case AF_INET:
4257 			sin = (struct sockaddr_in *)nd->nd_nam;
4258 			rin = (struct sockaddr_in *)clp->lc_req.nr_nam;
4259 			rin->sin_family = AF_INET;
4260 			rin->sin_len = sizeof(struct sockaddr_in);
4261 			rin->sin_addr.s_addr = sin->sin_addr.s_addr;
4262 			rin->sin_port = 0x0;
4263 			break;
4264 #endif
4265 #ifdef INET6
4266 		case AF_INET6:
4267 			sin6 = (struct sockaddr_in6 *)nd->nd_nam;
4268 			rin6 = (struct sockaddr_in6 *)clp->lc_req.nr_nam;
4269 			rin6->sin6_family = AF_INET6;
4270 			rin6->sin6_len = sizeof(struct sockaddr_in6);
4271 			rin6->sin6_addr = sin6->sin6_addr;
4272 			rin6->sin6_port = 0x0;
4273 			break;
4274 #endif
4275 		}
4276 		clp->lc_program = 0;
4277 	}
4278 nfsmout:
4279 	free(addr, M_TEMP);
4280 	NFSEXITCODE2(error, nd);
4281 	return (error);
4282 }
4283 
4284 /*
4285  * Turn a string of up to three decimal digits into a number. Return -1 upon
4286  * error.
4287  */
4288 static int
4289 nfsrv_getipnumber(u_char *cp)
4290 {
4291 	int i = 0, j = 0;
4292 
4293 	while (*cp) {
4294 		if (j > 2 || *cp < '0' || *cp > '9')
4295 			return (-1);
4296 		i *= 10;
4297 		i += (*cp - '0');
4298 		cp++;
4299 		j++;
4300 	}
4301 	if (i < 256)
4302 		return (i);
4303 	return (-1);
4304 }
4305 
4306 /*
4307  * This function checks for restart conditions.
4308  */
4309 static int
4310 nfsrv_checkrestart(nfsquad_t clientid, u_int32_t flags,
4311     nfsv4stateid_t *stateidp, int specialid)
4312 {
4313 	int ret = 0;
4314 
4315 	/*
4316 	 * First check for a server restart. Open, LockT, ReleaseLockOwner
4317 	 * and DelegPurge have a clientid, the rest a stateid.
4318 	 */
4319 	if (flags &
4320 	    (NFSLCK_OPEN | NFSLCK_TEST | NFSLCK_RELEASE | NFSLCK_DELEGPURGE)) {
4321 		if (clientid.lval[0] != nfsrvboottime) {
4322 			ret = NFSERR_STALECLIENTID;
4323 			goto out;
4324 		}
4325 	} else if (stateidp->other[0] != nfsrvboottime &&
4326 		specialid == 0) {
4327 		ret = NFSERR_STALESTATEID;
4328 		goto out;
4329 	}
4330 
4331 	/*
4332 	 * Read, Write, Setattr and LockT can return NFSERR_GRACE and do
4333 	 * not use a lock/open owner seqid#, so the check can be done now.
4334 	 * (The others will be checked, as required, later.)
4335 	 */
4336 	if (!(flags & (NFSLCK_CHECK | NFSLCK_TEST)))
4337 		goto out;
4338 
4339 	NFSLOCKSTATE();
4340 	ret = nfsrv_checkgrace(NULL, NULL, flags);
4341 	NFSUNLOCKSTATE();
4342 
4343 out:
4344 	NFSEXITCODE(ret);
4345 	return (ret);
4346 }
4347 
4348 /*
4349  * Check for grace.
4350  */
4351 static int
4352 nfsrv_checkgrace(struct nfsrv_descript *nd, struct nfsclient *clp,
4353     u_int32_t flags)
4354 {
4355 	int error = 0, notreclaimed;
4356 	struct nfsrv_stable *sp;
4357 
4358 	if ((nfsrv_stablefirst.nsf_flags & (NFSNSF_UPDATEDONE |
4359 	     NFSNSF_GRACEOVER)) == 0) {
4360 		/*
4361 		 * First, check to see if all of the clients have done a
4362 		 * ReclaimComplete.  If so, grace can end now.
4363 		 */
4364 		notreclaimed = 0;
4365 		LIST_FOREACH(sp, &nfsrv_stablefirst.nsf_head, nst_list) {
4366 			if ((sp->nst_flag & NFSNST_RECLAIMED) == 0) {
4367 				notreclaimed = 1;
4368 				break;
4369 			}
4370 		}
4371 		if (notreclaimed == 0)
4372 			nfsrv_stablefirst.nsf_flags |= (NFSNSF_GRACEOVER |
4373 			    NFSNSF_NEEDLOCK);
4374 	}
4375 
4376 	if ((nfsrv_stablefirst.nsf_flags & NFSNSF_GRACEOVER) != 0) {
4377 		if (flags & NFSLCK_RECLAIM) {
4378 			error = NFSERR_NOGRACE;
4379 			goto out;
4380 		}
4381 	} else {
4382 		if (!(flags & NFSLCK_RECLAIM)) {
4383 			error = NFSERR_GRACE;
4384 			goto out;
4385 		}
4386 		if (nd != NULL && clp != NULL &&
4387 		    (nd->nd_flag & ND_NFSV41) != 0 &&
4388 		    (clp->lc_flags & LCL_RECLAIMCOMPLETE) != 0) {
4389 			error = NFSERR_NOGRACE;
4390 			goto out;
4391 		}
4392 
4393 		/*
4394 		 * If grace is almost over and we are still getting Reclaims,
4395 		 * extend grace a bit.
4396 		 */
4397 		if ((NFSD_MONOSEC + NFSRV_LEASEDELTA) >
4398 		    nfsrv_stablefirst.nsf_eograce)
4399 			nfsrv_stablefirst.nsf_eograce = NFSD_MONOSEC +
4400 				NFSRV_LEASEDELTA;
4401 	}
4402 
4403 out:
4404 	NFSEXITCODE(error);
4405 	return (error);
4406 }
4407 
4408 /*
4409  * Do a server callback.
4410  * The "trunc" argument is slightly overloaded and refers to different
4411  * boolean arguments for CBRECALL and CBLAYOUTRECALL.
4412  */
4413 static int
4414 nfsrv_docallback(struct nfsclient *clp, int procnum, nfsv4stateid_t *stateidp,
4415     int trunc, fhandle_t *fhp, struct nfsvattr *nap, nfsattrbit_t *attrbitp,
4416     int laytype, NFSPROC_T *p)
4417 {
4418 	struct mbuf *m;
4419 	u_int32_t *tl;
4420 	struct nfsrv_descript *nd;
4421 	struct ucred *cred;
4422 	int error = 0;
4423 	u_int32_t callback;
4424 	struct nfsdsession *sep = NULL;
4425 	uint64_t tval;
4426 	bool dotls;
4427 
4428 	nd = malloc(sizeof(*nd), M_TEMP, M_WAITOK | M_ZERO);
4429 	cred = newnfs_getcred();
4430 	NFSLOCKSTATE();	/* mostly for lc_cbref++ */
4431 	if (clp->lc_flags & LCL_NEEDSCONFIRM) {
4432 		NFSUNLOCKSTATE();
4433 		panic("docallb");
4434 	}
4435 	clp->lc_cbref++;
4436 
4437 	/*
4438 	 * Fill the callback program# and version into the request
4439 	 * structure for newnfs_connect() to use.
4440 	 */
4441 	clp->lc_req.nr_prog = clp->lc_program;
4442 #ifdef notnow
4443 	if ((clp->lc_flags & LCL_NFSV41) != 0)
4444 		clp->lc_req.nr_vers = NFSV41_CBVERS;
4445 	else
4446 #endif
4447 		clp->lc_req.nr_vers = NFSV4_CBVERS;
4448 
4449 	/*
4450 	 * First, fill in some of the fields of nd and cr.
4451 	 */
4452 	nd->nd_flag = ND_NFSV4;
4453 	if (clp->lc_flags & LCL_GSS)
4454 		nd->nd_flag |= ND_KERBV;
4455 	if ((clp->lc_flags & LCL_NFSV41) != 0)
4456 		nd->nd_flag |= ND_NFSV41;
4457 	if ((clp->lc_flags & LCL_NFSV42) != 0)
4458 		nd->nd_flag |= ND_NFSV42;
4459 	nd->nd_repstat = 0;
4460 	cred->cr_uid = clp->lc_uid;
4461 	cred->cr_gid = clp->lc_gid;
4462 	callback = clp->lc_callback;
4463 	NFSUNLOCKSTATE();
4464 	cred->cr_ngroups = 1;
4465 
4466 	/*
4467 	 * Get the first mbuf for the request.
4468 	 */
4469 	MGET(m, M_WAITOK, MT_DATA);
4470 	m->m_len = 0;
4471 	nd->nd_mreq = nd->nd_mb = m;
4472 	nd->nd_bpos = mtod(m, caddr_t);
4473 
4474 	/*
4475 	 * and build the callback request.
4476 	 */
4477 	if (procnum == NFSV4OP_CBGETATTR) {
4478 		nd->nd_procnum = NFSV4PROC_CBCOMPOUND;
4479 		error = nfsrv_cbcallargs(nd, clp, callback, NFSV4OP_CBGETATTR,
4480 		    "CB Getattr", &sep);
4481 		if (error != 0) {
4482 			m_freem(nd->nd_mreq);
4483 			goto errout;
4484 		}
4485 		(void)nfsm_fhtom(nd, (u_int8_t *)fhp, NFSX_MYFH, 0);
4486 		(void)nfsrv_putattrbit(nd, attrbitp);
4487 	} else if (procnum == NFSV4OP_CBRECALL) {
4488 		nd->nd_procnum = NFSV4PROC_CBCOMPOUND;
4489 		error = nfsrv_cbcallargs(nd, clp, callback, NFSV4OP_CBRECALL,
4490 		    "CB Recall", &sep);
4491 		if (error != 0) {
4492 			m_freem(nd->nd_mreq);
4493 			goto errout;
4494 		}
4495 		NFSM_BUILD(tl, u_int32_t *, NFSX_UNSIGNED + NFSX_STATEID);
4496 		*tl++ = txdr_unsigned(stateidp->seqid);
4497 		NFSBCOPY((caddr_t)stateidp->other, (caddr_t)tl,
4498 		    NFSX_STATEIDOTHER);
4499 		tl += (NFSX_STATEIDOTHER / NFSX_UNSIGNED);
4500 		if (trunc)
4501 			*tl = newnfs_true;
4502 		else
4503 			*tl = newnfs_false;
4504 		(void)nfsm_fhtom(nd, (u_int8_t *)fhp, NFSX_MYFH, 0);
4505 	} else if (procnum == NFSV4OP_CBLAYOUTRECALL) {
4506 		NFSD_DEBUG(4, "docallback layout recall\n");
4507 		nd->nd_procnum = NFSV4PROC_CBCOMPOUND;
4508 		error = nfsrv_cbcallargs(nd, clp, callback,
4509 		    NFSV4OP_CBLAYOUTRECALL, "CB Reclayout", &sep);
4510 		NFSD_DEBUG(4, "aft cbcallargs=%d\n", error);
4511 		if (error != 0) {
4512 			m_freem(nd->nd_mreq);
4513 			goto errout;
4514 		}
4515 		NFSM_BUILD(tl, u_int32_t *, 4 * NFSX_UNSIGNED);
4516 		*tl++ = txdr_unsigned(laytype);
4517 		*tl++ = txdr_unsigned(NFSLAYOUTIOMODE_ANY);
4518 		if (trunc)
4519 			*tl++ = newnfs_true;
4520 		else
4521 			*tl++ = newnfs_false;
4522 		*tl = txdr_unsigned(NFSV4LAYOUTRET_FILE);
4523 		nfsm_fhtom(nd, (uint8_t *)fhp, NFSX_MYFH, 0);
4524 		NFSM_BUILD(tl, u_int32_t *, 2 * NFSX_HYPER + NFSX_STATEID);
4525 		tval = 0;
4526 		txdr_hyper(tval, tl); tl += 2;
4527 		tval = UINT64_MAX;
4528 		txdr_hyper(tval, tl); tl += 2;
4529 		*tl++ = txdr_unsigned(stateidp->seqid);
4530 		NFSBCOPY(stateidp->other, tl, NFSX_STATEIDOTHER);
4531 		tl += (NFSX_STATEIDOTHER / NFSX_UNSIGNED);
4532 		NFSD_DEBUG(4, "aft args\n");
4533 	} else if (procnum == NFSV4PROC_CBNULL) {
4534 		nd->nd_procnum = NFSV4PROC_CBNULL;
4535 		if ((clp->lc_flags & LCL_NFSV41) != 0) {
4536 			error = nfsv4_getcbsession(clp, &sep);
4537 			if (error != 0) {
4538 				m_freem(nd->nd_mreq);
4539 				goto errout;
4540 			}
4541 		}
4542 	} else {
4543 		error = NFSERR_SERVERFAULT;
4544 		m_freem(nd->nd_mreq);
4545 		goto errout;
4546 	}
4547 
4548 	/*
4549 	 * Call newnfs_connect(), as required, and then newnfs_request().
4550 	 */
4551 	dotls = false;
4552 	if ((clp->lc_flags & LCL_TLSCB) != 0)
4553 		dotls = true;
4554 	(void) newnfs_sndlock(&clp->lc_req.nr_lock);
4555 	if (clp->lc_req.nr_client == NULL) {
4556 		if ((clp->lc_flags & LCL_NFSV41) != 0) {
4557 			error = ECONNREFUSED;
4558 			nfsrv_freesession(sep, NULL);
4559 		} else if (nd->nd_procnum == NFSV4PROC_CBNULL)
4560 			error = newnfs_connect(NULL, &clp->lc_req, cred,
4561 			    NULL, 1, dotls);
4562 		else
4563 			error = newnfs_connect(NULL, &clp->lc_req, cred,
4564 			    NULL, 3, dotls);
4565 	}
4566 	newnfs_sndunlock(&clp->lc_req.nr_lock);
4567 	NFSD_DEBUG(4, "aft sndunlock=%d\n", error);
4568 	if (!error) {
4569 		if ((nd->nd_flag & ND_NFSV41) != 0) {
4570 			KASSERT(sep != NULL, ("sep NULL"));
4571 			if (sep->sess_cbsess.nfsess_xprt != NULL)
4572 				error = newnfs_request(nd, NULL, clp,
4573 				    &clp->lc_req, NULL, NULL, cred,
4574 				    clp->lc_program, clp->lc_req.nr_vers, NULL,
4575 				    1, NULL, &sep->sess_cbsess);
4576 			else {
4577 				/*
4578 				 * This should probably never occur, but if a
4579 				 * client somehow does an RPC without a
4580 				 * SequenceID Op that causes a callback just
4581 				 * after the nfsd threads have been terminated
4582 				 * and restared we could conceivably get here
4583 				 * without a backchannel xprt.
4584 				 */
4585 				printf("nfsrv_docallback: no xprt\n");
4586 				error = ECONNREFUSED;
4587 			}
4588 			NFSD_DEBUG(4, "aft newnfs_request=%d\n", error);
4589 			nfsrv_freesession(sep, NULL);
4590 		} else
4591 			error = newnfs_request(nd, NULL, clp, &clp->lc_req,
4592 			    NULL, NULL, cred, clp->lc_program,
4593 			    clp->lc_req.nr_vers, NULL, 1, NULL, NULL);
4594 	}
4595 errout:
4596 	NFSFREECRED(cred);
4597 
4598 	/*
4599 	 * If error is set here, the Callback path isn't working
4600 	 * properly, so twiddle the appropriate LCL_ flags.
4601 	 * (nd_repstat != 0 indicates the Callback path is working,
4602 	 *  but the callback failed on the client.)
4603 	 */
4604 	if (error) {
4605 		/*
4606 		 * Mark the callback pathway down, which disabled issuing
4607 		 * of delegations and gets Renew to return NFSERR_CBPATHDOWN.
4608 		 */
4609 		NFSLOCKSTATE();
4610 		clp->lc_flags |= LCL_CBDOWN;
4611 		NFSUNLOCKSTATE();
4612 	} else {
4613 		/*
4614 		 * Callback worked. If the callback path was down, disable
4615 		 * callbacks, so no more delegations will be issued. (This
4616 		 * is done on the assumption that the callback pathway is
4617 		 * flakey.)
4618 		 */
4619 		NFSLOCKSTATE();
4620 		if (clp->lc_flags & LCL_CBDOWN)
4621 			clp->lc_flags &= ~(LCL_CBDOWN | LCL_CALLBACKSON);
4622 		NFSUNLOCKSTATE();
4623 		if (nd->nd_repstat) {
4624 			error = nd->nd_repstat;
4625 			NFSD_DEBUG(1, "nfsrv_docallback op=%d err=%d\n",
4626 			    procnum, error);
4627 		} else if (error == 0 && procnum == NFSV4OP_CBGETATTR)
4628 			error = nfsv4_loadattr(nd, NULL, nap, NULL, NULL, 0,
4629 			    NULL, NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL,
4630 			    p, NULL);
4631 		m_freem(nd->nd_mrep);
4632 	}
4633 	NFSLOCKSTATE();
4634 	clp->lc_cbref--;
4635 	if ((clp->lc_flags & LCL_WAKEUPWANTED) && clp->lc_cbref == 0) {
4636 		clp->lc_flags &= ~LCL_WAKEUPWANTED;
4637 		wakeup(clp);
4638 	}
4639 	NFSUNLOCKSTATE();
4640 
4641 	free(nd, M_TEMP);
4642 	NFSEXITCODE(error);
4643 	return (error);
4644 }
4645 
4646 /*
4647  * Set up the compound RPC for the callback.
4648  */
4649 static int
4650 nfsrv_cbcallargs(struct nfsrv_descript *nd, struct nfsclient *clp,
4651     uint32_t callback, int op, const char *optag, struct nfsdsession **sepp)
4652 {
4653 	uint32_t *tl;
4654 	int error, len;
4655 
4656 	len = strlen(optag);
4657 	(void)nfsm_strtom(nd, optag, len);
4658 	NFSM_BUILD(tl, uint32_t *, 4 * NFSX_UNSIGNED);
4659 	if ((nd->nd_flag & ND_NFSV41) != 0) {
4660 		if ((nd->nd_flag & ND_NFSV42) != 0)
4661 			*tl++ = txdr_unsigned(NFSV42_MINORVERSION);
4662 		else
4663 			*tl++ = txdr_unsigned(NFSV41_MINORVERSION);
4664 		*tl++ = txdr_unsigned(callback);
4665 		*tl++ = txdr_unsigned(2);
4666 		*tl = txdr_unsigned(NFSV4OP_CBSEQUENCE);
4667 		error = nfsv4_setcbsequence(nd, clp, 1, sepp);
4668 		if (error != 0)
4669 			return (error);
4670 		NFSM_BUILD(tl, u_int32_t *, NFSX_UNSIGNED);
4671 		*tl = txdr_unsigned(op);
4672 	} else {
4673 		*tl++ = txdr_unsigned(NFSV4_MINORVERSION);
4674 		*tl++ = txdr_unsigned(callback);
4675 		*tl++ = txdr_unsigned(1);
4676 		*tl = txdr_unsigned(op);
4677 	}
4678 	return (0);
4679 }
4680 
4681 /*
4682  * Return the next index# for a clientid. Mostly just increment and return
4683  * the next one, but... if the 32bit unsigned does actually wrap around,
4684  * it should be rebooted.
4685  * At an average rate of one new client per second, it will wrap around in
4686  * approximately 136 years. (I think the server will have been shut
4687  * down or rebooted before then.)
4688  */
4689 static u_int32_t
4690 nfsrv_nextclientindex(void)
4691 {
4692 	static u_int32_t client_index = 0;
4693 
4694 	client_index++;
4695 	if (client_index != 0)
4696 		return (client_index);
4697 
4698 	printf("%s: out of clientids\n", __func__);
4699 	return (client_index);
4700 }
4701 
4702 /*
4703  * Return the next index# for a stateid. Mostly just increment and return
4704  * the next one, but... if the 32bit unsigned does actually wrap around
4705  * (will a BSD server stay up that long?), find
4706  * new start and end values.
4707  */
4708 static u_int32_t
4709 nfsrv_nextstateindex(struct nfsclient *clp)
4710 {
4711 	struct nfsstate *stp;
4712 	int i;
4713 	u_int32_t canuse, min_index, max_index;
4714 
4715 	if (!(clp->lc_flags & LCL_INDEXNOTOK)) {
4716 		clp->lc_stateindex++;
4717 		if (clp->lc_stateindex != clp->lc_statemaxindex)
4718 			return (clp->lc_stateindex);
4719 	}
4720 
4721 	/*
4722 	 * Yuck, we've hit the end.
4723 	 * Look for a new min and max.
4724 	 */
4725 	min_index = 0;
4726 	max_index = 0xffffffff;
4727 	for (i = 0; i < nfsrv_statehashsize; i++) {
4728 	    LIST_FOREACH(stp, &clp->lc_stateid[i], ls_hash) {
4729 		if (stp->ls_stateid.other[2] > 0x80000000) {
4730 		    if (stp->ls_stateid.other[2] < max_index)
4731 			max_index = stp->ls_stateid.other[2];
4732 		} else {
4733 		    if (stp->ls_stateid.other[2] > min_index)
4734 			min_index = stp->ls_stateid.other[2];
4735 		}
4736 	    }
4737 	}
4738 
4739 	/*
4740 	 * Yikes, highly unlikely, but I'll handle it anyhow.
4741 	 */
4742 	if (min_index == 0x80000000 && max_index == 0x80000001) {
4743 	    canuse = 0;
4744 	    /*
4745 	     * Loop around until we find an unused entry. Return that
4746 	     * and set LCL_INDEXNOTOK, so the search will continue next time.
4747 	     * (This is one of those rare cases where a goto is the
4748 	     *  cleanest way to code the loop.)
4749 	     */
4750 tryagain:
4751 	    for (i = 0; i < nfsrv_statehashsize; i++) {
4752 		LIST_FOREACH(stp, &clp->lc_stateid[i], ls_hash) {
4753 		    if (stp->ls_stateid.other[2] == canuse) {
4754 			canuse++;
4755 			goto tryagain;
4756 		    }
4757 		}
4758 	    }
4759 	    clp->lc_flags |= LCL_INDEXNOTOK;
4760 	    return (canuse);
4761 	}
4762 
4763 	/*
4764 	 * Ok to start again from min + 1.
4765 	 */
4766 	clp->lc_stateindex = min_index + 1;
4767 	clp->lc_statemaxindex = max_index;
4768 	clp->lc_flags &= ~LCL_INDEXNOTOK;
4769 	return (clp->lc_stateindex);
4770 }
4771 
4772 /*
4773  * The following functions handle the stable storage file that deals with
4774  * the edge conditions described in RFC3530 Sec. 8.6.3.
4775  * The file is as follows:
4776  * - a single record at the beginning that has the lease time of the
4777  *   previous server instance (before the last reboot) and the nfsrvboottime
4778  *   values for the previous server boots.
4779  *   These previous boot times are used to ensure that the current
4780  *   nfsrvboottime does not, somehow, get set to a previous one.
4781  *   (This is important so that Stale ClientIDs and StateIDs can
4782  *    be recognized.)
4783  *   The number of previous nfsvrboottime values precedes the list.
4784  * - followed by some number of appended records with:
4785  *   - client id string
4786  *   - flag that indicates it is a record revoking state via lease
4787  *     expiration or similar
4788  *     OR has successfully acquired state.
4789  * These structures vary in length, with the client string at the end, up
4790  * to NFSV4_OPAQUELIMIT in size.
4791  *
4792  * At the end of the grace period, the file is truncated, the first
4793  * record is rewritten with updated information and any acquired state
4794  * records for successful reclaims of state are written.
4795  *
4796  * Subsequent records are appended when the first state is issued to
4797  * a client and when state is revoked for a client.
4798  *
4799  * When reading the file in, state issued records that come later in
4800  * the file override older ones, since the append log is in cronological order.
4801  * If, for some reason, the file can't be read, the grace period is
4802  * immediately terminated and all reclaims get NFSERR_NOGRACE.
4803  */
4804 
4805 /*
4806  * Read in the stable storage file. Called by nfssvc() before the nfsd
4807  * processes start servicing requests.
4808  */
4809 void
4810 nfsrv_setupstable(NFSPROC_T *p)
4811 {
4812 	struct nfsrv_stablefirst *sf = &nfsrv_stablefirst;
4813 	struct nfsrv_stable *sp, *nsp;
4814 	struct nfst_rec *tsp;
4815 	int error, i, tryagain;
4816 	off_t off = 0;
4817 	ssize_t aresid, len;
4818 
4819 	/*
4820 	 * If NFSNSF_UPDATEDONE is set, this is a restart of the nfsds without
4821 	 * a reboot, so state has not been lost.
4822 	 */
4823 	if (sf->nsf_flags & NFSNSF_UPDATEDONE)
4824 		return;
4825 	/*
4826 	 * Set Grace over just until the file reads successfully.
4827 	 */
4828 	nfsrvboottime = time_second;
4829 	LIST_INIT(&sf->nsf_head);
4830 	sf->nsf_flags = (NFSNSF_GRACEOVER | NFSNSF_NEEDLOCK);
4831 	sf->nsf_eograce = NFSD_MONOSEC + NFSRV_LEASEDELTA;
4832 	if (sf->nsf_fp == NULL)
4833 		return;
4834 	error = NFSD_RDWR(UIO_READ, NFSFPVNODE(sf->nsf_fp),
4835 	    (caddr_t)&sf->nsf_rec, sizeof (struct nfsf_rec), off, UIO_SYSSPACE,
4836 	    0, NFSFPCRED(sf->nsf_fp), &aresid, p);
4837 	if (error || aresid || sf->nsf_numboots == 0 ||
4838 		sf->nsf_numboots > NFSNSF_MAXNUMBOOTS)
4839 		return;
4840 
4841 	/*
4842 	 * Now, read in the boottimes.
4843 	 */
4844 	sf->nsf_bootvals = (time_t *)malloc((sf->nsf_numboots + 1) *
4845 		sizeof (time_t), M_TEMP, M_WAITOK);
4846 	off = sizeof (struct nfsf_rec);
4847 	error = NFSD_RDWR(UIO_READ, NFSFPVNODE(sf->nsf_fp),
4848 	    (caddr_t)sf->nsf_bootvals, sf->nsf_numboots * sizeof (time_t), off,
4849 	    UIO_SYSSPACE, 0, NFSFPCRED(sf->nsf_fp), &aresid, p);
4850 	if (error || aresid) {
4851 		free(sf->nsf_bootvals, M_TEMP);
4852 		sf->nsf_bootvals = NULL;
4853 		return;
4854 	}
4855 
4856 	/*
4857 	 * Make sure this nfsrvboottime is different from all recorded
4858 	 * previous ones.
4859 	 */
4860 	do {
4861 		tryagain = 0;
4862 		for (i = 0; i < sf->nsf_numboots; i++) {
4863 			if (nfsrvboottime == sf->nsf_bootvals[i]) {
4864 				nfsrvboottime++;
4865 				tryagain = 1;
4866 				break;
4867 			}
4868 		}
4869 	} while (tryagain);
4870 
4871 	sf->nsf_flags |= NFSNSF_OK;
4872 	off += (sf->nsf_numboots * sizeof (time_t));
4873 
4874 	/*
4875 	 * Read through the file, building a list of records for grace
4876 	 * checking.
4877 	 * Each record is between sizeof (struct nfst_rec) and
4878 	 * sizeof (struct nfst_rec) + NFSV4_OPAQUELIMIT - 1
4879 	 * and is actually sizeof (struct nfst_rec) + nst_len - 1.
4880 	 */
4881 	tsp = (struct nfst_rec *)malloc(sizeof (struct nfst_rec) +
4882 		NFSV4_OPAQUELIMIT - 1, M_TEMP, M_WAITOK);
4883 	do {
4884 	    error = NFSD_RDWR(UIO_READ, NFSFPVNODE(sf->nsf_fp),
4885 	        (caddr_t)tsp, sizeof (struct nfst_rec) + NFSV4_OPAQUELIMIT - 1,
4886 	        off, UIO_SYSSPACE, 0, NFSFPCRED(sf->nsf_fp), &aresid, p);
4887 	    len = (sizeof (struct nfst_rec) + NFSV4_OPAQUELIMIT - 1) - aresid;
4888 	    if (error || (len > 0 && (len < sizeof (struct nfst_rec) ||
4889 		len < (sizeof (struct nfst_rec) + tsp->len - 1)))) {
4890 		/*
4891 		 * Yuck, the file has been corrupted, so just return
4892 		 * after clearing out any restart state, so the grace period
4893 		 * is over.
4894 		 */
4895 		LIST_FOREACH_SAFE(sp, &sf->nsf_head, nst_list, nsp) {
4896 			LIST_REMOVE(sp, nst_list);
4897 			free(sp, M_TEMP);
4898 		}
4899 		free(tsp, M_TEMP);
4900 		sf->nsf_flags &= ~NFSNSF_OK;
4901 		free(sf->nsf_bootvals, M_TEMP);
4902 		sf->nsf_bootvals = NULL;
4903 		return;
4904 	    }
4905 	    if (len > 0) {
4906 		off += sizeof (struct nfst_rec) + tsp->len - 1;
4907 		/*
4908 		 * Search the list for a matching client.
4909 		 */
4910 		LIST_FOREACH(sp, &sf->nsf_head, nst_list) {
4911 			if (tsp->len == sp->nst_len &&
4912 			    !NFSBCMP(tsp->client, sp->nst_client, tsp->len))
4913 				break;
4914 		}
4915 		if (sp == LIST_END(&sf->nsf_head)) {
4916 			sp = (struct nfsrv_stable *)malloc(tsp->len +
4917 				sizeof (struct nfsrv_stable) - 1, M_TEMP,
4918 				M_WAITOK);
4919 			NFSBCOPY((caddr_t)tsp, (caddr_t)&sp->nst_rec,
4920 				sizeof (struct nfst_rec) + tsp->len - 1);
4921 			LIST_INSERT_HEAD(&sf->nsf_head, sp, nst_list);
4922 		} else {
4923 			if (tsp->flag == NFSNST_REVOKE)
4924 				sp->nst_flag |= NFSNST_REVOKE;
4925 			else
4926 				/*
4927 				 * A subsequent timestamp indicates the client
4928 				 * did a setclientid/confirm and any previous
4929 				 * revoke is no longer relevant.
4930 				 */
4931 				sp->nst_flag &= ~NFSNST_REVOKE;
4932 		}
4933 	    }
4934 	} while (len > 0);
4935 	free(tsp, M_TEMP);
4936 	sf->nsf_flags = NFSNSF_OK;
4937 	sf->nsf_eograce = NFSD_MONOSEC + sf->nsf_lease +
4938 		NFSRV_LEASEDELTA;
4939 }
4940 
4941 /*
4942  * Update the stable storage file, now that the grace period is over.
4943  */
4944 void
4945 nfsrv_updatestable(NFSPROC_T *p)
4946 {
4947 	struct nfsrv_stablefirst *sf = &nfsrv_stablefirst;
4948 	struct nfsrv_stable *sp, *nsp;
4949 	int i;
4950 	struct nfsvattr nva;
4951 	vnode_t vp;
4952 #if defined(__FreeBSD_version) && (__FreeBSD_version >= 500000)
4953 	mount_t mp = NULL;
4954 #endif
4955 	int error;
4956 
4957 	if (sf->nsf_fp == NULL || (sf->nsf_flags & NFSNSF_UPDATEDONE))
4958 		return;
4959 	sf->nsf_flags |= NFSNSF_UPDATEDONE;
4960 	/*
4961 	 * Ok, we need to rewrite the stable storage file.
4962 	 * - truncate to 0 length
4963 	 * - write the new first structure
4964 	 * - loop through the data structures, writing out any that
4965 	 *   have timestamps older than the old boot
4966 	 */
4967 	if (sf->nsf_bootvals) {
4968 		sf->nsf_numboots++;
4969 		for (i = sf->nsf_numboots - 2; i >= 0; i--)
4970 			sf->nsf_bootvals[i + 1] = sf->nsf_bootvals[i];
4971 	} else {
4972 		sf->nsf_numboots = 1;
4973 		sf->nsf_bootvals = (time_t *)malloc(sizeof (time_t),
4974 			M_TEMP, M_WAITOK);
4975 	}
4976 	sf->nsf_bootvals[0] = nfsrvboottime;
4977 	sf->nsf_lease = nfsrv_lease;
4978 	NFSVNO_ATTRINIT(&nva);
4979 	NFSVNO_SETATTRVAL(&nva, size, 0);
4980 	vp = NFSFPVNODE(sf->nsf_fp);
4981 	vn_start_write(vp, &mp, V_WAIT);
4982 	if (NFSVOPLOCK(vp, LK_EXCLUSIVE) == 0) {
4983 		error = nfsvno_setattr(vp, &nva, NFSFPCRED(sf->nsf_fp), p,
4984 		    NULL);
4985 		NFSVOPUNLOCK(vp);
4986 	} else
4987 		error = EPERM;
4988 	vn_finished_write(mp);
4989 	if (!error)
4990 	    error = NFSD_RDWR(UIO_WRITE, vp,
4991 		(caddr_t)&sf->nsf_rec, sizeof (struct nfsf_rec), (off_t)0,
4992 		UIO_SYSSPACE, IO_SYNC, NFSFPCRED(sf->nsf_fp), NULL, p);
4993 	if (!error)
4994 	    error = NFSD_RDWR(UIO_WRITE, vp,
4995 		(caddr_t)sf->nsf_bootvals,
4996 		sf->nsf_numboots * sizeof (time_t),
4997 		(off_t)(sizeof (struct nfsf_rec)),
4998 		UIO_SYSSPACE, IO_SYNC, NFSFPCRED(sf->nsf_fp), NULL, p);
4999 	free(sf->nsf_bootvals, M_TEMP);
5000 	sf->nsf_bootvals = NULL;
5001 	if (error) {
5002 		sf->nsf_flags &= ~NFSNSF_OK;
5003 		printf("EEK! Can't write NfsV4 stable storage file\n");
5004 		return;
5005 	}
5006 	sf->nsf_flags |= NFSNSF_OK;
5007 
5008 	/*
5009 	 * Loop through the list and write out timestamp records for
5010 	 * any clients that successfully reclaimed state.
5011 	 */
5012 	LIST_FOREACH_SAFE(sp, &sf->nsf_head, nst_list, nsp) {
5013 		if (sp->nst_flag & NFSNST_GOTSTATE) {
5014 			nfsrv_writestable(sp->nst_client, sp->nst_len,
5015 				NFSNST_NEWSTATE, p);
5016 			sp->nst_clp->lc_flags |= LCL_STAMPEDSTABLE;
5017 		}
5018 		LIST_REMOVE(sp, nst_list);
5019 		free(sp, M_TEMP);
5020 	}
5021 	nfsrv_backupstable();
5022 }
5023 
5024 /*
5025  * Append a record to the stable storage file.
5026  */
5027 void
5028 nfsrv_writestable(u_char *client, int len, int flag, NFSPROC_T *p)
5029 {
5030 	struct nfsrv_stablefirst *sf = &nfsrv_stablefirst;
5031 	struct nfst_rec *sp;
5032 	int error;
5033 
5034 	if (!(sf->nsf_flags & NFSNSF_OK) || sf->nsf_fp == NULL)
5035 		return;
5036 	sp = (struct nfst_rec *)malloc(sizeof (struct nfst_rec) +
5037 		len - 1, M_TEMP, M_WAITOK);
5038 	sp->len = len;
5039 	NFSBCOPY(client, sp->client, len);
5040 	sp->flag = flag;
5041 	error = NFSD_RDWR(UIO_WRITE, NFSFPVNODE(sf->nsf_fp),
5042 	    (caddr_t)sp, sizeof (struct nfst_rec) + len - 1, (off_t)0,
5043 	    UIO_SYSSPACE, (IO_SYNC | IO_APPEND), NFSFPCRED(sf->nsf_fp), NULL, p);
5044 	free(sp, M_TEMP);
5045 	if (error) {
5046 		sf->nsf_flags &= ~NFSNSF_OK;
5047 		printf("EEK! Can't write NfsV4 stable storage file\n");
5048 	}
5049 }
5050 
5051 /*
5052  * This function is called during the grace period to mark a client
5053  * that successfully reclaimed state.
5054  */
5055 static void
5056 nfsrv_markstable(struct nfsclient *clp)
5057 {
5058 	struct nfsrv_stable *sp;
5059 
5060 	/*
5061 	 * First find the client structure.
5062 	 */
5063 	LIST_FOREACH(sp, &nfsrv_stablefirst.nsf_head, nst_list) {
5064 		if (sp->nst_len == clp->lc_idlen &&
5065 		    !NFSBCMP(sp->nst_client, clp->lc_id, sp->nst_len))
5066 			break;
5067 	}
5068 	if (sp == LIST_END(&nfsrv_stablefirst.nsf_head))
5069 		return;
5070 
5071 	/*
5072 	 * Now, just mark it and set the nfsclient back pointer.
5073 	 */
5074 	sp->nst_flag |= NFSNST_GOTSTATE;
5075 	sp->nst_clp = clp;
5076 }
5077 
5078 /*
5079  * This function is called when a NFSv4.1 client does a ReclaimComplete.
5080  * Very similar to nfsrv_markstable(), except for the flag being set.
5081  */
5082 static void
5083 nfsrv_markreclaim(struct nfsclient *clp)
5084 {
5085 	struct nfsrv_stable *sp;
5086 
5087 	/*
5088 	 * First find the client structure.
5089 	 */
5090 	LIST_FOREACH(sp, &nfsrv_stablefirst.nsf_head, nst_list) {
5091 		if (sp->nst_len == clp->lc_idlen &&
5092 		    !NFSBCMP(sp->nst_client, clp->lc_id, sp->nst_len))
5093 			break;
5094 	}
5095 	if (sp == LIST_END(&nfsrv_stablefirst.nsf_head))
5096 		return;
5097 
5098 	/*
5099 	 * Now, just set the flag.
5100 	 */
5101 	sp->nst_flag |= NFSNST_RECLAIMED;
5102 }
5103 
5104 /*
5105  * This function is called for a reclaim, to see if it gets grace.
5106  * It returns 0 if a reclaim is allowed, 1 otherwise.
5107  */
5108 static int
5109 nfsrv_checkstable(struct nfsclient *clp)
5110 {
5111 	struct nfsrv_stable *sp;
5112 
5113 	/*
5114 	 * First, find the entry for the client.
5115 	 */
5116 	LIST_FOREACH(sp, &nfsrv_stablefirst.nsf_head, nst_list) {
5117 		if (sp->nst_len == clp->lc_idlen &&
5118 		    !NFSBCMP(sp->nst_client, clp->lc_id, sp->nst_len))
5119 			break;
5120 	}
5121 
5122 	/*
5123 	 * If not in the list, state was revoked or no state was issued
5124 	 * since the previous reboot, a reclaim is denied.
5125 	 */
5126 	if (sp == LIST_END(&nfsrv_stablefirst.nsf_head) ||
5127 	    (sp->nst_flag & NFSNST_REVOKE) ||
5128 	    !(nfsrv_stablefirst.nsf_flags & NFSNSF_OK))
5129 		return (1);
5130 	return (0);
5131 }
5132 
5133 /*
5134  * Test for and try to clear out a conflicting client. This is called by
5135  * nfsrv_lockctrl() and nfsrv_openctrl() when conflicts with other clients
5136  * a found.
5137  * The trick here is that it can't revoke a conflicting client with an
5138  * expired lease unless it holds the v4root lock, so...
5139  * If no v4root lock, get the lock and return 1 to indicate "try again".
5140  * Return 0 to indicate the conflict can't be revoked and 1 to indicate
5141  * the revocation worked and the conflicting client is "bye, bye", so it
5142  * can be tried again.
5143  * Return 2 to indicate that the vnode is VIRF_DOOMED after NFSVOPLOCK().
5144  * Unlocks State before a non-zero value is returned.
5145  */
5146 static int
5147 nfsrv_clientconflict(struct nfsclient *clp, int *haslockp, vnode_t vp,
5148     NFSPROC_T *p)
5149 {
5150 	int gotlock, lktype = 0;
5151 
5152 	/*
5153 	 * If lease hasn't expired, we can't fix it.
5154 	 */
5155 	if (clp->lc_expiry >= NFSD_MONOSEC ||
5156 	    !(nfsrv_stablefirst.nsf_flags & NFSNSF_UPDATEDONE))
5157 		return (0);
5158 	if (*haslockp == 0) {
5159 		NFSUNLOCKSTATE();
5160 		if (vp != NULL) {
5161 			lktype = NFSVOPISLOCKED(vp);
5162 			NFSVOPUNLOCK(vp);
5163 		}
5164 		NFSLOCKV4ROOTMUTEX();
5165 		nfsv4_relref(&nfsv4rootfs_lock);
5166 		do {
5167 			gotlock = nfsv4_lock(&nfsv4rootfs_lock, 1, NULL,
5168 			    NFSV4ROOTLOCKMUTEXPTR, NULL);
5169 		} while (!gotlock);
5170 		NFSUNLOCKV4ROOTMUTEX();
5171 		*haslockp = 1;
5172 		if (vp != NULL) {
5173 			NFSVOPLOCK(vp, lktype | LK_RETRY);
5174 			if (VN_IS_DOOMED(vp))
5175 				return (2);
5176 		}
5177 		return (1);
5178 	}
5179 	NFSUNLOCKSTATE();
5180 
5181 	/*
5182 	 * Ok, we can expire the conflicting client.
5183 	 */
5184 	nfsrv_writestable(clp->lc_id, clp->lc_idlen, NFSNST_REVOKE, p);
5185 	nfsrv_backupstable();
5186 	nfsrv_cleanclient(clp, p);
5187 	nfsrv_freedeleglist(&clp->lc_deleg);
5188 	nfsrv_freedeleglist(&clp->lc_olddeleg);
5189 	LIST_REMOVE(clp, lc_hash);
5190 	nfsrv_zapclient(clp, p);
5191 	return (1);
5192 }
5193 
5194 /*
5195  * Resolve a delegation conflict.
5196  * Returns 0 to indicate the conflict was resolved without sleeping.
5197  * Return -1 to indicate that the caller should check for conflicts again.
5198  * Return > 0 for an error that should be returned, normally NFSERR_DELAY.
5199  *
5200  * Also, manipulate the nfsv4root_lock, as required. It isn't changed
5201  * for a return of 0, since there was no sleep and it could be required
5202  * later. It is released for a return of NFSERR_DELAY, since the caller
5203  * will return that error. It is released when a sleep was done waiting
5204  * for the delegation to be returned or expire (so that other nfsds can
5205  * handle ops). Then, it must be acquired for the write to stable storage.
5206  * (This function is somewhat similar to nfsrv_clientconflict(), but
5207  *  the semantics differ in a couple of subtle ways. The return of 0
5208  *  indicates the conflict was resolved without sleeping here, not
5209  *  that the conflict can't be resolved and the handling of nfsv4root_lock
5210  *  differs, as noted above.)
5211  * Unlocks State before returning a non-zero value.
5212  */
5213 static int
5214 nfsrv_delegconflict(struct nfsstate *stp, int *haslockp, NFSPROC_T *p,
5215     vnode_t vp)
5216 {
5217 	struct nfsclient *clp = stp->ls_clp;
5218 	int gotlock, error, lktype = 0, retrycnt, zapped_clp;
5219 	nfsv4stateid_t tstateid;
5220 	fhandle_t tfh;
5221 
5222 	/*
5223 	 * If the conflict is with an old delegation...
5224 	 */
5225 	if (stp->ls_flags & NFSLCK_OLDDELEG) {
5226 		/*
5227 		 * You can delete it, if it has expired.
5228 		 */
5229 		if (clp->lc_delegtime < NFSD_MONOSEC) {
5230 			nfsrv_freedeleg(stp);
5231 			NFSUNLOCKSTATE();
5232 			error = -1;
5233 			goto out;
5234 		}
5235 		NFSUNLOCKSTATE();
5236 		/*
5237 		 * During this delay, the old delegation could expire or it
5238 		 * could be recovered by the client via an Open with
5239 		 * CLAIM_DELEGATE_PREV.
5240 		 * Release the nfsv4root_lock, if held.
5241 		 */
5242 		if (*haslockp) {
5243 			*haslockp = 0;
5244 			NFSLOCKV4ROOTMUTEX();
5245 			nfsv4_unlock(&nfsv4rootfs_lock, 1);
5246 			NFSUNLOCKV4ROOTMUTEX();
5247 		}
5248 		error = NFSERR_DELAY;
5249 		goto out;
5250 	}
5251 
5252 	/*
5253 	 * It's a current delegation, so:
5254 	 * - check to see if the delegation has expired
5255 	 *   - if so, get the v4root lock and then expire it
5256 	 */
5257 	if (!(stp->ls_flags & NFSLCK_DELEGRECALL)) {
5258 		/*
5259 		 * - do a recall callback, since not yet done
5260 		 * For now, never allow truncate to be set. To use
5261 		 * truncate safely, it must be guaranteed that the
5262 		 * Remove, Rename or Setattr with size of 0 will
5263 		 * succeed and that would require major changes to
5264 		 * the VFS/Vnode OPs.
5265 		 * Set the expiry time large enough so that it won't expire
5266 		 * until after the callback, then set it correctly, once
5267 		 * the callback is done. (The delegation will now time
5268 		 * out whether or not the Recall worked ok. The timeout
5269 		 * will be extended when ops are done on the delegation
5270 		 * stateid, up to the timelimit.)
5271 		 */
5272 		stp->ls_delegtime = NFSD_MONOSEC + (2 * nfsrv_lease) +
5273 		    NFSRV_LEASEDELTA;
5274 		stp->ls_delegtimelimit = NFSD_MONOSEC + (6 * nfsrv_lease) +
5275 		    NFSRV_LEASEDELTA;
5276 		stp->ls_flags |= NFSLCK_DELEGRECALL;
5277 
5278 		/*
5279 		 * Loop NFSRV_CBRETRYCNT times while the CBRecall replies
5280 		 * NFSERR_BADSTATEID or NFSERR_BADHANDLE. This is done
5281 		 * in order to try and avoid a race that could happen
5282 		 * when a CBRecall request passed the Open reply with
5283 		 * the delegation in it when transitting the network.
5284 		 * Since nfsrv_docallback will sleep, don't use stp after
5285 		 * the call.
5286 		 */
5287 		NFSBCOPY((caddr_t)&stp->ls_stateid, (caddr_t)&tstateid,
5288 		    sizeof (tstateid));
5289 		NFSBCOPY((caddr_t)&stp->ls_lfp->lf_fh, (caddr_t)&tfh,
5290 		    sizeof (tfh));
5291 		NFSUNLOCKSTATE();
5292 		if (*haslockp) {
5293 			*haslockp = 0;
5294 			NFSLOCKV4ROOTMUTEX();
5295 			nfsv4_unlock(&nfsv4rootfs_lock, 1);
5296 			NFSUNLOCKV4ROOTMUTEX();
5297 		}
5298 		retrycnt = 0;
5299 		do {
5300 		    error = nfsrv_docallback(clp, NFSV4OP_CBRECALL,
5301 			&tstateid, 0, &tfh, NULL, NULL, 0, p);
5302 		    retrycnt++;
5303 		} while ((error == NFSERR_BADSTATEID ||
5304 		    error == NFSERR_BADHANDLE) && retrycnt < NFSV4_CBRETRYCNT);
5305 		error = NFSERR_DELAY;
5306 		goto out;
5307 	}
5308 
5309 	if (clp->lc_expiry >= NFSD_MONOSEC &&
5310 	    stp->ls_delegtime >= NFSD_MONOSEC) {
5311 		NFSUNLOCKSTATE();
5312 		/*
5313 		 * A recall has been done, but it has not yet expired.
5314 		 * So, RETURN_DELAY.
5315 		 */
5316 		if (*haslockp) {
5317 			*haslockp = 0;
5318 			NFSLOCKV4ROOTMUTEX();
5319 			nfsv4_unlock(&nfsv4rootfs_lock, 1);
5320 			NFSUNLOCKV4ROOTMUTEX();
5321 		}
5322 		error = NFSERR_DELAY;
5323 		goto out;
5324 	}
5325 
5326 	/*
5327 	 * If we don't yet have the lock, just get it and then return,
5328 	 * since we need that before deleting expired state, such as
5329 	 * this delegation.
5330 	 * When getting the lock, unlock the vnode, so other nfsds that
5331 	 * are in progress, won't get stuck waiting for the vnode lock.
5332 	 */
5333 	if (*haslockp == 0) {
5334 		NFSUNLOCKSTATE();
5335 		if (vp != NULL) {
5336 			lktype = NFSVOPISLOCKED(vp);
5337 			NFSVOPUNLOCK(vp);
5338 		}
5339 		NFSLOCKV4ROOTMUTEX();
5340 		nfsv4_relref(&nfsv4rootfs_lock);
5341 		do {
5342 			gotlock = nfsv4_lock(&nfsv4rootfs_lock, 1, NULL,
5343 			    NFSV4ROOTLOCKMUTEXPTR, NULL);
5344 		} while (!gotlock);
5345 		NFSUNLOCKV4ROOTMUTEX();
5346 		*haslockp = 1;
5347 		if (vp != NULL) {
5348 			NFSVOPLOCK(vp, lktype | LK_RETRY);
5349 			if (VN_IS_DOOMED(vp)) {
5350 				*haslockp = 0;
5351 				NFSLOCKV4ROOTMUTEX();
5352 				nfsv4_unlock(&nfsv4rootfs_lock, 1);
5353 				NFSUNLOCKV4ROOTMUTEX();
5354 				error = NFSERR_PERM;
5355 				goto out;
5356 			}
5357 		}
5358 		error = -1;
5359 		goto out;
5360 	}
5361 
5362 	NFSUNLOCKSTATE();
5363 	/*
5364 	 * Ok, we can delete the expired delegation.
5365 	 * First, write the Revoke record to stable storage and then
5366 	 * clear out the conflict.
5367 	 * Since all other nfsd threads are now blocked, we can safely
5368 	 * sleep without the state changing.
5369 	 */
5370 	nfsrv_writestable(clp->lc_id, clp->lc_idlen, NFSNST_REVOKE, p);
5371 	nfsrv_backupstable();
5372 	if (clp->lc_expiry < NFSD_MONOSEC) {
5373 		nfsrv_cleanclient(clp, p);
5374 		nfsrv_freedeleglist(&clp->lc_deleg);
5375 		nfsrv_freedeleglist(&clp->lc_olddeleg);
5376 		LIST_REMOVE(clp, lc_hash);
5377 		zapped_clp = 1;
5378 	} else {
5379 		nfsrv_freedeleg(stp);
5380 		zapped_clp = 0;
5381 	}
5382 	if (zapped_clp)
5383 		nfsrv_zapclient(clp, p);
5384 	error = -1;
5385 
5386 out:
5387 	NFSEXITCODE(error);
5388 	return (error);
5389 }
5390 
5391 /*
5392  * Check for a remove allowed, if remove is set to 1 and get rid of
5393  * delegations.
5394  */
5395 int
5396 nfsrv_checkremove(vnode_t vp, int remove, struct nfsrv_descript *nd,
5397     nfsquad_t clientid, NFSPROC_T *p)
5398 {
5399 	struct nfsclient *clp;
5400 	struct nfsstate *stp;
5401 	struct nfslockfile *lfp;
5402 	int error, haslock = 0;
5403 	fhandle_t nfh;
5404 
5405 	clp = NULL;
5406 	/*
5407 	 * First, get the lock file structure.
5408 	 * (A return of -1 means no associated state, so remove ok.)
5409 	 */
5410 	error = nfsrv_getlockfh(vp, NFSLCK_CHECK, NULL, &nfh, p);
5411 tryagain:
5412 	NFSLOCKSTATE();
5413 	if (error == 0 && clientid.qval != 0)
5414 		error = nfsrv_getclient(clientid, CLOPS_RENEW, &clp, NULL,
5415 		    (nfsquad_t)((u_quad_t)0), 0, nd, p);
5416 	if (!error)
5417 		error = nfsrv_getlockfile(NFSLCK_CHECK, NULL, &lfp, &nfh, 0);
5418 	if (error) {
5419 		NFSUNLOCKSTATE();
5420 		if (haslock) {
5421 			NFSLOCKV4ROOTMUTEX();
5422 			nfsv4_unlock(&nfsv4rootfs_lock, 1);
5423 			NFSUNLOCKV4ROOTMUTEX();
5424 		}
5425 		if (error == -1)
5426 			error = 0;
5427 		goto out;
5428 	}
5429 
5430 	/*
5431 	 * Now, we must Recall any delegations.
5432 	 */
5433 	error = nfsrv_cleandeleg(vp, lfp, clp, &haslock, p);
5434 	if (error) {
5435 		/*
5436 		 * nfsrv_cleandeleg() unlocks state for non-zero
5437 		 * return.
5438 		 */
5439 		if (error == -1)
5440 			goto tryagain;
5441 		if (haslock) {
5442 			NFSLOCKV4ROOTMUTEX();
5443 			nfsv4_unlock(&nfsv4rootfs_lock, 1);
5444 			NFSUNLOCKV4ROOTMUTEX();
5445 		}
5446 		goto out;
5447 	}
5448 
5449 	/*
5450 	 * Now, look for a conflicting open share.
5451 	 */
5452 	if (remove) {
5453 		/*
5454 		 * If the entry in the directory was the last reference to the
5455 		 * corresponding filesystem object, the object can be destroyed
5456 		 * */
5457 		if(lfp->lf_usecount>1)
5458 			LIST_FOREACH(stp, &lfp->lf_open, ls_file) {
5459 				if (stp->ls_flags & NFSLCK_WRITEDENY) {
5460 					error = NFSERR_FILEOPEN;
5461 					break;
5462 				}
5463 			}
5464 	}
5465 
5466 	NFSUNLOCKSTATE();
5467 	if (haslock) {
5468 		NFSLOCKV4ROOTMUTEX();
5469 		nfsv4_unlock(&nfsv4rootfs_lock, 1);
5470 		NFSUNLOCKV4ROOTMUTEX();
5471 	}
5472 
5473 out:
5474 	NFSEXITCODE(error);
5475 	return (error);
5476 }
5477 
5478 /*
5479  * Clear out all delegations for the file referred to by lfp.
5480  * May return NFSERR_DELAY, if there will be a delay waiting for
5481  * delegations to expire.
5482  * Returns -1 to indicate it slept while recalling a delegation.
5483  * This function has the side effect of deleting the nfslockfile structure,
5484  * if it no longer has associated state and didn't have to sleep.
5485  * Unlocks State before a non-zero value is returned.
5486  */
5487 static int
5488 nfsrv_cleandeleg(vnode_t vp, struct nfslockfile *lfp,
5489     struct nfsclient *clp, int *haslockp, NFSPROC_T *p)
5490 {
5491 	struct nfsstate *stp, *nstp;
5492 	int ret = 0;
5493 
5494 	stp = LIST_FIRST(&lfp->lf_deleg);
5495 	while (stp != LIST_END(&lfp->lf_deleg)) {
5496 		nstp = LIST_NEXT(stp, ls_file);
5497 		if (stp->ls_clp != clp) {
5498 			ret = nfsrv_delegconflict(stp, haslockp, p, vp);
5499 			if (ret) {
5500 				/*
5501 				 * nfsrv_delegconflict() unlocks state
5502 				 * when it returns non-zero.
5503 				 */
5504 				goto out;
5505 			}
5506 		}
5507 		stp = nstp;
5508 	}
5509 out:
5510 	NFSEXITCODE(ret);
5511 	return (ret);
5512 }
5513 
5514 /*
5515  * There are certain operations that, when being done outside of NFSv4,
5516  * require that any NFSv4 delegation for the file be recalled.
5517  * This function is to be called for those cases:
5518  * VOP_RENAME() - When a delegation is being recalled for any reason,
5519  *	the client may have to do Opens against the server, using the file's
5520  *	final component name. If the file has been renamed on the server,
5521  *	that component name will be incorrect and the Open will fail.
5522  * VOP_REMOVE() - Theoretically, a client could Open a file after it has
5523  *	been removed on the server, if there is a delegation issued to
5524  *	that client for the file. I say "theoretically" since clients
5525  *	normally do an Access Op before the Open and that Access Op will
5526  *	fail with ESTALE. Note that NFSv2 and 3 don't even do Opens, so
5527  *	they will detect the file's removal in the same manner. (There is
5528  *	one case where RFC3530 allows a client to do an Open without first
5529  *	doing an Access Op, which is passage of a check against the ACE
5530  *	returned with a Write delegation, but current practice is to ignore
5531  *	the ACE and always do an Access Op.)
5532  *	Since the functions can only be called with an unlocked vnode, this
5533  *	can't be done at this time.
5534  * VOP_ADVLOCK() - When a client holds a delegation, it can issue byte range
5535  *	locks locally in the client, which are not visible to the server. To
5536  *	deal with this, issuing of delegations for a vnode must be disabled
5537  *	and all delegations for the vnode recalled. This is done via the
5538  *	second function, using the VV_DISABLEDELEG vflag on the vnode.
5539  */
5540 void
5541 nfsd_recalldelegation(vnode_t vp, NFSPROC_T *p)
5542 {
5543 	time_t starttime;
5544 	int error;
5545 
5546 	/*
5547 	 * First, check to see if the server is currently running and it has
5548 	 * been called for a regular file when issuing delegations.
5549 	 */
5550 	if (newnfs_numnfsd == 0 || vp->v_type != VREG ||
5551 	    nfsrv_issuedelegs == 0)
5552 		return;
5553 
5554 	KASSERT((NFSVOPISLOCKED(vp) != LK_EXCLUSIVE), ("vp %p is locked", vp));
5555 	/*
5556 	 * First, get a reference on the nfsv4rootfs_lock so that an
5557 	 * exclusive lock cannot be acquired by another thread.
5558 	 */
5559 	NFSLOCKV4ROOTMUTEX();
5560 	nfsv4_getref(&nfsv4rootfs_lock, NULL, NFSV4ROOTLOCKMUTEXPTR, NULL);
5561 	NFSUNLOCKV4ROOTMUTEX();
5562 
5563 	/*
5564 	 * Now, call nfsrv_checkremove() in a loop while it returns
5565 	 * NFSERR_DELAY. Return upon any other error or when timed out.
5566 	 */
5567 	starttime = NFSD_MONOSEC;
5568 	do {
5569 		if (NFSVOPLOCK(vp, LK_EXCLUSIVE) == 0) {
5570 			error = nfsrv_checkremove(vp, 0, NULL,
5571 			    (nfsquad_t)((u_quad_t)0), p);
5572 			NFSVOPUNLOCK(vp);
5573 		} else
5574 			error = EPERM;
5575 		if (error == NFSERR_DELAY) {
5576 			if (NFSD_MONOSEC - starttime > NFS_REMOVETIMEO)
5577 				break;
5578 			/* Sleep for a short period of time */
5579 			(void) nfs_catnap(PZERO, 0, "nfsremove");
5580 		}
5581 	} while (error == NFSERR_DELAY);
5582 	NFSLOCKV4ROOTMUTEX();
5583 	nfsv4_relref(&nfsv4rootfs_lock);
5584 	NFSUNLOCKV4ROOTMUTEX();
5585 }
5586 
5587 void
5588 nfsd_disabledelegation(vnode_t vp, NFSPROC_T *p)
5589 {
5590 
5591 #ifdef VV_DISABLEDELEG
5592 	/*
5593 	 * First, flag issuance of delegations disabled.
5594 	 */
5595 	atomic_set_long(&vp->v_vflag, VV_DISABLEDELEG);
5596 #endif
5597 
5598 	/*
5599 	 * Then call nfsd_recalldelegation() to get rid of all extant
5600 	 * delegations.
5601 	 */
5602 	nfsd_recalldelegation(vp, p);
5603 }
5604 
5605 /*
5606  * Check for conflicting locks, etc. and then get rid of delegations.
5607  * (At one point I thought that I should get rid of delegations for any
5608  *  Setattr, since it could potentially disallow the I/O op (read or write)
5609  *  allowed by the delegation. However, Setattr Ops that aren't changing
5610  *  the size get a stateid of all 0s, so you can't tell if it is a delegation
5611  *  for the same client or a different one, so I decided to only get rid
5612  *  of delegations for other clients when the size is being changed.)
5613  * In general, a Setattr can disable NFS I/O Ops that are outstanding, such
5614  * as Write backs, even if there is no delegation, so it really isn't any
5615  * different?)
5616  */
5617 int
5618 nfsrv_checksetattr(vnode_t vp, struct nfsrv_descript *nd,
5619     nfsv4stateid_t *stateidp, struct nfsvattr *nvap, nfsattrbit_t *attrbitp,
5620     struct nfsexstuff *exp, NFSPROC_T *p)
5621 {
5622 	struct nfsstate st, *stp = &st;
5623 	struct nfslock lo, *lop = &lo;
5624 	int error = 0;
5625 	nfsquad_t clientid;
5626 
5627 	if (NFSISSET_ATTRBIT(attrbitp, NFSATTRBIT_SIZE)) {
5628 		stp->ls_flags = (NFSLCK_CHECK | NFSLCK_WRITEACCESS);
5629 		lop->lo_first = nvap->na_size;
5630 	} else {
5631 		stp->ls_flags = 0;
5632 		lop->lo_first = 0;
5633 	}
5634 	if (NFSISSET_ATTRBIT(attrbitp, NFSATTRBIT_OWNER) ||
5635 	    NFSISSET_ATTRBIT(attrbitp, NFSATTRBIT_OWNERGROUP) ||
5636 	    NFSISSET_ATTRBIT(attrbitp, NFSATTRBIT_MODE) ||
5637 	    NFSISSET_ATTRBIT(attrbitp, NFSATTRBIT_ACL))
5638 		stp->ls_flags |= NFSLCK_SETATTR;
5639 	if (stp->ls_flags == 0)
5640 		goto out;
5641 	lop->lo_end = NFS64BITSSET;
5642 	lop->lo_flags = NFSLCK_WRITE;
5643 	stp->ls_ownerlen = 0;
5644 	stp->ls_op = NULL;
5645 	stp->ls_uid = nd->nd_cred->cr_uid;
5646 	stp->ls_stateid.seqid = stateidp->seqid;
5647 	clientid.lval[0] = stp->ls_stateid.other[0] = stateidp->other[0];
5648 	clientid.lval[1] = stp->ls_stateid.other[1] = stateidp->other[1];
5649 	stp->ls_stateid.other[2] = stateidp->other[2];
5650 	error = nfsrv_lockctrl(vp, &stp, &lop, NULL, clientid,
5651 	    stateidp, exp, nd, p);
5652 
5653 out:
5654 	NFSEXITCODE2(error, nd);
5655 	return (error);
5656 }
5657 
5658 /*
5659  * Check for a write delegation and do a CBGETATTR if there is one, updating
5660  * the attributes, as required.
5661  * Should I return an error if I can't get the attributes? (For now, I'll
5662  * just return ok.
5663  */
5664 int
5665 nfsrv_checkgetattr(struct nfsrv_descript *nd, vnode_t vp,
5666     struct nfsvattr *nvap, nfsattrbit_t *attrbitp, NFSPROC_T *p)
5667 {
5668 	struct nfsstate *stp;
5669 	struct nfslockfile *lfp;
5670 	struct nfsclient *clp;
5671 	struct nfsvattr nva;
5672 	fhandle_t nfh;
5673 	int error = 0;
5674 	nfsattrbit_t cbbits;
5675 	u_quad_t delegfilerev;
5676 
5677 	NFSCBGETATTR_ATTRBIT(attrbitp, &cbbits);
5678 	if (!NFSNONZERO_ATTRBIT(&cbbits))
5679 		goto out;
5680 	if (nfsrv_writedelegcnt == 0)
5681 		goto out;
5682 
5683 	/*
5684 	 * Get the lock file structure.
5685 	 * (A return of -1 means no associated state, so return ok.)
5686 	 */
5687 	error = nfsrv_getlockfh(vp, NFSLCK_CHECK, NULL, &nfh, p);
5688 	NFSLOCKSTATE();
5689 	if (!error)
5690 		error = nfsrv_getlockfile(NFSLCK_CHECK, NULL, &lfp, &nfh, 0);
5691 	if (error) {
5692 		NFSUNLOCKSTATE();
5693 		if (error == -1)
5694 			error = 0;
5695 		goto out;
5696 	}
5697 
5698 	/*
5699 	 * Now, look for a write delegation.
5700 	 */
5701 	LIST_FOREACH(stp, &lfp->lf_deleg, ls_file) {
5702 		if (stp->ls_flags & NFSLCK_DELEGWRITE)
5703 			break;
5704 	}
5705 	if (stp == LIST_END(&lfp->lf_deleg)) {
5706 		NFSUNLOCKSTATE();
5707 		goto out;
5708 	}
5709 	clp = stp->ls_clp;
5710 
5711 	/* If the clientid is not confirmed, ignore the delegation. */
5712 	if (clp->lc_flags & LCL_NEEDSCONFIRM) {
5713 		NFSUNLOCKSTATE();
5714 		goto out;
5715 	}
5716 
5717 	delegfilerev = stp->ls_filerev;
5718 	/*
5719 	 * If the Write delegation was issued as a part of this Compound RPC
5720 	 * or if we have an Implied Clientid (used in a previous Op in this
5721 	 * compound) and it is the client the delegation was issued to,
5722 	 * just return ok.
5723 	 * I also assume that it is from the same client iff the network
5724 	 * host IP address is the same as the callback address. (Not
5725 	 * exactly correct by the RFC, but avoids a lot of Getattr
5726 	 * callbacks.)
5727 	 */
5728 	if (nd->nd_compref == stp->ls_compref ||
5729 	    ((nd->nd_flag & ND_IMPLIEDCLID) &&
5730 	     clp->lc_clientid.qval == nd->nd_clientid.qval) ||
5731 	     nfsaddr2_match(clp->lc_req.nr_nam, nd->nd_nam)) {
5732 		NFSUNLOCKSTATE();
5733 		goto out;
5734 	}
5735 
5736 	/*
5737 	 * We are now done with the delegation state structure,
5738 	 * so the statelock can be released and we can now tsleep().
5739 	 */
5740 
5741 	/*
5742 	 * Now, we must do the CB Getattr callback, to see if Change or Size
5743 	 * has changed.
5744 	 */
5745 	if (clp->lc_expiry >= NFSD_MONOSEC) {
5746 		NFSUNLOCKSTATE();
5747 		NFSVNO_ATTRINIT(&nva);
5748 		nva.na_filerev = NFS64BITSSET;
5749 		error = nfsrv_docallback(clp, NFSV4OP_CBGETATTR, NULL,
5750 		    0, &nfh, &nva, &cbbits, 0, p);
5751 		if (!error) {
5752 			if ((nva.na_filerev != NFS64BITSSET &&
5753 			    nva.na_filerev > delegfilerev) ||
5754 			    (NFSVNO_ISSETSIZE(&nva) &&
5755 			     nva.na_size != nvap->na_size)) {
5756 				error = nfsvno_updfilerev(vp, nvap, nd, p);
5757 				if (NFSVNO_ISSETSIZE(&nva))
5758 					nvap->na_size = nva.na_size;
5759 			}
5760 		} else
5761 			error = 0;	/* Ignore callback errors for now. */
5762 	} else {
5763 		NFSUNLOCKSTATE();
5764 	}
5765 
5766 out:
5767 	NFSEXITCODE2(error, nd);
5768 	return (error);
5769 }
5770 
5771 /*
5772  * This function looks for openowners that haven't had any opens for
5773  * a while and throws them away. Called by an nfsd when NFSNSF_NOOPENS
5774  * is set.
5775  */
5776 void
5777 nfsrv_throwawayopens(NFSPROC_T *p)
5778 {
5779 	struct nfsclient *clp, *nclp;
5780 	struct nfsstate *stp, *nstp;
5781 	int i;
5782 
5783 	NFSLOCKSTATE();
5784 	nfsrv_stablefirst.nsf_flags &= ~NFSNSF_NOOPENS;
5785 	/*
5786 	 * For each client...
5787 	 */
5788 	for (i = 0; i < nfsrv_clienthashsize; i++) {
5789 	    LIST_FOREACH_SAFE(clp, &nfsclienthash[i], lc_hash, nclp) {
5790 		LIST_FOREACH_SAFE(stp, &clp->lc_open, ls_list, nstp) {
5791 			if (LIST_EMPTY(&stp->ls_open) &&
5792 			    (stp->ls_noopens > NFSNOOPEN ||
5793 			     (nfsrv_openpluslock * 2) >
5794 			     nfsrv_v4statelimit))
5795 				nfsrv_freeopenowner(stp, 0, p);
5796 		}
5797 	    }
5798 	}
5799 	NFSUNLOCKSTATE();
5800 }
5801 
5802 /*
5803  * This function checks to see if the credentials are the same.
5804  * Returns 1 for not same, 0 otherwise.
5805  */
5806 static int
5807 nfsrv_notsamecredname(struct nfsrv_descript *nd, struct nfsclient *clp)
5808 {
5809 
5810 	if (nd->nd_flag & ND_GSS) {
5811 		if (!(clp->lc_flags & LCL_GSS))
5812 			return (1);
5813 		if (clp->lc_flags & LCL_NAME) {
5814 			if (nd->nd_princlen != clp->lc_namelen ||
5815 			    NFSBCMP(nd->nd_principal, clp->lc_name,
5816 				clp->lc_namelen))
5817 				return (1);
5818 			else
5819 				return (0);
5820 		}
5821 		if (nd->nd_cred->cr_uid == clp->lc_uid)
5822 			return (0);
5823 		else
5824 			return (1);
5825 	} else if (clp->lc_flags & LCL_GSS)
5826 		return (1);
5827 	/*
5828 	 * For AUTH_SYS, allow the same uid or root. (This is underspecified
5829 	 * in RFC3530, which talks about principals, but doesn't say anything
5830 	 * about uids for AUTH_SYS.)
5831 	 */
5832 	if (nd->nd_cred->cr_uid == clp->lc_uid || nd->nd_cred->cr_uid == 0)
5833 		return (0);
5834 	else
5835 		return (1);
5836 }
5837 
5838 /*
5839  * Calculate the lease expiry time.
5840  */
5841 static time_t
5842 nfsrv_leaseexpiry(void)
5843 {
5844 
5845 	if (nfsrv_stablefirst.nsf_eograce > NFSD_MONOSEC)
5846 		return (NFSD_MONOSEC + 2 * (nfsrv_lease + NFSRV_LEASEDELTA));
5847 	return (NFSD_MONOSEC + nfsrv_lease + NFSRV_LEASEDELTA);
5848 }
5849 
5850 /*
5851  * Delay the delegation timeout as far as ls_delegtimelimit, as required.
5852  */
5853 static void
5854 nfsrv_delaydelegtimeout(struct nfsstate *stp)
5855 {
5856 
5857 	if ((stp->ls_flags & NFSLCK_DELEGRECALL) == 0)
5858 		return;
5859 
5860 	if ((stp->ls_delegtime + 15) > NFSD_MONOSEC &&
5861 	    stp->ls_delegtime < stp->ls_delegtimelimit) {
5862 		stp->ls_delegtime += nfsrv_lease;
5863 		if (stp->ls_delegtime > stp->ls_delegtimelimit)
5864 			stp->ls_delegtime = stp->ls_delegtimelimit;
5865 	}
5866 }
5867 
5868 /*
5869  * This function checks to see if there is any other state associated
5870  * with the openowner for this Open.
5871  * It returns 1 if there is no other state, 0 otherwise.
5872  */
5873 static int
5874 nfsrv_nootherstate(struct nfsstate *stp)
5875 {
5876 	struct nfsstate *tstp;
5877 
5878 	LIST_FOREACH(tstp, &stp->ls_openowner->ls_open, ls_list) {
5879 		if (tstp != stp || !LIST_EMPTY(&tstp->ls_lock))
5880 			return (0);
5881 	}
5882 	return (1);
5883 }
5884 
5885 /*
5886  * Create a list of lock deltas (changes to local byte range locking
5887  * that can be rolled back using the list) and apply the changes via
5888  * nfsvno_advlock(). Optionally, lock the list. It is expected that either
5889  * the rollback or update function will be called after this.
5890  * It returns an error (and rolls back, as required), if any nfsvno_advlock()
5891  * call fails. If it returns an error, it will unlock the list.
5892  */
5893 static int
5894 nfsrv_locallock(vnode_t vp, struct nfslockfile *lfp, int flags,
5895     uint64_t first, uint64_t end, struct nfslockconflict *cfp, NFSPROC_T *p)
5896 {
5897 	struct nfslock *lop, *nlop;
5898 	int error = 0;
5899 
5900 	/* Loop through the list of locks. */
5901 	lop = LIST_FIRST(&lfp->lf_locallock);
5902 	while (first < end && lop != NULL) {
5903 		nlop = LIST_NEXT(lop, lo_lckowner);
5904 		if (first >= lop->lo_end) {
5905 			/* not there yet */
5906 			lop = nlop;
5907 		} else if (first < lop->lo_first) {
5908 			/* new one starts before entry in list */
5909 			if (end <= lop->lo_first) {
5910 				/* no overlap between old and new */
5911 				error = nfsrv_dolocal(vp, lfp, flags,
5912 				    NFSLCK_UNLOCK, first, end, cfp, p);
5913 				if (error != 0)
5914 					break;
5915 				first = end;
5916 			} else {
5917 				/* handle fragment overlapped with new one */
5918 				error = nfsrv_dolocal(vp, lfp, flags,
5919 				    NFSLCK_UNLOCK, first, lop->lo_first, cfp,
5920 				    p);
5921 				if (error != 0)
5922 					break;
5923 				first = lop->lo_first;
5924 			}
5925 		} else {
5926 			/* new one overlaps this entry in list */
5927 			if (end <= lop->lo_end) {
5928 				/* overlaps all of new one */
5929 				error = nfsrv_dolocal(vp, lfp, flags,
5930 				    lop->lo_flags, first, end, cfp, p);
5931 				if (error != 0)
5932 					break;
5933 				first = end;
5934 			} else {
5935 				/* handle fragment overlapped with new one */
5936 				error = nfsrv_dolocal(vp, lfp, flags,
5937 				    lop->lo_flags, first, lop->lo_end, cfp, p);
5938 				if (error != 0)
5939 					break;
5940 				first = lop->lo_end;
5941 				lop = nlop;
5942 			}
5943 		}
5944 	}
5945 	if (first < end && error == 0)
5946 		/* handle fragment past end of list */
5947 		error = nfsrv_dolocal(vp, lfp, flags, NFSLCK_UNLOCK, first,
5948 		    end, cfp, p);
5949 
5950 	NFSEXITCODE(error);
5951 	return (error);
5952 }
5953 
5954 /*
5955  * Local lock unlock. Unlock all byte ranges that are no longer locked
5956  * by NFSv4. To do this, unlock any subranges of first-->end that
5957  * do not overlap with the byte ranges of any lock in the lfp->lf_lock
5958  * list. This list has all locks for the file held by other
5959  * <clientid, lockowner> tuples. The list is ordered by increasing
5960  * lo_first value, but may have entries that overlap each other, for
5961  * the case of read locks.
5962  */
5963 static void
5964 nfsrv_localunlock(vnode_t vp, struct nfslockfile *lfp, uint64_t init_first,
5965     uint64_t init_end, NFSPROC_T *p)
5966 {
5967 	struct nfslock *lop;
5968 	uint64_t first, end, prevfirst __unused;
5969 
5970 	first = init_first;
5971 	end = init_end;
5972 	while (first < init_end) {
5973 		/* Loop through all nfs locks, adjusting first and end */
5974 		prevfirst = 0;
5975 		LIST_FOREACH(lop, &lfp->lf_lock, lo_lckfile) {
5976 			KASSERT(prevfirst <= lop->lo_first,
5977 			    ("nfsv4 locks out of order"));
5978 			KASSERT(lop->lo_first < lop->lo_end,
5979 			    ("nfsv4 bogus lock"));
5980 			prevfirst = lop->lo_first;
5981 			if (first >= lop->lo_first &&
5982 			    first < lop->lo_end)
5983 				/*
5984 				 * Overlaps with initial part, so trim
5985 				 * off that initial part by moving first past
5986 				 * it.
5987 				 */
5988 				first = lop->lo_end;
5989 			else if (end > lop->lo_first &&
5990 			    lop->lo_first > first) {
5991 				/*
5992 				 * This lock defines the end of the
5993 				 * segment to unlock, so set end to the
5994 				 * start of it and break out of the loop.
5995 				 */
5996 				end = lop->lo_first;
5997 				break;
5998 			}
5999 			if (first >= end)
6000 				/*
6001 				 * There is no segment left to do, so
6002 				 * break out of this loop and then exit
6003 				 * the outer while() since first will be set
6004 				 * to end, which must equal init_end here.
6005 				 */
6006 				break;
6007 		}
6008 		if (first < end) {
6009 			/* Unlock this segment */
6010 			(void) nfsrv_dolocal(vp, lfp, NFSLCK_UNLOCK,
6011 			    NFSLCK_READ, first, end, NULL, p);
6012 			nfsrv_locallock_commit(lfp, NFSLCK_UNLOCK,
6013 			    first, end);
6014 		}
6015 		/*
6016 		 * Now move past this segment and look for any further
6017 		 * segment in the range, if there is one.
6018 		 */
6019 		first = end;
6020 		end = init_end;
6021 	}
6022 }
6023 
6024 /*
6025  * Do the local lock operation and update the rollback list, as required.
6026  * Perform the rollback and return the error if nfsvno_advlock() fails.
6027  */
6028 static int
6029 nfsrv_dolocal(vnode_t vp, struct nfslockfile *lfp, int flags, int oldflags,
6030     uint64_t first, uint64_t end, struct nfslockconflict *cfp, NFSPROC_T *p)
6031 {
6032 	struct nfsrollback *rlp;
6033 	int error = 0, ltype, oldltype;
6034 
6035 	if (flags & NFSLCK_WRITE)
6036 		ltype = F_WRLCK;
6037 	else if (flags & NFSLCK_READ)
6038 		ltype = F_RDLCK;
6039 	else
6040 		ltype = F_UNLCK;
6041 	if (oldflags & NFSLCK_WRITE)
6042 		oldltype = F_WRLCK;
6043 	else if (oldflags & NFSLCK_READ)
6044 		oldltype = F_RDLCK;
6045 	else
6046 		oldltype = F_UNLCK;
6047 	if (ltype == oldltype || (oldltype == F_WRLCK && ltype == F_RDLCK))
6048 		/* nothing to do */
6049 		goto out;
6050 	error = nfsvno_advlock(vp, ltype, first, end, p);
6051 	if (error != 0) {
6052 		if (cfp != NULL) {
6053 			cfp->cl_clientid.lval[0] = 0;
6054 			cfp->cl_clientid.lval[1] = 0;
6055 			cfp->cl_first = 0;
6056 			cfp->cl_end = NFS64BITSSET;
6057 			cfp->cl_flags = NFSLCK_WRITE;
6058 			cfp->cl_ownerlen = 5;
6059 			NFSBCOPY("LOCAL", cfp->cl_owner, 5);
6060 		}
6061 		nfsrv_locallock_rollback(vp, lfp, p);
6062 	} else if (ltype != F_UNLCK) {
6063 		rlp = malloc(sizeof (struct nfsrollback), M_NFSDROLLBACK,
6064 		    M_WAITOK);
6065 		rlp->rlck_first = first;
6066 		rlp->rlck_end = end;
6067 		rlp->rlck_type = oldltype;
6068 		LIST_INSERT_HEAD(&lfp->lf_rollback, rlp, rlck_list);
6069 	}
6070 
6071 out:
6072 	NFSEXITCODE(error);
6073 	return (error);
6074 }
6075 
6076 /*
6077  * Roll back local lock changes and free up the rollback list.
6078  */
6079 static void
6080 nfsrv_locallock_rollback(vnode_t vp, struct nfslockfile *lfp, NFSPROC_T *p)
6081 {
6082 	struct nfsrollback *rlp, *nrlp;
6083 
6084 	LIST_FOREACH_SAFE(rlp, &lfp->lf_rollback, rlck_list, nrlp) {
6085 		(void) nfsvno_advlock(vp, rlp->rlck_type, rlp->rlck_first,
6086 		    rlp->rlck_end, p);
6087 		free(rlp, M_NFSDROLLBACK);
6088 	}
6089 	LIST_INIT(&lfp->lf_rollback);
6090 }
6091 
6092 /*
6093  * Update local lock list and delete rollback list (ie now committed to the
6094  * local locks). Most of the work is done by the internal function.
6095  */
6096 static void
6097 nfsrv_locallock_commit(struct nfslockfile *lfp, int flags, uint64_t first,
6098     uint64_t end)
6099 {
6100 	struct nfsrollback *rlp, *nrlp;
6101 	struct nfslock *new_lop, *other_lop;
6102 
6103 	new_lop = malloc(sizeof (struct nfslock), M_NFSDLOCK, M_WAITOK);
6104 	if (flags & (NFSLCK_READ | NFSLCK_WRITE))
6105 		other_lop = malloc(sizeof (struct nfslock), M_NFSDLOCK,
6106 		    M_WAITOK);
6107 	else
6108 		other_lop = NULL;
6109 	new_lop->lo_flags = flags;
6110 	new_lop->lo_first = first;
6111 	new_lop->lo_end = end;
6112 	nfsrv_updatelock(NULL, &new_lop, &other_lop, lfp);
6113 	if (new_lop != NULL)
6114 		free(new_lop, M_NFSDLOCK);
6115 	if (other_lop != NULL)
6116 		free(other_lop, M_NFSDLOCK);
6117 
6118 	/* and get rid of the rollback list */
6119 	LIST_FOREACH_SAFE(rlp, &lfp->lf_rollback, rlck_list, nrlp)
6120 		free(rlp, M_NFSDROLLBACK);
6121 	LIST_INIT(&lfp->lf_rollback);
6122 }
6123 
6124 /*
6125  * Lock the struct nfslockfile for local lock updating.
6126  */
6127 static void
6128 nfsrv_locklf(struct nfslockfile *lfp)
6129 {
6130 	int gotlock;
6131 
6132 	/* lf_usecount ensures *lfp won't be free'd */
6133 	lfp->lf_usecount++;
6134 	do {
6135 		gotlock = nfsv4_lock(&lfp->lf_locallock_lck, 1, NULL,
6136 		    NFSSTATEMUTEXPTR, NULL);
6137 	} while (gotlock == 0);
6138 	lfp->lf_usecount--;
6139 }
6140 
6141 /*
6142  * Unlock the struct nfslockfile after local lock updating.
6143  */
6144 static void
6145 nfsrv_unlocklf(struct nfslockfile *lfp)
6146 {
6147 
6148 	nfsv4_unlock(&lfp->lf_locallock_lck, 0);
6149 }
6150 
6151 /*
6152  * Clear out all state for the NFSv4 server.
6153  * Must be called by a thread that can sleep when no nfsds are running.
6154  */
6155 void
6156 nfsrv_throwawayallstate(NFSPROC_T *p)
6157 {
6158 	struct nfsclient *clp, *nclp;
6159 	struct nfslockfile *lfp, *nlfp;
6160 	int i;
6161 
6162 	/*
6163 	 * For each client, clean out the state and then free the structure.
6164 	 */
6165 	for (i = 0; i < nfsrv_clienthashsize; i++) {
6166 		LIST_FOREACH_SAFE(clp, &nfsclienthash[i], lc_hash, nclp) {
6167 			nfsrv_cleanclient(clp, p);
6168 			nfsrv_freedeleglist(&clp->lc_deleg);
6169 			nfsrv_freedeleglist(&clp->lc_olddeleg);
6170 			free(clp->lc_stateid, M_NFSDCLIENT);
6171 			free(clp, M_NFSDCLIENT);
6172 		}
6173 	}
6174 
6175 	/*
6176 	 * Also, free up any remaining lock file structures.
6177 	 */
6178 	for (i = 0; i < nfsrv_lockhashsize; i++) {
6179 		LIST_FOREACH_SAFE(lfp, &nfslockhash[i], lf_hash, nlfp) {
6180 			printf("nfsd unload: fnd a lock file struct\n");
6181 			nfsrv_freenfslockfile(lfp);
6182 		}
6183 	}
6184 
6185 	/* And get rid of the deviceid structures and layouts. */
6186 	nfsrv_freealllayoutsanddevids();
6187 }
6188 
6189 /*
6190  * Check the sequence# for the session and slot provided as an argument.
6191  * Also, renew the lease if the session will return NFS_OK.
6192  */
6193 int
6194 nfsrv_checksequence(struct nfsrv_descript *nd, uint32_t sequenceid,
6195     uint32_t *highest_slotidp, uint32_t *target_highest_slotidp, int cache_this,
6196     uint32_t *sflagsp, NFSPROC_T *p)
6197 {
6198 	struct nfsdsession *sep;
6199 	struct nfssessionhash *shp;
6200 	int error;
6201 	SVCXPRT *savxprt;
6202 
6203 	shp = NFSSESSIONHASH(nd->nd_sessionid);
6204 	NFSLOCKSESSION(shp);
6205 	sep = nfsrv_findsession(nd->nd_sessionid);
6206 	if (sep == NULL) {
6207 		NFSUNLOCKSESSION(shp);
6208 		return (NFSERR_BADSESSION);
6209 	}
6210 	error = nfsv4_seqsession(sequenceid, nd->nd_slotid, *highest_slotidp,
6211 	    sep->sess_slots, NULL, NFSV4_SLOTS - 1);
6212 	if (error != 0) {
6213 		NFSUNLOCKSESSION(shp);
6214 		return (error);
6215 	}
6216 	if (cache_this != 0)
6217 		nd->nd_flag |= ND_SAVEREPLY;
6218 	/* Renew the lease. */
6219 	sep->sess_clp->lc_expiry = nfsrv_leaseexpiry();
6220 	nd->nd_clientid.qval = sep->sess_clp->lc_clientid.qval;
6221 	nd->nd_flag |= ND_IMPLIEDCLID;
6222 
6223 	/* Save maximum request and reply sizes. */
6224 	nd->nd_maxreq = sep->sess_maxreq;
6225 	nd->nd_maxresp = sep->sess_maxresp;
6226 
6227 	/*
6228 	 * If this session handles the backchannel, save the nd_xprt for this
6229 	 * RPC, since this is the one being used.
6230 	 * RFC-5661 specifies that the fore channel will be implicitly
6231 	 * bound by a Sequence operation.  However, since some NFSv4.1 clients
6232 	 * erroneously assumed that the back channel would be implicitly
6233 	 * bound as well, do the implicit binding unless a
6234 	 * BindConnectiontoSession has already been done on the session.
6235 	 */
6236 	savxprt = NULL;
6237 	if (sep->sess_clp->lc_req.nr_client != NULL &&
6238 	    sep->sess_cbsess.nfsess_xprt != nd->nd_xprt &&
6239 	    (sep->sess_crflags & NFSV4CRSESS_CONNBACKCHAN) != 0 &&
6240 	    (sep->sess_clp->lc_flags & LCL_DONEBINDCONN) == 0) {
6241 		NFSD_DEBUG(2,
6242 		    "nfsrv_checksequence: implicit back channel bind\n");
6243 		savxprt = sep->sess_cbsess.nfsess_xprt;
6244 		SVC_ACQUIRE(nd->nd_xprt);
6245 		nd->nd_xprt->xp_p2 =
6246 		    sep->sess_clp->lc_req.nr_client->cl_private;
6247 		nd->nd_xprt->xp_idletimeout = 0;	/* Disable timeout. */
6248 		sep->sess_cbsess.nfsess_xprt = nd->nd_xprt;
6249 	}
6250 
6251 	*sflagsp = 0;
6252 	if (sep->sess_clp->lc_req.nr_client == NULL)
6253 		*sflagsp |= NFSV4SEQ_CBPATHDOWN;
6254 	NFSUNLOCKSESSION(shp);
6255 	if (savxprt != NULL)
6256 		SVC_RELEASE(savxprt);
6257 	if (error == NFSERR_EXPIRED) {
6258 		*sflagsp |= NFSV4SEQ_EXPIREDALLSTATEREVOKED;
6259 		error = 0;
6260 	} else if (error == NFSERR_ADMINREVOKED) {
6261 		*sflagsp |= NFSV4SEQ_ADMINSTATEREVOKED;
6262 		error = 0;
6263 	}
6264 	*highest_slotidp = *target_highest_slotidp = NFSV4_SLOTS - 1;
6265 	return (0);
6266 }
6267 
6268 /*
6269  * Check/set reclaim complete for this session/clientid.
6270  */
6271 int
6272 nfsrv_checkreclaimcomplete(struct nfsrv_descript *nd, int onefs)
6273 {
6274 	struct nfsdsession *sep;
6275 	struct nfssessionhash *shp;
6276 	int error = 0;
6277 
6278 	shp = NFSSESSIONHASH(nd->nd_sessionid);
6279 	NFSLOCKSTATE();
6280 	NFSLOCKSESSION(shp);
6281 	sep = nfsrv_findsession(nd->nd_sessionid);
6282 	if (sep == NULL) {
6283 		NFSUNLOCKSESSION(shp);
6284 		NFSUNLOCKSTATE();
6285 		return (NFSERR_BADSESSION);
6286 	}
6287 
6288 	if (onefs != 0)
6289 		sep->sess_clp->lc_flags |= LCL_RECLAIMONEFS;
6290 		/* Check to see if reclaim complete has already happened. */
6291 	else if ((sep->sess_clp->lc_flags & LCL_RECLAIMCOMPLETE) != 0)
6292 		error = NFSERR_COMPLETEALREADY;
6293 	else {
6294 		sep->sess_clp->lc_flags |= LCL_RECLAIMCOMPLETE;
6295 		nfsrv_markreclaim(sep->sess_clp);
6296 	}
6297 	NFSUNLOCKSESSION(shp);
6298 	NFSUNLOCKSTATE();
6299 	return (error);
6300 }
6301 
6302 /*
6303  * Cache the reply in a session slot.
6304  */
6305 void
6306 nfsrv_cache_session(struct nfsrv_descript *nd, struct mbuf **m)
6307 {
6308 	struct nfsdsession *sep;
6309 	struct nfssessionhash *shp;
6310 	char *buf, *cp;
6311 #ifdef INET
6312 	struct sockaddr_in *sin;
6313 #endif
6314 #ifdef INET6
6315 	struct sockaddr_in6 *sin6;
6316 #endif
6317 
6318 	shp = NFSSESSIONHASH(nd->nd_sessionid);
6319 	NFSLOCKSESSION(shp);
6320 	sep = nfsrv_findsession(nd->nd_sessionid);
6321 	if (sep == NULL) {
6322 		NFSUNLOCKSESSION(shp);
6323 		if ((nfsrv_stablefirst.nsf_flags & NFSNSF_GRACEOVER) != 0) {
6324 			buf = malloc(INET6_ADDRSTRLEN, M_TEMP, M_WAITOK);
6325 			switch (nd->nd_nam->sa_family) {
6326 #ifdef INET
6327 			case AF_INET:
6328 				sin = (struct sockaddr_in *)nd->nd_nam;
6329 				cp = inet_ntop(sin->sin_family,
6330 				    &sin->sin_addr.s_addr, buf,
6331 				    INET6_ADDRSTRLEN);
6332 				break;
6333 #endif
6334 #ifdef INET6
6335 			case AF_INET6:
6336 				sin6 = (struct sockaddr_in6 *)nd->nd_nam;
6337 				cp = inet_ntop(sin6->sin6_family,
6338 				    &sin6->sin6_addr, buf, INET6_ADDRSTRLEN);
6339 				break;
6340 #endif
6341 			default:
6342 				cp = NULL;
6343 			}
6344 			if (cp != NULL)
6345 				printf("nfsrv_cache_session: no session "
6346 				    "IPaddr=%s\n", cp);
6347 			else
6348 				printf("nfsrv_cache_session: no session\n");
6349 			free(buf, M_TEMP);
6350 		}
6351 		m_freem(*m);
6352 		return;
6353 	}
6354 	nfsv4_seqsess_cacherep(nd->nd_slotid, sep->sess_slots, nd->nd_repstat,
6355 	    m);
6356 	NFSUNLOCKSESSION(shp);
6357 }
6358 
6359 /*
6360  * Search for a session that matches the sessionid.
6361  */
6362 static struct nfsdsession *
6363 nfsrv_findsession(uint8_t *sessionid)
6364 {
6365 	struct nfsdsession *sep;
6366 	struct nfssessionhash *shp;
6367 
6368 	shp = NFSSESSIONHASH(sessionid);
6369 	LIST_FOREACH(sep, &shp->list, sess_hash) {
6370 		if (!NFSBCMP(sessionid, sep->sess_sessionid, NFSX_V4SESSIONID))
6371 			break;
6372 	}
6373 	return (sep);
6374 }
6375 
6376 /*
6377  * Destroy a session.
6378  */
6379 int
6380 nfsrv_destroysession(struct nfsrv_descript *nd, uint8_t *sessionid)
6381 {
6382 	int error, igotlock, samesess;
6383 
6384 	samesess = 0;
6385 	if (!NFSBCMP(sessionid, nd->nd_sessionid, NFSX_V4SESSIONID) &&
6386 	    (nd->nd_flag & ND_HASSEQUENCE) != 0) {
6387 		samesess = 1;
6388 		if ((nd->nd_flag & ND_LASTOP) == 0)
6389 			return (NFSERR_BADSESSION);
6390 	}
6391 
6392 	/* Lock out other nfsd threads */
6393 	NFSLOCKV4ROOTMUTEX();
6394 	nfsv4_relref(&nfsv4rootfs_lock);
6395 	do {
6396 		igotlock = nfsv4_lock(&nfsv4rootfs_lock, 1, NULL,
6397 		    NFSV4ROOTLOCKMUTEXPTR, NULL);
6398 	} while (igotlock == 0);
6399 	NFSUNLOCKV4ROOTMUTEX();
6400 
6401 	error = nfsrv_freesession(NULL, sessionid);
6402 	if (error == 0 && samesess != 0)
6403 		nd->nd_flag &= ~ND_HASSEQUENCE;
6404 
6405 	NFSLOCKV4ROOTMUTEX();
6406 	nfsv4_unlock(&nfsv4rootfs_lock, 1);
6407 	NFSUNLOCKV4ROOTMUTEX();
6408 	return (error);
6409 }
6410 
6411 /*
6412  * Bind a connection to a session.
6413  * For now, only certain variants are supported, since the current session
6414  * structure can only handle a single backchannel entry, which will be
6415  * applied to all connections if it is set.
6416  */
6417 int
6418 nfsrv_bindconnsess(struct nfsrv_descript *nd, uint8_t *sessionid, int *foreaftp)
6419 {
6420 	struct nfssessionhash *shp;
6421 	struct nfsdsession *sep;
6422 	struct nfsclient *clp;
6423 	SVCXPRT *savxprt;
6424 	int error;
6425 
6426 	error = 0;
6427 	savxprt = NULL;
6428 	shp = NFSSESSIONHASH(sessionid);
6429 	NFSLOCKSTATE();
6430 	NFSLOCKSESSION(shp);
6431 	sep = nfsrv_findsession(sessionid);
6432 	if (sep != NULL) {
6433 		clp = sep->sess_clp;
6434 		if (*foreaftp == NFSCDFC4_BACK ||
6435 		    *foreaftp == NFSCDFC4_BACK_OR_BOTH ||
6436 		    *foreaftp == NFSCDFC4_FORE_OR_BOTH) {
6437 			/* Try to set up a backchannel. */
6438 			if (clp->lc_req.nr_client == NULL) {
6439 				NFSD_DEBUG(2, "nfsrv_bindconnsess: acquire "
6440 				    "backchannel\n");
6441 				clp->lc_req.nr_client = (struct __rpc_client *)
6442 				    clnt_bck_create(nd->nd_xprt->xp_socket,
6443 				    sep->sess_cbprogram, NFSV4_CBVERS);
6444 			}
6445 			if (clp->lc_req.nr_client != NULL) {
6446 				NFSD_DEBUG(2, "nfsrv_bindconnsess: set up "
6447 				    "backchannel\n");
6448 				savxprt = sep->sess_cbsess.nfsess_xprt;
6449 				SVC_ACQUIRE(nd->nd_xprt);
6450 				nd->nd_xprt->xp_p2 =
6451 				    clp->lc_req.nr_client->cl_private;
6452 				/* Disable idle timeout. */
6453 				nd->nd_xprt->xp_idletimeout = 0;
6454 				sep->sess_cbsess.nfsess_xprt = nd->nd_xprt;
6455 				sep->sess_crflags |= NFSV4CRSESS_CONNBACKCHAN;
6456 				clp->lc_flags |= LCL_DONEBINDCONN;
6457 				if (*foreaftp == NFSCDFS4_BACK)
6458 					*foreaftp = NFSCDFS4_BACK;
6459 				else
6460 					*foreaftp = NFSCDFS4_BOTH;
6461 			} else if (*foreaftp != NFSCDFC4_BACK) {
6462 				NFSD_DEBUG(2, "nfsrv_bindconnsess: can't set "
6463 				    "up backchannel\n");
6464 				sep->sess_crflags &= ~NFSV4CRSESS_CONNBACKCHAN;
6465 				clp->lc_flags |= LCL_DONEBINDCONN;
6466 				*foreaftp = NFSCDFS4_FORE;
6467 			} else {
6468 				error = NFSERR_NOTSUPP;
6469 				printf("nfsrv_bindconnsess: Can't add "
6470 				    "backchannel\n");
6471 			}
6472 		} else {
6473 			NFSD_DEBUG(2, "nfsrv_bindconnsess: Set forechannel\n");
6474 			clp->lc_flags |= LCL_DONEBINDCONN;
6475 			*foreaftp = NFSCDFS4_FORE;
6476 		}
6477 	} else
6478 		error = NFSERR_BADSESSION;
6479 	NFSUNLOCKSESSION(shp);
6480 	NFSUNLOCKSTATE();
6481 	if (savxprt != NULL)
6482 		SVC_RELEASE(savxprt);
6483 	return (error);
6484 }
6485 
6486 /*
6487  * Free up a session structure.
6488  */
6489 static int
6490 nfsrv_freesession(struct nfsdsession *sep, uint8_t *sessionid)
6491 {
6492 	struct nfssessionhash *shp;
6493 	int i;
6494 
6495 	NFSLOCKSTATE();
6496 	if (sep == NULL) {
6497 		shp = NFSSESSIONHASH(sessionid);
6498 		NFSLOCKSESSION(shp);
6499 		sep = nfsrv_findsession(sessionid);
6500 	} else {
6501 		shp = NFSSESSIONHASH(sep->sess_sessionid);
6502 		NFSLOCKSESSION(shp);
6503 	}
6504 	if (sep != NULL) {
6505 		sep->sess_refcnt--;
6506 		if (sep->sess_refcnt > 0) {
6507 			NFSUNLOCKSESSION(shp);
6508 			NFSUNLOCKSTATE();
6509 			return (NFSERR_BACKCHANBUSY);
6510 		}
6511 		LIST_REMOVE(sep, sess_hash);
6512 		LIST_REMOVE(sep, sess_list);
6513 	}
6514 	NFSUNLOCKSESSION(shp);
6515 	NFSUNLOCKSTATE();
6516 	if (sep == NULL)
6517 		return (NFSERR_BADSESSION);
6518 	for (i = 0; i < NFSV4_SLOTS; i++)
6519 		if (sep->sess_slots[i].nfssl_reply != NULL)
6520 			m_freem(sep->sess_slots[i].nfssl_reply);
6521 	if (sep->sess_cbsess.nfsess_xprt != NULL)
6522 		SVC_RELEASE(sep->sess_cbsess.nfsess_xprt);
6523 	free(sep, M_NFSDSESSION);
6524 	return (0);
6525 }
6526 
6527 /*
6528  * Free a stateid.
6529  * RFC5661 says that it should fail when there are associated opens, locks
6530  * or delegations. Since stateids represent opens, I don't see how you can
6531  * free an open stateid (it will be free'd when closed), so this function
6532  * only works for lock stateids (freeing the lock_owner) or delegations.
6533  */
6534 int
6535 nfsrv_freestateid(struct nfsrv_descript *nd, nfsv4stateid_t *stateidp,
6536     NFSPROC_T *p)
6537 {
6538 	struct nfsclient *clp;
6539 	struct nfsstate *stp;
6540 	int error;
6541 
6542 	NFSLOCKSTATE();
6543 	/*
6544 	 * Look up the stateid
6545 	 */
6546 	error = nfsrv_getclient((nfsquad_t)((u_quad_t)0), CLOPS_RENEW, &clp,
6547 	    NULL, (nfsquad_t)((u_quad_t)0), 0, nd, p);
6548 	if (error == 0) {
6549 		/* First, check for a delegation. */
6550 		LIST_FOREACH(stp, &clp->lc_deleg, ls_list) {
6551 			if (!NFSBCMP(stp->ls_stateid.other, stateidp->other,
6552 			    NFSX_STATEIDOTHER))
6553 				break;
6554 		}
6555 		if (stp != NULL) {
6556 			nfsrv_freedeleg(stp);
6557 			NFSUNLOCKSTATE();
6558 			return (error);
6559 		}
6560 	}
6561 	/* Not a delegation, try for a lock_owner. */
6562 	if (error == 0)
6563 		error = nfsrv_getstate(clp, stateidp, 0, &stp);
6564 	if (error == 0 && ((stp->ls_flags & (NFSLCK_OPEN | NFSLCK_DELEGREAD |
6565 	    NFSLCK_DELEGWRITE)) != 0 || (stp->ls_flags & NFSLCK_LOCK) == 0))
6566 		/* Not a lock_owner stateid. */
6567 		error = NFSERR_LOCKSHELD;
6568 	if (error == 0 && !LIST_EMPTY(&stp->ls_lock))
6569 		error = NFSERR_LOCKSHELD;
6570 	if (error == 0)
6571 		nfsrv_freelockowner(stp, NULL, 0, p);
6572 	NFSUNLOCKSTATE();
6573 	return (error);
6574 }
6575 
6576 /*
6577  * Test a stateid.
6578  */
6579 int
6580 nfsrv_teststateid(struct nfsrv_descript *nd, nfsv4stateid_t *stateidp,
6581     NFSPROC_T *p)
6582 {
6583 	struct nfsclient *clp;
6584 	struct nfsstate *stp;
6585 	int error;
6586 
6587 	NFSLOCKSTATE();
6588 	/*
6589 	 * Look up the stateid
6590 	 */
6591 	error = nfsrv_getclient((nfsquad_t)((u_quad_t)0), CLOPS_RENEW, &clp,
6592 	    NULL, (nfsquad_t)((u_quad_t)0), 0, nd, p);
6593 	if (error == 0)
6594 		error = nfsrv_getstate(clp, stateidp, 0, &stp);
6595 	if (error == 0 && stateidp->seqid != 0 &&
6596 	    SEQ_LT(stateidp->seqid, stp->ls_stateid.seqid))
6597 		error = NFSERR_OLDSTATEID;
6598 	NFSUNLOCKSTATE();
6599 	return (error);
6600 }
6601 
6602 /*
6603  * Generate the xdr for an NFSv4.1 CBSequence Operation.
6604  */
6605 static int
6606 nfsv4_setcbsequence(struct nfsrv_descript *nd, struct nfsclient *clp,
6607     int dont_replycache, struct nfsdsession **sepp)
6608 {
6609 	struct nfsdsession *sep;
6610 	uint32_t *tl, slotseq = 0;
6611 	int maxslot, slotpos;
6612 	uint8_t sessionid[NFSX_V4SESSIONID];
6613 	int error;
6614 
6615 	error = nfsv4_getcbsession(clp, sepp);
6616 	if (error != 0)
6617 		return (error);
6618 	sep = *sepp;
6619 	(void)nfsv4_sequencelookup(NULL, &sep->sess_cbsess, &slotpos, &maxslot,
6620 	    &slotseq, sessionid);
6621 	KASSERT(maxslot >= 0, ("nfsv4_setcbsequence neg maxslot"));
6622 
6623 	/* Build the Sequence arguments. */
6624 	NFSM_BUILD(tl, uint32_t *, NFSX_V4SESSIONID + 5 * NFSX_UNSIGNED);
6625 	bcopy(sessionid, tl, NFSX_V4SESSIONID);
6626 	tl += NFSX_V4SESSIONID / NFSX_UNSIGNED;
6627 	nd->nd_slotseq = tl;
6628 	*tl++ = txdr_unsigned(slotseq);
6629 	*tl++ = txdr_unsigned(slotpos);
6630 	*tl++ = txdr_unsigned(maxslot);
6631 	if (dont_replycache == 0)
6632 		*tl++ = newnfs_true;
6633 	else
6634 		*tl++ = newnfs_false;
6635 	*tl = 0;			/* No referring call list, for now. */
6636 	nd->nd_flag |= ND_HASSEQUENCE;
6637 	return (0);
6638 }
6639 
6640 /*
6641  * Get a session for the callback.
6642  */
6643 static int
6644 nfsv4_getcbsession(struct nfsclient *clp, struct nfsdsession **sepp)
6645 {
6646 	struct nfsdsession *sep;
6647 
6648 	NFSLOCKSTATE();
6649 	LIST_FOREACH(sep, &clp->lc_session, sess_list) {
6650 		if ((sep->sess_crflags & NFSV4CRSESS_CONNBACKCHAN) != 0)
6651 			break;
6652 	}
6653 	if (sep == NULL) {
6654 		NFSUNLOCKSTATE();
6655 		return (NFSERR_BADSESSION);
6656 	}
6657 	sep->sess_refcnt++;
6658 	*sepp = sep;
6659 	NFSUNLOCKSTATE();
6660 	return (0);
6661 }
6662 
6663 /*
6664  * Free up all backchannel xprts.  This needs to be done when the nfsd threads
6665  * exit, since those transports will all be going away.
6666  * This is only called after all the nfsd threads are done performing RPCs,
6667  * so locking shouldn't be an issue.
6668  */
6669 void
6670 nfsrv_freeallbackchannel_xprts(void)
6671 {
6672 	struct nfsdsession *sep;
6673 	struct nfsclient *clp;
6674 	SVCXPRT *xprt;
6675 	int i;
6676 
6677 	for (i = 0; i < nfsrv_clienthashsize; i++) {
6678 		LIST_FOREACH(clp, &nfsclienthash[i], lc_hash) {
6679 			LIST_FOREACH(sep, &clp->lc_session, sess_list) {
6680 				xprt = sep->sess_cbsess.nfsess_xprt;
6681 				sep->sess_cbsess.nfsess_xprt = NULL;
6682 				if (xprt != NULL)
6683 					SVC_RELEASE(xprt);
6684 			}
6685 		}
6686 	}
6687 }
6688 
6689 /*
6690  * Do a layout commit.  Actually just call nfsrv_updatemdsattr().
6691  * I have no idea if the rest of these arguments will ever be useful?
6692  */
6693 int
6694 nfsrv_layoutcommit(struct nfsrv_descript *nd, vnode_t vp, int layouttype,
6695     int hasnewoff, uint64_t newoff, uint64_t offset, uint64_t len,
6696     int hasnewmtime, struct timespec *newmtimep, int reclaim,
6697     nfsv4stateid_t *stateidp, int maxcnt, char *layp, int *hasnewsizep,
6698     uint64_t *newsizep, struct ucred *cred, NFSPROC_T *p)
6699 {
6700 	struct nfsvattr na;
6701 	int error;
6702 
6703 	error = nfsrv_updatemdsattr(vp, &na, p);
6704 	if (error == 0) {
6705 		*hasnewsizep = 1;
6706 		*newsizep = na.na_size;
6707 	}
6708 	return (error);
6709 }
6710 
6711 /*
6712  * Try and get a layout.
6713  */
6714 int
6715 nfsrv_layoutget(struct nfsrv_descript *nd, vnode_t vp, struct nfsexstuff *exp,
6716     int layouttype, int *iomode, uint64_t *offset, uint64_t *len,
6717     uint64_t minlen, nfsv4stateid_t *stateidp, int maxcnt, int *retonclose,
6718     int *layoutlenp, char *layp, struct ucred *cred, NFSPROC_T *p)
6719 {
6720 	struct nfslayouthash *lhyp;
6721 	struct nfslayout *lyp;
6722 	char *devid;
6723 	fhandle_t fh, *dsfhp;
6724 	int error, mirrorcnt;
6725 
6726 	if (nfsrv_devidcnt == 0)
6727 		return (NFSERR_UNKNLAYOUTTYPE);
6728 
6729 	if (*offset != 0)
6730 		printf("nfsrv_layoutget: off=%ju len=%ju\n", (uintmax_t)*offset,
6731 		    (uintmax_t)*len);
6732 	error = nfsvno_getfh(vp, &fh, p);
6733 	NFSD_DEBUG(4, "layoutget getfh=%d\n", error);
6734 	if (error != 0)
6735 		return (error);
6736 
6737 	/*
6738 	 * For now, all layouts are for entire files.
6739 	 * Only issue Read/Write layouts if requested for a non-readonly fs.
6740 	 */
6741 	if (NFSVNO_EXRDONLY(exp)) {
6742 		if (*iomode == NFSLAYOUTIOMODE_RW)
6743 			return (NFSERR_LAYOUTTRYLATER);
6744 		*iomode = NFSLAYOUTIOMODE_READ;
6745 	}
6746 	if (*iomode != NFSLAYOUTIOMODE_RW)
6747 		*iomode = NFSLAYOUTIOMODE_READ;
6748 
6749 	/*
6750 	 * Check to see if a write layout can be issued for this file.
6751 	 * This is used during mirror recovery to avoid RW layouts being
6752 	 * issued for a file while it is being copied to the recovered
6753 	 * mirror.
6754 	 */
6755 	if (*iomode == NFSLAYOUTIOMODE_RW && nfsrv_dontlayout(&fh) != 0)
6756 		return (NFSERR_LAYOUTTRYLATER);
6757 
6758 	*retonclose = 0;
6759 	*offset = 0;
6760 	*len = UINT64_MAX;
6761 
6762 	/* First, see if a layout already exists and return if found. */
6763 	lhyp = NFSLAYOUTHASH(&fh);
6764 	NFSLOCKLAYOUT(lhyp);
6765 	error = nfsrv_findlayout(&nd->nd_clientid, &fh, layouttype, p, &lyp);
6766 	NFSD_DEBUG(4, "layoutget findlay=%d\n", error);
6767 	/*
6768 	 * Not sure if the seqid must be the same, so I won't check it.
6769 	 */
6770 	if (error == 0 && (stateidp->other[0] != lyp->lay_stateid.other[0] ||
6771 	    stateidp->other[1] != lyp->lay_stateid.other[1] ||
6772 	    stateidp->other[2] != lyp->lay_stateid.other[2])) {
6773 		if ((lyp->lay_flags & NFSLAY_CALLB) == 0) {
6774 			NFSUNLOCKLAYOUT(lhyp);
6775 			NFSD_DEBUG(1, "ret bad stateid\n");
6776 			return (NFSERR_BADSTATEID);
6777 		}
6778 		/*
6779 		 * I believe we get here because there is a race between
6780 		 * the client processing the CBLAYOUTRECALL and the layout
6781 		 * being deleted here on the server.
6782 		 * The client has now done a LayoutGet with a non-layout
6783 		 * stateid, as it would when there is no layout.
6784 		 * As such, free this layout and set error == NFSERR_BADSTATEID
6785 		 * so the code below will create a new layout structure as
6786 		 * would happen if no layout was found.
6787 		 * "lyp" will be set before being used below, but set it NULL
6788 		 * as a safety belt.
6789 		 */
6790 		nfsrv_freelayout(&lhyp->list, lyp);
6791 		lyp = NULL;
6792 		error = NFSERR_BADSTATEID;
6793 	}
6794 	if (error == 0) {
6795 		if (lyp->lay_layoutlen > maxcnt) {
6796 			NFSUNLOCKLAYOUT(lhyp);
6797 			NFSD_DEBUG(1, "ret layout too small\n");
6798 			return (NFSERR_TOOSMALL);
6799 		}
6800 		if (*iomode == NFSLAYOUTIOMODE_RW)
6801 			lyp->lay_flags |= NFSLAY_RW;
6802 		else
6803 			lyp->lay_flags |= NFSLAY_READ;
6804 		NFSBCOPY(lyp->lay_xdr, layp, lyp->lay_layoutlen);
6805 		*layoutlenp = lyp->lay_layoutlen;
6806 		if (++lyp->lay_stateid.seqid == 0)
6807 			lyp->lay_stateid.seqid = 1;
6808 		stateidp->seqid = lyp->lay_stateid.seqid;
6809 		NFSUNLOCKLAYOUT(lhyp);
6810 		NFSD_DEBUG(4, "ret fnd layout\n");
6811 		return (0);
6812 	}
6813 	NFSUNLOCKLAYOUT(lhyp);
6814 
6815 	/* Find the device id and file handle. */
6816 	dsfhp = malloc(sizeof(fhandle_t) * NFSDEV_MAXMIRRORS, M_TEMP, M_WAITOK);
6817 	devid = malloc(NFSX_V4DEVICEID * NFSDEV_MAXMIRRORS, M_TEMP, M_WAITOK);
6818 	error = nfsrv_dsgetdevandfh(vp, p, &mirrorcnt, dsfhp, devid);
6819 	NFSD_DEBUG(4, "layoutget devandfh=%d\n", error);
6820 	if (error == 0) {
6821 		if (layouttype == NFSLAYOUT_NFSV4_1_FILES) {
6822 			if (NFSX_V4FILELAYOUT > maxcnt)
6823 				error = NFSERR_TOOSMALL;
6824 			else
6825 				lyp = nfsrv_filelayout(nd, *iomode, &fh, dsfhp,
6826 				    devid, vp->v_mount->mnt_stat.f_fsid);
6827 		} else {
6828 			if (NFSX_V4FLEXLAYOUT(mirrorcnt) > maxcnt)
6829 				error = NFSERR_TOOSMALL;
6830 			else
6831 				lyp = nfsrv_flexlayout(nd, *iomode, mirrorcnt,
6832 				    &fh, dsfhp, devid,
6833 				    vp->v_mount->mnt_stat.f_fsid);
6834 		}
6835 	}
6836 	free(dsfhp, M_TEMP);
6837 	free(devid, M_TEMP);
6838 	if (error != 0)
6839 		return (error);
6840 
6841 	/*
6842 	 * Now, add this layout to the list.
6843 	 */
6844 	error = nfsrv_addlayout(nd, &lyp, stateidp, layp, layoutlenp, p);
6845 	NFSD_DEBUG(4, "layoutget addl=%d\n", error);
6846 	/*
6847 	 * The lyp will be set to NULL by nfsrv_addlayout() if it
6848 	 * linked the new structure into the lists.
6849 	 */
6850 	free(lyp, M_NFSDSTATE);
6851 	return (error);
6852 }
6853 
6854 /*
6855  * Generate a File Layout.
6856  */
6857 static struct nfslayout *
6858 nfsrv_filelayout(struct nfsrv_descript *nd, int iomode, fhandle_t *fhp,
6859     fhandle_t *dsfhp, char *devid, fsid_t fs)
6860 {
6861 	uint32_t *tl;
6862 	struct nfslayout *lyp;
6863 	uint64_t pattern_offset;
6864 
6865 	lyp = malloc(sizeof(struct nfslayout) + NFSX_V4FILELAYOUT, M_NFSDSTATE,
6866 	    M_WAITOK | M_ZERO);
6867 	lyp->lay_type = NFSLAYOUT_NFSV4_1_FILES;
6868 	if (iomode == NFSLAYOUTIOMODE_RW)
6869 		lyp->lay_flags = NFSLAY_RW;
6870 	else
6871 		lyp->lay_flags = NFSLAY_READ;
6872 	NFSBCOPY(fhp, &lyp->lay_fh, sizeof(*fhp));
6873 	lyp->lay_clientid.qval = nd->nd_clientid.qval;
6874 	lyp->lay_fsid = fs;
6875 
6876 	/* Fill in the xdr for the files layout. */
6877 	tl = (uint32_t *)lyp->lay_xdr;
6878 	NFSBCOPY(devid, tl, NFSX_V4DEVICEID);		/* Device ID. */
6879 	tl += (NFSX_V4DEVICEID / NFSX_UNSIGNED);
6880 
6881 	/*
6882 	 * Make the stripe size as many 64K blocks as will fit in the stripe
6883 	 * mask. Since there is only one stripe, the stripe size doesn't really
6884 	 * matter, except that the Linux client will only handle an exact
6885 	 * multiple of their PAGE_SIZE (usually 4K).  I chose 64K as a value
6886 	 * that should cover most/all arches w.r.t. PAGE_SIZE.
6887 	 */
6888 	*tl++ = txdr_unsigned(NFSFLAYUTIL_STRIPE_MASK & ~0xffff);
6889 	*tl++ = 0;					/* 1st stripe index. */
6890 	pattern_offset = 0;
6891 	txdr_hyper(pattern_offset, tl); tl += 2;	/* Pattern offset. */
6892 	*tl++ = txdr_unsigned(1);			/* 1 file handle. */
6893 	*tl++ = txdr_unsigned(NFSX_V4PNFSFH);
6894 	NFSBCOPY(dsfhp, tl, sizeof(*dsfhp));
6895 	lyp->lay_layoutlen = NFSX_V4FILELAYOUT;
6896 	return (lyp);
6897 }
6898 
6899 #define	FLEX_OWNERID	"999"
6900 #define	FLEX_UID0	"0"
6901 /*
6902  * Generate a Flex File Layout.
6903  * The FLEX_OWNERID can be any string of 3 decimal digits. Although this
6904  * string goes on the wire, it isn't supposed to be used by the client,
6905  * since this server uses tight coupling.
6906  * Although not recommended by the spec., if vfs.nfsd.flexlinuxhack=1 use
6907  * a string of "0". This works around the Linux Flex File Layout driver bug
6908  * which uses the synthetic uid/gid strings for the "tightly coupled" case.
6909  */
6910 static struct nfslayout *
6911 nfsrv_flexlayout(struct nfsrv_descript *nd, int iomode, int mirrorcnt,
6912     fhandle_t *fhp, fhandle_t *dsfhp, char *devid, fsid_t fs)
6913 {
6914 	uint32_t *tl;
6915 	struct nfslayout *lyp;
6916 	uint64_t lenval;
6917 	int i;
6918 
6919 	lyp = malloc(sizeof(struct nfslayout) + NFSX_V4FLEXLAYOUT(mirrorcnt),
6920 	    M_NFSDSTATE, M_WAITOK | M_ZERO);
6921 	lyp->lay_type = NFSLAYOUT_FLEXFILE;
6922 	if (iomode == NFSLAYOUTIOMODE_RW)
6923 		lyp->lay_flags = NFSLAY_RW;
6924 	else
6925 		lyp->lay_flags = NFSLAY_READ;
6926 	NFSBCOPY(fhp, &lyp->lay_fh, sizeof(*fhp));
6927 	lyp->lay_clientid.qval = nd->nd_clientid.qval;
6928 	lyp->lay_fsid = fs;
6929 	lyp->lay_mirrorcnt = mirrorcnt;
6930 
6931 	/* Fill in the xdr for the files layout. */
6932 	tl = (uint32_t *)lyp->lay_xdr;
6933 	lenval = 0;
6934 	txdr_hyper(lenval, tl); tl += 2;		/* Stripe unit. */
6935 	*tl++ = txdr_unsigned(mirrorcnt);		/* # of mirrors. */
6936 	for (i = 0; i < mirrorcnt; i++) {
6937 		*tl++ = txdr_unsigned(1);		/* One stripe. */
6938 		NFSBCOPY(devid, tl, NFSX_V4DEVICEID);	/* Device ID. */
6939 		tl += (NFSX_V4DEVICEID / NFSX_UNSIGNED);
6940 		devid += NFSX_V4DEVICEID;
6941 		*tl++ = txdr_unsigned(1);		/* Efficiency. */
6942 		*tl++ = 0;				/* Proxy Stateid. */
6943 		*tl++ = 0x55555555;
6944 		*tl++ = 0x55555555;
6945 		*tl++ = 0x55555555;
6946 		*tl++ = txdr_unsigned(1);		/* 1 file handle. */
6947 		*tl++ = txdr_unsigned(NFSX_V4PNFSFH);
6948 		NFSBCOPY(dsfhp, tl, sizeof(*dsfhp));
6949 		tl += (NFSM_RNDUP(NFSX_V4PNFSFH) / NFSX_UNSIGNED);
6950 		dsfhp++;
6951 		if (nfsrv_flexlinuxhack != 0) {
6952 			*tl++ = txdr_unsigned(strlen(FLEX_UID0));
6953 			*tl = 0;		/* 0 pad string. */
6954 			NFSBCOPY(FLEX_UID0, tl++, strlen(FLEX_UID0));
6955 			*tl++ = txdr_unsigned(strlen(FLEX_UID0));
6956 			*tl = 0;		/* 0 pad string. */
6957 			NFSBCOPY(FLEX_UID0, tl++, strlen(FLEX_UID0));
6958 		} else {
6959 			*tl++ = txdr_unsigned(strlen(FLEX_OWNERID));
6960 			NFSBCOPY(FLEX_OWNERID, tl++, NFSX_UNSIGNED);
6961 			*tl++ = txdr_unsigned(strlen(FLEX_OWNERID));
6962 			NFSBCOPY(FLEX_OWNERID, tl++, NFSX_UNSIGNED);
6963 		}
6964 	}
6965 	*tl++ = txdr_unsigned(0);		/* ff_flags. */
6966 	*tl = txdr_unsigned(60);		/* Status interval hint. */
6967 	lyp->lay_layoutlen = NFSX_V4FLEXLAYOUT(mirrorcnt);
6968 	return (lyp);
6969 }
6970 
6971 /*
6972  * Parse and process Flex File errors returned via LayoutReturn.
6973  */
6974 static void
6975 nfsrv_flexlayouterr(struct nfsrv_descript *nd, uint32_t *layp, int maxcnt,
6976     NFSPROC_T *p)
6977 {
6978 	uint32_t *tl;
6979 	int cnt, errcnt, i, j, opnum, stat;
6980 	char devid[NFSX_V4DEVICEID];
6981 
6982 	tl = layp;
6983 	cnt = fxdr_unsigned(int, *tl++);
6984 	NFSD_DEBUG(4, "flexlayouterr cnt=%d\n", cnt);
6985 	for (i = 0; i < cnt; i++) {
6986 		/* Skip offset, length and stateid for now. */
6987 		tl += (4 + NFSX_STATEID / NFSX_UNSIGNED);
6988 		errcnt = fxdr_unsigned(int, *tl++);
6989 		NFSD_DEBUG(4, "flexlayouterr errcnt=%d\n", errcnt);
6990 		for (j = 0; j < errcnt; j++) {
6991 			NFSBCOPY(tl, devid, NFSX_V4DEVICEID);
6992 			tl += (NFSX_V4DEVICEID / NFSX_UNSIGNED);
6993 			stat = fxdr_unsigned(int, *tl++);
6994 			opnum = fxdr_unsigned(int, *tl++);
6995 			NFSD_DEBUG(4, "flexlayouterr op=%d stat=%d\n", opnum,
6996 			    stat);
6997 			/*
6998 			 * Except for NFSERR_ACCES and NFSERR_STALE errors,
6999 			 * disable the mirror.
7000 			 */
7001 			if (stat != NFSERR_ACCES && stat != NFSERR_STALE)
7002 				nfsrv_delds(devid, p);
7003 		}
7004 	}
7005 }
7006 
7007 /*
7008  * This function removes all flex file layouts which has a mirror with
7009  * a device id that matches the argument.
7010  * Called when the DS represented by the device id has failed.
7011  */
7012 void
7013 nfsrv_flexmirrordel(char *devid, NFSPROC_T *p)
7014 {
7015 	uint32_t *tl;
7016 	struct nfslayout *lyp, *nlyp;
7017 	struct nfslayouthash *lhyp;
7018 	struct nfslayouthead loclyp;
7019 	int i, j;
7020 
7021 	NFSD_DEBUG(4, "flexmirrordel\n");
7022 	/* Move all layouts found onto a local list. */
7023 	TAILQ_INIT(&loclyp);
7024 	for (i = 0; i < nfsrv_layouthashsize; i++) {
7025 		lhyp = &nfslayouthash[i];
7026 		NFSLOCKLAYOUT(lhyp);
7027 		TAILQ_FOREACH_SAFE(lyp, &lhyp->list, lay_list, nlyp) {
7028 			if (lyp->lay_type == NFSLAYOUT_FLEXFILE &&
7029 			    lyp->lay_mirrorcnt > 1) {
7030 				NFSD_DEBUG(4, "possible match\n");
7031 				tl = lyp->lay_xdr;
7032 				tl += 3;
7033 				for (j = 0; j < lyp->lay_mirrorcnt; j++) {
7034 					tl++;
7035 					if (NFSBCMP(devid, tl, NFSX_V4DEVICEID)
7036 					    == 0) {
7037 						/* Found one. */
7038 						NFSD_DEBUG(4, "fnd one\n");
7039 						TAILQ_REMOVE(&lhyp->list, lyp,
7040 						    lay_list);
7041 						TAILQ_INSERT_HEAD(&loclyp, lyp,
7042 						    lay_list);
7043 						break;
7044 					}
7045 					tl += (NFSX_V4DEVICEID / NFSX_UNSIGNED +
7046 					    NFSM_RNDUP(NFSX_V4PNFSFH) /
7047 					    NFSX_UNSIGNED + 11 * NFSX_UNSIGNED);
7048 				}
7049 			}
7050 		}
7051 		NFSUNLOCKLAYOUT(lhyp);
7052 	}
7053 
7054 	/* Now, try to do a Layout recall for each one found. */
7055 	TAILQ_FOREACH_SAFE(lyp, &loclyp, lay_list, nlyp) {
7056 		NFSD_DEBUG(4, "do layout recall\n");
7057 		/*
7058 		 * The layout stateid.seqid needs to be incremented
7059 		 * before doing a LAYOUT_RECALL callback.
7060 		 */
7061 		if (++lyp->lay_stateid.seqid == 0)
7062 			lyp->lay_stateid.seqid = 1;
7063 		nfsrv_recalllayout(lyp->lay_clientid, &lyp->lay_stateid,
7064 		    &lyp->lay_fh, lyp, 1, lyp->lay_type, p);
7065 		nfsrv_freelayout(&loclyp, lyp);
7066 	}
7067 }
7068 
7069 /*
7070  * Do a recall callback to the client for this layout.
7071  */
7072 static int
7073 nfsrv_recalllayout(nfsquad_t clid, nfsv4stateid_t *stateidp, fhandle_t *fhp,
7074     struct nfslayout *lyp, int changed, int laytype, NFSPROC_T *p)
7075 {
7076 	struct nfsclient *clp;
7077 	int error;
7078 
7079 	NFSD_DEBUG(4, "nfsrv_recalllayout\n");
7080 	error = nfsrv_getclient(clid, 0, &clp, NULL, (nfsquad_t)((u_quad_t)0),
7081 	    0, NULL, p);
7082 	NFSD_DEBUG(4, "aft nfsrv_getclient=%d\n", error);
7083 	if (error != 0) {
7084 		printf("nfsrv_recalllayout: getclient err=%d\n", error);
7085 		return (error);
7086 	}
7087 	if ((clp->lc_flags & LCL_NFSV41) != 0) {
7088 		error = nfsrv_docallback(clp, NFSV4OP_CBLAYOUTRECALL,
7089 		    stateidp, changed, fhp, NULL, NULL, laytype, p);
7090 		/* If lyp != NULL, handle an error return here. */
7091 		if (error != 0 && lyp != NULL) {
7092 			NFSDRECALLLOCK();
7093 			/*
7094 			 * Mark it returned, since no layout recall
7095 			 * has been done.
7096 			 * All errors seem to be non-recoverable, although
7097 			 * NFSERR_NOMATCHLAYOUT is a normal event.
7098 			 */
7099 			if ((lyp->lay_flags & NFSLAY_RECALL) != 0) {
7100 				lyp->lay_flags |= NFSLAY_RETURNED;
7101 				wakeup(lyp);
7102 			}
7103 			NFSDRECALLUNLOCK();
7104 			if (error != NFSERR_NOMATCHLAYOUT)
7105 				printf("nfsrv_recalllayout: err=%d\n", error);
7106 		}
7107 	} else
7108 		printf("nfsrv_recalllayout: clp not NFSv4.1\n");
7109 	return (error);
7110 }
7111 
7112 /*
7113  * Find a layout to recall when we exceed our high water mark.
7114  */
7115 void
7116 nfsrv_recalloldlayout(NFSPROC_T *p)
7117 {
7118 	struct nfslayouthash *lhyp;
7119 	struct nfslayout *lyp;
7120 	nfsquad_t clientid;
7121 	nfsv4stateid_t stateid;
7122 	fhandle_t fh;
7123 	int error, laytype = 0, ret;
7124 
7125 	lhyp = &nfslayouthash[arc4random() % nfsrv_layouthashsize];
7126 	NFSLOCKLAYOUT(lhyp);
7127 	TAILQ_FOREACH_REVERSE(lyp, &lhyp->list, nfslayouthead, lay_list) {
7128 		if ((lyp->lay_flags & NFSLAY_CALLB) == 0) {
7129 			lyp->lay_flags |= NFSLAY_CALLB;
7130 			/*
7131 			 * The layout stateid.seqid needs to be incremented
7132 			 * before doing a LAYOUT_RECALL callback.
7133 			 */
7134 			if (++lyp->lay_stateid.seqid == 0)
7135 				lyp->lay_stateid.seqid = 1;
7136 			clientid = lyp->lay_clientid;
7137 			stateid = lyp->lay_stateid;
7138 			NFSBCOPY(&lyp->lay_fh, &fh, sizeof(fh));
7139 			laytype = lyp->lay_type;
7140 			break;
7141 		}
7142 	}
7143 	NFSUNLOCKLAYOUT(lhyp);
7144 	if (lyp != NULL) {
7145 		error = nfsrv_recalllayout(clientid, &stateid, &fh, NULL, 0,
7146 		    laytype, p);
7147 		if (error != 0 && error != NFSERR_NOMATCHLAYOUT)
7148 			NFSD_DEBUG(4, "recallold=%d\n", error);
7149 		if (error != 0) {
7150 			NFSLOCKLAYOUT(lhyp);
7151 			/*
7152 			 * Since the hash list was unlocked, we need to
7153 			 * find it again.
7154 			 */
7155 			ret = nfsrv_findlayout(&clientid, &fh, laytype, p,
7156 			    &lyp);
7157 			if (ret == 0 &&
7158 			    (lyp->lay_flags & NFSLAY_CALLB) != 0 &&
7159 			    lyp->lay_stateid.other[0] == stateid.other[0] &&
7160 			    lyp->lay_stateid.other[1] == stateid.other[1] &&
7161 			    lyp->lay_stateid.other[2] == stateid.other[2]) {
7162 				/*
7163 				 * The client no longer knows this layout, so
7164 				 * it can be free'd now.
7165 				 */
7166 				if (error == NFSERR_NOMATCHLAYOUT)
7167 					nfsrv_freelayout(&lhyp->list, lyp);
7168 				else {
7169 					/*
7170 					 * Leave it to be tried later by
7171 					 * clearing NFSLAY_CALLB and moving
7172 					 * it to the head of the list, so it
7173 					 * won't be tried again for a while.
7174 					 */
7175 					lyp->lay_flags &= ~NFSLAY_CALLB;
7176 					TAILQ_REMOVE(&lhyp->list, lyp,
7177 					    lay_list);
7178 					TAILQ_INSERT_HEAD(&lhyp->list, lyp,
7179 					    lay_list);
7180 				}
7181 			}
7182 			NFSUNLOCKLAYOUT(lhyp);
7183 		}
7184 	}
7185 }
7186 
7187 /*
7188  * Try and return layout(s).
7189  */
7190 int
7191 nfsrv_layoutreturn(struct nfsrv_descript *nd, vnode_t vp,
7192     int layouttype, int iomode, uint64_t offset, uint64_t len, int reclaim,
7193     int kind, nfsv4stateid_t *stateidp, int maxcnt, uint32_t *layp, int *fndp,
7194     struct ucred *cred, NFSPROC_T *p)
7195 {
7196 	struct nfsvattr na;
7197 	struct nfslayouthash *lhyp;
7198 	struct nfslayout *lyp;
7199 	fhandle_t fh;
7200 	int error = 0;
7201 
7202 	*fndp = 0;
7203 	if (kind == NFSV4LAYOUTRET_FILE) {
7204 		error = nfsvno_getfh(vp, &fh, p);
7205 		if (error == 0) {
7206 			error = nfsrv_updatemdsattr(vp, &na, p);
7207 			if (error != 0)
7208 				printf("nfsrv_layoutreturn: updatemdsattr"
7209 				    " failed=%d\n", error);
7210 		}
7211 		if (error == 0) {
7212 			if (reclaim == newnfs_true) {
7213 				error = nfsrv_checkgrace(NULL, NULL,
7214 				    NFSLCK_RECLAIM);
7215 				if (error != NFSERR_NOGRACE)
7216 					error = 0;
7217 				return (error);
7218 			}
7219 			lhyp = NFSLAYOUTHASH(&fh);
7220 			NFSDRECALLLOCK();
7221 			NFSLOCKLAYOUT(lhyp);
7222 			error = nfsrv_findlayout(&nd->nd_clientid, &fh,
7223 			    layouttype, p, &lyp);
7224 			NFSD_DEBUG(4, "layoutret findlay=%d\n", error);
7225 			if (error == 0 &&
7226 			    stateidp->other[0] == lyp->lay_stateid.other[0] &&
7227 			    stateidp->other[1] == lyp->lay_stateid.other[1] &&
7228 			    stateidp->other[2] == lyp->lay_stateid.other[2]) {
7229 				NFSD_DEBUG(4, "nfsrv_layoutreturn: stateid %d"
7230 				    " %x %x %x laystateid %d %x %x %x"
7231 				    " off=%ju len=%ju flgs=0x%x\n",
7232 				    stateidp->seqid, stateidp->other[0],
7233 				    stateidp->other[1], stateidp->other[2],
7234 				    lyp->lay_stateid.seqid,
7235 				    lyp->lay_stateid.other[0],
7236 				    lyp->lay_stateid.other[1],
7237 				    lyp->lay_stateid.other[2],
7238 				    (uintmax_t)offset, (uintmax_t)len,
7239 				    lyp->lay_flags);
7240 				if (++lyp->lay_stateid.seqid == 0)
7241 					lyp->lay_stateid.seqid = 1;
7242 				stateidp->seqid = lyp->lay_stateid.seqid;
7243 				if (offset == 0 && len == UINT64_MAX) {
7244 					if ((iomode & NFSLAYOUTIOMODE_READ) !=
7245 					    0)
7246 						lyp->lay_flags &= ~NFSLAY_READ;
7247 					if ((iomode & NFSLAYOUTIOMODE_RW) != 0)
7248 						lyp->lay_flags &= ~NFSLAY_RW;
7249 					if ((lyp->lay_flags & (NFSLAY_READ |
7250 					    NFSLAY_RW)) == 0)
7251 						nfsrv_freelayout(&lhyp->list,
7252 						    lyp);
7253 					else
7254 						*fndp = 1;
7255 				} else
7256 					*fndp = 1;
7257 			}
7258 			NFSUNLOCKLAYOUT(lhyp);
7259 			/* Search the nfsrv_recalllist for a match. */
7260 			TAILQ_FOREACH(lyp, &nfsrv_recalllisthead, lay_list) {
7261 				if (NFSBCMP(&lyp->lay_fh, &fh,
7262 				    sizeof(fh)) == 0 &&
7263 				    lyp->lay_clientid.qval ==
7264 				    nd->nd_clientid.qval &&
7265 				    stateidp->other[0] ==
7266 				    lyp->lay_stateid.other[0] &&
7267 				    stateidp->other[1] ==
7268 				    lyp->lay_stateid.other[1] &&
7269 				    stateidp->other[2] ==
7270 				    lyp->lay_stateid.other[2]) {
7271 					lyp->lay_flags |= NFSLAY_RETURNED;
7272 					wakeup(lyp);
7273 					error = 0;
7274 				}
7275 			}
7276 			NFSDRECALLUNLOCK();
7277 		}
7278 		if (layouttype == NFSLAYOUT_FLEXFILE)
7279 			nfsrv_flexlayouterr(nd, layp, maxcnt, p);
7280 	} else if (kind == NFSV4LAYOUTRET_FSID)
7281 		nfsrv_freelayouts(&nd->nd_clientid,
7282 		    &vp->v_mount->mnt_stat.f_fsid, layouttype, iomode);
7283 	else if (kind == NFSV4LAYOUTRET_ALL)
7284 		nfsrv_freelayouts(&nd->nd_clientid, NULL, layouttype, iomode);
7285 	else
7286 		error = NFSERR_INVAL;
7287 	if (error == -1)
7288 		error = 0;
7289 	return (error);
7290 }
7291 
7292 /*
7293  * Look for an existing layout.
7294  */
7295 static int
7296 nfsrv_findlayout(nfsquad_t *clientidp, fhandle_t *fhp, int laytype,
7297     NFSPROC_T *p, struct nfslayout **lypp)
7298 {
7299 	struct nfslayouthash *lhyp;
7300 	struct nfslayout *lyp;
7301 	int ret;
7302 
7303 	*lypp = NULL;
7304 	ret = 0;
7305 	lhyp = NFSLAYOUTHASH(fhp);
7306 	TAILQ_FOREACH(lyp, &lhyp->list, lay_list) {
7307 		if (NFSBCMP(&lyp->lay_fh, fhp, sizeof(*fhp)) == 0 &&
7308 		    lyp->lay_clientid.qval == clientidp->qval &&
7309 		    lyp->lay_type == laytype)
7310 			break;
7311 	}
7312 	if (lyp != NULL)
7313 		*lypp = lyp;
7314 	else
7315 		ret = -1;
7316 	return (ret);
7317 }
7318 
7319 /*
7320  * Add the new layout, as required.
7321  */
7322 static int
7323 nfsrv_addlayout(struct nfsrv_descript *nd, struct nfslayout **lypp,
7324     nfsv4stateid_t *stateidp, char *layp, int *layoutlenp, NFSPROC_T *p)
7325 {
7326 	struct nfsclient *clp;
7327 	struct nfslayouthash *lhyp;
7328 	struct nfslayout *lyp, *nlyp;
7329 	fhandle_t *fhp;
7330 	int error;
7331 
7332 	KASSERT((nd->nd_flag & ND_IMPLIEDCLID) != 0,
7333 	    ("nfsrv_layoutget: no nd_clientid\n"));
7334 	lyp = *lypp;
7335 	fhp = &lyp->lay_fh;
7336 	NFSLOCKSTATE();
7337 	error = nfsrv_getclient((nfsquad_t)((u_quad_t)0), CLOPS_RENEW, &clp,
7338 	    NULL, (nfsquad_t)((u_quad_t)0), 0, nd, p);
7339 	if (error != 0) {
7340 		NFSUNLOCKSTATE();
7341 		return (error);
7342 	}
7343 	lyp->lay_stateid.seqid = stateidp->seqid = 1;
7344 	lyp->lay_stateid.other[0] = stateidp->other[0] =
7345 	    clp->lc_clientid.lval[0];
7346 	lyp->lay_stateid.other[1] = stateidp->other[1] =
7347 	    clp->lc_clientid.lval[1];
7348 	lyp->lay_stateid.other[2] = stateidp->other[2] =
7349 	    nfsrv_nextstateindex(clp);
7350 	NFSUNLOCKSTATE();
7351 
7352 	lhyp = NFSLAYOUTHASH(fhp);
7353 	NFSLOCKLAYOUT(lhyp);
7354 	TAILQ_FOREACH(nlyp, &lhyp->list, lay_list) {
7355 		if (NFSBCMP(&nlyp->lay_fh, fhp, sizeof(*fhp)) == 0 &&
7356 		    nlyp->lay_clientid.qval == nd->nd_clientid.qval)
7357 			break;
7358 	}
7359 	if (nlyp != NULL) {
7360 		/* A layout already exists, so use it. */
7361 		nlyp->lay_flags |= (lyp->lay_flags & (NFSLAY_READ | NFSLAY_RW));
7362 		NFSBCOPY(nlyp->lay_xdr, layp, nlyp->lay_layoutlen);
7363 		*layoutlenp = nlyp->lay_layoutlen;
7364 		if (++nlyp->lay_stateid.seqid == 0)
7365 			nlyp->lay_stateid.seqid = 1;
7366 		stateidp->seqid = nlyp->lay_stateid.seqid;
7367 		stateidp->other[0] = nlyp->lay_stateid.other[0];
7368 		stateidp->other[1] = nlyp->lay_stateid.other[1];
7369 		stateidp->other[2] = nlyp->lay_stateid.other[2];
7370 		NFSUNLOCKLAYOUT(lhyp);
7371 		return (0);
7372 	}
7373 
7374 	/* Insert the new layout in the lists. */
7375 	*lypp = NULL;
7376 	atomic_add_int(&nfsrv_layoutcnt, 1);
7377 	NFSBCOPY(lyp->lay_xdr, layp, lyp->lay_layoutlen);
7378 	*layoutlenp = lyp->lay_layoutlen;
7379 	TAILQ_INSERT_HEAD(&lhyp->list, lyp, lay_list);
7380 	NFSUNLOCKLAYOUT(lhyp);
7381 	return (0);
7382 }
7383 
7384 /*
7385  * Get the devinfo for a deviceid.
7386  */
7387 int
7388 nfsrv_getdevinfo(char *devid, int layouttype, uint32_t *maxcnt,
7389     uint32_t *notify, int *devaddrlen, char **devaddr)
7390 {
7391 	struct nfsdevice *ds;
7392 
7393 	if ((layouttype != NFSLAYOUT_NFSV4_1_FILES && layouttype !=
7394 	     NFSLAYOUT_FLEXFILE) ||
7395 	    (nfsrv_maxpnfsmirror > 1 && layouttype == NFSLAYOUT_NFSV4_1_FILES))
7396 		return (NFSERR_UNKNLAYOUTTYPE);
7397 
7398 	/*
7399 	 * Now, search for the device id.  Note that the structures won't go
7400 	 * away, but the order changes in the list.  As such, the lock only
7401 	 * needs to be held during the search through the list.
7402 	 */
7403 	NFSDDSLOCK();
7404 	TAILQ_FOREACH(ds, &nfsrv_devidhead, nfsdev_list) {
7405 		if (NFSBCMP(devid, ds->nfsdev_deviceid, NFSX_V4DEVICEID) == 0 &&
7406 		    ds->nfsdev_nmp != NULL)
7407 			break;
7408 	}
7409 	NFSDDSUNLOCK();
7410 	if (ds == NULL)
7411 		return (NFSERR_NOENT);
7412 
7413 	/* If the correct nfsdev_XXXXaddrlen is > 0, we have the device info. */
7414 	*devaddrlen = 0;
7415 	if (layouttype == NFSLAYOUT_NFSV4_1_FILES) {
7416 		*devaddrlen = ds->nfsdev_fileaddrlen;
7417 		*devaddr = ds->nfsdev_fileaddr;
7418 	} else if (layouttype == NFSLAYOUT_FLEXFILE) {
7419 		*devaddrlen = ds->nfsdev_flexaddrlen;
7420 		*devaddr = ds->nfsdev_flexaddr;
7421 	}
7422 	if (*devaddrlen == 0)
7423 		return (NFSERR_UNKNLAYOUTTYPE);
7424 
7425 	/*
7426 	 * The XDR overhead is 3 unsigned values: layout_type,
7427 	 * length_of_address and notify bitmap.
7428 	 * If the notify array is changed to not all zeros, the
7429 	 * count of unsigned values must be increased.
7430 	 */
7431 	if (*maxcnt > 0 && *maxcnt < NFSM_RNDUP(*devaddrlen) +
7432 	    3 * NFSX_UNSIGNED) {
7433 		*maxcnt = NFSM_RNDUP(*devaddrlen) + 3 * NFSX_UNSIGNED;
7434 		return (NFSERR_TOOSMALL);
7435 	}
7436 	return (0);
7437 }
7438 
7439 /*
7440  * Free a list of layout state structures.
7441  */
7442 static void
7443 nfsrv_freelayoutlist(nfsquad_t clientid)
7444 {
7445 	struct nfslayouthash *lhyp;
7446 	struct nfslayout *lyp, *nlyp;
7447 	int i;
7448 
7449 	for (i = 0; i < nfsrv_layouthashsize; i++) {
7450 		lhyp = &nfslayouthash[i];
7451 		NFSLOCKLAYOUT(lhyp);
7452 		TAILQ_FOREACH_SAFE(lyp, &lhyp->list, lay_list, nlyp) {
7453 			if (lyp->lay_clientid.qval == clientid.qval)
7454 				nfsrv_freelayout(&lhyp->list, lyp);
7455 		}
7456 		NFSUNLOCKLAYOUT(lhyp);
7457 	}
7458 }
7459 
7460 /*
7461  * Free up a layout.
7462  */
7463 static void
7464 nfsrv_freelayout(struct nfslayouthead *lhp, struct nfslayout *lyp)
7465 {
7466 
7467 	NFSD_DEBUG(4, "Freelayout=%p\n", lyp);
7468 	atomic_add_int(&nfsrv_layoutcnt, -1);
7469 	TAILQ_REMOVE(lhp, lyp, lay_list);
7470 	free(lyp, M_NFSDSTATE);
7471 }
7472 
7473 /*
7474  * Free up a device id.
7475  */
7476 void
7477 nfsrv_freeonedevid(struct nfsdevice *ds)
7478 {
7479 	int i;
7480 
7481 	atomic_add_int(&nfsrv_devidcnt, -1);
7482 	vrele(ds->nfsdev_dvp);
7483 	for (i = 0; i < nfsrv_dsdirsize; i++)
7484 		if (ds->nfsdev_dsdir[i] != NULL)
7485 			vrele(ds->nfsdev_dsdir[i]);
7486 	free(ds->nfsdev_fileaddr, M_NFSDSTATE);
7487 	free(ds->nfsdev_flexaddr, M_NFSDSTATE);
7488 	free(ds->nfsdev_host, M_NFSDSTATE);
7489 	free(ds, M_NFSDSTATE);
7490 }
7491 
7492 /*
7493  * Free up a device id and its mirrors.
7494  */
7495 static void
7496 nfsrv_freedevid(struct nfsdevice *ds)
7497 {
7498 
7499 	TAILQ_REMOVE(&nfsrv_devidhead, ds, nfsdev_list);
7500 	nfsrv_freeonedevid(ds);
7501 }
7502 
7503 /*
7504  * Free all layouts and device ids.
7505  * Done when the nfsd threads are shut down since there may be a new
7506  * modified device id list created when the nfsd is restarted.
7507  */
7508 void
7509 nfsrv_freealllayoutsanddevids(void)
7510 {
7511 	struct nfsdontlist *mrp, *nmrp;
7512 	struct nfslayout *lyp, *nlyp;
7513 
7514 	/* Get rid of the deviceid structures. */
7515 	nfsrv_freealldevids();
7516 	TAILQ_INIT(&nfsrv_devidhead);
7517 	nfsrv_devidcnt = 0;
7518 
7519 	/* Get rid of all layouts. */
7520 	nfsrv_freealllayouts();
7521 
7522 	/* Get rid of any nfsdontlist entries. */
7523 	LIST_FOREACH_SAFE(mrp, &nfsrv_dontlisthead, nfsmr_list, nmrp)
7524 		free(mrp, M_NFSDSTATE);
7525 	LIST_INIT(&nfsrv_dontlisthead);
7526 	nfsrv_dontlistlen = 0;
7527 
7528 	/* Free layouts in the recall list. */
7529 	TAILQ_FOREACH_SAFE(lyp, &nfsrv_recalllisthead, lay_list, nlyp)
7530 		nfsrv_freelayout(&nfsrv_recalllisthead, lyp);
7531 	TAILQ_INIT(&nfsrv_recalllisthead);
7532 }
7533 
7534 /*
7535  * Free layouts that match the arguments.
7536  */
7537 static void
7538 nfsrv_freelayouts(nfsquad_t *clid, fsid_t *fs, int laytype, int iomode)
7539 {
7540 	struct nfslayouthash *lhyp;
7541 	struct nfslayout *lyp, *nlyp;
7542 	int i;
7543 
7544 	for (i = 0; i < nfsrv_layouthashsize; i++) {
7545 		lhyp = &nfslayouthash[i];
7546 		NFSLOCKLAYOUT(lhyp);
7547 		TAILQ_FOREACH_SAFE(lyp, &lhyp->list, lay_list, nlyp) {
7548 			if (clid->qval != lyp->lay_clientid.qval)
7549 				continue;
7550 			if (fs != NULL && fsidcmp(fs, &lyp->lay_fsid) != 0)
7551 				continue;
7552 			if (laytype != lyp->lay_type)
7553 				continue;
7554 			if ((iomode & NFSLAYOUTIOMODE_READ) != 0)
7555 				lyp->lay_flags &= ~NFSLAY_READ;
7556 			if ((iomode & NFSLAYOUTIOMODE_RW) != 0)
7557 				lyp->lay_flags &= ~NFSLAY_RW;
7558 			if ((lyp->lay_flags & (NFSLAY_READ | NFSLAY_RW)) == 0)
7559 				nfsrv_freelayout(&lhyp->list, lyp);
7560 		}
7561 		NFSUNLOCKLAYOUT(lhyp);
7562 	}
7563 }
7564 
7565 /*
7566  * Free all layouts for the argument file.
7567  */
7568 void
7569 nfsrv_freefilelayouts(fhandle_t *fhp)
7570 {
7571 	struct nfslayouthash *lhyp;
7572 	struct nfslayout *lyp, *nlyp;
7573 
7574 	lhyp = NFSLAYOUTHASH(fhp);
7575 	NFSLOCKLAYOUT(lhyp);
7576 	TAILQ_FOREACH_SAFE(lyp, &lhyp->list, lay_list, nlyp) {
7577 		if (NFSBCMP(&lyp->lay_fh, fhp, sizeof(*fhp)) == 0)
7578 			nfsrv_freelayout(&lhyp->list, lyp);
7579 	}
7580 	NFSUNLOCKLAYOUT(lhyp);
7581 }
7582 
7583 /*
7584  * Free all layouts.
7585  */
7586 static void
7587 nfsrv_freealllayouts(void)
7588 {
7589 	struct nfslayouthash *lhyp;
7590 	struct nfslayout *lyp, *nlyp;
7591 	int i;
7592 
7593 	for (i = 0; i < nfsrv_layouthashsize; i++) {
7594 		lhyp = &nfslayouthash[i];
7595 		NFSLOCKLAYOUT(lhyp);
7596 		TAILQ_FOREACH_SAFE(lyp, &lhyp->list, lay_list, nlyp)
7597 			nfsrv_freelayout(&lhyp->list, lyp);
7598 		NFSUNLOCKLAYOUT(lhyp);
7599 	}
7600 }
7601 
7602 /*
7603  * Look up the mount path for the DS server.
7604  */
7605 static int
7606 nfsrv_setdsserver(char *dspathp, char *mdspathp, NFSPROC_T *p,
7607     struct nfsdevice **dsp)
7608 {
7609 	struct nameidata nd;
7610 	struct nfsdevice *ds;
7611 	struct mount *mp;
7612 	int error, i;
7613 	char *dsdirpath;
7614 	size_t dsdirsize;
7615 
7616 	NFSD_DEBUG(4, "setdssrv path=%s\n", dspathp);
7617 	*dsp = NULL;
7618 	NDINIT(&nd, LOOKUP, FOLLOW | LOCKSHARED | LOCKLEAF, UIO_SYSSPACE,
7619 	    dspathp, p);
7620 	error = namei(&nd);
7621 	NFSD_DEBUG(4, "lookup=%d\n", error);
7622 	if (error != 0)
7623 		return (error);
7624 	if (nd.ni_vp->v_type != VDIR) {
7625 		vput(nd.ni_vp);
7626 		NFSD_DEBUG(4, "dspath not dir\n");
7627 		return (ENOTDIR);
7628 	}
7629 	if (strcmp(nd.ni_vp->v_mount->mnt_vfc->vfc_name, "nfs") != 0) {
7630 		vput(nd.ni_vp);
7631 		NFSD_DEBUG(4, "dspath not an NFS mount\n");
7632 		return (ENXIO);
7633 	}
7634 
7635 	/*
7636 	 * Allocate a DS server structure with the NFS mounted directory
7637 	 * vnode reference counted, so that a non-forced dismount will
7638 	 * fail with EBUSY.
7639 	 * This structure is always linked into the list, even if an error
7640 	 * is being returned.  The caller will free the entire list upon
7641 	 * an error return.
7642 	 */
7643 	*dsp = ds = malloc(sizeof(*ds) + nfsrv_dsdirsize * sizeof(vnode_t),
7644 	    M_NFSDSTATE, M_WAITOK | M_ZERO);
7645 	ds->nfsdev_dvp = nd.ni_vp;
7646 	ds->nfsdev_nmp = VFSTONFS(nd.ni_vp->v_mount);
7647 	NFSVOPUNLOCK(nd.ni_vp);
7648 
7649 	dsdirsize = strlen(dspathp) + 16;
7650 	dsdirpath = malloc(dsdirsize, M_TEMP, M_WAITOK);
7651 	/* Now, create the DS directory structures. */
7652 	for (i = 0; i < nfsrv_dsdirsize; i++) {
7653 		snprintf(dsdirpath, dsdirsize, "%s/ds%d", dspathp, i);
7654 		NDINIT(&nd, LOOKUP, FOLLOW | LOCKSHARED | LOCKLEAF,
7655 		    UIO_SYSSPACE, dsdirpath, p);
7656 		error = namei(&nd);
7657 		NFSD_DEBUG(4, "dsdirpath=%s lookup=%d\n", dsdirpath, error);
7658 		if (error != 0)
7659 			break;
7660 		if (nd.ni_vp->v_type != VDIR) {
7661 			vput(nd.ni_vp);
7662 			error = ENOTDIR;
7663 			NFSD_DEBUG(4, "dsdirpath not a VDIR\n");
7664 			break;
7665 		}
7666 		if (strcmp(nd.ni_vp->v_mount->mnt_vfc->vfc_name, "nfs") != 0) {
7667 			vput(nd.ni_vp);
7668 			error = ENXIO;
7669 			NFSD_DEBUG(4, "dsdirpath not an NFS mount\n");
7670 			break;
7671 		}
7672 		ds->nfsdev_dsdir[i] = nd.ni_vp;
7673 		NFSVOPUNLOCK(nd.ni_vp);
7674 	}
7675 	free(dsdirpath, M_TEMP);
7676 
7677 	if (strlen(mdspathp) > 0) {
7678 		/*
7679 		 * This DS stores file for a specific MDS exported file
7680 		 * system.
7681 		 */
7682 		NDINIT(&nd, LOOKUP, FOLLOW | LOCKSHARED | LOCKLEAF,
7683 		    UIO_SYSSPACE, mdspathp, p);
7684 		error = namei(&nd);
7685 		NFSD_DEBUG(4, "mds lookup=%d\n", error);
7686 		if (error != 0)
7687 			goto out;
7688 		if (nd.ni_vp->v_type != VDIR) {
7689 			vput(nd.ni_vp);
7690 			error = ENOTDIR;
7691 			NFSD_DEBUG(4, "mdspath not dir\n");
7692 			goto out;
7693 		}
7694 		mp = nd.ni_vp->v_mount;
7695 		if ((mp->mnt_flag & MNT_EXPORTED) == 0) {
7696 			vput(nd.ni_vp);
7697 			error = ENXIO;
7698 			NFSD_DEBUG(4, "mdspath not an exported fs\n");
7699 			goto out;
7700 		}
7701 		ds->nfsdev_mdsfsid = mp->mnt_stat.f_fsid;
7702 		ds->nfsdev_mdsisset = 1;
7703 		vput(nd.ni_vp);
7704 	}
7705 
7706 out:
7707 	TAILQ_INSERT_TAIL(&nfsrv_devidhead, ds, nfsdev_list);
7708 	atomic_add_int(&nfsrv_devidcnt, 1);
7709 	return (error);
7710 }
7711 
7712 /*
7713  * Look up the mount path for the DS server and delete it.
7714  */
7715 int
7716 nfsrv_deldsserver(int op, char *dspathp, NFSPROC_T *p)
7717 {
7718 	struct mount *mp;
7719 	struct nfsmount *nmp;
7720 	struct nfsdevice *ds;
7721 	int error;
7722 
7723 	NFSD_DEBUG(4, "deldssrv path=%s\n", dspathp);
7724 	/*
7725 	 * Search for the path in the mount list.  Avoid looking the path
7726 	 * up, since this mount point may be hung, with associated locked
7727 	 * vnodes, etc.
7728 	 * Set NFSMNTP_CANCELRPCS so that any forced dismount will be blocked
7729 	 * until this completes.
7730 	 * As noted in the man page, this should be done before any forced
7731 	 * dismount on the mount point, but at least the handshake on
7732 	 * NFSMNTP_CANCELRPCS should make it safe.
7733 	 */
7734 	error = 0;
7735 	ds = NULL;
7736 	nmp = NULL;
7737 	mtx_lock(&mountlist_mtx);
7738 	TAILQ_FOREACH(mp, &mountlist, mnt_list) {
7739 		if (strcmp(mp->mnt_stat.f_mntonname, dspathp) == 0 &&
7740 		    strcmp(mp->mnt_stat.f_fstypename, "nfs") == 0 &&
7741 		    mp->mnt_data != NULL) {
7742 			nmp = VFSTONFS(mp);
7743 			NFSLOCKMNT(nmp);
7744 			if ((nmp->nm_privflag & (NFSMNTP_FORCEDISM |
7745 			     NFSMNTP_CANCELRPCS)) == 0) {
7746 				nmp->nm_privflag |= NFSMNTP_CANCELRPCS;
7747 				NFSUNLOCKMNT(nmp);
7748 			} else {
7749 				NFSUNLOCKMNT(nmp);
7750 				nmp = NULL;
7751 			}
7752 			break;
7753 		}
7754 	}
7755 	mtx_unlock(&mountlist_mtx);
7756 
7757 	if (nmp != NULL) {
7758 		ds = nfsrv_deldsnmp(op, nmp, p);
7759 		NFSD_DEBUG(4, "deldsnmp=%p\n", ds);
7760 		if (ds != NULL) {
7761 			nfsrv_killrpcs(nmp);
7762 			NFSD_DEBUG(4, "aft killrpcs\n");
7763 		} else
7764 			error = ENXIO;
7765 		NFSLOCKMNT(nmp);
7766 		nmp->nm_privflag &= ~NFSMNTP_CANCELRPCS;
7767 		wakeup(nmp);
7768 		NFSUNLOCKMNT(nmp);
7769 	} else
7770 		error = EINVAL;
7771 	return (error);
7772 }
7773 
7774 /*
7775  * Search for and remove a DS entry which matches the "nmp" argument.
7776  * The nfsdevice structure pointer is returned so that the caller can
7777  * free it via nfsrv_freeonedevid().
7778  * For the forced case, do not try to do LayoutRecalls, since the server
7779  * must be shut down now anyhow.
7780  */
7781 struct nfsdevice *
7782 nfsrv_deldsnmp(int op, struct nfsmount *nmp, NFSPROC_T *p)
7783 {
7784 	struct nfsdevice *fndds;
7785 
7786 	NFSD_DEBUG(4, "deldsdvp\n");
7787 	NFSDDSLOCK();
7788 	if (op == PNFSDOP_FORCEDELDS)
7789 		fndds = nfsv4_findmirror(nmp);
7790 	else
7791 		fndds = nfsrv_findmirroredds(nmp);
7792 	if (fndds != NULL)
7793 		nfsrv_deleteds(fndds);
7794 	NFSDDSUNLOCK();
7795 	if (fndds != NULL) {
7796 		if (op != PNFSDOP_FORCEDELDS)
7797 			nfsrv_flexmirrordel(fndds->nfsdev_deviceid, p);
7798 		printf("pNFS server: mirror %s failed\n", fndds->nfsdev_host);
7799 	}
7800 	return (fndds);
7801 }
7802 
7803 /*
7804  * Similar to nfsrv_deldsnmp(), except that the DS is indicated by deviceid.
7805  * This function also calls nfsrv_killrpcs() to unblock RPCs on the mount
7806  * point.
7807  * Also, returns an error instead of the nfsdevice found.
7808  */
7809 int
7810 nfsrv_delds(char *devid, NFSPROC_T *p)
7811 {
7812 	struct nfsdevice *ds, *fndds;
7813 	struct nfsmount *nmp;
7814 	int fndmirror;
7815 
7816 	NFSD_DEBUG(4, "delds\n");
7817 	/*
7818 	 * Search the DS server list for a match with devid.
7819 	 * Remove the DS entry if found and there is a mirror.
7820 	 */
7821 	fndds = NULL;
7822 	nmp = NULL;
7823 	fndmirror = 0;
7824 	NFSDDSLOCK();
7825 	TAILQ_FOREACH(ds, &nfsrv_devidhead, nfsdev_list) {
7826 		if (NFSBCMP(ds->nfsdev_deviceid, devid, NFSX_V4DEVICEID) == 0 &&
7827 		    ds->nfsdev_nmp != NULL) {
7828 			NFSD_DEBUG(4, "fnd main ds\n");
7829 			fndds = ds;
7830 			break;
7831 		}
7832 	}
7833 	if (fndds == NULL) {
7834 		NFSDDSUNLOCK();
7835 		return (ENXIO);
7836 	}
7837 	if (fndds->nfsdev_mdsisset == 0 && nfsrv_faildscnt > 0)
7838 		fndmirror = 1;
7839 	else if (fndds->nfsdev_mdsisset != 0) {
7840 		/* For the fsid is set case, search for a mirror. */
7841 		TAILQ_FOREACH(ds, &nfsrv_devidhead, nfsdev_list) {
7842 			if (ds != fndds && ds->nfsdev_nmp != NULL &&
7843 			    ds->nfsdev_mdsisset != 0 &&
7844 			    fsidcmp(&ds->nfsdev_mdsfsid,
7845 			    &fndds->nfsdev_mdsfsid) == 0) {
7846 				fndmirror = 1;
7847 				break;
7848 			}
7849 		}
7850 	}
7851 	if (fndmirror != 0) {
7852 		nmp = fndds->nfsdev_nmp;
7853 		NFSLOCKMNT(nmp);
7854 		if ((nmp->nm_privflag & (NFSMNTP_FORCEDISM |
7855 		     NFSMNTP_CANCELRPCS)) == 0) {
7856 			nmp->nm_privflag |= NFSMNTP_CANCELRPCS;
7857 			NFSUNLOCKMNT(nmp);
7858 			nfsrv_deleteds(fndds);
7859 		} else {
7860 			NFSUNLOCKMNT(nmp);
7861 			nmp = NULL;
7862 		}
7863 	}
7864 	NFSDDSUNLOCK();
7865 	if (nmp != NULL) {
7866 		nfsrv_flexmirrordel(fndds->nfsdev_deviceid, p);
7867 		printf("pNFS server: mirror %s failed\n", fndds->nfsdev_host);
7868 		nfsrv_killrpcs(nmp);
7869 		NFSLOCKMNT(nmp);
7870 		nmp->nm_privflag &= ~NFSMNTP_CANCELRPCS;
7871 		wakeup(nmp);
7872 		NFSUNLOCKMNT(nmp);
7873 		return (0);
7874 	}
7875 	return (ENXIO);
7876 }
7877 
7878 /*
7879  * Mark a DS as disabled by setting nfsdev_nmp = NULL.
7880  */
7881 static void
7882 nfsrv_deleteds(struct nfsdevice *fndds)
7883 {
7884 
7885 	NFSD_DEBUG(4, "deleteds: deleting a mirror\n");
7886 	fndds->nfsdev_nmp = NULL;
7887 	if (fndds->nfsdev_mdsisset == 0)
7888 		nfsrv_faildscnt--;
7889 }
7890 
7891 /*
7892  * Fill in the addr structures for the File and Flex File layouts.
7893  */
7894 static void
7895 nfsrv_allocdevid(struct nfsdevice *ds, char *addr, char *dnshost)
7896 {
7897 	uint32_t *tl;
7898 	char *netprot;
7899 	int addrlen;
7900 	static uint64_t new_devid = 0;
7901 
7902 	if (strchr(addr, ':') != NULL)
7903 		netprot = "tcp6";
7904 	else
7905 		netprot = "tcp";
7906 
7907 	/* Fill in the device id. */
7908 	NFSBCOPY(&nfsdev_time, ds->nfsdev_deviceid, sizeof(nfsdev_time));
7909 	new_devid++;
7910 	NFSBCOPY(&new_devid, &ds->nfsdev_deviceid[sizeof(nfsdev_time)],
7911 	    sizeof(new_devid));
7912 
7913 	/*
7914 	 * Fill in the file addr (actually the nfsv4_file_layout_ds_addr4
7915 	 * as defined in RFC5661) in XDR.
7916 	 */
7917 	addrlen = NFSM_RNDUP(strlen(addr)) + NFSM_RNDUP(strlen(netprot)) +
7918 	    6 * NFSX_UNSIGNED;
7919 	NFSD_DEBUG(4, "hn=%s addr=%s netprot=%s\n", dnshost, addr, netprot);
7920 	ds->nfsdev_fileaddrlen = addrlen;
7921 	tl = malloc(addrlen, M_NFSDSTATE, M_WAITOK | M_ZERO);
7922 	ds->nfsdev_fileaddr = (char *)tl;
7923 	*tl++ = txdr_unsigned(1);		/* One stripe with index 0. */
7924 	*tl++ = 0;
7925 	*tl++ = txdr_unsigned(1);		/* One multipath list */
7926 	*tl++ = txdr_unsigned(1);		/* with one entry in it. */
7927 	/* The netaddr for this one entry. */
7928 	*tl++ = txdr_unsigned(strlen(netprot));
7929 	NFSBCOPY(netprot, tl, strlen(netprot));
7930 	tl += (NFSM_RNDUP(strlen(netprot)) / NFSX_UNSIGNED);
7931 	*tl++ = txdr_unsigned(strlen(addr));
7932 	NFSBCOPY(addr, tl, strlen(addr));
7933 
7934 	/*
7935 	 * Fill in the flex file addr (actually the ff_device_addr4
7936 	 * as defined for Flexible File Layout) in XDR.
7937 	 */
7938 	addrlen = NFSM_RNDUP(strlen(addr)) + NFSM_RNDUP(strlen(netprot)) +
7939 	    14 * NFSX_UNSIGNED;
7940 	ds->nfsdev_flexaddrlen = addrlen;
7941 	tl = malloc(addrlen, M_NFSDSTATE, M_WAITOK | M_ZERO);
7942 	ds->nfsdev_flexaddr = (char *)tl;
7943 	*tl++ = txdr_unsigned(1);		/* One multipath entry. */
7944 	/* The netaddr for this one entry. */
7945 	*tl++ = txdr_unsigned(strlen(netprot));
7946 	NFSBCOPY(netprot, tl, strlen(netprot));
7947 	tl += (NFSM_RNDUP(strlen(netprot)) / NFSX_UNSIGNED);
7948 	*tl++ = txdr_unsigned(strlen(addr));
7949 	NFSBCOPY(addr, tl, strlen(addr));
7950 	tl += (NFSM_RNDUP(strlen(addr)) / NFSX_UNSIGNED);
7951 	*tl++ = txdr_unsigned(2);		/* Two NFS Versions. */
7952 	*tl++ = txdr_unsigned(NFS_VER4);	/* NFSv4. */
7953 	*tl++ = txdr_unsigned(NFSV42_MINORVERSION); /* Minor version 2. */
7954 	*tl++ = txdr_unsigned(NFS_SRVMAXIO);	/* DS max rsize. */
7955 	*tl++ = txdr_unsigned(NFS_SRVMAXIO);	/* DS max wsize. */
7956 	*tl++ = newnfs_true;			/* Tightly coupled. */
7957 	*tl++ = txdr_unsigned(NFS_VER4);	/* NFSv4. */
7958 	*tl++ = txdr_unsigned(NFSV41_MINORVERSION); /* Minor version 1. */
7959 	*tl++ = txdr_unsigned(NFS_SRVMAXIO);	/* DS max rsize. */
7960 	*tl++ = txdr_unsigned(NFS_SRVMAXIO);	/* DS max wsize. */
7961 	*tl = newnfs_true;			/* Tightly coupled. */
7962 
7963 	ds->nfsdev_hostnamelen = strlen(dnshost);
7964 	ds->nfsdev_host = malloc(ds->nfsdev_hostnamelen + 1, M_NFSDSTATE,
7965 	    M_WAITOK);
7966 	NFSBCOPY(dnshost, ds->nfsdev_host, ds->nfsdev_hostnamelen + 1);
7967 }
7968 
7969 /*
7970  * Create the device id list.
7971  * Return 0 if the nfsd threads are to run and ENXIO if the "-p" argument
7972  * is misconfigured.
7973  */
7974 int
7975 nfsrv_createdevids(struct nfsd_nfsd_args *args, NFSPROC_T *p)
7976 {
7977 	struct nfsdevice *ds;
7978 	char *addrp, *dnshostp, *dspathp, *mdspathp;
7979 	int error, i;
7980 
7981 	addrp = args->addr;
7982 	dnshostp = args->dnshost;
7983 	dspathp = args->dspath;
7984 	mdspathp = args->mdspath;
7985 	nfsrv_maxpnfsmirror = args->mirrorcnt;
7986 	if (addrp == NULL || dnshostp == NULL || dspathp == NULL ||
7987 	    mdspathp == NULL)
7988 		return (0);
7989 
7990 	/*
7991 	 * Loop around for each nul-terminated string in args->addr,
7992 	 * args->dnshost, args->dnspath and args->mdspath.
7993 	 */
7994 	while (addrp < (args->addr + args->addrlen) &&
7995 	    dnshostp < (args->dnshost + args->dnshostlen) &&
7996 	    dspathp < (args->dspath + args->dspathlen) &&
7997 	    mdspathp < (args->mdspath + args->mdspathlen)) {
7998 		error = nfsrv_setdsserver(dspathp, mdspathp, p, &ds);
7999 		if (error != 0) {
8000 			/* Free all DS servers. */
8001 			nfsrv_freealldevids();
8002 			nfsrv_devidcnt = 0;
8003 			return (ENXIO);
8004 		}
8005 		nfsrv_allocdevid(ds, addrp, dnshostp);
8006 		addrp += (strlen(addrp) + 1);
8007 		dnshostp += (strlen(dnshostp) + 1);
8008 		dspathp += (strlen(dspathp) + 1);
8009 		mdspathp += (strlen(mdspathp) + 1);
8010 	}
8011 	if (nfsrv_devidcnt < nfsrv_maxpnfsmirror) {
8012 		/* Free all DS servers. */
8013 		nfsrv_freealldevids();
8014 		nfsrv_devidcnt = 0;
8015 		nfsrv_maxpnfsmirror = 1;
8016 		return (ENXIO);
8017 	}
8018 	/* We can fail at most one less DS than the mirror level. */
8019 	nfsrv_faildscnt = nfsrv_maxpnfsmirror - 1;
8020 
8021 	/*
8022 	 * Allocate the nfslayout hash table now, since this is a pNFS server.
8023 	 * Make it 1% of the high water mark and at least 100.
8024 	 */
8025 	if (nfslayouthash == NULL) {
8026 		nfsrv_layouthashsize = nfsrv_layouthighwater / 100;
8027 		if (nfsrv_layouthashsize < 100)
8028 			nfsrv_layouthashsize = 100;
8029 		nfslayouthash = mallocarray(nfsrv_layouthashsize,
8030 		    sizeof(struct nfslayouthash), M_NFSDSESSION, M_WAITOK |
8031 		    M_ZERO);
8032 		for (i = 0; i < nfsrv_layouthashsize; i++) {
8033 			mtx_init(&nfslayouthash[i].mtx, "nfslm", NULL, MTX_DEF);
8034 			TAILQ_INIT(&nfslayouthash[i].list);
8035 		}
8036 	}
8037 	return (0);
8038 }
8039 
8040 /*
8041  * Free all device ids.
8042  */
8043 static void
8044 nfsrv_freealldevids(void)
8045 {
8046 	struct nfsdevice *ds, *nds;
8047 
8048 	TAILQ_FOREACH_SAFE(ds, &nfsrv_devidhead, nfsdev_list, nds)
8049 		nfsrv_freedevid(ds);
8050 }
8051 
8052 /*
8053  * Check to see if there is a Read/Write Layout plus either:
8054  * - A Write Delegation
8055  * or
8056  * - An Open with Write_access.
8057  * Return 1 if this is the case and 0 otherwise.
8058  * This function is used by nfsrv_proxyds() to decide if doing a Proxy
8059  * Getattr RPC to the Data Server (DS) is necessary.
8060  */
8061 #define	NFSCLIDVECSIZE	6
8062 int
8063 nfsrv_checkdsattr(vnode_t vp, NFSPROC_T *p)
8064 {
8065 	fhandle_t fh, *tfhp;
8066 	struct nfsstate *stp;
8067 	struct nfslayout *lyp;
8068 	struct nfslayouthash *lhyp;
8069 	struct nfslockhashhead *hp;
8070 	struct nfslockfile *lfp;
8071 	nfsquad_t clid[NFSCLIDVECSIZE];
8072 	int clidcnt, ret;
8073 
8074 	ret = nfsvno_getfh(vp, &fh, p);
8075 	if (ret != 0)
8076 		return (0);
8077 
8078 	/* First check for a Read/Write Layout. */
8079 	clidcnt = 0;
8080 	lhyp = NFSLAYOUTHASH(&fh);
8081 	NFSLOCKLAYOUT(lhyp);
8082 	TAILQ_FOREACH(lyp, &lhyp->list, lay_list) {
8083 		if (NFSBCMP(&lyp->lay_fh, &fh, sizeof(fh)) == 0 &&
8084 		    ((lyp->lay_flags & NFSLAY_RW) != 0 ||
8085 		     ((lyp->lay_flags & NFSLAY_READ) != 0 &&
8086 		      nfsrv_pnfsatime != 0))) {
8087 			if (clidcnt < NFSCLIDVECSIZE)
8088 				clid[clidcnt].qval = lyp->lay_clientid.qval;
8089 			clidcnt++;
8090 		}
8091 	}
8092 	NFSUNLOCKLAYOUT(lhyp);
8093 	if (clidcnt == 0) {
8094 		/* None found, so return 0. */
8095 		return (0);
8096 	}
8097 
8098 	/* Get the nfslockfile for this fh. */
8099 	NFSLOCKSTATE();
8100 	hp = NFSLOCKHASH(&fh);
8101 	LIST_FOREACH(lfp, hp, lf_hash) {
8102 		tfhp = &lfp->lf_fh;
8103 		if (NFSVNO_CMPFH(&fh, tfhp))
8104 			break;
8105 	}
8106 	if (lfp == NULL) {
8107 		/* None found, so return 0. */
8108 		NFSUNLOCKSTATE();
8109 		return (0);
8110 	}
8111 
8112 	/* Now, look for a Write delegation for this clientid. */
8113 	LIST_FOREACH(stp, &lfp->lf_deleg, ls_file) {
8114 		if ((stp->ls_flags & NFSLCK_DELEGWRITE) != 0 &&
8115 		    nfsrv_fndclid(clid, stp->ls_clp->lc_clientid, clidcnt) != 0)
8116 			break;
8117 	}
8118 	if (stp != NULL) {
8119 		/* Found one, so return 1. */
8120 		NFSUNLOCKSTATE();
8121 		return (1);
8122 	}
8123 
8124 	/* No Write delegation, so look for an Open with Write_access. */
8125 	LIST_FOREACH(stp, &lfp->lf_open, ls_file) {
8126 		KASSERT((stp->ls_flags & NFSLCK_OPEN) != 0,
8127 		    ("nfsrv_checkdsattr: Non-open in Open list\n"));
8128 		if ((stp->ls_flags & NFSLCK_WRITEACCESS) != 0 &&
8129 		    nfsrv_fndclid(clid, stp->ls_clp->lc_clientid, clidcnt) != 0)
8130 			break;
8131 	}
8132 	NFSUNLOCKSTATE();
8133 	if (stp != NULL)
8134 		return (1);
8135 	return (0);
8136 }
8137 
8138 /*
8139  * Look for a matching clientid in the vector. Return 1 if one might match.
8140  */
8141 static int
8142 nfsrv_fndclid(nfsquad_t *clidvec, nfsquad_t clid, int clidcnt)
8143 {
8144 	int i;
8145 
8146 	/* If too many for the vector, return 1 since there might be a match. */
8147 	if (clidcnt > NFSCLIDVECSIZE)
8148 		return (1);
8149 
8150 	for (i = 0; i < clidcnt; i++)
8151 		if (clidvec[i].qval == clid.qval)
8152 			return (1);
8153 	return (0);
8154 }
8155 
8156 /*
8157  * Check the don't list for "vp" and see if issuing an rw layout is allowed.
8158  * Return 1 if issuing an rw layout isn't allowed, 0 otherwise.
8159  */
8160 static int
8161 nfsrv_dontlayout(fhandle_t *fhp)
8162 {
8163 	struct nfsdontlist *mrp;
8164 	int ret;
8165 
8166 	if (nfsrv_dontlistlen == 0)
8167 		return (0);
8168 	ret = 0;
8169 	NFSDDONTLISTLOCK();
8170 	LIST_FOREACH(mrp, &nfsrv_dontlisthead, nfsmr_list) {
8171 		if (NFSBCMP(fhp, &mrp->nfsmr_fh, sizeof(*fhp)) == 0 &&
8172 		    (mrp->nfsmr_flags & NFSMR_DONTLAYOUT) != 0) {
8173 			ret = 1;
8174 			break;
8175 		}
8176 	}
8177 	NFSDDONTLISTUNLOCK();
8178 	return (ret);
8179 }
8180 
8181 #define	PNFSDS_COPYSIZ	65536
8182 /*
8183  * Create a new file on a DS and copy the contents of an extant DS file to it.
8184  * This can be used for recovery of a DS file onto a recovered DS.
8185  * The steps are:
8186  * - When called, the MDS file's vnode is locked, blocking LayoutGet operations.
8187  * - Disable issuing of read/write layouts for the file via the nfsdontlist,
8188  *   so that they will be disabled after the MDS file's vnode is unlocked.
8189  * - Set up the nfsrv_recalllist so that recall of read/write layouts can
8190  *   be done.
8191  * - Unlock the MDS file's vnode, so that the client(s) can perform proxied
8192  *   writes, LayoutCommits and LayoutReturns for the file when completing the
8193  *   LayoutReturn requested by the LayoutRecall callback.
8194  * - Issue a LayoutRecall callback for all read/write layouts and wait for
8195  *   them to be returned. (If the LayoutRecall callback replies
8196  *   NFSERR_NOMATCHLAYOUT, they are gone and no LayoutReturn is needed.)
8197  * - Exclusively lock the MDS file's vnode.  This ensures that no proxied
8198  *   writes are in progress or can occur during the DS file copy.
8199  *   It also blocks Setattr operations.
8200  * - Create the file on the recovered mirror.
8201  * - Copy the file from the operational DS.
8202  * - Copy any ACL from the MDS file to the new DS file.
8203  * - Set the modify time of the new DS file to that of the MDS file.
8204  * - Update the extended attribute for the MDS file.
8205  * - Enable issuing of rw layouts by deleting the nfsdontlist entry.
8206  * - The caller will unlock the MDS file's vnode allowing operations
8207  *   to continue normally, since it is now on the mirror again.
8208  */
8209 int
8210 nfsrv_copymr(vnode_t vp, vnode_t fvp, vnode_t dvp, struct nfsdevice *ds,
8211     struct pnfsdsfile *pf, struct pnfsdsfile *wpf, int mirrorcnt,
8212     struct ucred *cred, NFSPROC_T *p)
8213 {
8214 	struct nfsdontlist *mrp, *nmrp;
8215 	struct nfslayouthash *lhyp;
8216 	struct nfslayout *lyp, *nlyp;
8217 	struct nfslayouthead thl;
8218 	struct mount *mp, *tvmp;
8219 	struct acl *aclp;
8220 	struct vattr va;
8221 	struct timespec mtime;
8222 	fhandle_t fh;
8223 	vnode_t tvp;
8224 	off_t rdpos, wrpos;
8225 	ssize_t aresid;
8226 	char *dat;
8227 	int didprintf, ret, retacl, xfer;
8228 
8229 	ASSERT_VOP_LOCKED(fvp, "nfsrv_copymr fvp");
8230 	ASSERT_VOP_LOCKED(vp, "nfsrv_copymr vp");
8231 	/*
8232 	 * Allocate a nfsdontlist entry and set the NFSMR_DONTLAYOUT flag
8233 	 * so that no more RW layouts will get issued.
8234 	 */
8235 	ret = nfsvno_getfh(vp, &fh, p);
8236 	if (ret != 0) {
8237 		NFSD_DEBUG(4, "nfsrv_copymr: getfh=%d\n", ret);
8238 		return (ret);
8239 	}
8240 	nmrp = malloc(sizeof(*nmrp), M_NFSDSTATE, M_WAITOK);
8241 	nmrp->nfsmr_flags = NFSMR_DONTLAYOUT;
8242 	NFSBCOPY(&fh, &nmrp->nfsmr_fh, sizeof(fh));
8243 	NFSDDONTLISTLOCK();
8244 	LIST_FOREACH(mrp, &nfsrv_dontlisthead, nfsmr_list) {
8245 		if (NFSBCMP(&fh, &mrp->nfsmr_fh, sizeof(fh)) == 0)
8246 			break;
8247 	}
8248 	if (mrp == NULL) {
8249 		LIST_INSERT_HEAD(&nfsrv_dontlisthead, nmrp, nfsmr_list);
8250 		mrp = nmrp;
8251 		nmrp = NULL;
8252 		nfsrv_dontlistlen++;
8253 		NFSD_DEBUG(4, "nfsrv_copymr: in dontlist\n");
8254 	} else {
8255 		NFSDDONTLISTUNLOCK();
8256 		free(nmrp, M_NFSDSTATE);
8257 		NFSD_DEBUG(4, "nfsrv_copymr: dup dontlist\n");
8258 		return (ENXIO);
8259 	}
8260 	NFSDDONTLISTUNLOCK();
8261 
8262 	/*
8263 	 * Search for all RW layouts for this file.  Move them to the
8264 	 * recall list, so they can be recalled and their return noted.
8265 	 */
8266 	lhyp = NFSLAYOUTHASH(&fh);
8267 	NFSDRECALLLOCK();
8268 	NFSLOCKLAYOUT(lhyp);
8269 	TAILQ_FOREACH_SAFE(lyp, &lhyp->list, lay_list, nlyp) {
8270 		if (NFSBCMP(&lyp->lay_fh, &fh, sizeof(fh)) == 0 &&
8271 		    (lyp->lay_flags & NFSLAY_RW) != 0) {
8272 			TAILQ_REMOVE(&lhyp->list, lyp, lay_list);
8273 			TAILQ_INSERT_HEAD(&nfsrv_recalllisthead, lyp, lay_list);
8274 			lyp->lay_trycnt = 0;
8275 		}
8276 	}
8277 	NFSUNLOCKLAYOUT(lhyp);
8278 	NFSDRECALLUNLOCK();
8279 
8280 	ret = 0;
8281 	mp = tvmp = NULL;
8282 	didprintf = 0;
8283 	TAILQ_INIT(&thl);
8284 	/* Unlock the MDS vp, so that a LayoutReturn can be done on it. */
8285 	NFSVOPUNLOCK(vp);
8286 	/* Now, do a recall for all layouts not yet recalled. */
8287 tryagain:
8288 	NFSDRECALLLOCK();
8289 	TAILQ_FOREACH(lyp, &nfsrv_recalllisthead, lay_list) {
8290 		if (NFSBCMP(&lyp->lay_fh, &fh, sizeof(fh)) == 0 &&
8291 		    (lyp->lay_flags & NFSLAY_RECALL) == 0) {
8292 			lyp->lay_flags |= NFSLAY_RECALL;
8293 			/*
8294 			 * The layout stateid.seqid needs to be incremented
8295 			 * before doing a LAYOUT_RECALL callback.
8296 			 */
8297 			if (++lyp->lay_stateid.seqid == 0)
8298 				lyp->lay_stateid.seqid = 1;
8299 			NFSDRECALLUNLOCK();
8300 			nfsrv_recalllayout(lyp->lay_clientid, &lyp->lay_stateid,
8301 			    &lyp->lay_fh, lyp, 0, lyp->lay_type, p);
8302 			NFSD_DEBUG(4, "nfsrv_copymr: recalled layout\n");
8303 			goto tryagain;
8304 		}
8305 	}
8306 
8307 	/* Now wait for them to be returned. */
8308 tryagain2:
8309 	TAILQ_FOREACH(lyp, &nfsrv_recalllisthead, lay_list) {
8310 		if (NFSBCMP(&lyp->lay_fh, &fh, sizeof(fh)) == 0) {
8311 			if ((lyp->lay_flags & NFSLAY_RETURNED) != 0) {
8312 				TAILQ_REMOVE(&nfsrv_recalllisthead, lyp,
8313 				    lay_list);
8314 				TAILQ_INSERT_HEAD(&thl, lyp, lay_list);
8315 				NFSD_DEBUG(4,
8316 				    "nfsrv_copymr: layout returned\n");
8317 			} else {
8318 				lyp->lay_trycnt++;
8319 				ret = mtx_sleep(lyp, NFSDRECALLMUTEXPTR,
8320 				    PVFS | PCATCH, "nfsmrl", hz);
8321 				NFSD_DEBUG(4, "nfsrv_copymr: aft sleep=%d\n",
8322 				    ret);
8323 				if (ret == EINTR || ret == ERESTART)
8324 					break;
8325 				if ((lyp->lay_flags & NFSLAY_RETURNED) == 0) {
8326 					/*
8327 					 * Give up after 60sec and return
8328 					 * ENXIO, failing the copymr.
8329 					 * This layout will remain on the
8330 					 * recalllist.  It can only be cleared
8331 					 * by restarting the nfsd.
8332 					 * This seems the safe way to handle
8333 					 * it, since it cannot be safely copied
8334 					 * with an outstanding RW layout.
8335 					 */
8336 					if (lyp->lay_trycnt >= 60) {
8337 						ret = ENXIO;
8338 						break;
8339 					}
8340 					if (didprintf == 0) {
8341 						printf("nfsrv_copymr: layout "
8342 						    "not returned\n");
8343 						didprintf = 1;
8344 					}
8345 				}
8346 			}
8347 			goto tryagain2;
8348 		}
8349 	}
8350 	NFSDRECALLUNLOCK();
8351 	/* We can now get rid of the layouts that have been returned. */
8352 	TAILQ_FOREACH_SAFE(lyp, &thl, lay_list, nlyp)
8353 		nfsrv_freelayout(&thl, lyp);
8354 
8355 	/*
8356 	 * Do the vn_start_write() calls here, before the MDS vnode is
8357 	 * locked and the tvp is created (locked) in the NFS file system
8358 	 * that dvp is in.
8359 	 * For tvmp, this probably isn't necessary, since it will be an
8360 	 * NFS mount and they are not suspendable at this time.
8361 	 */
8362 	if (ret == 0)
8363 		ret = vn_start_write(vp, &mp, V_WAIT | PCATCH);
8364 	if (ret == 0) {
8365 		tvmp = dvp->v_mount;
8366 		ret = vn_start_write(NULL, &tvmp, V_WAIT | PCATCH);
8367 	}
8368 
8369 	/*
8370 	 * LK_EXCLUSIVE lock the MDS vnode, so that any
8371 	 * proxied writes through the MDS will be blocked until we have
8372 	 * completed the copy and update of the extended attributes.
8373 	 * This will also ensure that any attributes and ACL will not be
8374 	 * changed until the copy is complete.
8375 	 */
8376 	NFSVOPLOCK(vp, LK_EXCLUSIVE | LK_RETRY);
8377 	if (ret == 0 && VN_IS_DOOMED(vp)) {
8378 		NFSD_DEBUG(4, "nfsrv_copymr: lk_exclusive doomed\n");
8379 		ret = ESTALE;
8380 	}
8381 
8382 	/* Create the data file on the recovered DS. */
8383 	if (ret == 0)
8384 		ret = nfsrv_createdsfile(vp, &fh, pf, dvp, ds, cred, p, &tvp);
8385 
8386 	/* Copy the DS file, if created successfully. */
8387 	if (ret == 0) {
8388 		/*
8389 		 * Get any NFSv4 ACL on the MDS file, so that it can be set
8390 		 * on the new DS file.
8391 		 */
8392 		aclp = acl_alloc(M_WAITOK | M_ZERO);
8393 		retacl = VOP_GETACL(vp, ACL_TYPE_NFS4, aclp, cred, p);
8394 		if (retacl != 0 && retacl != ENOATTR)
8395 			NFSD_DEBUG(1, "nfsrv_copymr: vop_getacl=%d\n", retacl);
8396 		dat = malloc(PNFSDS_COPYSIZ, M_TEMP, M_WAITOK);
8397 		/* Malloc a block of 0s used to check for holes. */
8398 		if (nfsrv_zeropnfsdat == NULL)
8399 			nfsrv_zeropnfsdat = malloc(PNFSDS_COPYSIZ, M_TEMP,
8400 			    M_WAITOK | M_ZERO);
8401 		rdpos = wrpos = 0;
8402 		ret = VOP_GETATTR(fvp, &va, cred);
8403 		aresid = 0;
8404 		while (ret == 0 && aresid == 0) {
8405 			ret = vn_rdwr(UIO_READ, fvp, dat, PNFSDS_COPYSIZ,
8406 			    rdpos, UIO_SYSSPACE, IO_NODELOCKED, cred, NULL,
8407 			    &aresid, p);
8408 			xfer = PNFSDS_COPYSIZ - aresid;
8409 			if (ret == 0 && xfer > 0) {
8410 				rdpos += xfer;
8411 				/*
8412 				 * Skip the write for holes, except for the
8413 				 * last block.
8414 				 */
8415 				if (xfer < PNFSDS_COPYSIZ || rdpos ==
8416 				    va.va_size || NFSBCMP(dat,
8417 				    nfsrv_zeropnfsdat, PNFSDS_COPYSIZ) != 0)
8418 					ret = vn_rdwr(UIO_WRITE, tvp, dat, xfer,
8419 					    wrpos, UIO_SYSSPACE, IO_NODELOCKED,
8420 					    cred, NULL, NULL, p);
8421 				if (ret == 0)
8422 					wrpos += xfer;
8423 			}
8424 		}
8425 
8426 		/* If there is an ACL and the copy succeeded, set the ACL. */
8427 		if (ret == 0 && retacl == 0) {
8428 			ret = VOP_SETACL(tvp, ACL_TYPE_NFS4, aclp, cred, p);
8429 			/*
8430 			 * Don't consider these as errors, since VOP_GETACL()
8431 			 * can return an ACL when they are not actually
8432 			 * supported.  For example, for UFS, VOP_GETACL()
8433 			 * will return a trivial ACL based on the uid/gid/mode
8434 			 * when there is no ACL on the file.
8435 			 * This case should be recognized as a trivial ACL
8436 			 * by UFS's VOP_SETACL() and succeed, but...
8437 			 */
8438 			if (ret == ENOATTR || ret == EOPNOTSUPP || ret == EPERM)
8439 				ret = 0;
8440 		}
8441 
8442 		if (ret == 0)
8443 			ret = VOP_FSYNC(tvp, MNT_WAIT, p);
8444 
8445 		/* Set the DS data file's modify time that of the MDS file. */
8446 		if (ret == 0)
8447 			ret = VOP_GETATTR(vp, &va, cred);
8448 		if (ret == 0) {
8449 			mtime = va.va_mtime;
8450 			VATTR_NULL(&va);
8451 			va.va_mtime = mtime;
8452 			ret = VOP_SETATTR(tvp, &va, cred);
8453 		}
8454 
8455 		vput(tvp);
8456 		acl_free(aclp);
8457 		free(dat, M_TEMP);
8458 	}
8459 	if (tvmp != NULL)
8460 		vn_finished_write(tvmp);
8461 
8462 	/* Update the extended attributes for the newly created DS file. */
8463 	if (ret == 0)
8464 		ret = vn_extattr_set(vp, IO_NODELOCKED,
8465 		    EXTATTR_NAMESPACE_SYSTEM, "pnfsd.dsfile",
8466 		    sizeof(*wpf) * mirrorcnt, (char *)wpf, p);
8467 	if (mp != NULL)
8468 		vn_finished_write(mp);
8469 
8470 	/* Get rid of the dontlist entry, so that Layouts can be issued. */
8471 	NFSDDONTLISTLOCK();
8472 	LIST_REMOVE(mrp, nfsmr_list);
8473 	NFSDDONTLISTUNLOCK();
8474 	free(mrp, M_NFSDSTATE);
8475 	return (ret);
8476 }
8477 
8478 /*
8479  * Create a data storage file on the recovered DS.
8480  */
8481 static int
8482 nfsrv_createdsfile(vnode_t vp, fhandle_t *fhp, struct pnfsdsfile *pf,
8483     vnode_t dvp, struct nfsdevice *ds, struct ucred *cred, NFSPROC_T *p,
8484     vnode_t *tvpp)
8485 {
8486 	struct vattr va, nva;
8487 	int error;
8488 
8489 	/* Make data file name based on FH. */
8490 	error = VOP_GETATTR(vp, &va, cred);
8491 	if (error == 0) {
8492 		/* Set the attributes for "vp" to Setattr the DS vp. */
8493 		VATTR_NULL(&nva);
8494 		nva.va_uid = va.va_uid;
8495 		nva.va_gid = va.va_gid;
8496 		nva.va_mode = va.va_mode;
8497 		nva.va_size = 0;
8498 		VATTR_NULL(&va);
8499 		va.va_type = VREG;
8500 		va.va_mode = nva.va_mode;
8501 		NFSD_DEBUG(4, "nfsrv_dscreatefile: dvp=%p pf=%p\n", dvp, pf);
8502 		error = nfsrv_dscreate(dvp, &va, &nva, fhp, pf, NULL,
8503 		    pf->dsf_filename, cred, p, tvpp);
8504 	}
8505 	return (error);
8506 }
8507 
8508 /*
8509  * Look up the MDS file shared locked, and then get the extended attribute
8510  * to find the extant DS file to be copied to the new mirror.
8511  * If successful, *vpp is set to the MDS file's vp and *nvpp is
8512  * set to a DS data file for the MDS file, both exclusively locked.
8513  * The "buf" argument has the pnfsdsfile structure from the MDS file
8514  * in it and buflen is set to its length.
8515  */
8516 int
8517 nfsrv_mdscopymr(char *mdspathp, char *dspathp, char *curdspathp, char *buf,
8518     int *buflenp, char *fname, NFSPROC_T *p, struct vnode **vpp,
8519     struct vnode **nvpp, struct pnfsdsfile **pfp, struct nfsdevice **dsp,
8520     struct nfsdevice **fdsp)
8521 {
8522 	struct nameidata nd;
8523 	struct vnode *vp, *curvp;
8524 	struct pnfsdsfile *pf;
8525 	struct nfsmount *nmp, *curnmp;
8526 	int dsdir, error, mirrorcnt, ippos;
8527 
8528 	vp = NULL;
8529 	curvp = NULL;
8530 	curnmp = NULL;
8531 	*dsp = NULL;
8532 	*fdsp = NULL;
8533 	if (dspathp == NULL && curdspathp != NULL)
8534 		return (EPERM);
8535 
8536 	/*
8537 	 * Look up the MDS file shared locked.  The lock will be upgraded
8538 	 * to an exclusive lock after any rw layouts have been returned.
8539 	 */
8540 	NFSD_DEBUG(4, "mdsopen path=%s\n", mdspathp);
8541 	NDINIT(&nd, LOOKUP, FOLLOW | LOCKSHARED | LOCKLEAF, UIO_SYSSPACE,
8542 	    mdspathp, p);
8543 	error = namei(&nd);
8544 	NFSD_DEBUG(4, "lookup=%d\n", error);
8545 	if (error != 0)
8546 		return (error);
8547 	if (nd.ni_vp->v_type != VREG) {
8548 		vput(nd.ni_vp);
8549 		NFSD_DEBUG(4, "mdspath not reg\n");
8550 		return (EISDIR);
8551 	}
8552 	vp = nd.ni_vp;
8553 
8554 	if (curdspathp != NULL) {
8555 		/*
8556 		 * Look up the current DS path and find the nfsdev structure for
8557 		 * it.
8558 		 */
8559 		NFSD_DEBUG(4, "curmdsdev path=%s\n", curdspathp);
8560 		NDINIT(&nd, LOOKUP, FOLLOW | LOCKSHARED | LOCKLEAF,
8561 		    UIO_SYSSPACE, curdspathp, p);
8562 		error = namei(&nd);
8563 		NFSD_DEBUG(4, "ds lookup=%d\n", error);
8564 		if (error != 0) {
8565 			vput(vp);
8566 			return (error);
8567 		}
8568 		if (nd.ni_vp->v_type != VDIR) {
8569 			vput(nd.ni_vp);
8570 			vput(vp);
8571 			NFSD_DEBUG(4, "curdspath not dir\n");
8572 			return (ENOTDIR);
8573 		}
8574 		if (strcmp(nd.ni_vp->v_mount->mnt_vfc->vfc_name, "nfs") != 0) {
8575 			vput(nd.ni_vp);
8576 			vput(vp);
8577 			NFSD_DEBUG(4, "curdspath not an NFS mount\n");
8578 			return (ENXIO);
8579 		}
8580 		curnmp = VFSTONFS(nd.ni_vp->v_mount);
8581 
8582 		/* Search the nfsdev list for a match. */
8583 		NFSDDSLOCK();
8584 		*fdsp = nfsv4_findmirror(curnmp);
8585 		NFSDDSUNLOCK();
8586 		if (*fdsp == NULL)
8587 			curnmp = NULL;
8588 		if (curnmp == NULL) {
8589 			vput(nd.ni_vp);
8590 			vput(vp);
8591 			NFSD_DEBUG(4, "mdscopymr: no current ds\n");
8592 			return (ENXIO);
8593 		}
8594 		curvp = nd.ni_vp;
8595 	}
8596 
8597 	if (dspathp != NULL) {
8598 		/* Look up the nfsdev path and find the nfsdev structure. */
8599 		NFSD_DEBUG(4, "mdsdev path=%s\n", dspathp);
8600 		NDINIT(&nd, LOOKUP, FOLLOW | LOCKSHARED | LOCKLEAF,
8601 		    UIO_SYSSPACE, dspathp, p);
8602 		error = namei(&nd);
8603 		NFSD_DEBUG(4, "ds lookup=%d\n", error);
8604 		if (error != 0) {
8605 			vput(vp);
8606 			if (curvp != NULL)
8607 				vput(curvp);
8608 			return (error);
8609 		}
8610 		if (nd.ni_vp->v_type != VDIR || nd.ni_vp == curvp) {
8611 			vput(nd.ni_vp);
8612 			vput(vp);
8613 			if (curvp != NULL)
8614 				vput(curvp);
8615 			NFSD_DEBUG(4, "dspath not dir\n");
8616 			if (nd.ni_vp == curvp)
8617 				return (EPERM);
8618 			return (ENOTDIR);
8619 		}
8620 		if (strcmp(nd.ni_vp->v_mount->mnt_vfc->vfc_name, "nfs") != 0) {
8621 			vput(nd.ni_vp);
8622 			vput(vp);
8623 			if (curvp != NULL)
8624 				vput(curvp);
8625 			NFSD_DEBUG(4, "dspath not an NFS mount\n");
8626 			return (ENXIO);
8627 		}
8628 		nmp = VFSTONFS(nd.ni_vp->v_mount);
8629 
8630 		/*
8631 		 * Search the nfsdevice list for a match.  If curnmp == NULL,
8632 		 * this is a recovery and there must be a mirror.
8633 		 */
8634 		NFSDDSLOCK();
8635 		if (curnmp == NULL)
8636 			*dsp = nfsrv_findmirroredds(nmp);
8637 		else
8638 			*dsp = nfsv4_findmirror(nmp);
8639 		NFSDDSUNLOCK();
8640 		if (*dsp == NULL) {
8641 			vput(nd.ni_vp);
8642 			vput(vp);
8643 			if (curvp != NULL)
8644 				vput(curvp);
8645 			NFSD_DEBUG(4, "mdscopymr: no ds\n");
8646 			return (ENXIO);
8647 		}
8648 	} else {
8649 		nd.ni_vp = NULL;
8650 		nmp = NULL;
8651 	}
8652 
8653 	/*
8654 	 * Get a vp for an available DS data file using the extended
8655 	 * attribute on the MDS file.
8656 	 * If there is a valid entry for the new DS in the extended attribute
8657 	 * on the MDS file (as checked via the nmp argument),
8658 	 * nfsrv_dsgetsockmnt() returns EEXIST, so no copying will occur.
8659 	 */
8660 	error = nfsrv_dsgetsockmnt(vp, 0, buf, buflenp, &mirrorcnt, p,
8661 	    NULL, NULL, NULL, fname, nvpp, &nmp, curnmp, &ippos, &dsdir);
8662 	if (curvp != NULL)
8663 		vput(curvp);
8664 	if (nd.ni_vp == NULL) {
8665 		if (error == 0 && nmp != NULL) {
8666 			/* Search the nfsdev list for a match. */
8667 			NFSDDSLOCK();
8668 			*dsp = nfsrv_findmirroredds(nmp);
8669 			NFSDDSUNLOCK();
8670 		}
8671 		if (error == 0 && (nmp == NULL || *dsp == NULL)) {
8672 			if (nvpp != NULL && *nvpp != NULL) {
8673 				vput(*nvpp);
8674 				*nvpp = NULL;
8675 			}
8676 			error = ENXIO;
8677 		}
8678 	} else
8679 		vput(nd.ni_vp);
8680 
8681 	/*
8682 	 * When dspathp != NULL and curdspathp == NULL, this is a recovery
8683 	 * and is only allowed if there is a 0.0.0.0 IP address entry.
8684 	 * When curdspathp != NULL, the ippos will be set to that entry.
8685 	 */
8686 	if (error == 0 && dspathp != NULL && ippos == -1) {
8687 		if (nvpp != NULL && *nvpp != NULL) {
8688 			vput(*nvpp);
8689 			*nvpp = NULL;
8690 		}
8691 		error = ENXIO;
8692 	}
8693 	if (error == 0) {
8694 		*vpp = vp;
8695 
8696 		pf = (struct pnfsdsfile *)buf;
8697 		if (ippos == -1) {
8698 			/* If no zeroip pnfsdsfile, add one. */
8699 			ippos = *buflenp / sizeof(*pf);
8700 			*buflenp += sizeof(*pf);
8701 			pf += ippos;
8702 			pf->dsf_dir = dsdir;
8703 			strlcpy(pf->dsf_filename, fname,
8704 			    sizeof(pf->dsf_filename));
8705 		} else
8706 			pf += ippos;
8707 		*pfp = pf;
8708 	} else
8709 		vput(vp);
8710 	return (error);
8711 }
8712 
8713 /*
8714  * Search for a matching pnfsd mirror device structure, base on the nmp arg.
8715  * Return one if found, NULL otherwise.
8716  */
8717 static struct nfsdevice *
8718 nfsrv_findmirroredds(struct nfsmount *nmp)
8719 {
8720 	struct nfsdevice *ds, *fndds;
8721 	int fndmirror;
8722 
8723 	mtx_assert(NFSDDSMUTEXPTR, MA_OWNED);
8724 	/*
8725 	 * Search the DS server list for a match with nmp.
8726 	 * Remove the DS entry if found and there is a mirror.
8727 	 */
8728 	fndds = NULL;
8729 	fndmirror = 0;
8730 	if (nfsrv_devidcnt == 0)
8731 		return (fndds);
8732 	TAILQ_FOREACH(ds, &nfsrv_devidhead, nfsdev_list) {
8733 		if (ds->nfsdev_nmp == nmp) {
8734 			NFSD_DEBUG(4, "nfsrv_findmirroredds: fnd main ds\n");
8735 			fndds = ds;
8736 			break;
8737 		}
8738 	}
8739 	if (fndds == NULL)
8740 		return (fndds);
8741 	if (fndds->nfsdev_mdsisset == 0 && nfsrv_faildscnt > 0)
8742 		fndmirror = 1;
8743 	else if (fndds->nfsdev_mdsisset != 0) {
8744 		/* For the fsid is set case, search for a mirror. */
8745 		TAILQ_FOREACH(ds, &nfsrv_devidhead, nfsdev_list) {
8746 			if (ds != fndds && ds->nfsdev_nmp != NULL &&
8747 			    ds->nfsdev_mdsisset != 0 &&
8748 			    fsidcmp(&ds->nfsdev_mdsfsid,
8749 			    &fndds->nfsdev_mdsfsid) == 0) {
8750 				fndmirror = 1;
8751 				break;
8752 			}
8753 		}
8754 	}
8755 	if (fndmirror == 0) {
8756 		NFSD_DEBUG(4, "nfsrv_findmirroredds: no mirror for DS\n");
8757 		return (NULL);
8758 	}
8759 	return (fndds);
8760 }
8761