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