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