xref: /freebsd/sys/nlm/nlm_prot_impl.c (revision 6356dba0b403daa023dec24559ab1f8e602e4f14)
1 /*-
2  * Copyright (c) 2008 Isilon Inc http://www.isilon.com/
3  * Authors: Doug Rabson <dfr@rabson.org>
4  * Developed with Red Inc: Alfred Perlstein <alfred@freebsd.org>
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
16  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
19  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25  * SUCH DAMAGE.
26  */
27 
28 #include "opt_inet6.h"
29 
30 #include <sys/cdefs.h>
31 __FBSDID("$FreeBSD$");
32 
33 #include <sys/param.h>
34 #include <sys/fcntl.h>
35 #include <sys/kernel.h>
36 #include <sys/kthread.h>
37 #include <sys/lockf.h>
38 #include <sys/malloc.h>
39 #include <sys/mount.h>
40 #if __FreeBSD_version >= 700000
41 #include <sys/priv.h>
42 #endif
43 #include <sys/proc.h>
44 #include <sys/socket.h>
45 #include <sys/socketvar.h>
46 #include <sys/syscall.h>
47 #include <sys/sysctl.h>
48 #include <sys/sysent.h>
49 #include <sys/sysproto.h>
50 #include <sys/systm.h>
51 #include <sys/taskqueue.h>
52 #include <sys/unistd.h>
53 #include <sys/vnode.h>
54 
55 #include <nfs/nfsproto.h>
56 #include <nfsclient/nfs.h>
57 #include <nfsclient/nfsnode.h>
58 
59 #include <nlm/nlm_prot.h>
60 #include <nlm/sm_inter.h>
61 #include <nlm/nlm.h>
62 #include <rpc/rpc_com.h>
63 #include <rpc/rpcb_prot.h>
64 
65 MALLOC_DEFINE(M_NLM, "NLM", "Network Lock Manager");
66 
67 /*
68  * If a host is inactive (and holds no locks) for this amount of
69  * seconds, we consider it idle and stop tracking it.
70  */
71 #define NLM_IDLE_TIMEOUT	30
72 
73 /*
74  * We check the host list for idle every few seconds.
75  */
76 #define NLM_IDLE_PERIOD		5
77 
78 /*
79  * Support for sysctl vfs.nlm.sysid
80  */
81 SYSCTL_NODE(_vfs, OID_AUTO, nlm, CTLFLAG_RW, NULL, "Network Lock Manager");
82 SYSCTL_NODE(_vfs_nlm, OID_AUTO, sysid, CTLFLAG_RW, NULL, "");
83 
84 /*
85  * Syscall hooks
86  */
87 static int nlm_syscall_offset = SYS_nlm_syscall;
88 static struct sysent nlm_syscall_prev_sysent;
89 #if __FreeBSD_version < 700000
90 static struct sysent nlm_syscall_sysent = {
91 	(sizeof(struct nlm_syscall_args) / sizeof(register_t)) | SYF_MPSAFE,
92 	(sy_call_t *) nlm_syscall
93 };
94 #else
95 MAKE_SYSENT(nlm_syscall);
96 #endif
97 static bool_t nlm_syscall_registered = FALSE;
98 
99 /*
100  * Debug level passed in from userland. We also support a sysctl hook
101  * so that it can be changed on a live system.
102  */
103 static int nlm_debug_level;
104 SYSCTL_INT(_debug, OID_AUTO, nlm_debug, CTLFLAG_RW, &nlm_debug_level, 0, "");
105 
106 /*
107  * Grace period handling. The value of nlm_grace_threshold is the
108  * value of time_uptime after which we are serving requests normally.
109  */
110 static time_t nlm_grace_threshold;
111 
112 /*
113  * We check for idle hosts if time_uptime is greater than
114  * nlm_next_idle_check,
115  */
116 static time_t nlm_next_idle_check;
117 
118 /*
119  * A socket to use for RPC - shared by all IPv4 RPC clients.
120  */
121 static struct socket *nlm_socket;
122 
123 #ifdef INET6
124 
125 /*
126  * A socket to use for RPC - shared by all IPv6 RPC clients.
127  */
128 static struct socket *nlm_socket6;
129 
130 #endif
131 
132 /*
133  * An RPC client handle that can be used to communicate with the local
134  * NSM.
135  */
136 static CLIENT *nlm_nsm;
137 
138 /*
139  * An AUTH handle for the server's creds.
140  */
141 static AUTH *nlm_auth;
142 
143 /*
144  * A zero timeval for sending async RPC messages.
145  */
146 struct timeval nlm_zero_tv = { 0, 0 };
147 
148 /*
149  * The local NSM state number
150  */
151 int nlm_nsm_state;
152 
153 
154 /*
155  * A lock to protect the host list and waiting lock list.
156  */
157 static struct mtx nlm_global_lock;
158 
159 /*
160  * Locks:
161  * (l)		locked by nh_lock
162  * (s)		only accessed via server RPC which is single threaded
163  * (g)		locked by nlm_global_lock
164  * (c)		const until freeing
165  * (a)		modified using atomic ops
166  */
167 
168 /*
169  * A pending client-side lock request, stored on the nlm_waiting_locks
170  * list.
171  */
172 struct nlm_waiting_lock {
173 	TAILQ_ENTRY(nlm_waiting_lock) nw_link; /* (g) */
174 	bool_t		nw_waiting;	       /* (g) */
175 	nlm4_lock	nw_lock;	       /* (c) */
176 	union nfsfh	nw_fh;		       /* (c) */
177 	struct vnode	*nw_vp;		       /* (c) */
178 };
179 TAILQ_HEAD(nlm_waiting_lock_list, nlm_waiting_lock);
180 
181 struct nlm_waiting_lock_list nlm_waiting_locks; /* (g) */
182 
183 /*
184  * A pending server-side asynchronous lock request, stored on the
185  * nh_pending list of the NLM host.
186  */
187 struct nlm_async_lock {
188 	TAILQ_ENTRY(nlm_async_lock) af_link; /* (l) host's list of locks */
189 	struct task	af_task;	/* (c) async callback details */
190 	void		*af_cookie;	/* (l) lock manager cancel token */
191 	struct vnode	*af_vp;		/* (l) vnode to lock */
192 	struct flock	af_fl;		/* (c) lock details */
193 	struct nlm_host *af_host;	/* (c) host which is locking */
194 	CLIENT		*af_rpc;	/* (c) rpc client to send message */
195 	nlm4_testargs	af_granted;	/* (c) notification details */
196 };
197 TAILQ_HEAD(nlm_async_lock_list, nlm_async_lock);
198 
199 /*
200  * NLM host.
201  */
202 enum nlm_host_state {
203 	NLM_UNMONITORED,
204 	NLM_MONITORED,
205 	NLM_MONITOR_FAILED,
206 	NLM_RECOVERING
207 };
208 struct nlm_host {
209 	struct mtx	nh_lock;
210 	volatile u_int	nh_refs;       /* (a) reference count */
211 	TAILQ_ENTRY(nlm_host) nh_link; /* (g) global list of hosts */
212 	char		nh_caller_name[MAXNAMELEN]; /* (c) printable name of host */
213 	uint32_t	nh_sysid;	 /* (c) our allocaed system ID */
214 	char		nh_sysid_string[10]; /* (c) string rep. of sysid */
215 	struct sockaddr_storage	nh_addr; /* (s) remote address of host */
216 	CLIENT		*nh_rpc;	 /* (l) RPC handle to send to host */
217 	rpcvers_t	nh_vers;	 /* (s) NLM version of host */
218 	int		nh_state;	 /* (s) last seen NSM state of host */
219 	enum nlm_host_state nh_monstate; /* (l) local NSM monitoring state */
220 	time_t		nh_idle_timeout; /* (s) Time at which host is idle */
221 	time_t		nh_rpc_create_time; /* (s) Time we create RPC client */
222 	struct sysctl_ctx_list nh_sysctl; /* (c) vfs.nlm.sysid nodes */
223 	struct nlm_async_lock_list nh_pending; /* (l) pending async locks */
224 	struct nlm_async_lock_list nh_finished; /* (l) finished async locks */
225 };
226 TAILQ_HEAD(nlm_host_list, nlm_host);
227 
228 static struct nlm_host_list nlm_hosts; /* (g) */
229 static uint32_t nlm_next_sysid = 1;    /* (g) */
230 
231 static void	nlm_host_unmonitor(struct nlm_host *);
232 
233 /**********************************************************************/
234 
235 /*
236  * Initialise NLM globals.
237  */
238 static void
239 nlm_init(void *dummy)
240 {
241 	int error;
242 
243 	mtx_init(&nlm_global_lock, "nlm_global_lock", NULL, MTX_DEF);
244 	TAILQ_INIT(&nlm_waiting_locks);
245 	TAILQ_INIT(&nlm_hosts);
246 
247 	error = syscall_register(&nlm_syscall_offset, &nlm_syscall_sysent,
248 	    &nlm_syscall_prev_sysent);
249 	if (error)
250 		printf("Can't register NLM syscall\n");
251 	else
252 		nlm_syscall_registered = TRUE;
253 }
254 SYSINIT(nlm_init, SI_SUB_LOCK, SI_ORDER_FIRST, nlm_init, NULL);
255 
256 static void
257 nlm_uninit(void *dummy)
258 {
259 
260 	if (nlm_syscall_registered)
261 		syscall_deregister(&nlm_syscall_offset,
262 		    &nlm_syscall_prev_sysent);
263 }
264 SYSUNINIT(nlm_uninit, SI_SUB_LOCK, SI_ORDER_FIRST, nlm_uninit, NULL);
265 
266 /*
267  * Copy a struct netobj.
268  */
269 void
270 nlm_copy_netobj(struct netobj *dst, struct netobj *src,
271     struct malloc_type *type)
272 {
273 
274 	dst->n_len = src->n_len;
275 	dst->n_bytes = malloc(src->n_len, type, M_WAITOK);
276 	memcpy(dst->n_bytes, src->n_bytes, src->n_len);
277 }
278 
279 /*
280  * Create an RPC client handle for the given (address,prog,vers)
281  * triple using UDP.
282  */
283 static CLIENT *
284 nlm_get_rpc(struct sockaddr *sa, rpcprog_t prog, rpcvers_t vers)
285 {
286 	const char *wchan = "nlmrcv";
287 	const char* protofmly;
288 	struct sockaddr_storage ss;
289 	struct socket *so;
290 	CLIENT *rpcb;
291 	struct timeval timo;
292 	RPCB parms;
293 	char *uaddr;
294 	enum clnt_stat stat = RPC_SUCCESS;
295 	int rpcvers = RPCBVERS4;
296 	bool_t do_tcp = FALSE;
297 	struct pmap mapping;
298 	u_short port = 0;
299 
300 	/*
301 	 * First we need to contact the remote RPCBIND service to find
302 	 * the right port.
303 	 */
304 	memcpy(&ss, sa, sa->sa_len);
305 	switch (ss.ss_family) {
306 	case AF_INET:
307 		((struct sockaddr_in *)&ss)->sin_port = htons(111);
308 		protofmly = "inet";
309 		so = nlm_socket;
310 		break;
311 
312 #ifdef INET6
313 	case AF_INET6:
314 		((struct sockaddr_in6 *)&ss)->sin6_port = htons(111);
315 		protofmly = "inet6";
316 		so = nlm_socket6;
317 		break;
318 #endif
319 
320 	default:
321 		/*
322 		 * Unsupported address family - fail.
323 		 */
324 		return (NULL);
325 	}
326 
327 	rpcb = clnt_dg_create(so, (struct sockaddr *)&ss,
328 	    RPCBPROG, rpcvers, 0, 0);
329 	if (!rpcb)
330 		return (NULL);
331 
332 try_tcp:
333 	parms.r_prog = prog;
334 	parms.r_vers = vers;
335 	if (do_tcp)
336 		parms.r_netid = "tcp";
337 	else
338 		parms.r_netid = "udp";
339 	parms.r_addr = "";
340 	parms.r_owner = "";
341 
342 	/*
343 	 * Use the default timeout.
344 	 */
345 	timo.tv_sec = 25;
346 	timo.tv_usec = 0;
347 again:
348 	switch (rpcvers) {
349 	case RPCBVERS4:
350 	case RPCBVERS:
351 		/*
352 		 * Try RPCBIND 4 then 3.
353 		 */
354 		uaddr = NULL;
355 		stat = CLNT_CALL(rpcb, (rpcprog_t) RPCBPROC_GETADDR,
356 		    (xdrproc_t) xdr_rpcb, &parms,
357 		    (xdrproc_t) xdr_wrapstring, &uaddr, timo);
358 		if (stat == RPC_PROGVERSMISMATCH) {
359 			if (rpcvers == RPCBVERS4)
360 				rpcvers = RPCBVERS;
361 			else if (rpcvers == RPCBVERS)
362 				rpcvers = PMAPVERS;
363 			CLNT_CONTROL(rpcb, CLSET_VERS, &rpcvers);
364 			goto again;
365 		} else if (stat == RPC_SUCCESS) {
366 			/*
367 			 * We have a reply from the remote RPCBIND - turn it
368 			 * into an appropriate address and make a new client
369 			 * that can talk to the remote NLM.
370 			 *
371 			 * XXX fixup IPv6 scope ID.
372 			 */
373 			struct netbuf *a;
374 			a = __rpc_uaddr2taddr_af(ss.ss_family, uaddr);
375 			if (!a) {
376 				CLNT_DESTROY(rpcb);
377 				return (NULL);
378 			}
379 			memcpy(&ss, a->buf, a->len);
380 			free(a->buf, M_RPC);
381 			free(a, M_RPC);
382 			xdr_free((xdrproc_t) xdr_wrapstring, &uaddr);
383 		}
384 		break;
385 	case PMAPVERS:
386 		/*
387 		 * Try portmap.
388 		 */
389 		mapping.pm_prog = parms.r_prog;
390 		mapping.pm_vers = parms.r_vers;
391 		mapping.pm_prot = do_tcp ? IPPROTO_TCP : IPPROTO_UDP;
392 		mapping.pm_port = 0;
393 
394 		stat = CLNT_CALL(rpcb, (rpcprog_t) PMAPPROC_GETPORT,
395 		    (xdrproc_t) xdr_pmap, &mapping,
396 		    (xdrproc_t) xdr_u_short, &port, timo);
397 
398 		if (stat == RPC_SUCCESS) {
399 			switch (ss.ss_family) {
400 			case AF_INET:
401 				((struct sockaddr_in *)&ss)->sin_port =
402 					htons(port);
403 				break;
404 
405 #ifdef INET6
406 			case AF_INET6:
407 				((struct sockaddr_in6 *)&ss)->sin6_port =
408 					htons(port);
409 				break;
410 #endif
411 			}
412 		}
413 		break;
414 	default:
415 		panic("invalid rpcvers %d", rpcvers);
416 	}
417 	/*
418 	 * We may have a positive response from the portmapper, but the NLM
419 	 * service was not found. Make sure we received a valid port.
420 	 */
421 	switch (ss.ss_family) {
422 	case AF_INET:
423 		port = ((struct sockaddr_in *)&ss)->sin_port;
424 		break;
425 #ifdef INET6
426 	case AF_INET6:
427 		port = ((struct sockaddr_in6 *)&ss)->sin6_port;
428 		break;
429 #endif
430 	}
431 	if (stat != RPC_SUCCESS || !port) {
432 		/*
433 		 * If we were able to talk to rpcbind or portmap, but the udp
434 		 * variant wasn't available, ask about tcp.
435 		 *
436 		 * XXX - We could also check for a TCP portmapper, but
437 		 * if the host is running a portmapper at all, we should be able
438 		 * to hail it over UDP.
439 		 */
440 		if (stat == RPC_SUCCESS && !do_tcp) {
441 			do_tcp = TRUE;
442 			goto try_tcp;
443 		}
444 
445 		/* Otherwise, bad news. */
446 		printf("NLM: failed to contact remote rpcbind, "
447 		    "stat = %d, port = %d\n",
448 		    (int) stat, port);
449 		CLNT_DESTROY(rpcb);
450 		return (NULL);
451 	}
452 
453 	if (do_tcp) {
454 		/*
455 		 * Destroy the UDP client we used to speak to rpcbind and
456 		 * recreate as a TCP client.
457 		 */
458 		struct netconfig *nconf = NULL;
459 
460 		CLNT_DESTROY(rpcb);
461 
462 		switch (ss.ss_family) {
463 		case AF_INET:
464 			nconf = getnetconfigent("tcp");
465 			break;
466 #ifdef INET6
467 		case AF_INET6:
468 			nconf = getnetconfigent("tcp6");
469 			break;
470 #endif
471 		}
472 
473 		rpcb = clnt_reconnect_create(nconf, (struct sockaddr *)&ss,
474 		    prog, vers, 0, 0);
475 		CLNT_CONTROL(rpcb, CLSET_WAITCHAN, &wchan);
476 		rpcb->cl_auth = nlm_auth;
477 
478 	} else {
479 		/*
480 		 * Re-use the client we used to speak to rpcbind.
481 		 */
482 		CLNT_CONTROL(rpcb, CLSET_SVC_ADDR, &ss);
483 		CLNT_CONTROL(rpcb, CLSET_PROG, &prog);
484 		CLNT_CONTROL(rpcb, CLSET_VERS, &vers);
485 		CLNT_CONTROL(rpcb, CLSET_WAITCHAN, &wchan);
486 		rpcb->cl_auth = nlm_auth;
487 	}
488 
489 	return (rpcb);
490 }
491 
492 /*
493  * This async callback after when an async lock request has been
494  * granted. We notify the host which initiated the request.
495  */
496 static void
497 nlm_lock_callback(void *arg, int pending)
498 {
499 	struct nlm_async_lock *af = (struct nlm_async_lock *) arg;
500 	struct rpc_callextra ext;
501 
502 	if (nlm_debug_level >= 2)
503 		printf("NLM: async lock %p for %s (sysid %d) granted\n",
504 		    af, af->af_host->nh_caller_name,
505 		    af->af_host->nh_sysid);
506 
507 	/*
508 	 * Send the results back to the host.
509 	 *
510 	 * Note: there is a possible race here with nlm_host_notify
511 	 * destroying the RPC client. To avoid problems, the first
512 	 * thing nlm_host_notify does is to cancel pending async lock
513 	 * requests.
514 	 */
515 	memset(&ext, 0, sizeof(ext));
516 	ext.rc_auth = nlm_auth;
517 	if (af->af_host->nh_vers == NLM_VERS4) {
518 		nlm4_granted_msg_4(&af->af_granted,
519 		    NULL, af->af_rpc, &ext, nlm_zero_tv);
520 	} else {
521 		/*
522 		 * Back-convert to legacy protocol
523 		 */
524 		nlm_testargs granted;
525 		granted.cookie = af->af_granted.cookie;
526 		granted.exclusive = af->af_granted.exclusive;
527 		granted.alock.caller_name =
528 			af->af_granted.alock.caller_name;
529 		granted.alock.fh = af->af_granted.alock.fh;
530 		granted.alock.oh = af->af_granted.alock.oh;
531 		granted.alock.svid = af->af_granted.alock.svid;
532 		granted.alock.l_offset =
533 			af->af_granted.alock.l_offset;
534 		granted.alock.l_len =
535 			af->af_granted.alock.l_len;
536 
537 		nlm_granted_msg_1(&granted,
538 		    NULL, af->af_rpc, &ext, nlm_zero_tv);
539 	}
540 
541 	/*
542 	 * Move this entry to the nh_finished list. Someone else will
543 	 * free it later - its too hard to do it here safely without
544 	 * racing with cancel.
545 	 *
546 	 * XXX possibly we should have a third "granted sent but not
547 	 * ack'ed" list so that we can re-send the granted message.
548 	 */
549 	mtx_lock(&af->af_host->nh_lock);
550 	TAILQ_REMOVE(&af->af_host->nh_pending, af, af_link);
551 	TAILQ_INSERT_TAIL(&af->af_host->nh_finished, af, af_link);
552 	mtx_unlock(&af->af_host->nh_lock);
553 }
554 
555 /*
556  * Free an async lock request. The request must have been removed from
557  * any list.
558  */
559 static void
560 nlm_free_async_lock(struct nlm_async_lock *af)
561 {
562 	/*
563 	 * Free an async lock.
564 	 */
565 	if (af->af_rpc)
566 		CLNT_RELEASE(af->af_rpc);
567 	xdr_free((xdrproc_t) xdr_nlm4_testargs, &af->af_granted);
568 	if (af->af_vp)
569 		vrele(af->af_vp);
570 	free(af, M_NLM);
571 }
572 
573 /*
574  * Cancel our async request - this must be called with
575  * af->nh_host->nh_lock held. This is slightly complicated by a
576  * potential race with our own callback. If we fail to cancel the
577  * lock, it must already have been granted - we make sure our async
578  * task has completed by calling taskqueue_drain in this case.
579  */
580 static int
581 nlm_cancel_async_lock(struct nlm_async_lock *af)
582 {
583 	struct nlm_host *host = af->af_host;
584 	int error;
585 
586 	mtx_assert(&host->nh_lock, MA_OWNED);
587 
588 	mtx_unlock(&host->nh_lock);
589 
590 	error = VOP_ADVLOCKASYNC(af->af_vp, NULL, F_CANCEL, &af->af_fl,
591 	    F_REMOTE, NULL, &af->af_cookie);
592 
593 	if (error) {
594 		/*
595 		 * We failed to cancel - make sure our callback has
596 		 * completed before we continue.
597 		 */
598 		taskqueue_drain(taskqueue_thread, &af->af_task);
599 	}
600 
601 	mtx_lock(&host->nh_lock);
602 
603 	if (!error) {
604 		if (nlm_debug_level >= 2)
605 			printf("NLM: async lock %p for %s (sysid %d) "
606 			    "cancelled\n",
607 			    af, host->nh_caller_name, host->nh_sysid);
608 
609 		/*
610 		 * Remove from the nh_pending list and free now that
611 		 * we are safe from the callback.
612 		 */
613 		TAILQ_REMOVE(&host->nh_pending, af, af_link);
614 		mtx_unlock(&host->nh_lock);
615 		nlm_free_async_lock(af);
616 		mtx_lock(&host->nh_lock);
617 	}
618 
619 	return (error);
620 }
621 
622 static void
623 nlm_free_finished_locks(struct nlm_host *host)
624 {
625 	struct nlm_async_lock *af;
626 
627 	mtx_lock(&host->nh_lock);
628 	while ((af = TAILQ_FIRST(&host->nh_finished)) != NULL) {
629 		TAILQ_REMOVE(&host->nh_finished, af, af_link);
630 		mtx_unlock(&host->nh_lock);
631 		nlm_free_async_lock(af);
632 		mtx_lock(&host->nh_lock);
633 	}
634 	mtx_unlock(&host->nh_lock);
635 }
636 
637 /*
638  * Free resources used by a host. This is called after the reference
639  * count has reached zero so it doesn't need to worry about locks.
640  */
641 static void
642 nlm_host_destroy(struct nlm_host *host)
643 {
644 
645 	mtx_lock(&nlm_global_lock);
646 	TAILQ_REMOVE(&nlm_hosts, host, nh_link);
647 	mtx_unlock(&nlm_global_lock);
648 
649 	if (host->nh_rpc)
650 		CLNT_RELEASE(host->nh_rpc);
651 	mtx_destroy(&host->nh_lock);
652 	sysctl_ctx_free(&host->nh_sysctl);
653 	free(host, M_NLM);
654 }
655 
656 /*
657  * Thread start callback for client lock recovery
658  */
659 static void
660 nlm_client_recovery_start(void *arg)
661 {
662 	struct nlm_host *host = (struct nlm_host *) arg;
663 
664 	if (nlm_debug_level >= 1)
665 		printf("NLM: client lock recovery for %s started\n",
666 		    host->nh_caller_name);
667 
668 	nlm_client_recovery(host);
669 
670 	if (nlm_debug_level >= 1)
671 		printf("NLM: client lock recovery for %s completed\n",
672 		    host->nh_caller_name);
673 
674 	host->nh_monstate = NLM_MONITORED;
675 	nlm_host_release(host);
676 
677 	kthread_exit();
678 }
679 
680 /*
681  * This is called when we receive a host state change notification. We
682  * unlock any active locks owned by the host. When rpc.lockd is
683  * shutting down, this function is called with newstate set to zero
684  * which allows us to cancel any pending async locks and clear the
685  * locking state.
686  */
687 static void
688 nlm_host_notify(struct nlm_host *host, int newstate)
689 {
690 	struct nlm_async_lock *af;
691 
692 	if (newstate) {
693 		if (nlm_debug_level >= 1)
694 			printf("NLM: host %s (sysid %d) rebooted, new "
695 			    "state is %d\n",
696 			    host->nh_caller_name, host->nh_sysid, newstate);
697 	}
698 
699 	/*
700 	 * Cancel any pending async locks for this host.
701 	 */
702 	mtx_lock(&host->nh_lock);
703 	while ((af = TAILQ_FIRST(&host->nh_pending)) != NULL) {
704 		/*
705 		 * nlm_cancel_async_lock will remove the entry from
706 		 * nh_pending and free it.
707 		 */
708 		nlm_cancel_async_lock(af);
709 	}
710 	mtx_unlock(&host->nh_lock);
711 	nlm_free_finished_locks(host);
712 
713 	/*
714 	 * The host just rebooted - trash its locks.
715 	 */
716 	lf_clearremotesys(host->nh_sysid);
717 	host->nh_state = newstate;
718 
719 	/*
720 	 * If we have any remote locks for this host (i.e. it
721 	 * represents a remote NFS server that our local NFS client
722 	 * has locks for), start a recovery thread.
723 	 */
724 	if (newstate != 0
725 	    && host->nh_monstate != NLM_RECOVERING
726 	    && lf_countlocks(NLM_SYSID_CLIENT | host->nh_sysid) > 0) {
727 		struct thread *td;
728 		host->nh_monstate = NLM_RECOVERING;
729 		refcount_acquire(&host->nh_refs);
730 		kthread_add(nlm_client_recovery_start, host, curproc, &td, 0, 0,
731 		    "NFS lock recovery for %s", host->nh_caller_name);
732 	}
733 }
734 
735 /*
736  * Sysctl handler to count the number of locks for a sysid.
737  */
738 static int
739 nlm_host_lock_count_sysctl(SYSCTL_HANDLER_ARGS)
740 {
741 	struct nlm_host *host;
742 	int count;
743 
744 	host = oidp->oid_arg1;
745 	count = lf_countlocks(host->nh_sysid);
746 	return sysctl_handle_int(oidp, &count, 0, req);
747 }
748 
749 /*
750  * Sysctl handler to count the number of client locks for a sysid.
751  */
752 static int
753 nlm_host_client_lock_count_sysctl(SYSCTL_HANDLER_ARGS)
754 {
755 	struct nlm_host *host;
756 	int count;
757 
758 	host = oidp->oid_arg1;
759 	count = lf_countlocks(NLM_SYSID_CLIENT | host->nh_sysid);
760 	return sysctl_handle_int(oidp, &count, 0, req);
761 }
762 
763 /*
764  * Create a new NLM host.
765  */
766 static struct nlm_host *
767 nlm_create_host(const char* caller_name)
768 {
769 	struct nlm_host *host;
770 	struct sysctl_oid *oid;
771 
772 	mtx_assert(&nlm_global_lock, MA_OWNED);
773 
774 	if (nlm_debug_level >= 1)
775 		printf("NLM: new host %s (sysid %d)\n",
776 		    caller_name, nlm_next_sysid);
777 	host = malloc(sizeof(struct nlm_host), M_NLM, M_NOWAIT|M_ZERO);
778 	if (!host)
779 		return (NULL);
780 	mtx_init(&host->nh_lock, "nh_lock", NULL, MTX_DEF);
781 	host->nh_refs = 1;
782 	strlcpy(host->nh_caller_name, caller_name, MAXNAMELEN);
783 	host->nh_sysid = nlm_next_sysid++;
784 	snprintf(host->nh_sysid_string, sizeof(host->nh_sysid_string),
785 		"%d", host->nh_sysid);
786 	host->nh_rpc = NULL;
787 	host->nh_vers = 0;
788 	host->nh_state = 0;
789 	host->nh_monstate = NLM_UNMONITORED;
790 	TAILQ_INIT(&host->nh_pending);
791 	TAILQ_INIT(&host->nh_finished);
792 	TAILQ_INSERT_TAIL(&nlm_hosts, host, nh_link);
793 
794 	mtx_unlock(&nlm_global_lock);
795 
796 	sysctl_ctx_init(&host->nh_sysctl);
797 	oid = SYSCTL_ADD_NODE(&host->nh_sysctl,
798 	    SYSCTL_STATIC_CHILDREN(_vfs_nlm_sysid),
799 	    OID_AUTO, host->nh_sysid_string, CTLFLAG_RD, NULL, "");
800 	SYSCTL_ADD_STRING(&host->nh_sysctl, SYSCTL_CHILDREN(oid), OID_AUTO,
801 	    "hostname", CTLFLAG_RD, host->nh_caller_name, 0, "");
802 	SYSCTL_ADD_INT(&host->nh_sysctl, SYSCTL_CHILDREN(oid), OID_AUTO,
803 	    "version", CTLFLAG_RD, &host->nh_vers, 0, "");
804 	SYSCTL_ADD_INT(&host->nh_sysctl, SYSCTL_CHILDREN(oid), OID_AUTO,
805 	    "monitored", CTLFLAG_RD, &host->nh_monstate, 0, "");
806 	SYSCTL_ADD_PROC(&host->nh_sysctl, SYSCTL_CHILDREN(oid), OID_AUTO,
807 	    "lock_count", CTLTYPE_INT | CTLFLAG_RD, host, 0,
808 	    nlm_host_lock_count_sysctl, "I", "");
809 	SYSCTL_ADD_PROC(&host->nh_sysctl, SYSCTL_CHILDREN(oid), OID_AUTO,
810 	    "client_lock_count", CTLTYPE_INT | CTLFLAG_RD, host, 0,
811 	    nlm_host_client_lock_count_sysctl, "I", "");
812 
813 	mtx_lock(&nlm_global_lock);
814 
815 	return (host);
816 }
817 
818 /*
819  * Return non-zero if the address parts of the two sockaddrs are the
820  * same.
821  */
822 static int
823 nlm_compare_addr(const struct sockaddr *a, const struct sockaddr *b)
824 {
825 	const struct sockaddr_in *a4, *b4;
826 #ifdef INET6
827 	const struct sockaddr_in6 *a6, *b6;
828 #endif
829 
830 	if (a->sa_family != b->sa_family)
831 		return (FALSE);
832 
833 	switch (a->sa_family) {
834 	case AF_INET:
835 		a4 = (const struct sockaddr_in *) a;
836 		b4 = (const struct sockaddr_in *) b;
837 		return !memcmp(&a4->sin_addr, &b4->sin_addr,
838 		    sizeof(a4->sin_addr));
839 #ifdef INET6
840 	case AF_INET6:
841 		a6 = (const struct sockaddr_in6 *) a;
842 		b6 = (const struct sockaddr_in6 *) b;
843 		return !memcmp(&a6->sin6_addr, &b6->sin6_addr,
844 		    sizeof(a6->sin6_addr));
845 #endif
846 	}
847 
848 	return (0);
849 }
850 
851 /*
852  * Check for idle hosts and stop monitoring them. We could also free
853  * the host structure here, possibly after a larger timeout but that
854  * would require some care to avoid races with
855  * e.g. nlm_host_lock_count_sysctl.
856  */
857 static void
858 nlm_check_idle(void)
859 {
860 	struct nlm_host *host;
861 
862 	mtx_assert(&nlm_global_lock, MA_OWNED);
863 
864 	if (time_uptime <= nlm_next_idle_check)
865 		return;
866 
867 	nlm_next_idle_check = time_uptime + NLM_IDLE_PERIOD;
868 
869 	TAILQ_FOREACH(host, &nlm_hosts, nh_link) {
870 		if (host->nh_monstate == NLM_MONITORED
871 		    && time_uptime > host->nh_idle_timeout) {
872 			mtx_unlock(&nlm_global_lock);
873 			if (lf_countlocks(host->nh_sysid) > 0
874 			    || lf_countlocks(NLM_SYSID_CLIENT
875 				+ host->nh_sysid)) {
876 				host->nh_idle_timeout =
877 					time_uptime + NLM_IDLE_TIMEOUT;
878 				mtx_lock(&nlm_global_lock);
879 				continue;
880 			}
881 			nlm_host_unmonitor(host);
882 			mtx_lock(&nlm_global_lock);
883 		}
884 	}
885 }
886 
887 /*
888  * Search for an existing NLM host that matches the given name
889  * (typically the caller_name element of an nlm4_lock).  If none is
890  * found, create a new host. If 'addr' is non-NULL, record the remote
891  * address of the host so that we can call it back for async
892  * responses. If 'vers' is greater than zero then record the NLM
893  * program version to use to communicate with this client.
894  */
895 struct nlm_host *
896 nlm_find_host_by_name(const char *name, const struct sockaddr *addr,
897     rpcvers_t vers)
898 {
899 	struct nlm_host *host;
900 
901 	mtx_lock(&nlm_global_lock);
902 
903 	/*
904 	 * The remote host is determined by caller_name.
905 	 */
906 	TAILQ_FOREACH(host, &nlm_hosts, nh_link) {
907 		if (!strcmp(host->nh_caller_name, name))
908 			break;
909 	}
910 
911 	if (!host) {
912 		host = nlm_create_host(name);
913 		if (!host) {
914 			mtx_unlock(&nlm_global_lock);
915 			return (NULL);
916 		}
917 	}
918 	refcount_acquire(&host->nh_refs);
919 
920 	host->nh_idle_timeout = time_uptime + NLM_IDLE_TIMEOUT;
921 
922 	/*
923 	 * If we have an address for the host, record it so that we
924 	 * can send async replies etc.
925 	 */
926 	if (addr) {
927 
928 		KASSERT(addr->sa_len < sizeof(struct sockaddr_storage),
929 		    ("Strange remote transport address length"));
930 
931 		/*
932 		 * If we have seen an address before and we currently
933 		 * have an RPC client handle, make sure the address is
934 		 * the same, otherwise discard the client handle.
935 		 */
936 		if (host->nh_addr.ss_len && host->nh_rpc) {
937 			if (!nlm_compare_addr(
938 				    (struct sockaddr *) &host->nh_addr,
939 				    addr)
940 			    || host->nh_vers != vers) {
941 				CLIENT *client;
942 				mtx_lock(&host->nh_lock);
943 				client = host->nh_rpc;
944 				host->nh_rpc = NULL;
945 				mtx_unlock(&host->nh_lock);
946 				if (client) {
947 					CLNT_RELEASE(client);
948 				}
949 			}
950 		}
951 		memcpy(&host->nh_addr, addr, addr->sa_len);
952 		host->nh_vers = vers;
953 	}
954 
955 	nlm_check_idle();
956 
957 	mtx_unlock(&nlm_global_lock);
958 
959 	return (host);
960 }
961 
962 /*
963  * Search for an existing NLM host that matches the given remote
964  * address. If none is found, create a new host with the requested
965  * address and remember 'vers' as the NLM protocol version to use for
966  * that host.
967  */
968 struct nlm_host *
969 nlm_find_host_by_addr(const struct sockaddr *addr, int vers)
970 {
971 	/*
972 	 * Fake up a name using inet_ntop. This buffer is
973 	 * large enough for an IPv6 address.
974 	 */
975 	char tmp[sizeof "ffff:ffff:ffff:ffff:ffff:ffff:255.255.255.255"];
976 	struct nlm_host *host;
977 
978 	switch (addr->sa_family) {
979 	case AF_INET:
980 		__rpc_inet_ntop(AF_INET,
981 		    &((const struct sockaddr_in *) addr)->sin_addr,
982 		    tmp, sizeof tmp);
983 		break;
984 #ifdef INET6
985 	case AF_INET6:
986 		__rpc_inet_ntop(AF_INET6,
987 		    &((const struct sockaddr_in6 *) addr)->sin6_addr,
988 		    tmp, sizeof tmp);
989 		break;
990 #endif
991 	default:
992 		strcmp(tmp, "<unknown>");
993 	}
994 
995 
996 	mtx_lock(&nlm_global_lock);
997 
998 	/*
999 	 * The remote host is determined by caller_name.
1000 	 */
1001 	TAILQ_FOREACH(host, &nlm_hosts, nh_link) {
1002 		if (nlm_compare_addr(addr,
1003 			(const struct sockaddr *) &host->nh_addr))
1004 			break;
1005 	}
1006 
1007 	if (!host) {
1008 		host = nlm_create_host(tmp);
1009 		if (!host) {
1010 			mtx_unlock(&nlm_global_lock);
1011 			return (NULL);
1012 		}
1013 		memcpy(&host->nh_addr, addr, addr->sa_len);
1014 		host->nh_vers = vers;
1015 	}
1016 	refcount_acquire(&host->nh_refs);
1017 
1018 	host->nh_idle_timeout = time_uptime + NLM_IDLE_TIMEOUT;
1019 
1020 	nlm_check_idle();
1021 
1022 	mtx_unlock(&nlm_global_lock);
1023 
1024 	return (host);
1025 }
1026 
1027 /*
1028  * Find the NLM host that matches the value of 'sysid'. If none
1029  * exists, return NULL.
1030  */
1031 static struct nlm_host *
1032 nlm_find_host_by_sysid(int sysid)
1033 {
1034 	struct nlm_host *host;
1035 
1036 	TAILQ_FOREACH(host, &nlm_hosts, nh_link) {
1037 		if (host->nh_sysid == sysid) {
1038 			refcount_acquire(&host->nh_refs);
1039 			return (host);
1040 		}
1041 	}
1042 
1043 	return (NULL);
1044 }
1045 
1046 void nlm_host_release(struct nlm_host *host)
1047 {
1048 	if (refcount_release(&host->nh_refs)) {
1049 		/*
1050 		 * Free the host
1051 		 */
1052 		nlm_host_destroy(host);
1053 	}
1054 }
1055 
1056 /*
1057  * Unregister this NLM host with the local NSM due to idleness.
1058  */
1059 static void
1060 nlm_host_unmonitor(struct nlm_host *host)
1061 {
1062 	mon_id smmonid;
1063 	sm_stat_res smstat;
1064 	struct timeval timo;
1065 	enum clnt_stat stat;
1066 
1067 	if (nlm_debug_level >= 1)
1068 		printf("NLM: unmonitoring %s (sysid %d)\n",
1069 		    host->nh_caller_name, host->nh_sysid);
1070 
1071 	/*
1072 	 * We put our assigned system ID value in the priv field to
1073 	 * make it simpler to find the host if we are notified of a
1074 	 * host restart.
1075 	 */
1076 	smmonid.mon_name = host->nh_caller_name;
1077 	smmonid.my_id.my_name = "localhost";
1078 	smmonid.my_id.my_prog = NLM_PROG;
1079 	smmonid.my_id.my_vers = NLM_SM;
1080 	smmonid.my_id.my_proc = NLM_SM_NOTIFY;
1081 
1082 	timo.tv_sec = 25;
1083 	timo.tv_usec = 0;
1084 	stat = CLNT_CALL(nlm_nsm, SM_UNMON,
1085 	    (xdrproc_t) xdr_mon, &smmonid,
1086 	    (xdrproc_t) xdr_sm_stat, &smstat, timo);
1087 
1088 	if (stat != RPC_SUCCESS) {
1089 		printf("Failed to contact local NSM - rpc error %d\n", stat);
1090 		return;
1091 	}
1092 	if (smstat.res_stat == stat_fail) {
1093 		printf("Local NSM refuses to unmonitor %s\n",
1094 		    host->nh_caller_name);
1095 		return;
1096 	}
1097 
1098 	host->nh_monstate = NLM_UNMONITORED;
1099 }
1100 
1101 /*
1102  * Register this NLM host with the local NSM so that we can be
1103  * notified if it reboots.
1104  */
1105 void
1106 nlm_host_monitor(struct nlm_host *host, int state)
1107 {
1108 	mon smmon;
1109 	sm_stat_res smstat;
1110 	struct timeval timo;
1111 	enum clnt_stat stat;
1112 
1113 	if (state && !host->nh_state) {
1114 		/*
1115 		 * This is the first time we have seen an NSM state
1116 		 * value for this host. We record it here to help
1117 		 * detect host reboots.
1118 		 */
1119 		host->nh_state = state;
1120 		if (nlm_debug_level >= 1)
1121 			printf("NLM: host %s (sysid %d) has NSM state %d\n",
1122 			    host->nh_caller_name, host->nh_sysid, state);
1123 	}
1124 
1125 	mtx_lock(&host->nh_lock);
1126 	if (host->nh_monstate != NLM_UNMONITORED) {
1127 		mtx_unlock(&host->nh_lock);
1128 		return;
1129 	}
1130 	host->nh_monstate = NLM_MONITORED;
1131 	mtx_unlock(&host->nh_lock);
1132 
1133 	if (nlm_debug_level >= 1)
1134 		printf("NLM: monitoring %s (sysid %d)\n",
1135 		    host->nh_caller_name, host->nh_sysid);
1136 
1137 	/*
1138 	 * We put our assigned system ID value in the priv field to
1139 	 * make it simpler to find the host if we are notified of a
1140 	 * host restart.
1141 	 */
1142 	smmon.mon_id.mon_name = host->nh_caller_name;
1143 	smmon.mon_id.my_id.my_name = "localhost";
1144 	smmon.mon_id.my_id.my_prog = NLM_PROG;
1145 	smmon.mon_id.my_id.my_vers = NLM_SM;
1146 	smmon.mon_id.my_id.my_proc = NLM_SM_NOTIFY;
1147 	memcpy(smmon.priv, &host->nh_sysid, sizeof(host->nh_sysid));
1148 
1149 	timo.tv_sec = 25;
1150 	timo.tv_usec = 0;
1151 	stat = CLNT_CALL(nlm_nsm, SM_MON,
1152 	    (xdrproc_t) xdr_mon, &smmon,
1153 	    (xdrproc_t) xdr_sm_stat, &smstat, timo);
1154 
1155 	if (stat != RPC_SUCCESS) {
1156 		printf("Failed to contact local NSM - rpc error %d\n", stat);
1157 		return;
1158 	}
1159 	if (smstat.res_stat == stat_fail) {
1160 		printf("Local NSM refuses to monitor %s\n",
1161 		    host->nh_caller_name);
1162 		mtx_lock(&host->nh_lock);
1163 		host->nh_monstate = NLM_MONITOR_FAILED;
1164 		mtx_unlock(&host->nh_lock);
1165 		return;
1166 	}
1167 
1168 	host->nh_monstate = NLM_MONITORED;
1169 }
1170 
1171 /*
1172  * Return an RPC client handle that can be used to talk to the NLM
1173  * running on the given host.
1174  */
1175 CLIENT *
1176 nlm_host_get_rpc(struct nlm_host *host)
1177 {
1178 	CLIENT *client;
1179 
1180 	mtx_lock(&host->nh_lock);
1181 
1182 	/*
1183 	 * We can't hold onto RPC handles for too long - the async
1184 	 * call/reply protocol used by some NLM clients makes it hard
1185 	 * to tell when they change port numbers (e.g. after a
1186 	 * reboot). Note that if a client reboots while it isn't
1187 	 * holding any locks, it won't bother to notify us. We
1188 	 * expire the RPC handles after two minutes.
1189 	 */
1190 	if (host->nh_rpc && time_uptime > host->nh_rpc_create_time + 2*60) {
1191 		client = host->nh_rpc;
1192 		host->nh_rpc = NULL;
1193 		mtx_unlock(&host->nh_lock);
1194 		CLNT_RELEASE(client);
1195 		mtx_lock(&host->nh_lock);
1196 	}
1197 
1198 	if (!host->nh_rpc) {
1199 		mtx_unlock(&host->nh_lock);
1200 		client = nlm_get_rpc((struct sockaddr *)&host->nh_addr,
1201 		    NLM_PROG, host->nh_vers);
1202 		mtx_lock(&host->nh_lock);
1203 
1204 		if (client) {
1205 			if (host->nh_rpc) {
1206 				mtx_unlock(&host->nh_lock);
1207 				CLNT_DESTROY(client);
1208 				mtx_lock(&host->nh_lock);
1209 			} else {
1210 				host->nh_rpc = client;
1211 				host->nh_rpc_create_time = time_uptime;
1212 			}
1213 		}
1214 	}
1215 
1216 	client = host->nh_rpc;
1217 	if (client)
1218 		CLNT_ACQUIRE(client);
1219 	mtx_unlock(&host->nh_lock);
1220 
1221 	return (client);
1222 
1223 }
1224 
1225 int nlm_host_get_sysid(struct nlm_host *host)
1226 {
1227 
1228 	return (host->nh_sysid);
1229 }
1230 
1231 int
1232 nlm_host_get_state(struct nlm_host *host)
1233 {
1234 
1235 	return (host->nh_state);
1236 }
1237 
1238 void *
1239 nlm_register_wait_lock(struct nlm4_lock *lock, struct vnode *vp)
1240 {
1241 	struct nlm_waiting_lock *nw;
1242 
1243 	nw = malloc(sizeof(struct nlm_waiting_lock), M_NLM, M_WAITOK);
1244 	nw->nw_lock = *lock;
1245 	memcpy(&nw->nw_fh.fh_bytes, nw->nw_lock.fh.n_bytes,
1246 	    nw->nw_lock.fh.n_len);
1247 	nw->nw_lock.fh.n_bytes = nw->nw_fh.fh_bytes;
1248 	nw->nw_waiting = TRUE;
1249 	nw->nw_vp = vp;
1250 	mtx_lock(&nlm_global_lock);
1251 	TAILQ_INSERT_TAIL(&nlm_waiting_locks, nw, nw_link);
1252 	mtx_unlock(&nlm_global_lock);
1253 
1254 	return nw;
1255 }
1256 
1257 void
1258 nlm_deregister_wait_lock(void *handle)
1259 {
1260 	struct nlm_waiting_lock *nw = handle;
1261 
1262 	mtx_lock(&nlm_global_lock);
1263 	TAILQ_REMOVE(&nlm_waiting_locks, nw, nw_link);
1264 	mtx_unlock(&nlm_global_lock);
1265 
1266 	free(nw, M_NLM);
1267 }
1268 
1269 int
1270 nlm_wait_lock(void *handle, int timo)
1271 {
1272 	struct nlm_waiting_lock *nw = handle;
1273 	int error;
1274 
1275 	/*
1276 	 * If the granted message arrived before we got here,
1277 	 * nw->nw_waiting will be FALSE - in that case, don't sleep.
1278 	 */
1279 	mtx_lock(&nlm_global_lock);
1280 	error = 0;
1281 	if (nw->nw_waiting)
1282 		error = msleep(nw, &nlm_global_lock, PCATCH, "nlmlock", timo);
1283 	TAILQ_REMOVE(&nlm_waiting_locks, nw, nw_link);
1284 	if (error) {
1285 		/*
1286 		 * The granted message may arrive after the
1287 		 * interrupt/timeout but before we manage to lock the
1288 		 * mutex. Detect this by examining nw_lock.
1289 		 */
1290 		if (!nw->nw_waiting)
1291 			error = 0;
1292 	} else {
1293 		/*
1294 		 * If nlm_cancel_wait is called, then error will be
1295 		 * zero but nw_waiting will still be TRUE. We
1296 		 * translate this into EINTR.
1297 		 */
1298 		if (nw->nw_waiting)
1299 			error = EINTR;
1300 	}
1301 	mtx_unlock(&nlm_global_lock);
1302 
1303 	free(nw, M_NLM);
1304 
1305 	return (error);
1306 }
1307 
1308 void
1309 nlm_cancel_wait(struct vnode *vp)
1310 {
1311 	struct nlm_waiting_lock *nw;
1312 
1313 	mtx_lock(&nlm_global_lock);
1314 	TAILQ_FOREACH(nw, &nlm_waiting_locks, nw_link) {
1315 		if (nw->nw_vp == vp) {
1316 			wakeup(nw);
1317 		}
1318 	}
1319 	mtx_unlock(&nlm_global_lock);
1320 }
1321 
1322 
1323 /**********************************************************************/
1324 
1325 /*
1326  * Syscall interface with userland.
1327  */
1328 
1329 extern void nlm_prog_0(struct svc_req *rqstp, SVCXPRT *transp);
1330 extern void nlm_prog_1(struct svc_req *rqstp, SVCXPRT *transp);
1331 extern void nlm_prog_3(struct svc_req *rqstp, SVCXPRT *transp);
1332 extern void nlm_prog_4(struct svc_req *rqstp, SVCXPRT *transp);
1333 
1334 static int
1335 nlm_register_services(SVCPOOL *pool, int addr_count, char **addrs)
1336 {
1337 	static rpcvers_t versions[] = {
1338 		NLM_SM, NLM_VERS, NLM_VERSX, NLM_VERS4
1339 	};
1340 	static void (*dispatchers[])(struct svc_req *, SVCXPRT *) = {
1341 		nlm_prog_0, nlm_prog_1, nlm_prog_3, nlm_prog_4
1342 	};
1343 	static const int version_count = sizeof(versions) / sizeof(versions[0]);
1344 
1345 	SVCXPRT **xprts;
1346 	char netid[16];
1347 	char uaddr[128];
1348 	struct netconfig *nconf;
1349 	int i, j, error;
1350 
1351 	if (!addr_count) {
1352 		printf("NLM: no service addresses given - can't start server");
1353 		return (EINVAL);
1354 	}
1355 
1356 	xprts = malloc(addr_count * sizeof(SVCXPRT *), M_NLM, M_WAITOK);
1357 	for (i = 0; i < version_count; i++) {
1358 		for (j = 0; j < addr_count; j++) {
1359 			/*
1360 			 * Create transports for the first version and
1361 			 * then just register everything else to the
1362 			 * same transports.
1363 			 */
1364 			if (i == 0) {
1365 				char *up;
1366 
1367 				error = copyin(&addrs[2*j], &up,
1368 				    sizeof(char*));
1369 				if (error)
1370 					goto out;
1371 				error = copyinstr(up, netid, sizeof(netid),
1372 				    NULL);
1373 				if (error)
1374 					goto out;
1375 				error = copyin(&addrs[2*j+1], &up,
1376 				    sizeof(char*));
1377 				if (error)
1378 					goto out;
1379 				error = copyinstr(up, uaddr, sizeof(uaddr),
1380 				    NULL);
1381 				if (error)
1382 					goto out;
1383 				nconf = getnetconfigent(netid);
1384 				if (!nconf) {
1385 					printf("Can't lookup netid %s\n",
1386 					    netid);
1387 					error = EINVAL;
1388 					goto out;
1389 				}
1390 				xprts[j] = svc_tp_create(pool, dispatchers[i],
1391 				    NLM_PROG, versions[i], uaddr, nconf);
1392 				if (!xprts[j]) {
1393 					printf("NLM: unable to create "
1394 					    "(NLM_PROG, %d).\n", versions[i]);
1395 					error = EINVAL;
1396 					goto out;
1397 				}
1398 				freenetconfigent(nconf);
1399 			} else {
1400 				nconf = getnetconfigent(xprts[j]->xp_netid);
1401 				rpcb_unset(NLM_PROG, versions[i], nconf);
1402 				if (!svc_reg(xprts[j], NLM_PROG, versions[i],
1403 					dispatchers[i], nconf)) {
1404 					printf("NLM: can't register "
1405 					    "(NLM_PROG, %d)\n", versions[i]);
1406 					error = EINVAL;
1407 					goto out;
1408 				}
1409 			}
1410 		}
1411 	}
1412 	error = 0;
1413 out:
1414 	free(xprts, M_NLM);
1415 	return (error);
1416 }
1417 
1418 /*
1419  * Main server entry point. Contacts the local NSM to get its current
1420  * state and send SM_UNMON_ALL. Registers the NLM services and then
1421  * services requests. Does not return until the server is interrupted
1422  * by a signal.
1423  */
1424 static int
1425 nlm_server_main(int addr_count, char **addrs)
1426 {
1427 	struct thread *td = curthread;
1428 	int error;
1429 	SVCPOOL *pool = NULL;
1430 	struct sockopt opt;
1431 	int portlow;
1432 #ifdef INET6
1433 	struct sockaddr_in6 sin6;
1434 #endif
1435 	struct sockaddr_in sin;
1436 	my_id id;
1437 	sm_stat smstat;
1438 	struct timeval timo;
1439 	enum clnt_stat stat;
1440 	struct nlm_host *host, *nhost;
1441 	struct nlm_waiting_lock *nw;
1442 	vop_advlock_t *old_nfs_advlock;
1443 	vop_reclaim_t *old_nfs_reclaim;
1444 	int v4_used;
1445 #ifdef INET6
1446 	int v6_used;
1447 #endif
1448 
1449 	if (nlm_socket) {
1450 		printf("NLM: can't start server - it appears to be running already\n");
1451 		return (EPERM);
1452 	}
1453 
1454 	memset(&opt, 0, sizeof(opt));
1455 
1456 	nlm_socket = NULL;
1457 	error = socreate(AF_INET, &nlm_socket, SOCK_DGRAM, 0,
1458 	    td->td_ucred, td);
1459 	if (error) {
1460 		printf("NLM: can't create IPv4 socket - error %d\n", error);
1461 		return (error);
1462 	}
1463 	opt.sopt_dir = SOPT_SET;
1464 	opt.sopt_level = IPPROTO_IP;
1465 	opt.sopt_name = IP_PORTRANGE;
1466 	portlow = IP_PORTRANGE_LOW;
1467 	opt.sopt_val = &portlow;
1468 	opt.sopt_valsize = sizeof(portlow);
1469 	sosetopt(nlm_socket, &opt);
1470 
1471 #ifdef INET6
1472 	nlm_socket6 = NULL;
1473 	error = socreate(AF_INET6, &nlm_socket6, SOCK_DGRAM, 0,
1474 	    td->td_ucred, td);
1475 	if (error) {
1476 		printf("NLM: can't create IPv6 socket - error %d\n", error);
1477 		goto out;
1478 		return (error);
1479 	}
1480 	opt.sopt_dir = SOPT_SET;
1481 	opt.sopt_level = IPPROTO_IPV6;
1482 	opt.sopt_name = IPV6_PORTRANGE;
1483 	portlow = IPV6_PORTRANGE_LOW;
1484 	opt.sopt_val = &portlow;
1485 	opt.sopt_valsize = sizeof(portlow);
1486 	sosetopt(nlm_socket6, &opt);
1487 #endif
1488 
1489 	nlm_auth = authunix_create(curthread->td_ucred);
1490 
1491 #ifdef INET6
1492 	memset(&sin6, 0, sizeof(sin6));
1493 	sin6.sin6_len = sizeof(sin6);
1494 	sin6.sin6_family = AF_INET6;
1495 	sin6.sin6_addr = in6addr_loopback;
1496 	nlm_nsm = nlm_get_rpc((struct sockaddr *) &sin6, SM_PROG, SM_VERS);
1497 	if (!nlm_nsm) {
1498 #endif
1499 		memset(&sin, 0, sizeof(sin));
1500 		sin.sin_len = sizeof(sin);
1501 		sin.sin_family = AF_INET;
1502 		sin.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
1503 		nlm_nsm = nlm_get_rpc((struct sockaddr *) &sin, SM_PROG,
1504 		    SM_VERS);
1505 #ifdef INET6
1506 	}
1507 #endif
1508 
1509 	if (!nlm_nsm) {
1510 		printf("Can't start NLM - unable to contact NSM\n");
1511 		error = EINVAL;
1512 		goto out;
1513 	}
1514 
1515 	pool = svcpool_create();
1516 
1517 	error = nlm_register_services(pool, addr_count, addrs);
1518 	if (error)
1519 		goto out;
1520 
1521 	memset(&id, 0, sizeof(id));
1522 	id.my_name = "NFS NLM";
1523 
1524 	timo.tv_sec = 25;
1525 	timo.tv_usec = 0;
1526 	stat = CLNT_CALL(nlm_nsm, SM_UNMON_ALL,
1527 	    (xdrproc_t) xdr_my_id, &id,
1528 	    (xdrproc_t) xdr_sm_stat, &smstat, timo);
1529 
1530 	if (stat != RPC_SUCCESS) {
1531 		struct rpc_err err;
1532 
1533 		CLNT_GETERR(nlm_nsm, &err);
1534 		printf("NLM: unexpected error contacting NSM, stat=%d, errno=%d\n",
1535 		    stat, err.re_errno);
1536 		error = EINVAL;
1537 		goto out;
1538 	}
1539 
1540 	if (nlm_debug_level >= 1)
1541 		printf("NLM: local NSM state is %d\n", smstat.state);
1542 	nlm_nsm_state = smstat.state;
1543 
1544 	old_nfs_advlock = nfs_advlock_p;
1545 	nfs_advlock_p = nlm_advlock;
1546 	old_nfs_reclaim = nfs_reclaim_p;
1547 	nfs_reclaim_p = nlm_reclaim;
1548 
1549 	svc_run(pool);
1550 	error = 0;
1551 
1552 	nfs_advlock_p = old_nfs_advlock;
1553 	nfs_reclaim_p = old_nfs_reclaim;
1554 
1555 out:
1556 	if (pool)
1557 		svcpool_destroy(pool);
1558 
1559 	/*
1560 	 * We are finished communicating with the NSM.
1561 	 */
1562 	if (nlm_nsm) {
1563 		CLNT_RELEASE(nlm_nsm);
1564 		nlm_nsm = NULL;
1565 	}
1566 
1567 	/*
1568 	 * Trash all the existing state so that if the server
1569 	 * restarts, it gets a clean slate. This is complicated by the
1570 	 * possibility that there may be other threads trying to make
1571 	 * client locking requests.
1572 	 *
1573 	 * First we fake a client reboot notification which will
1574 	 * cancel any pending async locks and purge remote lock state
1575 	 * from the local lock manager. We release the reference from
1576 	 * nlm_hosts to the host (which may remove it from the list
1577 	 * and free it). After this phase, the only entries in the
1578 	 * nlm_host list should be from other threads performing
1579 	 * client lock requests. We arrange to defer closing the
1580 	 * sockets until the last RPC client handle is released.
1581 	 */
1582 	v4_used = 0;
1583 #ifdef INET6
1584 	v6_used = 0;
1585 #endif
1586 	mtx_lock(&nlm_global_lock);
1587 	TAILQ_FOREACH(nw, &nlm_waiting_locks, nw_link) {
1588 		wakeup(nw);
1589 	}
1590 	TAILQ_FOREACH_SAFE(host, &nlm_hosts, nh_link, nhost) {
1591 		mtx_unlock(&nlm_global_lock);
1592 		nlm_host_notify(host, 0);
1593 		nlm_host_release(host);
1594 		mtx_lock(&nlm_global_lock);
1595 	}
1596 	TAILQ_FOREACH_SAFE(host, &nlm_hosts, nh_link, nhost) {
1597 		mtx_lock(&host->nh_lock);
1598 		if (host->nh_rpc) {
1599 			if (host->nh_addr.ss_family == AF_INET)
1600 				v4_used++;
1601 #ifdef INET6
1602 			if (host->nh_addr.ss_family == AF_INET6)
1603 				v6_used++;
1604 #endif
1605 			/*
1606 			 * Note that the rpc over udp code copes
1607 			 * correctly with the fact that a socket may
1608 			 * be used by many rpc handles.
1609 			 */
1610 			CLNT_CONTROL(host->nh_rpc, CLSET_FD_CLOSE, 0);
1611 		}
1612 		mtx_unlock(&host->nh_lock);
1613 	}
1614 	mtx_unlock(&nlm_global_lock);
1615 
1616 	AUTH_DESTROY(nlm_auth);
1617 
1618 	if (!v4_used)
1619 		soclose(nlm_socket);
1620 	nlm_socket = NULL;
1621 #ifdef INET6
1622 	if (!v6_used)
1623 		soclose(nlm_socket6);
1624 	nlm_socket6 = NULL;
1625 #endif
1626 
1627 	return (error);
1628 }
1629 
1630 int
1631 nlm_syscall(struct thread *td, struct nlm_syscall_args *uap)
1632 {
1633 	int error;
1634 
1635 #if __FreeBSD_version >= 700000
1636 	error = priv_check(td, PRIV_NFS_LOCKD);
1637 #else
1638 	error = suser(td);
1639 #endif
1640 	if (error)
1641 		return (error);
1642 
1643 	nlm_debug_level = uap->debug_level;
1644 	nlm_grace_threshold = time_uptime + uap->grace_period;
1645 	nlm_next_idle_check = time_uptime + NLM_IDLE_PERIOD;
1646 
1647 	return nlm_server_main(uap->addr_count, uap->addrs);
1648 }
1649 
1650 /**********************************************************************/
1651 
1652 /*
1653  * NLM implementation details, called from the RPC stubs.
1654  */
1655 
1656 
1657 void
1658 nlm_sm_notify(struct nlm_sm_status *argp)
1659 {
1660 	uint32_t sysid;
1661 	struct nlm_host *host;
1662 
1663 	if (nlm_debug_level >= 3)
1664 		printf("nlm_sm_notify(): mon_name = %s\n", argp->mon_name);
1665 	memcpy(&sysid, &argp->priv, sizeof(sysid));
1666 	host = nlm_find_host_by_sysid(sysid);
1667 	if (host) {
1668 		nlm_host_notify(host, argp->state);
1669 		nlm_host_release(host);
1670 	}
1671 }
1672 
1673 static void
1674 nlm_convert_to_fhandle_t(fhandle_t *fhp, struct netobj *p)
1675 {
1676 	memcpy(fhp, p->n_bytes, sizeof(fhandle_t));
1677 }
1678 
1679 struct vfs_state {
1680 	struct mount	*vs_mp;
1681 	struct vnode	*vs_vp;
1682 	int		vs_vfslocked;
1683 	int		vs_vnlocked;
1684 };
1685 
1686 static int
1687 nlm_get_vfs_state(struct nlm_host *host, struct svc_req *rqstp,
1688     fhandle_t *fhp, struct vfs_state *vs)
1689 {
1690 	int error, exflags, freecred;
1691 	struct ucred *cred = NULL, *credanon;
1692 
1693 	memset(vs, 0, sizeof(*vs));
1694 	freecred = FALSE;
1695 
1696 	vs->vs_mp = vfs_getvfs(&fhp->fh_fsid);
1697 	if (!vs->vs_mp) {
1698 		return (ESTALE);
1699 	}
1700 	vs->vs_vfslocked = VFS_LOCK_GIANT(vs->vs_mp);
1701 
1702 	error = VFS_CHECKEXP(vs->vs_mp, (struct sockaddr *)&host->nh_addr,
1703 	    &exflags, &credanon);
1704 	if (error)
1705 		goto out;
1706 
1707 	if (exflags & MNT_EXRDONLY || (vs->vs_mp->mnt_flag & MNT_RDONLY)) {
1708 		error = EROFS;
1709 		goto out;
1710 	}
1711 
1712 	error = VFS_FHTOVP(vs->vs_mp, &fhp->fh_fid, &vs->vs_vp);
1713 	if (error)
1714 		goto out;
1715 	vs->vs_vnlocked = TRUE;
1716 
1717 	cred = crget();
1718 	freecred = TRUE;
1719 	if (!svc_getcred(rqstp, cred, NULL)) {
1720 		error = EINVAL;
1721 		goto out;
1722 	}
1723 	if (cred->cr_uid == 0 || (exflags & MNT_EXPORTANON)) {
1724 		crfree(cred);
1725 		cred = credanon;
1726 		freecred = FALSE;
1727 	}
1728 
1729 	/*
1730 	 * Check cred.
1731 	 */
1732 	error = VOP_ACCESS(vs->vs_vp, VWRITE, cred, curthread);
1733 	if (error)
1734 		goto out;
1735 
1736 #if __FreeBSD_version < 800011
1737 	VOP_UNLOCK(vs->vs_vp, 0, curthread);
1738 #else
1739 	VOP_UNLOCK(vs->vs_vp, 0);
1740 #endif
1741 	vs->vs_vnlocked = FALSE;
1742 
1743 out:
1744 	if (freecred)
1745 		crfree(cred);
1746 
1747 	return (error);
1748 }
1749 
1750 static void
1751 nlm_release_vfs_state(struct vfs_state *vs)
1752 {
1753 
1754 	if (vs->vs_vp) {
1755 		if (vs->vs_vnlocked)
1756 			vput(vs->vs_vp);
1757 		else
1758 			vrele(vs->vs_vp);
1759 	}
1760 	if (vs->vs_mp)
1761 		vfs_rel(vs->vs_mp);
1762 	VFS_UNLOCK_GIANT(vs->vs_vfslocked);
1763 }
1764 
1765 static nlm4_stats
1766 nlm_convert_error(int error)
1767 {
1768 
1769 	if (error == ESTALE)
1770 		return nlm4_stale_fh;
1771 	else if (error == EROFS)
1772 		return nlm4_rofs;
1773 	else
1774 		return nlm4_failed;
1775 }
1776 
1777 int
1778 nlm_do_test(nlm4_testargs *argp, nlm4_testres *result, struct svc_req *rqstp,
1779 	CLIENT **rpcp)
1780 {
1781 	fhandle_t fh;
1782 	struct vfs_state vs;
1783 	struct nlm_host *host, *bhost;
1784 	int error, sysid;
1785 	struct flock fl;
1786 
1787 	memset(result, 0, sizeof(*result));
1788 	memset(&vs, 0, sizeof(vs));
1789 
1790 	host = nlm_find_host_by_name(argp->alock.caller_name,
1791 	    (struct sockaddr *) rqstp->rq_xprt->xp_rtaddr.buf, rqstp->rq_vers);
1792 	if (!host) {
1793 		result->stat.stat = nlm4_denied_nolocks;
1794 		return (ENOMEM);
1795 	}
1796 
1797 	if (nlm_debug_level >= 3)
1798 		printf("nlm_do_test(): caller_name = %s (sysid = %d)\n",
1799 		    host->nh_caller_name, host->nh_sysid);
1800 
1801 	nlm_free_finished_locks(host);
1802 	sysid = host->nh_sysid;
1803 
1804 	nlm_convert_to_fhandle_t(&fh, &argp->alock.fh);
1805 	nlm_copy_netobj(&result->cookie, &argp->cookie, M_RPC);
1806 
1807 	if (time_uptime < nlm_grace_threshold) {
1808 		result->stat.stat = nlm4_denied_grace_period;
1809 		goto out;
1810 	}
1811 
1812 	error = nlm_get_vfs_state(host, rqstp, &fh, &vs);
1813 	if (error) {
1814 		result->stat.stat = nlm_convert_error(error);
1815 		goto out;
1816 	}
1817 
1818 	fl.l_start = argp->alock.l_offset;
1819 	fl.l_len = argp->alock.l_len;
1820 	fl.l_pid = argp->alock.svid;
1821 	fl.l_sysid = sysid;
1822 	fl.l_whence = SEEK_SET;
1823 	if (argp->exclusive)
1824 		fl.l_type = F_WRLCK;
1825 	else
1826 		fl.l_type = F_RDLCK;
1827 	error = VOP_ADVLOCK(vs.vs_vp, NULL, F_GETLK, &fl, F_REMOTE);
1828 	if (error) {
1829 		result->stat.stat = nlm4_failed;
1830 		goto out;
1831 	}
1832 
1833 	if (fl.l_type == F_UNLCK) {
1834 		result->stat.stat = nlm4_granted;
1835 	} else {
1836 		result->stat.stat = nlm4_denied;
1837 		result->stat.nlm4_testrply_u.holder.exclusive =
1838 			(fl.l_type == F_WRLCK);
1839 		result->stat.nlm4_testrply_u.holder.svid = fl.l_pid;
1840 		bhost = nlm_find_host_by_sysid(fl.l_sysid);
1841 		if (bhost) {
1842 			/*
1843 			 * We don't have any useful way of recording
1844 			 * the value of oh used in the original lock
1845 			 * request. Ideally, the test reply would have
1846 			 * a space for the owning host's name allowing
1847 			 * our caller's NLM to keep track.
1848 			 *
1849 			 * As far as I can see, Solaris uses an eight
1850 			 * byte structure for oh which contains a four
1851 			 * byte pid encoded in local byte order and
1852 			 * the first four bytes of the host
1853 			 * name. Linux uses a variable length string
1854 			 * 'pid@hostname' in ascii but doesn't even
1855 			 * return that in test replies.
1856 			 *
1857 			 * For the moment, return nothing in oh
1858 			 * (already zero'ed above).
1859 			 */
1860 			nlm_host_release(bhost);
1861 		}
1862 		result->stat.nlm4_testrply_u.holder.l_offset = fl.l_start;
1863 		result->stat.nlm4_testrply_u.holder.l_len = fl.l_len;
1864 	}
1865 
1866 out:
1867 	nlm_release_vfs_state(&vs);
1868 	if (rpcp)
1869 		*rpcp = nlm_host_get_rpc(host);
1870 	nlm_host_release(host);
1871 	return (0);
1872 }
1873 
1874 int
1875 nlm_do_lock(nlm4_lockargs *argp, nlm4_res *result, struct svc_req *rqstp,
1876     bool_t monitor, CLIENT **rpcp)
1877 {
1878 	fhandle_t fh;
1879 	struct vfs_state vs;
1880 	struct nlm_host *host;
1881 	int error, sysid;
1882 	struct flock fl;
1883 
1884 	memset(result, 0, sizeof(*result));
1885 	memset(&vs, 0, sizeof(vs));
1886 
1887 	host = nlm_find_host_by_name(argp->alock.caller_name,
1888 	    (struct sockaddr *) rqstp->rq_xprt->xp_rtaddr.buf, rqstp->rq_vers);
1889 	if (!host) {
1890 		result->stat.stat = nlm4_denied_nolocks;
1891 		return (ENOMEM);
1892 	}
1893 
1894 	if (nlm_debug_level >= 3)
1895 		printf("nlm_do_lock(): caller_name = %s (sysid = %d)\n",
1896 		    host->nh_caller_name, host->nh_sysid);
1897 
1898 	if (monitor && host->nh_state && argp->state
1899 	    && host->nh_state != argp->state) {
1900 		/*
1901 		 * The host rebooted without telling us. Trash its
1902 		 * locks.
1903 		 */
1904 		nlm_host_notify(host, argp->state);
1905 	}
1906 
1907 	nlm_free_finished_locks(host);
1908 	sysid = host->nh_sysid;
1909 
1910 	nlm_convert_to_fhandle_t(&fh, &argp->alock.fh);
1911 	nlm_copy_netobj(&result->cookie, &argp->cookie, M_RPC);
1912 
1913 	if (time_uptime < nlm_grace_threshold && !argp->reclaim) {
1914 		result->stat.stat = nlm4_denied_grace_period;
1915 		goto out;
1916 	}
1917 
1918 	error = nlm_get_vfs_state(host, rqstp, &fh, &vs);
1919 	if (error) {
1920 		result->stat.stat = nlm_convert_error(error);
1921 		goto out;
1922 	}
1923 
1924 	fl.l_start = argp->alock.l_offset;
1925 	fl.l_len = argp->alock.l_len;
1926 	fl.l_pid = argp->alock.svid;
1927 	fl.l_sysid = sysid;
1928 	fl.l_whence = SEEK_SET;
1929 	if (argp->exclusive)
1930 		fl.l_type = F_WRLCK;
1931 	else
1932 		fl.l_type = F_RDLCK;
1933 	if (argp->block) {
1934 		struct nlm_async_lock *af;
1935 		CLIENT *client;
1936 
1937 		/*
1938 		 * First, make sure we can contact the host's NLM.
1939 		 */
1940 		client = nlm_host_get_rpc(host);
1941 		if (!client) {
1942 			result->stat.stat = nlm4_failed;
1943 			goto out;
1944 		}
1945 
1946 		/*
1947 		 * First we need to check and see if there is an
1948 		 * existing blocked lock that matches. This could be a
1949 		 * badly behaved client or an RPC re-send. If we find
1950 		 * one, just return nlm4_blocked.
1951 		 */
1952 		mtx_lock(&host->nh_lock);
1953 		TAILQ_FOREACH(af, &host->nh_pending, af_link) {
1954 			if (af->af_fl.l_start == fl.l_start
1955 			    && af->af_fl.l_len == fl.l_len
1956 			    && af->af_fl.l_pid == fl.l_pid
1957 			    && af->af_fl.l_type == fl.l_type) {
1958 				break;
1959 			}
1960 		}
1961 		mtx_unlock(&host->nh_lock);
1962 		if (af) {
1963 			CLNT_RELEASE(client);
1964 			result->stat.stat = nlm4_blocked;
1965 			goto out;
1966 		}
1967 
1968 		af = malloc(sizeof(struct nlm_async_lock), M_NLM,
1969 		    M_WAITOK|M_ZERO);
1970 		TASK_INIT(&af->af_task, 0, nlm_lock_callback, af);
1971 		af->af_vp = vs.vs_vp;
1972 		af->af_fl = fl;
1973 		af->af_host = host;
1974 		af->af_rpc = client;
1975 		/*
1976 		 * We use M_RPC here so that we can xdr_free the thing
1977 		 * later.
1978 		 */
1979 		af->af_granted.exclusive = argp->exclusive;
1980 		af->af_granted.alock.caller_name =
1981 			strdup(argp->alock.caller_name, M_RPC);
1982 		nlm_copy_netobj(&af->af_granted.alock.fh,
1983 		    &argp->alock.fh, M_RPC);
1984 		nlm_copy_netobj(&af->af_granted.alock.oh,
1985 		    &argp->alock.oh, M_RPC);
1986 		af->af_granted.alock.svid = argp->alock.svid;
1987 		af->af_granted.alock.l_offset = argp->alock.l_offset;
1988 		af->af_granted.alock.l_len = argp->alock.l_len;
1989 
1990 		/*
1991 		 * Put the entry on the pending list before calling
1992 		 * VOP_ADVLOCKASYNC. We do this in case the lock
1993 		 * request was blocked (returning EINPROGRESS) but
1994 		 * then granted before we manage to run again. The
1995 		 * client may receive the granted message before we
1996 		 * send our blocked reply but thats their problem.
1997 		 */
1998 		mtx_lock(&host->nh_lock);
1999 		TAILQ_INSERT_TAIL(&host->nh_pending, af, af_link);
2000 		mtx_unlock(&host->nh_lock);
2001 
2002 		error = VOP_ADVLOCKASYNC(vs.vs_vp, NULL, F_SETLK, &fl, F_REMOTE,
2003 		    &af->af_task, &af->af_cookie);
2004 
2005 		/*
2006 		 * If the lock completed synchronously, just free the
2007 		 * tracking structure now.
2008 		 */
2009 		if (error != EINPROGRESS) {
2010 			CLNT_RELEASE(af->af_rpc);
2011 			mtx_lock(&host->nh_lock);
2012 			TAILQ_REMOVE(&host->nh_pending, af, af_link);
2013 			mtx_unlock(&host->nh_lock);
2014 			xdr_free((xdrproc_t) xdr_nlm4_testargs,
2015 			    &af->af_granted);
2016 			free(af, M_NLM);
2017 		} else {
2018 			if (nlm_debug_level >= 2)
2019 				printf("NLM: pending async lock %p for %s "
2020 				    "(sysid %d)\n",
2021 				    af, host->nh_caller_name, sysid);
2022 			/*
2023 			 * Don't vrele the vnode just yet - this must
2024 			 * wait until either the async callback
2025 			 * happens or the lock is cancelled.
2026 			 */
2027 			vs.vs_vp = NULL;
2028 		}
2029 	} else {
2030 		error = VOP_ADVLOCK(vs.vs_vp, NULL, F_SETLK, &fl, F_REMOTE);
2031 	}
2032 
2033 	if (error) {
2034 		if (error == EINPROGRESS) {
2035 			result->stat.stat = nlm4_blocked;
2036 		} else if (error == EDEADLK) {
2037 			result->stat.stat = nlm4_deadlck;
2038 		} else if (error == EAGAIN) {
2039 			result->stat.stat = nlm4_denied;
2040 		} else {
2041 			result->stat.stat = nlm4_failed;
2042 		}
2043 	} else {
2044 		if (monitor)
2045 			nlm_host_monitor(host, argp->state);
2046 		result->stat.stat = nlm4_granted;
2047 	}
2048 
2049 out:
2050 	nlm_release_vfs_state(&vs);
2051 	if (rpcp)
2052 		*rpcp = nlm_host_get_rpc(host);
2053 	nlm_host_release(host);
2054 	return (0);
2055 }
2056 
2057 int
2058 nlm_do_cancel(nlm4_cancargs *argp, nlm4_res *result, struct svc_req *rqstp,
2059     CLIENT **rpcp)
2060 {
2061 	fhandle_t fh;
2062 	struct vfs_state vs;
2063 	struct nlm_host *host;
2064 	int error, sysid;
2065 	struct flock fl;
2066 	struct nlm_async_lock *af;
2067 
2068 	memset(result, 0, sizeof(*result));
2069 	memset(&vs, 0, sizeof(vs));
2070 
2071 	host = nlm_find_host_by_name(argp->alock.caller_name,
2072 	    (struct sockaddr *) rqstp->rq_xprt->xp_rtaddr.buf, rqstp->rq_vers);
2073 	if (!host) {
2074 		result->stat.stat = nlm4_denied_nolocks;
2075 		return (ENOMEM);
2076 	}
2077 
2078 	if (nlm_debug_level >= 3)
2079 		printf("nlm_do_cancel(): caller_name = %s (sysid = %d)\n",
2080 		    host->nh_caller_name, host->nh_sysid);
2081 
2082 	nlm_free_finished_locks(host);
2083 	sysid = host->nh_sysid;
2084 
2085 	nlm_convert_to_fhandle_t(&fh, &argp->alock.fh);
2086 	nlm_copy_netobj(&result->cookie, &argp->cookie, M_RPC);
2087 
2088 	if (time_uptime < nlm_grace_threshold) {
2089 		result->stat.stat = nlm4_denied_grace_period;
2090 		goto out;
2091 	}
2092 
2093 	error = nlm_get_vfs_state(host, rqstp, &fh, &vs);
2094 	if (error) {
2095 		result->stat.stat = nlm_convert_error(error);
2096 		goto out;
2097 	}
2098 
2099 	fl.l_start = argp->alock.l_offset;
2100 	fl.l_len = argp->alock.l_len;
2101 	fl.l_pid = argp->alock.svid;
2102 	fl.l_sysid = sysid;
2103 	fl.l_whence = SEEK_SET;
2104 	if (argp->exclusive)
2105 		fl.l_type = F_WRLCK;
2106 	else
2107 		fl.l_type = F_RDLCK;
2108 
2109 	/*
2110 	 * First we need to try and find the async lock request - if
2111 	 * there isn't one, we give up and return nlm4_denied.
2112 	 */
2113 	mtx_lock(&host->nh_lock);
2114 
2115 	TAILQ_FOREACH(af, &host->nh_pending, af_link) {
2116 		if (af->af_fl.l_start == fl.l_start
2117 		    && af->af_fl.l_len == fl.l_len
2118 		    && af->af_fl.l_pid == fl.l_pid
2119 		    && af->af_fl.l_type == fl.l_type) {
2120 			break;
2121 		}
2122 	}
2123 
2124 	if (!af) {
2125 		mtx_unlock(&host->nh_lock);
2126 		result->stat.stat = nlm4_denied;
2127 		goto out;
2128 	}
2129 
2130 	error = nlm_cancel_async_lock(af);
2131 
2132 	if (error) {
2133 		result->stat.stat = nlm4_denied;
2134 	} else {
2135 		result->stat.stat = nlm4_granted;
2136 	}
2137 
2138 	mtx_unlock(&host->nh_lock);
2139 
2140 out:
2141 	nlm_release_vfs_state(&vs);
2142 	if (rpcp)
2143 		*rpcp = nlm_host_get_rpc(host);
2144 	nlm_host_release(host);
2145 	return (0);
2146 }
2147 
2148 int
2149 nlm_do_unlock(nlm4_unlockargs *argp, nlm4_res *result, struct svc_req *rqstp,
2150     CLIENT **rpcp)
2151 {
2152 	fhandle_t fh;
2153 	struct vfs_state vs;
2154 	struct nlm_host *host;
2155 	int error, sysid;
2156 	struct flock fl;
2157 
2158 	memset(result, 0, sizeof(*result));
2159 	memset(&vs, 0, sizeof(vs));
2160 
2161 	host = nlm_find_host_by_name(argp->alock.caller_name,
2162 	    (struct sockaddr *) rqstp->rq_xprt->xp_rtaddr.buf, rqstp->rq_vers);
2163 	if (!host) {
2164 		result->stat.stat = nlm4_denied_nolocks;
2165 		return (ENOMEM);
2166 	}
2167 
2168 	if (nlm_debug_level >= 3)
2169 		printf("nlm_do_unlock(): caller_name = %s (sysid = %d)\n",
2170 		    host->nh_caller_name, host->nh_sysid);
2171 
2172 	nlm_free_finished_locks(host);
2173 	sysid = host->nh_sysid;
2174 
2175 	nlm_convert_to_fhandle_t(&fh, &argp->alock.fh);
2176 	nlm_copy_netobj(&result->cookie, &argp->cookie, M_RPC);
2177 
2178 	if (time_uptime < nlm_grace_threshold) {
2179 		result->stat.stat = nlm4_denied_grace_period;
2180 		goto out;
2181 	}
2182 
2183 	error = nlm_get_vfs_state(host, rqstp, &fh, &vs);
2184 	if (error) {
2185 		result->stat.stat = nlm_convert_error(error);
2186 		goto out;
2187 	}
2188 
2189 	fl.l_start = argp->alock.l_offset;
2190 	fl.l_len = argp->alock.l_len;
2191 	fl.l_pid = argp->alock.svid;
2192 	fl.l_sysid = sysid;
2193 	fl.l_whence = SEEK_SET;
2194 	fl.l_type = F_UNLCK;
2195 	error = VOP_ADVLOCK(vs.vs_vp, NULL, F_UNLCK, &fl, F_REMOTE);
2196 
2197 	/*
2198 	 * Ignore the error - there is no result code for failure,
2199 	 * only for grace period.
2200 	 */
2201 	result->stat.stat = nlm4_granted;
2202 
2203 out:
2204 	nlm_release_vfs_state(&vs);
2205 	if (rpcp)
2206 		*rpcp = nlm_host_get_rpc(host);
2207 	nlm_host_release(host);
2208 	return (0);
2209 }
2210 
2211 int
2212 nlm_do_granted(nlm4_testargs *argp, nlm4_res *result, struct svc_req *rqstp,
2213 
2214     CLIENT **rpcp)
2215 {
2216 	struct nlm_host *host;
2217 	struct nlm_waiting_lock *nw;
2218 
2219 	memset(result, 0, sizeof(*result));
2220 
2221 	host = nlm_find_host_by_addr(
2222 		(struct sockaddr *) rqstp->rq_xprt->xp_rtaddr.buf,
2223 		rqstp->rq_vers);
2224 	if (!host) {
2225 		result->stat.stat = nlm4_denied_nolocks;
2226 		return (ENOMEM);
2227 	}
2228 
2229 	nlm_copy_netobj(&result->cookie, &argp->cookie, M_RPC);
2230 	result->stat.stat = nlm4_denied;
2231 
2232 	mtx_lock(&nlm_global_lock);
2233 	TAILQ_FOREACH(nw, &nlm_waiting_locks, nw_link) {
2234 		if (!nw->nw_waiting)
2235 			continue;
2236 		if (argp->alock.svid == nw->nw_lock.svid
2237 		    && argp->alock.l_offset == nw->nw_lock.l_offset
2238 		    && argp->alock.l_len == nw->nw_lock.l_len
2239 		    && argp->alock.fh.n_len == nw->nw_lock.fh.n_len
2240 		    && !memcmp(argp->alock.fh.n_bytes, nw->nw_lock.fh.n_bytes,
2241 			nw->nw_lock.fh.n_len)) {
2242 			nw->nw_waiting = FALSE;
2243 			wakeup(nw);
2244 			result->stat.stat = nlm4_granted;
2245 			break;
2246 		}
2247 	}
2248 	mtx_unlock(&nlm_global_lock);
2249 	if (rpcp)
2250 		*rpcp = nlm_host_get_rpc(host);
2251 	nlm_host_release(host);
2252 	return (0);
2253 }
2254 
2255 void
2256 nlm_do_free_all(nlm4_notify *argp)
2257 {
2258 	struct nlm_host *host, *thost;
2259 
2260 	TAILQ_FOREACH_SAFE(host, &nlm_hosts, nh_link, thost) {
2261 		if (!strcmp(host->nh_caller_name, argp->name))
2262 			nlm_host_notify(host, argp->state);
2263 	}
2264 }
2265 
2266 /*
2267  * Kernel module glue
2268  */
2269 static int
2270 nfslockd_modevent(module_t mod, int type, void *data)
2271 {
2272 
2273 	return (0);
2274 }
2275 static moduledata_t nfslockd_mod = {
2276 	"nfslockd",
2277 	nfslockd_modevent,
2278 	NULL,
2279 };
2280 DECLARE_MODULE(nfslockd, nfslockd_mod, SI_SUB_VFS, SI_ORDER_ANY);
2281 
2282 /* So that loader and kldload(2) can find us, wherever we are.. */
2283 MODULE_DEPEND(nfslockd, krpc, 1, 1, 1);
2284 MODULE_DEPEND(nfslockd, nfs, 1, 1, 1);
2285 MODULE_VERSION(nfslockd, 1);
2286