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