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