xref: /freebsd/sys/fs/nfsserver/nfs_nfsdstate.c (revision cddbc3b40812213ff00041f79174cac0be360a2a)
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 int nfsrv_delds(char *devid, NFSPROC_T *p);
219 static void nfsrv_deleteds(struct nfsdevice *fndds);
220 static void nfsrv_allocdevid(struct nfsdevice *ds, char *addr, char *dnshost);
221 static void nfsrv_freealldevids(void);
222 static void nfsrv_flexlayouterr(struct nfsrv_descript *nd, uint32_t *layp,
223     int maxcnt, NFSPROC_T *p);
224 static int nfsrv_recalllayout(nfsquad_t clid, nfsv4stateid_t *stateidp,
225     fhandle_t *fhp, struct nfslayout *lyp, int changed, int laytype,
226     NFSPROC_T *p);
227 static int nfsrv_findlayout(nfsquad_t *clientidp, fhandle_t *fhp, int laytype,
228     NFSPROC_T *, struct nfslayout **lypp);
229 static int nfsrv_fndclid(nfsquad_t *clidvec, nfsquad_t clid, int clidcnt);
230 static struct nfslayout *nfsrv_filelayout(struct nfsrv_descript *nd, int iomode,
231     fhandle_t *fhp, fhandle_t *dsfhp, char *devid, fsid_t fs);
232 static struct nfslayout *nfsrv_flexlayout(struct nfsrv_descript *nd, int iomode,
233     int mirrorcnt, fhandle_t *fhp, fhandle_t *dsfhp, char *devid, fsid_t fs);
234 static int nfsrv_dontlayout(fhandle_t *fhp);
235 static int nfsrv_createdsfile(vnode_t vp, fhandle_t *fhp, struct pnfsdsfile *pf,
236     vnode_t dvp, struct nfsdevice *ds, struct ucred *cred, NFSPROC_T *p,
237     vnode_t *tvpp);
238 static struct nfsdevice *nfsrv_findmirroredds(struct nfsmount *nmp);
239 
240 /*
241  * Scan the client list for a match and either return the current one,
242  * create a new entry or return an error.
243  * If returning a non-error, the clp structure must either be linked into
244  * the client list or free'd.
245  */
246 APPLESTATIC int
247 nfsrv_setclient(struct nfsrv_descript *nd, struct nfsclient **new_clpp,
248     nfsquad_t *clientidp, nfsquad_t *confirmp, NFSPROC_T *p)
249 {
250 	struct nfsclient *clp = NULL, *new_clp = *new_clpp;
251 	int i, error = 0, ret;
252 	struct nfsstate *stp, *tstp;
253 #ifdef INET
254 	struct sockaddr_in *sin, *rin;
255 #endif
256 #ifdef INET6
257 	struct sockaddr_in6 *sin6, *rin6;
258 #endif
259 	struct nfsdsession *sep, *nsep;
260 	int zapit = 0, gotit, hasstate = 0, igotlock;
261 	static u_int64_t confirm_index = 0;
262 
263 	/*
264 	 * Check for state resource limit exceeded.
265 	 */
266 	if (nfsrv_openpluslock > nfsrv_v4statelimit) {
267 		error = NFSERR_RESOURCE;
268 		goto out;
269 	}
270 
271 	if (nfsrv_issuedelegs == 0 ||
272 	    ((nd->nd_flag & ND_GSS) != 0 && nfsrv_nogsscallback != 0))
273 		/*
274 		 * Don't do callbacks when delegations are disabled or
275 		 * for AUTH_GSS unless enabled via nfsrv_nogsscallback.
276 		 * If establishing a callback connection is attempted
277 		 * when a firewall is blocking the callback path, the
278 		 * server may wait too long for the connect attempt to
279 		 * succeed during the Open. Some clients, such as Linux,
280 		 * may timeout and give up on the Open before the server
281 		 * replies. Also, since AUTH_GSS callbacks are not
282 		 * yet interoperability tested, they might cause the
283 		 * server to crap out, if they get past the Init call to
284 		 * the client.
285 		 */
286 		new_clp->lc_program = 0;
287 
288 	/* Lock out other nfsd threads */
289 	NFSLOCKV4ROOTMUTEX();
290 	nfsv4_relref(&nfsv4rootfs_lock);
291 	do {
292 		igotlock = nfsv4_lock(&nfsv4rootfs_lock, 1, NULL,
293 		    NFSV4ROOTLOCKMUTEXPTR, NULL);
294 	} while (!igotlock);
295 	NFSUNLOCKV4ROOTMUTEX();
296 
297 	/*
298 	 * Search for a match in the client list.
299 	 */
300 	gotit = i = 0;
301 	while (i < nfsrv_clienthashsize && !gotit) {
302 	    LIST_FOREACH(clp, &nfsclienthash[i], lc_hash) {
303 		if (new_clp->lc_idlen == clp->lc_idlen &&
304 		    !NFSBCMP(new_clp->lc_id, clp->lc_id, clp->lc_idlen)) {
305 			gotit = 1;
306 			break;
307 		}
308 	    }
309 	    if (gotit == 0)
310 		i++;
311 	}
312 	if (!gotit ||
313 	    (clp->lc_flags & (LCL_NEEDSCONFIRM | LCL_ADMINREVOKED))) {
314 		if ((nd->nd_flag & ND_NFSV41) != 0 && confirmp->lval[1] != 0) {
315 			/*
316 			 * For NFSv4.1, if confirmp->lval[1] is non-zero, the
317 			 * client is trying to update a confirmed clientid.
318 			 */
319 			NFSLOCKV4ROOTMUTEX();
320 			nfsv4_unlock(&nfsv4rootfs_lock, 1);
321 			NFSUNLOCKV4ROOTMUTEX();
322 			confirmp->lval[1] = 0;
323 			error = NFSERR_NOENT;
324 			goto out;
325 		}
326 		/*
327 		 * Get rid of the old one.
328 		 */
329 		if (i != nfsrv_clienthashsize) {
330 			LIST_REMOVE(clp, lc_hash);
331 			nfsrv_cleanclient(clp, p);
332 			nfsrv_freedeleglist(&clp->lc_deleg);
333 			nfsrv_freedeleglist(&clp->lc_olddeleg);
334 			zapit = 1;
335 		}
336 		/*
337 		 * Add it after assigning a client id to it.
338 		 */
339 		new_clp->lc_flags |= LCL_NEEDSCONFIRM;
340 		if ((nd->nd_flag & ND_NFSV41) != 0)
341 			new_clp->lc_confirm.lval[0] = confirmp->lval[0] =
342 			    ++confirm_index;
343 		else
344 			confirmp->qval = new_clp->lc_confirm.qval =
345 			    ++confirm_index;
346 		clientidp->lval[0] = new_clp->lc_clientid.lval[0] =
347 		    (u_int32_t)nfsrvboottime;
348 		clientidp->lval[1] = new_clp->lc_clientid.lval[1] =
349 		    nfsrv_nextclientindex();
350 		new_clp->lc_stateindex = 0;
351 		new_clp->lc_statemaxindex = 0;
352 		new_clp->lc_cbref = 0;
353 		new_clp->lc_expiry = nfsrv_leaseexpiry();
354 		LIST_INIT(&new_clp->lc_open);
355 		LIST_INIT(&new_clp->lc_deleg);
356 		LIST_INIT(&new_clp->lc_olddeleg);
357 		LIST_INIT(&new_clp->lc_session);
358 		for (i = 0; i < nfsrv_statehashsize; i++)
359 			LIST_INIT(&new_clp->lc_stateid[i]);
360 		LIST_INSERT_HEAD(NFSCLIENTHASH(new_clp->lc_clientid), new_clp,
361 		    lc_hash);
362 		nfsstatsv1.srvclients++;
363 		nfsrv_openpluslock++;
364 		nfsrv_clients++;
365 		NFSLOCKV4ROOTMUTEX();
366 		nfsv4_unlock(&nfsv4rootfs_lock, 1);
367 		NFSUNLOCKV4ROOTMUTEX();
368 		if (zapit)
369 			nfsrv_zapclient(clp, p);
370 		*new_clpp = NULL;
371 		goto out;
372 	}
373 
374 	/*
375 	 * Now, handle the cases where the id is already issued.
376 	 */
377 	if (nfsrv_notsamecredname(nd, clp)) {
378 	    /*
379 	     * Check to see if there is expired state that should go away.
380 	     */
381 	    if (clp->lc_expiry < NFSD_MONOSEC &&
382 	        (!LIST_EMPTY(&clp->lc_open) || !LIST_EMPTY(&clp->lc_deleg))) {
383 		nfsrv_cleanclient(clp, p);
384 		nfsrv_freedeleglist(&clp->lc_deleg);
385 	    }
386 
387 	    /*
388 	     * If there is outstanding state, then reply NFSERR_CLIDINUSE per
389 	     * RFC3530 Sec. 8.1.2 last para.
390 	     */
391 	    if (!LIST_EMPTY(&clp->lc_deleg)) {
392 		hasstate = 1;
393 	    } else if (LIST_EMPTY(&clp->lc_open)) {
394 		hasstate = 0;
395 	    } else {
396 		hasstate = 0;
397 		/* Look for an Open on the OpenOwner */
398 		LIST_FOREACH(stp, &clp->lc_open, ls_list) {
399 		    if (!LIST_EMPTY(&stp->ls_open)) {
400 			hasstate = 1;
401 			break;
402 		    }
403 		}
404 	    }
405 	    if (hasstate) {
406 		/*
407 		 * If the uid doesn't match, return NFSERR_CLIDINUSE after
408 		 * filling out the correct ipaddr and portnum.
409 		 */
410 		switch (clp->lc_req.nr_nam->sa_family) {
411 #ifdef INET
412 		case AF_INET:
413 			sin = (struct sockaddr_in *)new_clp->lc_req.nr_nam;
414 			rin = (struct sockaddr_in *)clp->lc_req.nr_nam;
415 			sin->sin_addr.s_addr = rin->sin_addr.s_addr;
416 			sin->sin_port = rin->sin_port;
417 			break;
418 #endif
419 #ifdef INET6
420 		case AF_INET6:
421 			sin6 = (struct sockaddr_in6 *)new_clp->lc_req.nr_nam;
422 			rin6 = (struct sockaddr_in6 *)clp->lc_req.nr_nam;
423 			sin6->sin6_addr = rin6->sin6_addr;
424 			sin6->sin6_port = rin6->sin6_port;
425 			break;
426 #endif
427 		}
428 		NFSLOCKV4ROOTMUTEX();
429 		nfsv4_unlock(&nfsv4rootfs_lock, 1);
430 		NFSUNLOCKV4ROOTMUTEX();
431 		error = NFSERR_CLIDINUSE;
432 		goto out;
433 	    }
434 	}
435 
436 	if (NFSBCMP(new_clp->lc_verf, clp->lc_verf, NFSX_VERF)) {
437 		/*
438 		 * If the verifier has changed, the client has rebooted
439 		 * and a new client id is issued. The old state info
440 		 * can be thrown away once the SETCLIENTID_CONFIRM occurs.
441 		 */
442 		LIST_REMOVE(clp, lc_hash);
443 
444 		/* Get rid of all sessions on this clientid. */
445 		LIST_FOREACH_SAFE(sep, &clp->lc_session, sess_list, nsep) {
446 			ret = nfsrv_freesession(sep, NULL);
447 			if (ret != 0)
448 				printf("nfsrv_setclient: verifier changed free"
449 				    " session failed=%d\n", ret);
450 		}
451 
452 		new_clp->lc_flags |= LCL_NEEDSCONFIRM;
453 		if ((nd->nd_flag & ND_NFSV41) != 0)
454 			new_clp->lc_confirm.lval[0] = confirmp->lval[0] =
455 			    ++confirm_index;
456 		else
457 			confirmp->qval = new_clp->lc_confirm.qval =
458 			    ++confirm_index;
459 		clientidp->lval[0] = new_clp->lc_clientid.lval[0] =
460 		    nfsrvboottime;
461 		clientidp->lval[1] = new_clp->lc_clientid.lval[1] =
462 		    nfsrv_nextclientindex();
463 		new_clp->lc_stateindex = 0;
464 		new_clp->lc_statemaxindex = 0;
465 		new_clp->lc_cbref = 0;
466 		new_clp->lc_expiry = nfsrv_leaseexpiry();
467 
468 		/*
469 		 * Save the state until confirmed.
470 		 */
471 		LIST_NEWHEAD(&new_clp->lc_open, &clp->lc_open, ls_list);
472 		LIST_FOREACH(tstp, &new_clp->lc_open, ls_list)
473 			tstp->ls_clp = new_clp;
474 		LIST_NEWHEAD(&new_clp->lc_deleg, &clp->lc_deleg, ls_list);
475 		LIST_FOREACH(tstp, &new_clp->lc_deleg, ls_list)
476 			tstp->ls_clp = new_clp;
477 		LIST_NEWHEAD(&new_clp->lc_olddeleg, &clp->lc_olddeleg,
478 		    ls_list);
479 		LIST_FOREACH(tstp, &new_clp->lc_olddeleg, ls_list)
480 			tstp->ls_clp = new_clp;
481 		for (i = 0; i < nfsrv_statehashsize; i++) {
482 			LIST_NEWHEAD(&new_clp->lc_stateid[i],
483 			    &clp->lc_stateid[i], ls_hash);
484 			LIST_FOREACH(tstp, &new_clp->lc_stateid[i], ls_hash)
485 				tstp->ls_clp = new_clp;
486 		}
487 		LIST_INIT(&new_clp->lc_session);
488 		LIST_INSERT_HEAD(NFSCLIENTHASH(new_clp->lc_clientid), new_clp,
489 		    lc_hash);
490 		nfsstatsv1.srvclients++;
491 		nfsrv_openpluslock++;
492 		nfsrv_clients++;
493 		NFSLOCKV4ROOTMUTEX();
494 		nfsv4_unlock(&nfsv4rootfs_lock, 1);
495 		NFSUNLOCKV4ROOTMUTEX();
496 
497 		/*
498 		 * Must wait until any outstanding callback on the old clp
499 		 * completes.
500 		 */
501 		NFSLOCKSTATE();
502 		while (clp->lc_cbref) {
503 			clp->lc_flags |= LCL_WAKEUPWANTED;
504 			(void)mtx_sleep(clp, NFSSTATEMUTEXPTR, PZERO - 1,
505 			    "nfsd clp", 10 * hz);
506 		}
507 		NFSUNLOCKSTATE();
508 		nfsrv_zapclient(clp, p);
509 		*new_clpp = NULL;
510 		goto out;
511 	}
512 
513 	/* For NFSv4.1, mark that we found a confirmed clientid. */
514 	if ((nd->nd_flag & ND_NFSV41) != 0) {
515 		clientidp->lval[0] = clp->lc_clientid.lval[0];
516 		clientidp->lval[1] = clp->lc_clientid.lval[1];
517 		confirmp->lval[0] = 0;	/* Ignored by client */
518 		confirmp->lval[1] = 1;
519 	} else {
520 		/*
521 		 * id and verifier match, so update the net address info
522 		 * and get rid of any existing callback authentication
523 		 * handle, so a new one will be acquired.
524 		 */
525 		LIST_REMOVE(clp, lc_hash);
526 		new_clp->lc_flags |= (LCL_NEEDSCONFIRM | LCL_DONTCLEAN);
527 		new_clp->lc_expiry = nfsrv_leaseexpiry();
528 		confirmp->qval = new_clp->lc_confirm.qval = ++confirm_index;
529 		clientidp->lval[0] = new_clp->lc_clientid.lval[0] =
530 		    clp->lc_clientid.lval[0];
531 		clientidp->lval[1] = new_clp->lc_clientid.lval[1] =
532 		    clp->lc_clientid.lval[1];
533 		new_clp->lc_delegtime = clp->lc_delegtime;
534 		new_clp->lc_stateindex = clp->lc_stateindex;
535 		new_clp->lc_statemaxindex = clp->lc_statemaxindex;
536 		new_clp->lc_cbref = 0;
537 		LIST_NEWHEAD(&new_clp->lc_open, &clp->lc_open, ls_list);
538 		LIST_FOREACH(tstp, &new_clp->lc_open, ls_list)
539 			tstp->ls_clp = new_clp;
540 		LIST_NEWHEAD(&new_clp->lc_deleg, &clp->lc_deleg, ls_list);
541 		LIST_FOREACH(tstp, &new_clp->lc_deleg, ls_list)
542 			tstp->ls_clp = new_clp;
543 		LIST_NEWHEAD(&new_clp->lc_olddeleg, &clp->lc_olddeleg, ls_list);
544 		LIST_FOREACH(tstp, &new_clp->lc_olddeleg, ls_list)
545 			tstp->ls_clp = new_clp;
546 		for (i = 0; i < nfsrv_statehashsize; i++) {
547 			LIST_NEWHEAD(&new_clp->lc_stateid[i],
548 			    &clp->lc_stateid[i], ls_hash);
549 			LIST_FOREACH(tstp, &new_clp->lc_stateid[i], ls_hash)
550 				tstp->ls_clp = new_clp;
551 		}
552 		LIST_INIT(&new_clp->lc_session);
553 		LIST_INSERT_HEAD(NFSCLIENTHASH(new_clp->lc_clientid), new_clp,
554 		    lc_hash);
555 		nfsstatsv1.srvclients++;
556 		nfsrv_openpluslock++;
557 		nfsrv_clients++;
558 	}
559 	NFSLOCKV4ROOTMUTEX();
560 	nfsv4_unlock(&nfsv4rootfs_lock, 1);
561 	NFSUNLOCKV4ROOTMUTEX();
562 
563 	if ((nd->nd_flag & ND_NFSV41) == 0) {
564 		/*
565 		 * Must wait until any outstanding callback on the old clp
566 		 * completes.
567 		 */
568 		NFSLOCKSTATE();
569 		while (clp->lc_cbref) {
570 			clp->lc_flags |= LCL_WAKEUPWANTED;
571 			(void)mtx_sleep(clp, NFSSTATEMUTEXPTR, PZERO - 1,
572 			    "nfsdclp", 10 * hz);
573 		}
574 		NFSUNLOCKSTATE();
575 		nfsrv_zapclient(clp, p);
576 		*new_clpp = NULL;
577 	}
578 
579 out:
580 	NFSEXITCODE2(error, nd);
581 	return (error);
582 }
583 
584 /*
585  * Check to see if the client id exists and optionally confirm it.
586  */
587 APPLESTATIC int
588 nfsrv_getclient(nfsquad_t clientid, int opflags, struct nfsclient **clpp,
589     struct nfsdsession *nsep, nfsquad_t confirm, uint32_t cbprogram,
590     struct nfsrv_descript *nd, NFSPROC_T *p)
591 {
592 	struct nfsclient *clp;
593 	struct nfsstate *stp;
594 	int i;
595 	struct nfsclienthashhead *hp;
596 	int error = 0, igotlock, doneok;
597 	struct nfssessionhash *shp;
598 	struct nfsdsession *sep;
599 	uint64_t sessid[2];
600 	static uint64_t next_sess = 0;
601 
602 	if (clpp)
603 		*clpp = NULL;
604 	if ((nd == NULL || (nd->nd_flag & ND_NFSV41) == 0 ||
605 	    opflags != CLOPS_RENEW) && nfsrvboottime != clientid.lval[0]) {
606 		error = NFSERR_STALECLIENTID;
607 		goto out;
608 	}
609 
610 	/*
611 	 * If called with opflags == CLOPS_RENEW, the State Lock is
612 	 * already held. Otherwise, we need to get either that or,
613 	 * for the case of Confirm, lock out the nfsd threads.
614 	 */
615 	if (opflags & CLOPS_CONFIRM) {
616 		NFSLOCKV4ROOTMUTEX();
617 		nfsv4_relref(&nfsv4rootfs_lock);
618 		do {
619 			igotlock = nfsv4_lock(&nfsv4rootfs_lock, 1, NULL,
620 			    NFSV4ROOTLOCKMUTEXPTR, NULL);
621 		} while (!igotlock);
622 		/*
623 		 * Create a new sessionid here, since we need to do it where
624 		 * there is a mutex held to serialize update of next_sess.
625 		 */
626 		if ((nd->nd_flag & ND_NFSV41) != 0) {
627 			sessid[0] = ++next_sess;
628 			sessid[1] = clientid.qval;
629 		}
630 		NFSUNLOCKV4ROOTMUTEX();
631 	} else if (opflags != CLOPS_RENEW) {
632 		NFSLOCKSTATE();
633 	}
634 
635 	/* For NFSv4.1, the clp is acquired from the associated session. */
636 	if (nd != NULL && (nd->nd_flag & ND_NFSV41) != 0 &&
637 	    opflags == CLOPS_RENEW) {
638 		clp = NULL;
639 		if ((nd->nd_flag & ND_HASSEQUENCE) != 0) {
640 			shp = NFSSESSIONHASH(nd->nd_sessionid);
641 			NFSLOCKSESSION(shp);
642 			sep = nfsrv_findsession(nd->nd_sessionid);
643 			if (sep != NULL)
644 				clp = sep->sess_clp;
645 			NFSUNLOCKSESSION(shp);
646 		}
647 	} else {
648 		hp = NFSCLIENTHASH(clientid);
649 		LIST_FOREACH(clp, hp, lc_hash) {
650 			if (clp->lc_clientid.lval[1] == clientid.lval[1])
651 				break;
652 		}
653 	}
654 	if (clp == NULL) {
655 		if (opflags & CLOPS_CONFIRM)
656 			error = NFSERR_STALECLIENTID;
657 		else
658 			error = NFSERR_EXPIRED;
659 	} else if (clp->lc_flags & LCL_ADMINREVOKED) {
660 		/*
661 		 * If marked admin revoked, just return the error.
662 		 */
663 		error = NFSERR_ADMINREVOKED;
664 	}
665 	if (error) {
666 		if (opflags & CLOPS_CONFIRM) {
667 			NFSLOCKV4ROOTMUTEX();
668 			nfsv4_unlock(&nfsv4rootfs_lock, 1);
669 			NFSUNLOCKV4ROOTMUTEX();
670 		} else if (opflags != CLOPS_RENEW) {
671 			NFSUNLOCKSTATE();
672 		}
673 		goto out;
674 	}
675 
676 	/*
677 	 * Perform any operations specified by the opflags.
678 	 */
679 	if (opflags & CLOPS_CONFIRM) {
680 		if (((nd->nd_flag & ND_NFSV41) != 0 &&
681 		     clp->lc_confirm.lval[0] != confirm.lval[0]) ||
682 		    ((nd->nd_flag & ND_NFSV41) == 0 &&
683 		     clp->lc_confirm.qval != confirm.qval))
684 			error = NFSERR_STALECLIENTID;
685 		else if (nfsrv_notsamecredname(nd, clp))
686 			error = NFSERR_CLIDINUSE;
687 
688 		if (!error) {
689 		    if ((clp->lc_flags & (LCL_NEEDSCONFIRM | LCL_DONTCLEAN)) ==
690 			LCL_NEEDSCONFIRM) {
691 			/*
692 			 * Hang onto the delegations (as old delegations)
693 			 * for an Open with CLAIM_DELEGATE_PREV unless in
694 			 * grace, but get rid of the rest of the state.
695 			 */
696 			nfsrv_cleanclient(clp, p);
697 			nfsrv_freedeleglist(&clp->lc_olddeleg);
698 			if (nfsrv_checkgrace(nd, clp, 0)) {
699 			    /* In grace, so just delete delegations */
700 			    nfsrv_freedeleglist(&clp->lc_deleg);
701 			} else {
702 			    LIST_FOREACH(stp, &clp->lc_deleg, ls_list)
703 				stp->ls_flags |= NFSLCK_OLDDELEG;
704 			    clp->lc_delegtime = NFSD_MONOSEC +
705 				nfsrv_lease + NFSRV_LEASEDELTA;
706 			    LIST_NEWHEAD(&clp->lc_olddeleg, &clp->lc_deleg,
707 				ls_list);
708 			}
709 			if ((nd->nd_flag & ND_NFSV41) != 0)
710 			    clp->lc_program = cbprogram;
711 		    }
712 		    clp->lc_flags &= ~(LCL_NEEDSCONFIRM | LCL_DONTCLEAN);
713 		    if (clp->lc_program)
714 			clp->lc_flags |= LCL_NEEDSCBNULL;
715 		    /* For NFSv4.1, link the session onto the client. */
716 		    if (nsep != NULL) {
717 			/* Hold a reference on the xprt for a backchannel. */
718 			if ((nsep->sess_crflags & NFSV4CRSESS_CONNBACKCHAN)
719 			    != 0) {
720 			    if (clp->lc_req.nr_client == NULL)
721 				clp->lc_req.nr_client = (struct __rpc_client *)
722 				    clnt_bck_create(nd->nd_xprt->xp_socket,
723 				    cbprogram, NFSV4_CBVERS);
724 			    if (clp->lc_req.nr_client != NULL) {
725 				SVC_ACQUIRE(nd->nd_xprt);
726 				nd->nd_xprt->xp_p2 =
727 				    clp->lc_req.nr_client->cl_private;
728 				/* Disable idle timeout. */
729 				nd->nd_xprt->xp_idletimeout = 0;
730 				nsep->sess_cbsess.nfsess_xprt = nd->nd_xprt;
731 			    } else
732 				nsep->sess_crflags &= ~NFSV4CRSESS_CONNBACKCHAN;
733 			}
734 			NFSBCOPY(sessid, nsep->sess_sessionid,
735 			    NFSX_V4SESSIONID);
736 			NFSBCOPY(sessid, nsep->sess_cbsess.nfsess_sessionid,
737 			    NFSX_V4SESSIONID);
738 			shp = NFSSESSIONHASH(nsep->sess_sessionid);
739 			NFSLOCKSTATE();
740 			NFSLOCKSESSION(shp);
741 			LIST_INSERT_HEAD(&shp->list, nsep, sess_hash);
742 			LIST_INSERT_HEAD(&clp->lc_session, nsep, sess_list);
743 			nsep->sess_clp = clp;
744 			NFSUNLOCKSESSION(shp);
745 			NFSUNLOCKSTATE();
746 		    }
747 		}
748 	} else if (clp->lc_flags & LCL_NEEDSCONFIRM) {
749 		error = NFSERR_EXPIRED;
750 	}
751 
752 	/*
753 	 * If called by the Renew Op, we must check the principal.
754 	 */
755 	if (!error && (opflags & CLOPS_RENEWOP)) {
756 	    if (nfsrv_notsamecredname(nd, clp)) {
757 		doneok = 0;
758 		for (i = 0; i < nfsrv_statehashsize && doneok == 0; i++) {
759 		    LIST_FOREACH(stp, &clp->lc_stateid[i], ls_hash) {
760 			if ((stp->ls_flags & NFSLCK_OPEN) &&
761 			    stp->ls_uid == nd->nd_cred->cr_uid) {
762 				doneok = 1;
763 				break;
764 			}
765 		    }
766 		}
767 		if (!doneok)
768 			error = NFSERR_ACCES;
769 	    }
770 	    if (!error && (clp->lc_flags & LCL_CBDOWN))
771 		error = NFSERR_CBPATHDOWN;
772 	}
773 	if ((!error || error == NFSERR_CBPATHDOWN) &&
774 	     (opflags & CLOPS_RENEW)) {
775 		clp->lc_expiry = nfsrv_leaseexpiry();
776 	}
777 	if (opflags & CLOPS_CONFIRM) {
778 		NFSLOCKV4ROOTMUTEX();
779 		nfsv4_unlock(&nfsv4rootfs_lock, 1);
780 		NFSUNLOCKV4ROOTMUTEX();
781 	} else if (opflags != CLOPS_RENEW) {
782 		NFSUNLOCKSTATE();
783 	}
784 	if (clpp)
785 		*clpp = clp;
786 
787 out:
788 	NFSEXITCODE2(error, nd);
789 	return (error);
790 }
791 
792 /*
793  * Perform the NFSv4.1 destroy clientid.
794  */
795 int
796 nfsrv_destroyclient(nfsquad_t clientid, NFSPROC_T *p)
797 {
798 	struct nfsclient *clp;
799 	struct nfsclienthashhead *hp;
800 	int error = 0, i, igotlock;
801 
802 	if (nfsrvboottime != clientid.lval[0]) {
803 		error = NFSERR_STALECLIENTID;
804 		goto out;
805 	}
806 
807 	/* Lock out other nfsd threads */
808 	NFSLOCKV4ROOTMUTEX();
809 	nfsv4_relref(&nfsv4rootfs_lock);
810 	do {
811 		igotlock = nfsv4_lock(&nfsv4rootfs_lock, 1, NULL,
812 		    NFSV4ROOTLOCKMUTEXPTR, NULL);
813 	} while (igotlock == 0);
814 	NFSUNLOCKV4ROOTMUTEX();
815 
816 	hp = NFSCLIENTHASH(clientid);
817 	LIST_FOREACH(clp, hp, lc_hash) {
818 		if (clp->lc_clientid.lval[1] == clientid.lval[1])
819 			break;
820 	}
821 	if (clp == NULL) {
822 		NFSLOCKV4ROOTMUTEX();
823 		nfsv4_unlock(&nfsv4rootfs_lock, 1);
824 		NFSUNLOCKV4ROOTMUTEX();
825 		/* Just return ok, since it is gone. */
826 		goto out;
827 	}
828 
829 	/*
830 	 * Free up all layouts on the clientid.  Should the client return the
831 	 * layouts?
832 	 */
833 	nfsrv_freelayoutlist(clientid);
834 
835 	/* Scan for state on the clientid. */
836 	for (i = 0; i < nfsrv_statehashsize; i++)
837 		if (!LIST_EMPTY(&clp->lc_stateid[i])) {
838 			NFSLOCKV4ROOTMUTEX();
839 			nfsv4_unlock(&nfsv4rootfs_lock, 1);
840 			NFSUNLOCKV4ROOTMUTEX();
841 			error = NFSERR_CLIENTIDBUSY;
842 			goto out;
843 		}
844 	if (!LIST_EMPTY(&clp->lc_session) || !LIST_EMPTY(&clp->lc_deleg)) {
845 		NFSLOCKV4ROOTMUTEX();
846 		nfsv4_unlock(&nfsv4rootfs_lock, 1);
847 		NFSUNLOCKV4ROOTMUTEX();
848 		error = NFSERR_CLIENTIDBUSY;
849 		goto out;
850 	}
851 
852 	/* Destroy the clientid and return ok. */
853 	nfsrv_cleanclient(clp, p);
854 	nfsrv_freedeleglist(&clp->lc_deleg);
855 	nfsrv_freedeleglist(&clp->lc_olddeleg);
856 	LIST_REMOVE(clp, lc_hash);
857 	NFSLOCKV4ROOTMUTEX();
858 	nfsv4_unlock(&nfsv4rootfs_lock, 1);
859 	NFSUNLOCKV4ROOTMUTEX();
860 	nfsrv_zapclient(clp, p);
861 out:
862 	NFSEXITCODE2(error, nd);
863 	return (error);
864 }
865 
866 /*
867  * Called from the new nfssvc syscall to admin revoke a clientid.
868  * Returns 0 for success, error otherwise.
869  */
870 APPLESTATIC int
871 nfsrv_adminrevoke(struct nfsd_clid *revokep, NFSPROC_T *p)
872 {
873 	struct nfsclient *clp = NULL;
874 	int i, error = 0;
875 	int gotit, igotlock;
876 
877 	/*
878 	 * First, lock out the nfsd so that state won't change while the
879 	 * revocation record is being written to the stable storage restart
880 	 * file.
881 	 */
882 	NFSLOCKV4ROOTMUTEX();
883 	do {
884 		igotlock = nfsv4_lock(&nfsv4rootfs_lock, 1, NULL,
885 		    NFSV4ROOTLOCKMUTEXPTR, NULL);
886 	} while (!igotlock);
887 	NFSUNLOCKV4ROOTMUTEX();
888 
889 	/*
890 	 * Search for a match in the client list.
891 	 */
892 	gotit = i = 0;
893 	while (i < nfsrv_clienthashsize && !gotit) {
894 	    LIST_FOREACH(clp, &nfsclienthash[i], lc_hash) {
895 		if (revokep->nclid_idlen == clp->lc_idlen &&
896 		    !NFSBCMP(revokep->nclid_id, clp->lc_id, clp->lc_idlen)) {
897 			gotit = 1;
898 			break;
899 		}
900 	    }
901 	    i++;
902 	}
903 	if (!gotit) {
904 		NFSLOCKV4ROOTMUTEX();
905 		nfsv4_unlock(&nfsv4rootfs_lock, 0);
906 		NFSUNLOCKV4ROOTMUTEX();
907 		error = EPERM;
908 		goto out;
909 	}
910 
911 	/*
912 	 * Now, write out the revocation record
913 	 */
914 	nfsrv_writestable(clp->lc_id, clp->lc_idlen, NFSNST_REVOKE, p);
915 	nfsrv_backupstable();
916 
917 	/*
918 	 * and clear out the state, marking the clientid revoked.
919 	 */
920 	clp->lc_flags &= ~LCL_CALLBACKSON;
921 	clp->lc_flags |= LCL_ADMINREVOKED;
922 	nfsrv_cleanclient(clp, p);
923 	nfsrv_freedeleglist(&clp->lc_deleg);
924 	nfsrv_freedeleglist(&clp->lc_olddeleg);
925 	NFSLOCKV4ROOTMUTEX();
926 	nfsv4_unlock(&nfsv4rootfs_lock, 0);
927 	NFSUNLOCKV4ROOTMUTEX();
928 
929 out:
930 	NFSEXITCODE(error);
931 	return (error);
932 }
933 
934 /*
935  * Dump out stats for all clients. Called from nfssvc(2), that is used
936  * nfsstatsv1.
937  */
938 APPLESTATIC void
939 nfsrv_dumpclients(struct nfsd_dumpclients *dumpp, int maxcnt)
940 {
941 	struct nfsclient *clp;
942 	int i = 0, cnt = 0;
943 
944 	/*
945 	 * First, get a reference on the nfsv4rootfs_lock so that an
946 	 * exclusive lock cannot be acquired while dumping the clients.
947 	 */
948 	NFSLOCKV4ROOTMUTEX();
949 	nfsv4_getref(&nfsv4rootfs_lock, NULL, NFSV4ROOTLOCKMUTEXPTR, NULL);
950 	NFSUNLOCKV4ROOTMUTEX();
951 	NFSLOCKSTATE();
952 	/*
953 	 * Rattle through the client lists until done.
954 	 */
955 	while (i < nfsrv_clienthashsize && cnt < maxcnt) {
956 	    clp = LIST_FIRST(&nfsclienthash[i]);
957 	    while (clp != LIST_END(&nfsclienthash[i]) && cnt < maxcnt) {
958 		nfsrv_dumpaclient(clp, &dumpp[cnt]);
959 		cnt++;
960 		clp = LIST_NEXT(clp, lc_hash);
961 	    }
962 	    i++;
963 	}
964 	if (cnt < maxcnt)
965 	    dumpp[cnt].ndcl_clid.nclid_idlen = 0;
966 	NFSUNLOCKSTATE();
967 	NFSLOCKV4ROOTMUTEX();
968 	nfsv4_relref(&nfsv4rootfs_lock);
969 	NFSUNLOCKV4ROOTMUTEX();
970 }
971 
972 /*
973  * Dump stats for a client. Must be called with the NFSSTATELOCK and spl'd.
974  */
975 static void
976 nfsrv_dumpaclient(struct nfsclient *clp, struct nfsd_dumpclients *dumpp)
977 {
978 	struct nfsstate *stp, *openstp, *lckownstp;
979 	struct nfslock *lop;
980 	sa_family_t af;
981 #ifdef INET
982 	struct sockaddr_in *rin;
983 #endif
984 #ifdef INET6
985 	struct sockaddr_in6 *rin6;
986 #endif
987 
988 	dumpp->ndcl_nopenowners = dumpp->ndcl_nlockowners = 0;
989 	dumpp->ndcl_nopens = dumpp->ndcl_nlocks = 0;
990 	dumpp->ndcl_ndelegs = dumpp->ndcl_nolddelegs = 0;
991 	dumpp->ndcl_flags = clp->lc_flags;
992 	dumpp->ndcl_clid.nclid_idlen = clp->lc_idlen;
993 	NFSBCOPY(clp->lc_id, dumpp->ndcl_clid.nclid_id, clp->lc_idlen);
994 	af = clp->lc_req.nr_nam->sa_family;
995 	dumpp->ndcl_addrfam = af;
996 	switch (af) {
997 #ifdef INET
998 	case AF_INET:
999 		rin = (struct sockaddr_in *)clp->lc_req.nr_nam;
1000 		dumpp->ndcl_cbaddr.sin_addr = rin->sin_addr;
1001 		break;
1002 #endif
1003 #ifdef INET6
1004 	case AF_INET6:
1005 		rin6 = (struct sockaddr_in6 *)clp->lc_req.nr_nam;
1006 		dumpp->ndcl_cbaddr.sin6_addr = rin6->sin6_addr;
1007 		break;
1008 #endif
1009 	}
1010 
1011 	/*
1012 	 * Now, scan the state lists and total up the opens and locks.
1013 	 */
1014 	LIST_FOREACH(stp, &clp->lc_open, ls_list) {
1015 	    dumpp->ndcl_nopenowners++;
1016 	    LIST_FOREACH(openstp, &stp->ls_open, ls_list) {
1017 		dumpp->ndcl_nopens++;
1018 		LIST_FOREACH(lckownstp, &openstp->ls_open, ls_list) {
1019 		    dumpp->ndcl_nlockowners++;
1020 		    LIST_FOREACH(lop, &lckownstp->ls_lock, lo_lckowner) {
1021 			dumpp->ndcl_nlocks++;
1022 		    }
1023 		}
1024 	    }
1025 	}
1026 
1027 	/*
1028 	 * and the delegation lists.
1029 	 */
1030 	LIST_FOREACH(stp, &clp->lc_deleg, ls_list) {
1031 	    dumpp->ndcl_ndelegs++;
1032 	}
1033 	LIST_FOREACH(stp, &clp->lc_olddeleg, ls_list) {
1034 	    dumpp->ndcl_nolddelegs++;
1035 	}
1036 }
1037 
1038 /*
1039  * Dump out lock stats for a file.
1040  */
1041 APPLESTATIC void
1042 nfsrv_dumplocks(vnode_t vp, struct nfsd_dumplocks *ldumpp, int maxcnt,
1043     NFSPROC_T *p)
1044 {
1045 	struct nfsstate *stp;
1046 	struct nfslock *lop;
1047 	int cnt = 0;
1048 	struct nfslockfile *lfp;
1049 	sa_family_t af;
1050 #ifdef INET
1051 	struct sockaddr_in *rin;
1052 #endif
1053 #ifdef INET6
1054 	struct sockaddr_in6 *rin6;
1055 #endif
1056 	int ret;
1057 	fhandle_t nfh;
1058 
1059 	ret = nfsrv_getlockfh(vp, 0, NULL, &nfh, p);
1060 	/*
1061 	 * First, get a reference on the nfsv4rootfs_lock so that an
1062 	 * exclusive lock on it cannot be acquired while dumping the locks.
1063 	 */
1064 	NFSLOCKV4ROOTMUTEX();
1065 	nfsv4_getref(&nfsv4rootfs_lock, NULL, NFSV4ROOTLOCKMUTEXPTR, NULL);
1066 	NFSUNLOCKV4ROOTMUTEX();
1067 	NFSLOCKSTATE();
1068 	if (!ret)
1069 		ret = nfsrv_getlockfile(0, NULL, &lfp, &nfh, 0);
1070 	if (ret) {
1071 		ldumpp[0].ndlck_clid.nclid_idlen = 0;
1072 		NFSUNLOCKSTATE();
1073 		NFSLOCKV4ROOTMUTEX();
1074 		nfsv4_relref(&nfsv4rootfs_lock);
1075 		NFSUNLOCKV4ROOTMUTEX();
1076 		return;
1077 	}
1078 
1079 	/*
1080 	 * For each open share on file, dump it out.
1081 	 */
1082 	stp = LIST_FIRST(&lfp->lf_open);
1083 	while (stp != LIST_END(&lfp->lf_open) && cnt < maxcnt) {
1084 		ldumpp[cnt].ndlck_flags = stp->ls_flags;
1085 		ldumpp[cnt].ndlck_stateid.seqid = stp->ls_stateid.seqid;
1086 		ldumpp[cnt].ndlck_stateid.other[0] = stp->ls_stateid.other[0];
1087 		ldumpp[cnt].ndlck_stateid.other[1] = stp->ls_stateid.other[1];
1088 		ldumpp[cnt].ndlck_stateid.other[2] = stp->ls_stateid.other[2];
1089 		ldumpp[cnt].ndlck_owner.nclid_idlen =
1090 		    stp->ls_openowner->ls_ownerlen;
1091 		NFSBCOPY(stp->ls_openowner->ls_owner,
1092 		    ldumpp[cnt].ndlck_owner.nclid_id,
1093 		    stp->ls_openowner->ls_ownerlen);
1094 		ldumpp[cnt].ndlck_clid.nclid_idlen = stp->ls_clp->lc_idlen;
1095 		NFSBCOPY(stp->ls_clp->lc_id, ldumpp[cnt].ndlck_clid.nclid_id,
1096 		    stp->ls_clp->lc_idlen);
1097 		af = stp->ls_clp->lc_req.nr_nam->sa_family;
1098 		ldumpp[cnt].ndlck_addrfam = af;
1099 		switch (af) {
1100 #ifdef INET
1101 		case AF_INET:
1102 			rin = (struct sockaddr_in *)stp->ls_clp->lc_req.nr_nam;
1103 			ldumpp[cnt].ndlck_cbaddr.sin_addr = rin->sin_addr;
1104 			break;
1105 #endif
1106 #ifdef INET6
1107 		case AF_INET6:
1108 			rin6 = (struct sockaddr_in6 *)
1109 			    stp->ls_clp->lc_req.nr_nam;
1110 			ldumpp[cnt].ndlck_cbaddr.sin6_addr = rin6->sin6_addr;
1111 			break;
1112 #endif
1113 		}
1114 		stp = LIST_NEXT(stp, ls_file);
1115 		cnt++;
1116 	}
1117 
1118 	/*
1119 	 * and all locks.
1120 	 */
1121 	lop = LIST_FIRST(&lfp->lf_lock);
1122 	while (lop != LIST_END(&lfp->lf_lock) && cnt < maxcnt) {
1123 		stp = lop->lo_stp;
1124 		ldumpp[cnt].ndlck_flags = lop->lo_flags;
1125 		ldumpp[cnt].ndlck_first = lop->lo_first;
1126 		ldumpp[cnt].ndlck_end = lop->lo_end;
1127 		ldumpp[cnt].ndlck_stateid.seqid = stp->ls_stateid.seqid;
1128 		ldumpp[cnt].ndlck_stateid.other[0] = stp->ls_stateid.other[0];
1129 		ldumpp[cnt].ndlck_stateid.other[1] = stp->ls_stateid.other[1];
1130 		ldumpp[cnt].ndlck_stateid.other[2] = stp->ls_stateid.other[2];
1131 		ldumpp[cnt].ndlck_owner.nclid_idlen = stp->ls_ownerlen;
1132 		NFSBCOPY(stp->ls_owner, ldumpp[cnt].ndlck_owner.nclid_id,
1133 		    stp->ls_ownerlen);
1134 		ldumpp[cnt].ndlck_clid.nclid_idlen = stp->ls_clp->lc_idlen;
1135 		NFSBCOPY(stp->ls_clp->lc_id, ldumpp[cnt].ndlck_clid.nclid_id,
1136 		    stp->ls_clp->lc_idlen);
1137 		af = stp->ls_clp->lc_req.nr_nam->sa_family;
1138 		ldumpp[cnt].ndlck_addrfam = af;
1139 		switch (af) {
1140 #ifdef INET
1141 		case AF_INET:
1142 			rin = (struct sockaddr_in *)stp->ls_clp->lc_req.nr_nam;
1143 			ldumpp[cnt].ndlck_cbaddr.sin_addr = rin->sin_addr;
1144 			break;
1145 #endif
1146 #ifdef INET6
1147 		case AF_INET6:
1148 			rin6 = (struct sockaddr_in6 *)
1149 			    stp->ls_clp->lc_req.nr_nam;
1150 			ldumpp[cnt].ndlck_cbaddr.sin6_addr = rin6->sin6_addr;
1151 			break;
1152 #endif
1153 		}
1154 		lop = LIST_NEXT(lop, lo_lckfile);
1155 		cnt++;
1156 	}
1157 
1158 	/*
1159 	 * and the delegations.
1160 	 */
1161 	stp = LIST_FIRST(&lfp->lf_deleg);
1162 	while (stp != LIST_END(&lfp->lf_deleg) && cnt < maxcnt) {
1163 		ldumpp[cnt].ndlck_flags = stp->ls_flags;
1164 		ldumpp[cnt].ndlck_stateid.seqid = stp->ls_stateid.seqid;
1165 		ldumpp[cnt].ndlck_stateid.other[0] = stp->ls_stateid.other[0];
1166 		ldumpp[cnt].ndlck_stateid.other[1] = stp->ls_stateid.other[1];
1167 		ldumpp[cnt].ndlck_stateid.other[2] = stp->ls_stateid.other[2];
1168 		ldumpp[cnt].ndlck_owner.nclid_idlen = 0;
1169 		ldumpp[cnt].ndlck_clid.nclid_idlen = stp->ls_clp->lc_idlen;
1170 		NFSBCOPY(stp->ls_clp->lc_id, ldumpp[cnt].ndlck_clid.nclid_id,
1171 		    stp->ls_clp->lc_idlen);
1172 		af = stp->ls_clp->lc_req.nr_nam->sa_family;
1173 		ldumpp[cnt].ndlck_addrfam = af;
1174 		switch (af) {
1175 #ifdef INET
1176 		case AF_INET:
1177 			rin = (struct sockaddr_in *)stp->ls_clp->lc_req.nr_nam;
1178 			ldumpp[cnt].ndlck_cbaddr.sin_addr = rin->sin_addr;
1179 			break;
1180 #endif
1181 #ifdef INET6
1182 		case AF_INET6:
1183 			rin6 = (struct sockaddr_in6 *)
1184 			    stp->ls_clp->lc_req.nr_nam;
1185 			ldumpp[cnt].ndlck_cbaddr.sin6_addr = rin6->sin6_addr;
1186 			break;
1187 #endif
1188 		}
1189 		stp = LIST_NEXT(stp, ls_file);
1190 		cnt++;
1191 	}
1192 
1193 	/*
1194 	 * If list isn't full, mark end of list by setting the client name
1195 	 * to zero length.
1196 	 */
1197 	if (cnt < maxcnt)
1198 		ldumpp[cnt].ndlck_clid.nclid_idlen = 0;
1199 	NFSUNLOCKSTATE();
1200 	NFSLOCKV4ROOTMUTEX();
1201 	nfsv4_relref(&nfsv4rootfs_lock);
1202 	NFSUNLOCKV4ROOTMUTEX();
1203 }
1204 
1205 /*
1206  * Server timer routine. It can scan any linked list, so long
1207  * as it holds the spin/mutex lock and there is no exclusive lock on
1208  * nfsv4rootfs_lock.
1209  * (For OpenBSD, a kthread is ok. For FreeBSD, I think it is ok
1210  *  to do this from a callout, since the spin locks work. For
1211  *  Darwin, I'm not sure what will work correctly yet.)
1212  * Should be called once per second.
1213  */
1214 APPLESTATIC void
1215 nfsrv_servertimer(void)
1216 {
1217 	struct nfsclient *clp, *nclp;
1218 	struct nfsstate *stp, *nstp;
1219 	int got_ref, i;
1220 
1221 	/*
1222 	 * Make sure nfsboottime is set. This is used by V3 as well
1223 	 * as V4. Note that nfsboottime is not nfsrvboottime, which is
1224 	 * only used by the V4 server for leases.
1225 	 */
1226 	if (nfsboottime.tv_sec == 0)
1227 		NFSSETBOOTTIME(nfsboottime);
1228 
1229 	/*
1230 	 * If server hasn't started yet, just return.
1231 	 */
1232 	NFSLOCKSTATE();
1233 	if (nfsrv_stablefirst.nsf_eograce == 0) {
1234 		NFSUNLOCKSTATE();
1235 		return;
1236 	}
1237 	if (!(nfsrv_stablefirst.nsf_flags & NFSNSF_UPDATEDONE)) {
1238 		if (!(nfsrv_stablefirst.nsf_flags & NFSNSF_GRACEOVER) &&
1239 		    NFSD_MONOSEC > nfsrv_stablefirst.nsf_eograce)
1240 			nfsrv_stablefirst.nsf_flags |=
1241 			    (NFSNSF_GRACEOVER | NFSNSF_NEEDLOCK);
1242 		NFSUNLOCKSTATE();
1243 		return;
1244 	}
1245 
1246 	/*
1247 	 * Try and get a reference count on the nfsv4rootfs_lock so that
1248 	 * no nfsd thread can acquire an exclusive lock on it before this
1249 	 * call is done. If it is already exclusively locked, just return.
1250 	 */
1251 	NFSLOCKV4ROOTMUTEX();
1252 	got_ref = nfsv4_getref_nonblock(&nfsv4rootfs_lock);
1253 	NFSUNLOCKV4ROOTMUTEX();
1254 	if (got_ref == 0) {
1255 		NFSUNLOCKSTATE();
1256 		return;
1257 	}
1258 
1259 	/*
1260 	 * For each client...
1261 	 */
1262 	for (i = 0; i < nfsrv_clienthashsize; i++) {
1263 	    clp = LIST_FIRST(&nfsclienthash[i]);
1264 	    while (clp != LIST_END(&nfsclienthash[i])) {
1265 		nclp = LIST_NEXT(clp, lc_hash);
1266 		if (!(clp->lc_flags & LCL_EXPIREIT)) {
1267 		    if (((clp->lc_expiry + NFSRV_STALELEASE) < NFSD_MONOSEC
1268 			 && ((LIST_EMPTY(&clp->lc_deleg)
1269 			      && LIST_EMPTY(&clp->lc_open)) ||
1270 			     nfsrv_clients > nfsrv_clienthighwater)) ||
1271 			(clp->lc_expiry + NFSRV_MOULDYLEASE) < NFSD_MONOSEC ||
1272 			(clp->lc_expiry < NFSD_MONOSEC &&
1273 			 (nfsrv_openpluslock * 10 / 9) > nfsrv_v4statelimit)) {
1274 			/*
1275 			 * Lease has expired several nfsrv_lease times ago:
1276 			 * PLUS
1277 			 *    - no state is associated with it
1278 			 *    OR
1279 			 *    - above high water mark for number of clients
1280 			 *      (nfsrv_clienthighwater should be large enough
1281 			 *       that this only occurs when clients fail to
1282 			 *       use the same nfs_client_id4.id. Maybe somewhat
1283 			 *       higher that the maximum number of clients that
1284 			 *       will mount this server?)
1285 			 * OR
1286 			 * Lease has expired a very long time ago
1287 			 * OR
1288 			 * Lease has expired PLUS the number of opens + locks
1289 			 * has exceeded 90% of capacity
1290 			 *
1291 			 * --> Mark for expiry. The actual expiry will be done
1292 			 *     by an nfsd sometime soon.
1293 			 */
1294 			clp->lc_flags |= LCL_EXPIREIT;
1295 			nfsrv_stablefirst.nsf_flags |=
1296 			    (NFSNSF_NEEDLOCK | NFSNSF_EXPIREDCLIENT);
1297 		    } else {
1298 			/*
1299 			 * If there are no opens, increment no open tick cnt
1300 			 * If time exceeds NFSNOOPEN, mark it to be thrown away
1301 			 * otherwise, if there is an open, reset no open time
1302 			 * Hopefully, this will avoid excessive re-creation
1303 			 * of open owners and subsequent open confirms.
1304 			 */
1305 			stp = LIST_FIRST(&clp->lc_open);
1306 			while (stp != LIST_END(&clp->lc_open)) {
1307 				nstp = LIST_NEXT(stp, ls_list);
1308 				if (LIST_EMPTY(&stp->ls_open)) {
1309 					stp->ls_noopens++;
1310 					if (stp->ls_noopens > NFSNOOPEN ||
1311 					    (nfsrv_openpluslock * 2) >
1312 					    nfsrv_v4statelimit)
1313 						nfsrv_stablefirst.nsf_flags |=
1314 							NFSNSF_NOOPENS;
1315 				} else {
1316 					stp->ls_noopens = 0;
1317 				}
1318 				stp = nstp;
1319 			}
1320 		    }
1321 		}
1322 		clp = nclp;
1323 	    }
1324 	}
1325 	NFSUNLOCKSTATE();
1326 	NFSLOCKV4ROOTMUTEX();
1327 	nfsv4_relref(&nfsv4rootfs_lock);
1328 	NFSUNLOCKV4ROOTMUTEX();
1329 }
1330 
1331 /*
1332  * The following set of functions free up the various data structures.
1333  */
1334 /*
1335  * Clear out all open/lock state related to this nfsclient.
1336  * Caller must hold an exclusive lock on nfsv4rootfs_lock, so that
1337  * there are no other active nfsd threads.
1338  */
1339 APPLESTATIC void
1340 nfsrv_cleanclient(struct nfsclient *clp, NFSPROC_T *p)
1341 {
1342 	struct nfsstate *stp, *nstp;
1343 	struct nfsdsession *sep, *nsep;
1344 
1345 	LIST_FOREACH_SAFE(stp, &clp->lc_open, ls_list, nstp)
1346 		nfsrv_freeopenowner(stp, 1, p);
1347 	if ((clp->lc_flags & LCL_ADMINREVOKED) == 0)
1348 		LIST_FOREACH_SAFE(sep, &clp->lc_session, sess_list, nsep)
1349 			(void)nfsrv_freesession(sep, NULL);
1350 }
1351 
1352 /*
1353  * Free a client that has been cleaned. It should also already have been
1354  * removed from the lists.
1355  * (Just to be safe w.r.t. newnfs_disconnect(), call this function when
1356  *  softclock interrupts are enabled.)
1357  */
1358 APPLESTATIC void
1359 nfsrv_zapclient(struct nfsclient *clp, NFSPROC_T *p)
1360 {
1361 
1362 #ifdef notyet
1363 	if ((clp->lc_flags & (LCL_GSS | LCL_CALLBACKSON)) ==
1364 	     (LCL_GSS | LCL_CALLBACKSON) &&
1365 	    (clp->lc_hand.nfsh_flag & NFSG_COMPLETE) &&
1366 	    clp->lc_handlelen > 0) {
1367 		clp->lc_hand.nfsh_flag &= ~NFSG_COMPLETE;
1368 		clp->lc_hand.nfsh_flag |= NFSG_DESTROYED;
1369 		(void) nfsrv_docallback(clp, NFSV4PROC_CBNULL,
1370 			NULL, 0, NULL, NULL, NULL, 0, p);
1371 	}
1372 #endif
1373 	newnfs_disconnect(&clp->lc_req);
1374 	free(clp->lc_req.nr_nam, M_SONAME);
1375 	NFSFREEMUTEX(&clp->lc_req.nr_mtx);
1376 	free(clp->lc_stateid, M_NFSDCLIENT);
1377 	free(clp, M_NFSDCLIENT);
1378 	NFSLOCKSTATE();
1379 	nfsstatsv1.srvclients--;
1380 	nfsrv_openpluslock--;
1381 	nfsrv_clients--;
1382 	NFSUNLOCKSTATE();
1383 }
1384 
1385 /*
1386  * Free a list of delegation state structures.
1387  * (This function will also free all nfslockfile structures that no
1388  *  longer have associated state.)
1389  */
1390 APPLESTATIC void
1391 nfsrv_freedeleglist(struct nfsstatehead *sthp)
1392 {
1393 	struct nfsstate *stp, *nstp;
1394 
1395 	LIST_FOREACH_SAFE(stp, sthp, ls_list, nstp) {
1396 		nfsrv_freedeleg(stp);
1397 	}
1398 	LIST_INIT(sthp);
1399 }
1400 
1401 /*
1402  * Free up a delegation.
1403  */
1404 static void
1405 nfsrv_freedeleg(struct nfsstate *stp)
1406 {
1407 	struct nfslockfile *lfp;
1408 
1409 	LIST_REMOVE(stp, ls_hash);
1410 	LIST_REMOVE(stp, ls_list);
1411 	LIST_REMOVE(stp, ls_file);
1412 	if ((stp->ls_flags & NFSLCK_DELEGWRITE) != 0)
1413 		nfsrv_writedelegcnt--;
1414 	lfp = stp->ls_lfp;
1415 	if (LIST_EMPTY(&lfp->lf_open) &&
1416 	    LIST_EMPTY(&lfp->lf_lock) && LIST_EMPTY(&lfp->lf_deleg) &&
1417 	    LIST_EMPTY(&lfp->lf_locallock) && LIST_EMPTY(&lfp->lf_rollback) &&
1418 	    lfp->lf_usecount == 0 &&
1419 	    nfsv4_testlock(&lfp->lf_locallock_lck) == 0)
1420 		nfsrv_freenfslockfile(lfp);
1421 	free(stp, M_NFSDSTATE);
1422 	nfsstatsv1.srvdelegates--;
1423 	nfsrv_openpluslock--;
1424 	nfsrv_delegatecnt--;
1425 }
1426 
1427 /*
1428  * This function frees an open owner and all associated opens.
1429  */
1430 static void
1431 nfsrv_freeopenowner(struct nfsstate *stp, int cansleep, NFSPROC_T *p)
1432 {
1433 	struct nfsstate *nstp, *tstp;
1434 
1435 	LIST_REMOVE(stp, ls_list);
1436 	/*
1437 	 * Now, free all associated opens.
1438 	 */
1439 	nstp = LIST_FIRST(&stp->ls_open);
1440 	while (nstp != LIST_END(&stp->ls_open)) {
1441 		tstp = nstp;
1442 		nstp = LIST_NEXT(nstp, ls_list);
1443 		(void) nfsrv_freeopen(tstp, NULL, cansleep, p);
1444 	}
1445 	if (stp->ls_op)
1446 		nfsrvd_derefcache(stp->ls_op);
1447 	free(stp, M_NFSDSTATE);
1448 	nfsstatsv1.srvopenowners--;
1449 	nfsrv_openpluslock--;
1450 }
1451 
1452 /*
1453  * This function frees an open (nfsstate open structure) with all associated
1454  * lock_owners and locks. It also frees the nfslockfile structure iff there
1455  * are no other opens on the file.
1456  * Returns 1 if it free'd the nfslockfile, 0 otherwise.
1457  */
1458 static int
1459 nfsrv_freeopen(struct nfsstate *stp, vnode_t vp, int cansleep, NFSPROC_T *p)
1460 {
1461 	struct nfsstate *nstp, *tstp;
1462 	struct nfslockfile *lfp;
1463 	int ret;
1464 
1465 	LIST_REMOVE(stp, ls_hash);
1466 	LIST_REMOVE(stp, ls_list);
1467 	LIST_REMOVE(stp, ls_file);
1468 
1469 	lfp = stp->ls_lfp;
1470 	/*
1471 	 * Now, free all lockowners associated with this open.
1472 	 */
1473 	LIST_FOREACH_SAFE(tstp, &stp->ls_open, ls_list, nstp)
1474 		nfsrv_freelockowner(tstp, vp, cansleep, p);
1475 
1476 	/*
1477 	 * The nfslockfile is freed here if there are no locks
1478 	 * associated with the open.
1479 	 * If there are locks associated with the open, the
1480 	 * nfslockfile structure can be freed via nfsrv_freelockowner().
1481 	 * Acquire the state mutex to avoid races with calls to
1482 	 * nfsrv_getlockfile().
1483 	 */
1484 	if (cansleep != 0)
1485 		NFSLOCKSTATE();
1486 	if (lfp != NULL && LIST_EMPTY(&lfp->lf_open) &&
1487 	    LIST_EMPTY(&lfp->lf_deleg) && LIST_EMPTY(&lfp->lf_lock) &&
1488 	    LIST_EMPTY(&lfp->lf_locallock) && LIST_EMPTY(&lfp->lf_rollback) &&
1489 	    lfp->lf_usecount == 0 &&
1490 	    (cansleep != 0 || nfsv4_testlock(&lfp->lf_locallock_lck) == 0)) {
1491 		nfsrv_freenfslockfile(lfp);
1492 		ret = 1;
1493 	} else
1494 		ret = 0;
1495 	if (cansleep != 0)
1496 		NFSUNLOCKSTATE();
1497 	free(stp, M_NFSDSTATE);
1498 	nfsstatsv1.srvopens--;
1499 	nfsrv_openpluslock--;
1500 	return (ret);
1501 }
1502 
1503 /*
1504  * Frees a lockowner and all associated locks.
1505  */
1506 static void
1507 nfsrv_freelockowner(struct nfsstate *stp, vnode_t vp, int cansleep,
1508     NFSPROC_T *p)
1509 {
1510 
1511 	LIST_REMOVE(stp, ls_hash);
1512 	LIST_REMOVE(stp, ls_list);
1513 	nfsrv_freeallnfslocks(stp, vp, cansleep, p);
1514 	if (stp->ls_op)
1515 		nfsrvd_derefcache(stp->ls_op);
1516 	free(stp, M_NFSDSTATE);
1517 	nfsstatsv1.srvlockowners--;
1518 	nfsrv_openpluslock--;
1519 }
1520 
1521 /*
1522  * Free all the nfs locks on a lockowner.
1523  */
1524 static void
1525 nfsrv_freeallnfslocks(struct nfsstate *stp, vnode_t vp, int cansleep,
1526     NFSPROC_T *p)
1527 {
1528 	struct nfslock *lop, *nlop;
1529 	struct nfsrollback *rlp, *nrlp;
1530 	struct nfslockfile *lfp = NULL;
1531 	int gottvp = 0;
1532 	vnode_t tvp = NULL;
1533 	uint64_t first, end;
1534 
1535 	if (vp != NULL)
1536 		ASSERT_VOP_UNLOCKED(vp, "nfsrv_freeallnfslocks: vnode locked");
1537 	lop = LIST_FIRST(&stp->ls_lock);
1538 	while (lop != LIST_END(&stp->ls_lock)) {
1539 		nlop = LIST_NEXT(lop, lo_lckowner);
1540 		/*
1541 		 * Since all locks should be for the same file, lfp should
1542 		 * not change.
1543 		 */
1544 		if (lfp == NULL)
1545 			lfp = lop->lo_lfp;
1546 		else if (lfp != lop->lo_lfp)
1547 			panic("allnfslocks");
1548 		/*
1549 		 * If vp is NULL and cansleep != 0, a vnode must be acquired
1550 		 * from the file handle. This only occurs when called from
1551 		 * nfsrv_cleanclient().
1552 		 */
1553 		if (gottvp == 0) {
1554 			if (nfsrv_dolocallocks == 0)
1555 				tvp = NULL;
1556 			else if (vp == NULL && cansleep != 0) {
1557 				tvp = nfsvno_getvp(&lfp->lf_fh);
1558 				NFSVOPUNLOCK(tvp, 0);
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, 0);
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, 0);
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, 0);
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, 0);
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 ((vp->v_iflag & VI_DOOMED) != 0)
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, 0);
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, 0);
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 ((vp->v_iflag & VI_DOOMED) != 0) {
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, 0);
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 && (vp->v_iflag & VI_DOOMED) != 0)
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, 0);
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, *sin;
4061 #endif
4062 #ifdef INET6
4063 	struct sockaddr_in6 *rin6, *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 	nd->nd_repstat = 0;
4459 	cred->cr_uid = clp->lc_uid;
4460 	cred->cr_gid = clp->lc_gid;
4461 	callback = clp->lc_callback;
4462 	NFSUNLOCKSTATE();
4463 	cred->cr_ngroups = 1;
4464 
4465 	/*
4466 	 * Get the first mbuf for the request.
4467 	 */
4468 	MGET(m, M_WAITOK, MT_DATA);
4469 	mbuf_setlen(m, 0);
4470 	nd->nd_mreq = nd->nd_mb = m;
4471 	nd->nd_bpos = NFSMTOD(m, caddr_t);
4472 
4473 	/*
4474 	 * and build the callback request.
4475 	 */
4476 	if (procnum == NFSV4OP_CBGETATTR) {
4477 		nd->nd_procnum = NFSV4PROC_CBCOMPOUND;
4478 		error = nfsrv_cbcallargs(nd, clp, callback, NFSV4OP_CBGETATTR,
4479 		    "CB Getattr", &sep);
4480 		if (error != 0) {
4481 			mbuf_freem(nd->nd_mreq);
4482 			goto errout;
4483 		}
4484 		(void)nfsm_fhtom(nd, (u_int8_t *)fhp, NFSX_MYFH, 0);
4485 		(void)nfsrv_putattrbit(nd, attrbitp);
4486 	} else if (procnum == NFSV4OP_CBRECALL) {
4487 		nd->nd_procnum = NFSV4PROC_CBCOMPOUND;
4488 		error = nfsrv_cbcallargs(nd, clp, callback, NFSV4OP_CBRECALL,
4489 		    "CB Recall", &sep);
4490 		if (error != 0) {
4491 			mbuf_freem(nd->nd_mreq);
4492 			goto errout;
4493 		}
4494 		NFSM_BUILD(tl, u_int32_t *, NFSX_UNSIGNED + NFSX_STATEID);
4495 		*tl++ = txdr_unsigned(stateidp->seqid);
4496 		NFSBCOPY((caddr_t)stateidp->other, (caddr_t)tl,
4497 		    NFSX_STATEIDOTHER);
4498 		tl += (NFSX_STATEIDOTHER / NFSX_UNSIGNED);
4499 		if (trunc)
4500 			*tl = newnfs_true;
4501 		else
4502 			*tl = newnfs_false;
4503 		(void)nfsm_fhtom(nd, (u_int8_t *)fhp, NFSX_MYFH, 0);
4504 	} else if (procnum == NFSV4OP_CBLAYOUTRECALL) {
4505 		NFSD_DEBUG(4, "docallback layout recall\n");
4506 		nd->nd_procnum = NFSV4PROC_CBCOMPOUND;
4507 		error = nfsrv_cbcallargs(nd, clp, callback,
4508 		    NFSV4OP_CBLAYOUTRECALL, "CB Reclayout", &sep);
4509 		NFSD_DEBUG(4, "aft cbcallargs=%d\n", error);
4510 		if (error != 0) {
4511 			mbuf_freem(nd->nd_mreq);
4512 			goto errout;
4513 		}
4514 		NFSM_BUILD(tl, u_int32_t *, 4 * NFSX_UNSIGNED);
4515 		*tl++ = txdr_unsigned(laytype);
4516 		*tl++ = txdr_unsigned(NFSLAYOUTIOMODE_ANY);
4517 		if (trunc)
4518 			*tl++ = newnfs_true;
4519 		else
4520 			*tl++ = newnfs_false;
4521 		*tl = txdr_unsigned(NFSV4LAYOUTRET_FILE);
4522 		nfsm_fhtom(nd, (uint8_t *)fhp, NFSX_MYFH, 0);
4523 		NFSM_BUILD(tl, u_int32_t *, 2 * NFSX_HYPER + NFSX_STATEID);
4524 		tval = 0;
4525 		txdr_hyper(tval, tl); tl += 2;
4526 		tval = UINT64_MAX;
4527 		txdr_hyper(tval, tl); tl += 2;
4528 		*tl++ = txdr_unsigned(stateidp->seqid);
4529 		NFSBCOPY(stateidp->other, tl, NFSX_STATEIDOTHER);
4530 		tl += (NFSX_STATEIDOTHER / NFSX_UNSIGNED);
4531 		NFSD_DEBUG(4, "aft args\n");
4532 	} else if (procnum == NFSV4PROC_CBNULL) {
4533 		nd->nd_procnum = NFSV4PROC_CBNULL;
4534 		if ((clp->lc_flags & LCL_NFSV41) != 0) {
4535 			error = nfsv4_getcbsession(clp, &sep);
4536 			if (error != 0) {
4537 				mbuf_freem(nd->nd_mreq);
4538 				goto errout;
4539 			}
4540 		}
4541 	} else {
4542 		error = NFSERR_SERVERFAULT;
4543 		mbuf_freem(nd->nd_mreq);
4544 		goto errout;
4545 	}
4546 
4547 	/*
4548 	 * Call newnfs_connect(), as required, and then newnfs_request().
4549 	 */
4550 	(void) newnfs_sndlock(&clp->lc_req.nr_lock);
4551 	if (clp->lc_req.nr_client == NULL) {
4552 		if ((clp->lc_flags & LCL_NFSV41) != 0) {
4553 			error = ECONNREFUSED;
4554 			nfsrv_freesession(sep, NULL);
4555 		} else if (nd->nd_procnum == NFSV4PROC_CBNULL)
4556 			error = newnfs_connect(NULL, &clp->lc_req, cred,
4557 			    NULL, 1);
4558 		else
4559 			error = newnfs_connect(NULL, &clp->lc_req, cred,
4560 			    NULL, 3);
4561 	}
4562 	newnfs_sndunlock(&clp->lc_req.nr_lock);
4563 	NFSD_DEBUG(4, "aft sndunlock=%d\n", error);
4564 	if (!error) {
4565 		if ((nd->nd_flag & ND_NFSV41) != 0) {
4566 			KASSERT(sep != NULL, ("sep NULL"));
4567 			if (sep->sess_cbsess.nfsess_xprt != NULL)
4568 				error = newnfs_request(nd, NULL, clp,
4569 				    &clp->lc_req, NULL, NULL, cred,
4570 				    clp->lc_program, clp->lc_req.nr_vers, NULL,
4571 				    1, NULL, &sep->sess_cbsess);
4572 			else {
4573 				/*
4574 				 * This should probably never occur, but if a
4575 				 * client somehow does an RPC without a
4576 				 * SequenceID Op that causes a callback just
4577 				 * after the nfsd threads have been terminated
4578 				 * and restared we could conceivably get here
4579 				 * without a backchannel xprt.
4580 				 */
4581 				printf("nfsrv_docallback: no xprt\n");
4582 				error = ECONNREFUSED;
4583 			}
4584 			NFSD_DEBUG(4, "aft newnfs_request=%d\n", error);
4585 			nfsrv_freesession(sep, NULL);
4586 		} else
4587 			error = newnfs_request(nd, NULL, clp, &clp->lc_req,
4588 			    NULL, NULL, cred, clp->lc_program,
4589 			    clp->lc_req.nr_vers, NULL, 1, NULL, NULL);
4590 	}
4591 errout:
4592 	NFSFREECRED(cred);
4593 
4594 	/*
4595 	 * If error is set here, the Callback path isn't working
4596 	 * properly, so twiddle the appropriate LCL_ flags.
4597 	 * (nd_repstat != 0 indicates the Callback path is working,
4598 	 *  but the callback failed on the client.)
4599 	 */
4600 	if (error) {
4601 		/*
4602 		 * Mark the callback pathway down, which disabled issuing
4603 		 * of delegations and gets Renew to return NFSERR_CBPATHDOWN.
4604 		 */
4605 		NFSLOCKSTATE();
4606 		clp->lc_flags |= LCL_CBDOWN;
4607 		NFSUNLOCKSTATE();
4608 	} else {
4609 		/*
4610 		 * Callback worked. If the callback path was down, disable
4611 		 * callbacks, so no more delegations will be issued. (This
4612 		 * is done on the assumption that the callback pathway is
4613 		 * flakey.)
4614 		 */
4615 		NFSLOCKSTATE();
4616 		if (clp->lc_flags & LCL_CBDOWN)
4617 			clp->lc_flags &= ~(LCL_CBDOWN | LCL_CALLBACKSON);
4618 		NFSUNLOCKSTATE();
4619 		if (nd->nd_repstat) {
4620 			error = nd->nd_repstat;
4621 			NFSD_DEBUG(1, "nfsrv_docallback op=%d err=%d\n",
4622 			    procnum, error);
4623 		} else if (error == 0 && procnum == NFSV4OP_CBGETATTR)
4624 			error = nfsv4_loadattr(nd, NULL, nap, NULL, NULL, 0,
4625 			    NULL, NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL,
4626 			    p, NULL);
4627 		mbuf_freem(nd->nd_mrep);
4628 	}
4629 	NFSLOCKSTATE();
4630 	clp->lc_cbref--;
4631 	if ((clp->lc_flags & LCL_WAKEUPWANTED) && clp->lc_cbref == 0) {
4632 		clp->lc_flags &= ~LCL_WAKEUPWANTED;
4633 		wakeup(clp);
4634 	}
4635 	NFSUNLOCKSTATE();
4636 
4637 	free(nd, M_TEMP);
4638 	NFSEXITCODE(error);
4639 	return (error);
4640 }
4641 
4642 /*
4643  * Set up the compound RPC for the callback.
4644  */
4645 static int
4646 nfsrv_cbcallargs(struct nfsrv_descript *nd, struct nfsclient *clp,
4647     uint32_t callback, int op, const char *optag, struct nfsdsession **sepp)
4648 {
4649 	uint32_t *tl;
4650 	int error, len;
4651 
4652 	len = strlen(optag);
4653 	(void)nfsm_strtom(nd, optag, len);
4654 	NFSM_BUILD(tl, uint32_t *, 4 * NFSX_UNSIGNED);
4655 	if ((nd->nd_flag & ND_NFSV41) != 0) {
4656 		*tl++ = txdr_unsigned(NFSV41_MINORVERSION);
4657 		*tl++ = txdr_unsigned(callback);
4658 		*tl++ = txdr_unsigned(2);
4659 		*tl = txdr_unsigned(NFSV4OP_CBSEQUENCE);
4660 		error = nfsv4_setcbsequence(nd, clp, 1, sepp);
4661 		if (error != 0)
4662 			return (error);
4663 		NFSM_BUILD(tl, u_int32_t *, NFSX_UNSIGNED);
4664 		*tl = txdr_unsigned(op);
4665 	} else {
4666 		*tl++ = txdr_unsigned(NFSV4_MINORVERSION);
4667 		*tl++ = txdr_unsigned(callback);
4668 		*tl++ = txdr_unsigned(1);
4669 		*tl = txdr_unsigned(op);
4670 	}
4671 	return (0);
4672 }
4673 
4674 /*
4675  * Return the next index# for a clientid. Mostly just increment and return
4676  * the next one, but... if the 32bit unsigned does actually wrap around,
4677  * it should be rebooted.
4678  * At an average rate of one new client per second, it will wrap around in
4679  * approximately 136 years. (I think the server will have been shut
4680  * down or rebooted before then.)
4681  */
4682 static u_int32_t
4683 nfsrv_nextclientindex(void)
4684 {
4685 	static u_int32_t client_index = 0;
4686 
4687 	client_index++;
4688 	if (client_index != 0)
4689 		return (client_index);
4690 
4691 	printf("%s: out of clientids\n", __func__);
4692 	return (client_index);
4693 }
4694 
4695 /*
4696  * Return the next index# for a stateid. Mostly just increment and return
4697  * the next one, but... if the 32bit unsigned does actually wrap around
4698  * (will a BSD server stay up that long?), find
4699  * new start and end values.
4700  */
4701 static u_int32_t
4702 nfsrv_nextstateindex(struct nfsclient *clp)
4703 {
4704 	struct nfsstate *stp;
4705 	int i;
4706 	u_int32_t canuse, min_index, max_index;
4707 
4708 	if (!(clp->lc_flags & LCL_INDEXNOTOK)) {
4709 		clp->lc_stateindex++;
4710 		if (clp->lc_stateindex != clp->lc_statemaxindex)
4711 			return (clp->lc_stateindex);
4712 	}
4713 
4714 	/*
4715 	 * Yuck, we've hit the end.
4716 	 * Look for a new min and max.
4717 	 */
4718 	min_index = 0;
4719 	max_index = 0xffffffff;
4720 	for (i = 0; i < nfsrv_statehashsize; i++) {
4721 	    LIST_FOREACH(stp, &clp->lc_stateid[i], ls_hash) {
4722 		if (stp->ls_stateid.other[2] > 0x80000000) {
4723 		    if (stp->ls_stateid.other[2] < max_index)
4724 			max_index = stp->ls_stateid.other[2];
4725 		} else {
4726 		    if (stp->ls_stateid.other[2] > min_index)
4727 			min_index = stp->ls_stateid.other[2];
4728 		}
4729 	    }
4730 	}
4731 
4732 	/*
4733 	 * Yikes, highly unlikely, but I'll handle it anyhow.
4734 	 */
4735 	if (min_index == 0x80000000 && max_index == 0x80000001) {
4736 	    canuse = 0;
4737 	    /*
4738 	     * Loop around until we find an unused entry. Return that
4739 	     * and set LCL_INDEXNOTOK, so the search will continue next time.
4740 	     * (This is one of those rare cases where a goto is the
4741 	     *  cleanest way to code the loop.)
4742 	     */
4743 tryagain:
4744 	    for (i = 0; i < nfsrv_statehashsize; i++) {
4745 		LIST_FOREACH(stp, &clp->lc_stateid[i], ls_hash) {
4746 		    if (stp->ls_stateid.other[2] == canuse) {
4747 			canuse++;
4748 			goto tryagain;
4749 		    }
4750 		}
4751 	    }
4752 	    clp->lc_flags |= LCL_INDEXNOTOK;
4753 	    return (canuse);
4754 	}
4755 
4756 	/*
4757 	 * Ok to start again from min + 1.
4758 	 */
4759 	clp->lc_stateindex = min_index + 1;
4760 	clp->lc_statemaxindex = max_index;
4761 	clp->lc_flags &= ~LCL_INDEXNOTOK;
4762 	return (clp->lc_stateindex);
4763 }
4764 
4765 /*
4766  * The following functions handle the stable storage file that deals with
4767  * the edge conditions described in RFC3530 Sec. 8.6.3.
4768  * The file is as follows:
4769  * - a single record at the beginning that has the lease time of the
4770  *   previous server instance (before the last reboot) and the nfsrvboottime
4771  *   values for the previous server boots.
4772  *   These previous boot times are used to ensure that the current
4773  *   nfsrvboottime does not, somehow, get set to a previous one.
4774  *   (This is important so that Stale ClientIDs and StateIDs can
4775  *    be recognized.)
4776  *   The number of previous nfsvrboottime values precedes the list.
4777  * - followed by some number of appended records with:
4778  *   - client id string
4779  *   - flag that indicates it is a record revoking state via lease
4780  *     expiration or similar
4781  *     OR has successfully acquired state.
4782  * These structures vary in length, with the client string at the end, up
4783  * to NFSV4_OPAQUELIMIT in size.
4784  *
4785  * At the end of the grace period, the file is truncated, the first
4786  * record is rewritten with updated information and any acquired state
4787  * records for successful reclaims of state are written.
4788  *
4789  * Subsequent records are appended when the first state is issued to
4790  * a client and when state is revoked for a client.
4791  *
4792  * When reading the file in, state issued records that come later in
4793  * the file override older ones, since the append log is in cronological order.
4794  * If, for some reason, the file can't be read, the grace period is
4795  * immediately terminated and all reclaims get NFSERR_NOGRACE.
4796  */
4797 
4798 /*
4799  * Read in the stable storage file. Called by nfssvc() before the nfsd
4800  * processes start servicing requests.
4801  */
4802 APPLESTATIC void
4803 nfsrv_setupstable(NFSPROC_T *p)
4804 {
4805 	struct nfsrv_stablefirst *sf = &nfsrv_stablefirst;
4806 	struct nfsrv_stable *sp, *nsp;
4807 	struct nfst_rec *tsp;
4808 	int error, i, tryagain;
4809 	off_t off = 0;
4810 	ssize_t aresid, len;
4811 
4812 	/*
4813 	 * If NFSNSF_UPDATEDONE is set, this is a restart of the nfsds without
4814 	 * a reboot, so state has not been lost.
4815 	 */
4816 	if (sf->nsf_flags & NFSNSF_UPDATEDONE)
4817 		return;
4818 	/*
4819 	 * Set Grace over just until the file reads successfully.
4820 	 */
4821 	nfsrvboottime = time_second;
4822 	LIST_INIT(&sf->nsf_head);
4823 	sf->nsf_flags = (NFSNSF_GRACEOVER | NFSNSF_NEEDLOCK);
4824 	sf->nsf_eograce = NFSD_MONOSEC + NFSRV_LEASEDELTA;
4825 	if (sf->nsf_fp == NULL)
4826 		return;
4827 	error = NFSD_RDWR(UIO_READ, NFSFPVNODE(sf->nsf_fp),
4828 	    (caddr_t)&sf->nsf_rec, sizeof (struct nfsf_rec), off, UIO_SYSSPACE,
4829 	    0, NFSFPCRED(sf->nsf_fp), &aresid, p);
4830 	if (error || aresid || sf->nsf_numboots == 0 ||
4831 		sf->nsf_numboots > NFSNSF_MAXNUMBOOTS)
4832 		return;
4833 
4834 	/*
4835 	 * Now, read in the boottimes.
4836 	 */
4837 	sf->nsf_bootvals = (time_t *)malloc((sf->nsf_numboots + 1) *
4838 		sizeof (time_t), M_TEMP, M_WAITOK);
4839 	off = sizeof (struct nfsf_rec);
4840 	error = NFSD_RDWR(UIO_READ, NFSFPVNODE(sf->nsf_fp),
4841 	    (caddr_t)sf->nsf_bootvals, sf->nsf_numboots * sizeof (time_t), off,
4842 	    UIO_SYSSPACE, 0, NFSFPCRED(sf->nsf_fp), &aresid, p);
4843 	if (error || aresid) {
4844 		free(sf->nsf_bootvals, M_TEMP);
4845 		sf->nsf_bootvals = NULL;
4846 		return;
4847 	}
4848 
4849 	/*
4850 	 * Make sure this nfsrvboottime is different from all recorded
4851 	 * previous ones.
4852 	 */
4853 	do {
4854 		tryagain = 0;
4855 		for (i = 0; i < sf->nsf_numboots; i++) {
4856 			if (nfsrvboottime == sf->nsf_bootvals[i]) {
4857 				nfsrvboottime++;
4858 				tryagain = 1;
4859 				break;
4860 			}
4861 		}
4862 	} while (tryagain);
4863 
4864 	sf->nsf_flags |= NFSNSF_OK;
4865 	off += (sf->nsf_numboots * sizeof (time_t));
4866 
4867 	/*
4868 	 * Read through the file, building a list of records for grace
4869 	 * checking.
4870 	 * Each record is between sizeof (struct nfst_rec) and
4871 	 * sizeof (struct nfst_rec) + NFSV4_OPAQUELIMIT - 1
4872 	 * and is actually sizeof (struct nfst_rec) + nst_len - 1.
4873 	 */
4874 	tsp = (struct nfst_rec *)malloc(sizeof (struct nfst_rec) +
4875 		NFSV4_OPAQUELIMIT - 1, M_TEMP, M_WAITOK);
4876 	do {
4877 	    error = NFSD_RDWR(UIO_READ, NFSFPVNODE(sf->nsf_fp),
4878 	        (caddr_t)tsp, sizeof (struct nfst_rec) + NFSV4_OPAQUELIMIT - 1,
4879 	        off, UIO_SYSSPACE, 0, NFSFPCRED(sf->nsf_fp), &aresid, p);
4880 	    len = (sizeof (struct nfst_rec) + NFSV4_OPAQUELIMIT - 1) - aresid;
4881 	    if (error || (len > 0 && (len < sizeof (struct nfst_rec) ||
4882 		len < (sizeof (struct nfst_rec) + tsp->len - 1)))) {
4883 		/*
4884 		 * Yuck, the file has been corrupted, so just return
4885 		 * after clearing out any restart state, so the grace period
4886 		 * is over.
4887 		 */
4888 		LIST_FOREACH_SAFE(sp, &sf->nsf_head, nst_list, nsp) {
4889 			LIST_REMOVE(sp, nst_list);
4890 			free(sp, M_TEMP);
4891 		}
4892 		free(tsp, M_TEMP);
4893 		sf->nsf_flags &= ~NFSNSF_OK;
4894 		free(sf->nsf_bootvals, M_TEMP);
4895 		sf->nsf_bootvals = NULL;
4896 		return;
4897 	    }
4898 	    if (len > 0) {
4899 		off += sizeof (struct nfst_rec) + tsp->len - 1;
4900 		/*
4901 		 * Search the list for a matching client.
4902 		 */
4903 		LIST_FOREACH(sp, &sf->nsf_head, nst_list) {
4904 			if (tsp->len == sp->nst_len &&
4905 			    !NFSBCMP(tsp->client, sp->nst_client, tsp->len))
4906 				break;
4907 		}
4908 		if (sp == LIST_END(&sf->nsf_head)) {
4909 			sp = (struct nfsrv_stable *)malloc(tsp->len +
4910 				sizeof (struct nfsrv_stable) - 1, M_TEMP,
4911 				M_WAITOK);
4912 			NFSBCOPY((caddr_t)tsp, (caddr_t)&sp->nst_rec,
4913 				sizeof (struct nfst_rec) + tsp->len - 1);
4914 			LIST_INSERT_HEAD(&sf->nsf_head, sp, nst_list);
4915 		} else {
4916 			if (tsp->flag == NFSNST_REVOKE)
4917 				sp->nst_flag |= NFSNST_REVOKE;
4918 			else
4919 				/*
4920 				 * A subsequent timestamp indicates the client
4921 				 * did a setclientid/confirm and any previous
4922 				 * revoke is no longer relevant.
4923 				 */
4924 				sp->nst_flag &= ~NFSNST_REVOKE;
4925 		}
4926 	    }
4927 	} while (len > 0);
4928 	free(tsp, M_TEMP);
4929 	sf->nsf_flags = NFSNSF_OK;
4930 	sf->nsf_eograce = NFSD_MONOSEC + sf->nsf_lease +
4931 		NFSRV_LEASEDELTA;
4932 }
4933 
4934 /*
4935  * Update the stable storage file, now that the grace period is over.
4936  */
4937 APPLESTATIC void
4938 nfsrv_updatestable(NFSPROC_T *p)
4939 {
4940 	struct nfsrv_stablefirst *sf = &nfsrv_stablefirst;
4941 	struct nfsrv_stable *sp, *nsp;
4942 	int i;
4943 	struct nfsvattr nva;
4944 	vnode_t vp;
4945 #if defined(__FreeBSD_version) && (__FreeBSD_version >= 500000)
4946 	mount_t mp = NULL;
4947 #endif
4948 	int error;
4949 
4950 	if (sf->nsf_fp == NULL || (sf->nsf_flags & NFSNSF_UPDATEDONE))
4951 		return;
4952 	sf->nsf_flags |= NFSNSF_UPDATEDONE;
4953 	/*
4954 	 * Ok, we need to rewrite the stable storage file.
4955 	 * - truncate to 0 length
4956 	 * - write the new first structure
4957 	 * - loop through the data structures, writing out any that
4958 	 *   have timestamps older than the old boot
4959 	 */
4960 	if (sf->nsf_bootvals) {
4961 		sf->nsf_numboots++;
4962 		for (i = sf->nsf_numboots - 2; i >= 0; i--)
4963 			sf->nsf_bootvals[i + 1] = sf->nsf_bootvals[i];
4964 	} else {
4965 		sf->nsf_numboots = 1;
4966 		sf->nsf_bootvals = (time_t *)malloc(sizeof (time_t),
4967 			M_TEMP, M_WAITOK);
4968 	}
4969 	sf->nsf_bootvals[0] = nfsrvboottime;
4970 	sf->nsf_lease = nfsrv_lease;
4971 	NFSVNO_ATTRINIT(&nva);
4972 	NFSVNO_SETATTRVAL(&nva, size, 0);
4973 	vp = NFSFPVNODE(sf->nsf_fp);
4974 	vn_start_write(vp, &mp, V_WAIT);
4975 	if (NFSVOPLOCK(vp, LK_EXCLUSIVE) == 0) {
4976 		error = nfsvno_setattr(vp, &nva, NFSFPCRED(sf->nsf_fp), p,
4977 		    NULL);
4978 		NFSVOPUNLOCK(vp, 0);
4979 	} else
4980 		error = EPERM;
4981 	vn_finished_write(mp);
4982 	if (!error)
4983 	    error = NFSD_RDWR(UIO_WRITE, vp,
4984 		(caddr_t)&sf->nsf_rec, sizeof (struct nfsf_rec), (off_t)0,
4985 		UIO_SYSSPACE, IO_SYNC, NFSFPCRED(sf->nsf_fp), NULL, p);
4986 	if (!error)
4987 	    error = NFSD_RDWR(UIO_WRITE, vp,
4988 		(caddr_t)sf->nsf_bootvals,
4989 		sf->nsf_numboots * sizeof (time_t),
4990 		(off_t)(sizeof (struct nfsf_rec)),
4991 		UIO_SYSSPACE, IO_SYNC, NFSFPCRED(sf->nsf_fp), NULL, p);
4992 	free(sf->nsf_bootvals, M_TEMP);
4993 	sf->nsf_bootvals = NULL;
4994 	if (error) {
4995 		sf->nsf_flags &= ~NFSNSF_OK;
4996 		printf("EEK! Can't write NfsV4 stable storage file\n");
4997 		return;
4998 	}
4999 	sf->nsf_flags |= NFSNSF_OK;
5000 
5001 	/*
5002 	 * Loop through the list and write out timestamp records for
5003 	 * any clients that successfully reclaimed state.
5004 	 */
5005 	LIST_FOREACH_SAFE(sp, &sf->nsf_head, nst_list, nsp) {
5006 		if (sp->nst_flag & NFSNST_GOTSTATE) {
5007 			nfsrv_writestable(sp->nst_client, sp->nst_len,
5008 				NFSNST_NEWSTATE, p);
5009 			sp->nst_clp->lc_flags |= LCL_STAMPEDSTABLE;
5010 		}
5011 		LIST_REMOVE(sp, nst_list);
5012 		free(sp, M_TEMP);
5013 	}
5014 	nfsrv_backupstable();
5015 }
5016 
5017 /*
5018  * Append a record to the stable storage file.
5019  */
5020 APPLESTATIC void
5021 nfsrv_writestable(u_char *client, int len, int flag, NFSPROC_T *p)
5022 {
5023 	struct nfsrv_stablefirst *sf = &nfsrv_stablefirst;
5024 	struct nfst_rec *sp;
5025 	int error;
5026 
5027 	if (!(sf->nsf_flags & NFSNSF_OK) || sf->nsf_fp == NULL)
5028 		return;
5029 	sp = (struct nfst_rec *)malloc(sizeof (struct nfst_rec) +
5030 		len - 1, M_TEMP, M_WAITOK);
5031 	sp->len = len;
5032 	NFSBCOPY(client, sp->client, len);
5033 	sp->flag = flag;
5034 	error = NFSD_RDWR(UIO_WRITE, NFSFPVNODE(sf->nsf_fp),
5035 	    (caddr_t)sp, sizeof (struct nfst_rec) + len - 1, (off_t)0,
5036 	    UIO_SYSSPACE, (IO_SYNC | IO_APPEND), NFSFPCRED(sf->nsf_fp), NULL, p);
5037 	free(sp, M_TEMP);
5038 	if (error) {
5039 		sf->nsf_flags &= ~NFSNSF_OK;
5040 		printf("EEK! Can't write NfsV4 stable storage file\n");
5041 	}
5042 }
5043 
5044 /*
5045  * This function is called during the grace period to mark a client
5046  * that successfully reclaimed state.
5047  */
5048 static void
5049 nfsrv_markstable(struct nfsclient *clp)
5050 {
5051 	struct nfsrv_stable *sp;
5052 
5053 	/*
5054 	 * First find the client structure.
5055 	 */
5056 	LIST_FOREACH(sp, &nfsrv_stablefirst.nsf_head, nst_list) {
5057 		if (sp->nst_len == clp->lc_idlen &&
5058 		    !NFSBCMP(sp->nst_client, clp->lc_id, sp->nst_len))
5059 			break;
5060 	}
5061 	if (sp == LIST_END(&nfsrv_stablefirst.nsf_head))
5062 		return;
5063 
5064 	/*
5065 	 * Now, just mark it and set the nfsclient back pointer.
5066 	 */
5067 	sp->nst_flag |= NFSNST_GOTSTATE;
5068 	sp->nst_clp = clp;
5069 }
5070 
5071 /*
5072  * This function is called when a NFSv4.1 client does a ReclaimComplete.
5073  * Very similar to nfsrv_markstable(), except for the flag being set.
5074  */
5075 static void
5076 nfsrv_markreclaim(struct nfsclient *clp)
5077 {
5078 	struct nfsrv_stable *sp;
5079 
5080 	/*
5081 	 * First find the client structure.
5082 	 */
5083 	LIST_FOREACH(sp, &nfsrv_stablefirst.nsf_head, nst_list) {
5084 		if (sp->nst_len == clp->lc_idlen &&
5085 		    !NFSBCMP(sp->nst_client, clp->lc_id, sp->nst_len))
5086 			break;
5087 	}
5088 	if (sp == LIST_END(&nfsrv_stablefirst.nsf_head))
5089 		return;
5090 
5091 	/*
5092 	 * Now, just set the flag.
5093 	 */
5094 	sp->nst_flag |= NFSNST_RECLAIMED;
5095 }
5096 
5097 /*
5098  * This function is called for a reclaim, to see if it gets grace.
5099  * It returns 0 if a reclaim is allowed, 1 otherwise.
5100  */
5101 static int
5102 nfsrv_checkstable(struct nfsclient *clp)
5103 {
5104 	struct nfsrv_stable *sp;
5105 
5106 	/*
5107 	 * First, find the entry for the client.
5108 	 */
5109 	LIST_FOREACH(sp, &nfsrv_stablefirst.nsf_head, nst_list) {
5110 		if (sp->nst_len == clp->lc_idlen &&
5111 		    !NFSBCMP(sp->nst_client, clp->lc_id, sp->nst_len))
5112 			break;
5113 	}
5114 
5115 	/*
5116 	 * If not in the list, state was revoked or no state was issued
5117 	 * since the previous reboot, a reclaim is denied.
5118 	 */
5119 	if (sp == LIST_END(&nfsrv_stablefirst.nsf_head) ||
5120 	    (sp->nst_flag & NFSNST_REVOKE) ||
5121 	    !(nfsrv_stablefirst.nsf_flags & NFSNSF_OK))
5122 		return (1);
5123 	return (0);
5124 }
5125 
5126 /*
5127  * Test for and try to clear out a conflicting client. This is called by
5128  * nfsrv_lockctrl() and nfsrv_openctrl() when conflicts with other clients
5129  * a found.
5130  * The trick here is that it can't revoke a conflicting client with an
5131  * expired lease unless it holds the v4root lock, so...
5132  * If no v4root lock, get the lock and return 1 to indicate "try again".
5133  * Return 0 to indicate the conflict can't be revoked and 1 to indicate
5134  * the revocation worked and the conflicting client is "bye, bye", so it
5135  * can be tried again.
5136  * Return 2 to indicate that the vnode is VI_DOOMED after NFSVOPLOCK().
5137  * Unlocks State before a non-zero value is returned.
5138  */
5139 static int
5140 nfsrv_clientconflict(struct nfsclient *clp, int *haslockp, vnode_t vp,
5141     NFSPROC_T *p)
5142 {
5143 	int gotlock, lktype = 0;
5144 
5145 	/*
5146 	 * If lease hasn't expired, we can't fix it.
5147 	 */
5148 	if (clp->lc_expiry >= NFSD_MONOSEC ||
5149 	    !(nfsrv_stablefirst.nsf_flags & NFSNSF_UPDATEDONE))
5150 		return (0);
5151 	if (*haslockp == 0) {
5152 		NFSUNLOCKSTATE();
5153 		if (vp != NULL) {
5154 			lktype = NFSVOPISLOCKED(vp);
5155 			NFSVOPUNLOCK(vp, 0);
5156 		}
5157 		NFSLOCKV4ROOTMUTEX();
5158 		nfsv4_relref(&nfsv4rootfs_lock);
5159 		do {
5160 			gotlock = nfsv4_lock(&nfsv4rootfs_lock, 1, NULL,
5161 			    NFSV4ROOTLOCKMUTEXPTR, NULL);
5162 		} while (!gotlock);
5163 		NFSUNLOCKV4ROOTMUTEX();
5164 		*haslockp = 1;
5165 		if (vp != NULL) {
5166 			NFSVOPLOCK(vp, lktype | LK_RETRY);
5167 			if ((vp->v_iflag & VI_DOOMED) != 0)
5168 				return (2);
5169 		}
5170 		return (1);
5171 	}
5172 	NFSUNLOCKSTATE();
5173 
5174 	/*
5175 	 * Ok, we can expire the conflicting client.
5176 	 */
5177 	nfsrv_writestable(clp->lc_id, clp->lc_idlen, NFSNST_REVOKE, p);
5178 	nfsrv_backupstable();
5179 	nfsrv_cleanclient(clp, p);
5180 	nfsrv_freedeleglist(&clp->lc_deleg);
5181 	nfsrv_freedeleglist(&clp->lc_olddeleg);
5182 	LIST_REMOVE(clp, lc_hash);
5183 	nfsrv_zapclient(clp, p);
5184 	return (1);
5185 }
5186 
5187 /*
5188  * Resolve a delegation conflict.
5189  * Returns 0 to indicate the conflict was resolved without sleeping.
5190  * Return -1 to indicate that the caller should check for conflicts again.
5191  * Return > 0 for an error that should be returned, normally NFSERR_DELAY.
5192  *
5193  * Also, manipulate the nfsv4root_lock, as required. It isn't changed
5194  * for a return of 0, since there was no sleep and it could be required
5195  * later. It is released for a return of NFSERR_DELAY, since the caller
5196  * will return that error. It is released when a sleep was done waiting
5197  * for the delegation to be returned or expire (so that other nfsds can
5198  * handle ops). Then, it must be acquired for the write to stable storage.
5199  * (This function is somewhat similar to nfsrv_clientconflict(), but
5200  *  the semantics differ in a couple of subtle ways. The return of 0
5201  *  indicates the conflict was resolved without sleeping here, not
5202  *  that the conflict can't be resolved and the handling of nfsv4root_lock
5203  *  differs, as noted above.)
5204  * Unlocks State before returning a non-zero value.
5205  */
5206 static int
5207 nfsrv_delegconflict(struct nfsstate *stp, int *haslockp, NFSPROC_T *p,
5208     vnode_t vp)
5209 {
5210 	struct nfsclient *clp = stp->ls_clp;
5211 	int gotlock, error, lktype = 0, retrycnt, zapped_clp;
5212 	nfsv4stateid_t tstateid;
5213 	fhandle_t tfh;
5214 
5215 	/*
5216 	 * If the conflict is with an old delegation...
5217 	 */
5218 	if (stp->ls_flags & NFSLCK_OLDDELEG) {
5219 		/*
5220 		 * You can delete it, if it has expired.
5221 		 */
5222 		if (clp->lc_delegtime < NFSD_MONOSEC) {
5223 			nfsrv_freedeleg(stp);
5224 			NFSUNLOCKSTATE();
5225 			error = -1;
5226 			goto out;
5227 		}
5228 		NFSUNLOCKSTATE();
5229 		/*
5230 		 * During this delay, the old delegation could expire or it
5231 		 * could be recovered by the client via an Open with
5232 		 * CLAIM_DELEGATE_PREV.
5233 		 * Release the nfsv4root_lock, if held.
5234 		 */
5235 		if (*haslockp) {
5236 			*haslockp = 0;
5237 			NFSLOCKV4ROOTMUTEX();
5238 			nfsv4_unlock(&nfsv4rootfs_lock, 1);
5239 			NFSUNLOCKV4ROOTMUTEX();
5240 		}
5241 		error = NFSERR_DELAY;
5242 		goto out;
5243 	}
5244 
5245 	/*
5246 	 * It's a current delegation, so:
5247 	 * - check to see if the delegation has expired
5248 	 *   - if so, get the v4root lock and then expire it
5249 	 */
5250 	if (!(stp->ls_flags & NFSLCK_DELEGRECALL)) {
5251 		/*
5252 		 * - do a recall callback, since not yet done
5253 		 * For now, never allow truncate to be set. To use
5254 		 * truncate safely, it must be guaranteed that the
5255 		 * Remove, Rename or Setattr with size of 0 will
5256 		 * succeed and that would require major changes to
5257 		 * the VFS/Vnode OPs.
5258 		 * Set the expiry time large enough so that it won't expire
5259 		 * until after the callback, then set it correctly, once
5260 		 * the callback is done. (The delegation will now time
5261 		 * out whether or not the Recall worked ok. The timeout
5262 		 * will be extended when ops are done on the delegation
5263 		 * stateid, up to the timelimit.)
5264 		 */
5265 		stp->ls_delegtime = NFSD_MONOSEC + (2 * nfsrv_lease) +
5266 		    NFSRV_LEASEDELTA;
5267 		stp->ls_delegtimelimit = NFSD_MONOSEC + (6 * nfsrv_lease) +
5268 		    NFSRV_LEASEDELTA;
5269 		stp->ls_flags |= NFSLCK_DELEGRECALL;
5270 
5271 		/*
5272 		 * Loop NFSRV_CBRETRYCNT times while the CBRecall replies
5273 		 * NFSERR_BADSTATEID or NFSERR_BADHANDLE. This is done
5274 		 * in order to try and avoid a race that could happen
5275 		 * when a CBRecall request passed the Open reply with
5276 		 * the delegation in it when transitting the network.
5277 		 * Since nfsrv_docallback will sleep, don't use stp after
5278 		 * the call.
5279 		 */
5280 		NFSBCOPY((caddr_t)&stp->ls_stateid, (caddr_t)&tstateid,
5281 		    sizeof (tstateid));
5282 		NFSBCOPY((caddr_t)&stp->ls_lfp->lf_fh, (caddr_t)&tfh,
5283 		    sizeof (tfh));
5284 		NFSUNLOCKSTATE();
5285 		if (*haslockp) {
5286 			*haslockp = 0;
5287 			NFSLOCKV4ROOTMUTEX();
5288 			nfsv4_unlock(&nfsv4rootfs_lock, 1);
5289 			NFSUNLOCKV4ROOTMUTEX();
5290 		}
5291 		retrycnt = 0;
5292 		do {
5293 		    error = nfsrv_docallback(clp, NFSV4OP_CBRECALL,
5294 			&tstateid, 0, &tfh, NULL, NULL, 0, p);
5295 		    retrycnt++;
5296 		} while ((error == NFSERR_BADSTATEID ||
5297 		    error == NFSERR_BADHANDLE) && retrycnt < NFSV4_CBRETRYCNT);
5298 		error = NFSERR_DELAY;
5299 		goto out;
5300 	}
5301 
5302 	if (clp->lc_expiry >= NFSD_MONOSEC &&
5303 	    stp->ls_delegtime >= NFSD_MONOSEC) {
5304 		NFSUNLOCKSTATE();
5305 		/*
5306 		 * A recall has been done, but it has not yet expired.
5307 		 * So, RETURN_DELAY.
5308 		 */
5309 		if (*haslockp) {
5310 			*haslockp = 0;
5311 			NFSLOCKV4ROOTMUTEX();
5312 			nfsv4_unlock(&nfsv4rootfs_lock, 1);
5313 			NFSUNLOCKV4ROOTMUTEX();
5314 		}
5315 		error = NFSERR_DELAY;
5316 		goto out;
5317 	}
5318 
5319 	/*
5320 	 * If we don't yet have the lock, just get it and then return,
5321 	 * since we need that before deleting expired state, such as
5322 	 * this delegation.
5323 	 * When getting the lock, unlock the vnode, so other nfsds that
5324 	 * are in progress, won't get stuck waiting for the vnode lock.
5325 	 */
5326 	if (*haslockp == 0) {
5327 		NFSUNLOCKSTATE();
5328 		if (vp != NULL) {
5329 			lktype = NFSVOPISLOCKED(vp);
5330 			NFSVOPUNLOCK(vp, 0);
5331 		}
5332 		NFSLOCKV4ROOTMUTEX();
5333 		nfsv4_relref(&nfsv4rootfs_lock);
5334 		do {
5335 			gotlock = nfsv4_lock(&nfsv4rootfs_lock, 1, NULL,
5336 			    NFSV4ROOTLOCKMUTEXPTR, NULL);
5337 		} while (!gotlock);
5338 		NFSUNLOCKV4ROOTMUTEX();
5339 		*haslockp = 1;
5340 		if (vp != NULL) {
5341 			NFSVOPLOCK(vp, lktype | LK_RETRY);
5342 			if ((vp->v_iflag & VI_DOOMED) != 0) {
5343 				*haslockp = 0;
5344 				NFSLOCKV4ROOTMUTEX();
5345 				nfsv4_unlock(&nfsv4rootfs_lock, 1);
5346 				NFSUNLOCKV4ROOTMUTEX();
5347 				error = NFSERR_PERM;
5348 				goto out;
5349 			}
5350 		}
5351 		error = -1;
5352 		goto out;
5353 	}
5354 
5355 	NFSUNLOCKSTATE();
5356 	/*
5357 	 * Ok, we can delete the expired delegation.
5358 	 * First, write the Revoke record to stable storage and then
5359 	 * clear out the conflict.
5360 	 * Since all other nfsd threads are now blocked, we can safely
5361 	 * sleep without the state changing.
5362 	 */
5363 	nfsrv_writestable(clp->lc_id, clp->lc_idlen, NFSNST_REVOKE, p);
5364 	nfsrv_backupstable();
5365 	if (clp->lc_expiry < NFSD_MONOSEC) {
5366 		nfsrv_cleanclient(clp, p);
5367 		nfsrv_freedeleglist(&clp->lc_deleg);
5368 		nfsrv_freedeleglist(&clp->lc_olddeleg);
5369 		LIST_REMOVE(clp, lc_hash);
5370 		zapped_clp = 1;
5371 	} else {
5372 		nfsrv_freedeleg(stp);
5373 		zapped_clp = 0;
5374 	}
5375 	if (zapped_clp)
5376 		nfsrv_zapclient(clp, p);
5377 	error = -1;
5378 
5379 out:
5380 	NFSEXITCODE(error);
5381 	return (error);
5382 }
5383 
5384 /*
5385  * Check for a remove allowed, if remove is set to 1 and get rid of
5386  * delegations.
5387  */
5388 APPLESTATIC int
5389 nfsrv_checkremove(vnode_t vp, int remove, NFSPROC_T *p)
5390 {
5391 	struct nfsstate *stp;
5392 	struct nfslockfile *lfp;
5393 	int error, haslock = 0;
5394 	fhandle_t nfh;
5395 
5396 	/*
5397 	 * First, get the lock file structure.
5398 	 * (A return of -1 means no associated state, so remove ok.)
5399 	 */
5400 	error = nfsrv_getlockfh(vp, NFSLCK_CHECK, NULL, &nfh, p);
5401 tryagain:
5402 	NFSLOCKSTATE();
5403 	if (!error)
5404 		error = nfsrv_getlockfile(NFSLCK_CHECK, NULL, &lfp, &nfh, 0);
5405 	if (error) {
5406 		NFSUNLOCKSTATE();
5407 		if (haslock) {
5408 			NFSLOCKV4ROOTMUTEX();
5409 			nfsv4_unlock(&nfsv4rootfs_lock, 1);
5410 			NFSUNLOCKV4ROOTMUTEX();
5411 		}
5412 		if (error == -1)
5413 			error = 0;
5414 		goto out;
5415 	}
5416 
5417 	/*
5418 	 * Now, we must Recall any delegations.
5419 	 */
5420 	error = nfsrv_cleandeleg(vp, lfp, NULL, &haslock, p);
5421 	if (error) {
5422 		/*
5423 		 * nfsrv_cleandeleg() unlocks state for non-zero
5424 		 * return.
5425 		 */
5426 		if (error == -1)
5427 			goto tryagain;
5428 		if (haslock) {
5429 			NFSLOCKV4ROOTMUTEX();
5430 			nfsv4_unlock(&nfsv4rootfs_lock, 1);
5431 			NFSUNLOCKV4ROOTMUTEX();
5432 		}
5433 		goto out;
5434 	}
5435 
5436 	/*
5437 	 * Now, look for a conflicting open share.
5438 	 */
5439 	if (remove) {
5440 		/*
5441 		 * If the entry in the directory was the last reference to the
5442 		 * corresponding filesystem object, the object can be destroyed
5443 		 * */
5444 		if(lfp->lf_usecount>1)
5445 			LIST_FOREACH(stp, &lfp->lf_open, ls_file) {
5446 				if (stp->ls_flags & NFSLCK_WRITEDENY) {
5447 					error = NFSERR_FILEOPEN;
5448 					break;
5449 				}
5450 			}
5451 	}
5452 
5453 	NFSUNLOCKSTATE();
5454 	if (haslock) {
5455 		NFSLOCKV4ROOTMUTEX();
5456 		nfsv4_unlock(&nfsv4rootfs_lock, 1);
5457 		NFSUNLOCKV4ROOTMUTEX();
5458 	}
5459 
5460 out:
5461 	NFSEXITCODE(error);
5462 	return (error);
5463 }
5464 
5465 /*
5466  * Clear out all delegations for the file referred to by lfp.
5467  * May return NFSERR_DELAY, if there will be a delay waiting for
5468  * delegations to expire.
5469  * Returns -1 to indicate it slept while recalling a delegation.
5470  * This function has the side effect of deleting the nfslockfile structure,
5471  * if it no longer has associated state and didn't have to sleep.
5472  * Unlocks State before a non-zero value is returned.
5473  */
5474 static int
5475 nfsrv_cleandeleg(vnode_t vp, struct nfslockfile *lfp,
5476     struct nfsclient *clp, int *haslockp, NFSPROC_T *p)
5477 {
5478 	struct nfsstate *stp, *nstp;
5479 	int ret = 0;
5480 
5481 	stp = LIST_FIRST(&lfp->lf_deleg);
5482 	while (stp != LIST_END(&lfp->lf_deleg)) {
5483 		nstp = LIST_NEXT(stp, ls_file);
5484 		if (stp->ls_clp != clp) {
5485 			ret = nfsrv_delegconflict(stp, haslockp, p, vp);
5486 			if (ret) {
5487 				/*
5488 				 * nfsrv_delegconflict() unlocks state
5489 				 * when it returns non-zero.
5490 				 */
5491 				goto out;
5492 			}
5493 		}
5494 		stp = nstp;
5495 	}
5496 out:
5497 	NFSEXITCODE(ret);
5498 	return (ret);
5499 }
5500 
5501 /*
5502  * There are certain operations that, when being done outside of NFSv4,
5503  * require that any NFSv4 delegation for the file be recalled.
5504  * This function is to be called for those cases:
5505  * VOP_RENAME() - When a delegation is being recalled for any reason,
5506  *	the client may have to do Opens against the server, using the file's
5507  *	final component name. If the file has been renamed on the server,
5508  *	that component name will be incorrect and the Open will fail.
5509  * VOP_REMOVE() - Theoretically, a client could Open a file after it has
5510  *	been removed on the server, if there is a delegation issued to
5511  *	that client for the file. I say "theoretically" since clients
5512  *	normally do an Access Op before the Open and that Access Op will
5513  *	fail with ESTALE. Note that NFSv2 and 3 don't even do Opens, so
5514  *	they will detect the file's removal in the same manner. (There is
5515  *	one case where RFC3530 allows a client to do an Open without first
5516  *	doing an Access Op, which is passage of a check against the ACE
5517  *	returned with a Write delegation, but current practice is to ignore
5518  *	the ACE and always do an Access Op.)
5519  *	Since the functions can only be called with an unlocked vnode, this
5520  *	can't be done at this time.
5521  * VOP_ADVLOCK() - When a client holds a delegation, it can issue byte range
5522  *	locks locally in the client, which are not visible to the server. To
5523  *	deal with this, issuing of delegations for a vnode must be disabled
5524  *	and all delegations for the vnode recalled. This is done via the
5525  *	second function, using the VV_DISABLEDELEG vflag on the vnode.
5526  */
5527 APPLESTATIC void
5528 nfsd_recalldelegation(vnode_t vp, NFSPROC_T *p)
5529 {
5530 	time_t starttime;
5531 	int error;
5532 
5533 	/*
5534 	 * First, check to see if the server is currently running and it has
5535 	 * been called for a regular file when issuing delegations.
5536 	 */
5537 	if (newnfs_numnfsd == 0 || vp->v_type != VREG ||
5538 	    nfsrv_issuedelegs == 0)
5539 		return;
5540 
5541 	KASSERT((NFSVOPISLOCKED(vp) != LK_EXCLUSIVE), ("vp %p is locked", vp));
5542 	/*
5543 	 * First, get a reference on the nfsv4rootfs_lock so that an
5544 	 * exclusive lock cannot be acquired by another thread.
5545 	 */
5546 	NFSLOCKV4ROOTMUTEX();
5547 	nfsv4_getref(&nfsv4rootfs_lock, NULL, NFSV4ROOTLOCKMUTEXPTR, NULL);
5548 	NFSUNLOCKV4ROOTMUTEX();
5549 
5550 	/*
5551 	 * Now, call nfsrv_checkremove() in a loop while it returns
5552 	 * NFSERR_DELAY. Return upon any other error or when timed out.
5553 	 */
5554 	starttime = NFSD_MONOSEC;
5555 	do {
5556 		if (NFSVOPLOCK(vp, LK_EXCLUSIVE) == 0) {
5557 			error = nfsrv_checkremove(vp, 0, p);
5558 			NFSVOPUNLOCK(vp, 0);
5559 		} else
5560 			error = EPERM;
5561 		if (error == NFSERR_DELAY) {
5562 			if (NFSD_MONOSEC - starttime > NFS_REMOVETIMEO)
5563 				break;
5564 			/* Sleep for a short period of time */
5565 			(void) nfs_catnap(PZERO, 0, "nfsremove");
5566 		}
5567 	} while (error == NFSERR_DELAY);
5568 	NFSLOCKV4ROOTMUTEX();
5569 	nfsv4_relref(&nfsv4rootfs_lock);
5570 	NFSUNLOCKV4ROOTMUTEX();
5571 }
5572 
5573 APPLESTATIC void
5574 nfsd_disabledelegation(vnode_t vp, NFSPROC_T *p)
5575 {
5576 
5577 #ifdef VV_DISABLEDELEG
5578 	/*
5579 	 * First, flag issuance of delegations disabled.
5580 	 */
5581 	atomic_set_long(&vp->v_vflag, VV_DISABLEDELEG);
5582 #endif
5583 
5584 	/*
5585 	 * Then call nfsd_recalldelegation() to get rid of all extant
5586 	 * delegations.
5587 	 */
5588 	nfsd_recalldelegation(vp, p);
5589 }
5590 
5591 /*
5592  * Check for conflicting locks, etc. and then get rid of delegations.
5593  * (At one point I thought that I should get rid of delegations for any
5594  *  Setattr, since it could potentially disallow the I/O op (read or write)
5595  *  allowed by the delegation. However, Setattr Ops that aren't changing
5596  *  the size get a stateid of all 0s, so you can't tell if it is a delegation
5597  *  for the same client or a different one, so I decided to only get rid
5598  *  of delegations for other clients when the size is being changed.)
5599  * In general, a Setattr can disable NFS I/O Ops that are outstanding, such
5600  * as Write backs, even if there is no delegation, so it really isn't any
5601  * different?)
5602  */
5603 APPLESTATIC int
5604 nfsrv_checksetattr(vnode_t vp, struct nfsrv_descript *nd,
5605     nfsv4stateid_t *stateidp, struct nfsvattr *nvap, nfsattrbit_t *attrbitp,
5606     struct nfsexstuff *exp, NFSPROC_T *p)
5607 {
5608 	struct nfsstate st, *stp = &st;
5609 	struct nfslock lo, *lop = &lo;
5610 	int error = 0;
5611 	nfsquad_t clientid;
5612 
5613 	if (NFSISSET_ATTRBIT(attrbitp, NFSATTRBIT_SIZE)) {
5614 		stp->ls_flags = (NFSLCK_CHECK | NFSLCK_WRITEACCESS);
5615 		lop->lo_first = nvap->na_size;
5616 	} else {
5617 		stp->ls_flags = 0;
5618 		lop->lo_first = 0;
5619 	}
5620 	if (NFSISSET_ATTRBIT(attrbitp, NFSATTRBIT_OWNER) ||
5621 	    NFSISSET_ATTRBIT(attrbitp, NFSATTRBIT_OWNERGROUP) ||
5622 	    NFSISSET_ATTRBIT(attrbitp, NFSATTRBIT_MODE) ||
5623 	    NFSISSET_ATTRBIT(attrbitp, NFSATTRBIT_ACL))
5624 		stp->ls_flags |= NFSLCK_SETATTR;
5625 	if (stp->ls_flags == 0)
5626 		goto out;
5627 	lop->lo_end = NFS64BITSSET;
5628 	lop->lo_flags = NFSLCK_WRITE;
5629 	stp->ls_ownerlen = 0;
5630 	stp->ls_op = NULL;
5631 	stp->ls_uid = nd->nd_cred->cr_uid;
5632 	stp->ls_stateid.seqid = stateidp->seqid;
5633 	clientid.lval[0] = stp->ls_stateid.other[0] = stateidp->other[0];
5634 	clientid.lval[1] = stp->ls_stateid.other[1] = stateidp->other[1];
5635 	stp->ls_stateid.other[2] = stateidp->other[2];
5636 	error = nfsrv_lockctrl(vp, &stp, &lop, NULL, clientid,
5637 	    stateidp, exp, nd, p);
5638 
5639 out:
5640 	NFSEXITCODE2(error, nd);
5641 	return (error);
5642 }
5643 
5644 /*
5645  * Check for a write delegation and do a CBGETATTR if there is one, updating
5646  * the attributes, as required.
5647  * Should I return an error if I can't get the attributes? (For now, I'll
5648  * just return ok.
5649  */
5650 APPLESTATIC int
5651 nfsrv_checkgetattr(struct nfsrv_descript *nd, vnode_t vp,
5652     struct nfsvattr *nvap, nfsattrbit_t *attrbitp, NFSPROC_T *p)
5653 {
5654 	struct nfsstate *stp;
5655 	struct nfslockfile *lfp;
5656 	struct nfsclient *clp;
5657 	struct nfsvattr nva;
5658 	fhandle_t nfh;
5659 	int error = 0;
5660 	nfsattrbit_t cbbits;
5661 	u_quad_t delegfilerev;
5662 
5663 	NFSCBGETATTR_ATTRBIT(attrbitp, &cbbits);
5664 	if (!NFSNONZERO_ATTRBIT(&cbbits))
5665 		goto out;
5666 	if (nfsrv_writedelegcnt == 0)
5667 		goto out;
5668 
5669 	/*
5670 	 * Get the lock file structure.
5671 	 * (A return of -1 means no associated state, so return ok.)
5672 	 */
5673 	error = nfsrv_getlockfh(vp, NFSLCK_CHECK, NULL, &nfh, p);
5674 	NFSLOCKSTATE();
5675 	if (!error)
5676 		error = nfsrv_getlockfile(NFSLCK_CHECK, NULL, &lfp, &nfh, 0);
5677 	if (error) {
5678 		NFSUNLOCKSTATE();
5679 		if (error == -1)
5680 			error = 0;
5681 		goto out;
5682 	}
5683 
5684 	/*
5685 	 * Now, look for a write delegation.
5686 	 */
5687 	LIST_FOREACH(stp, &lfp->lf_deleg, ls_file) {
5688 		if (stp->ls_flags & NFSLCK_DELEGWRITE)
5689 			break;
5690 	}
5691 	if (stp == LIST_END(&lfp->lf_deleg)) {
5692 		NFSUNLOCKSTATE();
5693 		goto out;
5694 	}
5695 	clp = stp->ls_clp;
5696 	delegfilerev = stp->ls_filerev;
5697 
5698 	/*
5699 	 * If the Write delegation was issued as a part of this Compound RPC
5700 	 * or if we have an Implied Clientid (used in a previous Op in this
5701 	 * compound) and it is the client the delegation was issued to,
5702 	 * just return ok.
5703 	 * I also assume that it is from the same client iff the network
5704 	 * host IP address is the same as the callback address. (Not
5705 	 * exactly correct by the RFC, but avoids a lot of Getattr
5706 	 * callbacks.)
5707 	 */
5708 	if (nd->nd_compref == stp->ls_compref ||
5709 	    ((nd->nd_flag & ND_IMPLIEDCLID) &&
5710 	     clp->lc_clientid.qval == nd->nd_clientid.qval) ||
5711 	     nfsaddr2_match(clp->lc_req.nr_nam, nd->nd_nam)) {
5712 		NFSUNLOCKSTATE();
5713 		goto out;
5714 	}
5715 
5716 	/*
5717 	 * We are now done with the delegation state structure,
5718 	 * so the statelock can be released and we can now tsleep().
5719 	 */
5720 
5721 	/*
5722 	 * Now, we must do the CB Getattr callback, to see if Change or Size
5723 	 * has changed.
5724 	 */
5725 	if (clp->lc_expiry >= NFSD_MONOSEC) {
5726 		NFSUNLOCKSTATE();
5727 		NFSVNO_ATTRINIT(&nva);
5728 		nva.na_filerev = NFS64BITSSET;
5729 		error = nfsrv_docallback(clp, NFSV4OP_CBGETATTR, NULL,
5730 		    0, &nfh, &nva, &cbbits, 0, p);
5731 		if (!error) {
5732 			if ((nva.na_filerev != NFS64BITSSET &&
5733 			    nva.na_filerev > delegfilerev) ||
5734 			    (NFSVNO_ISSETSIZE(&nva) &&
5735 			     nva.na_size != nvap->na_size)) {
5736 				error = nfsvno_updfilerev(vp, nvap, nd, p);
5737 				if (NFSVNO_ISSETSIZE(&nva))
5738 					nvap->na_size = nva.na_size;
5739 			}
5740 		} else
5741 			error = 0;	/* Ignore callback errors for now. */
5742 	} else {
5743 		NFSUNLOCKSTATE();
5744 	}
5745 
5746 out:
5747 	NFSEXITCODE2(error, nd);
5748 	return (error);
5749 }
5750 
5751 /*
5752  * This function looks for openowners that haven't had any opens for
5753  * a while and throws them away. Called by an nfsd when NFSNSF_NOOPENS
5754  * is set.
5755  */
5756 APPLESTATIC void
5757 nfsrv_throwawayopens(NFSPROC_T *p)
5758 {
5759 	struct nfsclient *clp, *nclp;
5760 	struct nfsstate *stp, *nstp;
5761 	int i;
5762 
5763 	NFSLOCKSTATE();
5764 	nfsrv_stablefirst.nsf_flags &= ~NFSNSF_NOOPENS;
5765 	/*
5766 	 * For each client...
5767 	 */
5768 	for (i = 0; i < nfsrv_clienthashsize; i++) {
5769 	    LIST_FOREACH_SAFE(clp, &nfsclienthash[i], lc_hash, nclp) {
5770 		LIST_FOREACH_SAFE(stp, &clp->lc_open, ls_list, nstp) {
5771 			if (LIST_EMPTY(&stp->ls_open) &&
5772 			    (stp->ls_noopens > NFSNOOPEN ||
5773 			     (nfsrv_openpluslock * 2) >
5774 			     nfsrv_v4statelimit))
5775 				nfsrv_freeopenowner(stp, 0, p);
5776 		}
5777 	    }
5778 	}
5779 	NFSUNLOCKSTATE();
5780 }
5781 
5782 /*
5783  * This function checks to see if the credentials are the same.
5784  * Returns 1 for not same, 0 otherwise.
5785  */
5786 static int
5787 nfsrv_notsamecredname(struct nfsrv_descript *nd, struct nfsclient *clp)
5788 {
5789 
5790 	if (nd->nd_flag & ND_GSS) {
5791 		if (!(clp->lc_flags & LCL_GSS))
5792 			return (1);
5793 		if (clp->lc_flags & LCL_NAME) {
5794 			if (nd->nd_princlen != clp->lc_namelen ||
5795 			    NFSBCMP(nd->nd_principal, clp->lc_name,
5796 				clp->lc_namelen))
5797 				return (1);
5798 			else
5799 				return (0);
5800 		}
5801 		if (nd->nd_cred->cr_uid == clp->lc_uid)
5802 			return (0);
5803 		else
5804 			return (1);
5805 	} else if (clp->lc_flags & LCL_GSS)
5806 		return (1);
5807 	/*
5808 	 * For AUTH_SYS, allow the same uid or root. (This is underspecified
5809 	 * in RFC3530, which talks about principals, but doesn't say anything
5810 	 * about uids for AUTH_SYS.)
5811 	 */
5812 	if (nd->nd_cred->cr_uid == clp->lc_uid || nd->nd_cred->cr_uid == 0)
5813 		return (0);
5814 	else
5815 		return (1);
5816 }
5817 
5818 /*
5819  * Calculate the lease expiry time.
5820  */
5821 static time_t
5822 nfsrv_leaseexpiry(void)
5823 {
5824 
5825 	if (nfsrv_stablefirst.nsf_eograce > NFSD_MONOSEC)
5826 		return (NFSD_MONOSEC + 2 * (nfsrv_lease + NFSRV_LEASEDELTA));
5827 	return (NFSD_MONOSEC + nfsrv_lease + NFSRV_LEASEDELTA);
5828 }
5829 
5830 /*
5831  * Delay the delegation timeout as far as ls_delegtimelimit, as required.
5832  */
5833 static void
5834 nfsrv_delaydelegtimeout(struct nfsstate *stp)
5835 {
5836 
5837 	if ((stp->ls_flags & NFSLCK_DELEGRECALL) == 0)
5838 		return;
5839 
5840 	if ((stp->ls_delegtime + 15) > NFSD_MONOSEC &&
5841 	    stp->ls_delegtime < stp->ls_delegtimelimit) {
5842 		stp->ls_delegtime += nfsrv_lease;
5843 		if (stp->ls_delegtime > stp->ls_delegtimelimit)
5844 			stp->ls_delegtime = stp->ls_delegtimelimit;
5845 	}
5846 }
5847 
5848 /*
5849  * This function checks to see if there is any other state associated
5850  * with the openowner for this Open.
5851  * It returns 1 if there is no other state, 0 otherwise.
5852  */
5853 static int
5854 nfsrv_nootherstate(struct nfsstate *stp)
5855 {
5856 	struct nfsstate *tstp;
5857 
5858 	LIST_FOREACH(tstp, &stp->ls_openowner->ls_open, ls_list) {
5859 		if (tstp != stp || !LIST_EMPTY(&tstp->ls_lock))
5860 			return (0);
5861 	}
5862 	return (1);
5863 }
5864 
5865 /*
5866  * Create a list of lock deltas (changes to local byte range locking
5867  * that can be rolled back using the list) and apply the changes via
5868  * nfsvno_advlock(). Optionally, lock the list. It is expected that either
5869  * the rollback or update function will be called after this.
5870  * It returns an error (and rolls back, as required), if any nfsvno_advlock()
5871  * call fails. If it returns an error, it will unlock the list.
5872  */
5873 static int
5874 nfsrv_locallock(vnode_t vp, struct nfslockfile *lfp, int flags,
5875     uint64_t first, uint64_t end, struct nfslockconflict *cfp, NFSPROC_T *p)
5876 {
5877 	struct nfslock *lop, *nlop;
5878 	int error = 0;
5879 
5880 	/* Loop through the list of locks. */
5881 	lop = LIST_FIRST(&lfp->lf_locallock);
5882 	while (first < end && lop != NULL) {
5883 		nlop = LIST_NEXT(lop, lo_lckowner);
5884 		if (first >= lop->lo_end) {
5885 			/* not there yet */
5886 			lop = nlop;
5887 		} else if (first < lop->lo_first) {
5888 			/* new one starts before entry in list */
5889 			if (end <= lop->lo_first) {
5890 				/* no overlap between old and new */
5891 				error = nfsrv_dolocal(vp, lfp, flags,
5892 				    NFSLCK_UNLOCK, first, end, cfp, p);
5893 				if (error != 0)
5894 					break;
5895 				first = end;
5896 			} else {
5897 				/* handle fragment overlapped with new one */
5898 				error = nfsrv_dolocal(vp, lfp, flags,
5899 				    NFSLCK_UNLOCK, first, lop->lo_first, cfp,
5900 				    p);
5901 				if (error != 0)
5902 					break;
5903 				first = lop->lo_first;
5904 			}
5905 		} else {
5906 			/* new one overlaps this entry in list */
5907 			if (end <= lop->lo_end) {
5908 				/* overlaps all of new one */
5909 				error = nfsrv_dolocal(vp, lfp, flags,
5910 				    lop->lo_flags, first, end, cfp, p);
5911 				if (error != 0)
5912 					break;
5913 				first = end;
5914 			} else {
5915 				/* handle fragment overlapped with new one */
5916 				error = nfsrv_dolocal(vp, lfp, flags,
5917 				    lop->lo_flags, first, lop->lo_end, cfp, p);
5918 				if (error != 0)
5919 					break;
5920 				first = lop->lo_end;
5921 				lop = nlop;
5922 			}
5923 		}
5924 	}
5925 	if (first < end && error == 0)
5926 		/* handle fragment past end of list */
5927 		error = nfsrv_dolocal(vp, lfp, flags, NFSLCK_UNLOCK, first,
5928 		    end, cfp, p);
5929 
5930 	NFSEXITCODE(error);
5931 	return (error);
5932 }
5933 
5934 /*
5935  * Local lock unlock. Unlock all byte ranges that are no longer locked
5936  * by NFSv4. To do this, unlock any subranges of first-->end that
5937  * do not overlap with the byte ranges of any lock in the lfp->lf_lock
5938  * list. This list has all locks for the file held by other
5939  * <clientid, lockowner> tuples. The list is ordered by increasing
5940  * lo_first value, but may have entries that overlap each other, for
5941  * the case of read locks.
5942  */
5943 static void
5944 nfsrv_localunlock(vnode_t vp, struct nfslockfile *lfp, uint64_t init_first,
5945     uint64_t init_end, NFSPROC_T *p)
5946 {
5947 	struct nfslock *lop;
5948 	uint64_t first, end, prevfirst __unused;
5949 
5950 	first = init_first;
5951 	end = init_end;
5952 	while (first < init_end) {
5953 		/* Loop through all nfs locks, adjusting first and end */
5954 		prevfirst = 0;
5955 		LIST_FOREACH(lop, &lfp->lf_lock, lo_lckfile) {
5956 			KASSERT(prevfirst <= lop->lo_first,
5957 			    ("nfsv4 locks out of order"));
5958 			KASSERT(lop->lo_first < lop->lo_end,
5959 			    ("nfsv4 bogus lock"));
5960 			prevfirst = lop->lo_first;
5961 			if (first >= lop->lo_first &&
5962 			    first < lop->lo_end)
5963 				/*
5964 				 * Overlaps with initial part, so trim
5965 				 * off that initial part by moving first past
5966 				 * it.
5967 				 */
5968 				first = lop->lo_end;
5969 			else if (end > lop->lo_first &&
5970 			    lop->lo_first > first) {
5971 				/*
5972 				 * This lock defines the end of the
5973 				 * segment to unlock, so set end to the
5974 				 * start of it and break out of the loop.
5975 				 */
5976 				end = lop->lo_first;
5977 				break;
5978 			}
5979 			if (first >= end)
5980 				/*
5981 				 * There is no segment left to do, so
5982 				 * break out of this loop and then exit
5983 				 * the outer while() since first will be set
5984 				 * to end, which must equal init_end here.
5985 				 */
5986 				break;
5987 		}
5988 		if (first < end) {
5989 			/* Unlock this segment */
5990 			(void) nfsrv_dolocal(vp, lfp, NFSLCK_UNLOCK,
5991 			    NFSLCK_READ, first, end, NULL, p);
5992 			nfsrv_locallock_commit(lfp, NFSLCK_UNLOCK,
5993 			    first, end);
5994 		}
5995 		/*
5996 		 * Now move past this segment and look for any further
5997 		 * segment in the range, if there is one.
5998 		 */
5999 		first = end;
6000 		end = init_end;
6001 	}
6002 }
6003 
6004 /*
6005  * Do the local lock operation and update the rollback list, as required.
6006  * Perform the rollback and return the error if nfsvno_advlock() fails.
6007  */
6008 static int
6009 nfsrv_dolocal(vnode_t vp, struct nfslockfile *lfp, int flags, int oldflags,
6010     uint64_t first, uint64_t end, struct nfslockconflict *cfp, NFSPROC_T *p)
6011 {
6012 	struct nfsrollback *rlp;
6013 	int error = 0, ltype, oldltype;
6014 
6015 	if (flags & NFSLCK_WRITE)
6016 		ltype = F_WRLCK;
6017 	else if (flags & NFSLCK_READ)
6018 		ltype = F_RDLCK;
6019 	else
6020 		ltype = F_UNLCK;
6021 	if (oldflags & NFSLCK_WRITE)
6022 		oldltype = F_WRLCK;
6023 	else if (oldflags & NFSLCK_READ)
6024 		oldltype = F_RDLCK;
6025 	else
6026 		oldltype = F_UNLCK;
6027 	if (ltype == oldltype || (oldltype == F_WRLCK && ltype == F_RDLCK))
6028 		/* nothing to do */
6029 		goto out;
6030 	error = nfsvno_advlock(vp, ltype, first, end, p);
6031 	if (error != 0) {
6032 		if (cfp != NULL) {
6033 			cfp->cl_clientid.lval[0] = 0;
6034 			cfp->cl_clientid.lval[1] = 0;
6035 			cfp->cl_first = 0;
6036 			cfp->cl_end = NFS64BITSSET;
6037 			cfp->cl_flags = NFSLCK_WRITE;
6038 			cfp->cl_ownerlen = 5;
6039 			NFSBCOPY("LOCAL", cfp->cl_owner, 5);
6040 		}
6041 		nfsrv_locallock_rollback(vp, lfp, p);
6042 	} else if (ltype != F_UNLCK) {
6043 		rlp = malloc(sizeof (struct nfsrollback), M_NFSDROLLBACK,
6044 		    M_WAITOK);
6045 		rlp->rlck_first = first;
6046 		rlp->rlck_end = end;
6047 		rlp->rlck_type = oldltype;
6048 		LIST_INSERT_HEAD(&lfp->lf_rollback, rlp, rlck_list);
6049 	}
6050 
6051 out:
6052 	NFSEXITCODE(error);
6053 	return (error);
6054 }
6055 
6056 /*
6057  * Roll back local lock changes and free up the rollback list.
6058  */
6059 static void
6060 nfsrv_locallock_rollback(vnode_t vp, struct nfslockfile *lfp, NFSPROC_T *p)
6061 {
6062 	struct nfsrollback *rlp, *nrlp;
6063 
6064 	LIST_FOREACH_SAFE(rlp, &lfp->lf_rollback, rlck_list, nrlp) {
6065 		(void) nfsvno_advlock(vp, rlp->rlck_type, rlp->rlck_first,
6066 		    rlp->rlck_end, p);
6067 		free(rlp, M_NFSDROLLBACK);
6068 	}
6069 	LIST_INIT(&lfp->lf_rollback);
6070 }
6071 
6072 /*
6073  * Update local lock list and delete rollback list (ie now committed to the
6074  * local locks). Most of the work is done by the internal function.
6075  */
6076 static void
6077 nfsrv_locallock_commit(struct nfslockfile *lfp, int flags, uint64_t first,
6078     uint64_t end)
6079 {
6080 	struct nfsrollback *rlp, *nrlp;
6081 	struct nfslock *new_lop, *other_lop;
6082 
6083 	new_lop = malloc(sizeof (struct nfslock), M_NFSDLOCK, M_WAITOK);
6084 	if (flags & (NFSLCK_READ | NFSLCK_WRITE))
6085 		other_lop = malloc(sizeof (struct nfslock), M_NFSDLOCK,
6086 		    M_WAITOK);
6087 	else
6088 		other_lop = NULL;
6089 	new_lop->lo_flags = flags;
6090 	new_lop->lo_first = first;
6091 	new_lop->lo_end = end;
6092 	nfsrv_updatelock(NULL, &new_lop, &other_lop, lfp);
6093 	if (new_lop != NULL)
6094 		free(new_lop, M_NFSDLOCK);
6095 	if (other_lop != NULL)
6096 		free(other_lop, M_NFSDLOCK);
6097 
6098 	/* and get rid of the rollback list */
6099 	LIST_FOREACH_SAFE(rlp, &lfp->lf_rollback, rlck_list, nrlp)
6100 		free(rlp, M_NFSDROLLBACK);
6101 	LIST_INIT(&lfp->lf_rollback);
6102 }
6103 
6104 /*
6105  * Lock the struct nfslockfile for local lock updating.
6106  */
6107 static void
6108 nfsrv_locklf(struct nfslockfile *lfp)
6109 {
6110 	int gotlock;
6111 
6112 	/* lf_usecount ensures *lfp won't be free'd */
6113 	lfp->lf_usecount++;
6114 	do {
6115 		gotlock = nfsv4_lock(&lfp->lf_locallock_lck, 1, NULL,
6116 		    NFSSTATEMUTEXPTR, NULL);
6117 	} while (gotlock == 0);
6118 	lfp->lf_usecount--;
6119 }
6120 
6121 /*
6122  * Unlock the struct nfslockfile after local lock updating.
6123  */
6124 static void
6125 nfsrv_unlocklf(struct nfslockfile *lfp)
6126 {
6127 
6128 	nfsv4_unlock(&lfp->lf_locallock_lck, 0);
6129 }
6130 
6131 /*
6132  * Clear out all state for the NFSv4 server.
6133  * Must be called by a thread that can sleep when no nfsds are running.
6134  */
6135 void
6136 nfsrv_throwawayallstate(NFSPROC_T *p)
6137 {
6138 	struct nfsclient *clp, *nclp;
6139 	struct nfslockfile *lfp, *nlfp;
6140 	int i;
6141 
6142 	/*
6143 	 * For each client, clean out the state and then free the structure.
6144 	 */
6145 	for (i = 0; i < nfsrv_clienthashsize; i++) {
6146 		LIST_FOREACH_SAFE(clp, &nfsclienthash[i], lc_hash, nclp) {
6147 			nfsrv_cleanclient(clp, p);
6148 			nfsrv_freedeleglist(&clp->lc_deleg);
6149 			nfsrv_freedeleglist(&clp->lc_olddeleg);
6150 			free(clp->lc_stateid, M_NFSDCLIENT);
6151 			free(clp, M_NFSDCLIENT);
6152 		}
6153 	}
6154 
6155 	/*
6156 	 * Also, free up any remaining lock file structures.
6157 	 */
6158 	for (i = 0; i < nfsrv_lockhashsize; i++) {
6159 		LIST_FOREACH_SAFE(lfp, &nfslockhash[i], lf_hash, nlfp) {
6160 			printf("nfsd unload: fnd a lock file struct\n");
6161 			nfsrv_freenfslockfile(lfp);
6162 		}
6163 	}
6164 
6165 	/* And get rid of the deviceid structures and layouts. */
6166 	nfsrv_freealllayoutsanddevids();
6167 }
6168 
6169 /*
6170  * Check the sequence# for the session and slot provided as an argument.
6171  * Also, renew the lease if the session will return NFS_OK.
6172  */
6173 int
6174 nfsrv_checksequence(struct nfsrv_descript *nd, uint32_t sequenceid,
6175     uint32_t *highest_slotidp, uint32_t *target_highest_slotidp, int cache_this,
6176     uint32_t *sflagsp, NFSPROC_T *p)
6177 {
6178 	struct nfsdsession *sep;
6179 	struct nfssessionhash *shp;
6180 	int error;
6181 	SVCXPRT *savxprt;
6182 
6183 	shp = NFSSESSIONHASH(nd->nd_sessionid);
6184 	NFSLOCKSESSION(shp);
6185 	sep = nfsrv_findsession(nd->nd_sessionid);
6186 	if (sep == NULL) {
6187 		NFSUNLOCKSESSION(shp);
6188 		return (NFSERR_BADSESSION);
6189 	}
6190 	error = nfsv4_seqsession(sequenceid, nd->nd_slotid, *highest_slotidp,
6191 	    sep->sess_slots, NULL, NFSV4_SLOTS - 1);
6192 	if (error != 0) {
6193 		NFSUNLOCKSESSION(shp);
6194 		return (error);
6195 	}
6196 	if (cache_this != 0)
6197 		nd->nd_flag |= ND_SAVEREPLY;
6198 	/* Renew the lease. */
6199 	sep->sess_clp->lc_expiry = nfsrv_leaseexpiry();
6200 	nd->nd_clientid.qval = sep->sess_clp->lc_clientid.qval;
6201 	nd->nd_flag |= ND_IMPLIEDCLID;
6202 
6203 	/*
6204 	 * If this session handles the backchannel, save the nd_xprt for this
6205 	 * RPC, since this is the one being used.
6206 	 * RFC-5661 specifies that the fore channel will be implicitly
6207 	 * bound by a Sequence operation.  However, since some NFSv4.1 clients
6208 	 * erroneously assumed that the back channel would be implicitly
6209 	 * bound as well, do the implicit binding unless a
6210 	 * BindConnectiontoSession has already been done on the session.
6211 	 */
6212 	if (sep->sess_clp->lc_req.nr_client != NULL &&
6213 	    sep->sess_cbsess.nfsess_xprt != nd->nd_xprt &&
6214 	    (sep->sess_crflags & NFSV4CRSESS_CONNBACKCHAN) != 0 &&
6215 	    (sep->sess_clp->lc_flags & LCL_DONEBINDCONN) == 0) {
6216 		NFSD_DEBUG(2,
6217 		    "nfsrv_checksequence: implicit back channel bind\n");
6218 		savxprt = sep->sess_cbsess.nfsess_xprt;
6219 		SVC_ACQUIRE(nd->nd_xprt);
6220 		nd->nd_xprt->xp_p2 =
6221 		    sep->sess_clp->lc_req.nr_client->cl_private;
6222 		nd->nd_xprt->xp_idletimeout = 0;	/* Disable timeout. */
6223 		sep->sess_cbsess.nfsess_xprt = nd->nd_xprt;
6224 		if (savxprt != NULL)
6225 			SVC_RELEASE(savxprt);
6226 	}
6227 
6228 	*sflagsp = 0;
6229 	if (sep->sess_clp->lc_req.nr_client == NULL)
6230 		*sflagsp |= NFSV4SEQ_CBPATHDOWN;
6231 	NFSUNLOCKSESSION(shp);
6232 	if (error == NFSERR_EXPIRED) {
6233 		*sflagsp |= NFSV4SEQ_EXPIREDALLSTATEREVOKED;
6234 		error = 0;
6235 	} else if (error == NFSERR_ADMINREVOKED) {
6236 		*sflagsp |= NFSV4SEQ_ADMINSTATEREVOKED;
6237 		error = 0;
6238 	}
6239 	*highest_slotidp = *target_highest_slotidp = NFSV4_SLOTS - 1;
6240 	return (0);
6241 }
6242 
6243 /*
6244  * Check/set reclaim complete for this session/clientid.
6245  */
6246 int
6247 nfsrv_checkreclaimcomplete(struct nfsrv_descript *nd, int onefs)
6248 {
6249 	struct nfsdsession *sep;
6250 	struct nfssessionhash *shp;
6251 	int error = 0;
6252 
6253 	shp = NFSSESSIONHASH(nd->nd_sessionid);
6254 	NFSLOCKSTATE();
6255 	NFSLOCKSESSION(shp);
6256 	sep = nfsrv_findsession(nd->nd_sessionid);
6257 	if (sep == NULL) {
6258 		NFSUNLOCKSESSION(shp);
6259 		NFSUNLOCKSTATE();
6260 		return (NFSERR_BADSESSION);
6261 	}
6262 
6263 	if (onefs != 0)
6264 		sep->sess_clp->lc_flags |= LCL_RECLAIMONEFS;
6265 		/* Check to see if reclaim complete has already happened. */
6266 	else if ((sep->sess_clp->lc_flags & LCL_RECLAIMCOMPLETE) != 0)
6267 		error = NFSERR_COMPLETEALREADY;
6268 	else {
6269 		sep->sess_clp->lc_flags |= LCL_RECLAIMCOMPLETE;
6270 		nfsrv_markreclaim(sep->sess_clp);
6271 	}
6272 	NFSUNLOCKSESSION(shp);
6273 	NFSUNLOCKSTATE();
6274 	return (error);
6275 }
6276 
6277 /*
6278  * Cache the reply in a session slot.
6279  */
6280 void
6281 nfsrv_cache_session(uint8_t *sessionid, uint32_t slotid, int repstat,
6282    struct mbuf **m)
6283 {
6284 	struct nfsdsession *sep;
6285 	struct nfssessionhash *shp;
6286 
6287 	shp = NFSSESSIONHASH(sessionid);
6288 	NFSLOCKSESSION(shp);
6289 	sep = nfsrv_findsession(sessionid);
6290 	if (sep == NULL) {
6291 		NFSUNLOCKSESSION(shp);
6292 		printf("nfsrv_cache_session: no session\n");
6293 		m_freem(*m);
6294 		return;
6295 	}
6296 	nfsv4_seqsess_cacherep(slotid, sep->sess_slots, repstat, m);
6297 	NFSUNLOCKSESSION(shp);
6298 }
6299 
6300 /*
6301  * Search for a session that matches the sessionid.
6302  */
6303 static struct nfsdsession *
6304 nfsrv_findsession(uint8_t *sessionid)
6305 {
6306 	struct nfsdsession *sep;
6307 	struct nfssessionhash *shp;
6308 
6309 	shp = NFSSESSIONHASH(sessionid);
6310 	LIST_FOREACH(sep, &shp->list, sess_hash) {
6311 		if (!NFSBCMP(sessionid, sep->sess_sessionid, NFSX_V4SESSIONID))
6312 			break;
6313 	}
6314 	return (sep);
6315 }
6316 
6317 /*
6318  * Destroy a session.
6319  */
6320 int
6321 nfsrv_destroysession(struct nfsrv_descript *nd, uint8_t *sessionid)
6322 {
6323 	int error, igotlock, samesess;
6324 
6325 	samesess = 0;
6326 	if (!NFSBCMP(sessionid, nd->nd_sessionid, NFSX_V4SESSIONID) &&
6327 	    (nd->nd_flag & ND_HASSEQUENCE) != 0) {
6328 		samesess = 1;
6329 		if ((nd->nd_flag & ND_LASTOP) == 0)
6330 			return (NFSERR_BADSESSION);
6331 	}
6332 
6333 	/* Lock out other nfsd threads */
6334 	NFSLOCKV4ROOTMUTEX();
6335 	nfsv4_relref(&nfsv4rootfs_lock);
6336 	do {
6337 		igotlock = nfsv4_lock(&nfsv4rootfs_lock, 1, NULL,
6338 		    NFSV4ROOTLOCKMUTEXPTR, NULL);
6339 	} while (igotlock == 0);
6340 	NFSUNLOCKV4ROOTMUTEX();
6341 
6342 	error = nfsrv_freesession(NULL, sessionid);
6343 	if (error == 0 && samesess != 0)
6344 		nd->nd_flag &= ~ND_HASSEQUENCE;
6345 
6346 	NFSLOCKV4ROOTMUTEX();
6347 	nfsv4_unlock(&nfsv4rootfs_lock, 1);
6348 	NFSUNLOCKV4ROOTMUTEX();
6349 	return (error);
6350 }
6351 
6352 /*
6353  * Bind a connection to a session.
6354  * For now, only certain variants are supported, since the current session
6355  * structure can only handle a single backchannel entry, which will be
6356  * applied to all connections if it is set.
6357  */
6358 int
6359 nfsrv_bindconnsess(struct nfsrv_descript *nd, uint8_t *sessionid, int *foreaftp)
6360 {
6361 	struct nfssessionhash *shp;
6362 	struct nfsdsession *sep;
6363 	struct nfsclient *clp;
6364 	SVCXPRT *savxprt;
6365 	int error;
6366 
6367 	error = 0;
6368 	shp = NFSSESSIONHASH(sessionid);
6369 	NFSLOCKSTATE();
6370 	NFSLOCKSESSION(shp);
6371 	sep = nfsrv_findsession(sessionid);
6372 	if (sep != NULL) {
6373 		clp = sep->sess_clp;
6374 		if (*foreaftp == NFSCDFC4_BACK ||
6375 		    *foreaftp == NFSCDFC4_BACK_OR_BOTH ||
6376 		    *foreaftp == NFSCDFC4_FORE_OR_BOTH) {
6377 			/* Try to set up a backchannel. */
6378 			if (clp->lc_req.nr_client == NULL) {
6379 				NFSD_DEBUG(2, "nfsrv_bindconnsess: acquire "
6380 				    "backchannel\n");
6381 				clp->lc_req.nr_client = (struct __rpc_client *)
6382 				    clnt_bck_create(nd->nd_xprt->xp_socket,
6383 				    sep->sess_cbprogram, NFSV4_CBVERS);
6384 			}
6385 			if (clp->lc_req.nr_client != NULL) {
6386 				NFSD_DEBUG(2, "nfsrv_bindconnsess: set up "
6387 				    "backchannel\n");
6388 				savxprt = sep->sess_cbsess.nfsess_xprt;
6389 				SVC_ACQUIRE(nd->nd_xprt);
6390 				nd->nd_xprt->xp_p2 =
6391 				    clp->lc_req.nr_client->cl_private;
6392 				/* Disable idle timeout. */
6393 				nd->nd_xprt->xp_idletimeout = 0;
6394 				sep->sess_cbsess.nfsess_xprt = nd->nd_xprt;
6395 				if (savxprt != NULL)
6396 					SVC_RELEASE(savxprt);
6397 				sep->sess_crflags |= NFSV4CRSESS_CONNBACKCHAN;
6398 				clp->lc_flags |= LCL_DONEBINDCONN;
6399 				if (*foreaftp == NFSCDFS4_BACK)
6400 					*foreaftp = NFSCDFS4_BACK;
6401 				else
6402 					*foreaftp = NFSCDFS4_BOTH;
6403 			} else if (*foreaftp != NFSCDFC4_BACK) {
6404 				NFSD_DEBUG(2, "nfsrv_bindconnsess: can't set "
6405 				    "up backchannel\n");
6406 				sep->sess_crflags &= ~NFSV4CRSESS_CONNBACKCHAN;
6407 				clp->lc_flags |= LCL_DONEBINDCONN;
6408 				*foreaftp = NFSCDFS4_FORE;
6409 			} else {
6410 				error = NFSERR_NOTSUPP;
6411 				printf("nfsrv_bindconnsess: Can't add "
6412 				    "backchannel\n");
6413 			}
6414 		} else {
6415 			NFSD_DEBUG(2, "nfsrv_bindconnsess: Set forechannel\n");
6416 			clp->lc_flags |= LCL_DONEBINDCONN;
6417 			*foreaftp = NFSCDFS4_FORE;
6418 		}
6419 	} else
6420 		error = NFSERR_BADSESSION;
6421 	NFSUNLOCKSESSION(shp);
6422 	NFSUNLOCKSTATE();
6423 	return (error);
6424 }
6425 
6426 /*
6427  * Free up a session structure.
6428  */
6429 static int
6430 nfsrv_freesession(struct nfsdsession *sep, uint8_t *sessionid)
6431 {
6432 	struct nfssessionhash *shp;
6433 	int i;
6434 
6435 	NFSLOCKSTATE();
6436 	if (sep == NULL) {
6437 		shp = NFSSESSIONHASH(sessionid);
6438 		NFSLOCKSESSION(shp);
6439 		sep = nfsrv_findsession(sessionid);
6440 	} else {
6441 		shp = NFSSESSIONHASH(sep->sess_sessionid);
6442 		NFSLOCKSESSION(shp);
6443 	}
6444 	if (sep != NULL) {
6445 		sep->sess_refcnt--;
6446 		if (sep->sess_refcnt > 0) {
6447 			NFSUNLOCKSESSION(shp);
6448 			NFSUNLOCKSTATE();
6449 			return (NFSERR_BACKCHANBUSY);
6450 		}
6451 		LIST_REMOVE(sep, sess_hash);
6452 		LIST_REMOVE(sep, sess_list);
6453 	}
6454 	NFSUNLOCKSESSION(shp);
6455 	NFSUNLOCKSTATE();
6456 	if (sep == NULL)
6457 		return (NFSERR_BADSESSION);
6458 	for (i = 0; i < NFSV4_SLOTS; i++)
6459 		if (sep->sess_slots[i].nfssl_reply != NULL)
6460 			m_freem(sep->sess_slots[i].nfssl_reply);
6461 	if (sep->sess_cbsess.nfsess_xprt != NULL)
6462 		SVC_RELEASE(sep->sess_cbsess.nfsess_xprt);
6463 	free(sep, M_NFSDSESSION);
6464 	return (0);
6465 }
6466 
6467 /*
6468  * Free a stateid.
6469  * RFC5661 says that it should fail when there are associated opens, locks
6470  * or delegations. Since stateids represent opens, I don't see how you can
6471  * free an open stateid (it will be free'd when closed), so this function
6472  * only works for lock stateids (freeing the lock_owner) or delegations.
6473  */
6474 int
6475 nfsrv_freestateid(struct nfsrv_descript *nd, nfsv4stateid_t *stateidp,
6476     NFSPROC_T *p)
6477 {
6478 	struct nfsclient *clp;
6479 	struct nfsstate *stp;
6480 	int error;
6481 
6482 	NFSLOCKSTATE();
6483 	/*
6484 	 * Look up the stateid
6485 	 */
6486 	error = nfsrv_getclient((nfsquad_t)((u_quad_t)0), CLOPS_RENEW, &clp,
6487 	    NULL, (nfsquad_t)((u_quad_t)0), 0, nd, p);
6488 	if (error == 0) {
6489 		/* First, check for a delegation. */
6490 		LIST_FOREACH(stp, &clp->lc_deleg, ls_list) {
6491 			if (!NFSBCMP(stp->ls_stateid.other, stateidp->other,
6492 			    NFSX_STATEIDOTHER))
6493 				break;
6494 		}
6495 		if (stp != NULL) {
6496 			nfsrv_freedeleg(stp);
6497 			NFSUNLOCKSTATE();
6498 			return (error);
6499 		}
6500 	}
6501 	/* Not a delegation, try for a lock_owner. */
6502 	if (error == 0)
6503 		error = nfsrv_getstate(clp, stateidp, 0, &stp);
6504 	if (error == 0 && ((stp->ls_flags & (NFSLCK_OPEN | NFSLCK_DELEGREAD |
6505 	    NFSLCK_DELEGWRITE)) != 0 || (stp->ls_flags & NFSLCK_LOCK) == 0))
6506 		/* Not a lock_owner stateid. */
6507 		error = NFSERR_LOCKSHELD;
6508 	if (error == 0 && !LIST_EMPTY(&stp->ls_lock))
6509 		error = NFSERR_LOCKSHELD;
6510 	if (error == 0)
6511 		nfsrv_freelockowner(stp, NULL, 0, p);
6512 	NFSUNLOCKSTATE();
6513 	return (error);
6514 }
6515 
6516 /*
6517  * Test a stateid.
6518  */
6519 int
6520 nfsrv_teststateid(struct nfsrv_descript *nd, nfsv4stateid_t *stateidp,
6521     NFSPROC_T *p)
6522 {
6523 	struct nfsclient *clp;
6524 	struct nfsstate *stp;
6525 	int error;
6526 
6527 	NFSLOCKSTATE();
6528 	/*
6529 	 * Look up the stateid
6530 	 */
6531 	error = nfsrv_getclient((nfsquad_t)((u_quad_t)0), CLOPS_RENEW, &clp,
6532 	    NULL, (nfsquad_t)((u_quad_t)0), 0, nd, p);
6533 	if (error == 0)
6534 		error = nfsrv_getstate(clp, stateidp, 0, &stp);
6535 	if (error == 0 && stateidp->seqid != 0 &&
6536 	    SEQ_LT(stateidp->seqid, stp->ls_stateid.seqid))
6537 		error = NFSERR_OLDSTATEID;
6538 	NFSUNLOCKSTATE();
6539 	return (error);
6540 }
6541 
6542 /*
6543  * Generate the xdr for an NFSv4.1 CBSequence Operation.
6544  */
6545 static int
6546 nfsv4_setcbsequence(struct nfsrv_descript *nd, struct nfsclient *clp,
6547     int dont_replycache, struct nfsdsession **sepp)
6548 {
6549 	struct nfsdsession *sep;
6550 	uint32_t *tl, slotseq = 0;
6551 	int maxslot, slotpos;
6552 	uint8_t sessionid[NFSX_V4SESSIONID];
6553 	int error;
6554 
6555 	error = nfsv4_getcbsession(clp, sepp);
6556 	if (error != 0)
6557 		return (error);
6558 	sep = *sepp;
6559 	(void)nfsv4_sequencelookup(NULL, &sep->sess_cbsess, &slotpos, &maxslot,
6560 	    &slotseq, sessionid);
6561 	KASSERT(maxslot >= 0, ("nfsv4_setcbsequence neg maxslot"));
6562 
6563 	/* Build the Sequence arguments. */
6564 	NFSM_BUILD(tl, uint32_t *, NFSX_V4SESSIONID + 5 * NFSX_UNSIGNED);
6565 	bcopy(sessionid, tl, NFSX_V4SESSIONID);
6566 	tl += NFSX_V4SESSIONID / NFSX_UNSIGNED;
6567 	nd->nd_slotseq = tl;
6568 	*tl++ = txdr_unsigned(slotseq);
6569 	*tl++ = txdr_unsigned(slotpos);
6570 	*tl++ = txdr_unsigned(maxslot);
6571 	if (dont_replycache == 0)
6572 		*tl++ = newnfs_true;
6573 	else
6574 		*tl++ = newnfs_false;
6575 	*tl = 0;			/* No referring call list, for now. */
6576 	nd->nd_flag |= ND_HASSEQUENCE;
6577 	return (0);
6578 }
6579 
6580 /*
6581  * Get a session for the callback.
6582  */
6583 static int
6584 nfsv4_getcbsession(struct nfsclient *clp, struct nfsdsession **sepp)
6585 {
6586 	struct nfsdsession *sep;
6587 
6588 	NFSLOCKSTATE();
6589 	LIST_FOREACH(sep, &clp->lc_session, sess_list) {
6590 		if ((sep->sess_crflags & NFSV4CRSESS_CONNBACKCHAN) != 0)
6591 			break;
6592 	}
6593 	if (sep == NULL) {
6594 		NFSUNLOCKSTATE();
6595 		return (NFSERR_BADSESSION);
6596 	}
6597 	sep->sess_refcnt++;
6598 	*sepp = sep;
6599 	NFSUNLOCKSTATE();
6600 	return (0);
6601 }
6602 
6603 /*
6604  * Free up all backchannel xprts.  This needs to be done when the nfsd threads
6605  * exit, since those transports will all be going away.
6606  * This is only called after all the nfsd threads are done performing RPCs,
6607  * so locking shouldn't be an issue.
6608  */
6609 APPLESTATIC void
6610 nfsrv_freeallbackchannel_xprts(void)
6611 {
6612 	struct nfsdsession *sep;
6613 	struct nfsclient *clp;
6614 	SVCXPRT *xprt;
6615 	int i;
6616 
6617 	for (i = 0; i < nfsrv_clienthashsize; i++) {
6618 		LIST_FOREACH(clp, &nfsclienthash[i], lc_hash) {
6619 			LIST_FOREACH(sep, &clp->lc_session, sess_list) {
6620 				xprt = sep->sess_cbsess.nfsess_xprt;
6621 				sep->sess_cbsess.nfsess_xprt = NULL;
6622 				if (xprt != NULL)
6623 					SVC_RELEASE(xprt);
6624 			}
6625 		}
6626 	}
6627 }
6628 
6629 /*
6630  * Do a layout commit.  Actually just call nfsrv_updatemdsattr().
6631  * I have no idea if the rest of these arguments will ever be useful?
6632  */
6633 int
6634 nfsrv_layoutcommit(struct nfsrv_descript *nd, vnode_t vp, int layouttype,
6635     int hasnewoff, uint64_t newoff, uint64_t offset, uint64_t len,
6636     int hasnewmtime, struct timespec *newmtimep, int reclaim,
6637     nfsv4stateid_t *stateidp, int maxcnt, char *layp, int *hasnewsizep,
6638     uint64_t *newsizep, struct ucred *cred, NFSPROC_T *p)
6639 {
6640 	struct nfsvattr na;
6641 	int error;
6642 
6643 	error = nfsrv_updatemdsattr(vp, &na, p);
6644 	if (error == 0) {
6645 		*hasnewsizep = 1;
6646 		*newsizep = na.na_size;
6647 	}
6648 	return (error);
6649 }
6650 
6651 /*
6652  * Try and get a layout.
6653  */
6654 int
6655 nfsrv_layoutget(struct nfsrv_descript *nd, vnode_t vp, struct nfsexstuff *exp,
6656     int layouttype, int *iomode, uint64_t *offset, uint64_t *len,
6657     uint64_t minlen, nfsv4stateid_t *stateidp, int maxcnt, int *retonclose,
6658     int *layoutlenp, char *layp, struct ucred *cred, NFSPROC_T *p)
6659 {
6660 	struct nfslayouthash *lhyp;
6661 	struct nfslayout *lyp;
6662 	char *devid;
6663 	fhandle_t fh, *dsfhp;
6664 	int error, mirrorcnt;
6665 
6666 	if (nfsrv_devidcnt == 0)
6667 		return (NFSERR_UNKNLAYOUTTYPE);
6668 
6669 	if (*offset != 0)
6670 		printf("nfsrv_layoutget: off=%ju len=%ju\n", (uintmax_t)*offset,
6671 		    (uintmax_t)*len);
6672 	error = nfsvno_getfh(vp, &fh, p);
6673 	NFSD_DEBUG(4, "layoutget getfh=%d\n", error);
6674 	if (error != 0)
6675 		return (error);
6676 
6677 	/*
6678 	 * For now, all layouts are for entire files.
6679 	 * Only issue Read/Write layouts if requested for a non-readonly fs.
6680 	 */
6681 	if (NFSVNO_EXRDONLY(exp)) {
6682 		if (*iomode == NFSLAYOUTIOMODE_RW)
6683 			return (NFSERR_LAYOUTTRYLATER);
6684 		*iomode = NFSLAYOUTIOMODE_READ;
6685 	}
6686 	if (*iomode != NFSLAYOUTIOMODE_RW)
6687 		*iomode = NFSLAYOUTIOMODE_READ;
6688 
6689 	/*
6690 	 * Check to see if a write layout can be issued for this file.
6691 	 * This is used during mirror recovery to avoid RW layouts being
6692 	 * issued for a file while it is being copied to the recovered
6693 	 * mirror.
6694 	 */
6695 	if (*iomode == NFSLAYOUTIOMODE_RW && nfsrv_dontlayout(&fh) != 0)
6696 		return (NFSERR_LAYOUTTRYLATER);
6697 
6698 	*retonclose = 0;
6699 	*offset = 0;
6700 	*len = UINT64_MAX;
6701 
6702 	/* First, see if a layout already exists and return if found. */
6703 	lhyp = NFSLAYOUTHASH(&fh);
6704 	NFSLOCKLAYOUT(lhyp);
6705 	error = nfsrv_findlayout(&nd->nd_clientid, &fh, layouttype, p, &lyp);
6706 	NFSD_DEBUG(4, "layoutget findlay=%d\n", error);
6707 	/*
6708 	 * Not sure if the seqid must be the same, so I won't check it.
6709 	 */
6710 	if (error == 0 && (stateidp->other[0] != lyp->lay_stateid.other[0] ||
6711 	    stateidp->other[1] != lyp->lay_stateid.other[1] ||
6712 	    stateidp->other[2] != lyp->lay_stateid.other[2])) {
6713 		if ((lyp->lay_flags & NFSLAY_CALLB) == 0) {
6714 			NFSUNLOCKLAYOUT(lhyp);
6715 			NFSD_DEBUG(1, "ret bad stateid\n");
6716 			return (NFSERR_BADSTATEID);
6717 		}
6718 		/*
6719 		 * I believe we get here because there is a race between
6720 		 * the client processing the CBLAYOUTRECALL and the layout
6721 		 * being deleted here on the server.
6722 		 * The client has now done a LayoutGet with a non-layout
6723 		 * stateid, as it would when there is no layout.
6724 		 * As such, free this layout and set error == NFSERR_BADSTATEID
6725 		 * so the code below will create a new layout structure as
6726 		 * would happen if no layout was found.
6727 		 * "lyp" will be set before being used below, but set it NULL
6728 		 * as a safety belt.
6729 		 */
6730 		nfsrv_freelayout(&lhyp->list, lyp);
6731 		lyp = NULL;
6732 		error = NFSERR_BADSTATEID;
6733 	}
6734 	if (error == 0) {
6735 		if (lyp->lay_layoutlen > maxcnt) {
6736 			NFSUNLOCKLAYOUT(lhyp);
6737 			NFSD_DEBUG(1, "ret layout too small\n");
6738 			return (NFSERR_TOOSMALL);
6739 		}
6740 		if (*iomode == NFSLAYOUTIOMODE_RW)
6741 			lyp->lay_flags |= NFSLAY_RW;
6742 		else
6743 			lyp->lay_flags |= NFSLAY_READ;
6744 		NFSBCOPY(lyp->lay_xdr, layp, lyp->lay_layoutlen);
6745 		*layoutlenp = lyp->lay_layoutlen;
6746 		if (++lyp->lay_stateid.seqid == 0)
6747 			lyp->lay_stateid.seqid = 1;
6748 		stateidp->seqid = lyp->lay_stateid.seqid;
6749 		NFSUNLOCKLAYOUT(lhyp);
6750 		NFSD_DEBUG(4, "ret fnd layout\n");
6751 		return (0);
6752 	}
6753 	NFSUNLOCKLAYOUT(lhyp);
6754 
6755 	/* Find the device id and file handle. */
6756 	dsfhp = malloc(sizeof(fhandle_t) * NFSDEV_MAXMIRRORS, M_TEMP, M_WAITOK);
6757 	devid = malloc(NFSX_V4DEVICEID * NFSDEV_MAXMIRRORS, M_TEMP, M_WAITOK);
6758 	error = nfsrv_dsgetdevandfh(vp, p, &mirrorcnt, dsfhp, devid);
6759 	NFSD_DEBUG(4, "layoutget devandfh=%d\n", error);
6760 	if (error == 0) {
6761 		if (layouttype == NFSLAYOUT_NFSV4_1_FILES) {
6762 			if (NFSX_V4FILELAYOUT > maxcnt)
6763 				error = NFSERR_TOOSMALL;
6764 			else
6765 				lyp = nfsrv_filelayout(nd, *iomode, &fh, dsfhp,
6766 				    devid, vp->v_mount->mnt_stat.f_fsid);
6767 		} else {
6768 			if (NFSX_V4FLEXLAYOUT(mirrorcnt) > maxcnt)
6769 				error = NFSERR_TOOSMALL;
6770 			else
6771 				lyp = nfsrv_flexlayout(nd, *iomode, mirrorcnt,
6772 				    &fh, dsfhp, devid,
6773 				    vp->v_mount->mnt_stat.f_fsid);
6774 		}
6775 	}
6776 	free(dsfhp, M_TEMP);
6777 	free(devid, M_TEMP);
6778 	if (error != 0)
6779 		return (error);
6780 
6781 	/*
6782 	 * Now, add this layout to the list.
6783 	 */
6784 	error = nfsrv_addlayout(nd, &lyp, stateidp, layp, layoutlenp, p);
6785 	NFSD_DEBUG(4, "layoutget addl=%d\n", error);
6786 	/*
6787 	 * The lyp will be set to NULL by nfsrv_addlayout() if it
6788 	 * linked the new structure into the lists.
6789 	 */
6790 	free(lyp, M_NFSDSTATE);
6791 	return (error);
6792 }
6793 
6794 /*
6795  * Generate a File Layout.
6796  */
6797 static struct nfslayout *
6798 nfsrv_filelayout(struct nfsrv_descript *nd, int iomode, fhandle_t *fhp,
6799     fhandle_t *dsfhp, char *devid, fsid_t fs)
6800 {
6801 	uint32_t *tl;
6802 	struct nfslayout *lyp;
6803 	uint64_t pattern_offset;
6804 
6805 	lyp = malloc(sizeof(struct nfslayout) + NFSX_V4FILELAYOUT, M_NFSDSTATE,
6806 	    M_WAITOK | M_ZERO);
6807 	lyp->lay_type = NFSLAYOUT_NFSV4_1_FILES;
6808 	if (iomode == NFSLAYOUTIOMODE_RW)
6809 		lyp->lay_flags = NFSLAY_RW;
6810 	else
6811 		lyp->lay_flags = NFSLAY_READ;
6812 	NFSBCOPY(fhp, &lyp->lay_fh, sizeof(*fhp));
6813 	lyp->lay_clientid.qval = nd->nd_clientid.qval;
6814 	lyp->lay_fsid = fs;
6815 
6816 	/* Fill in the xdr for the files layout. */
6817 	tl = (uint32_t *)lyp->lay_xdr;
6818 	NFSBCOPY(devid, tl, NFSX_V4DEVICEID);		/* Device ID. */
6819 	tl += (NFSX_V4DEVICEID / NFSX_UNSIGNED);
6820 
6821 	/*
6822 	 * Make the stripe size as many 64K blocks as will fit in the stripe
6823 	 * mask. Since there is only one stripe, the stripe size doesn't really
6824 	 * matter, except that the Linux client will only handle an exact
6825 	 * multiple of their PAGE_SIZE (usually 4K).  I chose 64K as a value
6826 	 * that should cover most/all arches w.r.t. PAGE_SIZE.
6827 	 */
6828 	*tl++ = txdr_unsigned(NFSFLAYUTIL_STRIPE_MASK & ~0xffff);
6829 	*tl++ = 0;					/* 1st stripe index. */
6830 	pattern_offset = 0;
6831 	txdr_hyper(pattern_offset, tl); tl += 2;	/* Pattern offset. */
6832 	*tl++ = txdr_unsigned(1);			/* 1 file handle. */
6833 	*tl++ = txdr_unsigned(NFSX_V4PNFSFH);
6834 	NFSBCOPY(dsfhp, tl, sizeof(*dsfhp));
6835 	lyp->lay_layoutlen = NFSX_V4FILELAYOUT;
6836 	return (lyp);
6837 }
6838 
6839 #define	FLEX_OWNERID	"999"
6840 #define	FLEX_UID0	"0"
6841 /*
6842  * Generate a Flex File Layout.
6843  * The FLEX_OWNERID can be any string of 3 decimal digits. Although this
6844  * string goes on the wire, it isn't supposed to be used by the client,
6845  * since this server uses tight coupling.
6846  * Although not recommended by the spec., if vfs.nfsd.flexlinuxhack=1 use
6847  * a string of "0". This works around the Linux Flex File Layout driver bug
6848  * which uses the synthetic uid/gid strings for the "tightly coupled" case.
6849  */
6850 static struct nfslayout *
6851 nfsrv_flexlayout(struct nfsrv_descript *nd, int iomode, int mirrorcnt,
6852     fhandle_t *fhp, fhandle_t *dsfhp, char *devid, fsid_t fs)
6853 {
6854 	uint32_t *tl;
6855 	struct nfslayout *lyp;
6856 	uint64_t lenval;
6857 	int i;
6858 
6859 	lyp = malloc(sizeof(struct nfslayout) + NFSX_V4FLEXLAYOUT(mirrorcnt),
6860 	    M_NFSDSTATE, M_WAITOK | M_ZERO);
6861 	lyp->lay_type = NFSLAYOUT_FLEXFILE;
6862 	if (iomode == NFSLAYOUTIOMODE_RW)
6863 		lyp->lay_flags = NFSLAY_RW;
6864 	else
6865 		lyp->lay_flags = NFSLAY_READ;
6866 	NFSBCOPY(fhp, &lyp->lay_fh, sizeof(*fhp));
6867 	lyp->lay_clientid.qval = nd->nd_clientid.qval;
6868 	lyp->lay_fsid = fs;
6869 	lyp->lay_mirrorcnt = mirrorcnt;
6870 
6871 	/* Fill in the xdr for the files layout. */
6872 	tl = (uint32_t *)lyp->lay_xdr;
6873 	lenval = 0;
6874 	txdr_hyper(lenval, tl); tl += 2;		/* Stripe unit. */
6875 	*tl++ = txdr_unsigned(mirrorcnt);		/* # of mirrors. */
6876 	for (i = 0; i < mirrorcnt; i++) {
6877 		*tl++ = txdr_unsigned(1);		/* One stripe. */
6878 		NFSBCOPY(devid, tl, NFSX_V4DEVICEID);	/* Device ID. */
6879 		tl += (NFSX_V4DEVICEID / NFSX_UNSIGNED);
6880 		devid += NFSX_V4DEVICEID;
6881 		*tl++ = txdr_unsigned(1);		/* Efficiency. */
6882 		*tl++ = 0;				/* Proxy Stateid. */
6883 		*tl++ = 0x55555555;
6884 		*tl++ = 0x55555555;
6885 		*tl++ = 0x55555555;
6886 		*tl++ = txdr_unsigned(1);		/* 1 file handle. */
6887 		*tl++ = txdr_unsigned(NFSX_V4PNFSFH);
6888 		NFSBCOPY(dsfhp, tl, sizeof(*dsfhp));
6889 		tl += (NFSM_RNDUP(NFSX_V4PNFSFH) / NFSX_UNSIGNED);
6890 		dsfhp++;
6891 		if (nfsrv_flexlinuxhack != 0) {
6892 			*tl++ = txdr_unsigned(strlen(FLEX_UID0));
6893 			*tl = 0;		/* 0 pad string. */
6894 			NFSBCOPY(FLEX_UID0, tl++, strlen(FLEX_UID0));
6895 			*tl++ = txdr_unsigned(strlen(FLEX_UID0));
6896 			*tl = 0;		/* 0 pad string. */
6897 			NFSBCOPY(FLEX_UID0, tl++, strlen(FLEX_UID0));
6898 		} else {
6899 			*tl++ = txdr_unsigned(strlen(FLEX_OWNERID));
6900 			NFSBCOPY(FLEX_OWNERID, tl++, NFSX_UNSIGNED);
6901 			*tl++ = txdr_unsigned(strlen(FLEX_OWNERID));
6902 			NFSBCOPY(FLEX_OWNERID, tl++, NFSX_UNSIGNED);
6903 		}
6904 	}
6905 	*tl++ = txdr_unsigned(0);		/* ff_flags. */
6906 	*tl = txdr_unsigned(60);		/* Status interval hint. */
6907 	lyp->lay_layoutlen = NFSX_V4FLEXLAYOUT(mirrorcnt);
6908 	return (lyp);
6909 }
6910 
6911 /*
6912  * Parse and process Flex File errors returned via LayoutReturn.
6913  */
6914 static void
6915 nfsrv_flexlayouterr(struct nfsrv_descript *nd, uint32_t *layp, int maxcnt,
6916     NFSPROC_T *p)
6917 {
6918 	uint32_t *tl;
6919 	int cnt, errcnt, i, j, opnum, stat;
6920 	char devid[NFSX_V4DEVICEID];
6921 
6922 	tl = layp;
6923 	cnt = fxdr_unsigned(int, *tl++);
6924 	NFSD_DEBUG(4, "flexlayouterr cnt=%d\n", cnt);
6925 	for (i = 0; i < cnt; i++) {
6926 		/* Skip offset, length and stateid for now. */
6927 		tl += (4 + NFSX_STATEID / NFSX_UNSIGNED);
6928 		errcnt = fxdr_unsigned(int, *tl++);
6929 		NFSD_DEBUG(4, "flexlayouterr errcnt=%d\n", errcnt);
6930 		for (j = 0; j < errcnt; j++) {
6931 			NFSBCOPY(tl, devid, NFSX_V4DEVICEID);
6932 			tl += (NFSX_V4DEVICEID / NFSX_UNSIGNED);
6933 			stat = fxdr_unsigned(int, *tl++);
6934 			opnum = fxdr_unsigned(int, *tl++);
6935 			NFSD_DEBUG(4, "flexlayouterr op=%d stat=%d\n", opnum,
6936 			    stat);
6937 			/*
6938 			 * Except for NFSERR_ACCES and NFSERR_STALE errors,
6939 			 * disable the mirror.
6940 			 */
6941 			if (stat != NFSERR_ACCES && stat != NFSERR_STALE)
6942 				nfsrv_delds(devid, p);
6943 		}
6944 	}
6945 }
6946 
6947 /*
6948  * This function removes all flex file layouts which has a mirror with
6949  * a device id that matches the argument.
6950  * Called when the DS represented by the device id has failed.
6951  */
6952 void
6953 nfsrv_flexmirrordel(char *devid, NFSPROC_T *p)
6954 {
6955 	uint32_t *tl;
6956 	struct nfslayout *lyp, *nlyp;
6957 	struct nfslayouthash *lhyp;
6958 	struct nfslayouthead loclyp;
6959 	int i, j;
6960 
6961 	NFSD_DEBUG(4, "flexmirrordel\n");
6962 	/* Move all layouts found onto a local list. */
6963 	TAILQ_INIT(&loclyp);
6964 	for (i = 0; i < nfsrv_layouthashsize; i++) {
6965 		lhyp = &nfslayouthash[i];
6966 		NFSLOCKLAYOUT(lhyp);
6967 		TAILQ_FOREACH_SAFE(lyp, &lhyp->list, lay_list, nlyp) {
6968 			if (lyp->lay_type == NFSLAYOUT_FLEXFILE &&
6969 			    lyp->lay_mirrorcnt > 1) {
6970 				NFSD_DEBUG(4, "possible match\n");
6971 				tl = lyp->lay_xdr;
6972 				tl += 3;
6973 				for (j = 0; j < lyp->lay_mirrorcnt; j++) {
6974 					tl++;
6975 					if (NFSBCMP(devid, tl, NFSX_V4DEVICEID)
6976 					    == 0) {
6977 						/* Found one. */
6978 						NFSD_DEBUG(4, "fnd one\n");
6979 						TAILQ_REMOVE(&lhyp->list, lyp,
6980 						    lay_list);
6981 						TAILQ_INSERT_HEAD(&loclyp, lyp,
6982 						    lay_list);
6983 						break;
6984 					}
6985 					tl += (NFSX_V4DEVICEID / NFSX_UNSIGNED +
6986 					    NFSM_RNDUP(NFSX_V4PNFSFH) /
6987 					    NFSX_UNSIGNED + 11 * NFSX_UNSIGNED);
6988 				}
6989 			}
6990 		}
6991 		NFSUNLOCKLAYOUT(lhyp);
6992 	}
6993 
6994 	/* Now, try to do a Layout recall for each one found. */
6995 	TAILQ_FOREACH_SAFE(lyp, &loclyp, lay_list, nlyp) {
6996 		NFSD_DEBUG(4, "do layout recall\n");
6997 		/*
6998 		 * The layout stateid.seqid needs to be incremented
6999 		 * before doing a LAYOUT_RECALL callback.
7000 		 */
7001 		if (++lyp->lay_stateid.seqid == 0)
7002 			lyp->lay_stateid.seqid = 1;
7003 		nfsrv_recalllayout(lyp->lay_clientid, &lyp->lay_stateid,
7004 		    &lyp->lay_fh, lyp, 1, lyp->lay_type, p);
7005 		nfsrv_freelayout(&loclyp, lyp);
7006 	}
7007 }
7008 
7009 /*
7010  * Do a recall callback to the client for this layout.
7011  */
7012 static int
7013 nfsrv_recalllayout(nfsquad_t clid, nfsv4stateid_t *stateidp, fhandle_t *fhp,
7014     struct nfslayout *lyp, int changed, int laytype, NFSPROC_T *p)
7015 {
7016 	struct nfsclient *clp;
7017 	int error;
7018 
7019 	NFSD_DEBUG(4, "nfsrv_recalllayout\n");
7020 	error = nfsrv_getclient(clid, 0, &clp, NULL, (nfsquad_t)((u_quad_t)0),
7021 	    0, NULL, p);
7022 	NFSD_DEBUG(4, "aft nfsrv_getclient=%d\n", error);
7023 	if (error != 0) {
7024 		printf("nfsrv_recalllayout: getclient err=%d\n", error);
7025 		return (error);
7026 	}
7027 	if ((clp->lc_flags & LCL_NFSV41) != 0) {
7028 		error = nfsrv_docallback(clp, NFSV4OP_CBLAYOUTRECALL,
7029 		    stateidp, changed, fhp, NULL, NULL, laytype, p);
7030 		/* If lyp != NULL, handle an error return here. */
7031 		if (error != 0 && lyp != NULL) {
7032 			NFSDRECALLLOCK();
7033 			/*
7034 			 * Mark it returned, since no layout recall
7035 			 * has been done.
7036 			 * All errors seem to be non-recoverable, although
7037 			 * NFSERR_NOMATCHLAYOUT is a normal event.
7038 			 */
7039 			if ((lyp->lay_flags & NFSLAY_RECALL) != 0) {
7040 				lyp->lay_flags |= NFSLAY_RETURNED;
7041 				wakeup(lyp);
7042 			}
7043 			NFSDRECALLUNLOCK();
7044 			if (error != NFSERR_NOMATCHLAYOUT)
7045 				printf("nfsrv_recalllayout: err=%d\n", error);
7046 		}
7047 	} else
7048 		printf("nfsrv_recalllayout: clp not NFSv4.1\n");
7049 	return (error);
7050 }
7051 
7052 /*
7053  * Find a layout to recall when we exceed our high water mark.
7054  */
7055 void
7056 nfsrv_recalloldlayout(NFSPROC_T *p)
7057 {
7058 	struct nfslayouthash *lhyp;
7059 	struct nfslayout *lyp;
7060 	nfsquad_t clientid;
7061 	nfsv4stateid_t stateid;
7062 	fhandle_t fh;
7063 	int error, laytype, ret;
7064 
7065 	lhyp = &nfslayouthash[arc4random() % nfsrv_layouthashsize];
7066 	NFSLOCKLAYOUT(lhyp);
7067 	TAILQ_FOREACH_REVERSE(lyp, &lhyp->list, nfslayouthead, lay_list) {
7068 		if ((lyp->lay_flags & NFSLAY_CALLB) == 0) {
7069 			lyp->lay_flags |= NFSLAY_CALLB;
7070 			/*
7071 			 * The layout stateid.seqid needs to be incremented
7072 			 * before doing a LAYOUT_RECALL callback.
7073 			 */
7074 			if (++lyp->lay_stateid.seqid == 0)
7075 				lyp->lay_stateid.seqid = 1;
7076 			clientid = lyp->lay_clientid;
7077 			stateid = lyp->lay_stateid;
7078 			NFSBCOPY(&lyp->lay_fh, &fh, sizeof(fh));
7079 			laytype = lyp->lay_type;
7080 			break;
7081 		}
7082 	}
7083 	NFSUNLOCKLAYOUT(lhyp);
7084 	if (lyp != NULL) {
7085 		error = nfsrv_recalllayout(clientid, &stateid, &fh, NULL, 0,
7086 		    laytype, p);
7087 		if (error != 0 && error != NFSERR_NOMATCHLAYOUT)
7088 			NFSD_DEBUG(4, "recallold=%d\n", error);
7089 		if (error != 0) {
7090 			NFSLOCKLAYOUT(lhyp);
7091 			/*
7092 			 * Since the hash list was unlocked, we need to
7093 			 * find it again.
7094 			 */
7095 			ret = nfsrv_findlayout(&clientid, &fh, laytype, p,
7096 			    &lyp);
7097 			if (ret == 0 &&
7098 			    (lyp->lay_flags & NFSLAY_CALLB) != 0 &&
7099 			    lyp->lay_stateid.other[0] == stateid.other[0] &&
7100 			    lyp->lay_stateid.other[1] == stateid.other[1] &&
7101 			    lyp->lay_stateid.other[2] == stateid.other[2]) {
7102 				/*
7103 				 * The client no longer knows this layout, so
7104 				 * it can be free'd now.
7105 				 */
7106 				if (error == NFSERR_NOMATCHLAYOUT)
7107 					nfsrv_freelayout(&lhyp->list, lyp);
7108 				else {
7109 					/*
7110 					 * Leave it to be tried later by
7111 					 * clearing NFSLAY_CALLB and moving
7112 					 * it to the head of the list, so it
7113 					 * won't be tried again for a while.
7114 					 */
7115 					lyp->lay_flags &= ~NFSLAY_CALLB;
7116 					TAILQ_REMOVE(&lhyp->list, lyp,
7117 					    lay_list);
7118 					TAILQ_INSERT_HEAD(&lhyp->list, lyp,
7119 					    lay_list);
7120 				}
7121 			}
7122 			NFSUNLOCKLAYOUT(lhyp);
7123 		}
7124 	}
7125 }
7126 
7127 /*
7128  * Try and return layout(s).
7129  */
7130 int
7131 nfsrv_layoutreturn(struct nfsrv_descript *nd, vnode_t vp,
7132     int layouttype, int iomode, uint64_t offset, uint64_t len, int reclaim,
7133     int kind, nfsv4stateid_t *stateidp, int maxcnt, uint32_t *layp, int *fndp,
7134     struct ucred *cred, NFSPROC_T *p)
7135 {
7136 	struct nfsvattr na;
7137 	struct nfslayouthash *lhyp;
7138 	struct nfslayout *lyp;
7139 	fhandle_t fh;
7140 	int error = 0;
7141 
7142 	*fndp = 0;
7143 	if (kind == NFSV4LAYOUTRET_FILE) {
7144 		error = nfsvno_getfh(vp, &fh, p);
7145 		if (error == 0) {
7146 			error = nfsrv_updatemdsattr(vp, &na, p);
7147 			if (error != 0)
7148 				printf("nfsrv_layoutreturn: updatemdsattr"
7149 				    " failed=%d\n", error);
7150 		}
7151 		if (error == 0) {
7152 			if (reclaim == newnfs_true) {
7153 				error = nfsrv_checkgrace(NULL, NULL,
7154 				    NFSLCK_RECLAIM);
7155 				if (error != NFSERR_NOGRACE)
7156 					error = 0;
7157 				return (error);
7158 			}
7159 			lhyp = NFSLAYOUTHASH(&fh);
7160 			NFSDRECALLLOCK();
7161 			NFSLOCKLAYOUT(lhyp);
7162 			error = nfsrv_findlayout(&nd->nd_clientid, &fh,
7163 			    layouttype, p, &lyp);
7164 			NFSD_DEBUG(4, "layoutret findlay=%d\n", error);
7165 			if (error == 0 &&
7166 			    stateidp->other[0] == lyp->lay_stateid.other[0] &&
7167 			    stateidp->other[1] == lyp->lay_stateid.other[1] &&
7168 			    stateidp->other[2] == lyp->lay_stateid.other[2]) {
7169 				NFSD_DEBUG(4, "nfsrv_layoutreturn: stateid %d"
7170 				    " %x %x %x laystateid %d %x %x %x"
7171 				    " off=%ju len=%ju flgs=0x%x\n",
7172 				    stateidp->seqid, stateidp->other[0],
7173 				    stateidp->other[1], stateidp->other[2],
7174 				    lyp->lay_stateid.seqid,
7175 				    lyp->lay_stateid.other[0],
7176 				    lyp->lay_stateid.other[1],
7177 				    lyp->lay_stateid.other[2],
7178 				    (uintmax_t)offset, (uintmax_t)len,
7179 				    lyp->lay_flags);
7180 				if (++lyp->lay_stateid.seqid == 0)
7181 					lyp->lay_stateid.seqid = 1;
7182 				stateidp->seqid = lyp->lay_stateid.seqid;
7183 				if (offset == 0 && len == UINT64_MAX) {
7184 					if ((iomode & NFSLAYOUTIOMODE_READ) !=
7185 					    0)
7186 						lyp->lay_flags &= ~NFSLAY_READ;
7187 					if ((iomode & NFSLAYOUTIOMODE_RW) != 0)
7188 						lyp->lay_flags &= ~NFSLAY_RW;
7189 					if ((lyp->lay_flags & (NFSLAY_READ |
7190 					    NFSLAY_RW)) == 0)
7191 						nfsrv_freelayout(&lhyp->list,
7192 						    lyp);
7193 					else
7194 						*fndp = 1;
7195 				} else
7196 					*fndp = 1;
7197 			}
7198 			NFSUNLOCKLAYOUT(lhyp);
7199 			/* Search the nfsrv_recalllist for a match. */
7200 			TAILQ_FOREACH(lyp, &nfsrv_recalllisthead, lay_list) {
7201 				if (NFSBCMP(&lyp->lay_fh, &fh,
7202 				    sizeof(fh)) == 0 &&
7203 				    lyp->lay_clientid.qval ==
7204 				    nd->nd_clientid.qval &&
7205 				    stateidp->other[0] ==
7206 				    lyp->lay_stateid.other[0] &&
7207 				    stateidp->other[1] ==
7208 				    lyp->lay_stateid.other[1] &&
7209 				    stateidp->other[2] ==
7210 				    lyp->lay_stateid.other[2]) {
7211 					lyp->lay_flags |= NFSLAY_RETURNED;
7212 					wakeup(lyp);
7213 					error = 0;
7214 				}
7215 			}
7216 			NFSDRECALLUNLOCK();
7217 		}
7218 		if (layouttype == NFSLAYOUT_FLEXFILE)
7219 			nfsrv_flexlayouterr(nd, layp, maxcnt, p);
7220 	} else if (kind == NFSV4LAYOUTRET_FSID)
7221 		nfsrv_freelayouts(&nd->nd_clientid,
7222 		    &vp->v_mount->mnt_stat.f_fsid, layouttype, iomode);
7223 	else if (kind == NFSV4LAYOUTRET_ALL)
7224 		nfsrv_freelayouts(&nd->nd_clientid, NULL, layouttype, iomode);
7225 	else
7226 		error = NFSERR_INVAL;
7227 	if (error == -1)
7228 		error = 0;
7229 	return (error);
7230 }
7231 
7232 /*
7233  * Look for an existing layout.
7234  */
7235 static int
7236 nfsrv_findlayout(nfsquad_t *clientidp, fhandle_t *fhp, int laytype,
7237     NFSPROC_T *p, struct nfslayout **lypp)
7238 {
7239 	struct nfslayouthash *lhyp;
7240 	struct nfslayout *lyp;
7241 	int ret;
7242 
7243 	*lypp = NULL;
7244 	ret = 0;
7245 	lhyp = NFSLAYOUTHASH(fhp);
7246 	TAILQ_FOREACH(lyp, &lhyp->list, lay_list) {
7247 		if (NFSBCMP(&lyp->lay_fh, fhp, sizeof(*fhp)) == 0 &&
7248 		    lyp->lay_clientid.qval == clientidp->qval &&
7249 		    lyp->lay_type == laytype)
7250 			break;
7251 	}
7252 	if (lyp != NULL)
7253 		*lypp = lyp;
7254 	else
7255 		ret = -1;
7256 	return (ret);
7257 }
7258 
7259 /*
7260  * Add the new layout, as required.
7261  */
7262 static int
7263 nfsrv_addlayout(struct nfsrv_descript *nd, struct nfslayout **lypp,
7264     nfsv4stateid_t *stateidp, char *layp, int *layoutlenp, NFSPROC_T *p)
7265 {
7266 	struct nfsclient *clp;
7267 	struct nfslayouthash *lhyp;
7268 	struct nfslayout *lyp, *nlyp;
7269 	fhandle_t *fhp;
7270 	int error;
7271 
7272 	KASSERT((nd->nd_flag & ND_IMPLIEDCLID) != 0,
7273 	    ("nfsrv_layoutget: no nd_clientid\n"));
7274 	lyp = *lypp;
7275 	fhp = &lyp->lay_fh;
7276 	NFSLOCKSTATE();
7277 	error = nfsrv_getclient((nfsquad_t)((u_quad_t)0), CLOPS_RENEW, &clp,
7278 	    NULL, (nfsquad_t)((u_quad_t)0), 0, nd, p);
7279 	if (error != 0) {
7280 		NFSUNLOCKSTATE();
7281 		return (error);
7282 	}
7283 	lyp->lay_stateid.seqid = stateidp->seqid = 1;
7284 	lyp->lay_stateid.other[0] = stateidp->other[0] =
7285 	    clp->lc_clientid.lval[0];
7286 	lyp->lay_stateid.other[1] = stateidp->other[1] =
7287 	    clp->lc_clientid.lval[1];
7288 	lyp->lay_stateid.other[2] = stateidp->other[2] =
7289 	    nfsrv_nextstateindex(clp);
7290 	NFSUNLOCKSTATE();
7291 
7292 	lhyp = NFSLAYOUTHASH(fhp);
7293 	NFSLOCKLAYOUT(lhyp);
7294 	TAILQ_FOREACH(nlyp, &lhyp->list, lay_list) {
7295 		if (NFSBCMP(&nlyp->lay_fh, fhp, sizeof(*fhp)) == 0 &&
7296 		    nlyp->lay_clientid.qval == nd->nd_clientid.qval)
7297 			break;
7298 	}
7299 	if (nlyp != NULL) {
7300 		/* A layout already exists, so use it. */
7301 		nlyp->lay_flags |= (lyp->lay_flags & (NFSLAY_READ | NFSLAY_RW));
7302 		NFSBCOPY(nlyp->lay_xdr, layp, nlyp->lay_layoutlen);
7303 		*layoutlenp = nlyp->lay_layoutlen;
7304 		if (++nlyp->lay_stateid.seqid == 0)
7305 			nlyp->lay_stateid.seqid = 1;
7306 		stateidp->seqid = nlyp->lay_stateid.seqid;
7307 		stateidp->other[0] = nlyp->lay_stateid.other[0];
7308 		stateidp->other[1] = nlyp->lay_stateid.other[1];
7309 		stateidp->other[2] = nlyp->lay_stateid.other[2];
7310 		NFSUNLOCKLAYOUT(lhyp);
7311 		return (0);
7312 	}
7313 
7314 	/* Insert the new layout in the lists. */
7315 	*lypp = NULL;
7316 	atomic_add_int(&nfsrv_layoutcnt, 1);
7317 	NFSBCOPY(lyp->lay_xdr, layp, lyp->lay_layoutlen);
7318 	*layoutlenp = lyp->lay_layoutlen;
7319 	TAILQ_INSERT_HEAD(&lhyp->list, lyp, lay_list);
7320 	NFSUNLOCKLAYOUT(lhyp);
7321 	return (0);
7322 }
7323 
7324 /*
7325  * Get the devinfo for a deviceid.
7326  */
7327 int
7328 nfsrv_getdevinfo(char *devid, int layouttype, uint32_t *maxcnt,
7329     uint32_t *notify, int *devaddrlen, char **devaddr)
7330 {
7331 	struct nfsdevice *ds;
7332 
7333 	if ((layouttype != NFSLAYOUT_NFSV4_1_FILES && layouttype !=
7334 	     NFSLAYOUT_FLEXFILE) ||
7335 	    (nfsrv_maxpnfsmirror > 1 && layouttype == NFSLAYOUT_NFSV4_1_FILES))
7336 		return (NFSERR_UNKNLAYOUTTYPE);
7337 
7338 	/*
7339 	 * Now, search for the device id.  Note that the structures won't go
7340 	 * away, but the order changes in the list.  As such, the lock only
7341 	 * needs to be held during the search through the list.
7342 	 */
7343 	NFSDDSLOCK();
7344 	TAILQ_FOREACH(ds, &nfsrv_devidhead, nfsdev_list) {
7345 		if (NFSBCMP(devid, ds->nfsdev_deviceid, NFSX_V4DEVICEID) == 0 &&
7346 		    ds->nfsdev_nmp != NULL)
7347 			break;
7348 	}
7349 	NFSDDSUNLOCK();
7350 	if (ds == NULL)
7351 		return (NFSERR_NOENT);
7352 
7353 	/* If the correct nfsdev_XXXXaddrlen is > 0, we have the device info. */
7354 	*devaddrlen = 0;
7355 	if (layouttype == NFSLAYOUT_NFSV4_1_FILES) {
7356 		*devaddrlen = ds->nfsdev_fileaddrlen;
7357 		*devaddr = ds->nfsdev_fileaddr;
7358 	} else if (layouttype == NFSLAYOUT_FLEXFILE) {
7359 		*devaddrlen = ds->nfsdev_flexaddrlen;
7360 		*devaddr = ds->nfsdev_flexaddr;
7361 	}
7362 	if (*devaddrlen == 0)
7363 		return (NFSERR_UNKNLAYOUTTYPE);
7364 
7365 	/*
7366 	 * The XDR overhead is 3 unsigned values: layout_type,
7367 	 * length_of_address and notify bitmap.
7368 	 * If the notify array is changed to not all zeros, the
7369 	 * count of unsigned values must be increased.
7370 	 */
7371 	if (*maxcnt > 0 && *maxcnt < NFSM_RNDUP(*devaddrlen) +
7372 	    3 * NFSX_UNSIGNED) {
7373 		*maxcnt = NFSM_RNDUP(*devaddrlen) + 3 * NFSX_UNSIGNED;
7374 		return (NFSERR_TOOSMALL);
7375 	}
7376 	return (0);
7377 }
7378 
7379 /*
7380  * Free a list of layout state structures.
7381  */
7382 static void
7383 nfsrv_freelayoutlist(nfsquad_t clientid)
7384 {
7385 	struct nfslayouthash *lhyp;
7386 	struct nfslayout *lyp, *nlyp;
7387 	int i;
7388 
7389 	for (i = 0; i < nfsrv_layouthashsize; i++) {
7390 		lhyp = &nfslayouthash[i];
7391 		NFSLOCKLAYOUT(lhyp);
7392 		TAILQ_FOREACH_SAFE(lyp, &lhyp->list, lay_list, nlyp) {
7393 			if (lyp->lay_clientid.qval == clientid.qval)
7394 				nfsrv_freelayout(&lhyp->list, lyp);
7395 		}
7396 		NFSUNLOCKLAYOUT(lhyp);
7397 	}
7398 }
7399 
7400 /*
7401  * Free up a layout.
7402  */
7403 static void
7404 nfsrv_freelayout(struct nfslayouthead *lhp, struct nfslayout *lyp)
7405 {
7406 
7407 	NFSD_DEBUG(4, "Freelayout=%p\n", lyp);
7408 	atomic_add_int(&nfsrv_layoutcnt, -1);
7409 	TAILQ_REMOVE(lhp, lyp, lay_list);
7410 	free(lyp, M_NFSDSTATE);
7411 }
7412 
7413 /*
7414  * Free up a device id.
7415  */
7416 void
7417 nfsrv_freeonedevid(struct nfsdevice *ds)
7418 {
7419 	int i;
7420 
7421 	atomic_add_int(&nfsrv_devidcnt, -1);
7422 	vrele(ds->nfsdev_dvp);
7423 	for (i = 0; i < nfsrv_dsdirsize; i++)
7424 		if (ds->nfsdev_dsdir[i] != NULL)
7425 			vrele(ds->nfsdev_dsdir[i]);
7426 	free(ds->nfsdev_fileaddr, M_NFSDSTATE);
7427 	free(ds->nfsdev_flexaddr, M_NFSDSTATE);
7428 	free(ds->nfsdev_host, M_NFSDSTATE);
7429 	free(ds, M_NFSDSTATE);
7430 }
7431 
7432 /*
7433  * Free up a device id and its mirrors.
7434  */
7435 static void
7436 nfsrv_freedevid(struct nfsdevice *ds)
7437 {
7438 
7439 	TAILQ_REMOVE(&nfsrv_devidhead, ds, nfsdev_list);
7440 	nfsrv_freeonedevid(ds);
7441 }
7442 
7443 /*
7444  * Free all layouts and device ids.
7445  * Done when the nfsd threads are shut down since there may be a new
7446  * modified device id list created when the nfsd is restarted.
7447  */
7448 void
7449 nfsrv_freealllayoutsanddevids(void)
7450 {
7451 	struct nfsdontlist *mrp, *nmrp;
7452 	struct nfslayout *lyp, *nlyp;
7453 
7454 	/* Get rid of the deviceid structures. */
7455 	nfsrv_freealldevids();
7456 	TAILQ_INIT(&nfsrv_devidhead);
7457 	nfsrv_devidcnt = 0;
7458 
7459 	/* Get rid of all layouts. */
7460 	nfsrv_freealllayouts();
7461 
7462 	/* Get rid of any nfsdontlist entries. */
7463 	LIST_FOREACH_SAFE(mrp, &nfsrv_dontlisthead, nfsmr_list, nmrp)
7464 		free(mrp, M_NFSDSTATE);
7465 	LIST_INIT(&nfsrv_dontlisthead);
7466 	nfsrv_dontlistlen = 0;
7467 
7468 	/* Free layouts in the recall list. */
7469 	TAILQ_FOREACH_SAFE(lyp, &nfsrv_recalllisthead, lay_list, nlyp)
7470 		nfsrv_freelayout(&nfsrv_recalllisthead, lyp);
7471 	TAILQ_INIT(&nfsrv_recalllisthead);
7472 }
7473 
7474 /*
7475  * Free layouts that match the arguments.
7476  */
7477 static void
7478 nfsrv_freelayouts(nfsquad_t *clid, fsid_t *fs, int laytype, int iomode)
7479 {
7480 	struct nfslayouthash *lhyp;
7481 	struct nfslayout *lyp, *nlyp;
7482 	int i;
7483 
7484 	for (i = 0; i < nfsrv_layouthashsize; i++) {
7485 		lhyp = &nfslayouthash[i];
7486 		NFSLOCKLAYOUT(lhyp);
7487 		TAILQ_FOREACH_SAFE(lyp, &lhyp->list, lay_list, nlyp) {
7488 			if (clid->qval != lyp->lay_clientid.qval)
7489 				continue;
7490 			if (fs != NULL && (fs->val[0] != lyp->lay_fsid.val[0] ||
7491 			    fs->val[1] != lyp->lay_fsid.val[1]))
7492 				continue;
7493 			if (laytype != lyp->lay_type)
7494 				continue;
7495 			if ((iomode & NFSLAYOUTIOMODE_READ) != 0)
7496 				lyp->lay_flags &= ~NFSLAY_READ;
7497 			if ((iomode & NFSLAYOUTIOMODE_RW) != 0)
7498 				lyp->lay_flags &= ~NFSLAY_RW;
7499 			if ((lyp->lay_flags & (NFSLAY_READ | NFSLAY_RW)) == 0)
7500 				nfsrv_freelayout(&lhyp->list, lyp);
7501 		}
7502 		NFSUNLOCKLAYOUT(lhyp);
7503 	}
7504 }
7505 
7506 /*
7507  * Free all layouts for the argument file.
7508  */
7509 void
7510 nfsrv_freefilelayouts(fhandle_t *fhp)
7511 {
7512 	struct nfslayouthash *lhyp;
7513 	struct nfslayout *lyp, *nlyp;
7514 
7515 	lhyp = NFSLAYOUTHASH(fhp);
7516 	NFSLOCKLAYOUT(lhyp);
7517 	TAILQ_FOREACH_SAFE(lyp, &lhyp->list, lay_list, nlyp) {
7518 		if (NFSBCMP(&lyp->lay_fh, fhp, sizeof(*fhp)) == 0)
7519 			nfsrv_freelayout(&lhyp->list, lyp);
7520 	}
7521 	NFSUNLOCKLAYOUT(lhyp);
7522 }
7523 
7524 /*
7525  * Free all layouts.
7526  */
7527 static void
7528 nfsrv_freealllayouts(void)
7529 {
7530 	struct nfslayouthash *lhyp;
7531 	struct nfslayout *lyp, *nlyp;
7532 	int i;
7533 
7534 	for (i = 0; i < nfsrv_layouthashsize; i++) {
7535 		lhyp = &nfslayouthash[i];
7536 		NFSLOCKLAYOUT(lhyp);
7537 		TAILQ_FOREACH_SAFE(lyp, &lhyp->list, lay_list, nlyp)
7538 			nfsrv_freelayout(&lhyp->list, lyp);
7539 		NFSUNLOCKLAYOUT(lhyp);
7540 	}
7541 }
7542 
7543 /*
7544  * Look up the mount path for the DS server.
7545  */
7546 static int
7547 nfsrv_setdsserver(char *dspathp, char *mdspathp, NFSPROC_T *p,
7548     struct nfsdevice **dsp)
7549 {
7550 	struct nameidata nd;
7551 	struct nfsdevice *ds;
7552 	struct mount *mp;
7553 	int error, i;
7554 	char *dsdirpath;
7555 	size_t dsdirsize;
7556 
7557 	NFSD_DEBUG(4, "setdssrv path=%s\n", dspathp);
7558 	*dsp = NULL;
7559 	NDINIT(&nd, LOOKUP, FOLLOW | LOCKSHARED | LOCKLEAF, UIO_SYSSPACE,
7560 	    dspathp, p);
7561 	error = namei(&nd);
7562 	NFSD_DEBUG(4, "lookup=%d\n", error);
7563 	if (error != 0)
7564 		return (error);
7565 	if (nd.ni_vp->v_type != VDIR) {
7566 		vput(nd.ni_vp);
7567 		NFSD_DEBUG(4, "dspath not dir\n");
7568 		return (ENOTDIR);
7569 	}
7570 	if (strcmp(nd.ni_vp->v_mount->mnt_vfc->vfc_name, "nfs") != 0) {
7571 		vput(nd.ni_vp);
7572 		NFSD_DEBUG(4, "dspath not an NFS mount\n");
7573 		return (ENXIO);
7574 	}
7575 
7576 	/*
7577 	 * Allocate a DS server structure with the NFS mounted directory
7578 	 * vnode reference counted, so that a non-forced dismount will
7579 	 * fail with EBUSY.
7580 	 * This structure is always linked into the list, even if an error
7581 	 * is being returned.  The caller will free the entire list upon
7582 	 * an error return.
7583 	 */
7584 	*dsp = ds = malloc(sizeof(*ds) + nfsrv_dsdirsize * sizeof(vnode_t),
7585 	    M_NFSDSTATE, M_WAITOK | M_ZERO);
7586 	ds->nfsdev_dvp = nd.ni_vp;
7587 	ds->nfsdev_nmp = VFSTONFS(nd.ni_vp->v_mount);
7588 	NFSVOPUNLOCK(nd.ni_vp, 0);
7589 
7590 	dsdirsize = strlen(dspathp) + 16;
7591 	dsdirpath = malloc(dsdirsize, M_TEMP, M_WAITOK);
7592 	/* Now, create the DS directory structures. */
7593 	for (i = 0; i < nfsrv_dsdirsize; i++) {
7594 		snprintf(dsdirpath, dsdirsize, "%s/ds%d", dspathp, i);
7595 		NDINIT(&nd, LOOKUP, FOLLOW | LOCKSHARED | LOCKLEAF,
7596 		    UIO_SYSSPACE, dsdirpath, p);
7597 		error = namei(&nd);
7598 		NFSD_DEBUG(4, "dsdirpath=%s lookup=%d\n", dsdirpath, error);
7599 		if (error != 0)
7600 			break;
7601 		if (nd.ni_vp->v_type != VDIR) {
7602 			vput(nd.ni_vp);
7603 			error = ENOTDIR;
7604 			NFSD_DEBUG(4, "dsdirpath not a VDIR\n");
7605 			break;
7606 		}
7607 		if (strcmp(nd.ni_vp->v_mount->mnt_vfc->vfc_name, "nfs") != 0) {
7608 			vput(nd.ni_vp);
7609 			error = ENXIO;
7610 			NFSD_DEBUG(4, "dsdirpath not an NFS mount\n");
7611 			break;
7612 		}
7613 		ds->nfsdev_dsdir[i] = nd.ni_vp;
7614 		NFSVOPUNLOCK(nd.ni_vp, 0);
7615 	}
7616 	free(dsdirpath, M_TEMP);
7617 
7618 	if (strlen(mdspathp) > 0) {
7619 		/*
7620 		 * This DS stores file for a specific MDS exported file
7621 		 * system.
7622 		 */
7623 		NDINIT(&nd, LOOKUP, FOLLOW | LOCKSHARED | LOCKLEAF,
7624 		    UIO_SYSSPACE, mdspathp, p);
7625 		error = namei(&nd);
7626 		NFSD_DEBUG(4, "mds lookup=%d\n", error);
7627 		if (error != 0)
7628 			goto out;
7629 		if (nd.ni_vp->v_type != VDIR) {
7630 			vput(nd.ni_vp);
7631 			error = ENOTDIR;
7632 			NFSD_DEBUG(4, "mdspath not dir\n");
7633 			goto out;
7634 		}
7635 		mp = nd.ni_vp->v_mount;
7636 		if ((mp->mnt_flag & MNT_EXPORTED) == 0) {
7637 			vput(nd.ni_vp);
7638 			error = ENXIO;
7639 			NFSD_DEBUG(4, "mdspath not an exported fs\n");
7640 			goto out;
7641 		}
7642 		ds->nfsdev_mdsfsid = mp->mnt_stat.f_fsid;
7643 		ds->nfsdev_mdsisset = 1;
7644 		vput(nd.ni_vp);
7645 	}
7646 
7647 out:
7648 	TAILQ_INSERT_TAIL(&nfsrv_devidhead, ds, nfsdev_list);
7649 	atomic_add_int(&nfsrv_devidcnt, 1);
7650 	return (error);
7651 }
7652 
7653 /*
7654  * Look up the mount path for the DS server and delete it.
7655  */
7656 int
7657 nfsrv_deldsserver(int op, char *dspathp, NFSPROC_T *p)
7658 {
7659 	struct mount *mp;
7660 	struct nfsmount *nmp;
7661 	struct nfsdevice *ds;
7662 	int error;
7663 
7664 	NFSD_DEBUG(4, "deldssrv path=%s\n", dspathp);
7665 	/*
7666 	 * Search for the path in the mount list.  Avoid looking the path
7667 	 * up, since this mount point may be hung, with associated locked
7668 	 * vnodes, etc.
7669 	 * Set NFSMNTP_CANCELRPCS so that any forced dismount will be blocked
7670 	 * until this completes.
7671 	 * As noted in the man page, this should be done before any forced
7672 	 * dismount on the mount point, but at least the handshake on
7673 	 * NFSMNTP_CANCELRPCS should make it safe.
7674 	 */
7675 	error = 0;
7676 	ds = NULL;
7677 	nmp = NULL;
7678 	mtx_lock(&mountlist_mtx);
7679 	TAILQ_FOREACH(mp, &mountlist, mnt_list) {
7680 		if (strcmp(mp->mnt_stat.f_mntonname, dspathp) == 0 &&
7681 		    strcmp(mp->mnt_stat.f_fstypename, "nfs") == 0 &&
7682 		    mp->mnt_data != NULL) {
7683 			nmp = VFSTONFS(mp);
7684 			NFSLOCKMNT(nmp);
7685 			if ((nmp->nm_privflag & (NFSMNTP_FORCEDISM |
7686 			     NFSMNTP_CANCELRPCS)) == 0) {
7687 				nmp->nm_privflag |= NFSMNTP_CANCELRPCS;
7688 				NFSUNLOCKMNT(nmp);
7689 			} else {
7690 				NFSUNLOCKMNT(nmp);
7691 				nmp = NULL;
7692 			}
7693 			break;
7694 		}
7695 	}
7696 	mtx_unlock(&mountlist_mtx);
7697 
7698 	if (nmp != NULL) {
7699 		ds = nfsrv_deldsnmp(op, nmp, p);
7700 		NFSD_DEBUG(4, "deldsnmp=%p\n", ds);
7701 		if (ds != NULL) {
7702 			nfsrv_killrpcs(nmp);
7703 			NFSD_DEBUG(4, "aft killrpcs\n");
7704 		} else
7705 			error = ENXIO;
7706 		NFSLOCKMNT(nmp);
7707 		nmp->nm_privflag &= ~NFSMNTP_CANCELRPCS;
7708 		wakeup(nmp);
7709 		NFSUNLOCKMNT(nmp);
7710 	} else
7711 		error = EINVAL;
7712 	return (error);
7713 }
7714 
7715 /*
7716  * Search for and remove a DS entry which matches the "nmp" argument.
7717  * The nfsdevice structure pointer is returned so that the caller can
7718  * free it via nfsrv_freeonedevid().
7719  * For the forced case, do not try to do LayoutRecalls, since the server
7720  * must be shut down now anyhow.
7721  */
7722 struct nfsdevice *
7723 nfsrv_deldsnmp(int op, struct nfsmount *nmp, NFSPROC_T *p)
7724 {
7725 	struct nfsdevice *fndds;
7726 
7727 	NFSD_DEBUG(4, "deldsdvp\n");
7728 	NFSDDSLOCK();
7729 	if (op == PNFSDOP_FORCEDELDS)
7730 		fndds = nfsv4_findmirror(nmp);
7731 	else
7732 		fndds = nfsrv_findmirroredds(nmp);
7733 	if (fndds != NULL)
7734 		nfsrv_deleteds(fndds);
7735 	NFSDDSUNLOCK();
7736 	if (fndds != NULL) {
7737 		if (op != PNFSDOP_FORCEDELDS)
7738 			nfsrv_flexmirrordel(fndds->nfsdev_deviceid, p);
7739 		printf("pNFS server: mirror %s failed\n", fndds->nfsdev_host);
7740 	}
7741 	return (fndds);
7742 }
7743 
7744 /*
7745  * Similar to nfsrv_deldsnmp(), except that the DS is indicated by deviceid.
7746  * This function also calls nfsrv_killrpcs() to unblock RPCs on the mount
7747  * point.
7748  * Also, returns an error instead of the nfsdevice found.
7749  */
7750 static int
7751 nfsrv_delds(char *devid, NFSPROC_T *p)
7752 {
7753 	struct nfsdevice *ds, *fndds;
7754 	struct nfsmount *nmp;
7755 	int fndmirror;
7756 
7757 	NFSD_DEBUG(4, "delds\n");
7758 	/*
7759 	 * Search the DS server list for a match with devid.
7760 	 * Remove the DS entry if found and there is a mirror.
7761 	 */
7762 	fndds = NULL;
7763 	nmp = NULL;
7764 	fndmirror = 0;
7765 	NFSDDSLOCK();
7766 	TAILQ_FOREACH(ds, &nfsrv_devidhead, nfsdev_list) {
7767 		if (NFSBCMP(ds->nfsdev_deviceid, devid, NFSX_V4DEVICEID) == 0 &&
7768 		    ds->nfsdev_nmp != NULL) {
7769 			NFSD_DEBUG(4, "fnd main ds\n");
7770 			fndds = ds;
7771 			break;
7772 		}
7773 	}
7774 	if (fndds == NULL) {
7775 		NFSDDSUNLOCK();
7776 		return (ENXIO);
7777 	}
7778 	if (fndds->nfsdev_mdsisset == 0 && nfsrv_faildscnt > 0)
7779 		fndmirror = 1;
7780 	else if (fndds->nfsdev_mdsisset != 0) {
7781 		/* For the fsid is set case, search for a mirror. */
7782 		TAILQ_FOREACH(ds, &nfsrv_devidhead, nfsdev_list) {
7783 			if (ds != fndds && ds->nfsdev_nmp != NULL &&
7784 			    ds->nfsdev_mdsisset != 0 &&
7785 			    ds->nfsdev_mdsfsid.val[0] ==
7786 			    fndds->nfsdev_mdsfsid.val[0] &&
7787 			    ds->nfsdev_mdsfsid.val[1] ==
7788 			    fndds->nfsdev_mdsfsid.val[1]) {
7789 				fndmirror = 1;
7790 				break;
7791 			}
7792 		}
7793 	}
7794 	if (fndmirror != 0) {
7795 		nmp = fndds->nfsdev_nmp;
7796 		NFSLOCKMNT(nmp);
7797 		if ((nmp->nm_privflag & (NFSMNTP_FORCEDISM |
7798 		     NFSMNTP_CANCELRPCS)) == 0) {
7799 			nmp->nm_privflag |= NFSMNTP_CANCELRPCS;
7800 			NFSUNLOCKMNT(nmp);
7801 			nfsrv_deleteds(fndds);
7802 		} else {
7803 			NFSUNLOCKMNT(nmp);
7804 			nmp = NULL;
7805 		}
7806 	}
7807 	NFSDDSUNLOCK();
7808 	if (nmp != NULL) {
7809 		nfsrv_flexmirrordel(fndds->nfsdev_deviceid, p);
7810 		printf("pNFS server: mirror %s failed\n", fndds->nfsdev_host);
7811 		nfsrv_killrpcs(nmp);
7812 		NFSLOCKMNT(nmp);
7813 		nmp->nm_privflag &= ~NFSMNTP_CANCELRPCS;
7814 		wakeup(nmp);
7815 		NFSUNLOCKMNT(nmp);
7816 		return (0);
7817 	}
7818 	return (ENXIO);
7819 }
7820 
7821 /*
7822  * Mark a DS as disabled by setting nfsdev_nmp = NULL.
7823  */
7824 static void
7825 nfsrv_deleteds(struct nfsdevice *fndds)
7826 {
7827 
7828 	NFSD_DEBUG(4, "deleteds: deleting a mirror\n");
7829 	fndds->nfsdev_nmp = NULL;
7830 	if (fndds->nfsdev_mdsisset == 0)
7831 		nfsrv_faildscnt--;
7832 }
7833 
7834 /*
7835  * Fill in the addr structures for the File and Flex File layouts.
7836  */
7837 static void
7838 nfsrv_allocdevid(struct nfsdevice *ds, char *addr, char *dnshost)
7839 {
7840 	uint32_t *tl;
7841 	char *netprot;
7842 	int addrlen;
7843 	static uint64_t new_devid = 0;
7844 
7845 	if (strchr(addr, ':') != NULL)
7846 		netprot = "tcp6";
7847 	else
7848 		netprot = "tcp";
7849 
7850 	/* Fill in the device id. */
7851 	NFSBCOPY(&nfsdev_time, ds->nfsdev_deviceid, sizeof(nfsdev_time));
7852 	new_devid++;
7853 	NFSBCOPY(&new_devid, &ds->nfsdev_deviceid[sizeof(nfsdev_time)],
7854 	    sizeof(new_devid));
7855 
7856 	/*
7857 	 * Fill in the file addr (actually the nfsv4_file_layout_ds_addr4
7858 	 * as defined in RFC5661) in XDR.
7859 	 */
7860 	addrlen = NFSM_RNDUP(strlen(addr)) + NFSM_RNDUP(strlen(netprot)) +
7861 	    6 * NFSX_UNSIGNED;
7862 	NFSD_DEBUG(4, "hn=%s addr=%s netprot=%s\n", dnshost, addr, netprot);
7863 	ds->nfsdev_fileaddrlen = addrlen;
7864 	tl = malloc(addrlen, M_NFSDSTATE, M_WAITOK | M_ZERO);
7865 	ds->nfsdev_fileaddr = (char *)tl;
7866 	*tl++ = txdr_unsigned(1);		/* One stripe with index 0. */
7867 	*tl++ = 0;
7868 	*tl++ = txdr_unsigned(1);		/* One multipath list */
7869 	*tl++ = txdr_unsigned(1);		/* with one entry in it. */
7870 	/* The netaddr for this one entry. */
7871 	*tl++ = txdr_unsigned(strlen(netprot));
7872 	NFSBCOPY(netprot, tl, strlen(netprot));
7873 	tl += (NFSM_RNDUP(strlen(netprot)) / NFSX_UNSIGNED);
7874 	*tl++ = txdr_unsigned(strlen(addr));
7875 	NFSBCOPY(addr, tl, strlen(addr));
7876 
7877 	/*
7878 	 * Fill in the flex file addr (actually the ff_device_addr4
7879 	 * as defined for Flexible File Layout) in XDR.
7880 	 */
7881 	addrlen = NFSM_RNDUP(strlen(addr)) + NFSM_RNDUP(strlen(netprot)) +
7882 	    9 * NFSX_UNSIGNED;
7883 	ds->nfsdev_flexaddrlen = addrlen;
7884 	tl = malloc(addrlen, M_NFSDSTATE, M_WAITOK | M_ZERO);
7885 	ds->nfsdev_flexaddr = (char *)tl;
7886 	*tl++ = txdr_unsigned(1);		/* One multipath entry. */
7887 	/* The netaddr for this one entry. */
7888 	*tl++ = txdr_unsigned(strlen(netprot));
7889 	NFSBCOPY(netprot, tl, strlen(netprot));
7890 	tl += (NFSM_RNDUP(strlen(netprot)) / NFSX_UNSIGNED);
7891 	*tl++ = txdr_unsigned(strlen(addr));
7892 	NFSBCOPY(addr, tl, strlen(addr));
7893 	tl += (NFSM_RNDUP(strlen(addr)) / NFSX_UNSIGNED);
7894 	*tl++ = txdr_unsigned(1);		/* One NFS Version. */
7895 	*tl++ = txdr_unsigned(NFS_VER4);	/* NFSv4. */
7896 	*tl++ = txdr_unsigned(NFSV41_MINORVERSION); /* Minor version 1. */
7897 	*tl++ = txdr_unsigned(NFS_SRVMAXIO);	/* DS max rsize. */
7898 	*tl++ = txdr_unsigned(NFS_SRVMAXIO);	/* DS max wsize. */
7899 	*tl = newnfs_true;			/* Tightly coupled. */
7900 
7901 	ds->nfsdev_hostnamelen = strlen(dnshost);
7902 	ds->nfsdev_host = malloc(ds->nfsdev_hostnamelen + 1, M_NFSDSTATE,
7903 	    M_WAITOK);
7904 	NFSBCOPY(dnshost, ds->nfsdev_host, ds->nfsdev_hostnamelen + 1);
7905 }
7906 
7907 
7908 /*
7909  * Create the device id list.
7910  * Return 0 if the nfsd threads are to run and ENXIO if the "-p" argument
7911  * is misconfigured.
7912  */
7913 int
7914 nfsrv_createdevids(struct nfsd_nfsd_args *args, NFSPROC_T *p)
7915 {
7916 	struct nfsdevice *ds;
7917 	char *addrp, *dnshostp, *dspathp, *mdspathp;
7918 	int error, i;
7919 
7920 	addrp = args->addr;
7921 	dnshostp = args->dnshost;
7922 	dspathp = args->dspath;
7923 	mdspathp = args->mdspath;
7924 	nfsrv_maxpnfsmirror = args->mirrorcnt;
7925 	if (addrp == NULL || dnshostp == NULL || dspathp == NULL ||
7926 	    mdspathp == NULL)
7927 		return (0);
7928 
7929 	/*
7930 	 * Loop around for each nul-terminated string in args->addr,
7931 	 * args->dnshost, args->dnspath and args->mdspath.
7932 	 */
7933 	while (addrp < (args->addr + args->addrlen) &&
7934 	    dnshostp < (args->dnshost + args->dnshostlen) &&
7935 	    dspathp < (args->dspath + args->dspathlen) &&
7936 	    mdspathp < (args->mdspath + args->mdspathlen)) {
7937 		error = nfsrv_setdsserver(dspathp, mdspathp, p, &ds);
7938 		if (error != 0) {
7939 			/* Free all DS servers. */
7940 			nfsrv_freealldevids();
7941 			nfsrv_devidcnt = 0;
7942 			return (ENXIO);
7943 		}
7944 		nfsrv_allocdevid(ds, addrp, dnshostp);
7945 		addrp += (strlen(addrp) + 1);
7946 		dnshostp += (strlen(dnshostp) + 1);
7947 		dspathp += (strlen(dspathp) + 1);
7948 		mdspathp += (strlen(mdspathp) + 1);
7949 	}
7950 	if (nfsrv_devidcnt < nfsrv_maxpnfsmirror) {
7951 		/* Free all DS servers. */
7952 		nfsrv_freealldevids();
7953 		nfsrv_devidcnt = 0;
7954 		nfsrv_maxpnfsmirror = 1;
7955 		return (ENXIO);
7956 	}
7957 	/* We can fail at most one less DS than the mirror level. */
7958 	nfsrv_faildscnt = nfsrv_maxpnfsmirror - 1;
7959 
7960 	/*
7961 	 * Allocate the nfslayout hash table now, since this is a pNFS server.
7962 	 * Make it 1% of the high water mark and at least 100.
7963 	 */
7964 	if (nfslayouthash == NULL) {
7965 		nfsrv_layouthashsize = nfsrv_layouthighwater / 100;
7966 		if (nfsrv_layouthashsize < 100)
7967 			nfsrv_layouthashsize = 100;
7968 		nfslayouthash = mallocarray(nfsrv_layouthashsize,
7969 		    sizeof(struct nfslayouthash), M_NFSDSESSION, M_WAITOK |
7970 		    M_ZERO);
7971 		for (i = 0; i < nfsrv_layouthashsize; i++) {
7972 			mtx_init(&nfslayouthash[i].mtx, "nfslm", NULL, MTX_DEF);
7973 			TAILQ_INIT(&nfslayouthash[i].list);
7974 		}
7975 	}
7976 	return (0);
7977 }
7978 
7979 /*
7980  * Free all device ids.
7981  */
7982 static void
7983 nfsrv_freealldevids(void)
7984 {
7985 	struct nfsdevice *ds, *nds;
7986 
7987 	TAILQ_FOREACH_SAFE(ds, &nfsrv_devidhead, nfsdev_list, nds)
7988 		nfsrv_freedevid(ds);
7989 }
7990 
7991 /*
7992  * Check to see if there is a Read/Write Layout plus either:
7993  * - A Write Delegation
7994  * or
7995  * - An Open with Write_access.
7996  * Return 1 if this is the case and 0 otherwise.
7997  * This function is used by nfsrv_proxyds() to decide if doing a Proxy
7998  * Getattr RPC to the Data Server (DS) is necessary.
7999  */
8000 #define	NFSCLIDVECSIZE	6
8001 APPLESTATIC int
8002 nfsrv_checkdsattr(struct nfsrv_descript *nd, vnode_t vp, NFSPROC_T *p)
8003 {
8004 	fhandle_t fh, *tfhp;
8005 	struct nfsstate *stp;
8006 	struct nfslayout *lyp;
8007 	struct nfslayouthash *lhyp;
8008 	struct nfslockhashhead *hp;
8009 	struct nfslockfile *lfp;
8010 	nfsquad_t clid[NFSCLIDVECSIZE];
8011 	int clidcnt, ret;
8012 
8013 	ret = nfsvno_getfh(vp, &fh, p);
8014 	if (ret != 0)
8015 		return (0);
8016 
8017 	/* First check for a Read/Write Layout. */
8018 	clidcnt = 0;
8019 	lhyp = NFSLAYOUTHASH(&fh);
8020 	NFSLOCKLAYOUT(lhyp);
8021 	TAILQ_FOREACH(lyp, &lhyp->list, lay_list) {
8022 		if (NFSBCMP(&lyp->lay_fh, &fh, sizeof(fh)) == 0 &&
8023 		    ((lyp->lay_flags & NFSLAY_RW) != 0 ||
8024 		     ((lyp->lay_flags & NFSLAY_READ) != 0 &&
8025 		      nfsrv_pnfsatime != 0))) {
8026 			if (clidcnt < NFSCLIDVECSIZE)
8027 				clid[clidcnt].qval = lyp->lay_clientid.qval;
8028 			clidcnt++;
8029 		}
8030 	}
8031 	NFSUNLOCKLAYOUT(lhyp);
8032 	if (clidcnt == 0) {
8033 		/* None found, so return 0. */
8034 		return (0);
8035 	}
8036 
8037 	/* Get the nfslockfile for this fh. */
8038 	NFSLOCKSTATE();
8039 	hp = NFSLOCKHASH(&fh);
8040 	LIST_FOREACH(lfp, hp, lf_hash) {
8041 		tfhp = &lfp->lf_fh;
8042 		if (NFSVNO_CMPFH(&fh, tfhp))
8043 			break;
8044 	}
8045 	if (lfp == NULL) {
8046 		/* None found, so return 0. */
8047 		NFSUNLOCKSTATE();
8048 		return (0);
8049 	}
8050 
8051 	/* Now, look for a Write delegation for this clientid. */
8052 	LIST_FOREACH(stp, &lfp->lf_deleg, ls_file) {
8053 		if ((stp->ls_flags & NFSLCK_DELEGWRITE) != 0 &&
8054 		    nfsrv_fndclid(clid, stp->ls_clp->lc_clientid, clidcnt) != 0)
8055 			break;
8056 	}
8057 	if (stp != NULL) {
8058 		/* Found one, so return 1. */
8059 		NFSUNLOCKSTATE();
8060 		return (1);
8061 	}
8062 
8063 	/* No Write delegation, so look for an Open with Write_access. */
8064 	LIST_FOREACH(stp, &lfp->lf_open, ls_file) {
8065 		KASSERT((stp->ls_flags & NFSLCK_OPEN) != 0,
8066 		    ("nfsrv_checkdsattr: Non-open in Open list\n"));
8067 		if ((stp->ls_flags & NFSLCK_WRITEACCESS) != 0 &&
8068 		    nfsrv_fndclid(clid, stp->ls_clp->lc_clientid, clidcnt) != 0)
8069 			break;
8070 	}
8071 	NFSUNLOCKSTATE();
8072 	if (stp != NULL)
8073 		return (1);
8074 	return (0);
8075 }
8076 
8077 /*
8078  * Look for a matching clientid in the vector. Return 1 if one might match.
8079  */
8080 static int
8081 nfsrv_fndclid(nfsquad_t *clidvec, nfsquad_t clid, int clidcnt)
8082 {
8083 	int i;
8084 
8085 	/* If too many for the vector, return 1 since there might be a match. */
8086 	if (clidcnt > NFSCLIDVECSIZE)
8087 		return (1);
8088 
8089 	for (i = 0; i < clidcnt; i++)
8090 		if (clidvec[i].qval == clid.qval)
8091 			return (1);
8092 	return (0);
8093 }
8094 
8095 /*
8096  * Check the don't list for "vp" and see if issuing an rw layout is allowed.
8097  * Return 1 if issuing an rw layout isn't allowed, 0 otherwise.
8098  */
8099 static int
8100 nfsrv_dontlayout(fhandle_t *fhp)
8101 {
8102 	struct nfsdontlist *mrp;
8103 	int ret;
8104 
8105 	if (nfsrv_dontlistlen == 0)
8106 		return (0);
8107 	ret = 0;
8108 	NFSDDONTLISTLOCK();
8109 	LIST_FOREACH(mrp, &nfsrv_dontlisthead, nfsmr_list) {
8110 		if (NFSBCMP(fhp, &mrp->nfsmr_fh, sizeof(*fhp)) == 0 &&
8111 		    (mrp->nfsmr_flags & NFSMR_DONTLAYOUT) != 0) {
8112 			ret = 1;
8113 			break;
8114 		}
8115 	}
8116 	NFSDDONTLISTUNLOCK();
8117 	return (ret);
8118 }
8119 
8120 #define	PNFSDS_COPYSIZ	65536
8121 /*
8122  * Create a new file on a DS and copy the contents of an extant DS file to it.
8123  * This can be used for recovery of a DS file onto a recovered DS.
8124  * The steps are:
8125  * - When called, the MDS file's vnode is locked, blocking LayoutGet operations.
8126  * - Disable issuing of read/write layouts for the file via the nfsdontlist,
8127  *   so that they will be disabled after the MDS file's vnode is unlocked.
8128  * - Set up the nfsrv_recalllist so that recall of read/write layouts can
8129  *   be done.
8130  * - Unlock the MDS file's vnode, so that the client(s) can perform proxied
8131  *   writes, LayoutCommits and LayoutReturns for the file when completing the
8132  *   LayoutReturn requested by the LayoutRecall callback.
8133  * - Issue a LayoutRecall callback for all read/write layouts and wait for
8134  *   them to be returned. (If the LayoutRecall callback replies
8135  *   NFSERR_NOMATCHLAYOUT, they are gone and no LayoutReturn is needed.)
8136  * - Exclusively lock the MDS file's vnode.  This ensures that no proxied
8137  *   writes are in progress or can occur during the DS file copy.
8138  *   It also blocks Setattr operations.
8139  * - Create the file on the recovered mirror.
8140  * - Copy the file from the operational DS.
8141  * - Copy any ACL from the MDS file to the new DS file.
8142  * - Set the modify time of the new DS file to that of the MDS file.
8143  * - Update the extended attribute for the MDS file.
8144  * - Enable issuing of rw layouts by deleting the nfsdontlist entry.
8145  * - The caller will unlock the MDS file's vnode allowing operations
8146  *   to continue normally, since it is now on the mirror again.
8147  */
8148 int
8149 nfsrv_copymr(vnode_t vp, vnode_t fvp, vnode_t dvp, struct nfsdevice *ds,
8150     struct pnfsdsfile *pf, struct pnfsdsfile *wpf, int mirrorcnt,
8151     struct ucred *cred, NFSPROC_T *p)
8152 {
8153 	struct nfsdontlist *mrp, *nmrp;
8154 	struct nfslayouthash *lhyp;
8155 	struct nfslayout *lyp, *nlyp;
8156 	struct nfslayouthead thl;
8157 	struct mount *mp, *tvmp;
8158 	struct acl *aclp;
8159 	struct vattr va;
8160 	struct timespec mtime;
8161 	fhandle_t fh;
8162 	vnode_t tvp;
8163 	off_t rdpos, wrpos;
8164 	ssize_t aresid;
8165 	char *dat;
8166 	int didprintf, ret, retacl, xfer;
8167 
8168 	ASSERT_VOP_LOCKED(fvp, "nfsrv_copymr fvp");
8169 	ASSERT_VOP_LOCKED(vp, "nfsrv_copymr vp");
8170 	/*
8171 	 * Allocate a nfsdontlist entry and set the NFSMR_DONTLAYOUT flag
8172 	 * so that no more RW layouts will get issued.
8173 	 */
8174 	ret = nfsvno_getfh(vp, &fh, p);
8175 	if (ret != 0) {
8176 		NFSD_DEBUG(4, "nfsrv_copymr: getfh=%d\n", ret);
8177 		return (ret);
8178 	}
8179 	nmrp = malloc(sizeof(*nmrp), M_NFSDSTATE, M_WAITOK);
8180 	nmrp->nfsmr_flags = NFSMR_DONTLAYOUT;
8181 	NFSBCOPY(&fh, &nmrp->nfsmr_fh, sizeof(fh));
8182 	NFSDDONTLISTLOCK();
8183 	LIST_FOREACH(mrp, &nfsrv_dontlisthead, nfsmr_list) {
8184 		if (NFSBCMP(&fh, &mrp->nfsmr_fh, sizeof(fh)) == 0)
8185 			break;
8186 	}
8187 	if (mrp == NULL) {
8188 		LIST_INSERT_HEAD(&nfsrv_dontlisthead, nmrp, nfsmr_list);
8189 		mrp = nmrp;
8190 		nmrp = NULL;
8191 		nfsrv_dontlistlen++;
8192 		NFSD_DEBUG(4, "nfsrv_copymr: in dontlist\n");
8193 	} else {
8194 		NFSDDONTLISTUNLOCK();
8195 		free(nmrp, M_NFSDSTATE);
8196 		NFSD_DEBUG(4, "nfsrv_copymr: dup dontlist\n");
8197 		return (ENXIO);
8198 	}
8199 	NFSDDONTLISTUNLOCK();
8200 
8201 	/*
8202 	 * Search for all RW layouts for this file.  Move them to the
8203 	 * recall list, so they can be recalled and their return noted.
8204 	 */
8205 	lhyp = NFSLAYOUTHASH(&fh);
8206 	NFSDRECALLLOCK();
8207 	NFSLOCKLAYOUT(lhyp);
8208 	TAILQ_FOREACH_SAFE(lyp, &lhyp->list, lay_list, nlyp) {
8209 		if (NFSBCMP(&lyp->lay_fh, &fh, sizeof(fh)) == 0 &&
8210 		    (lyp->lay_flags & NFSLAY_RW) != 0) {
8211 			TAILQ_REMOVE(&lhyp->list, lyp, lay_list);
8212 			TAILQ_INSERT_HEAD(&nfsrv_recalllisthead, lyp, lay_list);
8213 			lyp->lay_trycnt = 0;
8214 		}
8215 	}
8216 	NFSUNLOCKLAYOUT(lhyp);
8217 	NFSDRECALLUNLOCK();
8218 
8219 	ret = 0;
8220 	mp = tvmp = NULL;
8221 	didprintf = 0;
8222 	TAILQ_INIT(&thl);
8223 	/* Unlock the MDS vp, so that a LayoutReturn can be done on it. */
8224 	NFSVOPUNLOCK(vp, 0);
8225 	/* Now, do a recall for all layouts not yet recalled. */
8226 tryagain:
8227 	NFSDRECALLLOCK();
8228 	TAILQ_FOREACH(lyp, &nfsrv_recalllisthead, lay_list) {
8229 		if (NFSBCMP(&lyp->lay_fh, &fh, sizeof(fh)) == 0 &&
8230 		    (lyp->lay_flags & NFSLAY_RECALL) == 0) {
8231 			lyp->lay_flags |= NFSLAY_RECALL;
8232 			/*
8233 			 * The layout stateid.seqid needs to be incremented
8234 			 * before doing a LAYOUT_RECALL callback.
8235 			 */
8236 			if (++lyp->lay_stateid.seqid == 0)
8237 				lyp->lay_stateid.seqid = 1;
8238 			NFSDRECALLUNLOCK();
8239 			nfsrv_recalllayout(lyp->lay_clientid, &lyp->lay_stateid,
8240 			    &lyp->lay_fh, lyp, 0, lyp->lay_type, p);
8241 			NFSD_DEBUG(4, "nfsrv_copymr: recalled layout\n");
8242 			goto tryagain;
8243 		}
8244 	}
8245 
8246 	/* Now wait for them to be returned. */
8247 tryagain2:
8248 	TAILQ_FOREACH(lyp, &nfsrv_recalllisthead, lay_list) {
8249 		if (NFSBCMP(&lyp->lay_fh, &fh, sizeof(fh)) == 0) {
8250 			if ((lyp->lay_flags & NFSLAY_RETURNED) != 0) {
8251 				TAILQ_REMOVE(&nfsrv_recalllisthead, lyp,
8252 				    lay_list);
8253 				TAILQ_INSERT_HEAD(&thl, lyp, lay_list);
8254 				NFSD_DEBUG(4,
8255 				    "nfsrv_copymr: layout returned\n");
8256 			} else {
8257 				lyp->lay_trycnt++;
8258 				ret = mtx_sleep(lyp, NFSDRECALLMUTEXPTR,
8259 				    PVFS | PCATCH, "nfsmrl", hz);
8260 				NFSD_DEBUG(4, "nfsrv_copymr: aft sleep=%d\n",
8261 				    ret);
8262 				if (ret == EINTR || ret == ERESTART)
8263 					break;
8264 				if ((lyp->lay_flags & NFSLAY_RETURNED) == 0) {
8265 					/*
8266 					 * Give up after 60sec and return
8267 					 * ENXIO, failing the copymr.
8268 					 * This layout will remain on the
8269 					 * recalllist.  It can only be cleared
8270 					 * by restarting the nfsd.
8271 					 * This seems the safe way to handle
8272 					 * it, since it cannot be safely copied
8273 					 * with an outstanding RW layout.
8274 					 */
8275 					if (lyp->lay_trycnt >= 60) {
8276 						ret = ENXIO;
8277 						break;
8278 					}
8279 					if (didprintf == 0) {
8280 						printf("nfsrv_copymr: layout "
8281 						    "not returned\n");
8282 						didprintf = 1;
8283 					}
8284 				}
8285 			}
8286 			goto tryagain2;
8287 		}
8288 	}
8289 	NFSDRECALLUNLOCK();
8290 	/* We can now get rid of the layouts that have been returned. */
8291 	TAILQ_FOREACH_SAFE(lyp, &thl, lay_list, nlyp)
8292 		nfsrv_freelayout(&thl, lyp);
8293 
8294 	/*
8295 	 * Do the vn_start_write() calls here, before the MDS vnode is
8296 	 * locked and the tvp is created (locked) in the NFS file system
8297 	 * that dvp is in.
8298 	 * For tvmp, this probably isn't necessary, since it will be an
8299 	 * NFS mount and they are not suspendable at this time.
8300 	 */
8301 	if (ret == 0)
8302 		ret = vn_start_write(vp, &mp, V_WAIT | PCATCH);
8303 	if (ret == 0) {
8304 		tvmp = dvp->v_mount;
8305 		ret = vn_start_write(NULL, &tvmp, V_WAIT | PCATCH);
8306 	}
8307 
8308 	/*
8309 	 * LK_EXCLUSIVE lock the MDS vnode, so that any
8310 	 * proxied writes through the MDS will be blocked until we have
8311 	 * completed the copy and update of the extended attributes.
8312 	 * This will also ensure that any attributes and ACL will not be
8313 	 * changed until the copy is complete.
8314 	 */
8315 	NFSVOPLOCK(vp, LK_EXCLUSIVE | LK_RETRY);
8316 	if (ret == 0 && (vp->v_iflag & VI_DOOMED) != 0) {
8317 		NFSD_DEBUG(4, "nfsrv_copymr: lk_exclusive doomed\n");
8318 		ret = ESTALE;
8319 	}
8320 
8321 	/* Create the data file on the recovered DS. */
8322 	if (ret == 0)
8323 		ret = nfsrv_createdsfile(vp, &fh, pf, dvp, ds, cred, p, &tvp);
8324 
8325 	/* Copy the DS file, if created successfully. */
8326 	if (ret == 0) {
8327 		/*
8328 		 * Get any NFSv4 ACL on the MDS file, so that it can be set
8329 		 * on the new DS file.
8330 		 */
8331 		aclp = acl_alloc(M_WAITOK | M_ZERO);
8332 		retacl = VOP_GETACL(vp, ACL_TYPE_NFS4, aclp, cred, p);
8333 		if (retacl != 0 && retacl != ENOATTR)
8334 			NFSD_DEBUG(1, "nfsrv_copymr: vop_getacl=%d\n", retacl);
8335 		dat = malloc(PNFSDS_COPYSIZ, M_TEMP, M_WAITOK);
8336 		/* Malloc a block of 0s used to check for holes. */
8337 		if (nfsrv_zeropnfsdat == NULL)
8338 			nfsrv_zeropnfsdat = malloc(PNFSDS_COPYSIZ, M_TEMP,
8339 			    M_WAITOK | M_ZERO);
8340 		rdpos = wrpos = 0;
8341 		ret = VOP_GETATTR(fvp, &va, cred);
8342 		aresid = 0;
8343 		while (ret == 0 && aresid == 0) {
8344 			ret = vn_rdwr(UIO_READ, fvp, dat, PNFSDS_COPYSIZ,
8345 			    rdpos, UIO_SYSSPACE, IO_NODELOCKED, cred, NULL,
8346 			    &aresid, p);
8347 			xfer = PNFSDS_COPYSIZ - aresid;
8348 			if (ret == 0 && xfer > 0) {
8349 				rdpos += xfer;
8350 				/*
8351 				 * Skip the write for holes, except for the
8352 				 * last block.
8353 				 */
8354 				if (xfer < PNFSDS_COPYSIZ || rdpos ==
8355 				    va.va_size || NFSBCMP(dat,
8356 				    nfsrv_zeropnfsdat, PNFSDS_COPYSIZ) != 0)
8357 					ret = vn_rdwr(UIO_WRITE, tvp, dat, xfer,
8358 					    wrpos, UIO_SYSSPACE, IO_NODELOCKED,
8359 					    cred, NULL, NULL, p);
8360 				if (ret == 0)
8361 					wrpos += xfer;
8362 			}
8363 		}
8364 
8365 		/* If there is an ACL and the copy succeeded, set the ACL. */
8366 		if (ret == 0 && retacl == 0) {
8367 			ret = VOP_SETACL(tvp, ACL_TYPE_NFS4, aclp, cred, p);
8368 			/*
8369 			 * Don't consider these as errors, since VOP_GETACL()
8370 			 * can return an ACL when they are not actually
8371 			 * supported.  For example, for UFS, VOP_GETACL()
8372 			 * will return a trivial ACL based on the uid/gid/mode
8373 			 * when there is no ACL on the file.
8374 			 * This case should be recognized as a trivial ACL
8375 			 * by UFS's VOP_SETACL() and succeed, but...
8376 			 */
8377 			if (ret == ENOATTR || ret == EOPNOTSUPP || ret == EPERM)
8378 				ret = 0;
8379 		}
8380 
8381 		if (ret == 0)
8382 			ret = VOP_FSYNC(tvp, MNT_WAIT, p);
8383 
8384 		/* Set the DS data file's modify time that of the MDS file. */
8385 		if (ret == 0)
8386 			ret = VOP_GETATTR(vp, &va, cred);
8387 		if (ret == 0) {
8388 			mtime = va.va_mtime;
8389 			VATTR_NULL(&va);
8390 			va.va_mtime = mtime;
8391 			ret = VOP_SETATTR(tvp, &va, cred);
8392 		}
8393 
8394 		vput(tvp);
8395 		acl_free(aclp);
8396 		free(dat, M_TEMP);
8397 	}
8398 	if (tvmp != NULL)
8399 		vn_finished_write(tvmp);
8400 
8401 	/* Update the extended attributes for the newly created DS file. */
8402 	if (ret == 0)
8403 		ret = vn_extattr_set(vp, IO_NODELOCKED,
8404 		    EXTATTR_NAMESPACE_SYSTEM, "pnfsd.dsfile",
8405 		    sizeof(*wpf) * mirrorcnt, (char *)wpf, p);
8406 	if (mp != NULL)
8407 		vn_finished_write(mp);
8408 
8409 	/* Get rid of the dontlist entry, so that Layouts can be issued. */
8410 	NFSDDONTLISTLOCK();
8411 	LIST_REMOVE(mrp, nfsmr_list);
8412 	NFSDDONTLISTUNLOCK();
8413 	free(mrp, M_NFSDSTATE);
8414 	return (ret);
8415 }
8416 
8417 /*
8418  * Create a data storage file on the recovered DS.
8419  */
8420 static int
8421 nfsrv_createdsfile(vnode_t vp, fhandle_t *fhp, struct pnfsdsfile *pf,
8422     vnode_t dvp, struct nfsdevice *ds, struct ucred *cred, NFSPROC_T *p,
8423     vnode_t *tvpp)
8424 {
8425 	struct vattr va, nva;
8426 	int error;
8427 
8428 	/* Make data file name based on FH. */
8429 	error = VOP_GETATTR(vp, &va, cred);
8430 	if (error == 0) {
8431 		/* Set the attributes for "vp" to Setattr the DS vp. */
8432 		VATTR_NULL(&nva);
8433 		nva.va_uid = va.va_uid;
8434 		nva.va_gid = va.va_gid;
8435 		nva.va_mode = va.va_mode;
8436 		nva.va_size = 0;
8437 		VATTR_NULL(&va);
8438 		va.va_type = VREG;
8439 		va.va_mode = nva.va_mode;
8440 		NFSD_DEBUG(4, "nfsrv_dscreatefile: dvp=%p pf=%p\n", dvp, pf);
8441 		error = nfsrv_dscreate(dvp, &va, &nva, fhp, pf, NULL,
8442 		    pf->dsf_filename, cred, p, tvpp);
8443 	}
8444 	return (error);
8445 }
8446 
8447 /*
8448  * Look up the MDS file shared locked, and then get the extended attribute
8449  * to find the extant DS file to be copied to the new mirror.
8450  * If successful, *vpp is set to the MDS file's vp and *nvpp is
8451  * set to a DS data file for the MDS file, both exclusively locked.
8452  * The "buf" argument has the pnfsdsfile structure from the MDS file
8453  * in it and buflen is set to its length.
8454  */
8455 int
8456 nfsrv_mdscopymr(char *mdspathp, char *dspathp, char *curdspathp, char *buf,
8457     int *buflenp, char *fname, NFSPROC_T *p, struct vnode **vpp,
8458     struct vnode **nvpp, struct pnfsdsfile **pfp, struct nfsdevice **dsp,
8459     struct nfsdevice **fdsp)
8460 {
8461 	struct nameidata nd;
8462 	struct vnode *vp, *curvp;
8463 	struct pnfsdsfile *pf;
8464 	struct nfsmount *nmp, *curnmp;
8465 	int dsdir, error, mirrorcnt, ippos;
8466 
8467 	vp = NULL;
8468 	curvp = NULL;
8469 	curnmp = NULL;
8470 	*dsp = NULL;
8471 	*fdsp = NULL;
8472 	if (dspathp == NULL && curdspathp != NULL)
8473 		return (EPERM);
8474 
8475 	/*
8476 	 * Look up the MDS file shared locked.  The lock will be upgraded
8477 	 * to an exclusive lock after any rw layouts have been returned.
8478 	 */
8479 	NFSD_DEBUG(4, "mdsopen path=%s\n", mdspathp);
8480 	NDINIT(&nd, LOOKUP, FOLLOW | LOCKSHARED | LOCKLEAF, UIO_SYSSPACE,
8481 	    mdspathp, p);
8482 	error = namei(&nd);
8483 	NFSD_DEBUG(4, "lookup=%d\n", error);
8484 	if (error != 0)
8485 		return (error);
8486 	if (nd.ni_vp->v_type != VREG) {
8487 		vput(nd.ni_vp);
8488 		NFSD_DEBUG(4, "mdspath not reg\n");
8489 		return (EISDIR);
8490 	}
8491 	vp = nd.ni_vp;
8492 
8493 	if (curdspathp != NULL) {
8494 		/*
8495 		 * Look up the current DS path and find the nfsdev structure for
8496 		 * it.
8497 		 */
8498 		NFSD_DEBUG(4, "curmdsdev path=%s\n", curdspathp);
8499 		NDINIT(&nd, LOOKUP, FOLLOW | LOCKSHARED | LOCKLEAF,
8500 		    UIO_SYSSPACE, curdspathp, p);
8501 		error = namei(&nd);
8502 		NFSD_DEBUG(4, "ds lookup=%d\n", error);
8503 		if (error != 0) {
8504 			vput(vp);
8505 			return (error);
8506 		}
8507 		if (nd.ni_vp->v_type != VDIR) {
8508 			vput(nd.ni_vp);
8509 			vput(vp);
8510 			NFSD_DEBUG(4, "curdspath not dir\n");
8511 			return (ENOTDIR);
8512 		}
8513 		if (strcmp(nd.ni_vp->v_mount->mnt_vfc->vfc_name, "nfs") != 0) {
8514 			vput(nd.ni_vp);
8515 			vput(vp);
8516 			NFSD_DEBUG(4, "curdspath not an NFS mount\n");
8517 			return (ENXIO);
8518 		}
8519 		curnmp = VFSTONFS(nd.ni_vp->v_mount);
8520 
8521 		/* Search the nfsdev list for a match. */
8522 		NFSDDSLOCK();
8523 		*fdsp = nfsv4_findmirror(curnmp);
8524 		NFSDDSUNLOCK();
8525 		if (*fdsp == NULL)
8526 			curnmp = NULL;
8527 		if (curnmp == NULL) {
8528 			vput(nd.ni_vp);
8529 			vput(vp);
8530 			NFSD_DEBUG(4, "mdscopymr: no current ds\n");
8531 			return (ENXIO);
8532 		}
8533 		curvp = nd.ni_vp;
8534 	}
8535 
8536 	if (dspathp != NULL) {
8537 		/* Look up the nfsdev path and find the nfsdev structure. */
8538 		NFSD_DEBUG(4, "mdsdev path=%s\n", dspathp);
8539 		NDINIT(&nd, LOOKUP, FOLLOW | LOCKSHARED | LOCKLEAF,
8540 		    UIO_SYSSPACE, dspathp, p);
8541 		error = namei(&nd);
8542 		NFSD_DEBUG(4, "ds lookup=%d\n", error);
8543 		if (error != 0) {
8544 			vput(vp);
8545 			if (curvp != NULL)
8546 				vput(curvp);
8547 			return (error);
8548 		}
8549 		if (nd.ni_vp->v_type != VDIR || nd.ni_vp == curvp) {
8550 			vput(nd.ni_vp);
8551 			vput(vp);
8552 			if (curvp != NULL)
8553 				vput(curvp);
8554 			NFSD_DEBUG(4, "dspath not dir\n");
8555 			if (nd.ni_vp == curvp)
8556 				return (EPERM);
8557 			return (ENOTDIR);
8558 		}
8559 		if (strcmp(nd.ni_vp->v_mount->mnt_vfc->vfc_name, "nfs") != 0) {
8560 			vput(nd.ni_vp);
8561 			vput(vp);
8562 			if (curvp != NULL)
8563 				vput(curvp);
8564 			NFSD_DEBUG(4, "dspath not an NFS mount\n");
8565 			return (ENXIO);
8566 		}
8567 		nmp = VFSTONFS(nd.ni_vp->v_mount);
8568 
8569 		/*
8570 		 * Search the nfsdevice list for a match.  If curnmp == NULL,
8571 		 * this is a recovery and there must be a mirror.
8572 		 */
8573 		NFSDDSLOCK();
8574 		if (curnmp == NULL)
8575 			*dsp = nfsrv_findmirroredds(nmp);
8576 		else
8577 			*dsp = nfsv4_findmirror(nmp);
8578 		NFSDDSUNLOCK();
8579 		if (*dsp == NULL) {
8580 			vput(nd.ni_vp);
8581 			vput(vp);
8582 			if (curvp != NULL)
8583 				vput(curvp);
8584 			NFSD_DEBUG(4, "mdscopymr: no ds\n");
8585 			return (ENXIO);
8586 		}
8587 	} else {
8588 		nd.ni_vp = NULL;
8589 		nmp = NULL;
8590 	}
8591 
8592 	/*
8593 	 * Get a vp for an available DS data file using the extended
8594 	 * attribute on the MDS file.
8595 	 * If there is a valid entry for the new DS in the extended attribute
8596 	 * on the MDS file (as checked via the nmp argument),
8597 	 * nfsrv_dsgetsockmnt() returns EEXIST, so no copying will occur.
8598 	 */
8599 	error = nfsrv_dsgetsockmnt(vp, 0, buf, buflenp, &mirrorcnt, p,
8600 	    NULL, NULL, NULL, fname, nvpp, &nmp, curnmp, &ippos, &dsdir);
8601 	if (curvp != NULL)
8602 		vput(curvp);
8603 	if (nd.ni_vp == NULL) {
8604 		if (error == 0 && nmp != NULL) {
8605 			/* Search the nfsdev list for a match. */
8606 			NFSDDSLOCK();
8607 			*dsp = nfsrv_findmirroredds(nmp);
8608 			NFSDDSUNLOCK();
8609 		}
8610 		if (error == 0 && (nmp == NULL || *dsp == NULL)) {
8611 			if (nvpp != NULL && *nvpp != NULL) {
8612 				vput(*nvpp);
8613 				*nvpp = NULL;
8614 			}
8615 			error = ENXIO;
8616 		}
8617 	} else
8618 		vput(nd.ni_vp);
8619 
8620 	/*
8621 	 * When dspathp != NULL and curdspathp == NULL, this is a recovery
8622 	 * and is only allowed if there is a 0.0.0.0 IP address entry.
8623 	 * When curdspathp != NULL, the ippos will be set to that entry.
8624 	 */
8625 	if (error == 0 && dspathp != NULL && ippos == -1) {
8626 		if (nvpp != NULL && *nvpp != NULL) {
8627 			vput(*nvpp);
8628 			*nvpp = NULL;
8629 		}
8630 		error = ENXIO;
8631 	}
8632 	if (error == 0) {
8633 		*vpp = vp;
8634 
8635 		pf = (struct pnfsdsfile *)buf;
8636 		if (ippos == -1) {
8637 			/* If no zeroip pnfsdsfile, add one. */
8638 			ippos = *buflenp / sizeof(*pf);
8639 			*buflenp += sizeof(*pf);
8640 			pf += ippos;
8641 			pf->dsf_dir = dsdir;
8642 			strlcpy(pf->dsf_filename, fname,
8643 			    sizeof(pf->dsf_filename));
8644 		} else
8645 			pf += ippos;
8646 		*pfp = pf;
8647 	} else
8648 		vput(vp);
8649 	return (error);
8650 }
8651 
8652 /*
8653  * Search for a matching pnfsd mirror device structure, base on the nmp arg.
8654  * Return one if found, NULL otherwise.
8655  */
8656 static struct nfsdevice *
8657 nfsrv_findmirroredds(struct nfsmount *nmp)
8658 {
8659 	struct nfsdevice *ds, *fndds;
8660 	int fndmirror;
8661 
8662 	mtx_assert(NFSDDSMUTEXPTR, MA_OWNED);
8663 	/*
8664 	 * Search the DS server list for a match with nmp.
8665 	 * Remove the DS entry if found and there is a mirror.
8666 	 */
8667 	fndds = NULL;
8668 	fndmirror = 0;
8669 	if (nfsrv_devidcnt == 0)
8670 		return (fndds);
8671 	TAILQ_FOREACH(ds, &nfsrv_devidhead, nfsdev_list) {
8672 		if (ds->nfsdev_nmp == nmp) {
8673 			NFSD_DEBUG(4, "nfsrv_findmirroredds: fnd main ds\n");
8674 			fndds = ds;
8675 			break;
8676 		}
8677 	}
8678 	if (fndds == NULL)
8679 		return (fndds);
8680 	if (fndds->nfsdev_mdsisset == 0 && nfsrv_faildscnt > 0)
8681 		fndmirror = 1;
8682 	else if (fndds->nfsdev_mdsisset != 0) {
8683 		/* For the fsid is set case, search for a mirror. */
8684 		TAILQ_FOREACH(ds, &nfsrv_devidhead, nfsdev_list) {
8685 			if (ds != fndds && ds->nfsdev_nmp != NULL &&
8686 			    ds->nfsdev_mdsisset != 0 &&
8687 			    ds->nfsdev_mdsfsid.val[0] ==
8688 			    fndds->nfsdev_mdsfsid.val[0] &&
8689 			    ds->nfsdev_mdsfsid.val[1] ==
8690 			    fndds->nfsdev_mdsfsid.val[1]) {
8691 				fndmirror = 1;
8692 				break;
8693 			}
8694 		}
8695 	}
8696 	if (fndmirror == 0) {
8697 		NFSD_DEBUG(4, "nfsrv_findmirroredds: no mirror for DS\n");
8698 		return (NULL);
8699 	}
8700 	return (fndds);
8701 }
8702 
8703