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