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