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