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