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