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