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