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