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